JustPaste.it

help_module.py

import discord
from discord.ext import commands
import menus
from menus import MenuPages, ListPageSource
from typing import Optional
from discord import Embed
 
def syntax(command):
    cmd_and_aliases = "|".join([str(command), *command.aliases])
    params = []
    
 
    for key, value in command.params.items():
        if key not in ("self", "ctx"):
            params.append(f"[{key}]" if "Optional" in str(value) else f"<{key}>")
 
    params = " ".join(params)
    return f"```{cmd_and_aliases} {params}```\n{command.brief}"
    
 
class HelpMenu(ListPageSource):
    def __init__(self, ctx, data):
        self.ctx = ctx
        super().__init__(data, per_page=5)
 
    def write_page(self, menu, categories):
        offset = (menu.current_page * self.per_page) + 1
        len_data = 0
        for l in categories.values():
           len_data += len(l)
        
 
        embed = Embed(
            title="Help",
            description="What can I help you with?",
            colour=self.ctx.author.colour
        )
        embed.set_thumbnail(url=self.ctx.author.avatar)
        embed.set_footer(text=f"{offset:,} - {min(len_data, offset + self.per_page - 1):,} of {len_data:,} commands.")
 
        for name, value in categories.items():
            embed.add_field(name=name, value="\n\n".join(value), inline=False)
        return embed
 
    async def format_page(self, menu, entries):
        categories = {} 
        for entry in entries:
            category = entry.extras.get("category")
            if category: 
              if category in categories:
                categories[category].append(syntax(entry))
              else:
                categories[category] = [syntax(entry)]
            else:
              if "Other" in categories:
                categories["Other"].append(syntax(entry))
              else:
                categories["Other"] = [syntax(entry)]
 
        
               
        return self.write_page(menu, categories)
 
class HelpModule(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.bot.remove_command("help")
 
    @commands.command(brief='This command displays this embed.', name="help", extras={"category": "Helpful Commands"})
    async def show_help(self, ctx, cmd: Optional[str]):
        if cmd:
            command = self.bot.get_command(cmd)
            if command:
                await ctx.send(f"{command.name}: {command.brief}")
                return
 
        menu = MenuPages(
            source=HelpMenu(ctx, list(self.bot.commands)),
            clear_reactions_after=True,
        )
        await menu.start(ctx)
 
def setup(bot):
    bot.add_cog(HelpModule(bot))