cocorum.servicephp

The primary use from this module is the ServicePHP class, a wrapper for Rumble's internal service.php API. Login is performed via this API, as well as most Rumble functions other than chat messaging and video upload. All other classes are supporting sub-classes.

Service.PHP interactions

Control Rumble via Service.PHP

Copyright 2026 Wilbur Jaywright d.b.a. Marswide BGL.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

S.D.G.

APIComment

Bases: JSONObj, BaseComment

A comment on a video as returned by a successful attempt to make it

Source code in src/cocorum/servicephp.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
class APIComment(JSONObj, BaseComment):
    """A comment on a video as returned by a successful attempt to make it"""

    def __init__(self, jsondata: dict, servicephp: ServicePHP):
        """A comment on a video as returned by a successful attempt to make it

        Args:
            jsondata (dict): The JSON block for a single comment.
            servicephp (ServicePHP): The ServicePHP object that spawned us.
        """

        JSONObj.__init__(self, jsondata)
        self.servicephp: ServicePHP = servicephp
        """Our parent ServicePHP wrapper"""

        # Badges of the user who commented if we have them
        if self.get("comment_user_badges"):
            self.user_badges = {
                slug: APIUserBadge(slug, data)
                for slug, data in self["comment_user_badges"].items()
            }

    def __repr__(self) -> str:
        """String to represent this object"""
        return f"{type(self).__name__}(user_display='{self.user_display}', text=\"{self.text}\")"

    @property
    def comment_id(self) -> int:
        """The numeric ID of the comment in base 10"""
        return int(self["comment_id"])

    @property
    def text(self) -> str:
        """The text of the comment"""
        return self["comment_text"]

    @property
    def user_display(self) -> str:
        """The display name of the user who commented"""
        return self["comment_user_display"]

    @property
    def tree_size(self):
        """TODO"""
        return self["comment_tree_size"]

comment_id property

The numeric ID of the comment in base 10

servicephp = servicephp instance-attribute

Our parent ServicePHP wrapper

text property

The text of the comment

tree_size property

TODO

user_display property

The display name of the user who commented

__init__(jsondata, servicephp)

A comment on a video as returned by a successful attempt to make it

Parameters:

Name Type Description Default
jsondata dict

The JSON block for a single comment.

required
servicephp ServicePHP

The ServicePHP object that spawned us.

required
Source code in src/cocorum/servicephp.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def __init__(self, jsondata: dict, servicephp: ServicePHP):
    """A comment on a video as returned by a successful attempt to make it

    Args:
        jsondata (dict): The JSON block for a single comment.
        servicephp (ServicePHP): The ServicePHP object that spawned us.
    """

    JSONObj.__init__(self, jsondata)
    self.servicephp: ServicePHP = servicephp
    """Our parent ServicePHP wrapper"""

    # Badges of the user who commented if we have them
    if self.get("comment_user_badges"):
        self.user_badges = {
            slug: APIUserBadge(slug, data)
            for slug, data in self["comment_user_badges"].items()
        }

__repr__()

String to represent this object

Source code in src/cocorum/servicephp.py
85
86
87
def __repr__(self) -> str:
    """String to represent this object"""
    return f"{type(self).__name__}(user_display='{self.user_display}', text=\"{self.text}\")"

APIPlaylist

Bases: JSONObj, BasePlaylist

Playlist as returned by the API

Source code in src/cocorum/servicephp.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
class APIPlaylist(JSONObj, BasePlaylist):
    """Playlist as returned by the API"""

    def __init__(self, jsondata: dict, servicephp: ServicePHP):
        """Playlist as returned by the API.

        Args:
            jsondata (dict): The JSON data block of a playlist.
            servicephp (ServicePHP): The ServicePHP object that spawned us.
        """

        JSONObj.__init__(self, jsondata)
        self.servicephp: ServicePHP = servicephp
        """Our parent ServicePHP wrapper"""

        self.user: APIUser = APIUser(jsondata["user"], self.servicephp)
        """The user that created this playlist"""

    @property
    def playlist_id(self) -> str:
        """The numeric playlist ID in base 64"""
        return self["id"]

    @property
    def title(self) -> str:
        """The title of the playlist"""
        return self["title"]

    @property
    def description(self) -> str:
        """The description of the playlist"""
        return self["description"]

    @property
    def visibility(self) -> str:
        """The visibility of the playlist"""
        return self["visibility"]

    @property
    def url(self) -> str:
        """The URL of the playlist"""
        return self["url"]

    @property
    def channel(self):
        """The channel the playlist is under, can be None"""
        # TODO Unknown return type
        return self["channel"]

    @property
    def created_on(self) -> float:
        """The time the playlist was created in seconds since epoch"""
        return utils.parse_timestamp(self["created_on"])

    @property
    def updated_on(self) -> float:
        """The time the playlist was last updated in seconds since epoch"""
        return utils.parse_timestamp(self["updated_on"])

    @property
    def permissions(self):
        """The permissions the ServicePHP user has on this playlist"""
        # TODO Unknown return type
        return self["permissions"]

    @property
    def num_items(self) -> int:
        """The number of items in the playlist"""
        return self["num_items"]

    @property
    def is_following(self) -> bool:
        """TODO -> Bool"""
        return self["is_following"]

    @property
    def items(self):
        """The items of the playlist"""
        # TODO unwrapped JSON data I think
        return self["items"]

    @property
    def extra(self):
        """TODO -> None, unknown"""
        return self["extra"]

channel property

The channel the playlist is under, can be None

created_on property

The time the playlist was created in seconds since epoch

description property

The description of the playlist

extra property

TODO -> None, unknown

is_following property

TODO -> Bool

items property

The items of the playlist

num_items property

The number of items in the playlist

permissions property

The permissions the ServicePHP user has on this playlist

playlist_id property

The numeric playlist ID in base 64

servicephp = servicephp instance-attribute

Our parent ServicePHP wrapper

title property

The title of the playlist

updated_on property

The time the playlist was last updated in seconds since epoch

url property

The URL of the playlist

user = APIUser(jsondata['user'], self.servicephp) instance-attribute

The user that created this playlist

visibility property

The visibility of the playlist

__init__(jsondata, servicephp)

Playlist as returned by the API.

Parameters:

Name Type Description Default
jsondata dict

The JSON data block of a playlist.

required
servicephp ServicePHP

The ServicePHP object that spawned us.

required
Source code in src/cocorum/servicephp.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def __init__(self, jsondata: dict, servicephp: ServicePHP):
    """Playlist as returned by the API.

    Args:
        jsondata (dict): The JSON data block of a playlist.
        servicephp (ServicePHP): The ServicePHP object that spawned us.
    """

    JSONObj.__init__(self, jsondata)
    self.servicephp: ServicePHP = servicephp
    """Our parent ServicePHP wrapper"""

    self.user: APIUser = APIUser(jsondata["user"], self.servicephp)
    """The user that created this playlist"""

APIUser

Bases: JSONObj, BaseUser

User data as returned by the API

Source code in src/cocorum/servicephp.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
class APIUser(JSONObj, BaseUser):
    """User data as returned by the API"""

    def __init__(self, jsondata: dict, servicephp: ServicePHP):
        """User data as returned by the API.

        Args:
            jsondata (dict): The JSON data block of a single user.
            servicephp (ServicePHP): The ServicePHP object that spawned us.
        """

        JSONObj.__init__(self, jsondata)
        self.servicephp: ServicePHP = servicephp
        """Our parent ServicePHP wrapper"""

        # Our profile picture data
        self.__picture = None

    def __repr__(self) -> str:
        """String to represent this object"""
        return (
            f"{type(self).__name__}(username='{self.username}', user_id={self.user_id})"
        )

    @property
    def user_id(self) -> int:
        """The numeric ID of the user in base 10"""
        return self["id"]

    @property
    def user_id_b10(self) -> int:
        """The numeric ID of the user in base 10"""
        return self.user_id

    @property
    def user_id_b36(self) -> str:
        """The numeric ID of the user in base 36"""
        return utils.base_10_to_36(self.user_id)

    @property
    def username(self) -> str:
        """The username of the user"""
        return self["username"]

    @property
    def picture_url(self) -> str:
        """The URL of the user's profile picture"""
        return self["picture"]

    @property
    def picture(self) -> bytes:
        """The user's profile picture as a bytes string"""
        if not self.picture_url:  # The profile picture is blank
            return b""

        if not self.__picture:  # We never queried the profile pic before
            response = requests.get(
                self.picture_url, timeout=static.Delays.request_timeout
            )
            assert response.status_code == 200, f"Status code {response.status_code}"

            self.__picture = response.content

        return self.__picture

    @property
    def verified_badge(self):
        """Is the user verified?"""
        # TODO Unknown return type
        return self["verified_badge"]

    @property
    def followers(self) -> int:
        """The number of followers this user has"""
        return self["followers"]

    @property
    def followed(self) -> bool:
        """TODO -> Bool"""
        return self["followed"]

followed property

TODO -> Bool

followers property

The number of followers this user has

picture property

The user's profile picture as a bytes string

picture_url property

The URL of the user's profile picture

servicephp = servicephp instance-attribute

Our parent ServicePHP wrapper

user_id property

The numeric ID of the user in base 10

user_id_b10 property

The numeric ID of the user in base 10

user_id_b36 property

The numeric ID of the user in base 36

username property

The username of the user

verified_badge property

Is the user verified?

__init__(jsondata, servicephp)

User data as returned by the API.

Parameters:

Name Type Description Default
jsondata dict

The JSON data block of a single user.

required
servicephp ServicePHP

The ServicePHP object that spawned us.

