Skip to content

Commit

Permalink
Merge pull request #30 from PaulMarisOUMary/small-fixes
Browse files Browse the repository at this point in the history
Small fixes
  • Loading branch information
PaulMarisOUMary authored Mar 18, 2022
2 parents 46b2461 + 6aa5ad0 commit c4f9b53
Show file tree
Hide file tree
Showing 19 changed files with 166 additions and 139 deletions.
13 changes: 8 additions & 5 deletions cogs/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from discord.ext import commands
from importlib import reload

class Admin(commands.Cog, name="admin", command_attrs=dict(hidden=True)):
class Admin(commands.Cog, name="admin"):
"""Admin commands, you probably don't have the permission to use them."""
def __init__(self, bot):
self.bot = bot
Expand Down Expand Up @@ -124,10 +124,10 @@ async def delete_channel(self, ctx, channel_name):
while channel:
await channel.delete()
channel = discord.utils.get(ctx.guild.channels, name=channel_name)
await ctx.send("All channels named `"+str(channel_name)+"` as been succesfuly deleted")

@commands.command(name="changeprefix", aliases=["cp"])
@commands.is_owner()
await ctx.send(f"All channels named `{channel_name}` as been succesfuly deleted")
@commands.command(name="changeprefix", aliases=["cp"], require_var_positional=True)
@commands.has_guild_permissions(administrator=True)
async def change_guild_prefix(self, ctx, new_prefix):
"""Change the guild prefix."""
try:
Expand All @@ -141,5 +141,8 @@ async def change_guild_prefix(self, ctx, new_prefix):
await ctx.send(f":warning: Prefix changed to `{new_prefix}`")
except Exception as e:
await ctx.send(f"Error: {e}")



def setup(bot):
bot.add_cog(Admin(bot))
30 changes: 15 additions & 15 deletions cogs/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from datetime import datetime, timedelta
from views import help as vhelp

class Basic(commands.Cog, name="basic", command_attrs=dict(hidden=False)):
class Basic(commands.Cog, name="basic"):
"""Basic commands, like help, ping, ..."""
def __init__(self, bot):
self.bot = bot
Expand All @@ -17,16 +17,16 @@ def help_custom(self):
description = "Basic commands, like help, ping, etc.."
return emoji, label, description

@commands.command(name='help', aliases=['?', 'h', 'commands'])
async def help(self, ctx, *input):
@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']
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="This help session will end <t:"+str(close_in)+":R>.\nType `help` to open a new session.\n\u200b", inline=False)
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)
Expand All @@ -47,21 +47,21 @@ async def help(self, ctx, *input):

if search_cog:
if "help_custom" in dir(search_cog):
emoji, label, description = search_cog.help_custom()
embed = discord.Embed(title = str(emoji)+" Help · "+str(label),description='`'+str(search_cog.__doc__)+'`', url='https://github.com/PaulMarisOUMary/Algosup-Discord')
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 += " <"+str(param)+">"
embed.add_field(name=str(command.name)+str(params), value=str(command.help)+"\n\u200b", inline=False)
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, description = cog.help_custom()
embed = discord.Embed(title = str(emoji)+" Help · "+str(label)+" : "+str(search_command.name), description="**Command** : "+str(search_command.name)+"\n"+str(search_command.help), url='https://github.com/PaulMarisOUMary/Algosup-Discord')
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 += " <"+str(param)+">"
embed.add_field(name="Usage", value=str(search_command.name)+str(params), inline=False)
embed.add_field(name="Aliases", value='`'+str(search_command.aliases)+'`')
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.")

Expand All @@ -71,7 +71,7 @@ async def help(self, ctx, *input):
elif len(input) > 1:
raise commands.CommandError("Too many arguments.")

@commands.command(name='ping', pass_context=True)
@commands.command(name="ping")
async def ping(self, ctx):
"""Show latency in seconds & milliseconds"""
before = time.monotonic()
Expand Down
10 changes: 5 additions & 5 deletions cogs/birthday.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ async def daily_birthday(self):
if user_birth.month == datetime.now().month and user_birth.day == datetime.now().day:
timestamp = round(time.mktime(user_birth.timetuple()))

