Skip to content

Commit

Permalink
Merge pull request #31 from PaulMarisOUMary/refactor-help
Browse files Browse the repository at this point in the history
Refactor help
  • Loading branch information
PaulMarisOUMary authored Mar 19, 2022
2 parents c4f9b53 + 1352b20 commit 6b4ed6f
Show file tree
Hide file tree
Showing 18 changed files with 123 additions and 83 deletions.
2 changes: 1 addition & 1 deletion bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ async def initBot() -> None:

if __name__ == '__main__':
#If you're not using any database replace the "command_prefix" with : commands.when_mentioned_or(bot_data["bot_default_prefix"])
bot = commands.Bot(command_prefix=get_prefix, description=bot_data["bot_description"], case_insensitive=True, intents=discord.Intents.all(), help_command=None)
bot = commands.Bot(command_prefix=get_prefix, description=bot_data["bot_description"], case_insensitive=True, intents=discord.Intents.all())
bot.loop.create_task(initBot())

@bot.event
Expand Down
2 changes: 1 addition & 1 deletion cogs/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ async def reload_latest(self, ctx):
else:
await ctx.send(f"🤘 {latest_cog[0]} reloaded ! | ☠️ __`{len(victims)} task killed`__ | 🔄 __`view(s) reloaded`__")

@commands.command(name="reloadviews", aliases=["rview", "rviews"])
@commands.command(name="reloadviews", aliases=["rview", "rviews", "rv"])
@commands.is_owner()
async def reload_view(self, ctx):
"""Reload each registered views."""
Expand Down
62 changes: 2 additions & 60 deletions cogs/basic.py
Original file line number Diff line number Diff line change
@@ -1,76 +1,18 @@
import time
import asyncio
import discord

from discord.ext import commands
from datetime import datetime, timedelta
from views import help as vhelp

class Basic(commands.Cog, name="basic"):
"""Basic commands, like help, ping, ..."""
"""Basic commands, like ping."""
def __init__(self, bot):
self.bot = bot

def help_custom(self):
emoji = '📙'
label = "Basic"
description = "Basic commands, like help, ping, etc.."
description = "Basic commands, like ping."
return emoji, label, description

@commands.command(name="help", aliases=['?', 'h', "commands"])
async def help(self, ctx, *input: str):
"""Show the help menu."""
if ctx.guild.id in self.bot.prefixes: guild_prefix = self.bot.prefixes[ctx.guild.id]
else: guild_prefix = self.bot.bot_data["bot_default_prefix"]
if not input:
allowed = 5
close_in = round(datetime.timestamp(datetime.now() + timedelta(minutes=allowed)))
embed = discord.Embed(color=discord.Color.dark_grey(), title = "👋 Help · Home", description = f"`Welcome to the help page.`\n\n**The prefix on this server is**: `{guild_prefix}`.\n\nUse `help command` for more info on a command.\nUse `help category` for more info on a category.\nUse the dropdown menu below to select a category.\n\u200b", url='https://github.com/PaulMarisOUMary/Algosup-Discord')
embed.add_field(name="Time remaining :", value=f"This help session will end <t:{close_in}:R>.\nType `help` to open a new session.\n\u200b", inline=False)
embed.add_field(name="Who am I ?", value="I'm a bot made by *WarriorMachine*. Made for Algosup in 2020.\nI have a lot of features such translator, events manager, utils, and more.\n\nI'm open source, you can see my code on [Github](https://github.com/PaulMarisOUMary/Algosup-Discord) !")

view = vhelp.View(bot=self.bot, ctx=ctx, homeembed=embed, ui=2)
message = await ctx.send(embed=embed, view=view)
try:
await asyncio.sleep(60*allowed)
view.stop()
await message.delete()
await ctx.message.add_reaction("<a:checkmark_a:842800730049871892>")
except: pass

elif len(input) == 1:
search, search_command, search_cog, embed = input[0].lower(), None, None, None
try:
search_command = self.bot.get_command(search)
search_cog = self.bot.cogs[search]
except: pass

