Skip to content

Latest commit

 

History

History
56 lines (37 loc) · 2.98 KB

File metadata and controls

56 lines (37 loc) · 2.98 KB
title Events
description Events used to listen for certain actions and react to them.

Events

Event Handlers

Events in Discord are a way to listen for certain actions. For example, if you want to know when a user joins your server so you could send a welcome message, you can use the on_member_join event.

First, you need to ask Discord to send you events. This is done via "Intents". Read up the Intents page for more information.

Once you understand what intents are, you can enable the events you need, or just use the default ones with discord.Intents.all().

Now that that's done, let's add an event handler for when a user joins the server. We will use the on_member_join event. We will send a private message to the user welcoming them to the server.

@bot.event
async def on_member_join(member):
    await member.send(
        f'Welcome to the server, {member.mention}! Enjoy your stay here.'
    )

We use the discord.Bot.event decorator to add the event handler.

The on_member_join event is called when a user joins the server. The member parameter is the user that joined. Different events have different names and parameters. You can find all of them here.

So, that's how you add event handlers!

Waiting for User Response

Let's say you want to create a Guess-the-Number game (where the user has to guess a number between 1-10). You need to send a message to a user and wait for them to respond. You can do this with the wait_for method.

@bot.command()
async def gtn(ctx):
    """A Slash Command to play a Guess-the-Number game."""

    await ctx.respond('Guess a number between 1 and 10.')
    guess = await bot.wait_for('message', check=lambda message: message.author == ctx.author)

    if int(guess.content) == 5:
        await ctx.send('You guessed it!')
    else:
        await ctx.send('Nope, try again.')

wait_for takes one argument, which is the event type. The event type is the name of the event you want to wait for. In this case, it's message. It could also be reaction to wait for a reaction to be added.

We pass a keyword argument to wait_for called check. The function may look complicated if you're a beginner. We pass a lambda function, which simplifies the code a bit.

The lambda function takes one parameter, message. When Pycord receives a message, it passes it to the check function. If the function returns True, the message is returned. If the function returns False, the message is ignored and the bot waits for another message.

Here, we check if the message is from the user that sent the command. We simply use message.author == ctx.author. This will check if the author of the message was the person who invoked the command.