message = f"Remembed this date because it's <@{str(user_id)}>'s birthday !\nHe was born <t:{timestamp}:R> !"
message = f"Remembed this date because it's <@{user_id}>'s birthday !\nHe was born <t:{timestamp}:R> !"
images = [
"https://sayingimages.com/wp-content/uploads/funny-birthday-and-believe-me-memes.jpg",
"https://i.kym-cdn.com/photos/images/newsfeed/001/988/649/1e8.jpg",
Expand All @@ -53,7 +53,7 @@ async def before_daily_birthday(self):
await self.bot.wait_until_ready()
while self.bot.database.connector is None: await asyncio.sleep(0.01) #wait_for initBirthday

@commands.command(name='birthday', aliases=['bd', 'setbirthday', 'setbirth', 'birth'])
@commands.command(name="birthday", aliases=["bd", "setbirthday", "setbirth", "birth"], require_var_positional=True)
@commands.cooldown(1, 10, commands.BucketType.user)
async def birthday(self, ctx, date: str = None):
"""Allows you to set/show your birthday."""
Expand All @@ -64,7 +64,7 @@ async def birthday(self, ctx, date: str = None):
# Insert
await self.bot.database.insert(self.birthday_data["table"], {"user_id": ctx.author.id, "user_birth": dataDate})
# Update
await self.bot.database.update(self.birthday_data["table"], "user_birth", dataDate, "user_id = "+str(ctx.author.id))
await self.bot.database.update(self.birthday_data["table"], "user_birth", dataDate, f"user_id = {ctx.author.id}")

await self.show_birthday_message(ctx, ctx.author)
except ValueError:
Expand All @@ -74,9 +74,9 @@ async def birthday(self, ctx, date: str = None):
else:
await self.show_birthday(ctx, ctx.author)

@commands.command(name='showbirthday', aliases=['showbirth', 'sbd'])
@commands.command(name="showbirthday", aliases=["showbirth", "sbd"])
@commands.cooldown(1, 5, commands.BucketType.user)
async def show_birthday(self, ctx, user:discord.Member = None):
async def show_birthday(self, ctx, user: discord.Member = None):
"""Allows you to show the birthday of other users."""
if not user: user = ctx.author
await self.show_birthday_message(ctx, user)
Expand Down
10 changes: 5 additions & 5 deletions cogs/croissants.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ def __init__(self, bot):
self.croissants_data = self.bot.database_data["croissants"]

def help_custom(self):
emoji = '🥐'
emoji = self.EMOJI
label = "Croissants"
description = "For when someone left their computer unlocked."
return emoji, label, description

@commands.Cog.listener('on_message')
@commands.Cog.listener("on_message")
async def on_receive_message(self, message : discord.Message):
if not message.author.bot and self.REGEX.match(message.content):
if not self.__is_on_cooldown(message.author):
Expand All @@ -48,12 +48,12 @@ async def croissants_rank(self, ctx):

async def __send_croissants(self, message) -> None:
answer_message = await message.reply(
content=f'{message.author.mention} took out the credit card! ' + self.EMOJI,
content=f"{message.author.mention} took out the credit card! {self.EMOJI}",
file=self.__get_screenshot(message.author, message.content)
)

count = await self.__increment_croissants_counter(message.author.id)
await answer_message.edit(content=f"{message.author.mention} took out the credit card ! And this is the `{count}` time, he's so generous! " + self.EMOJI)
await answer_message.edit(content=f"{message.author.mention} took out the credit card ! And this is the `{count}` time, he's so generous! {self.EMOJI}")

async def __increment_croissants_counter(self, user_id : int) -> int:
exist = await self.bot.database.exist(self.croissants_data["table"], "*", f"user_id={user_id}")
Expand All @@ -80,7 +80,7 @@ def __get_screenshot(self, author : discord.Member, content : str) -> discord.Fi
pfp_content = Image.open(BytesIO(requests.get(author.display_avatar.url).content))
images_sequence, duration_array = [], []
for frame in ImageSequence.Iterator(pfp_content):
try: duration_array.append(frame.info['duration'])
try: duration_array.append(frame.info["duration"])
except: duration_array.append(0)

img = Image.new("RGBA", size=(500, 100), color=bg_color)
Expand Down
4 changes: 2 additions & 2 deletions cogs/dad.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ async def on_receive_message(self, message : discord.Message):
name = im.group("name").strip()
id_ = re.search("<@!?(?P<id>\d{17,19})>", name) # https://github.com/discordjs/discord.js/blob/2f6f365098cbab397cda124711c4bb08da850a17/src/structures/MessageMentions.js#L221
if id_ and int(id_.group("id")) != author_id:
await channel.send("No you are " + message.author.mention)
await channel.send(f"No you are {message.author.mention}")
else:
await channel.send("Hi " + name + ", I'm " + self.bot.user.mention)
await channel.send(f"Hi {name}, I'm {self.bot.user.mention}")

def setup(bot):
bot.add_cog(Dad(bot))
26 changes: 16 additions & 10 deletions cogs/errors.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from discord.ext import commands

class Errors(commands.Cog, name="errors", command_attrs=dict(hidden=True)):
class Errors(commands.Cog, name="errors"):
"""Errors handler"""
def __init__(self, bot):
self.bot = bot
Expand All @@ -11,33 +11,39 @@ def __init__(self, bot):
description = "A custom errors handler."
return emoji, label, description"""

@commands.Cog.listener('on_command_error')
@commands.Cog.listener("on_error")
async def get_error(self, event, *args, **kwargs):
"""Error handler"""
print(f"! Unexpected Internal Error: (event) {event}, (args) {args}, (kwargs) {kwargs}.")

@commands.Cog.listener("on_command_error")
async def get_command_error(self, ctx, error):
"""Command Error handler"""
try:
message = await ctx.send("🕳️ There is an error.")
if isinstance(error, commands.errors.CommandNotFound):
await message.edit("🕳️ Command `"+str(error).split(' ')[1]+"` not found !")
await message.edit(f"🕳️ Command `{str(error).split(' ')[1]}` not found !")
elif isinstance(error, commands.errors.NotOwner):
await message.edit("🕳️ You must own this bot to run this command.")
elif isinstance(error, commands.errors.NoPrivateMessage):
await message.edit("🕳️ This command cannot be used in a private message.")
elif isinstance(error, commands.errors.CommandOnCooldown):
await message.edit("🕳️ Command is on cooldown, wait `"+str(error).split(' ')[7]+"` !")
await message.edit(f"🕳️ Command is on cooldown, wait `{str(error).split(' ')[7]}` !")
elif isinstance(error, commands.errors.MissingRequiredArgument):
command, params = ctx.command, ""
for param in command.clean_params: params += " {"+str(param)+"}"
await message.edit("🕳️ Something is missing. `?"+str(command)+str(params)+'`')
for param in command.clean_params: params += " {"+str(param)+'}'
await message.edit(f"🕳️ Something is missing. `?{command}{params}`")
elif isinstance(error, commands.errors.MemberNotFound):
await message.edit("🕳️ Member `"+str(error).split(' ')[1]+"` not found ! Don't hesitate to ping the requested member.")
await message.edit(f"🕳️ Member `{str(error).split(' ')[1]}` not found ! Don't hesitate to ping the requested member.")
elif isinstance(error, commands.errors.MissingPermissions):
await message.edit("🕳️ This command require more permissions.")
elif isinstance(error, commands.errors.DisabledCommand):
await message.edit("🕳️ This command is disabled.")
else:
await message.edit("🕳️ `"+str(type(error).__name__)+"` : "+str(error))
await message.edit(f"🕳️ `{type(error).__name__}` : {error}")
await ctx.message.add_reaction(emoji='<a:crossmark:842800737221607474>') #❌
except:
print("! Cog errors get_command_error : "+str(type(error).__name__)+" : "+str(error))
except Exception as e:
print(f"! Cogs.errors get_command_error : {type(error).__name__} : {error}\n! Internal Error : {e}\n")

def setup(bot):
bot.add_cog(Errors(bot))
2 changes: 1 addition & 1 deletion cogs/fridaycake.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def all(self, ctx):
for participants, _date in zip(self.participants, get_dates(start, holidays, len(self.participants))):
string = "`"
for _id, names in participants:
string += names + "` & `" if not int(_id) == author.id else names + "` [ᐊ](https://github.com/PaulMarisOUMary/Algosup-Discord) & `"
string += f"{names}` & `" if not int(_id) == author.id else f"{names}` [ᐊ](https://github.com/PaulMarisOUMary/Algosup-Discord) & `"
embed.add_field(name=f"Friday {_date.strftime('%d %B, %Y')}", value=f"~~{string[0:-4]}~~" if date.today() >= _date else f"{string[0:-4]}", inline=False)
return embed

Expand Down
Loading

0 comments on commit c4f9b53

Please sign in to comment.