Skip to content
TheChatArchiveThe Chat Archive
Metallama-4-maverick-03-26-experimental· MetaHugging Face LMArena Human Preference 140K

in python use class to create simple discord bot with cogs

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-5-haiku-20241022’s answer.
  1. User

    in python use class to create simple discord bot with cogs

  2. Meta Assistant

    A great request! Here's a simple example of a Discord bot written in Python using classes and cogs. We'll create a bot with two cogs: one for general commands and another for moderation commands.

    Prerequisites:

    1. Python 3.6+
    2. discord.py library (pip install discord.py)
    3. A Discord bot token (create a bot on the Discord Developer Portal)

    Project Structure:

    discord_bot/
    ├── bot.py
    ├── cogs/
    │   ├── general.py
    │   ├── moderation.py
    │   └── __init__.py
    └── config.py
    

    config.py (store your bot token and other config variables)

    # config.py
    TOKEN = "YOUR_BOT_TOKEN_HERE"
    PREFIX = "!"
    OWNER_ID = 1234567890  # your Discord user ID
    

    Replace YOUR_BOT_TOKEN_HERE with your actual bot token.

    bot.py (main bot class)

    # bot.py
    import discord
    from discord.ext import commands
    import config
    from cogs import General, Moderation
    
    class Bot(commands.Bot):
        def __init__(self):
            super().__init__(command_prefix=config.PREFIX, owner_id=config.OWNER_ID)
            self.remove_command("help")  # we'll create a custom help command later
    
            # Load cogs
            self.add_cog(General(self))
            self.add_cog(Moderation(self))
    
        async def on_ready(self):
            print(f"{self.user.name} has connected to Discord!")
            await self.change_presence(activity=discord.Game(name=f"{config.PREFIX}help"))
    
        async def on_message(self, message):
            # Ignore messages from the bot itself
            if message.author == self.user:
                return
    
            await self.process_commands(message)
    
    if __name__ == "__main__":
        bot = Bot()
        bot.run(config.TOKEN)
    

    Here's what's happening:

    • We create a Bot class that inherits from commands.Bot.
    • We set the command prefix, owner ID, and remove the default help command.
    • We load our cogs (General and Moderation) and pass the bot instance to them.
    • on_ready event is triggered when the bot connects to Discord. We print a message and set the bot's presence.
    • on_message event is triggered for every message. We ignore messages from the bot itself and process commands otherwise.

    cogs/general.py (general commands cog)

    # cogs/general.py
    import discord
    from discord.ext import commands
    
    class General(commands.Cog):
        def __init__(self, bot):
            self.bot = bot
    
        @commands.command(name="ping", help="Check the bot's latency")
        async def ping(self, ctx):
            latency = round(self.bot.latency * 1000)
            await ctx.send(f"Pong! {latency}ms")
    
        @commands.command(name="help", help="Show this message")
        async def help(self, ctx):
            embed = discord.Embed(title="Help", description="Available commands:")
            for command in self.bot.commands:
                embed.add_field(name=command.name, value=command.help, inline=False)
            await ctx.send(embed=embed)
    
        @commands.command(name="info", help="Get bot information")
        async def info(self, ctx):
            embed = discord.Embed(title="Bot Info")
            embed.add_field(name="Name", value=self.bot.user.name)
            embed.add_field(name="ID", value=self.bot.user.id)
            embed.add_field(name="Owner", value=f"<@{self.bot.owner_id}>")
            await ctx.send(embed=embed)
    
    def setup(bot):
        bot.add_cog(General(bot))
    

    This cog contains three commands:

    • ping: checks the bot's latency
    • help: shows a list of available commands (our custom help command)
    • info: displays bot information (name, ID, owner)

    cogs/moderation.py (moderation commands cog)

    # cogs/moderation.py
    import discord
    from discord.ext import commands
    
    class Moderation(commands.Cog):
        def __init__(self, bot):
            self.bot = bot
    
        @commands.command(name="kick", help="Kick a member")
        @commands.has_permissions(kick_members=True)
        async def kick(self, ctx, member: discord.Member, *, reason=None):
            await member.kick(reason=reason)
            await ctx.send(f"{member.mention} has been kicked!")
    
        @commands.command(name="ban", help="Ban a member")
        @commands.has_permissions(ban_members=True)
        async def ban(self, ctx, member: discord.Member, *, reason=None):
            await member.ban(reason=reason)
            await ctx.send(f"{member.mention} has been banned!")
    
        @commands.command(name="unban", help="Unban a member")
        @commands.has_permissions(ban_members=True)
        async def unban(self, ctx, *, member_id):
            banned_users = await ctx.guild.bans()
            for ban_entry in banned_users:
                user = ban_entry.user
                if str(user.id) == member_id:
                    await ctx.guild.unban(user)
                    await ctx.send(f"{user.name} has been unbanned!")
                    return
    
    def setup(bot):
        bot.add_cog(Moderation(bot))
    

    This cog contains three moderation commands:

    • kick: kicks a member (requires kick_members permission)
    • ban: bans a member (requires ban_members permission)
    • unban: unbans a member by ID (requires ban_members permission)

    cogs/init.py (empty file, just to make the folder a package)

    That's it! Run python bot.py to start your bot.

    Example Use Cases:

    • !ping - Check the bot's latency
    • !help - Show available commands
    • !info - Get bot information
    • !kick @member - Kick a member (with kick_members permission)
    • !ban @member - Ban a member (with ban_members permission)
    • !unban 1234567890 - Unban a member by ID (with ban_members permission)

    This is a basic example to get you started. You can add more cogs, commands, and features as needed. Happy bot-building!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.