Getting Started

Simple Bot with Ping Command

Now is the fun part! We'll start by making a simple bot that responds with "Pong" when someone types "!ping" in chat.

The full code is:

import discord
import asyncio

client = discord.Client()

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

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

client.run('Your_Token_Here')

But let's break it down so you can understand and follow along with what's happening.

import discord
import asyncio

as you should already know simply imports Discord.py and asyncio which is used for coroutines.

client = discord.Client()

just instantiates the discord.Client class. I used client in this example, but you can choose any name you want. Again, if you choose to do so, make sure you replace client with the name you pick.

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

prints the bot's name and id when the on_ready() event (@client.event) is triggered. This is when the bot has connected, finished preparing data received from Discord, and is ready to accept commands.

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

is run when the on_message() event (@client.event) is triggered, which is when a new message is sent in chat. The content of the message is then checked to make sure it startswith() the command prefix and actual command name. If the check passes, the bot sends a message saying "Pong!" in chat.

client.run('Your_Token_Here')

begins running the bot.

results matching ""

    No results matching ""