cocorum

The primary use from this module is the RumbleAPI class, the wrapper for the Rumble Live Stream API. All other classes are supporting sub-classes.

Cocorum

An unofficial Python wrapper for the Rumble.com APIs

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.

This base module is a Python wrapper for the Rumble Live Stream API v1.0 (beta), with some quality of life additions, such as: - Implementing a cache of the API data with an automatic time to live enforcer. If the stored API data is older than refresh_rate (and you are querying an endpoint that can actually change over time), the wrapper will automatically refresh in the background before handing you the fresh endpoint data. - All timespamps are parsed to seconds since Epoch, UTC timezone. - Additional new_followers and new_subscribers, plus chat.new_messages and chat.new_rants as endpoints that automatically clear themselves when read.

Modules exported by this package:

  • chatapi: Provide the ChatAPI object for interacting with a livestream chat.
  • servicephp: Provide the ServicePHP object for interacting with the service.php API.
  • uploadphp: Provide the UploadPHP object for uploading videos.
  • scraping: Provide functions and the Scraper object for getting various data via HTML scraping.
  • jsonhandles: Abstract classes for handling JSON data blocks.
  • basehandles: Abstract classes with common methods for both JSON and HTML wrappers.
  • utils: Various utility functions for internal calculations and checks.
  • static: Global data that does not change across the package.

Example usage:

from cocorum import RumbleAPI

## API_URL is Rumble Live Stream API URL with key
api = RumbleAPI(API_URL, refresh_rate=10)

print(api.username)
## Should display your Rumble username

print("Latest follower:", api.latest_follower)
## Should display your latest follower, or None if you have none.

if api.latest_subscriber:
    print(api.latest_subscriber, f"subscribed for ${api.latest_subscriber.amount_dollars}")
## Should display your latest subscriber if you have one.

livestream = api.latest_livestream # None if there is no stream running

if livestream:
    print(livestream.title)
    print("Stream visibility is", livestream.visibility)

    # We will use this later
    STREAM_ID = livestream.stream_id

    print("Stream ID is", STREAM_ID)

    import time # We'll need this Python builtin for delays and knowing when to stop

    # Get messages for one minute
    start_time = time.time()

    # Continue as long as we haven't been going for a whole minute, and the livestream is still live
    while time.time() - start_time < 60 and livestream.is_live:
        # For each new message...
        for message in livestream.chat.new_messages:
            # Display it
            print(message.username, "said", message)

        # Wait a bit, just to keep the loop from maxxing a CPU core
        time.sleep(0.1)

S.D.G.

ChatMessage

Bases: JSONUserAction

A single message in a Rumble livestream chat

Source code in src/cocorum/__init__.py
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
class ChatMessage(JSONUserAction):
    """A single message in a Rumble livestream chat"""

    def __eq__(self, other: Any) -> bool:
        """Is this message equal to another?

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

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

        # Check if the compared string is our message
        if isinstance(other, str):
            return self.text == other

        # # Check if the compared message has the same username and text (not needed)
        # if type(other) == type(self):
        #     return (self.username, self.text) == (other.username, other.text)

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

            return self.text == other.text  # the other object had no username attribute

        return False

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

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

    @property
    def text(self) -> str:
        """The message text"""
        return self["text"]

    @property
    def created_on(self) -> float:
        """When the message was created, in seconds since Epoch UTC"""
        return utils.parse_timestamp(self["created_on"])

    @property
    def badges(self) -> tuple[str, ...]:
        """The user's badges"""
        return tuple(self["badges"].values())

badges property

The user's badges

created_on property

When the message was created, in seconds since Epoch UTC

text property

The message text

__eq__(other)

Is this message 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/__init__.py
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
def __eq__(self, other: Any) -> bool:
    """Is this message equal to another?

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

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

    # Check if the compared string is our message
    if isinstance(other, str):
        return self.text == other

    # # Check if the compared message has the same username and text (not needed)
    # if type(other) == type(self):
    #     return (self.username, self.text) == (other.username, other.text)

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

        return self.text == other.text  # the other object had no username attribute

    return False

__repr__()

String to represent this object

Source code in src/cocorum/__init__.py
423
424
425
426
427
def __repr__(self) -> str:
    """String to represent this object"""
    return (
        f"{type(self).__name__}(username='{self.username}', text=\"{self.text}\")"
    )

__str__()

Message as a string (its content)

Source code in src/cocorum/__init__.py
419
420
421
def __str__(self) -> str:
    """Message as a string (its content)"""
    return self.text

Follower

Bases: JSONUserAction

Rumble follower

Source code in src/cocorum/__init__.py
107
108
109
110
111
112
113
114
115
116
117
class Follower(JSONUserAction):
    """Rumble follower"""

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

    @property
    def followed_on(self) -> float:
        """When the follower followed, in seconds since Epoch UTC"""
        return utils.parse_timestamp(self["followed_on"])

followed_on property

When the follower followed, in seconds since Epoch UTC

__repr__()

String to represent this object

Source code in src/cocorum/__init__.py
110
111
112
def __repr__(self) -> str:
    """String to represent this object"""
    return f"{type(self).__name__}(username='{self.username}', followed_on='{self.followed_on}')"

GiftedSub

Bases: JSONObj

A single gift containing one or more subscriptions

Source code in src/cocorum/__init__.py
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
class GiftedSub(JSONObj):
    """A single gift containing one or more subscriptions"""

    #     def __init__(self, jsondata, api):
    #         """A single gift containing one or more subscriptions
    #
    #     Args:
    #         jsondata (dict): The JSON block for a single livestream.
    #         api (RumbleAPI): The Rumble Live Stream API wrapper that spawned us.
    #         """
    #
    #         self._jsondata = jsondata
    #         self.api = api
    #         self.is_disappeared = False # The gift is in the API listing
    #
    #
    #     def __getitem__(self, key):
    #         """Return a key from the JSON, refreshing if necessary
    #
    #     Args:
    #         key (str): A valid JSON key.
    #         """
    #
    #         # The gift has not disappeared from the API listing,
    #         # the key requested is not a value that doesn't change,
    #         # and it has been api.refresh rate since the last time we refreshed
    #         if (not self.is_disappeared) and (key not in static.StaticAPIEndpoints.gifted_subs) and (time.time() - self.api.last_refresh_time > self.api.refresh_rate):
    #             self.api.refresh()
    #
    #         return self._jsondata[key]

    @property
    def jsondata(self):
        """A copy of the raw JSON from the API. Editing it does not change this object."""
        return copy.deepcopy(self._jsondata)

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

    @property
    def total_gifts(self) -> int:
        """The number of subscriptions in this gift"""
        return self["total_gifts"]

    @property
    def gift_type(self) -> str:
        """TODO"""
        return self["gift_type"]

    @property
    def remaining_gifts(self) -> int:
        """Subscriptions from the gift that have yet to apply to a user
        WARNING: This is shallow! I have no way to reliably ID particular gifts to update the GiftedSub data."""
        return self["remaining_gifts"]

    @property
    def video_id(self) -> int:
        """The numeric ID of the stream this gift was sent on, in base 10"""
        return self["video_id"]

    @property
    def video_id_b10(self) -> int:
        """The numeric ID of the stream this gift was sent on, in base 10"""
        return self.video_id

    @property
    def video_id_b36(self) -> str:
        """The numeric ID of the stream this gift was sent on, in base 36"""
        return utils.base_10_to_36(self.video_id)

    @property
    def purchased_by(self) -> str:
        """The username of who purchased this gift"""
        return self["purchased_by"]