if search_cog:
if "help_custom" in dir(search_cog):
emoji, label, _ = search_cog.help_custom()
embed = discord.Embed(title = f"{emoji} Help · {label}",description=f"`{search_cog.__doc__}`", url="https://github.com/PaulMarisOUMary/Algosup-Discord")
for command in search_cog.get_commands():
params = ""
for param in command.clean_params: params += f" <{param}>"
embed.add_field(name=f"{command.name}{params}", value=f"{command.help}\n\u200b", inline=False)
elif search_command:
cog = search_command.cog
if "help_custom" in dir(cog):
emoji, label, _ = cog.help_custom()
embed = discord.Embed(title = f"{emoji} Help · {label} : {search_command.name}", description=f"**Command** : {search_command.name}\n{search_command.help}", url="https://github.com/PaulMarisOUMary/Algosup-Discord")
params = ""
for param in search_command.clean_params: params += f" <{param}>"
embed.add_field(name="Usage", value=f"{search_command.name}{params}", inline=False)
embed.add_field(name="Aliases", value=f"{search_command.aliases}`")
else:
raise commands.CommandError("Nothing found.")

embed.set_footer(text="Remind : Hooks such as <> must not be used when executing commands.", icon_url=ctx.message.author.display_avatar.url)
await ctx.send(embed=embed)

elif len(input) > 1:
raise commands.CommandError("Too many arguments.")

@commands.command(name="ping")
async def ping(self, ctx):
"""Show latency in seconds & milliseconds"""
Expand Down
4 changes: 2 additions & 2 deletions cogs/birthday.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from discord.ext import commands, tasks

class Birthday(commands.Cog, name="birthday"):
"""I'll wish you soon a happy birthday!"""
"""I'll wish you soon a happy birthday !"""
def __init__(self, bot):
self.bot = bot

Expand All @@ -18,7 +18,7 @@ def __init__(self, bot):
def help_custom(self):
emoji = '🎁'
label = "Birthday"
description = "Maybe I'll wish you soon a happy birthday!"
description = "Maybe I'll wish you soon a happy birthday !"
return emoji, label, description

def cog_unload(self):
Expand Down
2 changes: 1 addition & 1 deletion cogs/croissants.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from PIL import Image, ImageDraw, ImageFont, ImageSequence

class Croissants(commands.Cog, name="croissants", command_attrs=dict(hidden=True)):
"""Don't leave your computer unlocked!"""
"""Don't leave your computer unlocked !"""
def __init__(self, bot):
self.bot = bot

Expand Down
8 changes: 7 additions & 1 deletion cogs/dad.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from random import random

class Dad(commands.Cog, name="dad", command_attrs=dict(hidden=True)):

