DEV Community

terabyte.
terabyte.

Posted on

Events in discord.py 🐍

discord.py has an extensive collection of features. Events are one of the most useful of these. Events are used for welcoming bots, reaction roles, and lots of other functions. This guide will teach you more about events, and how you can use them in your discord bot. In the end, we will have the bot print to the console when it is signed in, and give it a simple moderation and logging system.

If you haven't yet, I suggest reading the earlier post in this series, as this builds on the previous post.

So far, we have the following code:



import discord
from discord.ext import commands

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

@bot.command(name='hello', description="Greet the user!")
async def hello(ctx):
    await ctx.send(f"Hello {ctx.author.name}!") # f-string

bot.run('token')


Enter fullscreen mode Exit fullscreen mode

But what if we want to delete a message when a user sends a link in the chat? They obviously wouldn't use a command.


We can use the on_message event to trigger a function whenever a message is sent.

We first want to use the event decorator to tell discord.py that this is an event.



@bot.event
async def on_message(message):
   if 'https://' in message.content:
      await message.delete()
      await message.channel.send(f"{message.author.mention} Don't send links!")
   else:
      await bot.process_commands(message)


Enter fullscreen mode Exit fullscreen mode

Now, if we send a link, the bot will warn us!
Demo

Automoderation πŸ”§

But what if we want to create a profanity list?



badwords = ['bad', 'words', 'here']

@bot.event
async def on_message(message):
   for i in badwords: # Go through the list of bad words;
      if i in message:
         await message.delete()
         await message.channel.send(f"{message.author.mention} Don't use that word here!")
         return # So that it doesn't try to delete the message again.
   await bot.process_commands(message)


Enter fullscreen mode Exit fullscreen mode

Logging πŸ“œ

Events are called by using the dispatch function. When a message is sent, the internals of discord.py uses bot.dispatch('message', message_object). This triggers other parts of discord.py to find the function called on_message and run it. So, we could make our own event that logs profanity!

So let's adapt on the code so that it will use a logging system!



badwords = ['bad', 'words', 'here']

@bot.event
async def on_message(message):
   for i in badwords: # Go through the list of bad words;
      if i in message.content:
         await message.delete()
         await message.channel.send(f"{message.author.mention} Don't use that word!")
         bot.dispatch('profanity', message, i)
         return # So that it doesn't try to delete the message again, which will cause an error.
   await bot.process_commands(message)


Enter fullscreen mode Exit fullscreen mode

Our logging code:

Before beginning this section, you will need to know how to get channel IDs. You can follow this guide if you need to enable developer mode.

You will need to get your log channel ID so that the bot can access the specific channel. Don't worry, IDs aren't private, so you don't have to worry about sharing them.



@bot.event
async def on_profanity(message, word):
   channel = bot.get_channel(channel_id_here) # for me it's bot.get_channel(817421787289485322)
   embed = discord.Embed(title="Profanity Alert!",description=f"{message.author.name} just said ||{word}||", color=discord.Color.blurple()) # Let's make an embed!
   await channel.send(embed=embed)


Enter fullscreen mode Exit fullscreen mode

Demo

Congrats! You just:

  • Created your own event
  • Created a simple automoderation system
  • Logged when the rules are broken
  • Created an embed

Next, we'll be creating a Discord bot that moderates invite links!

Top comments (11)

Collapse
 
vertigoblip profile image
vertigo-blip

hey, very helpful guide. I was wondering how to trigger an event only if a certain user triggers it? For example, if I wanted to kick a certain user that said 'hello', but not have that kick apply to anyone else who said 'hello', how would I do that?

Collapse
 
mikeywastaken profile image
terabyte.

Events are always sent through to the bot, no matter who it's from. However, you can filter them using an if statement. For example, this snippet would work:

@bot.event
async def on_message(message):
    if message.content.lower() == "hello" and message.author.id == person_you_dont_like_id:
        await message.author.kick(reason="your reason goes here")
Enter fullscreen mode Exit fullscreen mode

You'll want to make sure you use .lower() on the text, because if you don't, they can send hEllo or just change the case of other letters to dodge your system.

Collapse
 
alexanderg profile image
Alexander G

Hi friend! very good post, and how I see you are also pythonist xD, I really like Python hehe, I have a bot in Discord.py, I do not know much every day I'm getting new things,For now Search by: YouTube, Google, Wikipedia, among other things :slight_smile: I plan to write more post and translate them so that everyone can read, to my bot also translates texts

Collapse
 
mikeywastaken profile image
terabyte.

That's actually really cool! So you're making a translation bot?

Collapse
 
alexanderg profile image
Alexander G

Hello, good exactly no, I mean my bot is of general purpose, translates and make searches also that if interacting with users and so, and good at discord.py because I really like python :p dev-to-uploads.s3.amazonaws.com/up...

Thread Thread
 
mikeywastaken profile image
terabyte.

Well your bot looks really nice!

Collapse
 
ffbboy30 profile image
ffbboy30

HI,
Thanks for all this explanation.
I need to make a py script that only receive message from a server.
The server is not mine, how can I register to this server ?
Do you have tips to help me.
Thanks

Collapse
 
mikeywastaken profile image
terabyte. • Edited

You can see a guide created by the discord.py creator here to add the bot to the server, which is what you want to do. Make sure that you have the Manage Server permission.

Collapse
 
ffbboy30 profile image
ffbboy30

I haven't this permission , the channel is not mine that why I'm looking for another way

Thread Thread
 
mikeywastaken profile image
terabyte.

You'll need to ask a channel admin to add the bot.

Collapse
 
hemantshukla01 profile image
hemantshukla01

hey can any can help how i can add backend trigger url in my code
@client.command(aliases=['AVN'])
async def AVN(ctx):
await ctx.send(f'@everyone Please all join AVN immediately!!!')