gift_type property

TODO

jsondata property

A copy of the raw JSON from the API. Editing it does not change this object.

purchased_by property

The username of who purchased this gift

remaining_gifts property

Subscriptions from the gift that have yet to apply to a user WARNING: This is shallow! I have no way to reliably ID particular gifts to update the GiftedSub data.

total_gifts property

The number of subscriptions in this gift

video_id property

The numeric ID of the stream this gift was sent on, in base 10

video_id_b10 property

The numeric ID of the stream this gift was sent on, in base 10

video_id_b36 property

The numeric ID of the stream this gift was sent on, in base 36

__repr__()

String to represent this object

Source code in src/cocorum/__init__.py
654
655
656
def __repr__(self) -> str:
    """String to represent this object"""
    return f"{type(self).__name__}(purchased_by='{self.purchased_by}')"

LiveChat

Reference for chat of a Rumble livestream

Source code in src/cocorum/__init__.py
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
class LiveChat:
    """Reference for chat of a Rumble livestream"""

    def __init__(self, stream: Livestream):
        """Reference for chat of a Rumble livestream

        Args:
            stream (Livestream): The wrapper for a single Rumble livestream.
        """

        self.stream: Livestream = stream
        """Our parent stream wrapper"""

        self.api = stream.api
        """Our parent RLS API wrapper"""

        self.last_newmessage_time: float = 0
        """The last time we were checked for "new" messages"""

        self.last_newrant_time: float = 0
        """The last time we were checked for "new" rants"""

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

    def __getitem__(self, key: str):
        """Return a key from the stream's chat JSON"""
        return self.stream["chat"][key]

    @property
    def latest_message(self) -> ChatMessage:
        """The latest chat message"""
        # This endpoint does not exist in the RUM Live Alerts LS API
        if self.api._rumbot_mode:
            print("ERROR: RUM Live Alerts does not pass full chat in its LS API.")
            return None

        if not self["latest_message"]:
            return None  # No-one has chatted on this stream yet
        return ChatMessage(self["latest_message"])

    @property
    def recent_messages(self) -> list[ChatMessage]:
        """Recent chat messages"""
        # This endpoint does not exist in the RUM Live Alerts LS API
        if self.api._rumbot_mode:
            print("ERROR: RUM Live Alerts does not pass full chat in its LS API.")
            return []

        data = self["recent_messages"].copy()
        return [ChatMessage(jsondata_block) for jsondata_block in data]

    @property
    def new_messages(self) -> list[ChatMessage]:
        """Chat messages that are newer than the last time this was referenced"""
        # This endpoint does not exist in the RUM Live Alerts LS API
        if self.api._rumbot_mode:
            print("ERROR: RUM Live Alerts does not pass full chat in its LS API.")
            return []

        rem = self.recent_messages.copy()
        rem.sort(
            key=lambda x: x.created_on
        )  # Sort the messages so the newest ones are last

        # There are no recent messages, or all messages are older than the last time we checked
        if not rem or rem[-1].created_on < self.last_newmessage_time:
            return []

        i = 0
        for i, m in enumerate(rem):
            if m.created_on > self.last_newmessage_time:
                break  # i is now the index of the oldest new message

        self.last_newmessage_time = time.monotonic()
        return rem[i:]

    @property
    def latest_rant(self) -> Rant:
        """The latest chat rant"""
        if not self["latest_rant"]:
            return None  # No-one has ranted on this stream yet
        return Rant(self["latest_rant"])

    @property
    def recent_rants(self) -> list[Rant]:
        """Recent chat rants"""
        data = self["recent_rants"].copy()
        return [Rant(jsondata_block) for jsondata_block in data]

    @property
    def new_rants(self) -> list[Rant]:
        """Chat rants that are newer than the last time this was referenced"""
        rera = self.recent_rants.copy()
        rera.sort(
            key=lambda x: x.created_on
        )  # Sort the rants so the newest ones are last

        # There are no recent rants, or all rants are older than the last time we checked
        if not rera or rera[-1].created_on < self.last_newrant_time:
            return []

        i = 0
        for i, r in enumerate(rera):
            if r.created_on > self.last_newrant_time:
                break  # i is now the index of the oldest new rant

        self.last_newrant_time = time.monotonic()
        return rera[i:]

api = stream.api instance-attribute

Our parent RLS API wrapper

last_newmessage_time = 0 instance-attribute

The last time we were checked for "new" messages

last_newrant_time = 0 instance-attribute

The last time we were checked for "new" rants

latest_message property

The latest chat message

latest_rant property

The latest chat rant

new_messages property

Chat messages that are newer than the last time this was referenced

