DEV Community

loading...

discord.py Project 1 - Invite Moderator πŸ”—

mikeywastaken profile image Mikey ・2 min read

For restricted servers, an invite moderation bot is a perfect choice.

You should read the first 2 posts in the series before reading this one!

The setup 🚧

We want to start by creating our bot. We will use a commands.Bot, as users will be able to create an invite.

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix="!", case_insensitive=True) # Note: Feel free to change the prefix to something else!

bot.run('token')
Enter fullscreen mode Exit fullscreen mode

Now, let's add the on_ready event so that we know when the bot is ready for commands!

@bot.event
async def on_ready():
    print("Ready for action! πŸ’₯")
Enter fullscreen mode Exit fullscreen mode

Adding our invite command ❗

We now need to add our invite command, so that the users will be able to create invites using the bot. We will need to manually dispatch an event so that it doesn't get confused with invite_create.

@bot.command(name='invite', description='Create an invite link')
async def invite(ctx, reason):
    invite = await ctx.guild.create_invite(reason=reason)
    await ctx.author.send(str(invite)) # Send the invite to the user
    invite.inviter = ctx.author
    bot.dispatch('invite_command', invite)
Enter fullscreen mode Exit fullscreen mode

Add logging πŸ“œ

We can add logging like we did in the last post. This time, we need to plug in our

@bot.event
async def on_invite_command(invite):
    channel = bot.get_channel(channel_id) # Remember how to get channel IDs?
    embed = discord.Embed(title="New Invite",description=f"Created by {invite.inviter}\nCode: {str(invite)}")
    await channel.send(embed=embed)
Enter fullscreen mode Exit fullscreen mode

Recap! You just:

  • Used the on_ready event for the first time
  • Edited an attribute
  • Used a custom event
  • Created another embed
  • Used get_channel

Final Code:

Discussion (0)

Forem Open with the Forem app