required
Source code in src/cocorum/servicephp.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def __init__(self, jsondata: dict, servicephp: ServicePHP):
    """User data as returned by the API.

    Args:
        jsondata (dict): The JSON data block of a single user.
        servicephp (ServicePHP): The ServicePHP object that spawned us.
    """

    JSONObj.__init__(self, jsondata)
    self.servicephp: ServicePHP = servicephp
    """Our parent ServicePHP wrapper"""

    # Our profile picture data
    self.__picture = None

__repr__()

String to represent this object

Source code in src/cocorum/servicephp.py
128
129
130
131
132
def __repr__(self) -> str:
    """String to represent this object"""
    return (
        f"{type(self).__name__}(username='{self.username}', user_id={self.user_id})"
    )

APIUserBadge

Bases: JSONObj, BaseUserBadge

A badge of a user as returned by the API

Source code in src/cocorum/servicephp.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class APIUserBadge(JSONObj, BaseUserBadge):
    """A badge of a user as returned by the API"""

    def __init__(self, slug: str, jsondata: dict):
        """A badge of a user as returned by the API.

        Args:
            slug (str): The string identifier of the badge.
            jsondata (dict): The JSON data block of the badge.
        """

        JSONObj.__init__(self, jsondata)
        self.slug: str = slug
        """The unique identification for this badge type"""

        self.__icon = None

    @property
    def label(self) -> str:
        """A dictionary of lang:label pairs"""
        return self["label"]

    @property
    def icon_url(self) -> str:
        """The URL of the badge's icon"""
        return static.URI.rumble_base + self["icons"][static.Misc.badge_icon_size]

icon_url property

The URL of the badge's icon

label property

A dictionary of lang:label pairs

slug = slug instance-attribute

The unique identification for this badge type

__init__(slug, jsondata)

A badge of a user as returned by the API.

Parameters:

Name Type Description Default
slug str

The string identifier of the badge.

required
jsondata dict

The JSON data block of the badge.

required
Source code in src/cocorum/servicephp.py
38
39
40
41
42
43
44
45
46
47
48
49
50
def __init__(self, slug: str, jsondata: dict):
    """A badge of a user as returned by the API.

    Args:
        slug (str): The string identifier of the badge.
        jsondata (dict): The JSON data block of the badge.
    """

    JSONObj.__init__(self, jsondata)
    self.slug: str = slug
    """The unique identification for this badge type"""

    self.__icon = None

BaseComment

A comment on a Rumble video

Source code in src/cocorum/basehandles.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
class BaseComment:
    """A comment on a Rumble video"""

    def __int__(self) -> int:
        """The comment in integer form (its ID)"""
        return self.comment_id

    def __str__(self) -> str:
        """The comment as a string (its text)"""
        return self.text

    @property
    def comment_id_b10(self) -> int:
        """The base 10 ID of the comment"""
        assert isinstance(
            self.comment_id, int), "Contact the Cocorum developers, this is probably their mistake"
        return self.comment_id

    @property
    def comment_id_b36(self) -> str:
        """The base 36 ID of the comment"""
        return utils.base_10_to_36(self.comment_id)

    def __eq__(self, other: Any) -> bool:
        """Determine if this comment is equal to another.

        Args:
            other (Any): Object to compare to.

        Returns:
            Comparison (bool): Did it fit the criteria?
        """

        # Check for direct matches first
        if isinstance(other, int):
            return self.comment_id_b10 == other
        if isinstance(other, str):
            return str(self) == other

        # Check for object attributes to match to
        if hasattr(other, "comment_id_b10"):
            return self.comment_id_b10 == other.comment_id_b10

        # Check conversion to integer last
        if hasattr(other, "__int__"):
            return self.comment_id_b10 == int(other)

        return False

    def pin(self, unpin: bool = False):
        """Pin or unpin this comment.

    Args:
        unpin (bool): If true, unpins instead of pinning comment.
        """

        return self.servicephp.comment_pin(self, unpin)

    def delete(self):
        """Delete this comment"""

        return self.servicephp.comment_delete(self)

    def restore(self) -> APIComment:
        """Un-delete this comment"""

        return self.servicephp.comment_restore(self)

comment_id_b10 property

The base 10 ID of the comment

comment_id_b36 property

The base 36 ID of the comment

__eq__(other)

Determine if this comment is equal to another.

Parameters:

Name Type Description Default
other Any

Object to compare to.

required

Returns:

Name Type Description
Comparison bool

Did it fit the criteria?

Source code in src/cocorum/basehandles.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def __eq__(self, other: Any) -> bool:
    """Determine if this comment is equal to another.

    Args:
        other (Any): Object to compare to.

    Returns:
        Comparison (bool): Did it fit the criteria?
    """

    # Check for direct matches first
    if isinstance(other, int):
        return self.comment_id_b10 == other
    if isinstance(other, str):
        return str(self) == other

    # Check for object attributes to match to
    if hasattr(other, "comment_id_b10"):
        return self.comment_id_b10 == other.comment_id_b10

    # Check conversion to integer last
    if hasattr(other, "__int__"):
        return self.comment_id_b10 == int(other)

    return False

__int__()

The comment in integer form (its ID)

Source code in src/cocorum/basehandles.py
80
81
82
def __int__(self) -> int:
    """The comment in integer form (its ID)"""
    return self.comment_id

__str__()

The comment as a string (its text)

Source code in src/cocorum/basehandles.py
84
85
86
def __str__(self) -> str:
    """The comment as a string (its text)"""
    return self.text

delete()

Delete this comment

Source code in src/cocorum/basehandles.py
135
136
137
138
def delete(self):
    """Delete this comment"""

    return self.servicephp.comment_delete(self)

pin(unpin=False)

Pin or unpin this comment.

Parameters:

Name Type Description Default
unpin bool

If true, unpins instead of pinning comment.

False
Source code in src/cocorum/basehandles.py
126
127
128
129
130
131
132
133
def pin(self, unpin: bool = False):
    """Pin or unpin this comment.

Args:
    unpin (bool): If true, unpins instead of pinning comment.
    """

    return self.servicephp.comment_pin(self, unpin)

restore()

Un-delete this comment

Source code in src/cocorum/basehandles.py
140
141
142
143
def restore(self) -> APIComment:
    """Un-delete this comment"""

    return self.servicephp.comment_restore(self)

BaseContentVotes

Likes and dislikes on a video or comment

Source code in src/cocorum/basehandles.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
class BaseContentVotes:
    """Likes and dislikes on a video or comment"""

    def __repr__(self) -> str:
        """String to represent this object"""
        return f"{type(self).__name__}(content_id={self.content_id}, score={self.score})"

    def __int__(self) -> int:
        """The integer form of the content votes"""
        return self.score

    def __eq__(self, other: Any) -> bool:
        """Determine if this content votes is equal to another.

        Args:
            other (Any): Object to compare to.

        Returns:
            Comparison (bool): Did it fit the criteria?
        """

        # Check for direct matches first
        if isinstance(other, int):
            return self.score == other
        if isinstance(other, str):
            return str(self) == other

        # Check for object attributes to match to
        if hasattr(other, "score"):
            return self.score == other.score

        # Check conversion to integer last
        if hasattr(other, "__int__"):
            return self.score == int(other)

        return False

__eq__(other)

Determine if this content votes is equal to another.

Parameters:

Name Type Description Default
other Any

Object to compare to.

required

Returns:

Name Type Description
Comparison bool

Did it fit the criteria?

Source code in src/cocorum/basehandles.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def __eq__(self, other: Any) -> bool:
    """Determine if this content votes is equal to another.

    Args:
        other (Any): Object to compare to.

    Returns:
        Comparison (bool): Did it fit the criteria?
    """

    # Check for direct matches first
    if isinstance(other, int):
        return self.score == other
    if isinstance(other, str):
        return str(self) == other

    # Check for object attributes to match to
    if hasattr(other, "score"):
        return self.score == other.score

    # Check conversion to integer last
    if hasattr(other, "__int__"):
        return self.score == int(other)

    return False

__int__()

The integer form of the content votes

Source code in src/cocorum/basehandles.py
153
154
155
def __int__(self) -> int:
    """The integer form of the content votes"""
    return self.score

__repr__()

String to represent this object

Source code in src/cocorum/basehandles.py
149
150
151
def __repr__(self) -> str:
    """String to represent this object"""
    return f"{type(self).__name__}(content_id={self.content_id}, score={self.score})"

BasePlaylist

A playlist of Rumble videos

Source code in src/cocorum/basehandles.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
class BasePlaylist:
    """A playlist of Rumble videos"""

    def __int__(self) -> int:
        """The playlist as an integer (it's ID in base 10)"""
        return self.playlist_id_b10

    def __str__(self) -> str:
        """The playlist as a string (it's ID in base 64)"""
        return self.playlist_id_b64

    def __repr__(self) -> str:
        """String to represent this object"""
        return f"{type(self).__name__}(playlist_id={self.playlist_id}, title=\"{self.title}\")"

    def __eq__(self, other: Any) -> bool:
        """Determine if this playlist is equal to another.

        Args:
            other (Any): Object to compare to.

        Returns:
            Comparison (bool): Did it fit the criteria?
        """

        # Check for direct matches first
        if isinstance(other, int):
            return self.playlist_id_b64 == other
        if isinstance(other, str):
            return str(other) == self.playlist_id_b64

        # # Check for object attributes to match to
        # if hasattr(other, "playlist_id_b10"):
        #     return self.playlist_id_b10 == other.playlist_id_b10

        # # Check conversion to integer last, in case another ID or something happens to match
        # if hasattr(other, "__int__"):
        #     return self.playlist_id_b10 == int(other)

        return False

    @property
    def playlist_id_b64(self) -> str:
        """The numeric ID of the playlist in base 64"""
        return self.playlist_id

    @property
    def playlist_id_b10(self) -> int:
        """The numeric ID of the playlist in base 10"""
        raise NotImplementedError("See Cocorum issue #22")
        # return utils.base_64_to_10(self.playlist_id)

    def add_video(self, video_id: SupportsInt | str):
        """Add a video to this playlist

    Args:
        video_id (SupportsInt | str): The numeric ID of the video to add, in base 10 or 36.
        """

        return self.servicephp.playlist_add_video(self.playlist_id, video_id)

    def delete_video(self, video_id: SupportsInt | str):
        """Remove a video from this playlist

    Args:
        video_id (SupportsInt | str): The numeric ID of the video to remove, in base 10 or 36.
        """

        self.servicephp.playlist_delete_video(self.playlist_id, video_id)

    def edit(self, title: str = None, description: str = None, visibility: str = None, channel_id: Optional[SupportsInt | str] = None) -> APIPlaylist:
        """Edit the details of this playlist. WARNING: The original object will probably be stale after this operation.

        Args:
            title (str): The title of the playlist.
                Defaults to staying the same.
            description (str): Describe the playlist.
                Defaults to staying the same.
            visibility (str): Set to public, unlisted, or private via string.
                Defaults to staying the same.
            channel_id (SupportsInt | str): The ID of the channel to have the playlist under. TODO: Cannot be retrieved!
                Defaults to resetting to None.

        Returns:
            playlist (APIPlaylist): The edit result.
        """

        if title is None:
            title = self.title
        if description is None:
            description = self.description
        if visibility is None:
            visibility = self.visibility
        # if channel_id is False:
        #     channel_id = self.channel_id

        return self.servicephp.playlist_edit(self.playlist_id, title, description, visibility, channel_id)

    def delete(self):
        """Delete this playlist"""

        self.servicephp.playlist_delete(self)

