Skip to content

Commit

Permalink
Respect des règles Codacy
Browse files Browse the repository at this point in the history
  • Loading branch information
S2P-KB committed Jul 12, 2024
1 parent 14b5a3a commit cfcd818
Show file tree
Hide file tree
Showing 8 changed files with 202 additions and 146 deletions.
61 changes: 0 additions & 61 deletions Discord-Bot-main/Bot/UR-Bot.py

This file was deleted.

86 changes: 86 additions & 0 deletions Discord-Bot-main/Bot/ur_bot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import DebugBot
import os
import discord
from discord.ext import commands

TOKEN = os.getenv('TOKEN')


class UrBot(commands.Bot):
"""
Classe initialisée à chaque lancement du BOT.
"""
async def on_ready(self):
"""
Éxécution d'une action au lancement du BOT.
"""
print('--- We have successfully logged in as {0.user}'.format(self))

async def on_message(self, message):
"""
Est une méthode qui permet :
- d'ignorer les messages envoyés par le BOT lui-même ;
- d'appeler une fonction de débogage pour chaque message entrant ;
- de traiter et d'exécuter les commandes des utilisateurs.
"""
if message.author == self.user:
return

await DebugBot.debug_on_message(message)

return await BOT.process_commands(message)


INTENT = discord.Intents.default()
INTENT.members = True
INTENT.messages = True
BOT = UrBot(command_prefix=DebugBot.event.BOT_PREFIX, intents=INTENT)
BOT.remove_command('help')


@BOT.command()
@commands.guild_only()
async def ping(ctx):
"""
Calcul de la latence de l'utilisateur (additionnée à celle des serveurs discord) et renvoie de cette dernière.
"""
latency = round(BOT.latency * 1000)
await ctx.send(f"Pong ! {latency}ms")


@BOT.command(name="help")
async def _help(ctx): # Ajouter un underscore évite l'erreur "Shadows built-in name 'help'", sans changer la commande.
"""
Appel d'une méthode quand la commande est reçue.
"""
await DebugBot.debug_on_help(ctx)


@BOT.command(name="prez")
async def prez(ctx):
"""
Appel d'une méthode quand la commande est reçue.
"""
await DebugBot.debug_on_prez(ctx)


# Fonction utilisée dans "reload_module".
@DebugBot.update_all_modules
async def reload_all_modules():
"""
Retourne 0.
"""
return 0


# Commande Discord pour recharger les modules
@BOT.command(aliases=['reload', 'rld'])
async def reload_module(ctx):
"""
Appel d'une méthode quand la commande est reçue.
"""
await reload_all_modules()
await ctx.channel.send("The scripts have been reloaded.")
return 0

BOT.run(TOKEN)
32 changes: 17 additions & 15 deletions bot/extends/base/base.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import os
import asyncio
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()

class Base(commands.Cog, name='Base'):
def __init__(self, bot: commands.Bot):
Expand All @@ -21,11 +19,11 @@ async def _ping(self, ctx):
await self._send_pong_response(ctx)

# Commande d'affichage des crédits
@commands.command(name="credits", help='affiche les crédits', aliases=['credit', 'c'])
@commands.command(name="credentials", help='affiche les crédits', aliases=['credit', 'c'])
async def _credits(self, ctx):
credits = await self._get_credits()
if credits:
await ctx.send(credits)
credentials = await self._get_credits()
if credentials:
await ctx.send(credentials)
else:
await ctx.send("Aucune information de crédits disponible.")

Expand Down Expand Up @@ -53,19 +51,20 @@ async def _send_pong_response(self, ctx):
)