new_rants property

Chat rants that are newer than the last time this was referenced

recent_messages property

Recent chat messages

recent_rants property

Recent chat rants

stream = stream instance-attribute

Our parent stream wrapper

__getitem__(key)

Return a key from the stream's chat JSON

Source code in src/cocorum/__init__.py
532
533
534
def __getitem__(self, key: str):
    """Return a key from the stream's chat JSON"""
    return self.stream["chat"][key]

__init__(stream)

Reference for chat of a Rumble livestream

Parameters:

Name Type Description Default
stream Livestream

The wrapper for a single Rumble livestream.

required
Source code in src/cocorum/__init__.py
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
def __init__(self, stream: Livestream):
    """Reference for chat of a Rumble livestream

    Args:
        stream (Livestream): The wrapper for a single Rumble livestream.
    """

    self.stream: Livestream = stream
    """Our parent stream wrapper"""

    self.api = stream.api
    """Our parent RLS API wrapper"""

    self.last_newmessage_time: float = 0
    """The last time we were checked for "new" messages"""

    self.last_newrant_time: float = 0
    """The last time we were checked for "new" rants"""

__repr__()

String to represent this object

Source code in src/cocorum/__init__.py
528
529
530
def __repr__(self) -> str:
    """String to represent this object"""
    return f"{type(self).__name__}(<for stream {self.stream.stream_id_b10}>)"

Livestream

Rumble livestream

Source code in src/cocorum/__init__.py
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
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
class Livestream:
    """Rumble livestream"""

    def __init__(self, jsondata: dict, api: RumbleAPI):
        """Rumble livestream

        Args:
            jsondata (dict): The JSON block for a single livestream.
            api (RumbleAPI): The Rumble Live Stream API wrapper that spawned us.
        """

        self._jsondata: dict = jsondata
        """The saved JSON data of this live stream"""

        self.api: RumbleAPI = api
        """Our parent RLS API wrapper."""

        self.is_disappeared: bool = False
        """If the livestream has vanished from the main API listing. If True, that indicates livestream has ended."""

        self.__chat = LiveChat(self)

    def __eq__(self, other: Any) -> bool:
        """Is this stream equal to another?

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

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

        # Check if the compared string is our stream ID
        if isinstance(other, str):
            return self.stream_id == other  # or self.title == other

        # check if the compared number is our chat ID (linked to stream ID)
        if isinstance(other, (int, float)):
            return self.stream_id_b10 == other

        # Check if the compared object has the same stream ID
        if hasattr(other, "stream_id"):
            return self.stream_id == utils.ensure_b36(other.stream_id)

        # Check if the compared object has the same chat ID
        if hasattr(other, "stream_id_b10"):
            return self.stream_id_b10 == other.stream_id_b10

        return False

    def __str__(self) -> str:
        """The livestream in string form (its ID in base 36)"""
        return self.stream_id

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

    def __getitem__(self, key: str):
        """Return a key from the JSON, refreshing if necessary

        Args:
            key (str): A valid JSON key.
        """

        # The livestream has not disappeared from the API listing,
        # and the key requested is not a value that doesn't change,
        if (not self.is_disappeared) and (key not in static.StaticAPIEndpoints.stream):
            # Make sure the data is not stale
            self.api.check_refresh()

        return self._jsondata[key]

    @property
    def jsondata(self):
        """A copy of the raw JSON from the API. Editing it does not change this object. Time-of-life is applied."""
        self.api.check_refresh()
        return copy.deepcopy(self._jsondata)

    @property
    def stream_id(self) -> str:
        """The livestream ID in base 36"""
        return self["id"]

    @property
    def stream_id_b36(self) -> str:
        """The livestream ID in base 36"""
        return self.stream_id

    @property
    def stream_id_b10(self) -> int:
        """The livestream chat ID (stream ID in base 10)"""
        return utils.base_36_to_10(self.stream_id)

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

    @property
    def created_on(self) -> float:
        """When the livestream was created, in seconds since the Epock UTC"""
        return utils.parse_timestamp(self["created_on"])

    @property
    def is_live(self) -> bool:
        """Is the stream live?"""
        return self["is_live"] and not self.is_disappeared

    @property
    def scheduled_on(self) -> float:
        """When the stream is scheduled to start in seconds since the Epoch UTC, or created_on if not scheduled"""
        if self["scheduled_on"]:
            return utils.parse_timestamp(self["scheduled_on"])
        return self.created_on

    @property
    def visibility(self) -> str:
        """Is the stream public, unlisted, or private?"""
        return self["visibility"]

    @property
    def categories(self) -> list[StreamCategory]:
        """A list of our categories"""
        data = self["categories"].copy().values()
        return [StreamCategory(jsondata_block) for jsondata_block in data]

    @property
    def server_url(self) -> str:
        """The ingest server to stream to"""
        return self["server_url"]

    @property
    def stream_key(self) -> str:
        """The key to use for this stream on the streaming ingest server"""
        return self["stream_key"]

    @property
    def likes(self) -> int:
        """Number of likes on the stream"""
        return self["likes"]

    @property
    def dislikes(self) -> int:
        """Number of dislikes on the stream"""
        return self["dislikes"]

    @property
    def like_ratio(self) -> float:
        """Ratio of people who liked the stream to people who reacted total"""
        try:
            return self.likes / (self.likes + self.dislikes)

        except ZeroDivisionError:
            return 0.5

    @property
    def watching_now(self) -> int:
        """The number of people watching now"""
        return self["watching_now"]

    @property
    def chat(self) -> LiveChat:
        """The livestream chat"""
        return self.__chat

api = api instance-attribute

Our parent RLS API wrapper.

categories property

A list of our categories

chat property

The livestream chat

created_on property

When the livestream was created, in seconds since the Epock UTC

dislikes property

Number of dislikes on the stream

is_disappeared = False instance-attribute

If the livestream has vanished from the main API listing. If True, that indicates livestream has ended.

is_live property

Is the stream live?

jsondata property

A copy of the raw JSON from the API. Editing it does not change this object. Time-of-life is applied.

like_ratio property

Ratio of people who liked the stream to people who reacted total

likes property

Number of likes on the stream

scheduled_on property

When the stream is scheduled to start in seconds since the Epoch UTC, or created_on if not scheduled

server_url property

The ingest server to stream to

stream_id property

The livestream ID in base 36

stream_id_b10 property

The livestream chat ID (stream ID in base 10)

stream_id_b36 property

The livestream ID in base 36

stream_key property

The key to use for this stream on the streaming ingest server

title property

The title of the livestream

visibility property

Is the stream public, unlisted, or private?

watching_now property

The number of people watching now

__eq__(other)

Is this stream 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/__init__.py
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
def __eq__(self, other: Any) -> bool:
    """Is this stream equal to another?

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

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

    # Check if the compared string is our stream ID
    if isinstance(other, str):
        return self.stream_id == other  # or self.title == other

    # check if the compared number is our chat ID (linked to stream ID)
    if isinstance(other, (int, float)):
        return self.stream_id_b10 == other

    # Check if the compared object has the same stream ID
    if hasattr(other, "stream_id"):
        return self.stream_id == utils.ensure_b36(other.stream_id)

    # Check if the compared object has the same chat ID
    if hasattr(other, "stream_id_b10"):
        return self.stream_id_b10 == other.stream_id_b10

    return False

