Discord.py Sending and Receiving Messages
Connecting to the Bot
To connect to the bot, we need to make a bot client with the bot token:
import discord
client = discord.Client()
client.run("your bot token")
When you run the script, you should see your bot is coming online in the server.
Receiving Messages
To receive messages, we can use an event when a message is sent in the server:
import discord
client = discord.Client()
@client.event
async def on_message(message):
print(message.content)
client.run("token")
The above code prints out the contents of every message sent in the server.
Notice how there is an at symbol (@
) in front of the on_message
function. This is a decorator. Also notice how the function is asynchronous. That means that we don't need to wait for something else to happen in the bot. Right now, our bot is small and it doesn't really matter that much, but imagine your bot became really popular and you would have to wait for everything else.
Checking For Messages
Of course, bots need commands and we need to listen for them. We can do this by simply putting some if statements in the on_message
listener. For example:
import discord
client = discord.Client()
@client.event
async def on_message(message):
if message.content == "$hello":
print("Hello!")
client.run("token")
Sending Messages
To send a message when a command is issued, we first check for the channel where it was issued and send it there:
import discord
client = discord.Client()
@client.event
async def on_message(message):
if message.content == "$hello":
await message.channel.send("Hello!")
client.run("token")
The await
keyword is used to make the message sending asynchronously.