diff --git a/cogs/admin.py b/cogs/admin.py index b30cd69..c43d3b3 100644 --- a/cogs/admin.py +++ b/cogs/admin.py @@ -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 @@ -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: @@ -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)) diff --git a/cogs/basic.py b/cogs/basic.py index 1d434fd..3b2632e 100644 --- a/cogs/basic.py +++ b/cogs/basic.py @@ -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 @@ -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 .\nType `help` to open a new session.\n\u200b", inline=False) + embed.add_field(name="Time remaining :", value=f"This help session will end .\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) @@ -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.") @@ -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() diff --git a/cogs/birthday.py b/cogs/birthday.py index a956906..02cade7 100644 --- a/cogs/birthday.py +++ b/cogs/birthday.py @@ -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 !" + message = f"Remembed this date because it's <@{user_id}>'s birthday !\nHe was born !" 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", @@ -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.""" @@ -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: @@ -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) diff --git a/cogs/croissants.py b/cogs/croissants.py index 08c550b..72e2521 100644 --- a/cogs/croissants.py +++ b/cogs/croissants.py @@ -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): @@ -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}") @@ -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) diff --git a/cogs/dad.py b/cogs/dad.py index 2cdf38c..c70c319 100644 --- a/cogs/dad.py +++ b/cogs/dad.py @@ -27,9 +27,9 @@ async def on_receive_message(self, message : discord.Message): name = im.group("name").strip() id_ = re.search("<@!?(?P\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)) diff --git a/cogs/errors.py b/cogs/errors.py index c83e14e..8a841c8 100644 --- a/cogs/errors.py +++ b/cogs/errors.py @@ -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 @@ -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='') #❌ - 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)) \ No newline at end of file diff --git a/cogs/fridaycake.py b/cogs/fridaycake.py index b49f217..fa6d0ca 100644 --- a/cogs/fridaycake.py +++ b/cogs/fridaycake.py @@ -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 diff --git a/cogs/info.py b/cogs/info.py index 641ff7f..34ff964 100644 --- a/cogs/info.py +++ b/cogs/info.py @@ -8,22 +8,22 @@ def statServer(guild): status = {} - must = ['members', 'bot', 'streaming', 'idle', 'dnd', 'online', 'offline', 'mobile'] + must = ["members", "bot", "streaming", "idle", "dnd", "online", "offline", "mobile"] for a in must: status[a] = 0 for member in guild: - status['members'] += 1 + status["members"] += 1 status[str(member.status)] += 1 - if member.is_on_mobile(): status['mobile'] += 1 - if member.bot: status['bot'] += 1 + if member.is_on_mobile(): status["mobile"] += 1 + if member.bot: status["bot"] += 1 if member.activity or member.activities: for activity in member.activities: if activity.type == discord.ActivityType.streaming: - status['streaming'] += 1 + status["streaming"] += 1 return status -class Info(commands.Cog, name="info", command_attrs=dict(hidden=False)): +class Info(commands.Cog, name="info"): """Info & statistics.""" def __init__(self, bot): self.bot = bot @@ -34,16 +34,16 @@ def help_custom(self): description = "Commands about additionals informations." return emoji, label, description - @commands.command(name='emojilist', aliases=['ce', 'el'], pass_context=True) + @commands.command(name="emojilist", aliases=["ce", "el"]) @commands.cooldown(1, 10, commands.BucketType.user) @commands.guild_only() async def getcustomemojis(self, ctx): """Return a list of each cutom emojis from the current server.""" - embed_list, embed = [], discord.Embed(title="Custom Emojis List ("+str(len(ctx.guild.emojis))+") :") + embed_list, embed = [], discord.Embed(title=f"Custom Emojis List ({len(ctx.guild.emojis)}) :") for i, emoji in enumerate(ctx.guild.emojis, start=1): if i == 0 : i += 1 - value = "`<:"+str(emoji.name)+":"+str(emoji.id)+">`" if not emoji.animated else "``" - embed.add_field(name=str(self.bot.get_emoji(emoji.id))+" - **:"+str(emoji.name)+":** - (*"+str(i)+"*)",value=value) + value = f"`<:{emoji.name}:{emoji.id}>`" if not emoji.animated else f"``" + embed.add_field(name=f"{self.bot.get_emoji(emoji.id)} - **:{emoji.name}:** - (*{i}*)",value=value) if len(embed.fields) == 25: embed_list.append(embed) embed = discord.Embed() @@ -52,38 +52,53 @@ async def getcustomemojis(self, ctx): for message in embed_list: await ctx.send(embed=message) - @commands.command(name='stat', aliases=['status','graph','gs','sg']) + @commands.command(name="stat", aliases=["status","graph","gs","sg"]) @commands.cooldown(1, 5, commands.BucketType.user) @commands.guild_only() async def stat(self, ctx): """Show a graphic pie about the server's members.""" plt.clf() ax, data, colors = plt.subplot(), statServer(ctx.guild.members), ["#747f8d","#f04747","#faa81a","#43b582"] - ax.pie([data['offline'], data['dnd'], data['idle'], data['online']], colors=colors, startangle=-40, wedgeprops=dict(width=0.5)) - leg = ax.legend(['Offline','dnd','idle','Online'],frameon=False, loc='lower center', ncol=5) + ax.pie([data["offline"], data["dnd"], data["idle"], data["online"]], colors=colors, startangle=-40, wedgeprops=dict(width=0.5)) + leg = ax.legend(["Offline","dnd","idle","Online"],frameon=False, loc="lower center", ncol=5) for color,text in zip(colors,leg.get_texts()): text.set_color(color) image_binary = io.BytesIO() plt.savefig(image_binary, transparent=True) image_binary.seek(0) - embed = discord.Embed(title="Current server stats ({})".format(data['members']),description="<:offline:698246924138184836> : **`{}`** (Offline)\n<:idle:698246924058361898> : **`{}`** (AFK)\n<:dnd:698246924528254986> : **`{}`** (dnd)\n<:online:698246924465340497> : **`{}`** (Online)\n<:streaming:699381397898395688> : **`{}`** (Streaming)\n<:phone:948279755248111756> : **`{}`** (on mobile)\n<:isbot:698250069165473852> : **`{}`** (Robot)".format(data['offline'], data['idle'], data['dnd'], data['online'], data['streaming'], data['mobile'], data['bot'])) - embed.set_image(url='attachment://stat.png') - embed.set_footer(text="Requested by : "+str(ctx.message.author)+" at "+str(time.strftime('%H:%M:%S')), icon_url=ctx.message.author.display_avatar.url) - await ctx.send(file=discord.File(fp=image_binary, filename='stat.png'), embed=embed) + embed = discord.Embed(title=f"Current server stats ({data['members']})",description=f"<:offline:698246924138184836> : **`{data['offline']}`** (Offline)\n<:idle:698246924058361898> : **`{data['idle']}`** (AFK)\n<:dnd:698246924528254986> : **`{data['dnd']}`** (dnd)\n<:online:698246924465340497> : **`{data['online']}`** (Online)\n<:streaming:699381397898395688> : **`{data['streaming']}`** (Streaming)\n<:phone:948279755248111756> : **`{data['mobile']}`** (on mobile)\n<:isbot:698250069165473852> : **`{data['bot']}`** (Robot)") + embed.set_image(url="attachment://stat.png") + embed.set_footer(text=f"Requested by : {ctx.message.author} at {time.strftime('%H:%M:%S')}", icon_url=ctx.message.author.display_avatar.url) + await ctx.send(file=discord.File(fp=image_binary, filename="stat.png"), embed=embed) - @commands.command(name='profilepicture', aliases=['pp']) + @commands.command(name="profilepicture", aliases=["pp"]) async def profilepicture(self, ctx, member : discord.Member = None): """Show the profile picture of the selected member.""" - author = member if member else ctx.message.author - await ctx.send(author.display_avatar.url) + if not member: member = ctx.author + await ctx.send(member.display_avatar.url) + + @commands.command(name="bannerpicture", aliases=["bp"]) + async def bannerpicture(self, ctx, member : discord.Member = None): + """Show the banner picture of the selected member.""" + if not member: member = ctx.author + user = await self.bot.fetch_user(member.id) + try: + await ctx.send(user.banner.url) + except: + await ctx.send("This user doesn't have a banner.") - @commands.command(name='lookup', aliases=['lk']) + @commands.command(name="lookup", aliases=["lk"]) @commands.cooldown(1, 5, commands.BucketType.user) @commands.guild_only() async def lookup(self, ctx, member: discord.Member = None): """Show few information about a discord Member""" if not member: member = ctx.author + + try: + user = await self.bot.fetch_user(member.id) + user_banner = user.banner.url + except: user_banner = None yes = "" no = "" @@ -104,8 +119,11 @@ async def lookup(self, ctx, member: discord.Member = None): embed.add_field(name="<:plus:948272417304883270> Account created at:", value=f"", inline=True) embed.add_field(name="<:join:948272122353057792> Joined the server at:", value=f"", inline=True) embed.set_thumbnail(url=member.display_avatar.url) + if user_banner: embed.set_image(url=user_banner) embed.set_footer(text=f"(The discord profile picture next to the 'lookup' text is your default profile picture.)\nRequested by : {ctx.message.author} at {time.strftime('%H:%M:%S')}", icon_url=ctx.message.author.display_avatar.url) await ctx.send(embed=embed) + + def setup(bot): bot.add_cog(Info(bot)) diff --git a/cogs/me.py b/cogs/me.py index b8aa9d0..f6b1874 100644 --- a/cogs/me.py +++ b/cogs/me.py @@ -2,7 +2,7 @@ from discord.ext import commands -class Me(commands.Cog, name="me", command_attrs=dict(hidden=False)): +class Me(commands.Cog, name="me"): """FridayCake's event commands.""" def __init__(self, bot): self.bot = bot @@ -16,35 +16,35 @@ def help_custom(self): description = "Set and show a brief description of yourself." return emoji, label, description - @commands.command(name='me', aliases=['description']) + @commands.command(name="me", aliases=["description"]) @commands.cooldown(1, 10, commands.BucketType.user) - async def me(self, ctx, *args:str): + async def me(self, ctx, *args: str): """Allows you to set or show a brief description of yourself.""" if len(args): try: text = " ".join(args).replace("'", "''") - if len(text) > self.max_lenght_me: raise commands.CommandError("The max-lenght of your *me* is set to: __"+str(self.max_lenght_me)+"__ (yours is "+str(len(text))+").") + if len(text) > self.max_lenght_me: raise commands.CommandError(f"The max-lenght of your *me* is set to: __{self.max_lenght_me}__ (yours is {len(text)}).") # Insert await self.bot.database.insert(self.me_data["table"], {"user_id": ctx.author.id, "user_me": text}) # Update - await self.bot.database.update(self.me_data["table"], "user_me", text, "user_id = "+str(ctx.author.id)) + await self.bot.database.update(self.me_data["table"], "user_me", text, f"user_id = {ctx.author.id}") await self.show_me_message(ctx, ctx.author) except Exception as e: raise commands.CommandError(str(e)) else: await self.show_me_message(ctx, ctx.author) - @commands.command(name='sme', aliases=['showdescription', 'showme']) + @commands.command(name="sme", aliases=["showdescription", "showme"]) @commands.cooldown(1, 5, commands.BucketType.user) - async def show_me(self, ctx, user:discord.Member = None): + async def show_me(self, ctx, user: discord.Member = None): """Allows you to show the description of other users.""" if not user: user = ctx.author await self.show_me_message(ctx, user) - async def show_me_message(self, ctx, user:discord.Member) -> None: + async def show_me_message(self, ctx, user: discord.Member) -> None: response = await self.bot.database.lookup(self.me_data["table"], "user_me", "user_id", str(user.id)) message = " ".join(response[0]) if len(response) else "No description provided.." - await ctx.send("• **"+ user.display_name + "** " + message) + await ctx.send(f"• **{user.display_name}** {message}") diff --git a/cogs/privatetextual.py b/cogs/privatetextual.py index ec1434b..3fcd81a 100644 --- a/cogs/privatetextual.py +++ b/cogs/privatetextual.py @@ -7,7 +7,7 @@ def text_to_allowed(input): for char in line: if not char in "abcdefghijklmnopqrstuvwxyz-_0123456789": forbidden.append(char) - char = char.replace(char,'') + char = char.replace(char, '') out += char return out, forbidden @@ -21,7 +21,7 @@ def get_created_roles(cont): return wrong_roles -class PrivateTextual(commands.Cog, name="privatetextual", command_attrs=dict(hidden=False)): +class PrivateTextual(commands.Cog, name="privatetextual"): """Create and manage private textual channels""" def __init__(self, bot): self.bot = bot @@ -32,7 +32,7 @@ def help_custom(self): description = "Add and edit textuals channels." return emoji, label, description - @commands.command(name='createprivate', aliases=['create', '+'], require_var_positional=True) + @commands.command(name="createprivate", aliases=["create", '+'], require_var_positional=True) @commands.cooldown(1, 10, commands.BucketType.user) async def create_private_channel(self, ctx, *members : discord.Member): """Create a private textual channel.""" @@ -54,11 +54,11 @@ async def create_private_channel(self, ctx, *members : discord.Member): await user.add_roles(role) mentions += " "+user.mention - await team_channel.send(str(team_channel.mention)+" was created by "+str(ctx.message.author.mention)+".") + await team_channel.send(f"{team_channel.mention} was created by {ctx.message.author.mention}.") await team_channel.send(mentions) - await ctx.message.add_reaction(emoji='') + await ctx.message.add_reaction(emoji="") - @commands.command(name='deleteprivate', aliases=['delete', '-']) + @commands.command(name="deleteprivate", aliases=["delete", '-']) async def delete_private_channel(self, ctx): """Delete your private textual channel.""" channel, roles = ctx.channel, get_created_roles(ctx) @@ -68,26 +68,26 @@ async def delete_private_channel(self, ctx): else: raise commands.CommandError("You can't delete a non-team channel.") - @commands.command(name='renameprivate', aliases=['rename', '_'], require_var_positional=True) + @commands.command(name="renameprivate", aliases=["rename", '_'], require_var_positional=True) async def rename_private_channel(self, ctx, custom_name : str): """Rename your private textual channel.""" channel, roles = ctx.channel, get_created_roles(ctx) normalize_cn, forbidden = text_to_allowed(custom_name) if '_' in channel.name and roles and len(normalize_cn) > 0: await channel.edit(name='_'+normalize_cn) - await ctx.message.add_reaction(emoji='') + await ctx.message.add_reaction(emoji="") elif not '_' in channel.name: raise commands.CommandError("You can't rename a non-team channel.") - if forbidden: raise commands.CommandError("You can't use `"+str(forbidden)+"` to rename a channel.") + if forbidden: raise commands.CommandError(f"You can't use `{forbidden}` to rename a channel.") - @commands.command(name='addprivate', aliases=['add', '>'], require_var_positional=True) + @commands.command(name="addprivate", aliases=["add", '>'], require_var_positional=True) async def addd_to_private_channel(self, ctx, *members : discord.Member): """Join a specified member to your team channel.""" roles = get_created_roles(ctx) for member in members: if not member.bot : await member.add_roles(roles[0]) else : raise commands.CommandError("You can't invite bots in your team.") - await ctx.message.add_reaction(emoji='') + await ctx.message.add_reaction(emoji="") def setup(bot): bot.add_cog(PrivateTextual(bot)) diff --git a/cogs/spotify.py b/cogs/spotify.py index e3a56ce..8472d10 100644 --- a/cogs/spotify.py +++ b/cogs/spotify.py @@ -3,18 +3,18 @@ from discord.ext import commands -class Spotify(commands.Cog, name="spotify", command_attrs=dict(hidden=False)): +class Spotify(commands.Cog, name="spotify"): """Show Spotify songs""" def __init__(self, bot): self.bot = bot def help_custom(self): - emoji = '<:spotify:880896591756656641>' + emoji = "<:spotify:880896591756656641>" label = "Spotify" description = "Spotify status commands." return emoji, label, description - @commands.command(name='spotify', aliases=['sy', 'sp', 'spy', 'spot']) + @commands.command(name="spotify", aliases=["sy", "sp", "spy", "spot"]) async def actual_calendar(self, ctx, user: discord.Member = None): """Show the current Spotify song.""" keeper = True @@ -22,12 +22,12 @@ async def actual_calendar(self, ctx, user: discord.Member = None): for activity in user.activities: if str(activity) == "Spotify": embed, keeper = discord.Embed(colour=activity.colour), False - embed.set_author(name="Spotify", url="https://open.spotify.com/track/"+str(activity.track_id), icon_url="https://toppng.com/uploads/thumbnail//spotify-logo-icon-transparent-icon-spotify-11553501653zkfre5mcur.png") + embed.set_author(name="Spotify", url=f"https://open.spotify.com/track/{activity.track_id}", icon_url="https://toppng.com/uploads/thumbnail//spotify-logo-icon-transparent-icon-spotify-11553501653zkfre5mcur.png") embed.add_field(name=activity.title, value=activity.artist, inline=False) embed.set_thumbnail(url=activity.album_cover_url) - embed.set_footer(text=str(activity.duration)[2:-7]+" | Requested by : "+str(ctx.message.author.name)+" at "+str(time.strftime('%H:%M:%S')), icon_url=ctx.message.author.display_avatar.url) + embed.set_footer(text=f"{str(activity.duration)[2:-7]} | Requested by : {ctx.message.author.name} at {time.strftime('%H:%M:%S')}", icon_url=ctx.message.author.display_avatar.url) await ctx.send(embed=embed) - if keeper: await ctx.send(str(user.name)+" is not currently listening to Spotify") + if keeper: await ctx.send(f"{user.name} is not currently listening to Spotify") def setup(bot): bot.add_cog(Spotify(bot)) diff --git a/cogs/status.py b/cogs/status.py index 75331ce..e8b2e23 100644 --- a/cogs/status.py +++ b/cogs/status.py @@ -3,7 +3,7 @@ from discord.ext import commands -class Status(commands.Cog, name="status", command_attrs=dict(hidden=True)): +class Status(commands.Cog, name="status"): """A loop to set the current status of the bot""" def __init__(self, bot): self.bot = bot @@ -22,7 +22,7 @@ async def loop_change_status(self): await self.bot.wait_until_ready() status_message, reset = ["?help", "?help basic", "?link"], 0 while not self.bot.is_closed(): - await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.streaming, name=status_message[reset], url='https://www.twitch.tv/warriormachine_'), status=discord.Status.dnd) + await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.streaming, name=status_message[reset], url="https://www.twitch.tv/warriormachine_"), status=discord.Status.dnd) await asyncio.sleep(10) if reset >= len(status_message)-1: reset = 0 else: reset += 1 diff --git a/cogs/traductor.py b/cogs/traductor.py index 0242bd8..b70ccb7 100644 --- a/cogs/traductor.py +++ b/cogs/traductor.py @@ -5,7 +5,7 @@ from discord.ext import commands from googletrans import Translator #pip install googletrans==4.0.0-rc1 -class Traductor(commands.Cog, name="traductor", command_attrs=dict(hidden=True)): +class Traductor(commands.Cog, name="traductor"): """A Cog to translate each non-English messages""" def __init__(self, bot): self.bot = bot @@ -16,7 +16,7 @@ def __init__(self, bot): description = "Informations about the Traductor." return emoji, label, description""" - @commands.Cog.listener('on_message') + @commands.Cog.listener("on_message") async def on_receive_message(self, message: discord.Message): convert_emoji = '🔀' converted_emoji = '⤵' @@ -30,8 +30,8 @@ async def on_receive_message(self, message: discord.Message): try: analysis: str = Translator().detect(content).lang - if not analysis == 'en': - translated = Translator().translate(content, dest='en', src=analysis).text + if not analysis == "en": + translated = Translator().translate(content, dest="en", src=analysis).text flag_emoji = str(chr(127365 + (ord(analysis[0]))))+str(chr(127365 + (ord(analysis[1])))) for regex in [mention_regex, channel_regex, emote_regex]: @@ -47,7 +47,7 @@ async def on_receive_message(self, message: discord.Message): def check(reaction, user) -> bool: return not user.bot and reaction.message.id == message.id and reaction.emoji == convert_emoji - await self.bot.wait_for('reaction_add', timeout=25, check=check) + await self.bot.wait_for("reaction_add", timeout=25, check=check) except asyncio.exceptions.TimeoutError: await message.clear_reaction(convert_emoji) except: pass diff --git a/cogs/usefull.py b/cogs/usefull.py index f6c1558..3835e7f 100644 --- a/cogs/usefull.py +++ b/cogs/usefull.py @@ -1,6 +1,6 @@ from discord.ext import commands -class Usefull(commands.Cog, name="usefull", command_attrs=dict(hidden=False)): +class Usefull(commands.Cog, name="usefull"): """Usefull commands for Devs & more""" def __init__(self, bot): self.bot = bot @@ -11,12 +11,12 @@ def help_custom(self): description = "Usefull commands." return emoji, label, description - @commands.command(name='strawpoll', aliases=['straw', 'stp', 'sond', 'sondage'], pass_context=True) + @commands.command(name="strawpoll", aliases=["straw", "stp", "sond", "sondage"], require_var_positional=True) async def strawpool(self, ctx, *, context): """Ask a sondage, and add 2 reactions to vote with your community.""" crossmark, checkmark = self.bot.get_emoji(842800737221607474), self.bot.get_emoji(842800730049871892) await ctx.message.delete() - message = await ctx.send("__*" + ctx.message.author.mention + "*__ : " + context) + message = await ctx.send(f"__*{ctx.message.author.mention}*__ : {context}") await message.add_reaction(emoji=checkmark) await message.add_reaction(emoji=crossmark) diff --git a/cogs/views.py b/cogs/views.py index c477b0c..0d25c8c 100644 --- a/cogs/views.py +++ b/cogs/views.py @@ -16,44 +16,44 @@ def help_custom(self): description = "Demo : New discord features." return emoji, label, description - @commands.command(name='bool') + @commands.command(name="bool") async def boo(self, ctx): """Discover buttons feature with this command.""" view = bool.View(flabel="Agree", slabel="Disagree", sstyle=discord.ButtonStyle.red, emojis = True, source=ctx) await ctx.send("Buttons demo right there !", view=view) - @commands.command(name='dropdown') + @commands.command(name="dropdown") async def dro(self, ctx): """Discover select menu feature with this command.""" options = [ - {'label':"Mandarin", 'description':"你好", 'emoji':"🇨🇳"}, - {'label':"Spanish", 'description':"Buenos dias", 'emoji':"🇪🇸"}, - {'label':"English", 'description':"Hello", 'emoji':"🇬🇧"}, - {'label':"Hindi", 'description':"नमस्ते", 'emoji':"🇮🇳"}, - {'label':"Arabic", 'description':"صباح الخير", 'emoji':"🇸🇦"}, - {'label':"Potuguese", 'description':"Olá", 'emoji':"🇵🇹"}, - {'label':"Bengali", 'description':"হ্যালো", 'emoji':"🇧🇩"}, - {'label':"Russian", 'description':"Привет", 'emoji':"🇷🇺"}, - {'label':"Japanese", 'description':"こんにちは", 'emoji':"🇯🇵"}, - {'label':"Turkish", 'description':"Merhaba", 'emoji':"🇹🇷"}, - {'label':"Korean", 'description':"안녕하십니까", 'emoji':"🇰🇷"}, - {'label':"French", 'description':"Bonjour", 'emoji':"🇫🇷"}, - {'label':"German", 'description':"Hallo", 'emoji':"🇩🇪"}, - {'label':"Vietnamese", 'description':"xin chào", 'emoji':"🇻🇳"}, - {'label':"Italian", 'description':"Buongiorno", 'emoji':"🇮🇹"}, - {'label':"Polish", 'description':"dzień dobry", 'emoji':"🇵🇱"}, - {'label':"Romanian", 'description':"Buna ziua", 'emoji':"🇷🇴"}, - {'label':"Dutch", 'description':"Hallo", 'emoji':"🇳🇱"}, - {'label':"Thai", 'description':"สวัสดี", 'emoji':"🇹🇭"}, - {'label':"Nepali", 'description':"नमस्कार", 'emoji':"🇳🇵"}, - {'label':"Greek", 'description':"γεια σας", 'emoji':"🇬🇷"}, - {'label':"Czech", 'description':"Ahoj", 'emoji':"🇨🇿"}, - {'label':"Persian", 'description':"سلام", 'emoji':"🇮🇷"} + {"label":"Mandarin", "description":"你好", "emoji":"🇨🇳"}, + {"label":"Spanish", "description":"Buenos dias", "emoji":"🇪🇸"}, + {"label":"English", "description":"Hello", "emoji":"🇬🇧"}, + {"label":"Hindi", "description":"नमस्ते", "emoji":"🇮🇳"}, + {"label":"Arabic", "description":"صباح الخير", "emoji":"🇸🇦"}, + {"label":"Potuguese", "description":"Olá", "emoji":"🇵🇹"}, + {"label":"Bengali", "description":"হ্যালো", "emoji":"🇧🇩"}, + {"label":"Russian", "description":"Привет", "emoji":"🇷🇺"}, + {"label":"Japanese", "description":"こんにちは", "emoji":"🇯🇵"}, + {"label":"Turkish", "description":"Merhaba", "emoji":"🇹🇷"}, + {"label":"Korean", "description":"안녕하십니까", "emoji":"🇰🇷"}, + {"label":"French", "description":"Bonjour", "emoji":"🇫🇷"}, + {"label":"German", "description":"Hallo", "emoji":"🇩🇪"}, + {"label":"Vietnamese", "description":"xin chào", "emoji":"🇻🇳"}, + {"label":"Italian", "description":"Buongiorno", "emoji":"🇮🇹"}, + {"label":"Polish", "description":"dzień dobry", "emoji":"🇵🇱"}, + {"label":"Romanian", "description":"Buna ziua", "emoji":"🇷🇴"}, + {"label":"Dutch", "description":"Hallo", "emoji":"🇳🇱"}, + {"label":"Thai", "description":"สวัสดี", "emoji":"🇹🇭"}, + {"label":"Nepali", "description":"नमस्कार", "emoji":"🇳🇵"}, + {"label":"Greek", "description":"γεια σας", "emoji":"🇬🇷"}, + {"label":"Czech", "description":"Ahoj", "emoji":"🇨🇿"}, + {"label":"Persian", "description":"سلام", "emoji":"🇮🇷"} ] view = dropdown.View(options=options, placeholder="Select your language(s)", min_val=1, max_val=9, source=ctx) await ctx.send("Dropdown demo right there !", view=view) - @commands.command(name='link') + @commands.command(name="link") async def lin(self, ctx): """Discover button link with this feature.""" view = link.View(label="Source code on Github", url="https://github.com/PaulMarisOUMary/Algosup-Discord") diff --git a/views/bool.py b/views/bool.py index 4f76430..960c261 100644 --- a/views/bool.py +++ b/views/bool.py @@ -18,7 +18,7 @@ async def bool_check(self, value, interaction): self.value = value await interaction.response.defer() await interaction.delete_original_message() - message = "✅ Confirmed"if self.value else "❌ Canceled" + message = "✅ Confirmed" if self.value else "❌ Canceled" await self.source.reply(message) else: await interaction.response.send_message("❌ Hey it's not your session !", ephemeral=True) diff --git a/views/dropdown.py b/views/dropdown.py index db8a3b1..789959b 100644 --- a/views/dropdown.py +++ b/views/dropdown.py @@ -7,10 +7,10 @@ def __init__(self, options, source, placeholder : str, min_val : int, max_val : choices = [] for option in options: - if not option['emoji']: - choices.append(discord.SelectOption(label=option['label'], description=option['description'])) + if not option["emoji"]: + choices.append(discord.SelectOption(label=option["label"], description=option["description"])) else: - choices.append(discord.SelectOption(label=option['label'], description=option['description'], emoji=option['emoji'])) + choices.append(discord.SelectOption(label=option["label"], description=option["description"], emoji=option["emoji"])) super().__init__(placeholder = placeholder, min_values = min_val, max_values = max_val, options = choices) @@ -18,7 +18,7 @@ async def callback(self, interaction: discord.Interaction): if self.invoker == interaction.user: message = "Selected languages : " for value in self.values: - message += '`'+value+"` " + message += f"`{value}` " await interaction.response.defer() await interaction.delete_original_message() await self.source.reply(message) diff --git a/views/fridaycake.py b/views/fridaycake.py index 7b064db..4cf3bea 100644 --- a/views/fridaycake.py +++ b/views/fridaycake.py @@ -10,10 +10,10 @@ def __init__(self, options, source, main, embed, placeholder : str, min_val : in choices = [] for option in options: - if not option['emoji']: - choices.append(discord.SelectOption(label=option['label'], description=option['description'])) + if not option["emoji"]: + choices.append(discord.SelectOption(label=option["label"], description=option["description"])) else: - choices.append(discord.SelectOption(label=option['label'], description=option['description'], emoji=option['emoji'])) + choices.append(discord.SelectOption(label=option["label"], description=option["description"], emoji=option["emoji"])) super().__init__(placeholder = placeholder, min_values = min_val, max_values = max_val, options = choices) @@ -25,7 +25,7 @@ async def callback(self, interaction: discord.Interaction): elif self.values[0] == "Home": await interaction.response.edit_message(embed=self.embed, view=self.view) else: - embed = discord.Embed(color=0xf7346b, title = "⚙️ Fridaycake · Can I trust you ?", description = "`The main concept of the algorithm explained.`\n\u200b", url='https://github.com/PaulMarisOUMary/Algosup-Discord') + embed = discord.Embed(color=0xf7346b, title = "⚙️ Fridaycake · Can I trust you ?", description = "`The main concept of the algorithm explained.`\n\u200b", url="https://github.com/PaulMarisOUMary/Algosup-Discord") embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/332696002144501760/800791318200188998/fridaycake.png") embed.add_field(name="How do you get the list of participants ?", value=f"There is a file named `participants.dat` in the `data/` folder.\nInside I have arranged each volunteers by promotion and then by alphabetical order.\n\u200b", inline=False) embed.add_field(name="How am I mixed up ?", value="I'm using a __seed__ to shuffle randomly the list of participants.\nThe point is, it doesn't matter on which computer or when the calculation is performed, it always return the same result as long we doesn't change the seed (it means also you can try at home it will return exactly the same result as Algobot).\n\u200b", inline=False) diff --git a/views/help.py b/views/help.py index 55e0701..f5f22e6 100644 --- a/views/help.py +++ b/views/help.py @@ -3,7 +3,7 @@ class Dropdown(discord.ui.Select): def __init__(self, ctx, options): - super().__init__(placeholder='Select a category...', min_values=1, max_values=1, options=options) + super().__init__(placeholder="Select a category...", min_values=1, max_values=1, options=options) self.invoker = ctx.author async def callback(self, interaction: discord.Interaction): @@ -79,13 +79,13 @@ def gen_embeds(self): if "help_custom" in dir(cog): emoji, label, description = cog.help_custom() options.append(discord.SelectOption(label=label, description=description, emoji=emoji)) - embed = discord.Embed(title = str(emoji)+" Help · "+str(label),description='`'+str(cog.__doc__)+'`', url='https://github.com/PaulMarisOUMary/Algosup-Discord') + embed = discord.Embed(title = f"{emoji} Help · {label}",description=f"`{cog.__doc__}`", url="https://github.com/PaulMarisOUMary/Algosup-Discord") embed.set_footer(text="Remind : Hooks such as <> must not be used when executing commands.", icon_url=self.ctx.message.author.display_avatar.url) for command in 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) embeds.append(embed) return options, embeds