Coding your bot

Getting started with coding your bot.

Assuming you read the last page, you should have your token copied by now. You should also have invited the bot to your server. Now, we need to actually start coding the bot.

Coding the basics

Open up your editor, and create a new folder, and within it a new file. Name it whatever you'd like, for eg. bot.py. Also create a file named .env. Now, lets start coding.

bot.py
import discord # make sure you install py-cord - read the Home Page
from discord.ext import commands # will be discussed later
import os

bot = commands.Bot(command_prefix='!', case_insensitive=True)

@bot.event
async def on_ready():
    print(f"{bot.user} is ready and online!")

@bot.command()
async def hello(ctx):
    await ctx.send("Hey!")

bot.run(os.getenv('TOKEN'))

import discord In this line, we import the py-cord module.

from discord.ext import commandsFrankly speaking, the Discord API doesn't have custom commands as you'd expect. It has events, interactions, and more. Hence, many people use the on_message event, which is triggered every time someone sends a message. To make commands, you need to use an extension called commands. Its installed with the library, so no worries!

bot = commands.Bot(command_prefix='!', case_insensitive=True)We create an instance of Bot. This connects us to Discord

@bot.event The @bot.event() decorator is used to register an event. This is an asynchronous library, so things are done with callbacks. A callback is a function that is called when something else happens. In this code, the on_ready() event is called when the bot is ready to start being used.

We use the @bot.command()decorator to register a command. The callback also becomes the name of the command. In the next lines, we send "Hey!" to the user.

Finally, we actually run the bot, getting the Token from the .env file.

Run the bot, and boom! You have your first bot.

Last updated