# Récupère les informations de crédits depuis les fichiers
async def _get_credits(self):
credits = ""
@staticmethod
async def _get_credits():
credentials = ""
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
for directory in os.listdir(parent_dir):
credits_file_path = os.path.join(parent_dir, directory, 'credits.txt')
if os.path.exists(credits_file_path):
try:
with open(credits_file_path, 'r') as f:
credits += f.read() + '\n\n'
credentials += f.read() + '\n\n'
except Exception as e:
print(e)
if credits:
credits_lines = credits.splitlines()
if credentials:
credits_lines = credentials.splitlines()
formatted_credits = (
f"```ansi\n"
f"\x1b[1;34m{credits_lines[0]}\x1b[0m\n" # Titre en bleu foncé
Expand All @@ -79,7 +78,8 @@ async def _get_credits(self):
return None

# Récupère les informations de versions depuis les fichiers
async def _get_versions(self):
@staticmethod
async def _get_versions():
versions = ""
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
directory_names = {
Expand Down Expand Up @@ -138,18 +138,20 @@ def _get_commands_by_category(self):
return dict(sorted(commands_by_category.items()))

# Génère la liste de commandes pour une catégorie
def _get_command_list(self, commands):
def _get_command_list(self, instructions):
command_list = ""
for command in commands:
for command in instructions:
aliases = self._get_command_aliases(command)
msg = f' -- \x1b[2;36m{command.help}\x1b[0m' if command.help is not None else ''
command_list += f"\x1b[2;33m{command.name}\x1b[0m{aliases}{msg}\n"
return command_list

# Récupère les alias d'une commande
def _get_command_aliases(self, command):
@staticmethod
def _get_command_aliases(command):
return f'''{' ' + str(command.aliases).replace("'", "") if command.aliases != [] else ''}'''


# Fonction d'initialisation du Cog
async def setup(bot):
bot.remove_command('help')
Expand Down
27 changes: 14 additions & 13 deletions src/bot/cog_About.py → src/bot/cog_about.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
from discord.ext import commands
from bot import templates
from bot import _, strings
import urpy
from urpy.utils import *
from Bot_Base.src.bot import templates
from Bot_Base.src.urpy.my_commands import MyBot, MyCog
from Bot_Base.src.urpy.utils import *
import strings

#UR_Bot © 2020 by "Association Union des Rôlistes & co" is licensed under Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA)
#To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/
#Ask a derogation at [email protected]

# UR_Bot © 2020 by "Association Union des Rôlistes & co" is licensed under Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA)
# To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/
# Ask a derogation at [email protected]

class About(commands.Cog):
""" This cog contains commands used to get general information about the bot. """
__doc__ = strings.About_descr
__doc__ = strings.ABOUT_DESCR

def __init__(self, owner: urpy.MyBot):
""" Creates an about cog. """
def __init__(self, owner: MyBot):
""" Creates an 'about cog'. """
super(About, self).__init__()
self.bot = owner

@commands.command(brief=strings.version_brief, help=strings.version_help)
@commands.command(brief=strings.VERSION_BRIEF, help=strings.VERSION_HELP)
async def version(self, ctx: commands.Context):
""" Displays the version numbers. """
await self.send_info_msg(ctx)

@commands.command(brief=strings.credit_brief, help=strings.credit_help)
@commands.command(brief=strings.CREDIT_BRIEF, help=strings.CREDIT_HELP)
async def credit(self, ctx: commands.Context):
""" Displays the credits. """
await self.send_info_msg(ctx, with_credits=True)
Expand All @@ -36,7 +37,7 @@ async def send_info_msg(self, ctx, with_credits=False):
version=cog.get_version(),
credits=cog.get_credits() if with_credits else "")

for name, cog in self.bot.cogs.items() if isinstance(cog, urpy.MyCog)
for name, cog in self.bot.cogs.items() if isinstance(cog, MyCog)
)

# sends the message
Expand Down
File renamed without changes.
37 changes: 21 additions & 16 deletions src/bot/strings.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
from urpy.localization import lcl
"""
Ce module contient les chaînes de caractères utilisées pour les messages
et les descriptions envoyés par le bot Discord.
"""

bot_title = lcl('URbot - The discord bot of "l\'Union des Rôlistes"')
lang_brief = lcl('Switches to specified language')
lang_help = lcl(
from Bot_Base.src.urpy.localization import lcl

BOT_TITLE = lcl('URbot - The discord bot of "l\'Union des Rôlistes"')
LANG_BRIEF = lcl('Switches to specified language')
LANG_HELP = lcl(
"""\
Switches to specified language
Expand All @@ -11,15 +16,15 @@
- fr
- special-rp\
""")
done_brief = lcl('Confirms the current action')
done_help = lang_brief
edit_brief = lcl('Edits a message')
edit_help = edit_brief
cancel_brief = lcl('Cancels the current action')
cancel_help = cancel_brief
version_brief = lcl('Displays the version numbers')
version_help = version_brief
credit_brief = lcl('Displays the credits')
credit_help = credit_brief
About_descr = lcl('This category groups various commands to display general information about the bot.')
General_descr = lcl('This category groups various commands whose utility depends on the context.')
DONE_BRIEF = lcl('Confirms the current action')
DONE_HELP = LANG_BRIEF
EDIT_BRIEF = lcl('Edits a message')
EDIT_HELP = EDIT_BRIEF
CANCEL_BRIEF = lcl('Cancels the current action')
CANCEL_HELP = CANCEL_BRIEF
VERSION_BRIEF = lcl('Displays the version numbers')
VERSION_HELP = VERSION_BRIEF
CREDIT_BRIEF = lcl('Displays the credits')
CREDIT_HELP = CREDIT_BRIEF
ABOUT_DESCR = lcl('This category groups various commands to display general information about the bot.')
GENERAL_DESCR = lcl('This category groups various commands whose utility depends on the context.')
Loading

0 comments on commit cfcd818

Please sign in to comment.