The RESTApi and Hikari’s Cache state#
What is REST?#
A REST (REpresentational State Transfer) Api is an interface which allows exchange of data from your application to a web service using HTTP requests (GET/POST/PATCH etc).
Hikari’s RESTClient#
In case of hikari, requests to the Discord RESTApi is handled by the hikari.api.RESTClient
class which can be accessed using GatewayBot.rest
.
The RESTClient provides you methods which can be utilised to send/fetch data payloads to/from discord API.
Example Usage
Sending a message to some channel whenever someone joins a server.
import hikari
intents = hikari.Intents(hikari.Intents.ALL_UNPRIVILEGED | hikari.Intents.GUILD_MEMBERS)
bot = hikari.GatewayBot("token", intents=intents)
CHANNEL_ID = 123456789
@bot.listen()
async def membed_added(event: hikari.MemberCreateEvent) -> None:
await bot.rest.create_message( # bot.rest here is a RESTClient object.
CHANNEL_ID, f"{event.member.username} Joined the server."
)
bot.run()
Explanation
Declaring a variable named
CHANNEL_ID
which stores the ID of channel to send logs in.Creating a
hikari.MemberCreateEvent
which is fired when a new Member is added to a server.Inside the membed_added listener,
bot.rest
is used to access thehikari.api.RESTClient
object …… which has a
create_message
method used to send messages on discord.
You can find all the RESTClient methods here
Cache#
Hikari has a clean and completely customisable Cache Implementation which the library uses to store discord objects states inside the bot process’ memory.
How is Cache helpful?
Discord has strict ratelimits for Bot applications, i.e. making too many requests to API can get you banned. Cache stores the object so you don’t need to fetch
them everytime from the API to use them.
It can be accessed using GatewayBot.cache
which returns a hikari.api.Cache
object with methods to work with the internal cache state.
Example Usage
Getting the total number of Members in a server.
import hikari
intents = hikari.Intents(
hikari.Intents.ALL_UNPRIVILEGED
| hikari.Intents.GUILD_MEMBERS # 1
| hikari.Intents.MESSAGE_CONTENT # 1
)
bot = hikari.GatewayBot("token", intents=intents)
@bot.listen()
async def membed_added(event: hikari.GuildMessageCreateEvent) -> None:
if event.content.startswith("!members"): # 2
members = bot.cache.get_members_view_for_guild(event.message.guild_id) # 3
await event.message.respond(f"This server has {len(members)} members.")
bot.run()
Explanation
#1: MESSAGE_CONTENT intents is required to get the content of a message, else
None
is returned. GUILD_MEMBERS intents is required for cache-ing guild members.#2: Checking if the message content starts with the string we want as the command.
#3: Getting all the members in the server as a dictionary as { member_id: hikari.Member } mapping.