Recipes for Bots
Discord
- Using discord.py
Cogs
Separation of concerns
Separate each set of commands into its own
Cog
import discord from discord.ext import commands class Moderation(commands.Cog): def __init__(self, bot, config): self.bot = bot self.config = config.cogs.Moderation @commands.command() async def kick(self, ctx, member: discord.Member, reason=None): ''' Kick a member from this server. Example: !kick user "toxic" ''' await member.kick(reason=reason) await ctx.send(f'{ctx.author} kicked {member}. Reason: {reason}') @commands.command() async def ban(self, ctx, member: discord.Member, reason=None): ''' Ban a member from this server. Example: !ban user "toxic" ''' await member.ban(reason=reason) await ctx.send(f'{ctx.author} banned {member}. Reason: {reason}')
Load a list of Cogs on startup
from operator import methodcaller import discord import lib.cogs from discord.ext import commands from lib.utilities import load_config, load_secrets config = load_config('config.yml') secrets = load_secrets('secrets.yml') bot = commands.Bot(command_prefix=config.prefix) for cog in config.cogs.keys(): cog_class = methodcaller(cog, bot=bot, config=config)(lib.cogs) bot.add_cog(cog_class) bot.run(secrets.token)