From d0f1ccaabb8f5e627260f9840ec79d2ea24aa39b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Pag=C3=A9s?= <55240756+clement-pages@users.noreply.github.com> Date: Sun, 10 Dec 2023 21:29:45 +0100 Subject: [PATCH] remove: remove fun features (#114) * remove: remove fun features These features were not used anymore, and complicated the code. * fix: fix undefined variables error --- sunbot/SunController.py | 75 ----------------------------------------- sunbot/SunServer.py | 22 ++++-------- sunbot/SunUser.py | 38 ++++++--------------- 3 files changed, 17 insertions(+), 118 deletions(-) diff --git a/sunbot/SunController.py b/sunbot/SunController.py index a9f0ca6..e6dfcd5 100644 --- a/sunbot/SunController.py +++ b/sunbot/SunController.py @@ -144,39 +144,6 @@ async def on_message(self, message: discord.Message) -> None: logging.info("A message was received on server n°%d", msg_srv.id) # Commands must be processed first await self.bot.process_commands(message) - # Enable eastereggs only on "fun" servers: - if msg_srv.fun: - # Randomly add a reaction to the message: - await self.__add_reaction(message) - lowered_msg = message.content.lower() - if lowered_msg in ["tête de pomme", "tete de pomme", "#tetedepomme"]: - msg_srv.appleHead += 1 - # If the message was repeted three consecutive times, send the gif: - if msg_srv.appleHead == 3: - msg_srv.appleHead = 0 - logging.info( - "Invocation of apple head on server %s!", message.guild.name) - embed2send = discord.Embed(title="Et tu savais qu'à Jean Jaurès", - color=0xff0000) - apple_head_gif = discord.File( - f"{sunbot.GIF_REPERTORY_PATH}{sunbot.APPLE_HEAD_GIF_NAME}") - embed2send.set_image( - url=f"attachment://{sunbot.APPLE_HEAD_GIF_NAME}") - await message.channel.send(embed=embed2send, file=apple_head_gif) - # Other types of messages: - else: - msg_srv.appleHead = 0 - # Easter eggs: - if "me foutre au sol" in lowered_msg and np.random.uniform() > 0.5: - await message.reply("Tu sais, il y a des gens qui disaient ça \ - et qui ont fini ingénieurs chez Boeing. \ - Donc tu as du potentiel \U0001f31e !") - elif lowered_msg == "sinus": - await message.channel.send("Tangente") - elif lowered_msg in ["patrick", "patou", "patoche", "pata", "patrikou"] and np.random.uniform() > 0.25: - pass # TODO add the list of gifs - elif "kernel is dead" in lowered_msg: - pass # TODO add corresponding list of gifs @commands.Cog().listener() async def on_shut_down(self, signame : str): @@ -200,25 +167,6 @@ async def on_shut_down(self, signame : str): # COMMANDS PART # ==================================================================================== - # TODO Replace this classic command by it slash counterpart: - @np.deprecate_with_doc - async def set_emoji(self, ctx: commands.Context, usr_id: int, emoji: str, emoji_freq: float): - """Set an emoji for specified user that the bot will used to randomly - react to a message from this user - ## Parameters: - - `ctx`: command call context - - `usr_id`: id of the user for which the emoji will be set - - `emoji`: emoji to set - - `emoji_freq`: probability that the bot reacts to an user message using - specified emoji - ## Return value: - not applicable - """ - try: - self.usr_dict[usr_id].emoji = emoji - except KeyError: - pass - @app_commands.command(name="disconnect", description="[admin] Deconnecte le bot de discord") @app_commands.describe(debug="1=mode debug on, 0=mode debut off") @app_commands.guilds(discord.Object(id=726063782606143618)) @@ -442,29 +390,6 @@ async def __save_data(self): srv.save_srv_data() await self.daily_weather_handler.save_locations_subscribers() - async def __add_reaction(self, msg: discord.Message) -> None: - """Private method to add a reaction to the specified message published - by an user, according to the user probability for this action - ## Parameters: - * `msg` : discord message that triggered this method - ## Return value: - not applicable - """ - # Add a reaction only if the user is not a bot: - if not msg.author.bot: - # Get the user that sent the message: - user: SunUser = self.usr_dict[msg.author.id] - # If an emoji is define for this user and probability is under freqEmoji proba: - if user.emoji != "" and np.random.uniform() <= user.freqEmoji: - try: - await msg.add_reaction(user.emoji) - except discord.errors.NotFound: - logging.error( - "Reaction cannot be added because the message was deleted or the emoji %s does not exist", user.emoji) - except TypeError: - logging.error( - "Emoji %s, set for the user n°%dis not in a valid emoji format", user.emoji, user.id) - # TODO Remove this unused private method: @np.deprecate_with_doc async def __delete_command_msg(self, ctx: commands.Context) -> None: diff --git a/sunbot/SunServer.py b/sunbot/SunServer.py index 8cb8517..2d1abd3 100644 --- a/sunbot/SunServer.py +++ b/sunbot/SunServer.py @@ -15,22 +15,20 @@ class SunServer: """This class defines a discord server (guild) where the bot is present. A - discord server is a set of sun users (discord users) and have webhooks that + discord server is a set of sun users (discord users) and has webhooks that allow the bot to send message without a context. It is identified by an ID - that corresponds to its ID on Discord. There are two sorts of server : normal - and 'fun' server.""" + that corresponds to its ID on Discord. + """ srv_backup_path = "" - def __init__(self, id : int, fun : bool = False) -> None: + def __init__(self, id : int) -> None: """Constructor of this class ## Parameter : * `id`: discord ID for the server to create. This ID is unique on Discord""" object.__setattr__(self, "id", id) - object.__setattr__(self, "fun", fun) object.__setattr__(self, "usersDict", {}) #In this dict users' ID are the keys and users the values object.__setattr__(self, "webhooksDict", {}) #In this dict links to the webhook are the keys and state of this webhooks the values - object.__setattr__(self, "appleHead", 0) #If backup directory for servers does not already exist, create it: if SunServer.srv_backup_path == "": @@ -46,7 +44,6 @@ def __init__(self, id : int, fun : bool = False) -> None: try: serverData = json.load(serverFile) object.__setattr__(self, "webhooksDict", serverData["webhooksDict"]) - object.__setattr__(self, "fun", serverData["fun"]) except json.decoder.JSONDecodeError: logging.error(f"An error occured when retrieving data for server n°{id}") #Else, create a new server with a new corresponding backup file: @@ -57,18 +54,11 @@ def __init__(self, id : int, fun : bool = False) -> None: def __setattr__(self, __name: str, __value) -> None: """Special method used to update object fields. Here, redefinition - prohibites all modifications excepted fun status and appleHead + prohibites all modifications. ## Parameters: * `__name`: name of the field to update * `__value`: new value for the field to update""" - if __name == "fun" : - object.__setattr__(self, __name, __value) - self.save_srv_data() - logging.info(f"Fun status for server {self.id} was updated. New value : {self.fun}") - if __name == "appleHead": - object.__setattr__(self, __name, __value) - else: - logging.error("Server attributes cannot directly modified") + logging.error("Server attributes cannot be directly modified") def __eq__(self, __o: object) -> bool: diff --git a/sunbot/SunUser.py b/sunbot/SunUser.py index 2ed1170..770f24a 100644 --- a/sunbot/SunUser.py +++ b/sunbot/SunUser.py @@ -14,35 +14,27 @@ class SunUser: - """This class represents a SunBot user. Each user has an ID that allows to - identify it in discord API. This can be used to send it a message for example. - In this class, an user is also defined by its name. + """This class represents a SunBot user. Each user has an ID that allows to + identify it in discord API. This can be used to send it a message for example. """ usr_backup_path = "" - def __init__(self, id : int, emoji : str = "", freqEmoji : float = 0.5, favLocation : str = "Toulouse", mp : bool = False) -> None: - """Constructor for this class. A SunBot user is defined by its Discord ID. - Other informations can be provided in arguments, such as an emoji that is - used to react to a message sent by this user, if the user authorize private - message from the bot, or a specific favorite location for weather notifications. - Each instance of this class is associated to a backup file. The link - between the user and its backup file is done thanks to the user ID + def __init__(self, id : int, favLocation : str = "Toulouse", mp : bool = False) -> None: + """Constructor for this class. A SunBot user is defined by its Discord ID. + Other informations can be provided in arguments, such as if the user authorize private + message from the bot, or a specific favorite location for weather notifications. + Each instance of this class is associated to a backup file. The link + between the user and its backup file is done thanks to the user ID (so ID is defined as a constant and cannot be modified). ## Parameters: * `id`: discord identifiant of the SunBot user to create - * `emoji`: optional, string code corresponding to the emoji that will be - used to react to messages sent by the user - * `freqEmoji`: optional, float corresponding to frequency at which an emoji - is added to a message from the user - * `favLocation`: optional, string indicating the favourite location name + * `favLocation`: optional, string indicating the favourite location name for user to create. Default to Toulouse - * `mp`: optional, boolean indicating if the user allows private messages + * `mp`: optional, boolean indicating if the user allows private messages from the SunBot. Default value is `False` """ object.__setattr__(self, "id", id) - object.__setattr__(self, "emoji", emoji) - object.__setattr__(self, "freqEmoji", freqEmoji) object.__setattr__(self, "favLocation", favLocation) object.__setattr__(self, "mp", mp) @@ -61,8 +53,6 @@ def __init__(self, id : int, emoji : str = "", freqEmoji : float = 0.5, favLocat with open(f"{self.usr_backup_path}{id}.json", "r", encoding="UTF-8") as userFile: try: userData = json.load(userFile) - object.__setattr__(self, "emoji", userData["emoji"]) - object.__setattr__(self, "freqEmoji", userData["freqEmoji"]) object.__setattr__(self, "favLocation", userData["favLocation"]) object.__setattr__(self, "mp", userData["mp"]) except json.decoder.JSONDecodeError: @@ -83,12 +73,6 @@ def __setattr__(self, __name: str, __value) -> None: #User id cannot be modified: if __name == "id": logging.error("User identifiant cannot be modified. Abort") - return - #Value for emoji frequency must be in [0, 1] interval: - if __name == "freqEmoji": - if __value < 0 or __value > 1: - raise ValueError - object.__setattr__(self, __name, __value) else: object.__setattr__(self, __name, __value) self.save_usr_data() @@ -98,7 +82,7 @@ def __setattr__(self, __name: str, __value) -> None: def __eq__(self, __o: object) -> bool: """Test if the specified object `o` is equal to this instance - ## Parameter: + ## Parameter: * `__o`: object to compare to this instance ## Return value: `True` if the specified object and this user are equal, `False` otherwise"""