Caching#
When it comes to maintaining a bot with a lot of traffic, You need to maintain a cache in order to prevent excessive API calls that may lead to ratelimits. Luster makes this process incredibly simple.
The library not only automatically maintains a cache for you but also allows you to write custom cache handlers to implement caching using some service such as Redis.
Cache#
- class luster.Cache#
A class that handles caching of various entities from Revolt API.
This acts as a base class for custom cache handlers. You may inherit this class to implement custom caching using a separate service such as Redis.
The possible ways of accessing the instance of this object is:
- add_channel(channel: ChannelT) None#
Adds a new channel to the cache.
If a similar channel already exists, It will be overwritten.
- Parameters
channel (Union[
ServerChannel,PrivateChannel]) – The channel to add.
- add_server(server: Server) None#
Adds a new server to the cache.
If a similar server already exists, It will be overwritten.
- Parameters
server (
Server) – The server to add.
- add_user(user: User) None#
Adds a new user to the cache.
If a similar user already exists, It will be overwritten.
- Parameters
user (
User) – The user to add.
- channels() List[ChannelT]#
The channels that are currently cached.
- Returns
- Return type
List[Union[
ServerChannel,PrivateChannel]]
- get_channel(channel_id: str) Optional[ChannelT]#
Gets a channel from the cache.
- Parameters
channel_id (
str) – The ID of channel to get.- Returns
The requested channel; if exists. Otherwise
None.- Return type
Optional[Union[
ServerChannel,PrivateChannel]]
- remove_channel(channel_id: str) Optional[ChannelT]#
Removes a channel from the cache.
- Parameters
channel_id (
str) – The ID of channel to remove.- Returns
The remoevd channel; if exists. Otherwise
None.- Return type
Optional[Union[
ServerChannel,PrivateChannel]]
Custom Cache Handler#
You can subclass Cache and override certain methods to implement custom caching. Here
is an example of implementing custom caching for users using a simple dictionary:
class MyCache(luster.Cache):
def __init__(self) -> None:
self._users = {}
def add_user(self, user):
self._users[user.id] = user
def get_user(self, user_id):
return self._users.get(user_id)
def remove_user(self, user_id):
return self._users.pop(user_id, None)
def users(self):
return list(self._users.values())
Now that we have implemented custom caching for users, we can pass our MyCache class to
Client:
client = luster.Client(token="...", cache_cls=MyCache)
# client.cache is now MyCache