Using Discord's API to Register New Messages

Question:

What I’m trying to understand is how Discord.py creates and sends responses from their on_message function.
Take this as an example:

@client.event()
async def on_message(message):
  print(message.content)

I’m trying to understand how Discord.py retrieves new messages from Discord without refreshing the channel histories for every single channel in every single server to scan for new messages which would surely hit Discord’s rate limit.

Is there a way to scan for new messages with Discord’s API using fetch or post requests? I am not trying get a solution on how to scan new messages using an already made library. I want to achieve this using only the requests module in python.

Asked By: Walker

||

Answers:

I’m trying to understand how Discord.py retrieves new messages from Discord without refreshing the channel histories for every single channel in every single server to scan for new messages which would surely hit Discord’s rate limit.

Discord bots establish a websocket connection with Discord’s servers, which is essentially a (secure) two-way tunnel. This means that once the connection is up, Discord can send events to you. Instead of you having to manually fetch every single channel, Discord tells you "Hey, a message was created", and the payload attached will give all the additional info about it.

The Discord (not discord.py) docs have detailed info about how everything works behind the scenes, to help the people creating the Bot libraries for you. For example, this section details which types of events Discord can send to you. To see how something is constructed, click on one of the event types and read up on the data that Discord provides.

Is there a way to scan for new messages with Discord’s API using fetch or post requests? I am not trying get a solution on how to scan new messages using an already made library. I want to achieve this using only the requests module in python.

Not really, unless you do in fact send a GET for every single channel, which will get you ratelimited. There’s really no reason to ever use only GET/POST requests (other than Webhooks, where you just send a POST with your info to send a message to a channel without a bot).

If you’d like to read up on Discord’s API, the docs I linked contain a full spec of everything, so you could try to do whatever your heart desires (… and the API supports).

Answered By: stijndcl