__getitem__(key)

Return a key from the JSON, refreshing if necessary

Parameters:

Name Type Description Default
key str

A valid JSON key.

required
Source code in src/cocorum/__init__.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def __getitem__(self, key: str):
    """Return a key from the JSON, refreshing if necessary

    Args:
        key (str): A valid JSON key.
    """

    # The livestream has not disappeared from the API listing,
    # and the key requested is not a value that doesn't change,
    if (not self.is_disappeared) and (key not in static.StaticAPIEndpoints.stream):
        # Make sure the data is not stale
        self.api.check_refresh()

    return self._jsondata[key]

__init__(jsondata, api)

Rumble livestream

Parameters:

Name Type Description Default
jsondata dict

The JSON block for a single livestream.

required
api RumbleAPI

The Rumble Live Stream API wrapper that spawned us.

required
Source code in src/cocorum/__init__.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def __init__(self, jsondata: dict, api: RumbleAPI):
    """Rumble livestream

    Args:
        jsondata (dict): The JSON block for a single livestream.
        api (RumbleAPI): The Rumble Live Stream API wrapper that spawned us.
    """

    self._jsondata: dict = jsondata
    """The saved JSON data of this live stream"""

    self.api: RumbleAPI = api
    """Our parent RLS API wrapper."""

    self.is_disappeared: bool = False
    """If the livestream has vanished from the main API listing. If True, that indicates livestream has ended."""

    self.__chat = LiveChat(self)

__repr__()

String to represent this object

Source code in src/cocorum/__init__.py
273
274
275
276
277
def __repr__(self) -> str:
    """String to represent this object"""
    return (
        f'{type(self).__name__}(title="{self.title}", stream_id={self.stream_id})'
    )

__str__()

The livestream in string form (its ID in base 36)

Source code in src/cocorum/__init__.py
269
270
271
def __str__(self) -> str:
    """The livestream in string form (its ID in base 36)"""
    return self.stream_id

Rant

Bases: ChatMessage

A single rant in a Rumble livestream chat

Source code in src/cocorum/__init__.py
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
class Rant(ChatMessage):
    """A single rant in a Rumble livestream chat"""

    def __eq__(self, other: Any) -> bool:
        """Is this category equal to another?

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

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

        # Check if the compared string is our message
        if isinstance(other, str):
            return self.text == other

        # # Check if the compared rant has the same username, amount, and text (unneccesary?)
        # if type(other) == type(self):
        #     return (self.username, self.amount_cents, self.text) == (other.username, other.amount_cents, other.text)

        # Check if the compared object has the same text
        if hasattr(other, "text"):
            # Check if the compared object has the same username, if it has one
            if hasattr(other, "username"):
                # Check if the compared object has the same cost amount, if it has one
                if hasattr(other, "amount_cents"):
                    return (self.username, self.amount_cents, self.text) == (
                        other.username,
                        other.amount_cents,
                        other.text,
                    )

                # Other object has no amount_cents attribute
                return (self.username, self.text) == (other.username, other.text)

            # Other object had no username attribute
            return self.text == other.text

        return False

    def __repr__(self) -> str:
        """String to represent this object"""
        return f"{type(self).__name__}(username='{self.username}', text=\"{self.text}\", <for ${self.amount_cents / 100:.02f}>)"

    @property
    def expires_on(self) -> float:
        """When the rant will expire, in seconds since the Epoch UTC"""
        return self["expires_on"]

    @property
    def amount_cents(self) -> int:
        """The total rant amount in cents"""
        return self["amount_cents"]

    @property
    def amount_dollars(self) -> int:
        """The rant amount in dollars"""
        return self["amount_dollars"]

amount_cents property

The total rant amount in cents

amount_dollars property

The rant amount in dollars

expires_on property

When the rant will expire, in seconds since the Epoch UTC

__eq__(other)

Is this category 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/__init__.py
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
def __eq__(self, other: Any) -> bool:
    """Is this category equal to another?

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

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

    # Check if the compared string is our message
    if isinstance(other, str):
        return self.text == other

    # # Check if the compared rant has the same username, amount, and text (unneccesary?)
    # if type(other) == type(self):
    #     return (self.username, self.amount_cents, self.text) == (other.username, other.amount_cents, other.text)

    # Check if the compared object has the same text
    if hasattr(other, "text"):
        # Check if the compared object has the same username, if it has one
        if hasattr(other, "username"):
            # Check if the compared object has the same cost amount, if it has one
            if hasattr(other, "amount_cents"):
                return (self.username, self.amount_cents, self.text) == (
                    other.username,
                    other.amount_cents,
                    other.text,
                )

            # Other object has no amount_cents attribute
            return (self.username, self.text) == (other.username, other.text)

        # Other object had no username attribute
        return self.text == other.text

    return False