"""Dad's jokes."""
def __init__(self, bot):
self.bot = bot
self.settings = bot.bot_data["dad"]
Expand All @@ -15,6 +15,12 @@ def __init__(self, bot):
(?P<name>.+) # The name
""", re.VERBOSE + re.IGNORECASE)

def help_custom(self):
emoji = '👨‍🦳'
label = "Dad's jokes"
description = "Ahah, it was a good one!"
return emoji, label, description

@commands.Cog.listener("on_message")
async def on_receive_message(self, message : discord.Message):
author_id = message.author.id
Expand Down
6 changes: 3 additions & 3 deletions cogs/errors.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
from discord.ext import commands

class Errors(commands.Cog, name="errors"):
"""Errors handler"""
"""Errors handler."""
def __init__(self, bot):
self.bot = bot

"""def help_custom(self):
emoji = '<a:crossmark:842800737221607474>'
emoji = "<a:crossmark:842800737221607474>"
label = "Error"
description = "A custom errors handler."
description = "A custom errors handler. Nothing to see here."
return emoji, label, description"""

@commands.Cog.listener("on_error")
Expand Down
1 change: 0 additions & 1 deletion cogs/fridaycake.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ def help_custom(self):
description = "Commands relative to the FridayCake event !"
return emoji, label, description


def all(self, ctx):
author = ctx.message.author
embed = discord.Embed(title=f"{random.choice(self.cakes)} Fridaycake · All", description="`Show your personnal order of passage.`\n\u200b" ,colour=0xf7346b, url='https://github.com/PaulMarisOUMary/Algosup-Discord')
Expand Down
93 changes: 93 additions & 0 deletions cogs/help.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import string
import discord
import asyncio

from discord.ext import commands
from datetime import datetime, timedelta
from views import help as vhelp #need big refactor

class HelpCommand(commands.HelpCommand):
"""Help command"""

async def on_help_command_error(self, ctx, error) -> None:
handledErrors = [
commands.CommandOnCooldown,
commands.CommandNotFound
]

if not type(error) in handledErrors:
print("! Help command Error :", error, type(error), type(error).__name__)
return await super().on_help_command_error(ctx, error)

def command_not_found(self, string) -> None:
raise commands.CommandNotFound(f"Command {string} is not found")

async def send_bot_help(self, mapping) -> None:
allowed = 5
close_in = round(datetime.timestamp(datetime.now() + timedelta(minutes=allowed)))
embed = discord.Embed(color=discord.Color.dark_grey(), title = "👋 Help · Home", description = f"`Welcome to the help page.`\n\n**The prefix on this server is**: `{self.context.clean_prefix}`.\n\nUse `help command` for more info on a command.\nUse `help category` for more info on a category.\nUse the dropdown menu below to select a category.\n\u200b", url='https://github.com/PaulMarisOUMary/Algosup-Discord')
embed.add_field(name="Time remaining :", value=f"This help session will end <t:{close_in}:R>.\nType `help` to open a new session.\n\u200b", inline=False)
embed.add_field(name="Who am I ?", value="I'm a bot made by *WarriorMachine*. Made for Algosup in 2020.\nI have a lot of features such translator, events manager, utils, and more.\n\nI'm open source, you can see my code on [Github](https://github.com/PaulMarisOUMary/Algosup-Discord) !")

view = vhelp.View(mapping = mapping, ctx = self.context, homeembed = embed, ui = 2)
message = await self.context.send(embed = embed, view = view)
try:
await asyncio.sleep(60*allowed)
view.stop()
await message.delete()
await self.context.message.add_reaction("<a:checkmark_a:842800730049871892>")
except: pass

async def send_command_help(self, command):
cog = command.cog
if "help_custom" in dir(cog):
emoji, label, _ = cog.help_custom()
embed = discord.Embed(title = f"{emoji} Help · {label} : {command.name}", description=f"**Command** : {command.name}\n{command.help}", url="https://github.com/PaulMarisOUMary/Algosup-Discord")
params = ""
for param in command.clean_params:
params += f" <{param}>"
embed.add_field(name="Usage", value=f"{command.name}{params}", inline=False)
embed.add_field(name="Aliases", value=f"{command.aliases}`")
embed.set_footer(text="Remind : Hooks such as <> must not be used when executing commands.", icon_url=self.context.message.author.display_avatar.url)
await self.context.send(embed=embed)

async def send_cog_help(self, cog):
if "help_custom" in dir(cog):
emoji, label, _ = cog.help_custom()
embed = discord.Embed(title = f"{emoji} Help · {label}",description=f"`{cog.__doc__}`", url="https://github.com/PaulMarisOUMary/Algosup-Discord")
for command in cog.get_commands():
params = ""
for param in command.clean_params:
params += f" <{param}>"
embed.add_field(name=f"{command.name}{params}", value=f"{command.help}\n\u200b", inline=False)
embed.set_footer(text="Remind : Hooks such as <> must not be used when executing commands.", icon_url=self.context.message.author.display_avatar.url)
await self.context.send(embed=embed)

async def send_group_help(self, group):
await self.context.send("Group commands unavailable.")

class Help(commands.Cog, name="help"):
"""Help commands."""
def __init__(self, bot):
self._original_help_command = bot.help_command

attributes = {
'name': "help",
'aliases': ['h', '?'],
'cooldown': commands.CooldownMapping.from_cooldown(1, 5, commands.BucketType.user) # discordpy2.0
}

bot.help_command = HelpCommand(command_attrs=attributes)
bot.help_command.cog = self

def cog_unload(self):
self.bot.help_command = self._original_help_command

def help_custom(self):
emoji = '🆘'
label = "Help"
description = "Help utilities."
return emoji, label, description

def setup(bot):
bot.add_cog(Help(bot))
2 changes: 1 addition & 1 deletion cogs/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def __init__(self, bot):
def help_custom(self):
emoji = '📊'
label = "Info"
description = "Commands about additionals informations."
description = "Commands about additionals informations such as stats."
return emoji, label, description

@commands.command(name="emojilist", aliases=["ce", "el"])
Expand Down
4 changes: 2 additions & 2 deletions cogs/me.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
from discord.ext import commands

class Me(commands.Cog, name="me"):
"""FridayCake's event commands."""
"""Like minecraft set your own /me !"""
def __init__(self, bot):
self.bot = bot