playlist_id_b10 property

The numeric ID of the playlist in base 10

playlist_id_b64 property

The numeric ID of the playlist in base 64

__eq__(other)

Determine if this playlist is equal to another.

Parameters:

Name Type Description Default
other Any

Object to compare to.

required

Returns:

Name Type Description
Comparison bool

Did it fit the criteria?

Source code in src/cocorum/basehandles.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def __eq__(self, other: Any) -> bool:
    """Determine if this playlist is equal to another.

    Args:
        other (Any): Object to compare to.

    Returns:
        Comparison (bool): Did it fit the criteria?
    """

    # Check for direct matches first
    if isinstance(other, int):
        return self.playlist_id_b64 == other
    if isinstance(other, str):
        return str(other) == self.playlist_id_b64

    # # Check for object attributes to match to
    # if hasattr(other, "playlist_id_b10"):
    #     return self.playlist_id_b10 == other.playlist_id_b10

    # # Check conversion to integer last, in case another ID or something happens to match
    # if hasattr(other, "__int__"):
    #     return self.playlist_id_b10 == int(other)

    return False

__int__()

The playlist as an integer (it's ID in base 10)

Source code in src/cocorum/basehandles.py
247
248
249
def __int__(self) -> int:
    """The playlist as an integer (it's ID in base 10)"""
    return self.playlist_id_b10

__repr__()

String to represent this object

Source code in src/cocorum/basehandles.py
255
256
257
def __repr__(self) -> str:
    """String to represent this object"""
    return f"{type(self).__name__}(playlist_id={self.playlist_id}, title=\"{self.title}\")"

__str__()

The playlist as a string (it's ID in base 64)

Source code in src/cocorum/basehandles.py
251
252
253
def __str__(self) -> str:
    """The playlist as a string (it's ID in base 64)"""
    return self.playlist_id_b64

add_video(video_id)

Add a video to this playlist

Parameters:

Name Type Description Default
video_id SupportsInt | str

The numeric ID of the video to add, in base 10 or 36.

required
Source code in src/cocorum/basehandles.py
296
297
298
299
300
301
302
303
def add_video(self, video_id: SupportsInt | str):
    """Add a video to this playlist

Args:
    video_id (SupportsInt | str): The numeric ID of the video to add, in base 10 or 36.
    """

    return self.servicephp.playlist_add_video(self.playlist_id, video_id)

delete()

Delete this playlist

Source code in src/cocorum/basehandles.py
342
343
344
345
def delete(self):
    """Delete this playlist"""

    self.servicephp.playlist_delete(self)

delete_video(video_id)

Remove a video from this playlist

Parameters:

Name Type Description Default
video_id SupportsInt | str

The numeric ID of the video to remove, in base 10 or 36.

required
Source code in src/cocorum/basehandles.py
305
306
307
308
309
310
311
312
def delete_video(self, video_id: SupportsInt | str):
    """Remove a video from this playlist

Args:
    video_id (SupportsInt | str): The numeric ID of the video to remove, in base 10 or 36.
    """

    self.servicephp.playlist_delete_video(self.playlist_id, video_id)

edit(title=None, description=None, visibility=None, channel_id=None)

Edit the details of this playlist. WARNING: The original object will probably be stale after this operation.

Parameters:

Name Type Description Default
title str

The title of the playlist. Defaults to staying the same.

None
description str

Describe the playlist. Defaults to staying the same.

None
visibility str

Set to public, unlisted, or private via string. Defaults to staying the same.

None
channel_id SupportsInt | str

The ID of the channel to have the playlist under. TODO: Cannot be retrieved! Defaults to resetting to None.

None

Returns:

Name Type Description
playlist APIPlaylist

The edit result.

Source code in src/cocorum/basehandles.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
def edit(self, title: str = None, description: str = None, visibility: str = None, channel_id: Optional[SupportsInt | str] = None) -> APIPlaylist:
    """Edit the details of this playlist. WARNING: The original object will probably be stale after this operation.

    Args:
        title (str): The title of the playlist.
            Defaults to staying the same.
        description (str): Describe the playlist.
            Defaults to staying the same.
        visibility (str): Set to public, unlisted, or private via string.
            Defaults to staying the same.
        channel_id (SupportsInt | str): The ID of the channel to have the playlist under. TODO: Cannot be retrieved!
            Defaults to resetting to None.

    Returns:
        playlist (APIPlaylist): The edit result.
    """

    if title is None:
        title = self.title
    if description is None:
        description = self.description
    if visibility is None:
        visibility = self.visibility
    # if channel_id is False:
    #     channel_id = self.channel_id

    return self.servicephp.playlist_edit(self.playlist_id, title, description, visibility, channel_id)

BaseUser

A Rumble user

Source code in src/cocorum/basehandles.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
class BaseUser:
    """A Rumble user"""

    def __int__(self) -> int:
        """The user as an integer (it's ID in base 10)"""
        return self.user_id_b10

    def __eq__(self, other: Any) -> bool:
        """Determine if this user is equal to another.

        Args:
            other (Any): Object to compare to.

        Returns:
            Comparison (bool): Did it fit the criteria?
        """

        # Check for direct matches first
        if isinstance(other, int):
            return self.user_id_b10 == other
        if isinstance(other, str):
            return str(other) in (self.user_id_b36, self.username)

        # Check for object attributes to match to
        if hasattr(other, "user_id"):
            return self.user_id_b10 == utils.ensure_b10(other.user_id)

        # Check conversion to integer last, in case another ID or something happens to match
        if hasattr(other, "__int__"):
            return self.user_id_b10 == int(other)

        return False

    @property
    def user_id_b10(self) -> int:
        """The numeric ID of the user in base 10"""
        return self.user_id

    @property
    def user_id_b36(self) -> str:
        """The numeric ID of the user in base 36"""
        return utils.base_10_to_36(self.user_id)

    def mute(self, duration: int = None, total: bool = False):
        """Mute this user.

    Args:
        duration (int): How long to mute the user in seconds.
            Defaults to infinite.
        total (bool): Wether or not they are muted across all videos.
            Defaults to False, just this video.
            """

        self.servicephp.mute(self, self.username, duration, total)

    def unmute(self):
        """Unmute this user."""
        self.servicephp.unmute(self.username)

user_id_b10 property

The numeric ID of the user in base 10

user_id_b36 property

The numeric ID of the user in base 36

__eq__(other)

Determine if this user is equal to another.

Parameters:

Name Type Description Default
other Any

Object to compare to.

required

Returns:

Name Type Description
Comparison bool

Did it fit the criteria?

Source code in src/cocorum/basehandles.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def __eq__(self, other: Any) -> bool:
    """Determine if this user is equal to another.

    Args:
        other (Any): Object to compare to.

    Returns:
        Comparison (bool): Did it fit the criteria?
    """

    # Check for direct matches first
    if isinstance(other, int):
        return self.user_id_b10 == other
    if isinstance(other, str):
        return str(other) in (self.user_id_b36, self.username)

    # Check for object attributes to match to
    if hasattr(other, "user_id"):
        return self.user_id_b10 == utils.ensure_b10(other.user_id)

    # Check conversion to integer last, in case another ID or something happens to match
    if hasattr(other, "__int__"):
        return self.user_id_b10 == int(other)

    return False

__int__()

The user as an integer (it's ID in base 10)

Source code in src/cocorum/basehandles.py
187
188
189
def __int__(self) -> int:
    """The user as an integer (it's ID in base 10)"""
    return self.user_id_b10

mute(duration=None, total=False)

Mute this user.

Parameters:

Name Type Description Default
duration int

How long to mute the user in seconds. Defaults to infinite.

None
total bool

Wether or not they are muted across all videos. Defaults to False, just this video.

False
Source code in src/cocorum/basehandles.py
227
228
229
230
231
232
233
234
235
236
237
def mute(self, duration: int = None, total: bool = False):
    """Mute this user.

Args:
    duration (int): How long to mute the user in seconds.
        Defaults to infinite.
    total (bool): Wether or not they are muted across all videos.
        Defaults to False, just this video.
        """

    self.servicephp.mute(self, self.username, duration, total)

unmute()

Unmute this user.

Source code in src/cocorum/basehandles.py
239
240
241
def unmute(self):
    """Unmute this user."""
    self.servicephp.unmute(self.username)

BaseUserBadge

A badge on a username

Source code in src/cocorum/basehandles.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class BaseUserBadge:
    """A badge on a username"""

    def __eq__(self, other: Any) -> bool:
        """Check if this badge is equal to another.

        Args:
            other (Any): Object to compare to.

        Returns:
            Comparison (bool): Did it fit the criteria?
        """

        # Check if the string is either our slug or our label in any language
        if isinstance(other, str):
            return other in (self.slug, self.label.values())

        # Check if the compared object has the same slug, if it has one
        if hasattr(other, "slug"):
            return self.slug == other.slug

        return False

    def __str__(self) -> str:
        """The chat user badge in string form"""
        return self.slug

    def __repr__(self) -> str:
        """String to represent this object"""
        return f"{type(self).__name__}(slug='{self.slug}')"

    @property
    def icon(self) -> bytes:
        """The badge's icon as a bytestring"""
        if not self.__icon:  # We never queried the icon before
            # TODO make the timeout configurable
            response = requests.get(
                self.icon_url, timeout=static.Delays.request_timeout)
            assert response.status_code == 200, f"Status code {response.status_code}"

            self.__icon = response.content

        return self.__icon

icon property

The badge's icon as a bytestring

__eq__(other)

Check if this badge is equal to another.

Parameters:

Name Type Description Default
other Any

Object to compare to.

required

Returns:

Name Type Description
Comparison bool

Did it fit the criteria?

Source code in src/cocorum/basehandles.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def __eq__(self, other: Any) -> bool:
    """Check if this badge is equal to another.

    Args:
        other (Any): Object to compare to.

    Returns:
        Comparison (bool): Did it fit the criteria?
    """

    # Check if the string is either our slug or our label in any language
    if isinstance(other, str):
        return other in (self.slug, self.label.values())

    # Check if the compared object has the same slug, if it has one
    if hasattr(other, "slug"):
        return self.slug == other.slug

    return False

__repr__()

String to represent this object

Source code in src/cocorum/basehandles.py
59
60
61
def __repr__(self) -> str:
    """String to represent this object"""
    return f"{type(self).__name__}(slug='{self.slug}')"

__str__()

The chat user badge in string form

Source code in src/cocorum/basehandles.py
55
56
57
def __str__(self) -> str:
    """The chat user badge in string form"""
    return self.slug

SSLContextAdapter

Bases: HTTPAdapter

Use Python's default TLS settings; Rumble/Cloudflare rejects urllib3's

Source code in src/cocorum/servicephp.py
368
369
370
371
372
373
class SSLContextAdapter(requests.adapters.HTTPAdapter):
    """Use Python's default TLS settings; Rumble/Cloudflare rejects urllib3's"""

    def init_poolmanager(self, *args, **kwargs):
        kwargs["ssl_context"] = ssl.create_default_context()
        return super().init_poolmanager(*args, **kwargs)

ServicePHP

Interact with Rumble's service.php API

Source code in src/cocorum/servicephp.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
class ServicePHP:
    """Interact with Rumble's service.php API"""

    def __init__(self, username: str = None, token: str | dict = None):
        """Interact with Rumble's service.php API.

        Args:
            username (str): The username we will be working under.
                Defaults to None, refer to token.
            token (str | dict): A pre-existing session token.
                Defaults to None, await login.
        """

        assert username or token, "Must pass at least one thing to log in with"

        # Set up initial auth data variables
        self.username: str | None = username
        """The username this ServicePHP wrapper is working under"""

        self.session = requests.Session()
        """requests.Session for persistent cookies and TLS context"""

        self.session.headers.update(static.RequestHeaders.user_agent)

        # Must be after session
        self.session_token = token

        # Need to set the TLS settings to something CloudFlare likes
        self.session.mount("https://", SSLContextAdapter(max_retries=3))

        # Stored ID of the logged in user
        self.__user_id = None

    def __repr__(self) -> str:
        """String to represent this object"""
        return f"{type(self).__name__}(username={self.username}, <{'not ' * bool(self.session_token)}logged in>)"

    @property
    def session_token(self) -> str:
        """The token stored in our session cookie, empty if if we are not logged in"""
        return self.session.cookies.get(static.Misc.session_token_key)

    @session_token.setter
    def session_token(self, token: str | dict | None):
        """Set our session token (does not logout if set to None)"""
        # Token is a cookie dict, extract to token string
        if isinstance(token, dict):
            token = token[static.Misc.session_token_key]

        # Enforce that token is now a string or nothing
        assert isinstance(token, str) or not token, f"Token must be a str, cookie dict, or test false, got {type(token)}"

        self.session.cookies.set(static.Misc.session_token_key, token)

        # If the token is something, ensure it works
        if token:
            assert self.test_session(), "Token is invalid"

    @property
    def user_id(self) -> int:
        """The numeric ID of the logged in user in base 10"""
        # We do not have a user ID, extract it from the unread notifications response
        if self.__user_id is None:
            j = self.sphp_request(
                "user.has_unread_notifications",
                method="GET",
            ).json()
            # The API suffixes the base 36 user ID with _u for some reason
            self.__user_id = utils.base_36_to_10(
                j["user"]["id"].removeprefix("_u"))

        return self.__user_id

    @property
    def user_id_b10(self) -> int:
        """The numeric ID of the logged in user in base 10"""
        return self.user_id

    @property
    def user_id_b36(self) -> str:
        """The numeric ID of the logged in user in base 36"""
        return utils.base_10_to_36(self.user_id)

    def test_session(self):
        """Determine if our current session token is valid"""
        if not self.session_token:
            return False

        r = self.session.get(
            static.URI.login_test,
            timeout=static.Delays.request_timeout,
        )

        # If this code is 200, we still need to log in and it FAILED
        return r.status_code == 409

    def sphp_request(
        self,
        service_name: str,
        data: dict = {},
        additional_params: dict = {},
        method: str = "POST",
    ) -> requests.Response:
        """
        Make a request to Service.PHP with common settings

        Args:
            service_name (str): The name parameter of the specific PHP service
            data (dict): Form data.
                Defaults to {}.
            additional_params (dict): Any additional query string parameters.
                Defaults to {}.
            method (str): What request method to use.
                Defaults to 'POST'.

        Returns:
            response (requests.Response): The response from Rumble.
        """

        params = {"name": service_name}
        params.update(additional_params)
        r = self.session.request(
            method,
            static.URI.servicephp,
            params=params,
            data=data,
            timeout=static.Delays.request_timeout,
        )
        assert (
            r.status_code == 200
        ), f"Service.PHP request for {service_name} failed: {r}\n{r.text}"
        # If the request json has a data -> success value, make sure it is True
        d = r.json().get("data")
        if isinstance(d, dict):
            assert d.get(
                "success", True
            ), f"Service.PHP request for {service_name} failed: \n{r.text}"
        # Data was not a dict but was not empty
        elif d:
            print(
                f"Service.PHP request for {service_name} did not fail but returned unknown data type {type(d)}: {d}"
            )

        return r

    def options_check(self, url: str, method: str, origin=static.URI.rumble_base, cookies: dict = {}, params: dict = {}) -> bool:
        """Check of we are allowed to do method on url via an options request

        Args:
            url (str): The URL to check at.
            method (str): The HTTP method to check permission for.
            origin (str): The origin header of the options request.
                Defaults to static.URI.rumble_base
            cookies (dict): Cookie dict to use in the request.
                Defaults to no cookies.
            params (dict): Parameters to use in the request.
                Defaults to no parameters.

        Returns:
            Result (bool): Is the HTTP method allowed at the URL?
        """

        r = self.session.options(
            url,
            headers={
                'Access-Control-Request-Method': method.upper(),
                'Access-Control-Request-Headers': 'content-type',
                'Origin': origin,
            },
            cookies=cookies,
            params=params,
            timeout=static.Delays.request_timeout,
        )
        return r.status_code == 200

    def get_hashed_password(self, password: str) -> str:
        """Use Rumble's salts to hash a pasword for login

        Args:
            password (str): The password to hash with the salts.

        Returns:
            hashed (str): The hashed password to use in the rest of the login.
        """

        # Get salts
        r = self.sphp_request(
            "user.get_salts",
            data={"username": self.username},
            additional_params={"response_type": "session"},
        )
        salts = r.json()["data"]["salts"]

        return ",".join(utils.calc_password_hashes(password, salts))

    def get_2fa_first_step(self, password_hashes: str) -> TwoFacAuth:
        """Get 2FA info on our account as a first 2FA step

        Args:
            password_hashes (str): The hashed password.

        Returns:
            info (TwoFacAuth): Information on 2FA."""

        r = self.sphp_request(
            "user.2fa.first_step",
            data={
                "legacy_password": 1,  # TODO
                "login": self.username,
                "password": password_hashes,
                "redirect_uri": static.URI.rumble_base,
            },
        )

        return TwoFacAuth(r.json()["data"], self)

    def login_basic(self, password: str) -> TwoFacAuth | None:
        """Perform a basic password authentication as the first step of login.
            If successful, sets our session token and returns None.
            If incomplete, returns TwoFacAuth() for next step.

        Args:
            password (str): The password to login with.

        Returns:
            result (TwoFacAuth | None): The result of the first login step.
                None means login is complete.
        """

        # Get the password hash to start off
        ph = self.get_hashed_password(password)

        # Check for 2FA
        two_fac_info = self.get_2fa_first_step(ph)

        # 2FA is enabled
        if two_fac_info.totp_id:  # two_fac_auth.options:
            return two_fac_info

        # Get session token for non-2FA
        r = self.sphp_request(
            "user.login",
            data={
                "username": self.username,
                # Hash the password using the salts
                "password_hashes": ph,
            },
        )

        j = r.json()
        assert j["data"]["session"], f"Login failed: No token returned\n{r.json()}"
        # Cookie is auto-saved to session

        return None

    def login_second_factor(self, two_fac_auth: TwoFacAuth, code: str):
        """Complete login with a 2FA code.

        Args:
            two_fac_auth (TwoFacAuth): 2FA information on this account.
            code (str): The code to enter."""

        # If this fails, sphp_request will raise AssertionError
        r = self.sphp_request(
            "user.2fa.verify_totp",
            data={
                "code": code,
                "redirect_url": static.URI.rumble_base,
                "totp_id": two_fac_auth.totp_id,
                "user_key": two_fac_auth.user_key,
            },
        )

        assert self.test_session(), f"Second factor failed, did not save cookie\n{r.json()}"

    def logout(self):
        """Log out this ServicePHP instance"""
        self.sphp_request("user.logout", method="GET")
        # Note: token cookie auto-clears from session on logout

    def chat_pin(
        self, stream_id: SupportsInt | str, message: SupportsInt, unpin: bool = False
    ):
        """Pin or unpin a message in a chat.

        Args:
            stream_id (int | str): ID of the stream in base 10 or 36.
            message (int): Converting this to int must return a chat message ID.
            unpin (bool): If true, unpins a message instead of pinning it.
        """

        self.sphp_request(
            f"chat.message.{"un" * unpin}pin",
            data={
                "video_id": utils.ensure_b10(stream_id),
                "message_id": int(message),
            },
        )

    def mute_user(
        self,
        username: str,
        is_channel: bool = False,
        video: Optional[SupportsInt] = None,
        duration: Optional[int] = None,
        total: bool = False,
    ):
        """Mute a user or channel by name.

        Args:
            username (str): The user to mute.
            is_channel (bool): Is this a channel name rather than a username?
            video (SupportsInt): The video to mute the user on.
                Defaults to None.
            duration (int): How long the user will be muted for, in seconds.
                Defaults to None, mute permanently.
            total (bool): Is this a mute across all videos?
                Defaults to False, requires video if False.
        """

        self.sphp_request(
            "moderation.mute",
            data={
                "user_to_mute": username,
                "entity_type": ("user", "channel")[is_channel],
                "video": int(video) if video else None,
                "duration": duration,
                "type": ("video", "total")[total],
            },
        )

    def unmute_user(self, record_id: SupportsInt):
        """Unmute a user.

        Args:
            record_id: The numeric ID of the mute record to undo.
        """

        self.sphp_request(
            "moderation.unmute",
            data={
                "record_id": int(record_id),
            },
        )

    def _is_comment_elem(self, e: bs4.Tag) -> bool:
        """Check if a beautifulsoup element is a comment.

        Args:
            e (bs4.Tag): The BeautifulSoup element to test.

        Returns:
            Result (bool): Did the element fit the criteria for being a comment?
        """

        return (
            e.name == "li"
            and "comment-item" in e.get("class")
            and "comments-create" not in e.get("class")
        )

    def comment_list(self, video_id: str | SupportsInt) -> list[scraping.HTMLComment]:
        """Get the list of comments under a video.

        Args:
            video_id (str | SupportsInt): The numeric ID of a video in base 10 or 36.

        Returns:
            Comments (list[scraping.HTMLComment]): A list of scraping.HTMLComment objects.
        """

        r = self.sphp_request(
            "comment.list",
            additional_params={
                "video": utils.ensure_b36(video_id),
            },
            method="GET",
        )
        soup = bs4.BeautifulSoup(r.json()["html"], features="html.parser")
        comment_elems = soup.find_all(self._is_comment_elem)
        return [scraping.HTMLComment(e, self) for e in comment_elems]

    def comment_add(
        self, video_id: SupportsInt | str, comment: str, reply_id: SupportsInt = 0
    ) -> APIComment:
        """Post a comment on a video.

        Args:
            video_id (SupportsInt | str): The numeric ID of a video / stream in base 10 or 36.
            comment (str): What to say.
            reply_id (SupportsInt): The ID of the comment to reply to.
                Defaults to zero (don't reply to anybody).

        Returns:
            Comment (APIComment): The comment, as parsed from the response data.
        """

        r = self.sphp_request(
            "comment.add",
            data={
                "video": utils.ensure_b10(video_id),
                "reply_id": int(reply_id),
                "comment": str(comment),
                "target": "comment-create-1",
            },
        )
        return APIComment(r.json()["data"], self)

    def comment_pin(self, comment_id: SupportsInt, unpin: bool = False):
        """Pin or unpin a comment by ID.

        Args:
            comment_id (SupportsInt): The numeric ID of the comment to pin/unpin.
            unpin (bool): If true, unpins instead of pinning comment.
        """

        self.sphp_request(
            f"comment.{"un" * unpin}pin",
            data={"comment_id": int(comment_id)},
        )

    def comment_delete(self, comment_id: SupportsInt):
        """Delete a comment by ID.

        Args:
            comment_id (SupportsInt): The numeric ID of the comment to delete.
        """

        self.sphp_request(
            "comment.delete",
            data={"comment_id": int(comment_id)},
        )

    def comment_restore(self, comment_id: SupportsInt) -> APIComment:
        """Restore a deleted comment by ID.

        Args:
            comment_id (SupportsInt): The numeric ID of the comment to restore.

        Returns:
            comment (APIComment): The restored comment.
        """

        r = self.sphp_request(
            "comment.restore",
            data={"comment_id": int(comment_id)},
        )
        return APIComment(r.json()["data"], self)

    def get_video_url(self, video_id: SupportsInt | str) -> str:
        """Get the URL of a Rumble video.

        Args:
            video_id (SupportsInt | str): The numeric ID of the video.

        Returns:
            URL (str): The URL of the video.
        """

        r = self.sphp_request(
            "media.share",
            additional_params={
                "video": utils.ensure_b36(video_id),
                "start": 0,
            },
            method="GET",
        )
        soup = bs4.BeautifulSoup(r.json()["html"], features="html.parser")
        elem = soup.find("div", attrs={"class": "fb-share-button share-fb"})
        return elem.attrs["data-url"]

    def playlist_add_video(self, playlist_id: str, video_id: SupportsInt | str):
        """Add a video to a playlist.

        Args:
            playlist_id (str): The numeric ID of the playlist in base 64.
            video_id (SupportsInt | str): The numeric ID of the video to add, in base 10 or 36.
        """

        self.sphp_request(
            "playlist.add_video",
            data={
                "playlist_id": str(playlist_id),
                "video_id": utils.ensure_b10(video_id),
            },
        )

    def playlist_delete_video(self, playlist_id: str, video_id: SupportsInt | str):
        """Remove a video from a playlist.

        Args:
            playlist_id (str): The numeric ID of the playlist in base 64.
            video_id (int, str): The numeric ID of the video to remove, in base 10 or 36.
        """

        self.sphp_request(
            "playlist.delete_video",
            data={
                "playlist_id": str(playlist_id),
                "video_id": utils.ensure_b10(video_id),
            },
        )

    def playlist_add(
        self,
        title: str,
        description: str = "",
        visibility: str = "public",
        channel_id: SupportsInt | str = None,
    ) -> APIPlaylist:
        """Create a new playlist.

        Args:
            title (str): The title of the playlist.
            description (str): Describe the playlist.
                Defaults to nothing.
            visibility (str): Set to public, unlisted, or private via string.
                Defaults to 'public'.
            channel_id (SupportsInt | str): The numeric ID of the channel to create the playlist under.
                Defaults to none.

        Returns:
            Playlist (APIPlaylist): The playlist as parsed from the response data.
        """

        r = self.sphp_request(
            "playlist.add",
            data={
                "title": str(title),
                "description": str(description),
                "visibility": str(visibility),
                "channel_id": str(utils.ensure_b10(channel_id)) if channel_id else None,
            },
        )
        return APIPlaylist(r.json()["data"], self)

    def playlist_edit(
        self,
        playlist_id: str,
        title: str,
        description: str = "",
        visibility: str = "public",
        channel_id: Optional[SupportsInt | str] = None,
    ) -> APIPlaylist:
        """Edit the details of an existing playlist

        Args:
            playlist_id (str): The numeric ID of the playlist to edit in base 64.
            title (str): The title of the playlist.
            description (str): Describe the playlist.
                Defaults to nothing.
            visibility (str): Set to public, unlisted, or private via string.
                Defaults to 'public'.
            channel_id (SupportsInt | str): The numeric ID of the channel to have the playlist under.
                Defaults to None.

        Returns:
            Playlist (APIPlaylist): The playlist as parsed from the response data.
        """

        r = self.sphp_request(
            "playlist.edit",
            data={
                "title": str(title),
                "description": str(description),
                "visibility": str(visibility),
                "channel_id": str(utils.ensure_b10(channel_id)) if channel_id else None,
                "playlist_id": str(playlist_id),
            },
        )
        return APIPlaylist(r.json()["data"], self)

    def playlist_delete(self, playlist_id: str):
        """Delete a playlist.

        Args:
            playlist_id (str): The numeric ID of the playlist to delete in base 64.
        """

        self.sphp_request(
            "playlist.delete",
            data={"playlist_id": str(playlist_id)},
        )

    def raid_confirm(self, stream_id: SupportsInt | str):
        """Confirm a raid, previously set up by command.

        Args:
            stream_id (SupportsInt | str): The numeric ID of the stream to confirm the raid from, in base 10 or 36.
        """

        self.sphp_request(
            "raid.confirm",
            data={"video_id": utils.ensure_b10(stream_id)},
        )

    def reset_rls_api_key(self, channel_id: SupportsInt | str = None) -> bool:
        """
        Reset the Live Stream API URL for a user or channel.

        Args:
            channel_id (SupportsInt | str): The channel to reset the API key for.
                Defaults to None, reset the user API key.

        Returns:
            success (bool): The success attribute of the returned JSON.
        """

        return self.sphp_request(
            "livestream_api.reset_api_key",
            data={
                "channel_id": str(utils.ensure_b10(channel_id)) if channel_id else None
            },
        ).json().get("data", {}).get("success", False)

session = requests.Session() instance-attribute

requests.Session for persistent cookies and TLS context

session_token property writable

The token stored in our session cookie, empty if if we are not logged in

user_id property

The numeric ID of the logged in user in base 10

user_id_b10 property

The numeric ID of the logged in user in base 10

user_id_b36 property

The numeric ID of the logged in user in base 36

username = username instance-attribute

The username this ServicePHP wrapper is working under

__init__(username=None, token=None)

Interact with Rumble's service.php API.

Parameters:

Name Type Description Default
username str

The username we will be working under. Defaults to None, refer to token.

None
token str | dict

A pre-existing session token. Defaults to None, await login.

None
Source code in src/cocorum/servicephp.py
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
def __init__(self, username: str = None, token: str | dict = None):
    """Interact with Rumble's service.php API.

    Args:
        username (str): The username we will be working under.
            Defaults to None, refer to token.
        token (str | dict): A pre-existing session token.
            Defaults to None, await login.
    """

    assert username or token, "Must pass at least one thing to log in with"

    # Set up initial auth data variables
    self.username: str | None = username
    """The username this ServicePHP wrapper is working under"""

    self.session = requests.Session()
    """requests.Session for persistent cookies and TLS context"""

    self.session.headers.update(static.RequestHeaders.user_agent)

    # Must be after session
    self.session_token = token

    # Need to set the TLS settings to something CloudFlare likes
    self.session.mount("https://", SSLContextAdapter(max_retries=3))

    # Stored ID of the logged in user
    self.__user_id = None

__repr__()

String to represent this object

Source code in src/cocorum/servicephp.py
409
410
411
def __repr__(self) -> str:
    """String to represent this object"""
    return f"{type(self).__name__}(username={self.username}, <{'not ' * bool(self.session_token)}logged in>)"

chat_pin(stream_id, message, unpin=False)

Pin or unpin a message in a chat.

Parameters:

Name Type Description Default
stream_id int | str

ID of the stream in base 10 or 36.

required
message int

Converting this to int must return a chat message ID.

required
unpin bool

If true, unpins a message instead of pinning it.

False
Source code in src/cocorum/servicephp.py
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
def chat_pin(
    self, stream_id: SupportsInt | str, message: SupportsInt, unpin: bool = False
):
    """Pin or unpin a message in a chat.

    Args:
        stream_id (int | str): ID of the stream in base 10 or 36.
        message (int): Converting this to int must return a chat message ID.
        unpin (bool): If true, unpins a message instead of pinning it.
    """

    self.sphp_request(
        f"chat.message.{"un" * unpin}pin",
        data={
            "video_id": utils.ensure_b10(stream_id),
            "message_id": int(message),
        },
    )

comment_add(video_id, comment, reply_id=0)

Post a comment on a video.

Parameters:

Name Type Description Default
video_id SupportsInt | str

The numeric ID of a video / stream in base 10 or 36.

required
comment str

What to say.

required
reply_id SupportsInt

The ID of the comment to reply to. Defaults to zero (don't reply to anybody).

0

Returns:

Name Type Description
Comment APIComment

The comment, as parsed from the response data.

Source code in src/cocorum/servicephp.py
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
def comment_add(
    self, video_id: SupportsInt | str, comment: str, reply_id: SupportsInt = 0
) -> APIComment:
    """Post a comment on a video.

    Args:
        video_id (SupportsInt | str): The numeric ID of a video / stream in base 10 or 36.
        comment (str): What to say.
        reply_id (SupportsInt): The ID of the comment to reply to.
            Defaults to zero (don't reply to anybody).

    Returns:
        Comment (APIComment): The comment, as parsed from the response data.
    """

    r = self.sphp_request(
        "comment.add",
        data={
            "video": utils.ensure_b10(video_id),
            "reply_id": int(reply_id),
            "comment": str(comment),
            "target": "comment-create-1",
        },
    )
    return APIComment(r.json()["data"], self)

comment_delete(comment_id)

Delete a comment by ID.

Parameters:

Name Type Description Default
comment_id SupportsInt

The numeric ID of the comment to delete.

required
Source code in src/cocorum/servicephp.py
797
798
799
800
801
802
803
804
805
806
807
def comment_delete(self, comment_id: SupportsInt):
    """Delete a comment by ID.

    Args:
        comment_id (SupportsInt): The numeric ID of the comment to delete.
    """

    self.sphp_request(
        "comment.delete",
        data={"comment_id": int(comment_id)},
    )

comment_list(video_id)

Get the list of comments under a video.

Parameters:

Name Type Description Default
video_id str | SupportsInt

The numeric ID of a video in base 10 or 36.

required

Returns:

Name Type Description
Comments list[HTMLComment]

A list of scraping.HTMLComment objects.

Source code in src/cocorum/servicephp.py
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
def comment_list(self, video_id: str | SupportsInt) -> list[scraping.HTMLComment]:
    """Get the list of comments under a video.

    Args:
        video_id (str | SupportsInt): The numeric ID of a video in base 10 or 36.

    Returns:
        Comments (list[scraping.HTMLComment]): A list of scraping.HTMLComment objects.
    """

    r = self.sphp_request(
        "comment.list",
        additional_params={
            "video": utils.ensure_b36(video_id),
        },
        method="GET",
    )
    soup = bs4.BeautifulSoup(r.json()["html"], features="html.parser")
    comment_elems = soup.find_all(self._is_comment_elem)
    return [scraping.HTMLComment(e, self) for e in comment_elems]

comment_pin(comment_id, unpin=False)

Pin or unpin a comment by ID.

Parameters:

Name Type Description Default
comment_id SupportsInt

The numeric ID of the comment to pin/unpin.

required
unpin bool

If true, unpins instead of pinning comment.

False
Source code in src/cocorum/servicephp.py
784
785
786
787
788
789
790
791
792
793
794
795
def comment_pin(self, comment_id: SupportsInt, unpin: bool = False):
    """Pin or unpin a comment by ID.

    Args:
        comment_id (SupportsInt): The numeric ID of the comment to pin/unpin.
        unpin (bool): If true, unpins instead of pinning comment.
    """

    self.sphp_request(
        f"comment.{"un" * unpin}pin",
        data={"comment_id": int(comment_id)},
    )

comment_restore(comment_id)

Restore a deleted comment by ID.

Parameters:

Name Type Description Default
comment_id SupportsInt

The numeric ID of the comment to restore.

required

Returns:

Name Type Description
comment APIComment

The restored comment.

Source code in src/cocorum/servicephp.py
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
def comment_restore(self, comment_id: SupportsInt) -> APIComment:
    """Restore a deleted comment by ID.

    Args:
        comment_id (SupportsInt): The numeric ID of the comment to restore.

    Returns:
        comment (APIComment): The restored comment.
    """

    r = self.sphp_request(
        "comment.restore",
        data={"comment_id": int(comment_id)},
    )
    return APIComment(r.json()["data"], self)

get_2fa_first_step(password_hashes)

Get 2FA info on our account as a first 2FA step

Parameters:

Name Type Description Default
password_hashes str

The hashed password.

required

Returns:

Name Type Description
info TwoFacAuth

Information on 2FA.

Source code in src/cocorum/servicephp.py
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
def get_2fa_first_step(self, password_hashes: str) -> TwoFacAuth:
    """Get 2FA info on our account as a first 2FA step

    Args:
        password_hashes (str): The hashed password.

    Returns:
        info (TwoFacAuth): Information on 2FA."""

    r = self.sphp_request(
        "user.2fa.first_step",
        data={
            "legacy_password": 1,  # TODO
            "login": self.username,
            "password": password_hashes,
            "redirect_uri": static.URI.rumble_base,
        },
    )

    return TwoFacAuth(r.json()["data"], self)

get_hashed_password(password)

Use Rumble's salts to hash a pasword for login

Parameters:

Name Type Description Default
password str

The password to hash with the salts.

required

Returns:

Name Type Description
hashed str

The hashed password to use in the rest of the login.

Source code in src/cocorum/servicephp.py
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
def get_hashed_password(self, password: str) -> str:
    """Use Rumble's salts to hash a pasword for login

    Args:
        password (str): The password to hash with the salts.

    Returns:
        hashed (str): The hashed password to use in the rest of the login.
    """

    # Get salts
    r = self.sphp_request(
        "user.get_salts",
        data={"username": self.username},
        additional_params={"response_type": "session"},
    )
    salts = r.json()["data"]["salts"]

    return ",".join(utils.calc_password_hashes(password, salts))

get_video_url(video_id)

Get the URL of a Rumble video.

Parameters:

Name Type Description Default
video_id SupportsInt | str

The numeric ID of the video.

required

Returns:

Name Type Description
URL str

The URL of the video.

Source code in src/cocorum/servicephp.py
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
def get_video_url(self, video_id: SupportsInt | str) -> str:
    """Get the URL of a Rumble video.

    Args:
        video_id (SupportsInt | str): The numeric ID of the video.

    Returns:
        URL (str): The URL of the video.
    """

    r = self.sphp_request(
        "media.share",
        additional_params={
            "video": utils.ensure_b36(video_id),
            "start": 0,
        },
        method="GET",
    )
    soup = bs4.BeautifulSoup(r.json()["html"], features="html.parser")
    elem = soup.find("div", attrs={"class": "fb-share-button share-fb"})
    return elem.attrs["data-url"]

login_basic(password)

Perform a basic password authentication as the first step of login. If successful, sets our session token and returns None. If incomplete, returns TwoFacAuth() for next step.

Parameters:

Name Type Description Default
password str

The password to login with.

required

Returns:

Name Type Description
result TwoFacAuth | None

The result of the first login step. None means login is complete.

Source code in src/cocorum/servicephp.py
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
def login_basic(self, password: str) -> TwoFacAuth | None:
    """Perform a basic password authentication as the first step of login.
        If successful, sets our session token and returns None.
        If incomplete, returns TwoFacAuth() for next step.

    Args:
        password (str): The password to login with.

    Returns:
        result (TwoFacAuth | None): The result of the first login step.
            None means login is complete.
    """

    # Get the password hash to start off
    ph = self.get_hashed_password(password)

    # Check for 2FA
    two_fac_info = self.get_2fa_first_step(ph)

    # 2FA is enabled
    if two_fac_info.totp_id:  # two_fac_auth.options:
        return two_fac_info

    # Get session token for non-2FA
    r = self.sphp_request(
        "user.login",
        data={
            "username": self.username,
            # Hash the password using the salts
            "password_hashes": ph,
        },
    )

    j = r.json()
    assert j["data"]["session"], f"Login failed: No token returned\n{r.json()}"
    # Cookie is auto-saved to session

    return None

login_second_factor(two_fac_auth, code)

Complete login with a 2FA code.

Parameters:

Name Type Description Default
two_fac_auth TwoFacAuth

2FA information on this account.

required
code str

The code to enter.

required
Source code in src/cocorum/servicephp.py
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
def login_second_factor(self, two_fac_auth: TwoFacAuth, code: str):
    """Complete login with a 2FA code.

    Args:
        two_fac_auth (TwoFacAuth): 2FA information on this account.
        code (str): The code to enter."""

    # If this fails, sphp_request will raise AssertionError
    r = self.sphp_request(
        "user.2fa.verify_totp",
        data={
            "code": code,
            "redirect_url": static.URI.rumble_base,
            "totp_id": two_fac_auth.totp_id,
            "user_key": two_fac_auth.user_key,
        },
    )

    assert self.test_session(), f"Second factor failed, did not save cookie\n{r.json()}"

logout()

Log out this ServicePHP instance

Source code in src/cocorum/servicephp.py
651
652
653
def logout(self):
    """Log out this ServicePHP instance"""
    self.sphp_request("user.logout", method="GET")

mute_user(username, is_channel=False, video=None, duration=None, total=False)

Mute a user or channel by name.

Parameters:

Name Type Description Default
username str

The user to mute.

required
is_channel bool

Is this a channel name rather than a username?

False
video SupportsInt

The video to mute the user on. Defaults to None.

None
duration int

How long the user will be muted for, in seconds. Defaults to None, mute permanently.

None
total bool

Is this a mute across all videos? Defaults to False, requires video if False.

False
Source code in src/cocorum/servicephp.py
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
def mute_user(
    self,
    username: str,
    is_channel: bool = False,
    video: Optional[SupportsInt] = None,
    duration: Optional[int] = None,
    total: bool = False,
):
    """Mute a user or channel by name.

    Args:
        username (str): The user to mute.
        is_channel (bool): Is this a channel name rather than a username?
        video (SupportsInt): The video to mute the user on.
            Defaults to None.
        duration (int): How long the user will be muted for, in seconds.
            Defaults to None, mute permanently.
        total (bool): Is this a mute across all videos?
            Defaults to False, requires video if False.
    """

    self.sphp_request(
        "moderation.mute",
        data={
            "user_to_mute": username,
            "entity_type": ("user", "channel")[is_channel],
            "video": int(video) if video else None,
            "duration": duration,
            "type": ("video", "total")[total],
        },
    )

options_check(url, method, origin=static.URI.rumble_base, cookies={}, params={})

Check of we are allowed to do method on url via an options request

Parameters:

Name Type Description Default
url str

The URL to check at.

required
method str

The HTTP method to check permission for.

required
origin str

The origin header of the options request. Defaults to static.URI.rumble_base

rumble_base
cookies dict

Cookie dict to use in the request. Defaults to no cookies.

{}
params dict

Parameters to use in the request. Defaults to no parameters.

{}

Returns:

Name Type Description
Result bool

Is the HTTP method allowed at the URL?

Source code in src/cocorum/servicephp.py
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
def options_check(self, url: str, method: str, origin=static.URI.rumble_base, cookies: dict = {}, params: dict = {}) -> bool:
    """Check of we are allowed to do method on url via an options request

    Args:
        url (str): The URL to check at.
        method (str): The HTTP method to check permission for.
        origin (str): The origin header of the options request.
            Defaults to static.URI.rumble_base
        cookies (dict): Cookie dict to use in the request.
            Defaults to no cookies.
        params (dict): Parameters to use in the request.
            Defaults to no parameters.

    Returns:
        Result (bool): Is the HTTP method allowed at the URL?
    """

    r = self.session.options(
        url,
        headers={
            'Access-Control-Request-Method': method.upper(),
            'Access-Control-Request-Headers': 'content-type',
            'Origin': origin,
        },
        cookies=cookies,
        params=params,
        timeout=static.Delays.request_timeout,
    )
    return r.status_code == 200

playlist_add(title, description='', visibility='public', channel_id=None)

Create a new playlist.

Parameters:

Name Type Description Default
title str

The title of the playlist.

required
description str

Describe the playlist. Defaults to nothing.

''
visibility str

Set to public, unlisted, or private via string. Defaults to 'public'.

'public'
channel_id SupportsInt | str

The numeric ID of the channel to create the playlist under. Defaults to none.

None

Returns:

Name Type Description
Playlist APIPlaylist

The playlist as parsed from the response data.

Source code in src/cocorum/servicephp.py
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
def playlist_add(
    self,
    title: str,
    description: str = "",
    visibility: str = "public",
    channel_id: SupportsInt | str = None,
) -> APIPlaylist:
    """Create a new playlist.

    Args:
        title (str): The title of the playlist.
        description (str): Describe the playlist.
            Defaults to nothing.
        visibility (str): Set to public, unlisted, or private via string.
            Defaults to 'public'.
        channel_id (SupportsInt | str): The numeric ID of the channel to create the playlist under.
            Defaults to none.

    Returns:
        Playlist (APIPlaylist): The playlist as parsed from the response data.
    """

    r = self.sphp_request(
        "playlist.add",
        data={
            "title": str(title),
            "description": str(description),
            "visibility": str(visibility),
            "channel_id": str(utils.ensure_b10(channel_id)) if channel_id else None,
        },
    )
    return APIPlaylist(r.json()["data"], self)

playlist_add_video(playlist_id, video_id)

Add a video to a playlist.

Parameters:

Name Type Description Default
playlist_id str

The numeric ID of the playlist in base 64.

required
video_id SupportsInt | str

The numeric ID of the video to add, in base 10 or 36.

required
Source code in src/cocorum/servicephp.py
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
def playlist_add_video(self, playlist_id: str, video_id: SupportsInt | str):
    """Add a video to a playlist.

    Args:
        playlist_id (str): The numeric ID of the playlist in base 64.
        video_id (SupportsInt | str): The numeric ID of the video to add, in base 10 or 36.
    """

    self.sphp_request(
        "playlist.add_video",
        data={
            "playlist_id": str(playlist_id),
            "video_id": utils.ensure_b10(video_id),
        },
    )

playlist_delete(playlist_id)

Delete a playlist.

Parameters:

Name Type Description Default
playlist_id str

The numeric ID of the playlist to delete in base 64.

required
Source code in src/cocorum/servicephp.py
948
949
950
951
952
953
954
955
956
957
958
def playlist_delete(self, playlist_id: str):
    """Delete a playlist.

    Args:
        playlist_id (str): The numeric ID of the playlist to delete in base 64.
    """

    self.sphp_request(
        "playlist.delete",
        data={"playlist_id": str(playlist_id)},
    )

playlist_delete_video(playlist_id, video_id)

Remove a video from a playlist.

Parameters:

Name Type Description Default
playlist_id str

The numeric ID of the playlist in base 64.

required
video_id (int, str)

The numeric ID of the video to remove, in base 10 or 36.

required
Source code in src/cocorum/servicephp.py
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
def playlist_delete_video(self, playlist_id: str, video_id: SupportsInt | str):
    """Remove a video from a playlist.

    Args:
        playlist_id (str): The numeric ID of the playlist in base 64.
        video_id (int, str): The numeric ID of the video to remove, in base 10 or 36.
    """

    self.sphp_request(
        "playlist.delete_video",
        data={
            "playlist_id": str(playlist_id),
            "video_id": utils.ensure_b10(video_id),
        },
    )

playlist_edit(playlist_id, title, description='', visibility='public', channel_id=None)

Edit the details of an existing playlist

Parameters:

Name Type Description Default
playlist_id str

The numeric ID of the playlist to edit in base 64.

required
title str

The title of the playlist.

required
description str

Describe the playlist. Defaults to nothing.

''
visibility str

Set to public, unlisted, or private via string. Defaults to 'public'.

'public'
channel_id SupportsInt | str

The numeric ID of the channel to have the playlist under. Defaults to None.

None

Returns:

Name Type Description
Playlist APIPlaylist

The playlist as parsed from the response data.

Source code in src/cocorum/servicephp.py
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
def playlist_edit(
    self,
    playlist_id: str,
    title: str,
    description: str = "",
    visibility: str = "public",
    channel_id: Optional[SupportsInt | str] = None,
) -> APIPlaylist:
    """Edit the details of an existing playlist

    Args:
        playlist_id (str): The numeric ID of the playlist to edit in base 64.
        title (str): The title of the playlist.
        description (str): Describe the playlist.
            Defaults to nothing.
        visibility (str): Set to public, unlisted, or private via string.
            Defaults to 'public'.
        channel_id (SupportsInt | str): The numeric ID of the channel to have the playlist under.
            Defaults to None.

    Returns:
        Playlist (APIPlaylist): The playlist as parsed from the response data.
    """

    r = self.sphp_request(
        "playlist.edit",
        data={
            "title": str(title),
            "description": str(description),
            "visibility": str(visibility),
            "channel_id": str(utils.ensure_b10(channel_id)) if channel_id else None,
            "playlist_id": str(playlist_id),
        },
    )
    return APIPlaylist(r.json()["data"], self)

raid_confirm(stream_id)

Confirm a raid, previously set up by command.

Parameters:

Name Type Description Default
stream_id SupportsInt | str

The numeric ID of the stream to confirm the raid from, in base 10 or 36.

required
Source code in src/cocorum/servicephp.py
960
961
962
963
964
965
966
967
968
969
970
def raid_confirm(self, stream_id: SupportsInt | str):
    """Confirm a raid, previously set up by command.

    Args:
        stream_id (SupportsInt | str): The numeric ID of the stream to confirm the raid from, in base 10 or 36.
    """

    self.sphp_request(
        "raid.confirm",
        data={"video_id": utils.ensure_b10(stream_id)},
    )

reset_rls_api_key(channel_id=None)

Reset the Live Stream API URL for a user or channel.

Parameters:

Name Type Description Default
channel_id SupportsInt | str

The channel to reset the API key for. Defaults to None, reset the user API key.

None

Returns:

Name Type Description
success bool

The success attribute of the returned JSON.

Source code in src/cocorum/servicephp.py
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
def reset_rls_api_key(self, channel_id: SupportsInt | str = None) -> bool:
    """
    Reset the Live Stream API URL for a user or channel.

    Args:
        channel_id (SupportsInt | str): The channel to reset the API key for.
            Defaults to None, reset the user API key.

    Returns:
        success (bool): The success attribute of the returned JSON.
    """

    return self.sphp_request(
        "livestream_api.reset_api_key",
        data={
            "channel_id": str(utils.ensure_b10(channel_id)) if channel_id else None
        },
    ).json().get("data", {}).get("success", False)

sphp_request(service_name, data={}, additional_params={}, method='POST')

Make a request to Service.PHP with common settings

Parameters:

Name Type Description Default
service_name str

The name parameter of the specific PHP service

required
data dict

Form data. Defaults to {}.

{}
additional_params dict

Any additional query string parameters. Defaults to {}.

{}
method str

What request method to use. Defaults to 'POST'.

'POST'

Returns:

Name Type Description
response Response

The response from Rumble.

Source code in src/cocorum/servicephp.py
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
def sphp_request(
    self,
    service_name: str,
    data: dict = {},
    additional_params: dict = {},
    method: str = "POST",
) -> requests.Response:
    """
    Make a request to Service.PHP with common settings

    Args:
        service_name (str): The name parameter of the specific PHP service
        data (dict): Form data.
            Defaults to {}.
        additional_params (dict): Any additional query string parameters.
            Defaults to {}.
        method (str): What request method to use.
            Defaults to 'POST'.

    Returns:
        response (requests.Response): The response from Rumble.
    """

    params = {"name": service_name}
    params.update(additional_params)
    r = self.session.request(
        method,
        static.URI.servicephp,
        params=params,
        data=data,
        timeout=static.Delays.request_timeout,
    )
    assert (
        r.status_code == 200
    ), f"Service.PHP request for {service_name} failed: {r}\n{r.text}"
    # If the request json has a data -> success value, make sure it is True
    d = r.json().get("data")
    if isinstance(d, dict):
        assert d.get(
            "success", True
        ), f"Service.PHP request for {service_name} failed: \n{r.text}"
    # Data was not a dict but was not empty
    elif d:
        print(
            f"Service.PHP request for {service_name} did not fail but returned unknown data type {type(d)}: {d}"
        )

    return r

test_session()

Determine if our current session token is valid

Source code in src/cocorum/servicephp.py
459
460
461
462
463
464
465
466
467
468
469
470
def test_session(self):
    """Determine if our current session token is valid"""
    if not self.session_token:
        return False

    r = self.session.get(
        static.URI.login_test,
        timeout=static.Delays.request_timeout,
    )

    # If this code is 200, we still need to log in and it FAILED
    return r.status_code == 409

unmute_user(record_id)

Unmute a user.

Parameters:

Name Type Description Default
record_id SupportsInt

The numeric ID of the mute record to undo.

required
Source code in src/cocorum/servicephp.py
707
708
709
710
711
712
713
714
715
716
717
718
719
def unmute_user(self, record_id: SupportsInt):
    """Unmute a user.

    Args:
        record_id: The numeric ID of the mute record to undo.
    """

    self.sphp_request(
        "moderation.unmute",
        data={
            "record_id": int(record_id),
        },
    )

TwoFacAuth

Bases: JSONObj

Handle and use the resposne data from the 2FA request

Source code in src/cocorum/servicephp.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
class TwoFacAuth(JSONObj):
    """Handle and use the resposne data from the 2FA request"""

    def __init__(self, jsondata: dict, servicephp: ServicePHP):
        """Handle and use the resposne data from the 2FA request.

        Args:
            jsondata (dict): The JSON data block of the 2FA first step data.
            servicephp (ServicePHP): The ServicePHP object that spawned us.
        """

        JSONObj.__init__(self, jsondata)
        self.servicephp: ServicePHP = servicephp
        """Our parent ServicePHP wrapper"""

    def __repr__(self) -> str:
        """String to represent this object"""
        return f"{type(self).__name__}(<{self.servicephp.username}>)"

    @property
    def totp_id(self) -> str | None:
        """Is None when 2FA is disabled"""
        return self["totp_id"]

    @property
    def user_key(self) -> str | None:
        """Is None when 2FA is disabled"""
        return self.get("user_key")

    @property
    def options(self) -> tuple:
        """The options we have for 2FA"""
        # 2FA is disabled it totp_id is None, so we have no options
        if not self.totp_id:
            return tuple()

        return tuple(
            option for option, available in self["options"].items() if available
        )

    def request_2fa_code(self, option: str = "authenticator") -> str | None:
        """Tell Rumble to send the user a 2FA code

        Args:
            option (str): The 2FA option to use. Must be in self.options.
                Defaults to "authenticator" app.

        Returns:
            sent_to (str | None): The code destination, semi-censored.
                If 'authenticator' was used, returns None, as such apps
                generate the 2FA codes on demand."""

        assert self.options, "2FA is not enabled on this account"

        assert (
            option in self.options
        ), f"Option '{option}' is not enabled on this account for 2FA"

        if option == "email":
            r = self.servicephp.sphp_request(
                "user.2fa.request_email_code",
                data={
                    "totp_id": self.totp_id,
                    "user_key": self.user_key,
                },
                logged_in=False,
            )
            return r.json()["data"]["sent_to"]

        if option == "phone":
            r = self.servicephp.sphp_request(
                "user.2fa.request_sms_code",
                data={
                    "totp_id": self.totp_id,
                    "user_key": self.user_key,
                },
                logged_in=False,
            )
            return r.json()["data"]["sent_to"]

        if option == "authenticator":
            # Nothing for us to do
            return None

        raise NotImplementedError(
            f"Cocorum does not support option '{option}' for 2FA."
        )

options property

The options we have for 2FA

servicephp = servicephp instance-attribute

Our parent ServicePHP wrapper

totp_id property

Is None when 2FA is disabled

user_key property

Is None when 2FA is disabled

__init__(jsondata, servicephp)

Handle and use the resposne data from the 2FA request.

Parameters:

Name Type Description Default
jsondata dict

The JSON data block of the 2FA first step data.

required
servicephp ServicePHP

The ServicePHP object that spawned us.

required
Source code in src/cocorum/servicephp.py
282
283
284
285
286
287
288
289
290
291
292
def __init__(self, jsondata: dict, servicephp: ServicePHP):
    """Handle and use the resposne data from the 2FA request.

    Args:
        jsondata (dict): The JSON data block of the 2FA first step data.
        servicephp (ServicePHP): The ServicePHP object that spawned us.
    """

    JSONObj.__init__(self, jsondata)
    self.servicephp: ServicePHP = servicephp
    """Our parent ServicePHP wrapper"""

__repr__()

String to represent this object

Source code in src/cocorum/servicephp.py
294
295
296
def __repr__(self) -> str:
    """String to represent this object"""
    return f"{type(self).__name__}(<{self.servicephp.username}>)"

request_2fa_code(option='authenticator')

Tell Rumble to send the user a 2FA code

Parameters:

Name Type Description Default
option str

The 2FA option to use. Must be in self.options. Defaults to "authenticator" app.

'authenticator'

Returns:

Name Type Description
sent_to str | None

The code destination, semi-censored. If 'authenticator' was used, returns None, as such apps generate the 2FA codes on demand.

Source code in src/cocorum/servicephp.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
def request_2fa_code(self, option: str = "authenticator") -> str | None:
    """Tell Rumble to send the user a 2FA code

    Args:
        option (str): The 2FA option to use. Must be in self.options.
            Defaults to "authenticator" app.

    Returns:
        sent_to (str | None): The code destination, semi-censored.
            If 'authenticator' was used, returns None, as such apps
            generate the 2FA codes on demand."""

    assert self.options, "2FA is not enabled on this account"

    assert (
        option in self.options
    ), f"Option '{option}' is not enabled on this account for 2FA"

    if option == "email":
        r = self.servicephp.sphp_request(
            "user.2fa.request_email_code",
            data={
                "totp_id": self.totp_id,
                "user_key": self.user_key,
            },
            logged_in=False,
        )
        return r.json()["data"]["sent_to"]

    if option == "phone":
        r = self.servicephp.sphp_request(
            "user.2fa.request_sms_code",
            data={
                "totp_id": self.totp_id,
                "user_key": self.user_key,
            },
            logged_in=False,
        )
        return r.json()["data"]["sent_to"]

    if option == "authenticator":
        # Nothing for us to do
        return None

    raise NotImplementedError(
        f"Cocorum does not support option '{option}' for 2FA."
    )

S.D.G.