__repr__()

String to represent this object

Source code in src/cocorum/__init__.py
486
487
488
def __repr__(self) -> str:
    """String to represent this object"""
    return f"{type(self).__name__}(username='{self.username}', text=\"{self.text}\", <for ${self.amount_cents / 100:.02f}>)"

RumbleAPI

Rumble Live Stream API wrapper

Source code in src/cocorum/__init__.py
 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
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
class RumbleAPI:
    """Rumble Live Stream API wrapper"""

    def __init__(
        self,
        api_url: str | scraping.HTMLRLSAPIKeyInfo,
        refresh_rate: int | float = static.Delays.api_refresh_default,
        rumbot_mode: Optional[bool] = None,
    ):
        """Rumble Live Stream API wrapper

        Args:
            api_url (str | scraping.HTMLRLSAPIKeyInfo): The Rumble API URL, with the key.
            refresh_rate (int | float): AKA time to live. How long to reuse queried data before refreshing.
                Defaults to static.Delays.api_refresh_default.
            rumbot_mode (bool): Does the api_url points to an instance of VapinGamers' RUM Live Alerts?
                The API URL for this would usually be http://localhost:9843/api/ls
                Useful to avoid rate limits, but some data is not passed through.
                Defaults to None, auto-detect.
        """

        self.refresh_rate: int | float = refresh_rate
        """How long to reuse queried data before refreshing"""

        api_url = str(api_url)
        self._rumbot_mode: bool = rumbot_mode or api_url.endswith(
            static.URI.rumbot_suffix
        )
        """Does the api_url points to an instance of VapinGamers' RUM Live Alerts?"""

        self.last_refresh_time: float = 0
        """The last time that we refreshed the API JSON data"""

        self.last_newfollower_time: float = time.monotonic()
        """The last time we were checked for "new" followers"""

        self.last_newsubscriber_time = time.monotonic()
        """The last time we were checked for "new" subscribers"""

        self.__livestreams = {}
        #        self.__gifted_subs = {}
        self._jsondata: dict = {}
        """The saved RLS API JSON data"""

        self.__api_url: str = ""

        # This is a property that sets the above private attribute
        self.api_url = api_url

        # Warn about refresh rate being below minimum
        if self.refresh_rate < static.Delays.api_refresh_minimum:
            warnings.warn(
                f"Cocorum set to over-refresh, rate of {self.refresh_rate} seconds (less than {static.Delays.api_refresh_minimum})."
                "Superscript must self-limit or Rumble will reject queries!"
            )

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

    @property
    def api_url(self) -> str:
        """Our API URL"""
        return self.__api_url

    @api_url.setter
    def api_url(self, url: str | scraping.HTMLRLSAPIKeyInfo):
        """Set a new API URL, and refresh

        Args:
            url (str | scraping.HTMLRLSAPIKeyInfo): The new API URL to use.
        """

        url = str(url)

        # Do nothing on a non-change
        if url == self.api_url:
            return

        self.__api_url = url
        self._rumbot_mode: bool = url.endswith(static.URI.rumbot_suffix)
        self.refresh()

    def __getitem__(self, key: str):
        """Return a key from the JSON, refreshing if necessary

        Args:
            key (str): A valid JSON key.
        """

        # This is not a static key, so make sure the data isn't stale
        if key not in static.StaticAPIEndpoints.main:
            self.check_refresh()

        return self._jsondata[key]

    @property
    def jsondata(self):
        """A copy of the raw JSON from the API. Editing it does not change this object. Time-of-life is applied."""
        self.check_refresh()
        return copy.deepcopy(self._jsondata)

    def check_refresh(self):
        """Refresh only if we are past the refresh rate"""
        if time.monotonic() - self.last_refresh_time > self.refresh_rate:
            self.refresh()

    def refresh(self):
        """Reload data from the API"""
        self.last_refresh_time = time.monotonic()
        response = requests.get(
            self.api_url,
            headers=static.RequestHeaders.user_agent,
            timeout=static.Delays.request_timeout,
        )
        assert response.status_code == 200, f"Status code {response.status_code}"

        self._jsondata = response.json()

        # If we are in RUM Live Alerts mode, remove padding
        if self._rumbot_mode:
            self.__unpad_jsondata()

        # Remove livestream references that are no longer listed
        listed_ids = [jsondata["id"] for jsondata in self._jsondata["livestreams"]]
        for stream_id in self.__livestreams.copy():
            if stream_id not in listed_ids:
                self.__livestreams[stream_id].is_disappeared = True
                del self.__livestreams[stream_id]

        # Update livestream references' JSONs in-place
        for jsondata in self._jsondata["livestreams"]:
            try:
                # Update the JSON of the stored livestream
                self.__livestreams[jsondata["id"]]._jsondata = jsondata

            except KeyError:  # The livestream has not been stored yet
                self.__livestreams[jsondata["id"]] = Livestream(jsondata, self)

    def __unpad_jsondata(self):
        """Remove padding from JSON data we retrieved from RUM Live Alerts"""

        # Nullify blank latest follower
        if not self._jsondata["followers"]["latest_follower"]["username"]:
            self._jsondata["followers"]["latest_follower"] = None

        # Remove blank recent followers
        self._jsondata["followers"]["recent_followers"] = [
            f for f in self._jsondata["followers"]["recent_followers"] if f["username"]
        ]

        # Nullify blank latest subscriber
        if not self._jsondata["subscribers"]["latest_subscriber"]["username"]:
            self._jsondata["subscribers"]["latest_subscriber"] = None

        # Remove blank recent subscribers
        self._jsondata["subscribers"]["recent_subscribers"] = [
            f
            for f in self._jsondata["subscribers"]["recent_subscribers"]
            if f["username"]
        ]

        # Remove blank livestreams
        self._jsondata["livestreams"] = [
            l for l in self._jsondata["livestreams"] if l["id"]
        ]

        # For each real Livestream
        for l in self._jsondata["livestreams"]:
            # Nullify blank latest Rant
            if not l["chat"]["latest_rant"]["username"]:
                l["chat"]["latest_rant"] = None

            # Remove blank recent rants
            l["chat"]["recent_rants"] = [
                r for r in l["chat"]["recent_rants"] if r["username"]
            ]

    @property
    def data_timestamp(self) -> float:
        """The timestamp on the last data refresh"""
        # Definitely don't ever trigger a refresh on this
        return self._jsondata["now"]

    @property
    def api_type(self) -> str:
        """Type of API URL in use, user or channel"""
        return self["type"]

    @property
    def user_id(self) -> str:
        """The user ID in base 36"""
        return self["user_id"]

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

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

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

    @property
    def channel_id(self) -> int | None:
        """The channel ID, if we are a channel, in base 10"""
        return self["channel_id"]

    @property
    def channel_id_b10(self) -> int | None:
        """The channel ID, if we are a channel, in base 10"""
        return self.channel_id

    @property
    def channel_id_b36(self) -> int | None:
        """The channel ID, if we are a channel, in base 36"""
        return utils.base_10_to_36(self.channel_id) if self.channel_id else None

    @property
    def channel_name(self) -> str:
        """The channel name, if we are a channel"""
        return self["channel_name"]

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

    @property
    def num_followers_total(self) -> int:
        """The total number of followers of this account across all channels"""
        return self["followers"]["num_followers_total"]

    @property
    def latest_follower(self) -> Follower:
        """The latest follower of this user or channel"""
        if not self["followers"]["latest_follower"]:
            return None  # No-one has followed this user or channel yet
        return Follower(self["followers"]["latest_follower"])

    @property
    def recent_followers(self) -> list[Follower]:
        """A list of recent followers"""
        data = self["followers"]["recent_followers"].copy()
        return [Follower(jsondata_block) for jsondata_block in data]

    @property
    def new_followers(self) -> list[Follower]:
        """Followers that are newer than the last time this was checked (or newer than RumbleAPI object creation)"""
        recent_followers = self.recent_followers

        nf = [
            follower
            for follower in recent_followers
            if follower.followed_on > self.last_newfollower_time
        ]
        nf.sort(key=lambda x: x.followed_on)

        self.last_newfollower_time = time.monotonic()

        return nf

    @property
    def num_subscribers(self) -> int:
        """The number of subscribers of this user or channel"""
        return self["subscribers"]["num_subscribers"]

    @property
    def num_subscribers_total(self) -> int:
        """The total number of subscribers of this account across all channels"""
        return self["subscribers"]["num_subscribers_total"]

    @property
    def latest_subscriber(self) -> Subscriber:
        """The latest subscriber of this user or channel"""
        if not self["subscribers"]["latest_subscriber"]:
            return None  # No-one has subscribed to this user or channel yet
        return Subscriber(self["subscribers"]["latest_subscriber"])

    @property
    def recent_subscribers(self) -> list[Subscriber]:
        """A list of recent subscribers (shallow)"""
        data = self["subscribers"]["recent_subscribers"].copy()
        return [Subscriber(jsondata_block) for jsondata_block in data]

    @property
    def new_subscribers(self) -> list[Subscriber]:
        """Subscribers that are newer than the last time this was checked (or newer than RumbleAPI object creation)"""
        recent_subscribers = self.recent_subscribers

        ns = [
            subscriber
            for subscriber in recent_subscribers
            if subscriber.subscribed_on > self.last_newsubscriber_time
        ]
        ns.sort(key=lambda x: x.subscribed_on)

        self.last_newsubscriber_time = time.monotonic()

        return ns

    @property
    def livestreams(self) -> dict[str, Livestream]:
        """A dictionairy of our livestreams by their base 36 IDs"""
        self.check_refresh()
        return self.__livestreams

    @property
    def latest_livestream(self) -> Livestream:
        """Return latest livestream to be created. Use this to get a single running livestream"""
        if not self.livestreams:
            return None  # No livestreams are running
        return max(self.livestreams.values(), key=lambda x: x.created_on)

    @property
    def latest_gifted_sub(self) -> GiftedSub | None:
        """The latest subscriptions gift sent on the user or channel.
        WARNING: This is shallow! I have no way to reliably ID particular gifts to update the GiftedSub data."""
        # This endpoint does not exist in the RUM Live Alerts LS API
        if self._rumbot_mode:
            warnings.warn(
                "RUM Live Alerts does not pass gifted subscriptions in its LS API passthrough. This will always be None."
            )
            return None

        return GiftedSub(self["latest_gifted_sub"])

    @property
    def recent_gifted_subs(self) -> list[GiftedSub]:
        """The most recent subscriptions gifts sent on the user or channel.
        WARNING: This is shallow! I have no way to reliably ID particular gifts to update the GiftedSub data."""
        # This endpoint does not exist in the RUM Live Alerts LS API
        if self._rumbot_mode:
            warnings.warn(
                "RUM Live Alerts does not pass gifted subscriptions in its LS API passthrough. This will always be an empty list."
            )
            return []

        return [GiftedSub(jsondata) for jsondata in self["recent_gifted_subs"]]

