Creating a simple Discord bot using the discord.py library

Asynchronous library discord.py contains everything that is needed for the bot, with it you can even work with the serverโ€™s voice channels. In this article I will tell you how to create a simple bot for your discord server.



Obtaining a token and Client ID for your bot


To get the token and bot ID, you need to create your own application and copy the Client ID in the General Information section.



And in the settings section, create a bot and copy its token. The task is not difficult, I think everyone can handle it.



Actually write a bot


Install discord.py with pip:

pip install discord

After a successful installation, create a file bot.py, where we will write the bot.

We import everything we need:

import discord
from discord.ext import commands

Create a variable with your token, about which I wrote above:

TOKEN = ' '

About token
, - , .

Create the body of the bot:

bot = commands.Bot(command_prefix='!') #    '!'

First, let's make a simple command, the argument of which the bot will simply forward:


@bot.command(pass_context=True) #  
async def test(ctx, arg): #   
    await ctx.send(arg) #  

And at the end we launch the bot with your token:

bot.run(TOKEN)

In the end, you should get this:

The code

import discord
from discord.ext import commands

TOKEN = ' '
bot = commands.Bot(command_prefix='!')


@bot.command(pass_context=True)  #   
async def test(ctx, arg):  #    
    await ctx.send(arg)  #   


bot.run(TOKEN)



Now you need to add the bot to the server. You can do this using the link:

https://discordapp.com/oauth2/authorize?&client_id={Client ID}&scope=bot&permissions={,  66395456}

The number of necessary rights can be obtained in the bot settings section.

Now you can run the bot:

python bot.py

After a few seconds, you can notice it on the network:



And finally try to send the command:



Conclusion


This is how you can easily launch a bot on your server. As you can see, the library does almost everything for you and you can only add your own functionality using python. Next time I will show how to follow events, connect to voice channels (avoiding problems with linux and Windows), use roles and rights of participants, and more.



I hope the article was useful to you, good luck!

All Articles