self.me_data = self.bot.database_data["me"]
self.max_lenght_me = self.me_data["max_length"]

def help_custom(self):
emoji = '🤸'
emoji = '🤙'
label = "Me"
description = "Set and show a brief description of yourself."
return emoji, label, description
Expand Down
2 changes: 1 addition & 1 deletion cogs/privatetextual.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def get_created_roles(cont):
return wrong_roles

class PrivateTextual(commands.Cog, name="privatetextual"):
"""Create and manage private textual channels"""
"""Create and manage private textual channels."""
def __init__(self, bot):
self.bot = bot

Expand Down
2 changes: 1 addition & 1 deletion cogs/spotify.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from discord.ext import commands

class Spotify(commands.Cog, name="spotify"):
"""Show Spotify songs"""
"""Show Spotify songs."""
def __init__(self, bot):
self.bot = bot

Expand Down
2 changes: 1 addition & 1 deletion cogs/status.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from discord.ext import commands

class Status(commands.Cog, name="status"):
"""A loop to set the current status of the bot"""
"""A loop to set the current status of the bot."""
def __init__(self, bot):
self.bot = bot
self.task_change_status = self.bot.loop.create_task(self.loop_change_status())
Expand Down
2 changes: 1 addition & 1 deletion cogs/traductor.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from googletrans import Translator #pip install googletrans==4.0.0-rc1

class Traductor(commands.Cog, name="traductor"):
"""A Cog to translate each non-English messages"""
"""A Cog to translate each non-English messages."""
def __init__(self, bot):
self.bot = bot

Expand Down
2 changes: 1 addition & 1 deletion cogs/usefull.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from discord.ext import commands

class Usefull(commands.Cog, name="usefull"):
"""Usefull commands for Devs & more"""
"""Usefull commands for Devs & more."""
def __init__(self, bot):
self.bot = bot

Expand Down
2 changes: 1 addition & 1 deletion cogs/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from views import link

class Views(commands.Cog, name="views"):
"""Experimental cog, new features such buttons, dropdown or whispering"""
"""Experimental cog, new features such buttons, dropdown or whispering."""
def __init__(self, bot):
self.bot = bot

Expand Down
8 changes: 4 additions & 4 deletions views/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message("❌ Hey it's not your session !", ephemeral=True)

class View(discord.ui.View):
def __init__(self, bot : discord.ext.commands.bot.Bot, ctx : discord.ext.commands.context.Context, homeembed : discord.embeds.Embed, ui : int):
def __init__(self, mapping: dict, ctx: discord.ext.commands.context.Context, homeembed: discord.embeds.Embed, ui: int):
super().__init__()
self.ctx, self.bot, self.home = ctx, bot, homeembed
self.mapping, self.ctx, self.home = mapping, ctx, homeembed
self.index, self.buttons = 0, None

self.options, self.embeds = self.gen_embeds()
Expand Down Expand Up @@ -67,8 +67,8 @@ def find_index_from_select(self, value):

def get_cogs(self):
cogs = []
for cog in self.bot.extensions:
cogs.append(self.bot.get_cog(cog[5:len(cog)]))
for cog in self.mapping.keys():
cogs.append(cog)
return cogs

def gen_embeds(self):
Expand Down

0 comments on commit 6b4ed6f

Please sign in to comment.