api_type property

Type of API URL in use, user or channel

api_url property writable

Our API URL

channel_id property

The channel ID, if we are a channel, in base 10

channel_id_b10 property

The channel ID, if we are a channel, in base 10

channel_id_b36 property

The channel ID, if we are a channel, in base 36

channel_name property

The channel name, if we are a channel

data_timestamp property

The timestamp on the last data refresh

jsondata property

A copy of the raw JSON from the API. Editing it does not change this object. Time-of-life is applied.

last_newfollower_time = time.monotonic() instance-attribute

The last time we were checked for "new" followers

last_newsubscriber_time = time.monotonic() instance-attribute

The last time we were checked for "new" subscribers

last_refresh_time = 0 instance-attribute

The last time that we refreshed the API JSON data

latest_follower property

The latest follower of this user or channel

latest_gifted_sub property

The latest subscriptions gift sent on the user or channel. WARNING: This is shallow! I have no way to reliably ID particular gifts to update the GiftedSub data.

latest_livestream property

Return latest livestream to be created. Use this to get a single running livestream

latest_subscriber property

The latest subscriber of this user or channel

livestreams property

A dictionairy of our livestreams by their base 36 IDs

new_followers property

Followers that are newer than the last time this was checked (or newer than RumbleAPI object creation)

new_subscribers property

