#132 – Learning to write a discord bot in Python

Hi everybody, today I’ll talk about writing a bot in Python for Discord. It’s a project I had in mind since a long time, but I wanted to do something for Skype at the time (which was kind of harder to do). Since all of my friends moved to Discord, I’ll learn to write a quick discord bot using the library “discord.py”.

Library choice

My library choice was pretty straightforward, I searched for discord api libraries and searched for python on that page. This was the only entry, but since I already knew discord.py by name I hadn’t any issue choosing it.

Once again, the installation is easy, all you have to do is “pip install -U discord.py”

 

Usage

You can find the documentation here.

First, you’ll need to define a discord.Client() object which will be used to connect to discord, then call run() on that object with your application token as parameter to connect to discord. I used that quick tutorial to create my application token and connect it to my server.

Once connected, you can also defined event triggers such as message triggers, for example:

@client.event
async def on_message(message):
if message.content.startswith('!test'):
  await client.send_message(message.channel, 'Writing test')

The first line will define the event trigger, then you’ll have to use the predefined function “on_message” which takes one parameter, “message”, containing one message sent into the chat as a string. The rest is pretty straightforward, client.send_message is used to print a message to the current channel (message.channel).

 

Quick project

So for tonight, I decided to do a quick project to add a “quote” functionality to my bot. I created a connection to a sqlite database which is able to add a new quote (with a Discord message id, or manually), delete it, search a quote, and other things. Here’s the full code:

Leave a Reply

Your email address will not be published.