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

ยท

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')

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! ๐Ÿ’ฅ")

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)

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)

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: {% gist gist.github.com/isigebengu-mikey/1d333f8647.. %}

ย