Subscribers that are newer than the last time this was checked (or newer than RumbleAPI object creation)

num_followers property

The number of followers of this user or channel

num_followers_total property

The total number of followers of this account across all channels

num_subscribers property

The number of subscribers of this user or channel

num_subscribers_total property

The total number of subscribers of this account across all channels

recent_followers property

A list of recent followers

recent_gifted_subs property

The most recent subscriptions gifts sent on the user or channel. WARNING: This is shallow! I have no way to reliably ID particular gifts to update the GiftedSub data.

recent_subscribers property

A list of recent subscribers (shallow)

refresh_rate = refresh_rate instance-attribute

How long to reuse queried data before refreshing

user_id property

The user ID in base 36

user_id_b10 property

The user ID in base 10

user_id_b36 property

The user ID in base 36

username property

The username

__getitem__(key)

Return a key from the JSON, refreshing if necessary

Parameters:

Name Type Description Default
key str

A valid JSON key.

required
Source code in src/cocorum/__init__.py
778
779
780
781
782
783
784
785
786
787
788
789
def __getitem__(self, key: str):
    """Return a key from the JSON, refreshing if necessary

    Args:
        key (str): A valid JSON key.
    """

    # This is not a static key, so make sure the data isn't stale
    if key not in static.StaticAPIEndpoints.main:
        self.check_refresh()

    return self._jsondata[key]

__init__(api_url, refresh_rate=static.Delays.api_refresh_default, rumbot_mode=None)

Rumble Live Stream API wrapper

Parameters:

Name Type Description Default
api_url str | HTMLRLSAPIKeyInfo

The Rumble API URL, with the key.

required
refresh_rate int | float

AKA time to live. How long to reuse queried data before refreshing. Defaults to static.Delays.api_refresh_default.

api_refresh_default
rumbot_mode bool

Does the api_url points to an instance of VapinGamers' RUM Live Alerts? The API URL for this would usually be http://localhost:9843/api/ls Useful to avoid rate limits, but some data is not passed through. Defaults to None, auto-detect.

None
Source code in src/cocorum/__init__.py
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
def __init__(
    self,
    api_url: str | scraping.HTMLRLSAPIKeyInfo,
    refresh_rate: int | float = static.Delays.api_refresh_default,
    rumbot_mode: Optional[bool] = None,
):
    """Rumble Live Stream API wrapper

    Args:
        api_url (str | scraping.HTMLRLSAPIKeyInfo): The Rumble API URL, with the key.
        refresh_rate (int | float): AKA time to live. How long to reuse queried data before refreshing.
            Defaults to static.Delays.api_refresh_default.
        rumbot_mode (bool): Does the api_url points to an instance of VapinGamers' RUM Live Alerts?
            The API URL for this would usually be http://localhost:9843/api/ls
            Useful to avoid rate limits, but some data is not passed through.
            Defaults to None, auto-detect.
    """

    self.refresh_rate: int | float = refresh_rate
    """How long to reuse queried data before refreshing"""

    api_url = str(api_url)
    self._rumbot_mode: bool = rumbot_mode or api_url.endswith(
        static.URI.rumbot_suffix
    )
    """Does the api_url points to an instance of VapinGamers' RUM Live Alerts?"""

    self.last_refresh_time: float = 0
    """The last time that we refreshed the API JSON data"""

    self.last_newfollower_time: float = time.monotonic()
    """The last time we were checked for "new" followers"""

    self.last_newsubscriber_time = time.monotonic()
    """The last time we were checked for "new" subscribers"""

    self.__livestreams = {}
    #        self.__gifted_subs = {}
    self._jsondata: dict = {}
    """The saved RLS API JSON data"""

    self.__api_url: str = ""

    # This is a property that sets the above private attribute
    self.api_url = api_url

    # Warn about refresh rate being below minimum
    if self.refresh_rate < static.Delays.api_refresh_minimum:
        warnings.warn(
            f"Cocorum set to over-refresh, rate of {self.refresh_rate} seconds (less than {static.Delays.api_refresh_minimum})."
            "Superscript must self-limit or Rumble will reject queries!"
        )

__repr__()

String to represent this object

Source code in src/cocorum/__init__.py
751
752
753
def __repr__(self) -> str:
    """String to represent this object"""
    return f"{type(self).__name__}(username='{self.username}', channel_name='{self.channel_name}')"

__unpad_jsondata()

Remove padding from JSON data we retrieved from RUM Live Alerts

Source code in src/cocorum/__init__.py
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
def __unpad_jsondata(self):
    """Remove padding from JSON data we retrieved from RUM Live Alerts"""

    # Nullify blank latest follower
    if not self._jsondata["followers"]["latest_follower"]["username"]:
        self._jsondata["followers"]["latest_follower"] = None

    # Remove blank recent followers
    self._jsondata["followers"]["recent_followers"] = [
        f for f in self._jsondata["followers"]["recent_followers"] if f["username"]
    ]

    # Nullify blank latest subscriber
    if not self._jsondata["subscribers"]["latest_subscriber"]["username"]:
        self._jsondata["subscribers"]["latest_subscriber"] = None

    # Remove blank recent subscribers
    self._jsondata["subscribers"]["recent_subscribers"] = [
        f
        for f in self._jsondata["subscribers"]["recent_subscribers"]
        if f["username"]
    ]

    # Remove blank livestreams
    self._jsondata["livestreams"] = [
        l for l in self._jsondata["livestreams"] if l["id"]
    ]

    # For each real Livestream
    for l in self._jsondata["livestreams"]:
        # Nullify blank latest Rant
        if not l["chat"]["latest_rant"]["username"]:
            l["chat"]["latest_rant"] = None

        # Remove blank recent rants
        l["chat"]["recent_rants"] = [
            r for r in l["chat"]["recent_rants"] if r["username"]
        ]

check_refresh()

Refresh only if we are past the refresh rate

Source code in src/cocorum/__init__.py
797
798
799
800
def check_refresh(self):
    """Refresh only if we are past the refresh rate"""
    if time.monotonic() - self.last_refresh_time > self.refresh_rate:
        self.refresh()

refresh()

Reload data from the API

Source code in src/cocorum/__init__.py
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
def refresh(self):
    """Reload data from the API"""
    self.last_refresh_time = time.monotonic()
    response = requests.get(
        self.api_url,
        headers=static.RequestHeaders.user_agent,
        timeout=static.Delays.request_timeout,
    )
    assert response.status_code == 200, f"Status code {response.status_code}"

    self._jsondata = response.json()

    # If we are in RUM Live Alerts mode, remove padding
    if self._rumbot_mode:
        self.__unpad_jsondata()

    # Remove livestream references that are no longer listed
    listed_ids = [jsondata["id"] for jsondata in self._jsondata["livestreams"]]
    for stream_id in self.__livestreams.copy():
        if stream_id not in listed_ids:
            self.__livestreams[stream_id].is_disappeared = True
            del self.__livestreams[stream_id]

    # Update livestream references' JSONs in-place
    for jsondata in self._jsondata["livestreams"]:
        try:
            # Update the JSON of the stored livestream
            self.__livestreams[jsondata["id"]]._jsondata = jsondata

        except KeyError:  # The livestream has not been stored yet
            self.__livestreams[jsondata["id"]] = Livestream(jsondata, self)

StreamCategory

Bases: JSONObj

Category of a Rumble stream

Source code in src/cocorum/__init__.py
177
178
179
180
181
182
183
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
class StreamCategory(JSONObj):
    """Category of a Rumble stream"""

    @property
    def slug(self) -> str:
        """Return the category's slug, AKA it's ID"""
        return self["slug"]

    @property
    def title(self) -> str:
        """Return the category's title"""
        return self["title"]

    def __eq__(self, other: Any) -> bool:
        """Is this category equal to another?

        Args:
            other (Any): Other object to compare to.

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

        # Check if the compared string is our slug or title
        if isinstance(other, str):
            return other in (self.slug, self.title)

        # 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 category in string form"""
        return self.title

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

slug property

Return the category's slug, AKA it's ID

title property

Return the category's title

__eq__(other)

Is this category equal to another?

Parameters:

Name Type Description Default
other Any

Other object to compare to.

required

Returns:

Name Type Description
Comparison bool

Did it fit the criteria?

Source code in src/cocorum/__init__.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def __eq__(self, other: Any) -> bool:
    """Is this category equal to another?

    Args:
        other (Any): Other object to compare to.

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

    # Check if the compared string is our slug or title
    if isinstance(other, str):
        return other in (self.slug, self.title)

    # 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/__init__.py
214
215
216
def __repr__(self) -> str:
    """String to represent this object"""
    return f"{type(self).__name__}(slug='{self.slug}')"

__str__()

The category in string form

Source code in src/cocorum/__init__.py
210
211
212
def __str__(self) -> str:
    """The category in string form"""
    return self.title

Subscriber

Bases: JSONUserAction

Rumble subscriber

Source code in src/cocorum/__init__.py
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
class Subscriber(JSONUserAction):
    """Rumble subscriber"""

    def __repr__(self) -> str:
        """String to represent this object"""
        return f"{type(self).__name__}(username='{self.username}', subscribed_on='{self.subscribed_on}', <for ${self.amount_cents / 100:.02f}>)"

    def __eq__(self, other: Any) -> bool:
        """Is this subscriber equal to another?

        Args:
            other (Any): The other object to compare to.

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

        # Check if the compared string is our username
        if isinstance(other, str):
            return self.username == other

        # check if the compared number is our amount in cents
        # if isinstance(other, (int, float)):
        # return self.amount_cents == other

        # Check if the compared object's username matches our own, if it has one
        if hasattr(other, "username"):
            # Check if the compared object's cost amout matches our own, if it has one
            if hasattr(other, "amount_cents"):
                return self.amount_cents == other.amount_cents

            # Other object has no amount_cents attribute
            return self.username == other.username

        return False

    @property
    def user(self) -> str:
        """AFAIK this is being deprecated, use username instead"""
        return self["user"]

    @property
    def amount_cents(self) -> int:
        """The total subscription amount in cents"""
        return self["amount_cents"]

    @property
    def amount_dollars(self) -> int:
        """The subscription amount in dollars"""
        return self["amount_dollars"]

    @property
    def subscribed_on(self) -> float:
        """When the subscriber subscribed, in seconds since Epoch UTC"""
        return utils.parse_timestamp(self["subscribed_on"])

amount_cents property

The total subscription amount in cents

amount_dollars property

The subscription amount in dollars

subscribed_on property

When the subscriber subscribed, in seconds since Epoch UTC

user property

AFAIK this is being deprecated, use username instead

__eq__(other)

Is this subscriber equal to another?

Parameters:

Name Type Description Default
other Any

The other object to compare to.

required

Returns:

Name Type Description
Comparison bool

Did it fit the criteria?

Source code in src/cocorum/__init__.py
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
def __eq__(self, other: Any) -> bool:
    """Is this subscriber equal to another?

    Args:
        other (Any): The other object to compare to.

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

    # Check if the compared string is our username
    if isinstance(other, str):
        return self.username == other

    # check if the compared number is our amount in cents
    # if isinstance(other, (int, float)):
    # return self.amount_cents == other

    # Check if the compared object's username matches our own, if it has one
    if hasattr(other, "username"):
        # Check if the compared object's cost amout matches our own, if it has one
        if hasattr(other, "amount_cents"):
            return self.amount_cents == other.amount_cents

        # Other object has no amount_cents attribute
        return self.username == other.username

    return False

__repr__()

String to represent this object

Source code in src/cocorum/__init__.py
123
124
125
def __repr__(self) -> str:
    """String to represent this object"""
    return f"{type(self).__name__}(username='{self.username}', subscribed_on='{self.subscribed_on}', <for ${self.amount_cents / 100:.02f}>)"

S.D.G.