From 568aa99270e132f621ef516f7ff91a01fa6016df Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 27 Mar 2021 00:02:01 +0100 Subject: [PATCH 001/286] =?UTF-8?q?am=C3=A9lioration=20lisibilit=C3=A9=20c?= =?UTF-8?q?itation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main.py b/src/main.py index a851d14..d84bbf3 100644 --- a/src/main.py +++ b/src/main.py @@ -155,16 +155,15 @@ async def on_message(message): edit = "" if msgID.edited_at: date_edit = str(msgID.edited_at.astimezone(timezone('Europe/Paris')))[:-13].replace('-', '/').split() - edit = f"(Dernier edit : {date_edit[0][8:]}/{date_edit[0][5:-3]}/{date_edit[0][:4]} à {date_edit[1]})" - message_1 = f"Date : {date_1[0][8:]}/{date_1[0][5:-3]}/{date_1[0][:4]} à {date_1[1]} {edit}" + edit = f" et modifié le {date_edit[0][8:]}/{date_edit[0][5:-3]}/{date_edit[0][:4]} à {date_edit[1]})" + messageDuBas = f"Posté le {date_1[0][8:]}/{date_1[0][5:-3]}/{date_1[0][:4]} à {date_1[1]}{edit}" date_2 = str(message.created_at.astimezone(timezone('Europe/Paris')))[:-13].replace('-', '/').split() date_2 = f"{date_2[0][8:]}/{date_2[0][5:-3]}/{date_2[0][:4]} à {date_2[1]}" - cite = "" if auteur == "Auteur": - cite = f"\nCité par {user_or_nick(message.author)} le {date_2}" - embed.set_footer(icon_url = icon_url, text = f"{message_1}{cite}") + messageDuBas = messageDuBas + f"\nCité par {user_or_nick(message.author)} le {date_2}" + embed.set_footer(icon_url = icon_url, text = messageDuBas) if message.content == linkURL.replace(' ',''): await message.channel.send(embed = embed) await message.delete() From 69445cd6a06c24aab2169e2f45337a37ca5940bf Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 27 Mar 2021 00:08:53 +0100 Subject: [PATCH 002/286] update timezone : using env variable --- README.md | 5 +++-- docker-compose.yml | 1 + src/cogs/utils.py | 6 +++--- src/main.py | 10 +++++----- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 9b47931..75371fd 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ [![Github forks](https://img.shields.io/github/forks/Confrerie-du-Kassoulait/KassouBot?label=Github%20Forks&style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/network) ## __Setting up__ -You have to replace `TOKEN_DISCORD`, `TOKEN_GENIUS`, `TOKEN_REDDIT_CLIENT_ID`, `TOKEN_REDDIT_CLIENT_SECRET` and `TOKEN_REDDIT_USER_AGENT` with your desired values. +You have to replace `TOKEN_DISCORD`, `TOKEN_GENIUS`, `TOKEN_REDDIT_CLIENT_ID`, `TOKEN_REDDIT_CLIENT_SECRET`, `TOKEN_REDDIT_USER_AGENT` and [`TIMEZONE`](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) with your desired values. With a [docker-compose](https://github.com/Confrerie-du-Kassoulait/KassouBot/blob/master/docker-compose.yml) or in command line: ``` @@ -18,7 +18,8 @@ docker run -d \ --TOKEN_GENIUS="yourValue" \ --TOKEN_REDDIT_CLIENT_ID="yourValue" \ --TOKEN_REDDIT_CLIENT_SECRET="yourValue" \ - --TOKEN_REDDIT_USER_AGENT="yourValue" + --TOKEN_REDDIT_USER_AGENT="yourValue" \ + --TIMEZONE="yourTimezone" ``` To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and here are the instructions: ![instructions](https://i.imgur.com/tEzYKDA.png) diff --git a/docker-compose.yml b/docker-compose.yml index b958fad..e438608 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,4 +9,5 @@ services: - TOKEN_REDDIT_CLIENT_ID=your-reddit-client-id - TOKEN_REDDIT_CLIENT_SECRET=your-reddit-client-secret - TOKEN_REDDIT_USER_AGENT=your-reddit-user-agent + - TIMEZONE=your-timezone # https://en.wikipedia.org/wiki/List_of_tz_database_time_zones restart: unless-stopped diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 9dcd53c..3c13886 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -1,4 +1,4 @@ -import discord, pytz, time +import discord, pytz, time, os from discord.ext import commands from random import randint, shuffle from datetime import datetime @@ -246,14 +246,14 @@ class Utils(commands.Cog): embed.add_field(name = "ID", value = user[0].id) - value = str(user[0].created_at.astimezone(timezone('Europe/Paris')))[:-13].replace('-', '/').split() + value = str(user[0].created_at.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').split() embed.add_field(name = "Compte créé le", value = f"{value[0][8:]}/{value[0][5:-3]}/{value[0][:4]} à {value[1]}") embed.add_field(name = "Âge du compte", value = self._age_layout(self._get_age(user[0].created_at))) embed.add_field(name = "Mention", value = user[0].mention) - value = str(user[0].joined_at.astimezone(timezone('Europe/Paris')))[:-13].replace('-', '/').split() + value = str(user[0].joined_at.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').split() embed.add_field(name = "Serveur rejoint le", value = f"{value[0][8:]}/{value[0][5:-3]}/{value[0][:4]} à {value[1]}") embed.add_field(name = "Est sur le serveur depuis", value = self._age_layout(self._get_age(user[0].joined_at))) diff --git a/src/main.py b/src/main.py index d84bbf3..4f20cf7 100644 --- a/src/main.py +++ b/src/main.py @@ -151,14 +151,14 @@ async def on_message(message): embed.set_author(name = "Citation", icon_url = msgID.author.avatar_url) icon_url = message.author.avatar_url - date_1 = str(msgID.created_at.astimezone(timezone('Europe/Paris')))[:-13].replace('-', '/').split() + date_1 = str(msgID.created_at.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').split() edit = "" if msgID.edited_at: - date_edit = str(msgID.edited_at.astimezone(timezone('Europe/Paris')))[:-13].replace('-', '/').split() + date_edit = str(msgID.edited_at.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').split() edit = f" et modifié le {date_edit[0][8:]}/{date_edit[0][5:-3]}/{date_edit[0][:4]} à {date_edit[1]})" messageDuBas = f"Posté le {date_1[0][8:]}/{date_1[0][5:-3]}/{date_1[0][:4]} à {date_1[1]}{edit}" - date_2 = str(message.created_at.astimezone(timezone('Europe/Paris')))[:-13].replace('-', '/').split() + date_2 = str(message.created_at.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').split() date_2 = f"{date_2[0][8:]}/{date_2[0][5:-3]}/{date_2[0][:4]} à {date_2[1]}" if auteur == "Auteur": @@ -196,9 +196,9 @@ async def on_message_delete(message): embed.set_author(name = user_or_nick(message.author), icon_url = message.author.avatar_url) if not user_suppressed: - embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {str(message.created_at.astimezone(timezone('Europe/Paris')))[:-13].replace('-', '/').replace(' ', ' à ')}\nSupprimé le {datetime.now(pytz.timezone('Europe/Paris')).strftime('%d/%m/%Y à %H:%M:%S')}") + embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {str(message.created_at.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').replace(' ', ' à ')}\nSupprimé le {datetime.now(pytz.timezone(os.environ['TIMEZONE'])).strftime('%d/%m/%Y à %H:%M:%S')}") else: - embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {str(message.created_at.astimezone(timezone('Europe/Paris')))[:-13].replace('-', '/').replace(' ', ' à ')}\nSupprimé par {user_or_nick(user_suppressed)} le {datetime.now(pytz.timezone('Europe/Paris')).strftime('%d/%m/%Y à %H:%M:%S')}") + embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {str(message.created_at.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').replace(' ', ' à ')}\nSupprimé par {user_or_nick(user_suppressed)} le {datetime.now(pytz.timezone(os.environ['TIMEZONE'])).strftime('%d/%m/%Y à %H:%M:%S')}") await channel.send(embed = embed) # ne fonctionne pas quand un message a été supprimé avant que le bot ai démarré From 22b5924c290a82ebe4e9a9cbb843d6813893cc46 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 28 Mar 2021 01:38:28 +0100 Subject: [PATCH 003/286] grouping timezone format in one command --- src/main.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/main.py b/src/main.py index 4f20cf7..e92e17e 100644 --- a/src/main.py +++ b/src/main.py @@ -151,14 +151,14 @@ async def on_message(message): embed.set_author(name = "Citation", icon_url = msgID.author.avatar_url) icon_url = message.author.avatar_url - date_1 = str(msgID.created_at.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').split() + date_1 = goodTimezone(msgID.created_at, 0) edit = "" if msgID.edited_at: - date_edit = str(msgID.edited_at.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').split() + date_edit = goodTimezone(msgID.edited_at, 0) edit = f" et modifié le {date_edit[0][8:]}/{date_edit[0][5:-3]}/{date_edit[0][:4]} à {date_edit[1]})" messageDuBas = f"Posté le {date_1[0][8:]}/{date_1[0][5:-3]}/{date_1[0][:4]} à {date_1[1]}{edit}" - date_2 = str(message.created_at.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').split() + date_2 = goodTimezone(message.created_at, 0) date_2 = f"{date_2[0][8:]}/{date_2[0][5:-3]}/{date_2[0][:4]} à {date_2[1]}" if auteur == "Auteur": @@ -196,9 +196,9 @@ async def on_message_delete(message): embed.set_author(name = user_or_nick(message.author), icon_url = message.author.avatar_url) if not user_suppressed: - embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {str(message.created_at.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').replace(' ', ' à ')}\nSupprimé le {datetime.now(pytz.timezone(os.environ['TIMEZONE'])).strftime('%d/%m/%Y à %H:%M:%S')}") + embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1)}\nSupprimé le {datetime.now(pytz.timezone(os.environ['TIMEZONE'])).strftime('%d/%m/%Y à %H:%M:%S')}") else: - embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {str(message.created_at.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').replace(' ', ' à ')}\nSupprimé par {user_or_nick(user_suppressed)} le {datetime.now(pytz.timezone(os.environ['TIMEZONE'])).strftime('%d/%m/%Y à %H:%M:%S')}") + embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1)}\nSupprimé par {user_or_nick(user_suppressed)} le {datetime.now(pytz.timezone(os.environ['TIMEZONE'])).strftime('%d/%m/%Y à %H:%M:%S')}") await channel.send(embed = embed) # ne fonctionne pas quand un message a été supprimé avant que le bot ai démarré @@ -210,4 +210,10 @@ def user_or_nick(user): else: return f"{user.name}#{user.discriminator}" +def goodTimezone(date, type): + if type == 0: + return str(date.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').split() + elif type == 1: + return str(date.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').replace(' ', ' à ') + client.run(os.environ['TOKEN_DISCORD']) From bd8b256e6d63f4aa1d717ba39445295ae729b465 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 28 Mar 2021 01:41:54 +0100 Subject: [PATCH 004/286] fix issue #2 --- src/main.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.py b/src/main.py index e92e17e..a178da4 100644 --- a/src/main.py +++ b/src/main.py @@ -212,8 +212,8 @@ def user_or_nick(user): def goodTimezone(date, type): if type == 0: - return str(date.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').split() + return str(pytz.timezone(os.environ['TIMEZONE']).fromutc(date))[:-13].replace('-', '/').split() elif type == 1: - return str(date.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').replace(' ', ' à ') + return str(pytz.timezone(os.environ['TIMEZONE']).fromutc(date))[:-13].replace('-', '/').replace(' ', ' à ') client.run(os.environ['TOKEN_DISCORD']) From 500d3efb3b81556e75dfe06859a0574bd123e23f Mon Sep 17 00:00:00 2001 From: Mylloon <29067904+Mylloon@users.noreply.github.com> Date: Sun, 28 Mar 2021 01:46:26 +0100 Subject: [PATCH 005/286] Create LICENSE --- LICENSE | 201 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 201 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. From c50fd001dd51d0f2c9445ffc72fc762d38ad75fe Mon Sep 17 00:00:00 2001 From: Mylloon <29067904+Mylloon@users.noreply.github.com> Date: Sun, 28 Mar 2021 01:47:31 +0100 Subject: [PATCH 006/286] Create CODE_OF_CONDUCT.md --- CODE_OF_CONDUCT.md | 128 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 CODE_OF_CONDUCT.md diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..18c9147 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. From a9907eb6d44ecab1ac245a5bb23a794bfdbbeb49 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 28 Mar 2021 01:56:38 +0100 Subject: [PATCH 007/286] removing useless files for the docker --- .dockerignore | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .dockerignore diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..33e952b --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +README.md +LICENSE +CODE_OF_CONDUCT.md +.gitignore From 3ff644c5de4fe05939b33cb08f12d805b6bb4c26 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 28 Mar 2021 14:41:34 +0200 Subject: [PATCH 008/286] adding uppercase --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 75371fd..1132453 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ With a [docker-compose](https://github.com/Confrerie-du-Kassoulait/KassouBot/blo ``` docker run -d \ - --name="kassoubot" \ + --name="KassouBot" \ mylloon/kassoubot \ --TOKEN_DISCORD="yourValue" \ --TOKEN_GENIUS="yourValue" \ From 733027e8c61373f0d89c746a27e76ebc808c73dc Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 1 Apr 2021 16:01:43 +0200 Subject: [PATCH 009/286] update map amongus --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 3c13886..33c392e 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -225,7 +225,7 @@ class Utils(commands.Cog): await ctx.send(embed = embed) await ctx.message.add_reaction(emoji = '✅') elif map.lower() in self._map_list_among_us("airship"): - image = "https://i.imgur.com/CYbPlQ6.png" + image = "https://i.imgur.com/cm8Wogw.png" embed = discord.Embed(title = f"Map Airship d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") embed.set_image(url = image) await ctx.send(embed = embed) From e10e81963f03351bf1b6a5a2fa6afb11c27580ee Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 1 Apr 2021 16:08:27 +0200 Subject: [PATCH 010/286] bump to v1.1 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1132453..fd7a0cf 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Bot developed with [discord.py](https://github.com/Rapptz/discord.py) (rewrite) - FRENCH -[![Version](https://img.shields.io/badge/version-1.0-green?style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/releases/latest) +[![Version](https://img.shields.io/badge/version-1.1-green?style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/releases/latest) [![Docker Stars](https://img.shields.io/docker/stars/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/repository/docker/mylloon/kassoubot) [![Docker Pulls](https://img.shields.io/docker/pulls/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/repository/docker/mylloon/kassoubot) [![Github stars](https://img.shields.io/github/stars/Confrerie-du-Kassoulait/kassoubot?label=Github%20Stars&style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/stargazers) From e4efc8db1ccec4b83edc56b67636006f8a037301 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 1 Apr 2021 16:09:58 +0200 Subject: [PATCH 011/286] bump to 1.2 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fd7a0cf..016374d 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Bot developed with [discord.py](https://github.com/Rapptz/discord.py) (rewrite) - FRENCH -[![Version](https://img.shields.io/badge/version-1.1-green?style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/releases/latest) +[![Version](https://img.shields.io/badge/version-1.2-green?style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/releases/latest) [![Docker Stars](https://img.shields.io/docker/stars/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/repository/docker/mylloon/kassoubot) [![Docker Pulls](https://img.shields.io/docker/pulls/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/repository/docker/mylloon/kassoubot) [![Github stars](https://img.shields.io/github/stars/Confrerie-du-Kassoulait/kassoubot?label=Github%20Stars&style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/stargazers) From 1331189048bd0aeacae7f9e046e4c02d7c8c5455 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 1 Apr 2021 16:22:31 +0200 Subject: [PATCH 012/286] fix docker links --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fd7a0cf..d584f66 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # Bot developed with [discord.py](https://github.com/Rapptz/discord.py) (rewrite) - FRENCH [![Version](https://img.shields.io/badge/version-1.1-green?style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/releases/latest) -[![Docker Stars](https://img.shields.io/docker/stars/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/repository/docker/mylloon/kassoubot) -[![Docker Pulls](https://img.shields.io/docker/pulls/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/repository/docker/mylloon/kassoubot) +[![Docker Stars](https://img.shields.io/docker/stars/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/r/mylloon/kassoubot) +[![Docker Pulls](https://img.shields.io/docker/pulls/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/r/mylloon/kassoubot) [![Github stars](https://img.shields.io/github/stars/Confrerie-du-Kassoulait/kassoubot?label=Github%20Stars&style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/stargazers) [![Github forks](https://img.shields.io/github/forks/Confrerie-du-Kassoulait/KassouBot?label=Github%20Forks&style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/network) ## __Setting up__ From f62a4b37a666ba23cddad6ae57c3ddc873452d1b Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 7 May 2021 16:38:16 +0200 Subject: [PATCH 013/286] =?UTF-8?q?ajout=20commande=20avis=20+=20fix=20pro?= =?UTF-8?q?bleme=20r=C3=A9cup=C3=A9ration=20ID=20lors=20d'un=20copi=C3=A9?= =?UTF-8?q?=20coll=C3=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/utils.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 33c392e..0bc7e09 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -337,7 +337,34 @@ class Utils(commands.Cog): else: return await ctx.send(f'Désolé, mais il manque des arguments : `.sondage "" "" "" ""`') def user_or_nick(self, user): + if user == None: + return "Utilisateur inconnu" # Mauvais copié/collé -> changement d'ID if user.nick: return f"{user.nick} ({user.name}#{user.discriminator})" else: return f"{user.name}#{user.discriminator}" + + @commands.command(name='avis', aliases=['vote']) + async def _avis(self, ctx, *args): + """Demande un avis.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .avis "[Titre]" "" """ + args = list(args) + if len(args) > 2 or len(args) == 0: + return await ctx.send("Désolé, la syntaxe est mauvaise.") + else: + if len(args) == 1: + titre = "Nouveau vote" + else: + titre = args[0].replace("<@!", "").replace(">", "").replace("<@", "") + for findedId in re.findall(r'\d+', titre): + associatedId = self.user_or_nick(ctx.author.guild.get_member(int(findedId))) + try: + titre = titre.replace(findedId, associatedId) + except: + pass + args = args[1:] + embed = discord.Embed(title = titre, description = f"```{args[0]}```", color = discord.Colour.random()).set_footer(text = self.user_or_nick(ctx.author), icon_url = ctx.author.avatar_url) + message = await ctx.send(embed = embed) + reactions = ['✅', '🤷', '❌'] + for i in reactions: + await message.add_reaction(emoji = i) + return await ctx.message.delete() From 099cf2cc0641c440b16631e7cfcbd0be89b7b1f4 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 7 May 2021 16:44:47 +0200 Subject: [PATCH 014/286] adding custom prefix --- README.md | 7 ++++--- docker-compose.yml | 1 + src/main.py | 3 ++- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 8dc34c7..140bbce 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ [![Github forks](https://img.shields.io/github/forks/Confrerie-du-Kassoulait/KassouBot?label=Github%20Forks&style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/network) ## __Setting up__ -You have to replace `TOKEN_DISCORD`, `TOKEN_GENIUS`, `TOKEN_REDDIT_CLIENT_ID`, `TOKEN_REDDIT_CLIENT_SECRET`, `TOKEN_REDDIT_USER_AGENT` and [`TIMEZONE`](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) with your desired values. +You have to replace `TOKEN_DISCORD`, `PREFIX`, `TOKEN_GENIUS`, `TOKEN_REDDIT_CLIENT_ID`, `TOKEN_REDDIT_CLIENT_SECRET`, `TOKEN_REDDIT_USER_AGENT` and [`TIMEZONE`](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) with your desired values. With a [docker-compose](https://github.com/Confrerie-du-Kassoulait/KassouBot/blob/master/docker-compose.yml) or in command line: ``` @@ -19,7 +19,8 @@ docker run -d \ --TOKEN_REDDIT_CLIENT_ID="yourValue" \ --TOKEN_REDDIT_CLIENT_SECRET="yourValue" \ --TOKEN_REDDIT_USER_AGENT="yourValue" \ - --TIMEZONE="yourTimezone" + --TIMEZONE="yourTimezone" \ + --PREFIX="." ``` To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and here are the instructions: ![instructions](https://i.imgur.com/tEzYKDA.png) @@ -34,4 +35,4 @@ To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and ## __Features__ -Everything is explained by doing `.help` +Everything is explained by doing the `help` command. diff --git a/docker-compose.yml b/docker-compose.yml index e438608..ec26ed5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -10,4 +10,5 @@ services: - TOKEN_REDDIT_CLIENT_SECRET=your-reddit-client-secret - TOKEN_REDDIT_USER_AGENT=your-reddit-user-agent - TIMEZONE=your-timezone # https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + - PREFIX=your-prefix restart: unless-stopped diff --git a/src/main.py b/src/main.py index a178da4..9098819 100644 --- a/src/main.py +++ b/src/main.py @@ -5,8 +5,9 @@ from discord.ext import commands from random import choice from datetime import datetime from pytz import timezone +customPrefix = os.environ['PREFIX'] -client = commands.Bot(command_prefix = ".", case_insensitive = True, intents = discord.Intents.all()) +client = commands.Bot(command_prefix = customPrefix, case_insensitive = True, intents = discord.Intents.all()) print("Chargement des extensions & librairie...") client.load_extension("cogs.help") From 05d8c40cb7ad4e5df88cf4a3c34572e490d4d769 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 7 May 2021 16:48:40 +0200 Subject: [PATCH 015/286] adding the right prefix in the rich presence --- src/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.py b/src/main.py index 9098819..45b0c5a 100644 --- a/src/main.py +++ b/src/main.py @@ -24,7 +24,7 @@ async def on_connect(): @client.event async def on_ready(): - await client.change_presence(status = discord.Status.online, activity = discord.Activity(name = ".help", type = discord.ActivityType.playing)) + await client.change_presence(status = discord.Status.online, activity = discord.Activity(name = f"{customPrefix}help", type = discord.ActivityType.playing)) print("Bot prêt.") channel = client.get_channel(742564480050790512) await channel.send("Le bot a bien démarré.") From 316e95760b1c6bfbdac25af34eaf7ddc83a145a3 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 8 May 2021 01:48:06 +0200 Subject: [PATCH 016/286] changement sondage/avis try:except: --- src/cogs/utils.py | 45 +++++++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 0bc7e09..05e780d 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -249,14 +249,14 @@ class Utils(commands.Cog): value = str(user[0].created_at.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').split() embed.add_field(name = "Compte créé le", value = f"{value[0][8:]}/{value[0][5:-3]}/{value[0][:4]} à {value[1]}") - embed.add_field(name = "Âge du compte", value = self._age_layout(self._get_age(user[0].created_at))) + embed.add_field(name = "Âge du compte", value = self._ageLayout(self._get_age(user[0].created_at))) embed.add_field(name = "Mention", value = user[0].mention) value = str(user[0].joined_at.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').split() embed.add_field(name = "Serveur rejoint le", value = f"{value[0][8:]}/{value[0][5:-3]}/{value[0][:4]} à {value[1]}") - embed.add_field(name = "Est sur le serveur depuis", value = self._age_layout(self._get_age(user[0].joined_at))) + embed.add_field(name = "Est sur le serveur depuis", value = self._ageLayout(self._get_age(user[0].joined_at))) await ctx.message.add_reaction(emoji = '✅') return await ctx.send(embed = embed) await ctx.send("Tu mentionnes trop d'utilisateurs : `.whois [@Membre]`") @@ -269,7 +269,7 @@ class Utils(commands.Cog): minutes = (hours - int(hours)) * 60 seconds = (minutes - int(minutes)) * 60 return (int(years), int(months), int(days), int(hours), int(minutes), int(seconds)) - def _age_layout(self, tuple): + def _ageLayout(self, tuple): time = {} time[0], time[1], time[2], time[3], time[4], time[5] = "an", "mois", "jour", "heure", "minute", "seconde" for i in range(len(tuple)): @@ -291,6 +291,22 @@ class Utils(commands.Cog): for i in affichage: message = message + f", {tuple[i]} {time[i]}" return message[2:] + + def _userOrNick(self, user): + if user == None: + return "Utilisateur inconnu" # Mauvais copié/collé -> changement d'ID + if user.nick: + return f"{user.nick} ({user.name}#{user.discriminator})" + else: + return f"{user.name}#{user.discriminator}" + + def _cleanUser(self, ctx, stringMessage, stringID, option = 0): + associatedId = self._userOrNick(ctx.author.guild.get_member(int(stringID))) + try: + stringMessage = stringMessage.replace(stringID, associatedId) + except: + pass + return stringMessage @commands.command(name='sondage') async def _sondage(self, ctx, *args): @@ -299,11 +315,7 @@ class Utils(commands.Cog): if len(args) > 2: question = args[0].replace("<@!", "").replace(">", "").replace("<@", "") for i in re.findall(r'\d+', question): - ii = self.user_or_nick(ctx.author.guild.get_member(int(i))) - try: - question = question.replace(i, ii) - except: - pass + question = self._cleanUser(ctx, question, i) propositions = args[1:] if len(propositions) <= 20: message = "" @@ -327,7 +339,7 @@ class Utils(commands.Cog): shuffle(emojis_chosen) for i in range(len(args[1:])): message += f"{emojis_chosen[i]} -> {propositions[i]}\n" - embed = discord.Embed(title = question, description = message,color = discord.Colour.random()).set_footer(text = self.user_or_nick(ctx.author), icon_url = ctx.author.avatar_url) + embed = discord.Embed(title = question, description = message,color = discord.Colour.random()).set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) sondage = await ctx.send(embed = embed) for i in range(len(args[1:])): await sondage.add_reaction(emoji = emojis_chosen[i]) @@ -336,13 +348,6 @@ class Utils(commands.Cog): return await ctx.send(f"Désolé, mais tu as mis trop de possibilités (maximum : 20)") else: return await ctx.send(f'Désolé, mais il manque des arguments : `.sondage "" "" "" ""`') - def user_or_nick(self, user): - if user == None: - return "Utilisateur inconnu" # Mauvais copié/collé -> changement d'ID - if user.nick: - return f"{user.nick} ({user.name}#{user.discriminator})" - else: - return f"{user.name}#{user.discriminator}" @commands.command(name='avis', aliases=['vote']) async def _avis(self, ctx, *args): @@ -356,13 +361,9 @@ class Utils(commands.Cog): else: titre = args[0].replace("<@!", "").replace(">", "").replace("<@", "") for findedId in re.findall(r'\d+', titre): - associatedId = self.user_or_nick(ctx.author.guild.get_member(int(findedId))) - try: - titre = titre.replace(findedId, associatedId) - except: - pass + titre = self._cleanUser(ctx, titre, findedId) args = args[1:] - embed = discord.Embed(title = titre, description = f"```{args[0]}```", color = discord.Colour.random()).set_footer(text = self.user_or_nick(ctx.author), icon_url = ctx.author.avatar_url) + embed = discord.Embed(title = titre, description = f"```{args[0]}```", color = discord.Colour.random()).set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) message = await ctx.send(embed = embed) reactions = ['✅', '🤷', '❌'] for i in reactions: From c1131967b6cea87a513c8607861571ec7bbb7718 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 8 May 2021 02:22:22 +0200 Subject: [PATCH 017/286] fix mention in vote --- src/cogs/utils.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 05e780d..5f2b986 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -300,10 +300,11 @@ class Utils(commands.Cog): else: return f"{user.name}#{user.discriminator}" - def _cleanUser(self, ctx, stringMessage, stringID, option = 0): - associatedId = self._userOrNick(ctx.author.guild.get_member(int(stringID))) + def _cleanUser(self, ctx, stringMessage, stringID): + stringMessage = stringMessage.replace("<@!", "").replace(">", "").replace("<@", "") + associatedID = self._userOrNick(ctx.author.guild.get_member(int(stringID))) try: - stringMessage = stringMessage.replace(stringID, associatedId) + stringMessage = stringMessage.replace(stringID, associatedID) except: pass return stringMessage @@ -313,7 +314,7 @@ class Utils(commands.Cog): """Fais un sondage.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .sondage "" "" "" "" """ args = list(args) if len(args) > 2: - question = args[0].replace("<@!", "").replace(">", "").replace("<@", "") + question = args[0] for i in re.findall(r'\d+', question): question = self._cleanUser(ctx, question, i) propositions = args[1:] @@ -339,7 +340,7 @@ class Utils(commands.Cog): shuffle(emojis_chosen) for i in range(len(args[1:])): message += f"{emojis_chosen[i]} -> {propositions[i]}\n" - embed = discord.Embed(title = question, description = message,color = discord.Colour.random()).set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) + embed = discord.Embed(title = question, description = message, color = discord.Colour.random()).set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) sondage = await ctx.send(embed = embed) for i in range(len(args[1:])): await sondage.add_reaction(emoji = emojis_chosen[i]) @@ -351,7 +352,7 @@ class Utils(commands.Cog): @commands.command(name='avis', aliases=['vote']) async def _avis(self, ctx, *args): - """Demande un avis.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .avis "[Titre]" "" """ + """Demande un avis.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .avis/vote "[Titre]" "" """ args = list(args) if len(args) > 2 or len(args) == 0: return await ctx.send("Désolé, la syntaxe est mauvaise.") @@ -359,11 +360,14 @@ class Utils(commands.Cog): if len(args) == 1: titre = "Nouveau vote" else: - titre = args[0].replace("<@!", "").replace(">", "").replace("<@", "") + titre = args[0] for findedId in re.findall(r'\d+', titre): titre = self._cleanUser(ctx, titre, findedId) args = args[1:] - embed = discord.Embed(title = titre, description = f"```{args[0]}```", color = discord.Colour.random()).set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) + demande = args[0] + for findedMention in re.findall(r'<@[!]?\d*>', demande): + demande = demande.replace(findedMention, f"`{findedMention}`") + embed = discord.Embed(title = titre, description = f"`{demande}`", color = discord.Colour.random()).set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) message = await ctx.send(embed = embed) reactions = ['✅', '🤷', '❌'] for i in reactions: From 716d9039bd12edf8070b337a8d08a97a308a56f6 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 8 May 2021 02:30:53 +0200 Subject: [PATCH 018/286] adding right prefix in command suggestion --- src/cogs/fun.py | 4 ++-- src/cogs/games.py | 2 +- src/cogs/music.py | 20 ++++++++++---------- src/cogs/utils.py | 9 +++++---- 4 files changed, 18 insertions(+), 17 deletions(-) diff --git a/src/cogs/fun.py b/src/cogs/fun.py index d36c941..900acac 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -80,7 +80,7 @@ class Fun(commands.Cog): await ctx.send(f"{''.join(user1)} et {''.join(user2)} ont {coef_amour}% de chance de se mettre en couple !") else: await ctx.message.add_reaction(emoji = '❌') - await ctx.send("Erreur! Syntaxe : `.love [User2]`\n") + await ctx.send(f"Erreur! Syntaxe : `{ctx.prefix}love [User2]`\n") def _retirerDoublons(self, liste): Newliste = [] for element in liste: @@ -102,7 +102,7 @@ class Fun(commands.Cog): @_8ball.error async def _8ball_error(self, ctx, error): if str(error) == "question is a required argument that is missing.": - await ctx.send("Mauvaise syntaxe : `.8ball/8b/8balls `.") + await ctx.send(f"Mauvaise syntaxe : `{ctx.prefix}8ball/8b/8balls `.") @commands.command(name='pileouface', aliases=['pf']) async def _pileouface(self, ctx): diff --git a/src/cogs/games.py b/src/cogs/games.py index a73b048..bf5236a 100644 --- a/src/cogs/games.py +++ b/src/cogs/games.py @@ -42,7 +42,7 @@ class Games(commands.Cog): await ctx.message.add_reaction(emoji = '✅') @_chifumi.error async def _chifumi_error(self, ctx, error): - await ctx.send("Mauvaise syntaxe : `.chifumi/shifumi/ppc `.") + await ctx.send(f"Mauvaise syntaxe : `{ctx.prefix}chifumi/shifumi/ppc `.") @commands.command(name='plusoumoins', aliases = ['+ou-', '+-']) diff --git a/src/cogs/music.py b/src/cogs/music.py index 66e8ef0..b301e7b 100644 --- a/src/cogs/music.py +++ b/src/cogs/music.py @@ -320,7 +320,7 @@ class Music(commands.Cog): """Arrête la chanson en cours de lecture et quitte le salon vocal.\n ➡ Syntaxe: .disconnect/dc/stop⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" if not ctx.voice_state.voice: - embed = discord.Embed(description = "Tape `.play ` pour jouer quelque chose ou `.join [id]` pour me connecter à un salon vocal.", color = 0xC41B1B) + embed = discord.Embed(description = f"Tape `{ctx.prefix}play ` pour jouer quelque chose ou `{ctx.prefix}join [id]` pour me connecter à un salon vocal.", color = 0xC41B1B) embed.set_author(name = "Je ne suis connecté à aucun vocal.") return await ctx.send(embed = embed) @@ -359,7 +359,7 @@ class Music(commands.Cog): await ctx.message.add_reaction('⏯') await ctx.send(f"**`{ctx.author}`** met en pause la chanson en cours.") else: - embed = discord.Embed(description = "Tape `.play ` pour jouer quelque chose.", color = 0xC41B1B) + embed = discord.Embed(description = f"Tape `{ctx.prefix}play ` pour jouer quelque chose.", color = 0xC41B1B) embed.set_author(name = "Je ne joue rien en ce moment !") return await ctx.send(embed = embed) @@ -373,11 +373,11 @@ class Music(commands.Cog): await ctx.send(f"**`{ctx.author}`** relance la chanson.") else: if ctx.voice_state.is_playing: - embed = discord.Embed(description = "Tape `.pause` pour mettre en pause la chanson.", color = 0xC41B1B) + embed = discord.Embed(description = f"Tape `{ctx.prefix}pause` pour mettre en pause la chanson.", color = 0xC41B1B) embed.set_author(name = "Je suis déjà en lecture !") return await ctx.send(embed = embed) else: - embed = discord.Embed(description = "Tape `.play ` pour jouer quelque chose ou `.join [id]` pour me connecter à un salon vocal.", color = 0xC41B1B) + embed = discord.Embed(description = f"Tape `{ctx.prefix}play ` pour jouer quelque chose ou `{ctx.prefix}join [id]` pour me connecter à un salon vocal.", color = 0xC41B1B) embed.set_author(name = "Je ne suis connecté à aucun vocal.") return await ctx.send(embed = embed) @@ -386,7 +386,7 @@ class Music(commands.Cog): """Passe la chanson.\n ➡ Syntaxe: .skip/s""" if not ctx.voice_state.is_playing: - embed = discord.Embed(description = "Tape `.play ` pour jouer quelque chose.", color = 0xC41B1B) + embed = discord.Embed(description = f"Tape `{ctx.prefix}play ` pour jouer quelque chose.", color = 0xC41B1B) embed.set_author(name = "Je ne joue rien en ce moment !") return await ctx.send(embed = embed) @@ -399,7 +399,7 @@ class Music(commands.Cog): """Affiche la file d'attente des chansons à venir.\n ➡ Syntaxe: .queue/q⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢/playlist [page]""" if len(ctx.voice_state.songs) == 0: - embed = discord.Embed(description = "Tape `.play ` pour jouer quelque chose.", color = 0xC41B1B) + embed = discord.Embed(description = f"Tape `{ctx.prefix}play ` pour jouer quelque chose.", color = 0xC41B1B) embed.set_author(name = "Il n'y a plus de chanson à venir dans la playlist.") return await ctx.send(embed = embed) @@ -407,7 +407,7 @@ class Music(commands.Cog): pages = math.ceil(len(ctx.voice_state.songs) / items_per_page) if page > pages: - embed = discord.Embed(description = "Tape `.play ` pour rajouter encore de la musique.", color = 0xC41B1B) + embed = discord.Embed(description = f"Tape `{ctx.prefix}play ` pour rajouter encore de la musique.", color = 0xC41B1B) embed.set_author(name = "Il n'y a pas autant de pages") return await ctx.send(embed = embed) @@ -427,7 +427,7 @@ class Music(commands.Cog): """Mélange la file d'attente.""" if len(ctx.voice_state.songs) == 0: - embed = discord.Embed(description = "Tape `.play ` pour jouer quelque chose.", color = 0xC41B1B) + embed = discord.Embed(description = f"Tape `{ctx.prefix}play ` pour jouer quelque chose.", color = 0xC41B1B) embed.set_author(name = "La file est vide.") return await ctx.send(embed = embed) @@ -450,7 +450,7 @@ class Music(commands.Cog): """Répète la chanson actuellement en lecture.\n ➡ Syntaxe: .loop/repeat""" if not ctx.voice_state.is_playing: - embed = discord.Embed(description = "Tape `.play ` pour jouer quelque chose.", color = 0xC41B1B) + embed = discord.Embed(description = f"Tape `{ctx.prefix}play ` pour jouer quelque chose.", color = 0xC41B1B) embed.set_author(name = "Je ne joue rien en ce moment !") return await ctx.send(embed = embed) @@ -544,7 +544,7 @@ class Music(commands.Cog): return await ctx.send(embed = embed) else: await ctx.message.add_reaction(emoji = '❌') - await ctx.send("Aucune musique demandé... `.lyrics/l/lyrics `.") + await ctx.send(f"Aucune musique demandé... `{ctx.prefix}lyrics/l/lyrics `.") def ligne_formatage(self, ligne): liste_balise = [ ('[Hook', '[Accroche'), ('[Verse', '[Couplet'), ('[Chorus', '[Chœur'), diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 5f2b986..51e5bad 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -149,7 +149,7 @@ class Utils(commands.Cog): @_memo.error async def _note_error(self, ctx, error): if str(error) == "text is a required argument that is missing.": - await ctx.send("Vous devez renseigner un message : `.note/memo ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢`.") + await ctx.send(f"Vous devez renseigner un message : `{ctx.prefix}note/memo ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢`.") @commands.command(name='infos', aliases = ['info']) async def _infos(self, ctx): @@ -231,7 +231,7 @@ class Utils(commands.Cog): await ctx.send(embed = embed) await ctx.message.add_reaction(emoji = '✅') else: - await ctx.send("`.amongus `") + await ctx.send(f"`{ctx.prefix}amongus `") @commands.command(name='whois') async def _whois(self, ctx, *user: discord.Member): @@ -259,7 +259,8 @@ class Utils(commands.Cog): embed.add_field(name = "Est sur le serveur depuis", value = self._ageLayout(self._get_age(user[0].joined_at))) await ctx.message.add_reaction(emoji = '✅') return await ctx.send(embed = embed) - await ctx.send("Tu mentionnes trop d'utilisateurs : `.whois [@Membre]`") + return await ctx.send(f"Tu mentionnes trop d'utilisateurs : `{ctx.prefix}whois [@Membre]`") + def _get_age(self, date): joursRestants = datetime.now() - date years = joursRestants.total_seconds() / (365.242 * 24 * 3600) @@ -348,7 +349,7 @@ class Utils(commands.Cog): else: return await ctx.send(f"Désolé, mais tu as mis trop de possibilités (maximum : 20)") else: - return await ctx.send(f'Désolé, mais il manque des arguments : `.sondage "" "" "" ""`') + return await ctx.send(f'Désolé, mais il manque des arguments : `{ctx.prefix}sondage "" "" "" ""`') @commands.command(name='avis', aliases=['vote']) async def _avis(self, ctx, *args): From 189bf74a718339f1acca2175041c26d74b669c92 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 8 May 2021 02:35:45 +0200 Subject: [PATCH 019/286] harmonization of presets --- README.md | 12 ++++++------ docker-compose.yml | 14 +++++++------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 140bbce..c87b30c 100644 --- a/README.md +++ b/README.md @@ -14,13 +14,13 @@ With a [docker-compose](https://github.com/Confrerie-du-Kassoulait/KassouBot/blo docker run -d \ --name="KassouBot" \ mylloon/kassoubot \ - --TOKEN_DISCORD="yourValue" \ - --TOKEN_GENIUS="yourValue" \ - --TOKEN_REDDIT_CLIENT_ID="yourValue" \ - --TOKEN_REDDIT_CLIENT_SECRET="yourValue" \ - --TOKEN_REDDIT_USER_AGENT="yourValue" \ + --TOKEN_DISCORD="yourTokenDiscord" \ + --TOKEN_GENIUS="yourTokenGenius" \ + --TOKEN_REDDIT_CLIENT_ID="yourRedditClientID" \ + --TOKEN_REDDIT_CLIENT_SECRET="yourRedditClientSecret" \ + --TOKEN_REDDIT_USER_AGENT="yourRedditUserAgent" \ --TIMEZONE="yourTimezone" \ - --PREFIX="." + --PREFIX="yourPrefix" ``` To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and here are the instructions: ![instructions](https://i.imgur.com/tEzYKDA.png) diff --git a/docker-compose.yml b/docker-compose.yml index ec26ed5..390527a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -4,11 +4,11 @@ services: image: mylloon/kassoubot container_name: KassouBot environment: - - TOKEN_DISCORD=your-token-discord - - TOKEN_GENIUS=your-token-genius - - TOKEN_REDDIT_CLIENT_ID=your-reddit-client-id - - TOKEN_REDDIT_CLIENT_SECRET=your-reddit-client-secret - - TOKEN_REDDIT_USER_AGENT=your-reddit-user-agent - - TIMEZONE=your-timezone # https://en.wikipedia.org/wiki/List_of_tz_database_time_zones - - PREFIX=your-prefix + - TOKEN_DISCORD=yourTokenDiscord + - TOKEN_GENIUS=yourTokenGenius + - TOKEN_REDDIT_CLIENT_ID=yourRedditClientID + - TOKEN_REDDIT_CLIENT_SECRET=yourRedditClientSecret + - TOKEN_REDDIT_USER_AGENT=yourRedditUserAgent + - TIMEZONE=yourTimezone # More info here: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + - PREFIX=yourPrefix restart: unless-stopped From ab1b0d11c9a65b00a55c858fd49cb3965a4353d1 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 8 May 2021 10:28:58 +0200 Subject: [PATCH 020/286] fix mention in avis at the beginning and at the end --- src/cogs/utils.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 51e5bad..e2085ca 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -365,10 +365,18 @@ class Utils(commands.Cog): for findedId in re.findall(r'\d+', titre): titre = self._cleanUser(ctx, titre, findedId) args = args[1:] - demande = args[0] - for findedMention in re.findall(r'<@[!]?\d*>', demande): - demande = demande.replace(findedMention, f"`{findedMention}`") - embed = discord.Embed(title = titre, description = f"`{demande}`", color = discord.Colour.random()).set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) + demande = f"`{args[0]}`" + findedMention = [] + for findingMention in re.findall(r'<@[!]?\d*>', demande): + findedMention.append(findingMention) + findedMention = list(dict.fromkeys(findedMention)) + for i in range(0, len(findedMention)): + demande = demande.replace(findedMention[i], f"`{findedMention[i]}`") + if demande.startswith("``<@"): + demande = demande[2:] + if demande.endswith(">``"): + demande = demande[:-2] + embed = discord.Embed(title = titre, description = demande, color = discord.Colour.random()).set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) message = await ctx.send(embed = embed) reactions = ['✅', '🤷', '❌'] for i in reactions: From aed75a118cf1bad7752a4aeba4e3ea901dbcaba5 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 8 May 2021 10:31:05 +0200 Subject: [PATCH 021/286] ajout annotations commande avis --- src/cogs/utils.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index e2085ca..c55d7d5 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -358,23 +358,23 @@ class Utils(commands.Cog): if len(args) > 2 or len(args) == 0: return await ctx.send("Désolé, la syntaxe est mauvaise.") else: - if len(args) == 1: + if len(args) == 1: # si aucun titre défini titre = "Nouveau vote" - else: + else: # si titre défini titre = args[0] - for findedId in re.findall(r'\d+', titre): + for findedId in re.findall(r'\d+', titre): # récupération mention dans titre titre = self._cleanUser(ctx, titre, findedId) args = args[1:] demande = f"`{args[0]}`" findedMention = [] - for findingMention in re.findall(r'<@[!]?\d*>', demande): + for findingMention in re.findall(r'<@[!]?\d*>', demande): # récupération mention dans la demande findedMention.append(findingMention) - findedMention = list(dict.fromkeys(findedMention)) + findedMention = list(dict.fromkeys(findedMention)) # suppression doublon de mention for i in range(0, len(findedMention)): - demande = demande.replace(findedMention[i], f"`{findedMention[i]}`") - if demande.startswith("``<@"): + demande = demande.replace(findedMention[i], f"`{findedMention[i]}`") # conserve la mention dans le message + if demande.startswith("``<@"): # conserve le format quand mention au début de la demande demande = demande[2:] - if demande.endswith(">``"): + if demande.endswith(">``"): # conserve le format quand mention à la fin de la demande demande = demande[:-2] embed = discord.Embed(title = titre, description = demande, color = discord.Colour.random()).set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) message = await ctx.send(embed = embed) From c82370ae497b4fe0ed5c301987800629a7f49afe Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 11 May 2021 10:05:47 +0200 Subject: [PATCH 022/286] ajout reminder --- src/cogs/utils.py | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index c55d7d5..b8c8de0 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -3,7 +3,7 @@ from discord.ext import commands from random import randint, shuffle from datetime import datetime from pytz import timezone -import re +import re, asyncio def setup(client): client.add_cog(Utils(client)) @@ -382,3 +382,34 @@ class Utils(commands.Cog): for i in reactions: await message.add_reaction(emoji = i) return await ctx.message.delete() + + @commands.command(name='reminder', aliases=["remind", "remindme", "remind_me"]) + async def _reminder(self, ctx, time, *, reminder): + embed = discord.Embed(color = 0xC41B1B) + seconds = 0 + if reminder: + if time.lower().endswith("d"): + seconds += int(time[:-1]) * 60 * 60 * 24 + counter = f"{seconds // 60 // 60 // 24} jours" + if time.lower().endswith("h"): + seconds += int(time[:-1]) * 60 * 60 + counter = f"{seconds // 60 // 60} heures" + elif time.lower().endswith("m"): + seconds += int(time[:-1]) * 60 + counter = f"{seconds // 60} minutes" + elif time.lower().endswith("s"): + seconds += int(time[:-1]) + counter = f"{seconds} secondes" + if seconds == 0: + embed.add_field(name="Attention", value="Mauvais format pour l'heure, `d` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (ne fonctionne qu'avec une seule unité).") + elif seconds < 300: + embed.add_field(name="Attention", value="Tu as spécifié une durée trop courte, la durée minimum étant de 5 minutes.") + elif seconds > 7776000: + embed.add_field(name="Attention", value="Tu as spécifié une durée trop longue, la durée maximum étant de 90 jours.") + else: + await ctx.send(f"Ok, je t'en parles dans {counter} !") + await asyncio.sleep(seconds) + return await ctx.send(f"{ctx.author.mention}, voici ton message d'il y a {counter} :```{reminder}```") + else: + embed.add_field(name="Attention", value="Mauvaise syntaxe : reminder ") + await ctx.send(embed = embed) From 63b08d0007964bb29ddff2dd15279ba0aef4b9a7 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 11 May 2021 10:07:36 +0200 Subject: [PATCH 023/286] ajout help command for reminder --- src/cogs/utils.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index b8c8de0..58b3050 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -383,8 +383,9 @@ class Utils(commands.Cog): await message.add_reaction(emoji = i) return await ctx.message.delete() - @commands.command(name='reminder', aliases=["remind", "remindme", "remind_me"]) + @commands.command(name='reminder', aliases=["remind", "remindme"]) async def _reminder(self, ctx, time, *, reminder): + """Met en place un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .reminder/remind/remindme """ embed = discord.Embed(color = 0xC41B1B) seconds = 0 if reminder: From 8d33e5e1ac48698ea2aea3a019421c5654eb8923 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 11 May 2021 10:09:59 +0200 Subject: [PATCH 024/286] commentaire --- src/cogs/utils.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 58b3050..59be673 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -403,9 +403,9 @@ class Utils(commands.Cog): counter = f"{seconds} secondes" if seconds == 0: embed.add_field(name="Attention", value="Mauvais format pour l'heure, `d` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (ne fonctionne qu'avec une seule unité).") - elif seconds < 300: + elif seconds < 300: # 5 * 60 embed.add_field(name="Attention", value="Tu as spécifié une durée trop courte, la durée minimum étant de 5 minutes.") - elif seconds > 7776000: + elif seconds > 7776000: # 90 * 60 * 60 * 24 embed.add_field(name="Attention", value="Tu as spécifié une durée trop longue, la durée maximum étant de 90 jours.") else: await ctx.send(f"Ok, je t'en parles dans {counter} !") From 47984b16829e28b0fb4c4806bc2dcaedff5874b7 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 11 May 2021 10:45:05 +0200 Subject: [PATCH 025/286] update ping command --- src/cogs/utils.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 59be673..16f8d4a 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -19,14 +19,14 @@ class Utils(commands.Cog): async def _ping(self, ctx, *, question = '0'): """Affiche mon ping.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .ping [help]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" if question == 'help': - return await ctx.send(embed = discord.Embed(color = discord.Colour.random(), description = ":hourglass: correspond au temps entre deux battements de cœurs (en millisecondes)\n\n:stopwatch: correspond au temps que met le client a calculer le ping (en millisecondes)\n\n:heartbeat: correspond au temps que met le client a réagir au messages (en millisecondes)")) + return await ctx.send(embed = discord.Embed(color = discord.Colour.random(), description = ":hourglass: correspond au temps entre deux battements de cœurs\n\n:stopwatch: correspond au temps que met le client a calculer le ping\n\n:heartbeat: correspond au temps que met le client a réagir au messages")) else: now = int(round(time.time() * 1000)) ping = now - int(round(ctx.message.created_at.timestamp() * 1000)) embed = discord.Embed(description = 'Pinging...') message = await ctx.send(embed = embed) ping2 = int(round(time.time() * 1000)) - now - await message.edit(embed = discord.Embed(color = discord.Colour.random(), description = f':hourglass: {round(self.client.latency * 1000)}ms\n\n:stopwatch: {ping2}ms\n\n:heartbeat: {ping}ms')) + await message.edit(embed = discord.Embed(color = discord.Colour.random(), description = f':hourglass: {round(self.client.latency * 1000)} ms\n\n:stopwatch: {ping2} ms\n\n:heartbeat: {ping} ms')) await ctx.message.add_reaction(emoji = '✅') @commands.command(name='avatar') From af88144ad002def149a744279cd9c6cce8c14e8a Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 11 May 2021 15:39:06 +0200 Subject: [PATCH 026/286] meilleur articulation de la commande AVIS - affichage du remindme avec un embed - support des accords dans le remindme et meilleur gestion d'erreurs --- src/cogs/utils.py | 62 +++++++++++++++++++++++++++-------------------- 1 file changed, 36 insertions(+), 26 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 16f8d4a..32f214f 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -310,6 +310,20 @@ class Utils(commands.Cog): pass return stringMessage + def _cleanCodeStringWithMention(self, string): + string = f"`{string}`" + findedMention = [] + for findingMention in re.findall(r'<@[!]?\d*>', string): # récupération mention dans la string + findedMention.append(findingMention) + findedMention = list(dict.fromkeys(findedMention)) # suppression doublon de mention + for i in range(0, len(findedMention)): + string = string.replace(findedMention[i], f"`{findedMention[i]}`") # conserve la mention dans le message + if string.startswith("``<@"): # conserve le format quand mention au début de la string + string = string[2:] + if string.endswith(">``"): # conserve le format quand mention à la fin de la string + string = string[:-2] + return string + @commands.command(name='sondage') async def _sondage(self, ctx, *args): """Fais un sondage.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .sondage "" "" "" "" """ @@ -365,18 +379,7 @@ class Utils(commands.Cog): for findedId in re.findall(r'\d+', titre): # récupération mention dans titre titre = self._cleanUser(ctx, titre, findedId) args = args[1:] - demande = f"`{args[0]}`" - findedMention = [] - for findingMention in re.findall(r'<@[!]?\d*>', demande): # récupération mention dans la demande - findedMention.append(findingMention) - findedMention = list(dict.fromkeys(findedMention)) # suppression doublon de mention - for i in range(0, len(findedMention)): - demande = demande.replace(findedMention[i], f"`{findedMention[i]}`") # conserve la mention dans le message - if demande.startswith("``<@"): # conserve le format quand mention au début de la demande - demande = demande[2:] - if demande.endswith(">``"): # conserve le format quand mention à la fin de la demande - demande = demande[:-2] - embed = discord.Embed(title = titre, description = demande, color = discord.Colour.random()).set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) + embed = discord.Embed(title = titre, description = self._cleanCodeStringWithMention(args[0]), color = discord.Colour.random()).set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) message = await ctx.send(embed = embed) reactions = ['✅', '🤷', '❌'] for i in reactions: @@ -388,21 +391,28 @@ class Utils(commands.Cog): """Met en place un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .reminder/remind/remindme """ embed = discord.Embed(color = 0xC41B1B) seconds = 0 + timestamp = datetime.utcnow() if reminder: - if time.lower().endswith("d"): - seconds += int(time[:-1]) * 60 * 60 * 24 - counter = f"{seconds // 60 // 60 // 24} jours" - if time.lower().endswith("h"): - seconds += int(time[:-1]) * 60 * 60 - counter = f"{seconds // 60 // 60} heures" - elif time.lower().endswith("m"): - seconds += int(time[:-1]) * 60 - counter = f"{seconds // 60} minutes" - elif time.lower().endswith("s"): - seconds += int(time[:-1]) - counter = f"{seconds} secondes" + try: + if time.lower().endswith("d"): + seconds += int(time[:-1]) * 60 * 60 * 24 + _seconds = seconds // 60 // 60 // 24 + counter = f"{_seconds} jour{'s' if _seconds > 1 else ''}" + if time.lower().endswith("h"): + seconds += int(time[:-1]) * 60 * 60 + _seconds = seconds // 60 // 60 + counter = f"{_seconds} heure{'s' if _seconds > 1 else ''}" + elif time.lower().endswith("m"): + seconds += int(time[:-1]) * 60 + _seconds = seconds // 60 + counter = f"{_seconds} minute{'s' if _seconds > 1 else ''}" + elif time.lower().endswith("s"): + seconds += int(time[:-1]) + counter = f"{seconds} seconde{'s' if seconds > 1 else ''}" + except: + pass if seconds == 0: - embed.add_field(name="Attention", value="Mauvais format pour l'heure, `d` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (ne fonctionne qu'avec une seule unité).") + embed.add_field(name="Attention", value="Mauvais format pour le temps, `d` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (ne fonctionne qu'avec une seule unité).") elif seconds < 300: # 5 * 60 embed.add_field(name="Attention", value="Tu as spécifié une durée trop courte, la durée minimum étant de 5 minutes.") elif seconds > 7776000: # 90 * 60 * 60 * 24 @@ -410,7 +420,7 @@ class Utils(commands.Cog): else: await ctx.send(f"Ok, je t'en parles dans {counter} !") await asyncio.sleep(seconds) - return await ctx.send(f"{ctx.author.mention}, voici ton message d'il y a {counter} :```{reminder}```") + return await ctx.send(ctx.author.mention, embed = discord.Embed(description = self._cleanCodeStringWithMention(reminder), timestamp = timestamp, color = discord.Colour.random()).set_footer(text=f"Message d'il y a {counter}")) else: embed.add_field(name="Attention", value="Mauvaise syntaxe : reminder ") await ctx.send(embed = embed) From 8a4cefb6ef91d7e4131c89c23f3303f59335921d Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 11 May 2021 19:07:21 +0200 Subject: [PATCH 027/286] ajout mention facultative dans reminder --- src/cogs/utils.py | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 32f214f..440bc54 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -270,6 +270,7 @@ class Utils(commands.Cog): minutes = (hours - int(hours)) * 60 seconds = (minutes - int(minutes)) * 60 return (int(years), int(months), int(days), int(hours), int(minutes), int(seconds)) + def _ageLayout(self, tuple): time = {} time[0], time[1], time[2], time[3], time[4], time[5] = "an", "mois", "jour", "heure", "minute", "seconde" @@ -292,7 +293,7 @@ class Utils(commands.Cog): for i in affichage: message = message + f", {tuple[i]} {time[i]}" return message[2:] - + def _userOrNick(self, user): if user == None: return "Utilisateur inconnu" # Mauvais copié/collé -> changement d'ID @@ -312,10 +313,7 @@ class Utils(commands.Cog): def _cleanCodeStringWithMention(self, string): string = f"`{string}`" - findedMention = [] - for findingMention in re.findall(r'<@[!]?\d*>', string): # récupération mention dans la string - findedMention.append(findingMention) - findedMention = list(dict.fromkeys(findedMention)) # suppression doublon de mention + findedMention = self._getMentionInString(string) for i in range(0, len(findedMention)): string = string.replace(findedMention[i], f"`{findedMention[i]}`") # conserve la mention dans le message if string.startswith("``<@"): # conserve le format quand mention au début de la string @@ -324,6 +322,13 @@ class Utils(commands.Cog): string = string[:-2] return string + def _getMentionInString(self, string): + findedMention = [] + for findingMention in re.findall(r'<@[!]?\d*>', string): # récupération mention dans la string + findedMention.append(findingMention) + findedMention = list(dict.fromkeys(findedMention)) # suppression doublon de mention + return findedMention + @commands.command(name='sondage') async def _sondage(self, ctx, *args): """Fais un sondage.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .sondage "" "" "" "" """ @@ -388,11 +393,15 @@ class Utils(commands.Cog): @commands.command(name='reminder', aliases=["remind", "remindme"]) async def _reminder(self, ctx, time, *, reminder): - """Met en place un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .reminder/remind/remindme """ + """Met en place un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .reminder/remind/remindme [@] """ embed = discord.Embed(color = 0xC41B1B) seconds = 0 timestamp = datetime.utcnow() + mention = False if reminder: + if time.lower().endswith("@"): + time = time[:-1] + mention = True try: if time.lower().endswith("d"): seconds += int(time[:-1]) * 60 * 60 * 24 @@ -412,7 +421,7 @@ class Utils(commands.Cog): except: pass if seconds == 0: - embed.add_field(name="Attention", value="Mauvais format pour le temps, `d` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (ne fonctionne qu'avec une seule unité).") + embed.add_field(name="Attention", value="Mauvais format pour le temps, `d` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (ne fonctionne qu'avec une seule unité)\nMet un `@` accolée à l'unité pour mentionner les gens mentionner dans ton message.") elif seconds < 300: # 5 * 60 embed.add_field(name="Attention", value="Tu as spécifié une durée trop courte, la durée minimum étant de 5 minutes.") elif seconds > 7776000: # 90 * 60 * 60 * 24 @@ -420,7 +429,12 @@ class Utils(commands.Cog): else: await ctx.send(f"Ok, je t'en parles dans {counter} !") await asyncio.sleep(seconds) - return await ctx.send(ctx.author.mention, embed = discord.Embed(description = self._cleanCodeStringWithMention(reminder), timestamp = timestamp, color = discord.Colour.random()).set_footer(text=f"Message d'il y a {counter}")) + message = ctx.author.mention + if mention: + mentionList = self._getMentionInString(reminder) + for i in mentionList: + message += f" {i}" + return await ctx.send(message, embed = discord.Embed(description = self._cleanCodeStringWithMention(reminder), timestamp = timestamp, color = discord.Colour.random()).set_footer(text=f"Message d'il y a {counter}")) else: embed.add_field(name="Attention", value="Mauvaise syntaxe : reminder ") await ctx.send(embed = embed) From a07edd5155e61b42d2d4247c902d999e2b4cac98 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 11 May 2021 19:22:18 +0200 Subject: [PATCH 028/286] retire les espaces en trop dans les commandes avis et remind --- src/cogs/utils.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 440bc54..5dad03d 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -312,7 +312,7 @@ class Utils(commands.Cog): return stringMessage def _cleanCodeStringWithMention(self, string): - string = f"`{string}`" + string = f"`{self._removeStartEndSpacesString(string)}`" findedMention = self._getMentionInString(string) for i in range(0, len(findedMention)): string = string.replace(findedMention[i], f"`{findedMention[i]}`") # conserve la mention dans le message @@ -328,6 +328,13 @@ class Utils(commands.Cog): findedMention.append(findingMention) findedMention = list(dict.fromkeys(findedMention)) # suppression doublon de mention return findedMention + + def _removeStartEndSpacesString(self, string): + while string.startswith(" "): + string = string[1:] + while string.endswith(" "): + string = string[:-1] + return string @commands.command(name='sondage') async def _sondage(self, ctx, *args): From 068382899196483b8f578991d49063d9639e9602 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 12 May 2021 01:59:05 +0200 Subject: [PATCH 029/286] update subreddit --- src/cogs/internet.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 8633a21..9fbab36 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -39,7 +39,7 @@ class Internet(commands.Cog): subredditchoix = args else: # si il n'y a pas d'arguments - subredditchoix = choice(['memes', 'anime_irl', 'goodanimemes', 'BikiniclienttomTwitter', 'dankmemes', 'DeepFriedMemes', + subredditchoix = choice(['memes', 'anime_irl', 'goodanimemes', 'BikiniclienttomTwitter', 'dankmemes', 'DeepFried', 'educationalmemes', 'funny', 'marvelmemes', 'me_irl', 'meme', 'MemeEconomy', 'Memes_Of_The_Dank', 'MinecraftMemes', 'physicsmemes', 'reactiongifs', 'blackpeopletwitter', 'metal_me_irl', 'bee_irl', '195', 'shittyadviceanimals', 'meirl', '2meirl4meirl', 'AdviceAnimals', 'weirdmemes']) From a0f1e6bf62717aa2839f4b6cecdbc74dd826f88c Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 12 May 2021 02:03:22 +0200 Subject: [PATCH 030/286] remove limitation of 5mn in remind --- src/cogs/utils.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 5dad03d..673e41e 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -429,8 +429,6 @@ class Utils(commands.Cog): pass if seconds == 0: embed.add_field(name="Attention", value="Mauvais format pour le temps, `d` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (ne fonctionne qu'avec une seule unité)\nMet un `@` accolée à l'unité pour mentionner les gens mentionner dans ton message.") - elif seconds < 300: # 5 * 60 - embed.add_field(name="Attention", value="Tu as spécifié une durée trop courte, la durée minimum étant de 5 minutes.") elif seconds > 7776000: # 90 * 60 * 60 * 24 embed.add_field(name="Attention", value="Tu as spécifié une durée trop longue, la durée maximum étant de 90 jours.") else: From fba0fa06725c8bb93eed3fc44698222c0b59b0a9 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 12 May 2021 02:37:03 +0200 Subject: [PATCH 031/286] update discord 1.6.0 -> 1.7.2 update youtube-dl 2021.2.22 -> 2021.4.26 update lyrcicsgenius 3.0.0 -> 3.0.1 changement praw -> asyncpraw --- requirements.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/requirements.txt b/requirements.txt index 06a7e71..920fa85 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,6 @@ -discord.py[voice]==1.6.0 # discord +discord.py[voice]==1.7.2 # discord pytz==2021.1 # timezone -praw==7.1.4 # reddit -youtube-dl==2021.2.22 # music -lyricsgenius==3.0.0 # lyrics +asyncpraw==7.2.0 # reddit +youtube-dl==2021.4.26 # music +lyricsgenius==3.0.1 # lyrics feedparser==6.0.2 # rss feed (news) From 8f8cc112cd7c63b7665e21c2dc7cdaabd2a6ec99 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 12 May 2021 02:37:45 +0200 Subject: [PATCH 032/286] changement praw -> asyncpraw changement commande meme -> async --- src/cogs/internet.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 9fbab36..84ad1be 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -1,6 +1,7 @@ -import discord, praw, json, requests, time, feedparser, os +import discord, json, requests, time, feedparser, os from discord.ext import commands -from random import randint, choice +from random import choice +from asyncpraw import Reddit def setup(client): client.add_cog(Internet(client)) @@ -33,8 +34,6 @@ class Internet(commands.Cog): async def _memes(self, ctx, *, args = ""): """Envois un meme de reddit.\n ➡ Syntaxe: .memes/meme [subreddit]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" try: - reddit = praw.Reddit(client_id = os.environ['TOKEN_REDDIT_CLIENT_ID'], client_secret = os.environ['TOKEN_REDDIT_CLIENT_SECRET'], user_agent = f"disreddit /u/{os.environ['TOKEN_REDDIT_USER_AGENT']}, http://localhost:8080") - if args != "": # si il y a un arg différent d'un meme subredditchoix = args @@ -44,11 +43,11 @@ class Internet(commands.Cog): 'physicsmemes', 'reactiongifs', 'blackpeopletwitter', 'metal_me_irl', 'bee_irl', '195', 'shittyadviceanimals', 'meirl', '2meirl4meirl', 'AdviceAnimals', 'weirdmemes']) - memes_submissions = reddit.subreddit(subredditchoix).hot() - post_to_pick = randint(1, 10) - for i in range(0, post_to_pick): # i pas important - i = i #retire l'erreur sur vscode - submission = next(x for x in memes_submissions if not x.stickied) + async with Reddit(client_id = os.environ['TOKEN_REDDIT_CLIENT_ID'], client_secret = os.environ['TOKEN_REDDIT_CLIENT_SECRET'], user_agent = f"disreddit /u/{os.environ['TOKEN_REDDIT_USER_AGENT']}, http://localhost:8080") as reddit: + subreddit = await reddit.subreddit(subredditchoix) # récupération du subreddit + hot = subreddit.top(limit = 20) # récupération des memes avec une limite aux 10 premiers memes + all_subs = [item async for item in hot] # liste des memes + submission = choice(all_subs) # choix aléatoire image = ["png", "jpg", "jpeg", "bmp", "gif"] if submission.url[-3:] in image: From 1b94dd973dccc4994227ee0f15d238631bb3b86d Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 12 May 2021 02:46:04 +0200 Subject: [PATCH 033/286] meilleurs commentaires --- src/cogs/internet.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 84ad1be..10b5290 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -31,18 +31,18 @@ class Internet(commands.Cog): await self._cat(await self.client.get_context(message)) @commands.command(name='memes', aliases = ['meme']) - async def _memes(self, ctx, *, args = ""): + async def _memes(self, ctx, *, args = None): """Envois un meme de reddit.\n ➡ Syntaxe: .memes/meme [subreddit]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + + if args: # s'il y a un subreddit de défini + subredditchoix = args + else: # s'il n'y en a pas + subredditchoix = choice(['memes', 'anime_irl', 'goodanimemes', 'BikiniclienttomTwitter', 'dankmemes', 'DeepFried', + 'educationalmemes', 'funny', 'marvelmemes', 'me_irl', 'meme', 'MemeEconomy', 'Memes_Of_The_Dank', 'MinecraftMemes', + 'physicsmemes', 'reactiongifs', 'blackpeopletwitter', 'metal_me_irl', 'bee_irl', '195', 'shittyadviceanimals', 'meirl', + '2meirl4meirl', 'AdviceAnimals', 'weirdmemes']) + try: - if args != "": # si il y a un arg différent d'un meme - subredditchoix = args - - else: # si il n'y a pas d'arguments - subredditchoix = choice(['memes', 'anime_irl', 'goodanimemes', 'BikiniclienttomTwitter', 'dankmemes', 'DeepFried', - 'educationalmemes', 'funny', 'marvelmemes', 'me_irl', 'meme', 'MemeEconomy', 'Memes_Of_The_Dank', 'MinecraftMemes', - 'physicsmemes', 'reactiongifs', 'blackpeopletwitter', 'metal_me_irl', 'bee_irl', '195', - 'shittyadviceanimals', 'meirl', '2meirl4meirl', 'AdviceAnimals', 'weirdmemes']) - async with Reddit(client_id = os.environ['TOKEN_REDDIT_CLIENT_ID'], client_secret = os.environ['TOKEN_REDDIT_CLIENT_SECRET'], user_agent = f"disreddit /u/{os.environ['TOKEN_REDDIT_USER_AGENT']}, http://localhost:8080") as reddit: subreddit = await reddit.subreddit(subredditchoix) # récupération du subreddit hot = subreddit.top(limit = 20) # récupération des memes avec une limite aux 10 premiers memes @@ -63,7 +63,7 @@ class Internet(commands.Cog): return await message.add_reaction('👎') except Exception as error: - print(f"args: {args}, subreddit: {subredditchoix}, error: {error}") + print(f"Error in _memes command = args: {args}, subreddit: {subredditchoix}, error: {error}") await ctx.message.add_reaction(emoji = '❌') return await ctx.send(f"Ce subreddit est interdit, mis en quarantaine ou n'existe pas. ({subredditchoix})") From f96d395777b25ab5af6515f6d9d9839d022581e8 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 13 May 2021 08:36:42 +0200 Subject: [PATCH 034/286] adding custom timezone everywhere with one unique call per file --- src/cogs/utils.py | 7 ++++--- src/main.py | 9 +++++---- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 673e41e..52608b8 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -13,6 +13,7 @@ class Utils(commands.Cog): def __init__(self, client): self.client = client + self.customTimezone = os.environ['TIMEZONE'] @commands.command(name='ping') @@ -143,7 +144,7 @@ class Utils(commands.Cog): await ctx.message.delete() embed = discord.Embed(description = text, color = discord.Colour.random()) embed.set_author(name = f"Mémo noté depuis {ctx.guild.name}", icon_url = ctx.author.avatar_url) - embed.set_footer(text = f'📝 le {datetime.now(pytz.timezone("Europe/Paris")).strftime("%d/%m/%Y à %H:%M:%S")}') + embed.set_footer(text = f'📝 le {datetime.now(pytz.timezone(self.customTimezone)).strftime("%d/%m/%Y à %H:%M:%S")}') await ctx.author.send(embed = embed) return await ctx.send("Tu viens de recevoir ton mémo !", delete_after = 5) @_memo.error @@ -246,14 +247,14 @@ class Utils(commands.Cog): embed.add_field(name = "ID", value = user[0].id) - value = str(user[0].created_at.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').split() + value = str(user[0].created_at.astimezone(timezone(self.customTimezone)))[:-13].replace('-', '/').split() embed.add_field(name = "Compte créé le", value = f"{value[0][8:]}/{value[0][5:-3]}/{value[0][:4]} à {value[1]}") embed.add_field(name = "Âge du compte", value = self._ageLayout(self._get_age(user[0].created_at))) embed.add_field(name = "Mention", value = user[0].mention) - value = str(user[0].joined_at.astimezone(timezone(os.environ['TIMEZONE'])))[:-13].replace('-', '/').split() + value = str(user[0].joined_at.astimezone(timezone(self.customTimezone)))[:-13].replace('-', '/').split() embed.add_field(name = "Serveur rejoint le", value = f"{value[0][8:]}/{value[0][5:-3]}/{value[0][:4]} à {value[1]}") embed.add_field(name = "Est sur le serveur depuis", value = self._ageLayout(self._get_age(user[0].joined_at))) diff --git a/src/main.py b/src/main.py index 45b0c5a..28d5cc0 100644 --- a/src/main.py +++ b/src/main.py @@ -6,6 +6,7 @@ from random import choice from datetime import datetime from pytz import timezone customPrefix = os.environ['PREFIX'] +customTimezone = os.environ['TIMEZONE'] client = commands.Bot(command_prefix = customPrefix, case_insensitive = True, intents = discord.Intents.all()) @@ -197,9 +198,9 @@ async def on_message_delete(message): embed.set_author(name = user_or_nick(message.author), icon_url = message.author.avatar_url) if not user_suppressed: - embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1)}\nSupprimé le {datetime.now(pytz.timezone(os.environ['TIMEZONE'])).strftime('%d/%m/%Y à %H:%M:%S')}") + embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1)}\nSupprimé le {datetime.now(pytz.timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") else: - embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1)}\nSupprimé par {user_or_nick(user_suppressed)} le {datetime.now(pytz.timezone(os.environ['TIMEZONE'])).strftime('%d/%m/%Y à %H:%M:%S')}") + embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1)}\nSupprimé par {user_or_nick(user_suppressed)} le {datetime.now(pytz.timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") await channel.send(embed = embed) # ne fonctionne pas quand un message a été supprimé avant que le bot ai démarré @@ -213,8 +214,8 @@ def user_or_nick(user): def goodTimezone(date, type): if type == 0: - return str(pytz.timezone(os.environ['TIMEZONE']).fromutc(date))[:-13].replace('-', '/').split() + return str(pytz.timezone(customTimezone).fromutc(date))[:-13].replace('-', '/').split() elif type == 1: - return str(pytz.timezone(os.environ['TIMEZONE']).fromutc(date))[:-13].replace('-', '/').replace(' ', ' à ') + return str(pytz.timezone(customTimezone).fromutc(date))[:-13].replace('-', '/').replace(' ', ' à ') client.run(os.environ['TOKEN_DISCORD']) From 263674b11f1433ead7863c62fc587cbabc6a2a37 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 13 May 2021 09:06:43 +0200 Subject: [PATCH 035/286] new field in info command --- src/cogs/utils.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 52608b8..de143df 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -172,11 +172,20 @@ class Utils(commands.Cog): text = len(text_channels) voice = len(voice_channels) + nombreServeur = len(self.client.guilds) + + with open(os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "README.md"), "r") as file: + for versionNumber in re.findall(r'https://img.shields.io/badge/version-(\d+\.\d+)', file.readlines()[2]): + version = versionNumber embed.add_field(name = "Dev", value = f"[{appinfo.owner}](https://github.com/Mylloon)") - embed.add_field(name = "Serveurs", value = len(self.client.guilds)) - embed.add_field(name = "Membres", value = f"{total_unique} au total\n{total_online} en ligne") - embed.add_field(name = "Channels", value = f"{text} textuelles\n{voice} vocales") + embed.add_field(name = f"Serveur{'s' if nombreServeur > 1 else ''}", value = f"`{nombreServeur}`") + embed.add_field(name = f"Membre{'s' if total_unique > 1 else ''}", value = f"`{total_unique}` au total\n`{total_online}` en ligne") + embed.add_field(name = f"Salon{'s' if (text + voice) > 1 else ''}", value = f"`{text}` textuel{'s' if text > 1 else ''}\n`{voice}` voca{'ux' if voice > 1 else 'l'}") + embed.add_field(name = "Prefix", value = f"`{ctx.prefix}`") + embed.add_field(name = "Code source", value = f"[Lien Github](https://github.com/Confrerie-du-Kassoulait/KassouBot/)") + embed.add_field(name = "Timezone", value = f"`{self.customTimezone}`") + embed.add_field(name = "Version", value = f"`{version}`") embed.set_footer(text = f"Basé sur discord.py {discord.__version__}") await ctx.message.add_reaction(emoji = '✅') await ctx.send(embed = embed) From d97c1b41b3a4d8c3f8f1118694b8edca665f5dd1 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 13 May 2021 09:11:09 +0200 Subject: [PATCH 036/286] =?UTF-8?q?adding=20a=20=E2=9C=85=20to=20original?= =?UTF-8?q?=20message=20of=20the=20remindme=20command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/utils.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index de143df..139609e 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -449,6 +449,10 @@ class Utils(commands.Cog): mentionList = self._getMentionInString(reminder) for i in mentionList: message += f" {i}" + try: + await ctx.message.add_reaction(emoji = '✅') + except: + pass return await ctx.send(message, embed = discord.Embed(description = self._cleanCodeStringWithMention(reminder), timestamp = timestamp, color = discord.Colour.random()).set_footer(text=f"Message d'il y a {counter}")) else: embed.add_field(name="Attention", value="Mauvaise syntaxe : reminder ") From 04675a2425782f681d8be1d5d42ba4bf871f761f Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 13 May 2021 09:17:39 +0200 Subject: [PATCH 037/286] adding readme to docker --- .dockerignore | 1 - 1 file changed, 1 deletion(-) diff --git a/.dockerignore b/.dockerignore index 33e952b..7d0b599 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,4 +1,3 @@ -README.md LICENSE CODE_OF_CONDUCT.md .gitignore From e65cd46e1e9beabb8b6c443941f690dae265c5f9 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 13 May 2021 09:23:49 +0200 Subject: [PATCH 038/286] better docker health --- .dockerignore | 3 --- Dockerfile | 1 + 2 files changed, 1 insertion(+), 3 deletions(-) delete mode 100644 .dockerignore diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index 7d0b599..0000000 --- a/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ -LICENSE -CODE_OF_CONDUCT.md -.gitignore diff --git a/Dockerfile b/Dockerfile index 0a2f7ee..197f862 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,6 +6,7 @@ RUN pip install -r requirements.txt RUN apt update && \ apt install -y --no-install-recommends ffmpeg +COPY README.md . COPY src . CMD [ "python", "-u", "./main.py" ] From 9b57903abbdc7e68cb59d2673c8072b7e0abd08a Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 13 May 2021 09:44:17 +0200 Subject: [PATCH 039/286] remove parenthesis --- src/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.py b/src/main.py index 28d5cc0..d74d0e7 100644 --- a/src/main.py +++ b/src/main.py @@ -157,7 +157,7 @@ async def on_message(message): edit = "" if msgID.edited_at: date_edit = goodTimezone(msgID.edited_at, 0) - edit = f" et modifié le {date_edit[0][8:]}/{date_edit[0][5:-3]}/{date_edit[0][:4]} à {date_edit[1]})" + edit = f" et modifié le {date_edit[0][8:]}/{date_edit[0][5:-3]}/{date_edit[0][:4]} à {date_edit[1]}" messageDuBas = f"Posté le {date_1[0][8:]}/{date_1[0][5:-3]}/{date_1[0][:4]} à {date_1[1]}{edit}" date_2 = goodTimezone(message.created_at, 0) From 0c981a943e3abc9e37acb9ad3117302c6928c420 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 15 May 2021 19:45:34 +0200 Subject: [PATCH 040/286] =?UTF-8?q?modification=20avis=20/=20reminder=20->?= =?UTF-8?q?=202=20mentions=20coll=C3=A9s=20ne=20posent=20plus=20de=20pb=20?= =?UTF-8?q?modification=20reminder=20->=20les=20liens=20sont=20d=C3=A9sorm?= =?UTF-8?q?ais=20cliquable?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/utils.py | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 139609e..2b1c47f 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -321,23 +321,32 @@ class Utils(commands.Cog): pass return stringMessage - def _cleanCodeStringWithMention(self, string): + def _cleanCodeStringWithMentionAndURLs(self, string): string = f"`{self._removeStartEndSpacesString(string)}`" + findedMention = self._getMentionInString(string) for i in range(0, len(findedMention)): string = string.replace(findedMention[i], f"`{findedMention[i]}`") # conserve la mention dans le message + if string.startswith("``<@"): # conserve le format quand mention au début de la string string = string[2:] if string.endswith(">``"): # conserve le format quand mention à la fin de la string string = string[:-2] + string = string.replace("``", "") # conserve le format quand deux mentions sont collés return string def _getMentionInString(self, string): findedMention = [] - for findingMention in re.findall(r'<@[!]?\d*>', string): # récupération mention dans la string + for findingMention in re.findall(r'<@[!]?\d*>', string): # récupération mention dans le string findedMention.append(findingMention) - findedMention = list(dict.fromkeys(findedMention)) # suppression doublon de mention + findedMention = list(dict.fromkeys(findedMention)) # suppression doublon de mention dans la liste return findedMention + + def _getURLsInString(self, string): + findedURLs = [] + for findingMention in re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', string): # récupération URLs dans le string + findedURLs.append(findingMention) + return findedURLs def _removeStartEndSpacesString(self, string): while string.startswith(" "): @@ -401,7 +410,7 @@ class Utils(commands.Cog): for findedId in re.findall(r'\d+', titre): # récupération mention dans titre titre = self._cleanUser(ctx, titre, findedId) args = args[1:] - embed = discord.Embed(title = titre, description = self._cleanCodeStringWithMention(args[0]), color = discord.Colour.random()).set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) + embed = discord.Embed(title = titre, description = self._cleanCodeStringWithMentionAndURLs(args[0]), color = discord.Colour.random()).set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) message = await ctx.send(embed = embed) reactions = ['✅', '🤷', '❌'] for i in reactions: @@ -453,7 +462,17 @@ class Utils(commands.Cog): await ctx.message.add_reaction(emoji = '✅') except: pass - return await ctx.send(message, embed = discord.Embed(description = self._cleanCodeStringWithMention(reminder), timestamp = timestamp, color = discord.Colour.random()).set_footer(text=f"Message d'il y a {counter}")) + finalEmbed = discord.Embed(description = self._cleanCodeStringWithMentionAndURLs(reminder), timestamp = timestamp, color = discord.Colour.random()) + finalEmbed.set_footer(text=f"Message d'il y a {counter}") + + links = "" + findedURLs = self._getURLsInString(reminder) + for i in range(0, len(findedURLs)): + links += f"[Lien {i + 1}]({findedURLs[i]}) · " + if len(findedURLs) > 0: + finalEmbed.add_field(name = f"Lien{'s' if len(findedURLs) > 1 else ''}", value = links[:-3]) + + return await ctx.send(message, embed = finalEmbed) else: embed.add_field(name="Attention", value="Mauvaise syntaxe : reminder ") await ctx.send(embed = embed) From 6390f6b6ca49947293f3f0fc4190a8041145b92e Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 15 May 2021 20:07:49 +0200 Subject: [PATCH 041/286] new school category --- src/cogs/school.py | 59 ++++++++++++++++++++++++++++++++++++++++++++++ src/main.py | 1 + 2 files changed, 60 insertions(+) create mode 100644 src/cogs/school.py diff --git a/src/cogs/school.py b/src/cogs/school.py new file mode 100644 index 0000000..1e1a88a --- /dev/null +++ b/src/cogs/school.py @@ -0,0 +1,59 @@ +import discord +from discord.ext import commands + +def setup(client): + client.add_cog(School(client)) + +class School(commands.Cog): + """Commandes relatives aux cours.""" + + def __init__(self, client): + self.client = client + + @commands.command(name='appel') + # @commands.has_any_role("Professeur", "professeur", "Prof", "prof") + async def _appel(self, ctx, *, voice_channel: int = None): + """Fais l'appel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .appel [ID salon vocal]""" + voice_channels = [] + voice_channels.extend(ctx.guild.voice_channels) + await ctx.message.add_reaction(emoji = "✅") + limite_voice_channels = 7 + if len(voice_channels) > limite_voice_channels: + return await ctx.send(f"""Désolé mais il y a plus de {limite_voice_channels} salons vocaux sur ce serveur, utilisez plutôt `{ctx.prefix}appel {{ID salon vocal}}`. + \nPour savoir comment récuperer l'id d'un salon vous pouvez faire `{ctx.prefix}getid`.""") + if voice_channel: + canal = self.client.get_channel(voice_channel) + if canal.type.__str__() == "voice": + voice_channels = [canal] + else: + return await ctx.send("Tu as spécifié un channel textuelle et non vocal.") + if len(voice_channels) > 0: + embed = discord.Embed(title = "Réagissez à ce message avec ✋ pour signaler votre présence.", description = f"(attention, je réagis aussi) — Professeur : {ctx.author.mention}") + for channel in voice_channels: + prof = [] + for role in ["Professeur", "professeur", "Prof", "prof"]: + role = discord.utils.get(ctx.guild.roles, name=role) + for user in channel.members: + if role in user.roles and user not in prof: + prof.append(user) + eleve = channel.members + for user in channel.members: + if user in prof: + eleve.remove(user) + value = f"**{len(channel.members)}** personne{'s' if len(channel.members)>1 else ''} connectée{'s' if len(channel.members)>1 else ''}.\nDont {len(eleve)} élève{'s' if len(eleve)>1 else ''} et {len(prof)} professeur{'s' if len(prof)>1 else ''}." + embed.add_field(name = f"🔊 {channel.name}", value = value, inline = False) + message = await ctx.send(embed = embed) + else: + message = await ctx.send("Aucun salon vocal dans ce serveur, réagissez à ce message avec ✋ pour signaler votre présence (attention, je réagis aussi).") + await message.add_reaction(emoji = "✋") + @_appel.error + async def _appel_error(self, ctx, error): + # if isinstance(error, commands.CheckFailure): + # await ctx.send("Tu n'as pas la permission de faire cette commande, demande à un professeur.") + # else: + await ctx.send(f"Une erreur est survenue, syntaxe: `{ctx.prefix}appel [ID salon vocal]`.") + + @commands.command(name='getid', hidden = True) + async def _getid(self, ctx): + await ctx.message.add_reaction(emoji = '✅') + return await ctx.send("Explication sur comment récuperer l'ID d'un utilisateur/salon : https://cdn.discordapp.com/attachments/640312926892195842/780802253258358834/GetID.mp4") diff --git a/src/main.py b/src/main.py index d74d0e7..37f18d7 100644 --- a/src/main.py +++ b/src/main.py @@ -18,6 +18,7 @@ client.load_extension("cogs.music") client.load_extension("cogs.games") client.load_extension("cogs.fun") client.load_extension("cogs.autopublish") +client.load_extension("cogs.school") @client.event async def on_connect(): From 466d8054f729f1883ebb448b0bafe59cde10fd1c Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 15 May 2021 20:22:14 +0200 Subject: [PATCH 042/286] Ajout du bon prefix dans la commande help --- src/cogs/fun.py | 8 ++++---- src/cogs/games.py | 4 ++-- src/cogs/help.py | 4 ++-- src/cogs/internet.py | 10 +++++----- src/cogs/music.py | 18 +++++++++--------- src/cogs/school.py | 2 +- src/cogs/utils.py | 20 ++++++++++---------- 7 files changed, 33 insertions(+), 33 deletions(-) diff --git a/src/cogs/fun.py b/src/cogs/fun.py index 900acac..37f5b59 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -14,7 +14,7 @@ class Fun(commands.Cog): @commands.command(name='iq') async def _iq(self, ctx, *, user = '0'): - """Calcule ton IQ.\n ➡ Syntaxe: .iq [user]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Calcule ton IQ.\n ➡ Syntaxe: {PREFIX}iq [user]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" if user == '0': user = ctx.author await ctx.message.add_reaction(emoji = '✅') @@ -41,7 +41,7 @@ class Fun(commands.Cog): @commands.command(name='love') async def _love(self, ctx, *users: discord.Member): - """Découvre la probabilité que ces deux personnes se mettent en couple.\n ➡ Syntaxe: .love """ + """Découvre la probabilité que ces deux personnes se mettent en couple.\n ➡ Syntaxe: {PREFIX}love """ if len(users) == 2 or len(users) == 1: UneDemande = False if len(users) == 1: @@ -93,7 +93,7 @@ class Fun(commands.Cog): @commands.command(name='8ball', aliases=['8b', '8balls']) async def _8ball(self, ctx, *, question): - """Répond à ta question 🔮.\n ➡ Syntaxe: .8ball/8b ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Répond à ta question 🔮.\n ➡ Syntaxe: {PREFIX}8ball/8b ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" reponses=["c'est sûr.","il en est décidément ainsi.","incontestablement.","oui sans aucun doute.","tu peux t'y fier.","tel que je le vois, oui.","c'est le plus probable.", "cela montre de bonnes perspectives.","certes.","les signes indiquent que oui.","ma réponse est oui.","ta question est trop floue, réessaie.","redemandes plus tard stp.", "je ferais mieux de pas te le dire maintenant...","je ne peux pas le prédire actuellement :/","concentre-toi et redemande.","n'y comptes pas trop.","ma réponse est non.", @@ -106,7 +106,7 @@ class Fun(commands.Cog): @commands.command(name='pileouface', aliases=['pf']) async def _pileouface(self, ctx): - """Pile ou face.\n ➡ Syntaxe: .pileouface/pf""" + """Pile ou face.\n ➡ Syntaxe: {PREFIX}pileouface/pf""" await ctx.message.add_reaction(emoji = '✅') return await ctx.send(f"{'Pile' if randint(0,1) == 1 else 'Face'} !") diff --git a/src/cogs/games.py b/src/cogs/games.py index bf5236a..e7f49f6 100644 --- a/src/cogs/games.py +++ b/src/cogs/games.py @@ -15,7 +15,7 @@ class Games(commands.Cog): @commands.command(name='chifumi', aliases = ["shifumi", "ppc"]) async def _chifumi(self, ctx, *, choix): - """Un simple Chifumi contre le bot.\n ➡ Syntaxe: .chifumi/shifumi/ppc """ + """Un simple Chifumi contre le bot.\n ➡ Syntaxe: {PREFIX}chifumi/shifumi/ppc """ choix_jeu = ["Pierre ✊", "Papier 🧻", "Ciseaux ✂"] orditxt = choice(choix_jeu) @@ -47,7 +47,7 @@ class Games(commands.Cog): @commands.command(name='plusoumoins', aliases = ['+ou-', '+-']) async def _plusoumoins(self, ctx): - """Un plus ou moins entre 1 et 100.\n ➡ Syntaxe: .plusoumoins/+ou-/+-⁢⁢⁢⁢⁢""" + """Un plus ou moins entre 1 et 100.\n ➡ Syntaxe: {PREFIX}plusoumoins/+ou-/+-⁢⁢⁢⁢⁢""" if str(ctx.author.id) in self.guessing_game: return await ctx.send("Tu es déjà en partie.") guess = 5 diff --git a/src/cogs/help.py b/src/cogs/help.py index 6ec79ac..cfbd76c 100644 --- a/src/cogs/help.py +++ b/src/cogs/help.py @@ -13,7 +13,7 @@ class Help(commands.Cog): @commands.command(name='help') async def _help(self, ctx, *cog): - """Affiche toutes les commandes du bot.\n ➡ Syntaxe: .help [catégorie]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Affiche toutes les commandes du bot.\n ➡ Syntaxe: {PREFIX}help [catégorie]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" if not cog: """Liste des Cog""" halp=discord.Embed(title = 'Liste des catégories et commandes sans catégorie', @@ -52,7 +52,7 @@ class Help(commands.Cog): halp = discord.Embed(title = f'{cog[0]} - Liste des commandes', description = self.client.cogs[cog[0]].__doc__, color = discord.Colour.random()) for c in self.client.get_cog(y).get_commands(): if not c.hidden: - cmds_help = str(c.help).split("\n") + cmds_help = str(c.help).replace("{PREFIX}", ctx.prefix).split("\n") del cmds_help[0] backslash = '\n' halp.add_field(name = f"`{ctx.prefix}{c.name}` - {str(c.help).split(backslash)[0]}", value = f"{''.join(cmds_help)}\u200b", inline = False) diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 10b5290..6bf9dd0 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -32,7 +32,7 @@ class Internet(commands.Cog): @commands.command(name='memes', aliases = ['meme']) async def _memes(self, ctx, *, args = None): - """Envois un meme de reddit.\n ➡ Syntaxe: .memes/meme [subreddit]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Envois un meme de reddit.\n ➡ Syntaxe: {PREFIX}memes/meme [subreddit]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" if args: # s'il y a un subreddit de défini subredditchoix = args @@ -87,7 +87,7 @@ class Internet(commands.Cog): @commands.command(name='cat', aliases = ['chat']) async def _cat(self, ctx): - """Te montre un magnifique chat\n ➡ Syntaxe: .cat/chat""" + """Te montre un magnifique chat\n ➡ Syntaxe: {PREFIX}cat/chat""" if ctx.author.nick: name = f"{ctx.author.nick} ({ctx.author.name}#{ctx.author.discriminator})" @@ -103,7 +103,7 @@ class Internet(commands.Cog): @commands.command(name='dog', aliases = ['chien']) async def _dog(self, ctx): - """Te montre un magnifique chien\n ➡ Syntaxe: .dog/chien""" + """Te montre un magnifique chien\n ➡ Syntaxe: {PREFIX}dog/chien""" if ctx.author.nick: name = f"{ctx.author.nick} ({ctx.author.name}#{ctx.author.discriminator})" @@ -119,7 +119,7 @@ class Internet(commands.Cog): @commands.command(name='sexe', aliases=['sexes', 'nude', 'nudes', 'nsfw']) async def _sexe(self, ctx, *, choice_of_nsfw = None): - """Envois une image coquine. (NSFW)\n ➡ Syntaxe: .sexe/sexes/nude/nudes [butts/boobs]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Envois une image coquine. (NSFW)\n ➡ Syntaxe: {PREFIX}sexe/sexes/nude/nudes [butts/boobs]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" liste_hot = ['butts', 'boobs'] if choice_of_nsfw in liste_hot: pass @@ -138,7 +138,7 @@ class Internet(commands.Cog): @commands.command(name='news', aliases=['rss']) async def _news(self, ctx, *, arg = ""): - """Info random dans le domaine de l'informatique\n ➡ Syntaxe: .news/rss [site/liste]""" + """Info random dans le domaine de l'informatique\n ➡ Syntaxe: {PREFIX}news/rss [site/liste]""" rss_website = { "anandtech": "https://www.anandtech.com/rss/", diff --git a/src/cogs/music.py b/src/cogs/music.py index b301e7b..26af84c 100644 --- a/src/cogs/music.py +++ b/src/cogs/music.py @@ -301,7 +301,7 @@ class Music(commands.Cog): @commands.command(name='join', aliases=['j'], invoke_without_subcommand=True) async def _summon(self, ctx: commands.Context, *, channel: discord.VoiceChannel = None): - """Se connecte au salon vocal.\n ➡ Syntaxe: .connect/join⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Se connecte au salon vocal.\n ➡ Syntaxe: {PREFIX}connect/join⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" if not channel and not ctx.author.voice: await ctx.send("Aucun channel à rejoindre. Connecte toi dans un vocal ou donne-moi son id.") @@ -317,7 +317,7 @@ class Music(commands.Cog): @commands.command(name='stop', aliases=['disconnect', 'dc']) async def _leave(self, ctx: commands.Context): - """Arrête la chanson en cours de lecture et quitte le salon vocal.\n ➡ Syntaxe: .disconnect/dc/stop⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Arrête la chanson en cours de lecture et quitte le salon vocal.\n ➡ Syntaxe: {PREFIX}disconnect/dc/stop⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" if not ctx.voice_state.voice: embed = discord.Embed(description = f"Tape `{ctx.prefix}play ` pour jouer quelque chose ou `{ctx.prefix}join [id]` pour me connecter à un salon vocal.", color = 0xC41B1B) @@ -330,7 +330,7 @@ class Music(commands.Cog): @commands.command(name='volume', aliases=['vol']) async def _volume(self, ctx: commands.Context, *, volume: int = False): - """Modifie le volume du bot (entre 1 et 100).\n ➡ Syntaxe: .volume/vol [1;100]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Modifie le volume du bot (entre 1 et 100).\n ➡ Syntaxe: {PREFIX}volume/vol [1;100]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" if not ctx.voice_state.is_playing: return await ctx.send("Rien n'est joué pour le moment.") @@ -346,7 +346,7 @@ class Music(commands.Cog): @commands.command(name='now', aliases=['current', 'playing', 'np']) async def _now(self, ctx: commands.Context): - """Affiche des informations sur la chanson en cours de lecture.\n ➡ Syntaxe: .now/current⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢/playing/np""" + """Affiche des informations sur la chanson en cours de lecture.\n ➡ Syntaxe: {PREFIX}now/current⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢/playing/np""" await ctx.send(embed=ctx.voice_state.current.create_embed()) @@ -383,7 +383,7 @@ class Music(commands.Cog): @commands.command(name='skip', aliases=['s']) async def _skip(self, ctx: commands.Context): - """Passe la chanson.\n ➡ Syntaxe: .skip/s""" + """Passe la chanson.\n ➡ Syntaxe: {PREFIX}skip/s""" if not ctx.voice_state.is_playing: embed = discord.Embed(description = f"Tape `{ctx.prefix}play ` pour jouer quelque chose.", color = 0xC41B1B) @@ -396,7 +396,7 @@ class Music(commands.Cog): @commands.command(name='queue', aliases=['q', 'playlist']) async def _queue(self, ctx: commands.Context, *, page: int = 1): - """Affiche la file d'attente des chansons à venir.\n ➡ Syntaxe: .queue/q⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢/playlist [page]""" + """Affiche la file d'attente des chansons à venir.\n ➡ Syntaxe: {PREFIX}queue/q⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢/playlist [page]""" if len(ctx.voice_state.songs) == 0: embed = discord.Embed(description = f"Tape `{ctx.prefix}play ` pour jouer quelque chose.", color = 0xC41B1B) @@ -447,7 +447,7 @@ class Music(commands.Cog): @commands.command(name='loop', aliases=['repeat']) async def _loop(self, ctx: commands.Context): - """Répète la chanson actuellement en lecture.\n ➡ Syntaxe: .loop/repeat""" + """Répète la chanson actuellement en lecture.\n ➡ Syntaxe: {PREFIX}loop/repeat""" if not ctx.voice_state.is_playing: embed = discord.Embed(description = f"Tape `{ctx.prefix}play ` pour jouer quelque chose.", color = 0xC41B1B) @@ -461,7 +461,7 @@ class Music(commands.Cog): @commands.command(name='play', aliases=['p']) async def _play(self, ctx: commands.Context, *, search: str): - """Recherche une chanson sur les sites compatibles avec YoutubeDL si aucun URL n'est donné et l'ajoute à la file d'attente.\n ➡ Syntaxe: .play/p⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Recherche une chanson sur les sites compatibles avec YoutubeDL si aucun URL n'est donné et l'ajoute à la file d'attente.\n ➡ Syntaxe: {PREFIX}play/p⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" if not ctx.voice_state.voice: await ctx.invoke(self._summon) @@ -489,7 +489,7 @@ class Music(commands.Cog): @commands.command(name='lyrics', aliases = ['l', 'lyric']) async def _lyrics(self, ctx, *, song: str = None): - """Affiche les paroles de la musique en cours, ou de la chanson spécifiée.\n ➡ Syntaxe: .lyrics/lyric/l (musique)⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Affiche les paroles de la musique en cours, ou de la chanson spécifiée.\n ➡ Syntaxe: {PREFIX}lyrics/lyric/l (musique)⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" if song or ctx.voice_state.is_playing: if not song: song = f"{ctx.voice_state.current.title()}" diff --git a/src/cogs/school.py b/src/cogs/school.py index 1e1a88a..2fb4b29 100644 --- a/src/cogs/school.py +++ b/src/cogs/school.py @@ -13,7 +13,7 @@ class School(commands.Cog): @commands.command(name='appel') # @commands.has_any_role("Professeur", "professeur", "Prof", "prof") async def _appel(self, ctx, *, voice_channel: int = None): - """Fais l'appel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .appel [ID salon vocal]""" + """Fais l'appel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}appel [ID salon vocal]""" voice_channels = [] voice_channels.extend(ctx.guild.voice_channels) await ctx.message.add_reaction(emoji = "✅") diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 2b1c47f..020a0b2 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -18,7 +18,7 @@ class Utils(commands.Cog): @commands.command(name='ping') async def _ping(self, ctx, *, question = '0'): - """Affiche mon ping.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .ping [help]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Affiche mon ping.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}ping [help]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" if question == 'help': return await ctx.send(embed = discord.Embed(color = discord.Colour.random(), description = ":hourglass: correspond au temps entre deux battements de cœurs\n\n:stopwatch: correspond au temps que met le client a calculer le ping\n\n:heartbeat: correspond au temps que met le client a réagir au messages")) else: @@ -32,7 +32,7 @@ class Utils(commands.Cog): @commands.command(name='avatar') async def _avatar(self, ctx, *, user = '0'): - """Affiche ton avatar ou celui que tu mentionnes.\n ➡ Syntaxe: .avatar [user]""" + """Affiche ton avatar ou celui que tu mentionnes.\n ➡ Syntaxe: {PREFIX}avatar [user]""" if user == '0': user = ctx.author else: @@ -45,7 +45,7 @@ class Utils(commands.Cog): @commands.command(name='calc') async def _calc(self, ctx, *, msg): - """Calculatrice.\n ➡ Syntaxe: .calc ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Calculatrice.\n ➡ Syntaxe: {PREFIX}calc ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" equation = msg.replace('^', '**').replace('x', '*').replace('×', '*').replace('÷', '/').replace('≥', '>=').replace('≤', '<=') try: try: @@ -133,7 +133,7 @@ class Utils(commands.Cog): @commands.command(name='memo', aliases = ['note']) async def _memo(self, ctx, *, text): - """T'envoie un petit memo par message privé.\n ➡ Syntaxe: .memo/note ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """T'envoie un petit memo par message privé.\n ➡ Syntaxe: {PREFIX}memo/note ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" if len(text) <= 5: await ctx.message.add_reaction(emoji = '❌') return await ctx.send("Ta note doit au moins faire 5 caractères.") @@ -154,7 +154,7 @@ class Utils(commands.Cog): @commands.command(name='infos', aliases = ['info']) async def _infos(self, ctx): - """Donne des infos sur le bot.\n ➡ Syntaxe: .infos/info⁢""" + """Donne des infos sur le bot.\n ➡ Syntaxe: {PREFIX}infos/info⁢""" appinfo = await self.client.application_info() embed = discord.Embed(color = discord.Colour.random()) @@ -215,7 +215,7 @@ class Utils(commands.Cog): @commands.command(name='amongus') async def _amongus(self, ctx, *, map = "0"): - """Affiche la carte voulue d'Among Us.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .amongus ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Affiche la carte voulue d'Among Us.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}amongus ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" if map.lower() in self._map_list_among_us("mira"): image = "https://i.imgur.com/6ijrH1h.jpg" embed = discord.Embed(title = f"Map Mira HQ d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") @@ -245,7 +245,7 @@ class Utils(commands.Cog): @commands.command(name='whois') async def _whois(self, ctx, *user: discord.Member): - """Affiche les infos sur l'utilisateur.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .whois [user]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Affiche les infos sur l'utilisateur.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}whois [user]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" if len(user) <= 1: if user == (): user = [ctx.author] @@ -357,7 +357,7 @@ class Utils(commands.Cog): @commands.command(name='sondage') async def _sondage(self, ctx, *args): - """Fais un sondage.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .sondage "" "" "" "" """ + """Fais un sondage.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}sondage "" "" "" "" """ args = list(args) if len(args) > 2: question = args[0] @@ -398,7 +398,7 @@ class Utils(commands.Cog): @commands.command(name='avis', aliases=['vote']) async def _avis(self, ctx, *args): - """Demande un avis.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .avis/vote "[Titre]" "" """ + """Demande un avis.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}avis/vote "[Titre]" "" """ args = list(args) if len(args) > 2 or len(args) == 0: return await ctx.send("Désolé, la syntaxe est mauvaise.") @@ -419,7 +419,7 @@ class Utils(commands.Cog): @commands.command(name='reminder', aliases=["remind", "remindme"]) async def _reminder(self, ctx, time, *, reminder): - """Met en place un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: .reminder/remind/remindme [@] """ + """Met en place un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminder/remind/remindme [@] """ embed = discord.Embed(color = 0xC41B1B) seconds = 0 timestamp = datetime.utcnow() From c60fbcdfbb7eb3b021209628cbe7b74a7841737f Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 15 May 2021 20:36:22 +0200 Subject: [PATCH 043/286] bump to 1.3 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c87b30c..02f9149 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Bot developed with [discord.py](https://github.com/Rapptz/discord.py) (rewrite) - FRENCH -[![Version](https://img.shields.io/badge/version-1.2-green?style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/releases/latest) +[![Version](https://img.shields.io/badge/version-1.3-green?style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/releases/latest) [![Docker Stars](https://img.shields.io/docker/stars/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/r/mylloon/kassoubot) [![Docker Pulls](https://img.shields.io/docker/pulls/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/r/mylloon/kassoubot) [![Github stars](https://img.shields.io/github/stars/Confrerie-du-Kassoulait/kassoubot?label=Github%20Stars&style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/stargazers) From b617b37085f0c9b5338a76d03969a48315be1af1 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 19 May 2021 09:06:49 +0200 Subject: [PATCH 044/286] better footer in calc --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 020a0b2..e878293 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -75,7 +75,7 @@ class Utils(commands.Cog): equation = f"'{equation}' arrondi à 2" equation = equation.replace('*', '×').replace('/', '÷').replace('>=', '≥').replace('<=', '≤') embed = discord.Embed(color = discord.Colour.random(), title = 'Calculatrice') - embed.set_footer(text = ctx.author) + embed.set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) embed.add_field(name = 'Calcul :', value = equation, inline = False) embed.add_field(name = 'Réponse :', value = answer.replace('False', 'Faux').replace('True', 'Vrai'), inline = False) From eba1de37f9c14428e7f764deb87dbd3a919ff1d3 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 19 May 2021 09:11:11 +0200 Subject: [PATCH 045/286] fix #3 appel command --- src/cogs/school.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/school.py b/src/cogs/school.py index 2fb4b29..8cf7260 100644 --- a/src/cogs/school.py +++ b/src/cogs/school.py @@ -18,7 +18,7 @@ class School(commands.Cog): voice_channels.extend(ctx.guild.voice_channels) await ctx.message.add_reaction(emoji = "✅") limite_voice_channels = 7 - if len(voice_channels) > limite_voice_channels: + if len(voice_channels) > limite_voice_channels and not voice_channel: return await ctx.send(f"""Désolé mais il y a plus de {limite_voice_channels} salons vocaux sur ce serveur, utilisez plutôt `{ctx.prefix}appel {{ID salon vocal}}`. \nPour savoir comment récuperer l'id d'un salon vous pouvez faire `{ctx.prefix}getid`.""") if voice_channel: From d913f7758f11af3139dbdb0f9fb8ba6140595242 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 26 May 2021 18:27:17 +0200 Subject: [PATCH 046/286] adding ctx to sondage and avis commands --- src/cogs/utils.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index e878293..5b8bab3 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -386,7 +386,7 @@ class Utils(commands.Cog): shuffle(emojis_chosen) for i in range(len(args[1:])): message += f"{emojis_chosen[i]} -> {propositions[i]}\n" - embed = discord.Embed(title = question, description = message, color = discord.Colour.random()).set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) + embed = discord.Embed(title = question, description = message, color = discord.Colour.random()).set_footer(text = f"Sondage de {self._userOrNick(ctx.author)}", icon_url = ctx.author.avatar_url) sondage = await ctx.send(embed = embed) for i in range(len(args[1:])): await sondage.add_reaction(emoji = emojis_chosen[i]) @@ -410,7 +410,7 @@ class Utils(commands.Cog): for findedId in re.findall(r'\d+', titre): # récupération mention dans titre titre = self._cleanUser(ctx, titre, findedId) args = args[1:] - embed = discord.Embed(title = titre, description = self._cleanCodeStringWithMentionAndURLs(args[0]), color = discord.Colour.random()).set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) + embed = discord.Embed(title = titre, description = self._cleanCodeStringWithMentionAndURLs(args[0]), color = discord.Colour.random()).set_footer(text = f"Sondage de {self._userOrNick(ctx.author)}", icon_url = ctx.author.avatar_url) message = await ctx.send(embed = embed) reactions = ['✅', '🤷', '❌'] for i in reactions: From 32e2e5cd75d97367e2c08c0e4b12e1124ff91805 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 28 May 2021 13:29:52 +0200 Subject: [PATCH 047/286] remove mention in citation --- src/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.py b/src/main.py index 37f18d7..3a3d607 100644 --- a/src/main.py +++ b/src/main.py @@ -171,7 +171,7 @@ async def on_message(message): await message.channel.send(embed = embed) await message.delete() else: - await message.reply(embed = embed) + await message.reply(embed = embed, mention_author = False) except Exception as e: e = str(e) if not "invalid literal for int() with base 10:" in e or not "404 Not Found (error code: 10008)" in e: # faute de frappe / message supprimé From 7caa86075335c564a69e9abdcc9ee5c1c3c9e721 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 28 May 2021 13:52:37 +0200 Subject: [PATCH 048/286] =?UTF-8?q?r=C3=A9organisation=20des=20prints?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main.py b/src/main.py index 3a3d607..4db72ee 100644 --- a/src/main.py +++ b/src/main.py @@ -1,4 +1,4 @@ -print("Connexion à Discord...") +print("Chargement des extensions & librairie...", end = " ") import discord, re, pytz, os from discord.ext import commands @@ -10,7 +10,6 @@ customTimezone = os.environ['TIMEZONE'] client = commands.Bot(command_prefix = customPrefix, case_insensitive = True, intents = discord.Intents.all()) -print("Chargement des extensions & librairie...") client.load_extension("cogs.help") client.load_extension("cogs.utils") client.load_extension("cogs.internet") @@ -19,10 +18,11 @@ client.load_extension("cogs.games") client.load_extension("cogs.fun") client.load_extension("cogs.autopublish") client.load_extension("cogs.school") +print("Terminé !") @client.event async def on_connect(): - print(f"Connecté.") + print(f"Connecté !") @client.event async def on_ready(): @@ -219,4 +219,5 @@ def goodTimezone(date, type): elif type == 1: return str(pytz.timezone(customTimezone).fromutc(date))[:-13].replace('-', '/').replace(' ', ' à ') +print("Connexion à Discord...", end = " ") client.run(os.environ['TOKEN_DISCORD']) From b1f2e3ad39269c02a0f840ba80b5f4f4c7743857 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 28 May 2021 14:03:34 +0200 Subject: [PATCH 049/286] adding test cog for new slash commands --- requirements.txt | 1 + src/cogs/slash.py | 17 +++++++++++++++++ src/main.py | 3 +++ 3 files changed, 21 insertions(+) create mode 100644 src/cogs/slash.py diff --git a/requirements.txt b/requirements.txt index 920fa85..2b3444a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,3 +4,4 @@ asyncpraw==7.2.0 # reddit youtube-dl==2021.4.26 # music lyricsgenius==3.0.1 # lyrics feedparser==6.0.2 # rss feed (news) +discord-py-slash-command==1.2.0 # slash commands diff --git a/src/cogs/slash.py b/src/cogs/slash.py new file mode 100644 index 0000000..ec5c133 --- /dev/null +++ b/src/cogs/slash.py @@ -0,0 +1,17 @@ +import discord +from discord.ext import commands +from discord_slash import cog_ext, SlashContext + +def setup(client): + client.add_cog(Slash(client)) + +class Slash(commands.Cog): + """Slash commands test.""" + + def __init__(self, client): + self.client = client + + @cog_ext.cog_slash(name="test") + async def _test(self, ctx: SlashContext): + embed = discord.Embed(title="embed test") + await ctx.send(content="test", embeds=[embed]) diff --git a/src/main.py b/src/main.py index 4db72ee..fdf7a32 100644 --- a/src/main.py +++ b/src/main.py @@ -1,6 +1,7 @@ print("Chargement des extensions & librairie...", end = " ") import discord, re, pytz, os +from discord_slash import SlashCommand from discord.ext import commands from random import choice from datetime import datetime @@ -9,6 +10,7 @@ customPrefix = os.environ['PREFIX'] customTimezone = os.environ['TIMEZONE'] client = commands.Bot(command_prefix = customPrefix, case_insensitive = True, intents = discord.Intents.all()) +slash = SlashCommand(client, sync_commands = True, sync_on_cog_reload = True) client.load_extension("cogs.help") client.load_extension("cogs.utils") @@ -18,6 +20,7 @@ client.load_extension("cogs.games") client.load_extension("cogs.fun") client.load_extension("cogs.autopublish") client.load_extension("cogs.school") +client.load_extension("cogs.slash") print("Terminé !") @client.event From 80963051210fd8995e9d1b6e5c0deb829b041165 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 28 May 2021 14:10:05 +0200 Subject: [PATCH 050/286] adding ping command for the slash test --- src/cogs/slash.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/cogs/slash.py b/src/cogs/slash.py index ec5c133..7bee9a4 100644 --- a/src/cogs/slash.py +++ b/src/cogs/slash.py @@ -1,4 +1,5 @@ import discord +import time from discord.ext import commands from discord_slash import cog_ext, SlashContext @@ -11,7 +12,12 @@ class Slash(commands.Cog): def __init__(self, client): self.client = client - @cog_ext.cog_slash(name="test") - async def _test(self, ctx: SlashContext): - embed = discord.Embed(title="embed test") - await ctx.send(content="test", embeds=[embed]) + @cog_ext.cog_slash(name="pingSlash", description = "Affiche mon ping.") + async def _pingSlash(self, ctx: SlashContext): + now = int(round(time.time() * 1000)) + ping = now - int(round(ctx.message.created_at.timestamp() * 1000)) + embed = discord.Embed(description = 'Pinging...') + message = await ctx.send(embed = embed) + ping2 = int(round(time.time() * 1000)) - now + await message.edit(embed = discord.Embed(color = discord.Colour.random(), description = f':hourglass: {round(self.client.latency * 1000)} ms\n\n:stopwatch: {ping2} ms\n\n:heartbeat: {ping} ms')) + await ctx.message.add_reaction(emoji = '✅') From 610b4c4065c523e404363f219f73b05885370786 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 28 May 2021 14:13:14 +0200 Subject: [PATCH 051/286] better import --- src/cogs/fun.py | 3 ++- src/cogs/internet.py | 7 ++++++- src/cogs/utils.py | 8 ++++++-- src/main.py | 5 ++++- 4 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/cogs/fun.py b/src/cogs/fun.py index 37f5b59..3e6e46f 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -1,4 +1,5 @@ -import discord, re +import discord +import re from discord.ext import commands from random import randint, choice from datetime import timedelta diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 6bf9dd0..22bf83d 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -1,4 +1,9 @@ -import discord, json, requests, time, feedparser, os +import discord +import json +import requests +import time +import feedparser +import os from discord.ext import commands from random import choice from asyncpraw import Reddit diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 5b8bab3..ce936c6 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -1,9 +1,13 @@ -import discord, pytz, time, os +import discord +import pytz +import time +import os +import re +import asyncio from discord.ext import commands from random import randint, shuffle from datetime import datetime from pytz import timezone -import re, asyncio def setup(client): client.add_cog(Utils(client)) diff --git a/src/main.py b/src/main.py index 4db72ee..0a0b365 100644 --- a/src/main.py +++ b/src/main.py @@ -1,6 +1,9 @@ print("Chargement des extensions & librairie...", end = " ") -import discord, re, pytz, os +import discord +import re +import pytz +import os from discord.ext import commands from random import choice from datetime import datetime From 6941d251d43564fe579c956c2a69c5e493579405 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 28 May 2021 14:14:22 +0200 Subject: [PATCH 052/286] fix useless import --- src/main.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main.py b/src/main.py index 0a0b365..ce93c94 100644 --- a/src/main.py +++ b/src/main.py @@ -2,7 +2,6 @@ print("Chargement des extensions & librairie...", end = " ") import discord import re -import pytz import os from discord.ext import commands from random import choice @@ -202,9 +201,9 @@ async def on_message_delete(message): embed.set_author(name = user_or_nick(message.author), icon_url = message.author.avatar_url) if not user_suppressed: - embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1)}\nSupprimé le {datetime.now(pytz.timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") + embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1)}\nSupprimé le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") else: - embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1)}\nSupprimé par {user_or_nick(user_suppressed)} le {datetime.now(pytz.timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") + embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1)}\nSupprimé par {user_or_nick(user_suppressed)} le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") await channel.send(embed = embed) # ne fonctionne pas quand un message a été supprimé avant que le bot ai démarré @@ -218,9 +217,9 @@ def user_or_nick(user): def goodTimezone(date, type): if type == 0: - return str(pytz.timezone(customTimezone).fromutc(date))[:-13].replace('-', '/').split() + return str(timezone(customTimezone).fromutc(date))[:-13].replace('-', '/').split() elif type == 1: - return str(pytz.timezone(customTimezone).fromutc(date))[:-13].replace('-', '/').replace(' ', ' à ') + return str(timezone(customTimezone).fromutc(date))[:-13].replace('-', '/').replace(' ', ' à ') print("Connexion à Discord...", end = " ") client.run(os.environ['TOKEN_DISCORD']) From 414c4352f10c299a3566f56da26daf58d75e06fa Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 28 May 2021 17:52:23 +0200 Subject: [PATCH 053/286] update how to add the bot with the right perms --- README.md | 6 +++--- src/cogs/slash.py | 15 ++++----------- 2 files changed, 7 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 02f9149..ac54f5a 100644 --- a/README.md +++ b/README.md @@ -29,9 +29,9 @@ To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and ## __Add the bot to your server__ -- [This site](https://discordapi.com/permissions.html) allows you to choose which permissions to add by default to the bot. - - Choose *Administrator* so you don't get in over your head. - - Copy and paste the ID of your bot in *Client ID* found [here](https://discord.com/developers/applications) and go to the link at the bottom of the page. +- In the [Discord Dev Portal](https://discord.com/developers/applications) create an application, and make sure it's a `Bot` (third tab). +- To invite it, go to the `OAuth2` (second tab) tab, select the scopes `bot` (required) and `applications.commands` (for the slashs commands) and in the bot permissions select `Administrator` (You can select manually at your own risk). +- You have the link above between the two blocks scope and permissions ## __Features__ diff --git a/src/cogs/slash.py b/src/cogs/slash.py index 7bee9a4..ad0795a 100644 --- a/src/cogs/slash.py +++ b/src/cogs/slash.py @@ -1,5 +1,4 @@ -import discord -import time + from discord.ext import commands from discord_slash import cog_ext, SlashContext @@ -12,12 +11,6 @@ class Slash(commands.Cog): def __init__(self, client): self.client = client - @cog_ext.cog_slash(name="pingSlash", description = "Affiche mon ping.") - async def _pingSlash(self, ctx: SlashContext): - now = int(round(time.time() * 1000)) - ping = now - int(round(ctx.message.created_at.timestamp() * 1000)) - embed = discord.Embed(description = 'Pinging...') - message = await ctx.send(embed = embed) - ping2 = int(round(time.time() * 1000)) - now - await message.edit(embed = discord.Embed(color = discord.Colour.random(), description = f':hourglass: {round(self.client.latency * 1000)} ms\n\n:stopwatch: {ping2} ms\n\n:heartbeat: {ping} ms')) - await ctx.message.add_reaction(emoji = '✅') + @cog_ext.cog_slash(name="pingg") + async def pingg(self, ctx: SlashContext): + await ctx.send(content="Pong!") From ed2d7b9a2e9bc97fd927ecebffae2a643c4e7ed2 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 28 May 2021 19:59:31 +0200 Subject: [PATCH 054/286] adding first true command who support the slash --- src/cogs/fun.py | 13 +++++++++---- src/cogs/slash.py | 16 ---------------- src/main.py | 1 - 3 files changed, 9 insertions(+), 21 deletions(-) delete mode 100644 src/cogs/slash.py diff --git a/src/cogs/fun.py b/src/cogs/fun.py index 37f5b59..85b143b 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -2,6 +2,7 @@ import discord, re from discord.ext import commands from random import randint, choice from datetime import timedelta +from discord_slash import cog_ext, SlashContext def setup(client): client.add_cog(Fun(client)) @@ -92,8 +93,8 @@ class Fun(commands.Cog): await ctx.send(str(error).replace('Member "', "Le membre **").replace('" not found', "** n'as pas été trouvé.")) @commands.command(name='8ball', aliases=['8b', '8balls']) - async def _8ball(self, ctx, *, question): - """Répond à ta question 🔮.\n ➡ Syntaxe: {PREFIX}8ball/8b ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + async def _8ball(self, ctx): + """Répond à ta question 🔮.\n ➡ Syntaxe: {PREFIX}8ball/8b⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" reponses=["c'est sûr.","il en est décidément ainsi.","incontestablement.","oui sans aucun doute.","tu peux t'y fier.","tel que je le vois, oui.","c'est le plus probable.", "cela montre de bonnes perspectives.","certes.","les signes indiquent que oui.","ma réponse est oui.","ta question est trop floue, réessaie.","redemandes plus tard stp.", "je ferais mieux de pas te le dire maintenant...","je ne peux pas le prédire actuellement :/","concentre-toi et redemande.","n'y comptes pas trop.","ma réponse est non.", @@ -105,10 +106,14 @@ class Fun(commands.Cog): await ctx.send(f"Mauvaise syntaxe : `{ctx.prefix}8ball/8b/8balls `.") @commands.command(name='pileouface', aliases=['pf']) - async def _pileouface(self, ctx): + async def _pileouface(self, ctx, fromSlash = False): """Pile ou face.\n ➡ Syntaxe: {PREFIX}pileouface/pf""" - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') return await ctx.send(f"{'Pile' if randint(0,1) == 1 else 'Face'} !") + @cog_ext.cog_slash(name="pileouface", description = "Pile ou face.") + async def __pileouface(self, ctx: SlashContext): + await self._pileouface(ctx, True) @commands.command(name='mock') async def _mock(self, ctx): diff --git a/src/cogs/slash.py b/src/cogs/slash.py deleted file mode 100644 index ad0795a..0000000 --- a/src/cogs/slash.py +++ /dev/null @@ -1,16 +0,0 @@ - -from discord.ext import commands -from discord_slash import cog_ext, SlashContext - -def setup(client): - client.add_cog(Slash(client)) - -class Slash(commands.Cog): - """Slash commands test.""" - - def __init__(self, client): - self.client = client - - @cog_ext.cog_slash(name="pingg") - async def pingg(self, ctx: SlashContext): - await ctx.send(content="Pong!") diff --git a/src/main.py b/src/main.py index fdf7a32..8a71588 100644 --- a/src/main.py +++ b/src/main.py @@ -20,7 +20,6 @@ client.load_extension("cogs.games") client.load_extension("cogs.fun") client.load_extension("cogs.autopublish") client.load_extension("cogs.school") -client.load_extension("cogs.slash") print("Terminé !") @client.event From 4226c1758e3869ea4110b63eb984380aa0f5c470 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 28 May 2021 21:22:43 +0200 Subject: [PATCH 055/286] adding the iq function in the slashs commands --- src/cogs/fun.py | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/src/cogs/fun.py b/src/cogs/fun.py index 85b143b..75bd2b4 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -14,31 +14,42 @@ class Fun(commands.Cog): self.client = client @commands.command(name='iq') - async def _iq(self, ctx, *, user = '0'): - """Calcule ton IQ.\n ➡ Syntaxe: {PREFIX}iq [user]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - if user == '0': + async def _iq(self, ctx, *user): + """Calcule ton QI.\n ➡ Syntaxe: {PREFIX}iq [user]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + fromSlash = False + if user[-1] == True: + fromSlash = user[-1] + user = user[:-1] + if len(user) == 0: user = ctx.author - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') return await ctx.send(f"T'as {randint(randint(-100,0),220)} IQ {user.mention} !") else: + user = user[0] try: user2 = user user2 = user2[2:-1] user2 = user2.replace("!","") user2 = int(user2) user2 = self.client.get_user(user2) - KassouBot = self.client.get_user(740140888373854269) - if user2.id == KassouBot.id: - await ctx.message.add_reaction(emoji = '✅') - return await ctx.send(f"Bah... pas ouf... j'ai juste 100000 IQ :/") + if user2.id == self.client.user.id: + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + return await ctx.send(f"Bah... pas ouf... j'ai juste 100000 de QI :/") else: - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') message = await ctx.send("...") - return await message.edit(content = f"{user2.mention} a {randint(randint(-100,0),220)} IQ !") + return await message.edit(content = f"{user2.mention} a {randint(randint(-100,0),220)} de QI !") except: - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') message = await ctx.send("...") - return await message.edit(content = f"{user} a {randint(randint(-100,0),220)} IQ !") + return await message.edit(content = f"{user} a {randint(randint(-100,0),220)} de QI !") + @cog_ext.cog_slash(name="iq", description = "Calcule ton QI.") + async def __iq(self, ctx, user = ()): + await self._iq(ctx, user, True) @commands.command(name='love') async def _love(self, ctx, *users: discord.Member): @@ -112,7 +123,7 @@ class Fun(commands.Cog): await ctx.message.add_reaction(emoji = '✅') return await ctx.send(f"{'Pile' if randint(0,1) == 1 else 'Face'} !") @cog_ext.cog_slash(name="pileouface", description = "Pile ou face.") - async def __pileouface(self, ctx: SlashContext): + async def __pileouface(self, ctx): await self._pileouface(ctx, True) @commands.command(name='mock') From 2a2fd806744e99d2ae174d443fa368c1e4b0b2bd Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 28 May 2021 21:30:55 +0200 Subject: [PATCH 056/286] fix slash command for the iq --- src/cogs/fun.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/cogs/fun.py b/src/cogs/fun.py index 75bd2b4..ef2bf41 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -17,9 +17,13 @@ class Fun(commands.Cog): async def _iq(self, ctx, *user): """Calcule ton QI.\n ➡ Syntaxe: {PREFIX}iq [user]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" fromSlash = False - if user[-1] == True: - fromSlash = user[-1] - user = user[:-1] + if len(user) > 0: + if user[-1] == True: + fromSlash = user[-1] + user = user[:-1] + if len(user) > 0: + if user[0] == None: + user = user[1:] if len(user) == 0: user = ctx.author if fromSlash != True: @@ -48,7 +52,7 @@ class Fun(commands.Cog): message = await ctx.send("...") return await message.edit(content = f"{user} a {randint(randint(-100,0),220)} de QI !") @cog_ext.cog_slash(name="iq", description = "Calcule ton QI.") - async def __iq(self, ctx, user = ()): + async def __iq(self, ctx, user = None): await self._iq(ctx, user, True) @commands.command(name='love') From 5ce54afa6e247216001908ab7a497608eadf20d5 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 28 May 2021 23:11:07 +0200 Subject: [PATCH 057/286] all available commands in fun cogs added to slash commands --- src/cogs/fun.py | 57 +++++++++++++++++++++++++++++------------------ src/cogs/games.py | 12 ++++++++++ 2 files changed, 47 insertions(+), 22 deletions(-) diff --git a/src/cogs/fun.py b/src/cogs/fun.py index ef2bf41..e4d3be5 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -2,7 +2,7 @@ import discord, re from discord.ext import commands from random import randint, choice from datetime import timedelta -from discord_slash import cog_ext, SlashContext +from discord_slash import cog_ext def setup(client): client.add_cog(Fun(client)) @@ -21,9 +21,6 @@ class Fun(commands.Cog): if user[-1] == True: fromSlash = user[-1] user = user[:-1] - if len(user) > 0: - if user[0] == None: - user = user[1:] if len(user) == 0: user = ctx.author if fromSlash != True: @@ -53,11 +50,19 @@ class Fun(commands.Cog): return await message.edit(content = f"{user} a {randint(randint(-100,0),220)} de QI !") @cog_ext.cog_slash(name="iq", description = "Calcule ton QI.") async def __iq(self, ctx, user = None): - await self._iq(ctx, user, True) + if user == None: + return await self._iq(ctx, True) + else: + return await self._iq(ctx, user, True) @commands.command(name='love') async def _love(self, ctx, *users: discord.Member): """Découvre la probabilité que ces deux personnes se mettent en couple.\n ➡ Syntaxe: {PREFIX}love """ + fromSlash = False + if len(users) > 0: + if users[-1] == True: + fromSlash = users[-1] + users = users[:-1] if len(users) == 2 or len(users) == 1: UneDemande = False if len(users) == 1: @@ -67,7 +72,8 @@ class Fun(commands.Cog): users.append(ctx.author) UneDemande = True if users[0] == users[1]: - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') return await ctx.send("Je suis sûr que cette personne s'aime ! :angry:") if users[0].nick: user1 = list(users[0].nick) @@ -86,16 +92,19 @@ class Fun(commands.Cog): else: taille_du_pls_grand = len(user2_CALC) taille_du_ms_grand = len(user1_CALC) - coef_amour = round(float(len(list(set(user1_CALC).intersection(user2_CALC))) / taille_du_pls_grand),1) * 100 + ((taille_du_pls_grand-taille_du_ms_grand) * 1.5) * 1.7 + coef_amour = round(float(len(list(set(user1_CALC).intersection(user2_CALC))) / taille_du_pls_grand), 1) * 100 + ((taille_du_pls_grand-taille_du_ms_grand) * 1.5) * 1.7 if coef_amour > 100: coef_amour = 100 if UneDemande == True: - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') return await ctx.send(f"Tu as {coef_amour}% de chance de te mettre en couple avec {''.join(user1)}") - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') await ctx.send(f"{''.join(user1)} et {''.join(user2)} ont {coef_amour}% de chance de se mettre en couple !") else: - await ctx.message.add_reaction(emoji = '❌') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '❌') await ctx.send(f"Erreur! Syntaxe : `{ctx.prefix}love [User2]`\n") def _retirerDoublons(self, liste): Newliste = [] @@ -106,29 +115,33 @@ class Fun(commands.Cog): @_love.error async def _love_error(self, ctx, error): await ctx.send(str(error).replace('Member "', "Le membre **").replace('" not found', "** n'as pas été trouvé.")) + @cog_ext.cog_slash(name="love", description = "Découvre la probabilité que ces deux personnes se mettent en couple.") + async def __love(self, ctx, user1 = None, user2 = None): + if user1 != None: + if user2 != None: + return await self._love(ctx, user1, user2, True) + else: + return await self._love(ctx, user1, True) + else: + return await self._love(ctx, True) @commands.command(name='8ball', aliases=['8b', '8balls']) - async def _8ball(self, ctx): + async def _8ball(self, ctx, fromSlash = False): """Répond à ta question 🔮.\n ➡ Syntaxe: {PREFIX}8ball/8b⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" reponses=["c'est sûr.","il en est décidément ainsi.","incontestablement.","oui sans aucun doute.","tu peux t'y fier.","tel que je le vois, oui.","c'est le plus probable.", "cela montre de bonnes perspectives.","certes.","les signes indiquent que oui.","ma réponse est oui.","ta question est trop floue, réessaie.","redemandes plus tard stp.", "je ferais mieux de pas te le dire maintenant...","je ne peux pas le prédire actuellement :/","concentre-toi et redemande.","n'y comptes pas trop.","ma réponse est non.", "mes sources disent que non.", "les perspectives ne sont pas si bonnes...","c'est très douteux."] - await ctx.send(f"{ctx.author.mention}, {choice(reponses)}") + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + return await ctx.send(f"{ctx.author.mention}, {choice(reponses)}") @_8ball.error async def _8ball_error(self, ctx, error): if str(error) == "question is a required argument that is missing.": await ctx.send(f"Mauvaise syntaxe : `{ctx.prefix}8ball/8b/8balls `.") - - @commands.command(name='pileouface', aliases=['pf']) - async def _pileouface(self, ctx, fromSlash = False): - """Pile ou face.\n ➡ Syntaxe: {PREFIX}pileouface/pf""" - if fromSlash != True: - await ctx.message.add_reaction(emoji = '✅') - return await ctx.send(f"{'Pile' if randint(0,1) == 1 else 'Face'} !") - @cog_ext.cog_slash(name="pileouface", description = "Pile ou face.") - async def __pileouface(self, ctx): - await self._pileouface(ctx, True) + @cog_ext.cog_slash(name="8ball", description = "Répond à ta question 🔮.") + async def __8ball(self, ctx): + await self._8ball(ctx, True) @commands.command(name='mock') async def _mock(self, ctx): diff --git a/src/cogs/games.py b/src/cogs/games.py index e7f49f6..6f7cda8 100644 --- a/src/cogs/games.py +++ b/src/cogs/games.py @@ -2,6 +2,7 @@ import discord from discord.ext import commands from random import randint, choice import asyncio +from discord_slash import cog_ext def setup(client): client.add_cog(Games(client)) @@ -91,3 +92,14 @@ class Games(commands.Cog): await ctx.send(f"Erreur dans la réponse {ctx.author.mention}, merci de n'écrire qu'un nombre. Tapez `stop` pour arrêter le jeu.") del self.guessing_game[str(ctx.author.id)] await ctx.send(f"T'as pas trouvé {ctx.author.mention}... dommage, c'était {number}.") + + + @commands.command(name='pileouface', aliases=['pf']) + async def _pileouface(self, ctx, fromSlash = False): + """Pile ou face.\n ➡ Syntaxe: {PREFIX}pileouface/pf""" + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + return await ctx.send(f"{'Pile' if randint(0,1) == 1 else 'Face'} !") + @cog_ext.cog_slash(name="pileouface", description = "Pile ou face.") + async def __pileouface(self, ctx): + await self._pileouface(ctx, True) From 4b25f756f7733cd3e1ba6a0984f309c302927be0 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 28 May 2021 23:44:52 +0200 Subject: [PATCH 058/286] fixing errors in slash commands --- src/cogs/fun.py | 13 +++++-------- src/cogs/games.py | 18 +++++++++++++----- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/cogs/fun.py b/src/cogs/fun.py index e4d3be5..8b52dc9 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -116,14 +116,11 @@ class Fun(commands.Cog): async def _love_error(self, ctx, error): await ctx.send(str(error).replace('Member "', "Le membre **").replace('" not found', "** n'as pas été trouvé.")) @cog_ext.cog_slash(name="love", description = "Découvre la probabilité que ces deux personnes se mettent en couple.") - async def __love(self, ctx, user1 = None, user2 = None): - if user1 != None: - if user2 != None: - return await self._love(ctx, user1, user2, True) - else: - return await self._love(ctx, user1, True) + async def __love(self, ctx, user1: discord.Member, user2: discord.Member = None): + if user2 != None: + return await self._love(ctx, user1, user2, True) else: - return await self._love(ctx, True) + return await self._love(ctx, user1, True) @commands.command(name='8ball', aliases=['8b', '8balls']) async def _8ball(self, ctx, fromSlash = False): @@ -140,7 +137,7 @@ class Fun(commands.Cog): if str(error) == "question is a required argument that is missing.": await ctx.send(f"Mauvaise syntaxe : `{ctx.prefix}8ball/8b/8balls `.") @cog_ext.cog_slash(name="8ball", description = "Répond à ta question 🔮.") - async def __8ball(self, ctx): + async def __8ball(self, ctx, question): await self._8ball(ctx, True) @commands.command(name='mock') diff --git a/src/cogs/games.py b/src/cogs/games.py index 6f7cda8..8897886 100644 --- a/src/cogs/games.py +++ b/src/cogs/games.py @@ -15,8 +15,14 @@ class Games(commands.Cog): self.guessing_game = {} @commands.command(name='chifumi', aliases = ["shifumi", "ppc"]) - async def _chifumi(self, ctx, *, choix): + async def _chifumi(self, ctx, *choix): """Un simple Chifumi contre le bot.\n ➡ Syntaxe: {PREFIX}chifumi/shifumi/ppc """ + fromSlash = False + if len(choix) < 1: + raise ModuleNotFoundError + if choix[-1] == True: + fromSlash = choix[-1] + choix = choix[0] choix_jeu = ["Pierre ✊", "Papier 🧻", "Ciseaux ✂"] orditxt = choice(choix_jeu) @@ -39,12 +45,15 @@ class Games(commands.Cog): embed = discord.Embed(title = f"{choix_jeu[choix][-1:]}VS {choix_jeu[ordi][-1:]}", description = description) embed.set_author(name = ctx.author.name, icon_url = ctx.author.avatar_url) - await ctx.send(embed = embed) - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + return await ctx.send(embed = embed) @_chifumi.error async def _chifumi_error(self, ctx, error): await ctx.send(f"Mauvaise syntaxe : `{ctx.prefix}chifumi/shifumi/ppc `.") - + @cog_ext.cog_slash(name="chifumi", description = "Un simple Chifumi contre le bot.") + async def __chifumi(self, ctx, choix): + return await self._chifumi(ctx, choix, True) @commands.command(name='plusoumoins', aliases = ['+ou-', '+-']) async def _plusoumoins(self, ctx): @@ -93,7 +102,6 @@ class Games(commands.Cog): del self.guessing_game[str(ctx.author.id)] await ctx.send(f"T'as pas trouvé {ctx.author.mention}... dommage, c'était {number}.") - @commands.command(name='pileouface', aliases=['pf']) async def _pileouface(self, ctx, fromSlash = False): """Pile ou face.\n ➡ Syntaxe: {PREFIX}pileouface/pf""" From c9737bb115c206358f28e1ab046c0ae6aca2b157 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 29 May 2021 00:04:58 +0200 Subject: [PATCH 059/286] =?UTF-8?q?ajout=20pr=C3=A9cision=20dans=20le=20sl?= =?UTF-8?q?ash=20du=20chifumi?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/games.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/games.py b/src/cogs/games.py index 8897886..95d7bdf 100644 --- a/src/cogs/games.py +++ b/src/cogs/games.py @@ -51,7 +51,7 @@ class Games(commands.Cog): @_chifumi.error async def _chifumi_error(self, ctx, error): await ctx.send(f"Mauvaise syntaxe : `{ctx.prefix}chifumi/shifumi/ppc `.") - @cog_ext.cog_slash(name="chifumi", description = "Un simple Chifumi contre le bot.") + @cog_ext.cog_slash(name="chifumi", description = "Un simple Chifumi contre le bot. ") async def __chifumi(self, ctx, choix): return await self._chifumi(ctx, choix, True) From 463b0080d48919e0b872c56b2703e4ece121b061 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 29 May 2021 00:20:12 +0200 Subject: [PATCH 060/286] adding available commands in internet cogs to slash commands --- src/cogs/internet.py | 59 +++++++++++++++++++++++++++++++++++++------- 1 file changed, 50 insertions(+), 9 deletions(-) diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 6bf9dd0..af7c2e7 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -2,6 +2,7 @@ import discord, json, requests, time, feedparser, os from discord.ext import commands from random import choice from asyncpraw import Reddit +from discord_slash import cog_ext def setup(client): client.add_cog(Internet(client)) @@ -9,7 +10,6 @@ def setup(client): class Internet(commands.Cog): """Commandes relatives à ce qui provient d'internet.""" - def __init__(self, client): self.client = client @@ -31,8 +31,17 @@ class Internet(commands.Cog): await self._cat(await self.client.get_context(message)) @commands.command(name='memes', aliases = ['meme']) - async def _memes(self, ctx, *, args = None): + async def _memes(self, ctx, *args): """Envois un meme de reddit.\n ➡ Syntaxe: {PREFIX}memes/meme [subreddit]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + fromSlash = False + if len(args) > 0: + if args[-1] == True: + fromSlash = args[-1] + args = args[:-1] + if len(args) > 0: + args = args[0] + else: + args = None if args: # s'il y a un subreddit de défini subredditchoix = args @@ -58,7 +67,8 @@ class Internet(commands.Cog): else: await ctx.send(f"```r/{subredditchoix} pour {ctx.author.name}```\n{submission.url}") message = await ctx.send("```Meme de Reddit```") - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') await message.add_reaction('👍') return await message.add_reaction('👎') @@ -66,6 +76,13 @@ class Internet(commands.Cog): print(f"Error in _memes command = args: {args}, subreddit: {subredditchoix}, error: {error}") await ctx.message.add_reaction(emoji = '❌') return await ctx.send(f"Ce subreddit est interdit, mis en quarantaine ou n'existe pas. ({subredditchoix})") + @cog_ext.cog_slash(name="meme", description = "Envois un meme de reddit.") + async def __memes(self, ctx, subreddit = None): + if subreddit == None: + return await self._memes(ctx, True) + else: + return await self._memes(ctx, subreddit, True) + def _random_image(self, link): temps_requete = int(round(time.time() * 1000)) @@ -86,7 +103,7 @@ class Internet(commands.Cog): return (json_data, temps_requete) @commands.command(name='cat', aliases = ['chat']) - async def _cat(self, ctx): + async def _cat(self, ctx, fromSlash = False): """Te montre un magnifique chat\n ➡ Syntaxe: {PREFIX}cat/chat""" if ctx.author.nick: @@ -97,12 +114,16 @@ class Internet(commands.Cog): cat = self._random_image("http://aws.random.cat/meow") embed.set_image(url = cat[0]['file']) embed.set_footer(text = f"random.cat a pris {cat[1]} ms.") - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') message = await ctx.send(embed=embed) return await message.add_reaction('❤️') + @cog_ext.cog_slash(name="cat", description = "Te montre un magnifique chat") + async def __cat(self, ctx): + return await self._cat(ctx, True) @commands.command(name='dog', aliases = ['chien']) - async def _dog(self, ctx): + async def _dog(self, ctx, fromSlash = False): """Te montre un magnifique chien\n ➡ Syntaxe: {PREFIX}dog/chien""" if ctx.author.nick: @@ -113,9 +134,13 @@ class Internet(commands.Cog): dog = self._random_image("https://dog.ceo/api/breeds/image/random") embed.set_image(url = dog[0]['message']) embed.set_footer(text = f"dog.ceo a pris {dog[1]} ms.") - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') message = await ctx.send(embed=embed) return await message.add_reaction('❤️') + @cog_ext.cog_slash(name="dog", description = "Te montre un magnifique chien") + async def __dog(self, ctx): + return await self._dog(ctx, True) @commands.command(name='sexe', aliases=['sexes', 'nude', 'nudes', 'nsfw']) async def _sexe(self, ctx, *, choice_of_nsfw = None): @@ -137,8 +162,17 @@ class Internet(commands.Cog): await ctx.send(f"Désolé mais je n'envois ce genre de message seulement dans les salons NSFW !") @commands.command(name='news', aliases=['rss']) - async def _news(self, ctx, *, arg = ""): + async def _news(self, ctx, *arg): """Info random dans le domaine de l'informatique\n ➡ Syntaxe: {PREFIX}news/rss [site/liste]""" + fromSlash = False + if len(arg) > 0: + if arg[-1] == True: + fromSlash = arg[-1] + arg = arg[:-1] + if len(arg) > 0: + arg = arg[0] + else: + arg = "" rss_website = { "anandtech": "https://www.anandtech.com/rss/", @@ -180,4 +214,11 @@ class Internet(commands.Cog): pass embed.set_footer(text = f"News de {choix_site.capitalize()}") await ctx.send(embed = embed) - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + @cog_ext.cog_slash(name="news", description = "Info random dans le domaine de l'informatique, met commme arg liste pour la liste des sources dispo.") + async def __news(self, ctx, source = None): + if source == None: + return await self._news(ctx, True) + else: + return await self._news(ctx, source, True) From ca12edc1e24acaf918d7c9a1ecb09883529c6816 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 29 May 2021 12:31:51 +0200 Subject: [PATCH 061/286] adding link to my discord --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index ac54f5a..d91a93a 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and - In the [Discord Dev Portal](https://discord.com/developers/applications) create an application, and make sure it's a `Bot` (third tab). - To invite it, go to the `OAuth2` (second tab) tab, select the scopes `bot` (required) and `applications.commands` (for the slashs commands) and in the bot permissions select `Administrator` (You can select manually at your own risk). - You have the link above between the two blocks scope and permissions +- If you need help, you can [join my Discord](https://discord.gg/Z5ePxH4) ## __Features__ From 673377404e87118089058c4ca1b01302be8df7e5 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 29 May 2021 12:50:18 +0200 Subject: [PATCH 062/286] adding all school commands to slash --- src/cogs/school.py | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/src/cogs/school.py b/src/cogs/school.py index 8cf7260..5b41c15 100644 --- a/src/cogs/school.py +++ b/src/cogs/school.py @@ -1,5 +1,6 @@ import discord from discord.ext import commands +from discord_slash import cog_ext def setup(client): client.add_cog(School(client)) @@ -12,13 +13,26 @@ class School(commands.Cog): @commands.command(name='appel') # @commands.has_any_role("Professeur", "professeur", "Prof", "prof") - async def _appel(self, ctx, *, voice_channel: int = None): + async def _appel(self, ctx, *voice_channel: int): """Fais l'appel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}appel [ID salon vocal]""" + fromSlash = False + if len(voice_channel) > 0: + if voice_channel[-1] == True: + fromSlash = voice_channel[-1] + voice_channel = voice_channel[:-1] + if len(voice_channel) > 0: + voice_channel = voice_channel[0] + else: + voice_channel = None + voice_channels = [] voice_channels.extend(ctx.guild.voice_channels) - await ctx.message.add_reaction(emoji = "✅") + if fromSlash != True: + await ctx.message.add_reaction(emoji = "✅") limite_voice_channels = 7 if len(voice_channels) > limite_voice_channels and not voice_channel: + if fromSlash == True: + ctx.prefix = "/" return await ctx.send(f"""Désolé mais il y a plus de {limite_voice_channels} salons vocaux sur ce serveur, utilisez plutôt `{ctx.prefix}appel {{ID salon vocal}}`. \nPour savoir comment récuperer l'id d'un salon vous pouvez faire `{ctx.prefix}getid`.""") if voice_channel: @@ -52,8 +66,19 @@ class School(commands.Cog): # await ctx.send("Tu n'as pas la permission de faire cette commande, demande à un professeur.") # else: await ctx.send(f"Une erreur est survenue, syntaxe: `{ctx.prefix}appel [ID salon vocal]`.") + @cog_ext.cog_slash(name="appel", description = "Fais l'appel.") + async def __appel(self, ctx, voice_channel: int = None): + if voice_channel == None: + return await self._appel(ctx, True) + else: + return await self._appel(ctx, voice_channel, True) @commands.command(name='getid', hidden = True) - async def _getid(self, ctx): - await ctx.message.add_reaction(emoji = '✅') + async def _getid(self, ctx, fromSlash): + """Tuto vidéo sur comment récupérer l'ID d'un utilisateur/salon⁢⁢⁢⁢⁢""" + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') return await ctx.send("Explication sur comment récuperer l'ID d'un utilisateur/salon : https://cdn.discordapp.com/attachments/640312926892195842/780802253258358834/GetID.mp4") + @cog_ext.cog_slash(name="getid", description = "Tuto vidéo sur comment récupérer l'ID d'un utilisateur/salon⁢⁢⁢⁢⁢") + async def __getid(self, ctx): + return await self._getid(ctx, True) From 9eeb286ff63f47be2c44ad8fe5f5f1f5a6625916 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 29 May 2021 12:50:55 +0200 Subject: [PATCH 063/286] useless sync on reload removed bc we never unload cogs --- src/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.py b/src/main.py index 8a71588..033f7f0 100644 --- a/src/main.py +++ b/src/main.py @@ -10,7 +10,7 @@ customPrefix = os.environ['PREFIX'] customTimezone = os.environ['TIMEZONE'] client = commands.Bot(command_prefix = customPrefix, case_insensitive = True, intents = discord.Intents.all()) -slash = SlashCommand(client, sync_commands = True, sync_on_cog_reload = True) +slash = SlashCommand(client, sync_commands = True) client.load_extension("cogs.help") client.load_extension("cogs.utils") From 637b7209a75ba3c6ee4fa00823158be832ee7e93 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sat, 29 May 2021 13:25:02 +0200 Subject: [PATCH 064/286] fix appel slash command --- src/cogs/school.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/cogs/school.py b/src/cogs/school.py index 5b41c15..1df8604 100644 --- a/src/cogs/school.py +++ b/src/cogs/school.py @@ -67,11 +67,14 @@ class School(commands.Cog): # else: await ctx.send(f"Une erreur est survenue, syntaxe: `{ctx.prefix}appel [ID salon vocal]`.") @cog_ext.cog_slash(name="appel", description = "Fais l'appel.") - async def __appel(self, ctx, voice_channel: int = None): - if voice_channel == None: + async def __appel(self, ctx, voice_channel_id = None): + if voice_channel_id == None: return await self._appel(ctx, True) else: - return await self._appel(ctx, voice_channel, True) + try: + return await self._appel(ctx, int(voice_channel_id), True) + except: + pass @commands.command(name='getid', hidden = True) async def _getid(self, ctx, fromSlash): From 08eba4e42e398f9d2d9d266bccb59dc6f77c7b0a Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 30 May 2021 13:11:00 +0200 Subject: [PATCH 065/286] fix get id + better prefix location + appel command fix --- src/cogs/school.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/cogs/school.py b/src/cogs/school.py index 1df8604..8a53dd4 100644 --- a/src/cogs/school.py +++ b/src/cogs/school.py @@ -31,8 +31,6 @@ class School(commands.Cog): await ctx.message.add_reaction(emoji = "✅") limite_voice_channels = 7 if len(voice_channels) > limite_voice_channels and not voice_channel: - if fromSlash == True: - ctx.prefix = "/" return await ctx.send(f"""Désolé mais il y a plus de {limite_voice_channels} salons vocaux sur ce serveur, utilisez plutôt `{ctx.prefix}appel {{ID salon vocal}}`. \nPour savoir comment récuperer l'id d'un salon vous pouvez faire `{ctx.prefix}getid`.""") if voice_channel: @@ -42,7 +40,7 @@ class School(commands.Cog): else: return await ctx.send("Tu as spécifié un channel textuelle et non vocal.") if len(voice_channels) > 0: - embed = discord.Embed(title = "Réagissez à ce message avec ✋ pour signaler votre présence.", description = f"(attention, je réagis aussi) — Professeur : {ctx.author.mention}") + embed = discord.Embed(title = "Réagissez à ce message avec ✋ pour signaler votre présence.", description = f"(attention, je réagis aussi) — Demandeur : {ctx.author.mention}") for channel in voice_channels: prof = [] for role in ["Professeur", "professeur", "Prof", "prof"]: @@ -68,6 +66,7 @@ class School(commands.Cog): await ctx.send(f"Une erreur est survenue, syntaxe: `{ctx.prefix}appel [ID salon vocal]`.") @cog_ext.cog_slash(name="appel", description = "Fais l'appel.") async def __appel(self, ctx, voice_channel_id = None): + ctx.prefix = "/" if voice_channel_id == None: return await self._appel(ctx, True) else: @@ -77,7 +76,7 @@ class School(commands.Cog): pass @commands.command(name='getid', hidden = True) - async def _getid(self, ctx, fromSlash): + async def _getid(self, ctx, fromSlash = False): """Tuto vidéo sur comment récupérer l'ID d'un utilisateur/salon⁢⁢⁢⁢⁢""" if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') From 049ba85627f63aa0e496ee226a0c368902fbdeb0 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 30 May 2021 13:20:43 +0200 Subject: [PATCH 066/286] =?UTF-8?q?support=20des=20commandes=20slash=20pou?= =?UTF-8?q?r=20la=20cat=C3=A9gorie=20cogs=20compatible?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/utils.py | 250 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 188 insertions(+), 62 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 5b8bab3..b5d7c7b 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -4,6 +4,8 @@ from random import randint, shuffle from datetime import datetime from pytz import timezone import re, asyncio +from discord_slash import cog_ext +import shlex def setup(client): client.add_cog(Utils(client)) @@ -31,22 +33,49 @@ class Utils(commands.Cog): await ctx.message.add_reaction(emoji = '✅') @commands.command(name='avatar') - async def _avatar(self, ctx, *, user = '0'): + async def _avatar(self, ctx, *user): """Affiche ton avatar ou celui que tu mentionnes.\n ➡ Syntaxe: {PREFIX}avatar [user]""" - if user == '0': + fromSlash = False + if len(user) > 0: + if user[-1] == True: + fromSlash = user[-1] + user = user[:-1] + if len(user) > 0: + user = user[0] + else: + user = None + + if user == None: user = ctx.author else: user = self.client.get_user(int(user[2:-1].replace("!",""))) - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') embed = discord.Embed(description = f"[lien vers la photo de profil]({user.avatar_url}) de {user.mention}", color = discord.Colour.random()) embed.set_author(name = f"Photo de profil de {user.name}") embed.set_image(url = user.avatar_url) await ctx.send(embed = embed) + @cog_ext.cog_slash(name="avatar", description = "Affiche ton avatar ou celui que tu mentionnes.") + async def __avatar(self, ctx, user = None): + if user == None: + return await self._avatar(ctx, True) + else: + return await self._avatar(ctx, user, True) @commands.command(name='calc') - async def _calc(self, ctx, *, msg): + async def _calc(self, ctx, *calcul): """Calculatrice.\n ➡ Syntaxe: {PREFIX}calc ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - equation = msg.replace('^', '**').replace('x', '*').replace('×', '*').replace('÷', '/').replace('≥', '>=').replace('≤', '<=') + fromSlash = False + if len(calcul) > 0: + if calcul[-1] == True: + fromSlash = calcul[-1] + calcul = calcul[:-1] + if len(calcul) > 0: + calcul = calcul[0] + else: + raise ModuleNotFoundError + + equation = calcul.replace('^', '**').replace('x', '*').replace('×', '*').replace('÷', '/').replace('≥', '>=').replace('≤', '<=') try: try: if '=' in equation: @@ -79,14 +108,18 @@ class Utils(commands.Cog): embed.add_field(name = 'Calcul :', value = equation, inline = False) embed.add_field(name = 'Réponse :', value = answer.replace('False', 'Faux').replace('True', 'Vrai'), inline = False) - await ctx.message.add_reaction(emoji = '✅') - await ctx.send(content = None, embed = embed) + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + await ctx.send(embed = embed) @_calc.error async def _calc_error(self, ctx, error): await ctx.send("Tu n'as pas spécifié de calcul.") + @cog_ext.cog_slash(name="calc", description = "Calculatrice.") + async def __calc(self, ctx, calcul): + return await self._calc(ctx, calcul, True) @commands.command(name='syntax') - async def _syntax(self, ctx): + async def _syntax(self, ctx, fromSlash = False): """Informations pour bien éditer son texte.⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" syntaxe = "-----------------------------------------------------\n" syntaxe += discord.utils.escape_markdown("```Js\n") @@ -128,32 +161,52 @@ class Utils(commands.Cog): syntaxe += "-----------------------------------------------------\n" syntaxe += discord.utils.escape_markdown(">>> cette ligne est cité\ncelle là aussi (et elles le seront toutes!)\n") syntaxe += ">>> cette ligne est cité\ncelle là aussi (et elles le seront toutes!)\n" - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') await ctx.send(syntaxe) + @cog_ext.cog_slash(name="syntax", description = "Informations pour bien éditer son texte.") + async def __syntax(self, ctx): + return await self._syntax(ctx, True) @commands.command(name='memo', aliases = ['note']) - async def _memo(self, ctx, *, text): + async def _memo(self, ctx, *text): """T'envoie un petit memo par message privé.\n ➡ Syntaxe: {PREFIX}memo/note ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + fromSlash = False + if len(text) > 0: + if text[-1] == True: + fromSlash = text[-1] + text = text[:-1] + if len(text) > 0: + text = " ".join(text) + else: + raise ModuleNotFoundError + if len(text) <= 5: - await ctx.message.add_reaction(emoji = '❌') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '❌') return await ctx.send("Ta note doit au moins faire 5 caractères.") elif len(text) >= 2048: - await ctx.message.add_reaction(emoji = '❌') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '❌') return await ctx.send("Ta note doit faire moins de 2048 caractères.") else: - await ctx.message.delete() + if fromSlash != True: + await ctx.message.delete() embed = discord.Embed(description = text, color = discord.Colour.random()) embed.set_author(name = f"Mémo noté depuis {ctx.guild.name}", icon_url = ctx.author.avatar_url) embed.set_footer(text = f'📝 le {datetime.now(pytz.timezone(self.customTimezone)).strftime("%d/%m/%Y à %H:%M:%S")}') await ctx.author.send(embed = embed) return await ctx.send("Tu viens de recevoir ton mémo !", delete_after = 5) @_memo.error - async def _note_error(self, ctx, error): + async def _memo_error(self, ctx, error): if str(error) == "text is a required argument that is missing.": - await ctx.send(f"Vous devez renseigner un message : `{ctx.prefix}note/memo ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢`.") + await ctx.send(f"Vous devez renseigner un message : `{ctx.prefix}memo/note ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢`.") + @cog_ext.cog_slash(name="memo", description = "T'envoie un petit memo par message privé.") + async def __memo(self, ctx, memo): + return await self._memo(ctx, memo, True) @commands.command(name='infos', aliases = ['info']) - async def _infos(self, ctx): + async def _infos(self, ctx, fromSlash = False): """Donne des infos sur le bot.\n ➡ Syntaxe: {PREFIX}infos/info⁢""" appinfo = await self.client.application_info() @@ -187,21 +240,60 @@ class Utils(commands.Cog): embed.add_field(name = "Timezone", value = f"`{self.customTimezone}`") embed.add_field(name = "Version", value = f"`{version}`") embed.set_footer(text = f"Basé sur discord.py {discord.__version__}") - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') await ctx.send(embed = embed) + @cog_ext.cog_slash(name="infos", description = "Donne des infos sur le bot.") + async def __infos(self, ctx): + ctx.prefix = "/" + return await self._infos(ctx, True) - def _map_list_among_us(self, map): - maps = {} - maps["skeld"] = ["skeld", "the skeld", "theskeld"] - maps["mira"] = ["mira", "mira hq", "mirahq"] - maps["polus"] = ["polus"] - maps["airship"] = ["airship", "air ship"] - if map == "all": - return maps["skeld"] + maps["mira"] + maps["polus"] + maps["airship"] - return maps[map] - + @commands.command(name='amongus') + async def _amongus(self, ctx, *map): + """Affiche la carte voulue d'Among Us.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}amongus ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + fromSlash = False + if len(map) > 0: + if map[-1] == True: + fromSlash = map[-1] + map = map[:-1] + if len(map) > 0: + map = " ".join(map) + else: + map = "0" + + if map.lower() in self._map_list_among_us("mira"): + image = "https://i.imgur.com/6ijrH1h.jpg" + embed = discord.Embed(title = f"Map Mira HQ d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") + embed.set_image(url = image) + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + await ctx.send(embed = embed) + elif map.lower() in self._map_list_among_us("polus"): + image = "https://i.imgur.com/mhFmcw3.jpg" + embed = discord.Embed(title = f"Map Polus d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") + embed.set_image(url = image) + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + await ctx.send(embed = embed) + elif map.lower() in self._map_list_among_us("skeld"): + image = "https://i.imgur.com/OSXI4Zv.jpg" + embed = discord.Embed(title = f"Map The Skeld d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") + embed.set_image(url = image) + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + await ctx.send(embed = embed) + elif map.lower() in self._map_list_among_us("airship"): + image = "https://i.imgur.com/cm8Wogw.png" + embed = discord.Embed(title = f"Map Airship d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") + embed.set_image(url = image) + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + await ctx.send(embed = embed) + else: + await ctx.send(f"`{ctx.prefix}amongus `") @commands.command(name='among', hidden = True) async def _among(self, ctx, *, args = ""): + """Raccourci à la commande amongus⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" if not args == "": args = args.split() del args[0] @@ -212,40 +304,29 @@ class Utils(commands.Cog): await ctx.invoke(self.client.get_command("amongus")) else: await ctx.message.add_reaction(emoji = '❓') - - @commands.command(name='amongus') - async def _amongus(self, ctx, *, map = "0"): - """Affiche la carte voulue d'Among Us.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}amongus ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - if map.lower() in self._map_list_among_us("mira"): - image = "https://i.imgur.com/6ijrH1h.jpg" - embed = discord.Embed(title = f"Map Mira HQ d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") - embed.set_image(url = image) - await ctx.send(embed = embed) - await ctx.message.add_reaction(emoji = '✅') - elif map.lower() in self._map_list_among_us("polus"): - image = "https://i.imgur.com/mhFmcw3.jpg" - embed = discord.Embed(title = f"Map Polus d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") - embed.set_image(url = image) - await ctx.send(embed = embed) - await ctx.message.add_reaction(emoji = '✅') - elif map.lower() in self._map_list_among_us("skeld"): - image = "https://i.imgur.com/OSXI4Zv.jpg" - embed = discord.Embed(title = f"Map The Skeld d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") - embed.set_image(url = image) - await ctx.send(embed = embed) - await ctx.message.add_reaction(emoji = '✅') - elif map.lower() in self._map_list_among_us("airship"): - image = "https://i.imgur.com/cm8Wogw.png" - embed = discord.Embed(title = f"Map Airship d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") - embed.set_image(url = image) - await ctx.send(embed = embed) - await ctx.message.add_reaction(emoji = '✅') - else: - await ctx.send(f"`{ctx.prefix}amongus `") + def _map_list_among_us(self, map): + """Sélecteur de map pour la commande amongus⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + maps = {} + maps["skeld"] = ["skeld", "the skeld", "theskeld"] + maps["mira"] = ["mira", "mira hq", "mirahq"] + maps["polus"] = ["polus"] + maps["airship"] = ["airship", "air ship"] + if map == "all": + return maps["skeld"] + maps["mira"] + maps["polus"] + maps["airship"] + return maps[map] + @cog_ext.cog_slash(name="amongus", description = "Affiche la carte voulue d'Among Us.") + async def __amongus(self, ctx, map): + return await self._amongus(ctx, map, True) @commands.command(name='whois') async def _whois(self, ctx, *user: discord.Member): """Affiche les infos sur l'utilisateur.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}whois [user]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + fromSlash = False + if len(user) > 0: + if user[-1] == True: + fromSlash = user[-1] + user = user[:-1] + if len(user) <= 1: if user == (): user = [ctx.author] @@ -267,9 +348,17 @@ class Utils(commands.Cog): embed.add_field(name = "Serveur rejoint le", value = f"{value[0][8:]}/{value[0][5:-3]}/{value[0][:4]} à {value[1]}") embed.add_field(name = "Est sur le serveur depuis", value = self._ageLayout(self._get_age(user[0].joined_at))) - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') return await ctx.send(embed = embed) return await ctx.send(f"Tu mentionnes trop d'utilisateurs : `{ctx.prefix}whois [@Membre]`") + @cog_ext.cog_slash(name="whois", description = "Affiche les infos sur l'utilisateur.") + async def __whois(self, ctx, user: discord.Member = None): + ctx.prefix = "/" # pas sûr que ce soit utile + if user == None: + return await self._whois(ctx, True) + else: + return await self._whois(ctx, user, True) def _get_age(self, date): joursRestants = datetime.now() - date @@ -358,6 +447,12 @@ class Utils(commands.Cog): @commands.command(name='sondage') async def _sondage(self, ctx, *args): """Fais un sondage.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}sondage "" "" "" "" """ + fromSlash = False + if len(args) > 0: + if args[-1] == True: + fromSlash = args[-1] + args = args[:-1] + args = list(args) if len(args) > 2: question = args[0] @@ -390,15 +485,27 @@ class Utils(commands.Cog): sondage = await ctx.send(embed = embed) for i in range(len(args[1:])): await sondage.add_reaction(emoji = emojis_chosen[i]) - return await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + return await ctx.message.add_reaction(emoji = '✅') else: return await ctx.send(f"Désolé, mais tu as mis trop de possibilités (maximum : 20)") else: return await ctx.send(f'Désolé, mais il manque des arguments : `{ctx.prefix}sondage "" "" "" ""`') + @cog_ext.cog_slash(name="sondage", description = "Fais un sondage.") + async def __sondage(self, ctx, args): + ctx.prefix = "/" + args = shlex.split(args) + return await self._sondage(ctx, *args, True) @commands.command(name='avis', aliases=['vote']) async def _avis(self, ctx, *args): """Demande un avis.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}avis/vote "[Titre]" "" """ + fromSlash = False + if len(args) > 0: + if args[-1] == True: + fromSlash = args[-1] + args = args[:-1] + args = list(args) if len(args) > 2 or len(args) == 0: return await ctx.send("Désolé, la syntaxe est mauvaise.") @@ -415,11 +522,26 @@ class Utils(commands.Cog): reactions = ['✅', '🤷', '❌'] for i in reactions: await message.add_reaction(emoji = i) - return await ctx.message.delete() + if fromSlash != True: + return await ctx.message.delete() + @cog_ext.cog_slash(name="avis", description = "Demande un avis.") + async def __avis(self, ctx, args): + args = shlex.split(args) + return await self._avis(ctx, *args, True) @commands.command(name='reminder', aliases=["remind", "remindme"]) - async def _reminder(self, ctx, time, *, reminder): + async def _reminder(self, ctx, time, *reminder): """Met en place un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminder/remind/remindme [@] """ + fromSlash = False + if len(reminder) > 0: + if reminder[-1] == True: + fromSlash = reminder[-1] + reminder = reminder[:-1] + if len(reminder) > 0: + reminder = " ".join(reminder) + else: + reminder = None + embed = discord.Embed(color = 0xC41B1B) seconds = 0 timestamp = datetime.utcnow() @@ -459,7 +581,8 @@ class Utils(commands.Cog): for i in mentionList: message += f" {i}" try: - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') except: pass finalEmbed = discord.Embed(description = self._cleanCodeStringWithMentionAndURLs(reminder), timestamp = timestamp, color = discord.Colour.random()) @@ -476,3 +599,6 @@ class Utils(commands.Cog): else: embed.add_field(name="Attention", value="Mauvaise syntaxe : reminder ") await ctx.send(embed = embed) + @cog_ext.cog_slash(name="reminder", description = "Met en place un rappel.") + async def __reminder(self, ctx, time, reminder): + return await self._reminder(ctx, time, reminder, True) From dfc82c6a9278c49a446e6633ba57962b24e4112f Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 30 May 2021 13:24:38 +0200 Subject: [PATCH 067/286] deletion of old music cog --- .gitignore | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitignore b/.gitignore index 044335f..60bddb1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ .vscode/ update/ -src/cogs/music_old.py src/cogs/__pycache__/ .envrc From 3f81011fbf88a19c5ec7500cf9e61fc13aa8a3c8 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 30 May 2021 13:52:00 +0200 Subject: [PATCH 068/286] ajout aliase connect --- src/cogs/music.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/music.py b/src/cogs/music.py index 26af84c..b0ffcbe 100644 --- a/src/cogs/music.py +++ b/src/cogs/music.py @@ -299,7 +299,7 @@ class Music(commands.Cog): async def cog_command_error(self, ctx: commands.Context, error: commands.CommandError): await ctx.send(f"Une erreur est survenue : {str(error)}") - @commands.command(name='join', aliases=['j'], invoke_without_subcommand=True) + @commands.command(name='join', aliases=['j', 'connect'], invoke_without_subcommand=True) async def _summon(self, ctx: commands.Context, *, channel: discord.VoiceChannel = None): """Se connecte au salon vocal.\n ➡ Syntaxe: {PREFIX}connect/join⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" From 8b8c26eb178632e4a7e4d070879eec84b2bfe209 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 30 May 2021 13:54:34 +0200 Subject: [PATCH 069/286] adding dot --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d91a93a..253b63d 100644 --- a/README.md +++ b/README.md @@ -31,8 +31,8 @@ To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and - In the [Discord Dev Portal](https://discord.com/developers/applications) create an application, and make sure it's a `Bot` (third tab). - To invite it, go to the `OAuth2` (second tab) tab, select the scopes `bot` (required) and `applications.commands` (for the slashs commands) and in the bot permissions select `Administrator` (You can select manually at your own risk). -- You have the link above between the two blocks scope and permissions -- If you need help, you can [join my Discord](https://discord.gg/Z5ePxH4) +- You have the link above between the two blocks scope and permissions. +- If you need help, you can [join my Discord](https://discord.gg/Z5ePxH4). ## __Features__ From 428ebb98d0ffb19bc979822b33dd5c42563178b9 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 14:06:51 +0200 Subject: [PATCH 070/286] swapping commands for help discord server to his own cog --- src/cogs/confreriedukassoulait.py | 115 ++++++++++++++++++++++++++++++ src/main.py | 86 +--------------------- 2 files changed, 116 insertions(+), 85 deletions(-) create mode 100644 src/cogs/confreriedukassoulait.py diff --git a/src/cogs/confreriedukassoulait.py b/src/cogs/confreriedukassoulait.py new file mode 100644 index 0000000..b471979 --- /dev/null +++ b/src/cogs/confreriedukassoulait.py @@ -0,0 +1,115 @@ +import discord +import re +import os +from discord.ext import commands +from random import choice +from datetime import datetime +from pytz import timezone +customTimezone = os.environ['TIMEZONE'] + +def setup(client): + client.add_cog(ConfrerieDuKassoulait(client)) + +class ConfrerieDuKassoulait(commands.Cog): + """Unique pour le serveur Discord "La confrérie du Kassoulait".""" + + def __init__(self, client): + self.client = client + + @commands.Cog.listener() + async def on_ready(self): + channel = self.client.get_channel(742564480050790512) + await channel.send("Le bot a bien démarré.") + + @commands.Cog.listener() + async def on_member_join(self, member): + if member.guild.id == 441208120644075520: # Confrérie du Kassoulait + if member.bot == True: + role = discord.utils.get(member.guild.roles, name = "Bot") + else: + role = discord.utils.get(member.guild.roles, name = "Copain") + await member.add_roles(role) + try: + await member.send(f"Coucou **{member.name}** sur {member.guild.name} ! 🥰\n\nTu as le rôle **{role}** 💖!") + except: + pass + channel = self.client.get_channel(741639570172674120) # salons des arrivées + switch = [ + f"Bienvenue, {member.mention}. On espère que tu as apporté de la pizza.", + f"C'est un plaisir de te voir, {member.mention}.", + f"{member.mention} vient juste d'arriver !", + f"{member.mention} vient juste d'atterrir.", + f"{member.mention} vient de se glisser dans le serveur.", + f"{member.mention} a bondi dans le serveur.", + f"Contents de te voir, {member.mention}.", + f"{member.mention} est arrivé(e).", + f"Tout le monde, accueillez comme il se doit {member.mention} !", + f"Youhou, tu as réussi, {member.mention} !", + f"{member.mention} a rejoint le groupe." + ] + message = await channel.send("...") # évite d'envoyer une notification + await message.edit(content = choice(switch)) + + @commands.Cog.listener() + async def on_member_remove(self, member): + if member.guild.id == 441208120644075520: # Confrérie du Kassoulait + channel = self.client.get_channel(741639570172674120) # salons des arrivées + await channel.send(f"{member.mention} vient de quitter le serveur.") + + @commands.Cog.listener() + async def on_raw_reaction_add(self, payload): + if payload.message_id == 644922358745792512: # Règles de la Confrérie du Kassoulait + if payload.emoji.name == '✅': + role = discord.utils.get(payload.member.guild.roles, name="règles-acceptés") + await payload.member.add_roles(role) + + @commands.Cog.listener() + async def on_raw_reaction_remove(self, payload): + if payload.message_id == 644922358745792512: # Règles de la Confrérie du Kassoulait + if payload.emoji.name == '✅': + guild = discord.utils.find(lambda g : g.id == payload.guild_id, self.client.guilds) + member = discord.utils.find(lambda m: m.id == payload.user_id, guild.members) + role = discord.utils.get(guild.roles, name="règles-acceptés") + await member.remove_roles(role) + + @commands.Cog.listener() + async def on_message_delete(self, message): + if message.author.guild.id == 441208120644075520: # Confrérie du Kassoulait + prefix = await self.client.get_prefix(message) + if not ( + message.content.startswith(f"{prefix}note") or + message.content.startswith(f"{prefix}memo") or + len(re.findall(".com/channels/", message.content)) != 0 or + self.client.user.id is message.author.id + ): + user_suppressed = None + + async for entry in message.guild.audit_logs(limit=1): + if (datetime.now() - entry.created_at).seconds < 5 and str(entry.action) == 'AuditLogAction.message_delete': + user_suppressed = entry.user + + channel = self.client.get_channel(742588187456831659) + embed = discord.Embed(description = f"{message.content}") + + embed.set_author(name = self.user_or_nick(message.author), icon_url = message.author.avatar_url) + + if not user_suppressed: + embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {self.goodTimezone(message.created_at, 1)}\nSupprimé le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") + else: + embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {self.goodTimezone(message.created_at, 1)}\nSupprimé par {self.user_or_nick(user_suppressed)} le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") + + await channel.send(embed = embed) + # ne fonctionne pas quand un message a été supprimé avant que le bot ai démarré + # info sur la personne qui a supprimé ne fonctionne pas si il a supprimé un message auparavant (les logs se rajoute a un log deja existant) + + def user_or_nick(user): + if user.nick: + return f"{user.nick} ({user.name}#{user.discriminator})" + else: + return f"{user.name}#{user.discriminator}" + + def goodTimezone(self, date, type): + if type == 0: + return str(timezone(customTimezone).fromutc(date))[:-13].replace('-', '/').split() + elif type == 1: + return str(timezone(customTimezone).fromutc(date))[:-13].replace('-', '/').replace(' ', ' à ') diff --git a/src/main.py b/src/main.py index fe9a28f..cfa5ce0 100644 --- a/src/main.py +++ b/src/main.py @@ -5,8 +5,6 @@ import re import os from discord_slash import SlashCommand from discord.ext import commands -from random import choice -from datetime import datetime from pytz import timezone customPrefix = os.environ['PREFIX'] customTimezone = os.environ['TIMEZONE'] @@ -22,6 +20,7 @@ client.load_extension("cogs.games") client.load_extension("cogs.fun") client.load_extension("cogs.autopublish") client.load_extension("cogs.school") +client.load_extension("cogs.confreriedukassoulait") print("Terminé !") @client.event @@ -32,59 +31,6 @@ async def on_connect(): async def on_ready(): await client.change_presence(status = discord.Status.online, activity = discord.Activity(name = f"{customPrefix}help", type = discord.ActivityType.playing)) print("Bot prêt.") - channel = client.get_channel(742564480050790512) - await channel.send("Le bot a bien démarré.") - -@client.event -async def on_member_join(member): - if member.guild.id == 441208120644075520: # Confrérie du Kassoulait - if member.bot == True: - role = discord.utils.get(member.guild.roles, name = "Bot") - else: - role = discord.utils.get(member.guild.roles, name = "Copain") - await member.add_roles(role) - try: - await member.send(f"Coucou **{member.name}** sur {member.guild.name} ! 🥰\n\nTu as le rôle **{role}** 💖!") - except: - pass - channel = client.get_channel(741639570172674120) # salons des arrivées - switch = [ - f"Bienvenue, {member.mention}. On espère que tu as apporté de la pizza.", - f"C'est un plaisir de te voir, {member.mention}.", - f"{member.mention} vient juste d'arriver !", - f"{member.mention} vient juste d'atterrir.", - f"{member.mention} vient de se glisser dans le serveur.", - f"{member.mention} a bondi dans le serveur.", - f"Contents de te voir, {member.mention}.", - f"{member.mention} est arrivé(e).", - f"Tout le monde, accueillez comme il se doit {member.mention} !", - f"Youhou, tu as réussi, {member.mention} !", - f"{member.mention} a rejoint le groupe." - ] - message = await channel.send("...") # évite d'envoyer une notification - await message.edit(content = choice(switch)) - -@client.event -async def on_member_remove(member): - if member.guild.id == 441208120644075520: # Confrérie du Kassoulait - channel = client.get_channel(741639570172674120) # salons des arrivées - await channel.send(f"{member.mention} vient de quitter le serveur.") - -@client.event -async def on_raw_reaction_add(payload): - if payload.message_id == 644922358745792512: # Règles de la Confrérie du Kassoulait - if payload.emoji.name == '✅': - role = discord.utils.get(payload.member.guild.roles, name="règles-acceptés") - await payload.member.add_roles(role) - -@client.event -async def on_raw_reaction_remove(payload): - if payload.message_id == 644922358745792512: # Règles de la Confrérie du Kassoulait - if payload.emoji.name == '✅': - guild = discord.utils.find(lambda g : g.id == payload.guild_id, client.guilds) - member = discord.utils.find(lambda m: m.id == payload.user_id, guild.members) - role = discord.utils.get(guild.roles, name="règles-acceptés") - await member.remove_roles(role) @client.event async def on_command_error(ctx, error): @@ -181,36 +127,6 @@ async def on_message(message): if not "invalid literal for int() with base 10:" in e or not "404 Not Found (error code: 10008)" in e: # faute de frappe / message supprimé print(e) -@client.event -async def on_message_delete(message): - if message.author.guild.id == 441208120644075520: # Confrérie du Kassoulait - prefix = await client.get_prefix(message) - if not ( - message.content.startswith(f"{prefix}note") or - message.content.startswith(f"{prefix}memo") or - len(re.findall(".com/channels/", message.content)) != 0 or - client.user.id is message.author.id - ): - user_suppressed = None - - async for entry in message.guild.audit_logs(limit=1): - if (datetime.now() - entry.created_at).seconds < 5 and str(entry.action) == 'AuditLogAction.message_delete': - user_suppressed = entry.user - - channel = client.get_channel(742588187456831659) - embed = discord.Embed(description = f"{message.content}") - - embed.set_author(name = user_or_nick(message.author), icon_url = message.author.avatar_url) - - if not user_suppressed: - embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1)}\nSupprimé le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") - else: - embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1)}\nSupprimé par {user_or_nick(user_suppressed)} le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") - - await channel.send(embed = embed) - # ne fonctionne pas quand un message a été supprimé avant que le bot ai démarré - # info sur la personne qui a supprimé ne fonctionne pas si il a supprimé un message auparavant (les logs se rajoute a un log deja existant) - def user_or_nick(user): if user.nick: return f"{user.nick} ({user.name}#{user.discriminator})" From 96460820837140c4be13e0514c1d1e59a542424e Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 15:14:02 +0200 Subject: [PATCH 071/286] better pycache ignore --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 60bddb1..05faf8d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ .vscode/ update/ -src/cogs/__pycache__/ +__pycache__/ .envrc From 34459adc5e0abc5478762e298b93d63bb584c0d7 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 15:14:31 +0200 Subject: [PATCH 072/286] passage des methodes non asynchrone dans un fichier extene "core" --- src/cogs/confreriedukassoulait.py | 19 +--- src/cogs/fun.py | 11 +-- src/cogs/internet.py | 29 +----- src/cogs/music.py | 20 +--- src/cogs/utils.py | 126 ++++-------------------- src/main.py | 22 +---- src/utils/core.py | 153 ++++++++++++++++++++++++++++++ 7 files changed, 189 insertions(+), 191 deletions(-) create mode 100644 src/utils/core.py diff --git a/src/cogs/confreriedukassoulait.py b/src/cogs/confreriedukassoulait.py index b471979..b2126c8 100644 --- a/src/cogs/confreriedukassoulait.py +++ b/src/cogs/confreriedukassoulait.py @@ -6,6 +6,7 @@ from random import choice from datetime import datetime from pytz import timezone customTimezone = os.environ['TIMEZONE'] +from utils.core import goodTimezone, userOrNick def setup(client): client.add_cog(ConfrerieDuKassoulait(client)) @@ -91,25 +92,13 @@ class ConfrerieDuKassoulait(commands.Cog): channel = self.client.get_channel(742588187456831659) embed = discord.Embed(description = f"{message.content}") - embed.set_author(name = self.user_or_nick(message.author), icon_url = message.author.avatar_url) + embed.set_author(name = userOrNick(message.author), icon_url = message.author.avatar_url) if not user_suppressed: - embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {self.goodTimezone(message.created_at, 1)}\nSupprimé le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") + embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1, customTimezone)}\nSupprimé le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") else: - embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {self.goodTimezone(message.created_at, 1)}\nSupprimé par {self.user_or_nick(user_suppressed)} le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") + embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1, customTimezone)}\nSupprimé par {userOrNick(user_suppressed)} le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") await channel.send(embed = embed) # ne fonctionne pas quand un message a été supprimé avant que le bot ai démarré # info sur la personne qui a supprimé ne fonctionne pas si il a supprimé un message auparavant (les logs se rajoute a un log deja existant) - - def user_or_nick(user): - if user.nick: - return f"{user.nick} ({user.name}#{user.discriminator})" - else: - return f"{user.name}#{user.discriminator}" - - def goodTimezone(self, date, type): - if type == 0: - return str(timezone(customTimezone).fromutc(date))[:-13].replace('-', '/').split() - elif type == 1: - return str(timezone(customTimezone).fromutc(date))[:-13].replace('-', '/').replace(' ', ' à ') diff --git a/src/cogs/fun.py b/src/cogs/fun.py index 9e45640..f8bc4b1 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -4,6 +4,7 @@ from discord.ext import commands from random import randint, choice from datetime import timedelta from discord_slash import cog_ext +from utils.core import retirerDoublons def setup(client): client.add_cog(Fun(client)) @@ -84,8 +85,8 @@ class Fun(commands.Cog): user2 = list(users[1].nick) else: user2 = list(users[1].name) - user1_CALC = self._retirerDoublons([x.lower() for x in user1]) - user2_CALC = self._retirerDoublons([x.lower() for x in user2]) + user1_CALC = retirerDoublons([x.lower() for x in user1]) + user2_CALC = retirerDoublons([x.lower() for x in user2]) coef_amour = 0 if len(user1_CALC) > len(user2_CALC): taille_du_pls_grand = len(user1_CALC) @@ -107,12 +108,6 @@ class Fun(commands.Cog): if fromSlash != True: await ctx.message.add_reaction(emoji = '❌') await ctx.send(f"Erreur! Syntaxe : `{ctx.prefix}love [User2]`\n") - def _retirerDoublons(self, liste): - Newliste = [] - for element in liste: - if element not in Newliste: - Newliste.append(element) - return Newliste @_love.error async def _love_error(self, ctx, error): await ctx.send(str(error).replace('Member "', "Le membre **").replace('" not found', "** n'as pas été trouvé.")) diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 0e7386a..6a09f4a 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -1,13 +1,11 @@ import discord -import json -import requests -import time import feedparser import os from discord.ext import commands from random import choice from asyncpraw import Reddit from discord_slash import cog_ext +from utils.core import randomImage def setup(client): client.add_cog(Internet(client)) @@ -88,25 +86,6 @@ class Internet(commands.Cog): else: return await self._memes(ctx, subreddit, True) - - def _random_image(self, link): - temps_requete = int(round(time.time() * 1000)) - try: - request_data = requests.get(link) - except Exception as e: - raise Exception(f"Une erreur s'est produite lors de la tentative de demande de l'API {link} : {e}") - - if not request_data.status_code == 200: - raise Exception(f"Code HTTP {request_data.status_code} au lieu de HTTP 200 à l'appel de {link} : {request_data.text}") - - try: - json_data = json.loads(request_data.text) - except Exception as e: - raise Exception(f"Erreur lors de la transformation les données de {link} en json : {e}") - - temps_requete = int(round(time.time() * 1000)) - temps_requete - return (json_data, temps_requete) - @commands.command(name='cat', aliases = ['chat']) async def _cat(self, ctx, fromSlash = False): """Te montre un magnifique chat\n ➡ Syntaxe: {PREFIX}cat/chat""" @@ -116,7 +95,7 @@ class Internet(commands.Cog): else: name = f"{ctx.author.name}" embed = discord.Embed(title = f"Poticha pour {name}", colour = discord.Colour.random()) - cat = self._random_image("http://aws.random.cat/meow") + cat = randomImage("http://aws.random.cat/meow") embed.set_image(url = cat[0]['file']) embed.set_footer(text = f"random.cat a pris {cat[1]} ms.") if fromSlash != True: @@ -136,7 +115,7 @@ class Internet(commands.Cog): else: name = f"{ctx.author.name}" embed = discord.Embed(title = f"Potichien pour {name}", colour = discord.Colour.random()) - dog = self._random_image("https://dog.ceo/api/breeds/image/random") + dog = randomImage("https://dog.ceo/api/breeds/image/random") embed.set_image(url = dog[0]['message']) embed.set_footer(text = f"dog.ceo a pris {dog[1]} ms.") if fromSlash != True: @@ -157,7 +136,7 @@ class Internet(commands.Cog): choice_of_nsfw = choice(liste_hot) if ctx.channel.is_nsfw(): embed = discord.Embed(title = f"{choice_of_nsfw.capitalize()} pour {ctx.author.name}", colour = discord.Colour.random()) - nsfw = self._random_image(f'http://api.o{choice_of_nsfw}.ru/noise/') + nsfw = randomImage(f'http://api.o{choice_of_nsfw}.ru/noise/') embed.set_image(url = f"http://media.o{choice_of_nsfw}.ru/{nsfw[0][0]['preview']}") embed.set_footer(text = f"o{choice_of_nsfw}.ru a pris {nsfw[1]} ms.") await ctx.message.add_reaction(emoji = '✅') diff --git a/src/cogs/music.py b/src/cogs/music.py index b0ffcbe..e7c20bb 100644 --- a/src/cogs/music.py +++ b/src/cogs/music.py @@ -22,6 +22,7 @@ import lyricsgenius import time import os genius = lyricsgenius.Genius(os.environ['TOKEN_GENIUS']) +from utils.core import ligneFormatage, userOrNick # Silence useless bug reports messages youtube_dl.utils.bug_reports_message = lambda: '' @@ -518,7 +519,7 @@ class Music(commands.Cog): type_de_comptage = "\n" for ligne in paroles.split(type_de_comptage): if len(f"{lignetotal}{type_de_comptage}{ligne}") < 1900: - lignetotal = f"{lignetotal}{type_de_comptage}{self.ligne_formatage(ligne)}" + lignetotal = f"{lignetotal}{type_de_comptage}{ligneFormatage(ligne)}" else: if premierembed == True: premierembed = False @@ -528,10 +529,10 @@ class Music(commands.Cog): else: embed = discord.Embed(description = lignetotal, color = couleur_embed) await ctx.send(embed = embed) - lignetotal = f"{self.ligne_formatage(ligne)}" + lignetotal = f"{ligneFormatage(ligne)}" temps_requete = int(round(time.time() * 1000)) - temps_requete - footer_embed = f"Pour {self.user_or_nick(ctx.author)} par Genius en {round(temps_requete / 1000, 2)} s." + footer_embed = f"Pour {userOrNick(ctx.author)} par Genius en {round(temps_requete / 1000, 2)} s." await ctx.message.add_reaction(emoji = '✅') if premierembed == True: premierembed = False @@ -545,19 +546,6 @@ class Music(commands.Cog): else: await ctx.message.add_reaction(emoji = '❌') await ctx.send(f"Aucune musique demandé... `{ctx.prefix}lyrics/l/lyrics `.") - def ligne_formatage(self, ligne): - liste_balise = [ - ('[Hook', '[Accroche'), ('[Verse', '[Couplet'), ('[Chorus', '[Chœur'), - ('[Bridge', '[Pont'),('[Pre-Chorus', '[Pré-chœur'), ('[Post-Chorus', '[Post-chœur') - ] - for balises in liste_balise: - ligne = ligne.replace(balises[0], balises[1]) - return ligne - def user_or_nick(self, user): - if user.nick: - return f"{user.nick} ({user.name}#{user.discriminator})" - else: - return f"{user.name}#{user.discriminator}" @commands.command(name='lyricsromanized', aliases = ['lr', 'lyricromanized'], hidden = True) async def _lyricsromanized(self, ctx, *, song: str = None): diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 46a492d..00fe9bf 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -10,6 +10,7 @@ from datetime import datetime from pytz import timezone from discord_slash import cog_ext import shlex +from utils.core import map_list_among_us, get_age, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick, ageLayout def setup(client): client.add_cog(Utils(client)) @@ -21,7 +22,6 @@ class Utils(commands.Cog): self.client = client self.customTimezone = os.environ['TIMEZONE'] - @commands.command(name='ping') async def _ping(self, ctx, *, question = '0'): """Affiche mon ping.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}ping [help]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" @@ -108,7 +108,7 @@ class Utils(commands.Cog): equation = f"'{equation}' arrondi à 2" equation = equation.replace('*', '×').replace('/', '÷').replace('>=', '≥').replace('<=', '≤') embed = discord.Embed(color = discord.Colour.random(), title = 'Calculatrice') - embed.set_footer(text = self._userOrNick(ctx.author), icon_url = ctx.author.avatar_url) + embed.set_footer(text = userOrNick(ctx.author), icon_url = ctx.author.avatar_url) embed.add_field(name = 'Calcul :', value = equation, inline = False) embed.add_field(name = 'Réponse :', value = answer.replace('False', 'Faux').replace('True', 'Vrai'), inline = False) @@ -265,28 +265,28 @@ class Utils(commands.Cog): else: map = "0" - if map.lower() in self._map_list_among_us("mira"): + if map.lower() in map_list_among_us("mira"): image = "https://i.imgur.com/6ijrH1h.jpg" embed = discord.Embed(title = f"Map Mira HQ d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") embed.set_image(url = image) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') await ctx.send(embed = embed) - elif map.lower() in self._map_list_among_us("polus"): + elif map.lower() in map_list_among_us("polus"): image = "https://i.imgur.com/mhFmcw3.jpg" embed = discord.Embed(title = f"Map Polus d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") embed.set_image(url = image) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') await ctx.send(embed = embed) - elif map.lower() in self._map_list_among_us("skeld"): + elif map.lower() in map_list_among_us("skeld"): image = "https://i.imgur.com/OSXI4Zv.jpg" embed = discord.Embed(title = f"Map The Skeld d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") embed.set_image(url = image) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') await ctx.send(embed = embed) - elif map.lower() in self._map_list_among_us("airship"): + elif map.lower() in map_list_among_us("airship"): image = "https://i.imgur.com/cm8Wogw.png" embed = discord.Embed(title = f"Map Airship d'Among Us", color = discord.Colour.random(), description = f"[lien de l'image]({image})") embed.set_image(url = image) @@ -302,22 +302,12 @@ class Utils(commands.Cog): args = args.split() del args[0] args = " ".join(args) - if args.lower() in self._map_list_among_us("all"): + if args.lower() in map_list_among_us("all"): await ctx.invoke(self.client.get_command("amongus"), map=args) else: await ctx.invoke(self.client.get_command("amongus")) else: await ctx.message.add_reaction(emoji = '❓') - def _map_list_among_us(self, map): - """Sélecteur de map pour la commande amongus⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - maps = {} - maps["skeld"] = ["skeld", "the skeld", "theskeld"] - maps["mira"] = ["mira", "mira hq", "mirahq"] - maps["polus"] = ["polus"] - maps["airship"] = ["airship", "air ship"] - if map == "all": - return maps["skeld"] + maps["mira"] + maps["polus"] + maps["airship"] - return maps[map] @cog_ext.cog_slash(name="amongus", description = "Affiche la carte voulue d'Among Us.") async def __amongus(self, ctx, map): return await self._amongus(ctx, map, True) @@ -344,14 +334,14 @@ class Utils(commands.Cog): value = str(user[0].created_at.astimezone(timezone(self.customTimezone)))[:-13].replace('-', '/').split() embed.add_field(name = "Compte créé le", value = f"{value[0][8:]}/{value[0][5:-3]}/{value[0][:4]} à {value[1]}") - embed.add_field(name = "Âge du compte", value = self._ageLayout(self._get_age(user[0].created_at))) + embed.add_field(name = "Âge du compte", value = ageLayout(get_age(user[0].created_at))) embed.add_field(name = "Mention", value = user[0].mention) value = str(user[0].joined_at.astimezone(timezone(self.customTimezone)))[:-13].replace('-', '/').split() embed.add_field(name = "Serveur rejoint le", value = f"{value[0][8:]}/{value[0][5:-3]}/{value[0][:4]} à {value[1]}") - embed.add_field(name = "Est sur le serveur depuis", value = self._ageLayout(self._get_age(user[0].joined_at))) + embed.add_field(name = "Est sur le serveur depuis", value = ageLayout(get_age(user[0].joined_at))) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') return await ctx.send(embed = embed) @@ -364,90 +354,6 @@ class Utils(commands.Cog): else: return await self._whois(ctx, user, True) - def _get_age(self, date): - joursRestants = datetime.now() - date - years = joursRestants.total_seconds() / (365.242 * 24 * 3600) - months = (years - int(years)) * 12 - days = (months - int(months)) * (365.242 / 12) - hours = (days - int(days)) * 24 - minutes = (hours - int(hours)) * 60 - seconds = (minutes - int(minutes)) * 60 - return (int(years), int(months), int(days), int(hours), int(minutes), int(seconds)) - - def _ageLayout(self, tuple): - time = {} - time[0], time[1], time[2], time[3], time[4], time[5] = "an", "mois", "jour", "heure", "minute", "seconde" - for i in range(len(tuple)): - if tuple[i] > 1 and i != 1: - time[i] = time[i] + "s" - message = "" - if tuple[5] > 0: # pour les secondes - affichage = [5] # on affiche que : seconde - if tuple[4] > 0: - affichage = [4, 5] # on affiche : minute + seconde - if tuple[3] > 0: - affichage = [3, 4, 5] # on affiche : heure + minute + seconde - if tuple[2] > 0: - affichage = [2, 3, 4] # on affiche : jour + heure + minute - if tuple[1] > 0: - affichage = [1, 2, 3] # on affiche : mois + jour + heure - if tuple[0] > 0: - affichage = [0, 1, 3] # on affiche : an + mois + heure - for i in affichage: - message = message + f", {tuple[i]} {time[i]}" - return message[2:] - - def _userOrNick(self, user): - if user == None: - return "Utilisateur inconnu" # Mauvais copié/collé -> changement d'ID - if user.nick: - return f"{user.nick} ({user.name}#{user.discriminator})" - else: - return f"{user.name}#{user.discriminator}" - - def _cleanUser(self, ctx, stringMessage, stringID): - stringMessage = stringMessage.replace("<@!", "").replace(">", "").replace("<@", "") - associatedID = self._userOrNick(ctx.author.guild.get_member(int(stringID))) - try: - stringMessage = stringMessage.replace(stringID, associatedID) - except: - pass - return stringMessage - - def _cleanCodeStringWithMentionAndURLs(self, string): - string = f"`{self._removeStartEndSpacesString(string)}`" - - findedMention = self._getMentionInString(string) - for i in range(0, len(findedMention)): - string = string.replace(findedMention[i], f"`{findedMention[i]}`") # conserve la mention dans le message - - if string.startswith("``<@"): # conserve le format quand mention au début de la string - string = string[2:] - if string.endswith(">``"): # conserve le format quand mention à la fin de la string - string = string[:-2] - string = string.replace("``", "") # conserve le format quand deux mentions sont collés - return string - - def _getMentionInString(self, string): - findedMention = [] - for findingMention in re.findall(r'<@[!]?\d*>', string): # récupération mention dans le string - findedMention.append(findingMention) - findedMention = list(dict.fromkeys(findedMention)) # suppression doublon de mention dans la liste - return findedMention - - def _getURLsInString(self, string): - findedURLs = [] - for findingMention in re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', string): # récupération URLs dans le string - findedURLs.append(findingMention) - return findedURLs - - def _removeStartEndSpacesString(self, string): - while string.startswith(" "): - string = string[1:] - while string.endswith(" "): - string = string[:-1] - return string - @commands.command(name='sondage') async def _sondage(self, ctx, *args): """Fais un sondage.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}sondage "" "" "" "" """ @@ -461,7 +367,7 @@ class Utils(commands.Cog): if len(args) > 2: question = args[0] for i in re.findall(r'\d+', question): - question = self._cleanUser(ctx, question, i) + question = cleanUser(ctx, question, i) propositions = args[1:] if len(propositions) <= 20: message = "" @@ -485,7 +391,7 @@ class Utils(commands.Cog): shuffle(emojis_chosen) for i in range(len(args[1:])): message += f"{emojis_chosen[i]} -> {propositions[i]}\n" - embed = discord.Embed(title = question, description = message, color = discord.Colour.random()).set_footer(text = f"Sondage de {self._userOrNick(ctx.author)}", icon_url = ctx.author.avatar_url) + embed = discord.Embed(title = question, description = message, color = discord.Colour.random()).set_footer(text = f"Sondage de {userOrNick(ctx.author)}", icon_url = ctx.author.avatar_url) sondage = await ctx.send(embed = embed) for i in range(len(args[1:])): await sondage.add_reaction(emoji = emojis_chosen[i]) @@ -519,9 +425,9 @@ class Utils(commands.Cog): else: # si titre défini titre = args[0] for findedId in re.findall(r'\d+', titre): # récupération mention dans titre - titre = self._cleanUser(ctx, titre, findedId) + titre = cleanUser(ctx, titre, findedId) args = args[1:] - embed = discord.Embed(title = titre, description = self._cleanCodeStringWithMentionAndURLs(args[0]), color = discord.Colour.random()).set_footer(text = f"Sondage de {self._userOrNick(ctx.author)}", icon_url = ctx.author.avatar_url) + embed = discord.Embed(title = titre, description = cleanCodeStringWithMentionAndURLs(args[0]), color = discord.Colour.random()).set_footer(text = f"Sondage de {userOrNick(ctx.author)}", icon_url = ctx.author.avatar_url) message = await ctx.send(embed = embed) reactions = ['✅', '🤷', '❌'] for i in reactions: @@ -581,7 +487,7 @@ class Utils(commands.Cog): await asyncio.sleep(seconds) message = ctx.author.mention if mention: - mentionList = self._getMentionInString(reminder) + mentionList = getMentionInString(reminder) for i in mentionList: message += f" {i}" try: @@ -589,11 +495,11 @@ class Utils(commands.Cog): await ctx.message.add_reaction(emoji = '✅') except: pass - finalEmbed = discord.Embed(description = self._cleanCodeStringWithMentionAndURLs(reminder), timestamp = timestamp, color = discord.Colour.random()) + finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = timestamp, color = discord.Colour.random()) finalEmbed.set_footer(text=f"Message d'il y a {counter}") links = "" - findedURLs = self._getURLsInString(reminder) + findedURLs = getURLsInString(reminder) for i in range(0, len(findedURLs)): links += f"[Lien {i + 1}]({findedURLs[i]}) · " if len(findedURLs) > 0: diff --git a/src/main.py b/src/main.py index cfa5ce0..3739f62 100644 --- a/src/main.py +++ b/src/main.py @@ -5,9 +5,9 @@ import re import os from discord_slash import SlashCommand from discord.ext import commands -from pytz import timezone customPrefix = os.environ['PREFIX'] customTimezone = os.environ['TIMEZONE'] +from utils.core import userOrNick, goodTimezone client = commands.Bot(command_prefix = customPrefix, case_insensitive = True, intents = discord.Intents.all()) slash = SlashCommand(client, sync_commands = True) @@ -104,18 +104,18 @@ async def on_message(message): embed.set_author(name = "Citation", icon_url = msgID.author.avatar_url) icon_url = message.author.avatar_url - date_1 = goodTimezone(msgID.created_at, 0) + date_1 = goodTimezone(msgID.created_at, 0, customTimezone) edit = "" if msgID.edited_at: - date_edit = goodTimezone(msgID.edited_at, 0) + date_edit = goodTimezone(msgID.edited_at, 0, customTimezone) edit = f" et modifié le {date_edit[0][8:]}/{date_edit[0][5:-3]}/{date_edit[0][:4]} à {date_edit[1]}" messageDuBas = f"Posté le {date_1[0][8:]}/{date_1[0][5:-3]}/{date_1[0][:4]} à {date_1[1]}{edit}" - date_2 = goodTimezone(message.created_at, 0) + date_2 = goodTimezone(message.created_at, 0, customTimezone) date_2 = f"{date_2[0][8:]}/{date_2[0][5:-3]}/{date_2[0][:4]} à {date_2[1]}" if auteur == "Auteur": - messageDuBas = messageDuBas + f"\nCité par {user_or_nick(message.author)} le {date_2}" + messageDuBas = messageDuBas + f"\nCité par {userOrNick(message.author)} le {date_2}" embed.set_footer(icon_url = icon_url, text = messageDuBas) if message.content == linkURL.replace(' ',''): await message.channel.send(embed = embed) @@ -127,17 +127,5 @@ async def on_message(message): if not "invalid literal for int() with base 10:" in e or not "404 Not Found (error code: 10008)" in e: # faute de frappe / message supprimé print(e) -def user_or_nick(user): - if user.nick: - return f"{user.nick} ({user.name}#{user.discriminator})" - else: - return f"{user.name}#{user.discriminator}" - -def goodTimezone(date, type): - if type == 0: - return str(timezone(customTimezone).fromutc(date))[:-13].replace('-', '/').split() - elif type == 1: - return str(timezone(customTimezone).fromutc(date))[:-13].replace('-', '/').replace(' ', ' à ') - print("Connexion à Discord...", end = " ") client.run(os.environ['TOKEN_DISCORD']) diff --git a/src/utils/core.py b/src/utils/core.py new file mode 100644 index 0000000..14945c8 --- /dev/null +++ b/src/utils/core.py @@ -0,0 +1,153 @@ +import re +import json +import requests +import time +from pytz import timezone +from datetime import datetime + +def goodTimezone(date, type, tz): + """renvoie une date en fonction d'un timezone""" + if type == 0: + return str(timezone(tz).fromutc(date))[:-13].replace('-', '/').split() + elif type == 1: + return str(timezone(tz).fromutc(date))[:-13].replace('-', '/').replace(' ', ' à ') + +def map_list_among_us(map): + """Sélecteur de map pour la commande amongus⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + maps = {} + maps["skeld"] = ["skeld", "the skeld", "theskeld"] + maps["mira"] = ["mira", "mira hq", "mirahq"] + maps["polus"] = ["polus"] + maps["airship"] = ["airship", "air ship"] + if map == "all": + return maps["skeld"] + maps["mira"] + maps["polus"] + maps["airship"] + return maps[map] + +def get_age(date): + """Recupère un age précisément à la seconde près""" + joursRestants = datetime.now() - date + years = joursRestants.total_seconds() / (365.242 * 24 * 3600) + months = (years - int(years)) * 12 + days = (months - int(months)) * (365.242 / 12) + hours = (days - int(days)) * 24 + minutes = (hours - int(hours)) * 60 + seconds = (minutes - int(minutes)) * 60 + return (int(years), int(months), int(days), int(hours), int(minutes), int(seconds)) + +def ageLayout(tuple): + """avec la méthode 'get_age', permet de mettre en forme un âge⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + time = {} + time[0], time[1], time[2], time[3], time[4], time[5] = "an", "mois", "jour", "heure", "minute", "seconde" + for i in range(len(tuple)): + if tuple[i] > 1 and i != 1: + time[i] = time[i] + "s" + message = "" + if tuple[5] > 0: # pour les secondes + affichage = [5] # on affiche que : seconde + if tuple[4] > 0: + affichage = [4, 5] # on affiche : minute + seconde + if tuple[3] > 0: + affichage = [3, 4, 5] # on affiche : heure + minute + seconde + if tuple[2] > 0: + affichage = [2, 3, 4] # on affiche : jour + heure + minute + if tuple[1] > 0: + affichage = [1, 2, 3] # on affiche : mois + jour + heure + if tuple[0] > 0: + affichage = [0, 1, 3] # on affiche : an + mois + heure + for i in affichage: + message = message + f", {tuple[i]} {time[i]}" + return message[2:] + +def userOrNick(user): + """Affiche le pseudo et/ou le surnom""" + if user == None: + return "Utilisateur inconnu" # Mauvais copié/collé -> changement d'ID + if user.nick: + return f"{user.nick} ({user.name}#{user.discriminator})" + else: + return f"{user.name}#{user.discriminator}" + +def cleanUser(ctx, stringMessage, stringID): + """récupère l'utilisateur avec son id""" + stringMessage = stringMessage.replace("<@!", "").replace(">", "").replace("<@", "") # améliorer ça avec du regex + associatedID = userOrNick(ctx.author.guild.get_member(int(stringID))) + try: + stringMessage = stringMessage.replace(stringID, associatedID) + except: + pass + return stringMessage + +def cleanCodeStringWithMentionAndURLs(string): + """formate un string avec des ` tout en gardant les mention et les liens""" + string = f"`{removeStartEndSpacesString(string)}`" + + findedMention = getMentionInString(string) + for i in range(0, len(findedMention)): + string = string.replace(findedMention[i], f"`{findedMention[i]}`") # conserve la mention dans le message + + if string.startswith("``<@"): # conserve le format quand mention au début de la string + string = string[2:] + if string.endswith(">``"): # conserve le format quand mention à la fin de la string + string = string[:-2] + string = string.replace("``", "") # conserve le format quand deux mentions sont collés + return string + +def getMentionInString(string): + """récupère les mentions dans un string⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + findedMention = [] + for findingMention in re.findall(r'<@[!]?\d*>', string): # récupération mention dans le string + findedMention.append(findingMention) + findedMention = list(dict.fromkeys(findedMention)) # suppression doublon de mention dans la liste + return findedMention + +def getURLsInString(string): + """récupère les liens dans un string""" + findedURLs = [] + for findingMention in re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', string): # récupération URLs dans le string + findedURLs.append(findingMention) + return findedURLs + +def removeStartEndSpacesString(string): + """Retire les espaces en trop au début et à la fin d'un string⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + while string.startswith(" "): + string = string[1:] + while string.endswith(" "): + string = string[:-1] + return string + +def randomImage(link): + """Récupération d'une image aléatoirement⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + temps_requete = int(round(time.time() * 1000)) + try: + request_data = requests.get(link) + except Exception as e: + raise Exception(f"Une erreur s'est produite lors de la tentative de demande de l'API {link} : {e}") + + if not request_data.status_code == 200: + raise Exception(f"Code HTTP {request_data.status_code} au lieu de HTTP 200 à l'appel de {link} : {request_data.text}") + + try: + json_data = json.loads(request_data.text) + except Exception as e: + raise Exception(f"Erreur lors de la transformation les données de {link} en json : {e}") + + temps_requete = int(round(time.time() * 1000)) - temps_requete + return (json_data, temps_requete) + +def retirerDoublons(liste): + """Supprime les doublons d'une liste""" + Newliste = [] + for element in liste: + if element not in Newliste: + Newliste.append(element) + return Newliste + +def ligneFormatage(ligne): + """Traduit en français les balises dans les lyrics d'une chanson""" + liste_balise = [ + ('[Hook', '[Accroche'), ('[Verse', '[Couplet'), ('[Chorus', '[Chœur'), + ('[Bridge', '[Pont'),('[Pre-Chorus', '[Pré-chœur'), ('[Post-Chorus', '[Post-chœur') + ] + for balises in liste_balise: + ligne = ligne.replace(balises[0], balises[1]) + return ligne From e96fad8bf160ce9aabd26250e466451ca2d13c33 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 16:07:21 +0200 Subject: [PATCH 073/286] real correction due to the new slash command whose commands were bugging if they had arguments --- src/cogs/fun.py | 6 ++++-- src/cogs/games.py | 4 +++- src/cogs/internet.py | 4 +++- src/cogs/school.py | 4 +++- src/cogs/utils.py | 22 ++++++++++++++++------ 5 files changed, 29 insertions(+), 11 deletions(-) diff --git a/src/cogs/fun.py b/src/cogs/fun.py index f8bc4b1..1f81b6d 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -119,14 +119,16 @@ class Fun(commands.Cog): return await self._love(ctx, user1, True) @commands.command(name='8ball', aliases=['8b', '8balls']) - async def _8ball(self, ctx, fromSlash = False): + async def _8ball(self, ctx, fromSlash = None): """Répond à ta question 🔮.\n ➡ Syntaxe: {PREFIX}8ball/8b⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + if fromSlash == None: + fromSlash = False reponses=["c'est sûr.","il en est décidément ainsi.","incontestablement.","oui sans aucun doute.","tu peux t'y fier.","tel que je le vois, oui.","c'est le plus probable.", "cela montre de bonnes perspectives.","certes.","les signes indiquent que oui.","ma réponse est oui.","ta question est trop floue, réessaie.","redemandes plus tard stp.", "je ferais mieux de pas te le dire maintenant...","je ne peux pas le prédire actuellement :/","concentre-toi et redemande.","n'y comptes pas trop.","ma réponse est non.", "mes sources disent que non.", "les perspectives ne sont pas si bonnes...","c'est très douteux."] if fromSlash != True: - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') return await ctx.send(f"{ctx.author.mention}, {choice(reponses)}") @_8ball.error async def _8ball_error(self, ctx, error): diff --git a/src/cogs/games.py b/src/cogs/games.py index 95d7bdf..a420dbe 100644 --- a/src/cogs/games.py +++ b/src/cogs/games.py @@ -103,8 +103,10 @@ class Games(commands.Cog): await ctx.send(f"T'as pas trouvé {ctx.author.mention}... dommage, c'était {number}.") @commands.command(name='pileouface', aliases=['pf']) - async def _pileouface(self, ctx, fromSlash = False): + async def _pileouface(self, ctx, fromSlash = None): """Pile ou face.\n ➡ Syntaxe: {PREFIX}pileouface/pf""" + if fromSlash == None: + fromSlash = False if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') return await ctx.send(f"{'Pile' if randint(0,1) == 1 else 'Face'} !") diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 6a09f4a..9e4e40f 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -107,8 +107,10 @@ class Internet(commands.Cog): return await self._cat(ctx, True) @commands.command(name='dog', aliases = ['chien']) - async def _dog(self, ctx, fromSlash = False): + async def _dog(self, ctx, fromSlash = None): """Te montre un magnifique chien\n ➡ Syntaxe: {PREFIX}dog/chien""" + if fromSlash == None: + fromSlash = False if ctx.author.nick: name = f"{ctx.author.nick} ({ctx.author.name}#{ctx.author.discriminator})" diff --git a/src/cogs/school.py b/src/cogs/school.py index 8a53dd4..caf7557 100644 --- a/src/cogs/school.py +++ b/src/cogs/school.py @@ -76,8 +76,10 @@ class School(commands.Cog): pass @commands.command(name='getid', hidden = True) - async def _getid(self, ctx, fromSlash = False): + async def _getid(self, ctx, fromSlash = None): """Tuto vidéo sur comment récupérer l'ID d'un utilisateur/salon⁢⁢⁢⁢⁢""" + if fromSlash == None: + fromSlash = False if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') return await ctx.send("Explication sur comment récuperer l'ID d'un utilisateur/salon : https://cdn.discordapp.com/attachments/640312926892195842/780802253258358834/GetID.mp4") diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 00fe9bf..a48ff1b 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -123,8 +123,10 @@ class Utils(commands.Cog): return await self._calc(ctx, calcul, True) @commands.command(name='syntax') - async def _syntax(self, ctx, fromSlash = False): + async def _syntax(self, ctx, fromSlash = None): """Informations pour bien éditer son texte.⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + if fromSlash == None: + fromSlash = False syntaxe = "-----------------------------------------------------\n" syntaxe += discord.utils.escape_markdown("```Js\n") syntaxe += discord.utils.escape_markdown("//code en js (possible de remplacer 'js' par d'autres languages . adaptez le !)\n") @@ -165,8 +167,11 @@ class Utils(commands.Cog): syntaxe += "-----------------------------------------------------\n" syntaxe += discord.utils.escape_markdown(">>> cette ligne est cité\ncelle là aussi (et elles le seront toutes!)\n") syntaxe += ">>> cette ligne est cité\ncelle là aussi (et elles le seront toutes!)\n" - if fromSlash != True: - await ctx.message.add_reaction(emoji = '✅') + try: + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + except: + pass await ctx.send(syntaxe) @cog_ext.cog_slash(name="syntax", description = "Informations pour bien éditer son texte.") async def __syntax(self, ctx): @@ -210,8 +215,10 @@ class Utils(commands.Cog): return await self._memo(ctx, memo, True) @commands.command(name='infos', aliases = ['info']) - async def _infos(self, ctx, fromSlash = False): + async def _infos(self, ctx, fromSlash = None): """Donne des infos sur le bot.\n ➡ Syntaxe: {PREFIX}infos/info⁢""" + if fromSlash == None: + fromSlash = False appinfo = await self.client.application_info() embed = discord.Embed(color = discord.Colour.random()) @@ -244,8 +251,11 @@ class Utils(commands.Cog): embed.add_field(name = "Timezone", value = f"`{self.customTimezone}`") embed.add_field(name = "Version", value = f"`{version}`") embed.set_footer(text = f"Basé sur discord.py {discord.__version__}") - if fromSlash != True: - await ctx.message.add_reaction(emoji = '✅') + try: + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + except: + pass await ctx.send(embed = embed) @cog_ext.cog_slash(name="infos", description = "Donne des infos sur le bot.") async def __infos(self, ctx): From 6afa48fc1390737b53f59f13052e180f6f7d37c5 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 16:21:32 +0200 Subject: [PATCH 074/286] adding canary links to the citation --- src/main.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main.py b/src/main.py index 3739f62..73473bd 100644 --- a/src/main.py +++ b/src/main.py @@ -53,13 +53,15 @@ async def on_message(message): urls = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', message.content) for i in range(len(urls)): - if urls[i].startswith("https://discordapp.com/channels/") or urls[i].startswith("https://discord.com/channels/") or urls[i].startswith("https://ptb.discordapp.com/"): + if urls[i].startswith("https://discordapp.com/channels/") or urls[i].startswith("https://discord.com/channels/") or urls[i].startswith("https://ptb.discordapp.com/") or urls[i].startswith("https://canary.discordapp.com/"): link = urls[i] linkURL = link - if link.startswith("https://discord.com/channels/"): + if link.startswith("https://discord.com/"): link = f'000{link}' if link.startswith("https://ptb.discordapp.com/"): link = link[4:] + if link.startswith("https://canary.discordapp.com/"): + link = link[7:] if "@me" in urls[i]: return await message.channel.send("Je ne cite pas les messages privés.", delete_after = 5) try: From ad1360d3ea3318fbb3f7c7ba27131cb3075c5d89 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 16:43:35 +0200 Subject: [PATCH 075/286] fix support for citation for ptb and canary with new domain --- src/main.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/main.py b/src/main.py index 73473bd..7f48315 100644 --- a/src/main.py +++ b/src/main.py @@ -52,18 +52,21 @@ async def on_message(message): await ctx.send(f">>> Coucou !\nMon préfix est `{prefix}` et ma commande d'aide est `{prefix}help`") urls = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', message.content) + httpsString = "https://" + channelsString = "discord.com/channels/" for i in range(len(urls)): - if urls[i].startswith("https://discordapp.com/channels/") or urls[i].startswith("https://discord.com/channels/") or urls[i].startswith("https://ptb.discordapp.com/") or urls[i].startswith("https://canary.discordapp.com/"): + if urls[i].startswith(f"{httpsString}{channelsString}") or urls[i].startswith(f"{httpsString}ptb.{channelsString}") or urls[i].startswith(f"{httpsString}canary.{channelsString}"): link = urls[i] linkURL = link - if link.startswith("https://discord.com/"): + if link.startswith(f"{httpsString}{channelsString}"): link = f'000{link}' - if link.startswith("https://ptb.discordapp.com/"): + if link.startswith(f"{httpsString}ptb.{channelsString}"): + link = link[1:] + if link.startswith(f"{httpsString}canary.{channelsString}"): link = link[4:] - if link.startswith("https://canary.discordapp.com/"): - link = link[7:] if "@me" in urls[i]: return await message.channel.send("Je ne cite pas les messages privés.", delete_after = 5) + print(link) try: if int(link[32:-38]) == message.guild.id: msgID = await client.get_channel(int(link[51:-19])).fetch_message(int(link[70:])) From 29bf7c3b4ed36a54b019466e11e17d53996c33fe Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 16:44:02 +0200 Subject: [PATCH 076/286] remove print --- src/main.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main.py b/src/main.py index 7f48315..d0b690a 100644 --- a/src/main.py +++ b/src/main.py @@ -66,7 +66,6 @@ async def on_message(message): link = link[4:] if "@me" in urls[i]: return await message.channel.send("Je ne cite pas les messages privés.", delete_after = 5) - print(link) try: if int(link[32:-38]) == message.guild.id: msgID = await client.get_channel(int(link[51:-19])).fetch_message(int(link[70:])) From 8c88ba9efb5bbf07064f9906686e630ac5359ef3 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 20:24:37 +0200 Subject: [PATCH 077/286] ajout du prefix custom dans la gestion des erreurs --- src/main.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main.py b/src/main.py index d0b690a..31baa56 100644 --- a/src/main.py +++ b/src/main.py @@ -34,7 +34,7 @@ async def on_ready(): @client.event async def on_command_error(ctx, error): - if not ctx.invoked_with.startswith('.'): + if not ctx.invoked_with.startswith(customPrefix): print(error) await ctx.message.add_reaction(emoji = '❓') @@ -42,7 +42,6 @@ async def on_command_error(ctx, error): async def on_message(message): await client.process_commands(message) - if message.author == client.user: return From 5ddef1976ae8c5656211d47a1b2f9d6680d96acc Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 20:26:57 +0200 Subject: [PATCH 078/286] ajout commentaires --- src/main.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main.py b/src/main.py index 31baa56..219e0a9 100644 --- a/src/main.py +++ b/src/main.py @@ -5,9 +5,9 @@ import re import os from discord_slash import SlashCommand from discord.ext import commands +from utils.core import userOrNick, goodTimezone customPrefix = os.environ['PREFIX'] customTimezone = os.environ['TIMEZONE'] -from utils.core import userOrNick, goodTimezone client = commands.Bot(command_prefix = customPrefix, case_insensitive = True, intents = discord.Intents.all()) slash = SlashCommand(client, sync_commands = True) @@ -45,11 +45,13 @@ async def on_message(message): if message.author == client.user: return + """informations concernant le bot lorsqu'il est mentionner""" if client.user.mention == message.content.replace("!",""): ctx = await client.get_context(message) prefix = await client.get_prefix(message) await ctx.send(f">>> Coucou !\nMon préfix est `{prefix}` et ma commande d'aide est `{prefix}help`") + """citation""" urls = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', message.content) httpsString = "https://" channelsString = "discord.com/channels/" From b23acae6d487dbcafc12440d672ed29ebf28e225 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 20:54:26 +0200 Subject: [PATCH 079/286] adding ping slash command --- src/cogs/utils.py | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index a48ff1b..d7450bd 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -1,5 +1,4 @@ import discord -import pytz import time import os import re @@ -23,18 +22,40 @@ class Utils(commands.Cog): self.customTimezone = os.environ['TIMEZONE'] @commands.command(name='ping') - async def _ping(self, ctx, *, question = '0'): + async def _ping(self, ctx, *arg): """Affiche mon ping.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}ping [help]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - if question == 'help': + fromSlash = False + if len(arg) > 0: + if arg[-1] == True: + fromSlash = arg[-1] + arg = arg[:-1] + if len(arg) > 0: + arg = arg[0] + else: + arg = None + + if arg == 'help': return await ctx.send(embed = discord.Embed(color = discord.Colour.random(), description = ":hourglass: correspond au temps entre deux battements de cœurs\n\n:stopwatch: correspond au temps que met le client a calculer le ping\n\n:heartbeat: correspond au temps que met le client a réagir au messages")) else: now = int(round(time.time() * 1000)) - ping = now - int(round(ctx.message.created_at.timestamp() * 1000)) + if fromSlash != True: + ping = now - int(round(ctx.message.created_at.timestamp() * 1000)) + else: + ping = now - int(round(ctx.slash_created_at * 1000)) embed = discord.Embed(description = 'Pinging...') message = await ctx.send(embed = embed) ping2 = int(round(time.time() * 1000)) - now await message.edit(embed = discord.Embed(color = discord.Colour.random(), description = f':hourglass: {round(self.client.latency * 1000)} ms\n\n:stopwatch: {ping2} ms\n\n:heartbeat: {ping} ms')) - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + @cog_ext.cog_slash(name="ping", description = "Affiche mon ping.") + async def __ping(self, ctx, arg = None): + ctx.slash_created_at = int(datetime.now(timezone(self.customTimezone)).timestamp()) + if arg == None: + return await self._ping(ctx, True) + else: + return await self._ping(ctx, arg, True) + @commands.command(name='avatar') async def _avatar(self, ctx, *user): @@ -203,7 +224,7 @@ class Utils(commands.Cog): await ctx.message.delete() embed = discord.Embed(description = text, color = discord.Colour.random()) embed.set_author(name = f"Mémo noté depuis {ctx.guild.name}", icon_url = ctx.author.avatar_url) - embed.set_footer(text = f'📝 le {datetime.now(pytz.timezone(self.customTimezone)).strftime("%d/%m/%Y à %H:%M:%S")}') + embed.set_footer(text = f'📝 le {datetime.now(timezone(self.customTimezone)).strftime("%d/%m/%Y à %H:%M:%S")}') await ctx.author.send(embed = embed) return await ctx.send("Tu viens de recevoir ton mémo !", delete_after = 5) @_memo.error From 6683921bbf4a2b8e03e31f942e2539ea468d6dd9 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 21:29:15 +0200 Subject: [PATCH 080/286] =?UTF-8?q?pr=C3=A9cision=20sur=20le=20cogs=20conf?= =?UTF-8?q?reriedukassoulait?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.py b/src/main.py index 219e0a9..039d094 100644 --- a/src/main.py +++ b/src/main.py @@ -20,7 +20,7 @@ client.load_extension("cogs.games") client.load_extension("cogs.fun") client.load_extension("cogs.autopublish") client.load_extension("cogs.school") -client.load_extension("cogs.confreriedukassoulait") +client.load_extension("cogs.confreriedukassoulait") # you can remove this cogs, only for my private guild print("Terminé !") @client.event From 8590c6995503c62703a4e427c5916c9cf933fad3 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 21:30:43 +0200 Subject: [PATCH 081/286] =?UTF-8?q?deplacement=20fonctionnalit=C3=A9=20per?= =?UTF-8?q?so=20dans=20le=20bon=20cog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/confreriedukassoulait.py | 20 ++++++++++++++++++++ src/cogs/internet.py | 17 ----------------- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/src/cogs/confreriedukassoulait.py b/src/cogs/confreriedukassoulait.py index b2126c8..14815d9 100644 --- a/src/cogs/confreriedukassoulait.py +++ b/src/cogs/confreriedukassoulait.py @@ -7,6 +7,7 @@ from datetime import datetime from pytz import timezone customTimezone = os.environ['TIMEZONE'] from utils.core import goodTimezone, userOrNick +from cogs.internet import Internet def setup(client): client.add_cog(ConfrerieDuKassoulait(client)) @@ -102,3 +103,22 @@ class ConfrerieDuKassoulait(commands.Cog): await channel.send(embed = embed) # ne fonctionne pas quand un message a été supprimé avant que le bot ai démarré # info sur la personne qui a supprimé ne fonctionne pas si il a supprimé un message auparavant (les logs se rajoute a un log deja existant) + + + # autre serveur + @commands.Cog.listener() + async def on_message(self, message): + if message.channel.id == 770805818487865404 or message.channel.id == 772239638240165928: # Le groupe de l'amour ❤❤ -- channel chien/chat + chiens = ["dog", "chien", "potichien"] + chats = ["kat", "mace", "kater", "katze", "sinta", "minoos", "cat", "qitt", "besseh", "katu", "caun", "kazh", + "bisig", "moggy", "kotka", "maow", "gat", "we'sa", "guigna", "kodkod", "mao", "koyangi", "ghjattu", "míw", "pussi", + "gato", "gata", "kato", "kass", "domadh", "demmat", "kissa", "chat", "minou", "piscín", "cath", "k'at'a", "muca", "gali", + "gatos", "popoki", "kike", "chatul", "chatula", "billa", "kat poes", "macska", "cica", "kutjing", "kucing", "köttur", + "gatto", "gattina", "neko", "chma", "pising", "feles", "felix", "kakis", "katé", "qattus", "qattusa", "ngeru", "miz", "felino", + "felina", "muur", "katt", "shimii", "billi", "gorbe", "pusa", "kot", "giat", "pisica", "koshka", "pusi", "macka", "mizhu", + "kotsur", "bisad", "büsi", "chatz", "paka", "muc", "poonai", "puunay", "kocour", "kocka", "maa-oh", "kedi", "kit", "con mêo", + "tchèt", "mouss", "ologbo", "kats", "猫", "кот", "고양이", "poticha", "😼", "ʇɐɥɔ"] + if message.content.lower() in chiens: + await Internet()._dog(await self.client.get_context(message)) + if message.content.lower() in chats: + await Internet()._cat(await self.client.get_context(message)) diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 9e4e40f..1a20475 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -16,23 +16,6 @@ class Internet(commands.Cog): def __init__(self, client): self.client = client - @commands.Cog.listener() - async def on_message(self, message): - if message.channel.id == 770805818487865404 or message.channel.id == 772239638240165928: # Le groupe de l'amour ❤❤ -- channel chien/chat - chiens = ["dog", "chien", "potichien"] - chats = ["kat", "mace", "kater", "katze", "sinta", "minoos", "cat", "qitt", "besseh", "katu", "caun", "kazh", - "bisig", "moggy", "kotka", "maow", "gat", "we'sa", "guigna", "kodkod", "mao", "koyangi", "ghjattu", "míw", "pussi", - "gato", "gata", "kato", "kass", "domadh", "demmat", "kissa", "chat", "minou", "piscín", "cath", "k'at'a", "muca", "gali", - "gatos", "popoki", "kike", "chatul", "chatula", "billa", "kat poes", "macska", "cica", "kutjing", "kucing", "köttur", - "gatto", "gattina", "neko", "chma", "pising", "feles", "felix", "kakis", "katé", "qattus", "qattusa", "ngeru", "miz", "felino", - "felina", "muur", "katt", "shimii", "billi", "gorbe", "pusa", "kot", "giat", "pisica", "koshka", "pusi", "macka", "mizhu", - "kotsur", "bisad", "büsi", "chatz", "paka", "muc", "poonai", "puunay", "kocour", "kocka", "maa-oh", "kedi", "kit", "con mêo", - "tchèt", "mouss", "ologbo", "kats", "猫", "кот", "고양이", "poticha", "😼", "ʇɐɥɔ"] - if message.content.lower() in chiens: - await self._dog(await self.client.get_context(message)) - if message.content.lower() in chats: - await self._cat(await self.client.get_context(message)) - @commands.command(name='memes', aliases = ['meme']) async def _memes(self, ctx, *args): """Envois un meme de reddit.\n ➡ Syntaxe: {PREFIX}memes/meme [subreddit]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" From e4a7122ea80895e0a439ad810a887f89dd910775 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 21:55:04 +0200 Subject: [PATCH 082/286] ajout commande s*xe dans les slash --- src/cogs/internet.py | 39 +++++++++++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 1a20475..bf2231c 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -71,7 +71,7 @@ class Internet(commands.Cog): @commands.command(name='cat', aliases = ['chat']) async def _cat(self, ctx, fromSlash = False): - """Te montre un magnifique chat\n ➡ Syntaxe: {PREFIX}cat/chat""" + """Te montre un magnifique chat.\n ➡ Syntaxe: {PREFIX}cat/chat""" if ctx.author.nick: name = f"{ctx.author.nick} ({ctx.author.name}#{ctx.author.discriminator})" @@ -85,13 +85,13 @@ class Internet(commands.Cog): await ctx.message.add_reaction(emoji = '✅') message = await ctx.send(embed=embed) return await message.add_reaction('❤️') - @cog_ext.cog_slash(name="cat", description = "Te montre un magnifique chat") + @cog_ext.cog_slash(name="cat", description = "Te montre un magnifique chat.") async def __cat(self, ctx): return await self._cat(ctx, True) @commands.command(name='dog', aliases = ['chien']) async def _dog(self, ctx, fromSlash = None): - """Te montre un magnifique chien\n ➡ Syntaxe: {PREFIX}dog/chien""" + """Te montre un magnifique chien.\n ➡ Syntaxe: {PREFIX}dog/chien""" if fromSlash == None: fromSlash = False @@ -107,14 +107,28 @@ class Internet(commands.Cog): await ctx.message.add_reaction(emoji = '✅') message = await ctx.send(embed=embed) return await message.add_reaction('❤️') - @cog_ext.cog_slash(name="dog", description = "Te montre un magnifique chien") + @cog_ext.cog_slash(name="dog", description = "Te montre un magnifique chien.") async def __dog(self, ctx): return await self._dog(ctx, True) @commands.command(name='sexe', aliases=['sexes', 'nude', 'nudes', 'nsfw']) - async def _sexe(self, ctx, *, choice_of_nsfw = None): + async def _sexe(self, ctx, *choice_of_nsfw): """Envois une image coquine. (NSFW)\n ➡ Syntaxe: {PREFIX}sexe/sexes/nude/nudes [butts/boobs]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + fromSlash = False + if len(choice_of_nsfw) > 0: + if choice_of_nsfw[-1] == True: + fromSlash = choice_of_nsfw[-1] + choice_of_nsfw = choice_of_nsfw[:-1] + if len(choice_of_nsfw) > 0: + choice_of_nsfw = choice_of_nsfw[0] + else: + choice_of_nsfw = None + liste_hot = ['butts', 'boobs'] + if choice_of_nsfw == 'butt': + choice_of_nsfw = 'butts' + if choice_of_nsfw == 'boob': + choice_of_nsfw = 'boobs' if choice_of_nsfw in liste_hot: pass else: @@ -122,13 +136,22 @@ class Internet(commands.Cog): if ctx.channel.is_nsfw(): embed = discord.Embed(title = f"{choice_of_nsfw.capitalize()} pour {ctx.author.name}", colour = discord.Colour.random()) nsfw = randomImage(f'http://api.o{choice_of_nsfw}.ru/noise/') + print(nsfw) embed.set_image(url = f"http://media.o{choice_of_nsfw}.ru/{nsfw[0][0]['preview']}") - embed.set_footer(text = f"o{choice_of_nsfw}.ru a pris {nsfw[1]} ms.") - await ctx.message.add_reaction(emoji = '✅') + embed.set_footer(text = f"o{choice_of_nsfw}.ru a pris {nsfw[1]} ms pour sortir l'image n°{nsfw[0][1]}-{nsfw[1]}.") + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') await ctx.send(embed = embed) else: - await ctx.message.add_reaction(emoji = '❌') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '❌') await ctx.send(f"Désolé mais je n'envois ce genre de message seulement dans les salons NSFW !") + @cog_ext.cog_slash(name="sexe", description = "Envois une image coquine. (NSFW)") + async def __sexe(self, ctx, buttsorboobs = None): + if buttsorboobs == None: + return await self._sexe(ctx, True) + else: + return await self._sexe(ctx, buttsorboobs, True) @commands.command(name='news', aliases=['rss']) async def _news(self, ctx, *arg): From 3233b7b7091cd108bab016139a01f69139c7846f Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 22:10:40 +0200 Subject: [PATCH 083/286] suppression print de deboguage --- src/cogs/internet.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/cogs/internet.py b/src/cogs/internet.py index bf2231c..1d240fb 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -136,7 +136,6 @@ class Internet(commands.Cog): if ctx.channel.is_nsfw(): embed = discord.Embed(title = f"{choice_of_nsfw.capitalize()} pour {ctx.author.name}", colour = discord.Colour.random()) nsfw = randomImage(f'http://api.o{choice_of_nsfw}.ru/noise/') - print(nsfw) embed.set_image(url = f"http://media.o{choice_of_nsfw}.ru/{nsfw[0][0]['preview']}") embed.set_footer(text = f"o{choice_of_nsfw}.ru a pris {nsfw[1]} ms pour sortir l'image n°{nsfw[0][1]}-{nsfw[1]}.") if fromSlash != True: From 65325f8b5d8cf7e355d79504a140169211ad6bda Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 23:17:21 +0200 Subject: [PATCH 084/286] ajout help slash command + cog desc in regular help --- src/cogs/help.py | 36 ++++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/src/cogs/help.py b/src/cogs/help.py index cfbd76c..c5b801a 100644 --- a/src/cogs/help.py +++ b/src/cogs/help.py @@ -1,5 +1,6 @@ import discord from discord.ext import commands +from discord_slash import cog_ext def setup(client): client.add_cog(Help(client)) @@ -14,9 +15,14 @@ class Help(commands.Cog): @commands.command(name='help') async def _help(self, ctx, *cog): """Affiche toutes les commandes du bot.\n ➡ Syntaxe: {PREFIX}help [catégorie]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - if not cog: - """Liste des Cog""" - halp=discord.Embed(title = 'Liste des catégories et commandes sans catégorie', + fromSlash = False + if len(cog) > 0: + if cog[-1] == True: + fromSlash = cog[-1] + cog = cog[:-1] + + if not cog: # Liste des Cog + halp = discord.Embed(title = 'Liste des catégories et commandes sans catégorie', description = f'Utilisez `{ctx.prefix}help [catégorie]` pour en savoir plus sur elles et leur commande.', color = discord.Colour.random()) for name_cog in self.client.cogs: @@ -27,7 +33,7 @@ class Help(commands.Cog): liste_cmds += f", `{ctx.prefix}{cmds.name}`" nb_cmds += 1 if name_cog != "Help" and nb_cmds > 0: - halp.add_field(name = f'**{name_cog} — {nb_cmds}**', value = liste_cmds[2:], inline = False) + halp.add_field(name = f'**{name_cog} ({nb_cmds}) — {self.client.cogs[name_cog].__doc__}**', value = liste_cmds[2:], inline = False) cmds_desc = '' for y in self.client.walk_commands(): if not y.cog_name and not y.hidden: @@ -35,15 +41,14 @@ class Help(commands.Cog): if len(cmds_desc) > 1: halp.add_field(name = 'Commandes sans catégorie', value = cmds_desc[0:len(cmds_desc)-1], inline = False) - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') await ctx.send(embed = halp) - else: - """Avertissement si il y a trop d'arguments dans la variable cog""" + else: # Avertissement si il y a trop d'arguments dans la variable cog if len(cog) > 1: halp = discord.Embed(title = 'Erreur !', description = "Tu as renseigné trop d'arguments !", color = 0xC41B1B) await ctx.send(embed = halp) - else: - """Liste des commandes avec cogs.""" + else: # Liste des commandes avec cogs. cog = [item.capitalize() for item in cog] found = False for x in self.client.cogs: @@ -57,10 +62,17 @@ class Help(commands.Cog): backslash = '\n' halp.add_field(name = f"`{ctx.prefix}{c.name}` - {str(c.help).split(backslash)[0]}", value = f"{''.join(cmds_help)}\u200b", inline = False) found = True - if not found: - """Rappel si le cog n'existe pas.""" + if not found: # Rappel si le cog n'existe pas. await ctx.message.add_reaction(emoji = '❌') halp = discord.Embed(title = 'Erreur !', description = f"Qu'est ce que {cog[0]} ?", color = 0xC41B1B) else: - await ctx.message.add_reaction(emoji = '✅') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') await ctx.send('', embed = halp) + @cog_ext.cog_slash(name="help", description = "Envois un meme de reddit.") + async def __help(self, ctx, cog = None): + ctx.prefix = "/" + if cog == None: + return await self._help(ctx, True) + else: + return await self._help(ctx, cog, True) From ae0d2864689195a9e065f17ac9e031e817e0055a Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 23:19:12 +0200 Subject: [PATCH 085/286] change comment --- src/cogs/music.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/music.py b/src/cogs/music.py index e7c20bb..ed6ca54 100644 --- a/src/cogs/music.py +++ b/src/cogs/music.py @@ -271,7 +271,7 @@ class VoiceState: class Music(commands.Cog): - """Commandes relatives à la musique - © vbe0201.""" + """Commandes relatives à la musique © vbe0201.""" def __init__(self, client: commands.bot): self.client = client self.voice_states = {} From c9b759e7b886e879d29a4c69afe3e6b34f38356f Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 23:21:57 +0200 Subject: [PATCH 086/286] disclaimer slash commands not working --- src/cogs/music.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/music.py b/src/cogs/music.py index ed6ca54..b871d73 100644 --- a/src/cogs/music.py +++ b/src/cogs/music.py @@ -271,7 +271,7 @@ class VoiceState: class Music(commands.Cog): - """Commandes relatives à la musique © vbe0201.""" + """Commandes relatives à la musique © vbe0201. (slash commands not working)""" def __init__(self, client: commands.bot): self.client = client self.voice_states = {} From d6f3b6462c01d9f757129ac0085e87c7f73e3349 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 23:28:54 +0200 Subject: [PATCH 087/286] precision mock command for slash --- src/cogs/fun.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/fun.py b/src/cogs/fun.py index 1f81b6d..c68ff7c 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -140,7 +140,7 @@ class Fun(commands.Cog): @commands.command(name='mock') async def _mock(self, ctx): - """Se moque du message précédent⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Se moque du message précédent. - Slash command not available⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" first = 0 suite_auteur = None temps_limite = (await ctx.message.channel.history(limit = 2).flatten())[1].created_at - timedelta(minutes = 5) From df2ae8f6f193af508a1d25b90e4f09ecdb8dc903 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 23:29:24 +0200 Subject: [PATCH 088/286] adding "plus ou moins" in slash commands --- src/cogs/games.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/cogs/games.py b/src/cogs/games.py index a420dbe..97a02fe 100644 --- a/src/cogs/games.py +++ b/src/cogs/games.py @@ -101,6 +101,9 @@ class Games(commands.Cog): await ctx.send(f"Erreur dans la réponse {ctx.author.mention}, merci de n'écrire qu'un nombre. Tapez `stop` pour arrêter le jeu.") del self.guessing_game[str(ctx.author.id)] await ctx.send(f"T'as pas trouvé {ctx.author.mention}... dommage, c'était {number}.") + @cog_ext.cog_slash(name="plusoumoins", description = "Un plus ou moins entre 1 et 100.") + async def __plusoumoins(self, ctx): + await self._plusoumoins(ctx) @commands.command(name='pileouface', aliases=['pf']) async def _pileouface(self, ctx, fromSlash = None): From b22058fc77da445f09832e0cab7924bccc640077 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 23:47:02 +0200 Subject: [PATCH 089/286] ajout commande invite --- src/cogs/help.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/cogs/help.py b/src/cogs/help.py index c5b801a..bf049ad 100644 --- a/src/cogs/help.py +++ b/src/cogs/help.py @@ -6,7 +6,7 @@ def setup(client): client.add_cog(Help(client)) class Help(commands.Cog): - """Listes des commandes et/ou catégories.""" + """Commandes relatives à l'aide utilisateur.""" def __init__(self, client): self.client = client @@ -76,3 +76,16 @@ class Help(commands.Cog): return await self._help(ctx, True) else: return await self._help(ctx, cog, True) + + @commands.command(name='invite') + async def _invite(self, ctx, fromSlash = None): + """Invite ce bot sur ton serveur !""" + if fromSlash == None: + fromSlash = False + embed = discord.Embed(description = f"[Lien vers l'invitation Discord](https://discord.com/api/oauth2/authorize?client_id={self.client.user.id}&permissions=0&scope=bot%20applications.commands)").set_author(name="Invite moi !") + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + return await ctx.send(embed = embed) + @cog_ext.cog_slash(name="invite", description = "Invite ce bot sur ton serveur !") + async def __invite(self, ctx): + return await self._invite(ctx, True) From 7f41c596935ebb7283c29ce9e45c28ffbf147a34 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 31 May 2021 23:51:02 +0200 Subject: [PATCH 090/286] ajout permission administrateur --- src/cogs/help.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/help.py b/src/cogs/help.py index bf049ad..cbf8473 100644 --- a/src/cogs/help.py +++ b/src/cogs/help.py @@ -82,7 +82,7 @@ class Help(commands.Cog): """Invite ce bot sur ton serveur !""" if fromSlash == None: fromSlash = False - embed = discord.Embed(description = f"[Lien vers l'invitation Discord](https://discord.com/api/oauth2/authorize?client_id={self.client.user.id}&permissions=0&scope=bot%20applications.commands)").set_author(name="Invite moi !") + embed = discord.Embed(description = f"[Lien vers l'invitation Discord](https://discord.com/api/oauth2/authorize?client_id={self.client.user.id}&permissions=8&scope=bot%20applications.commands)").set_author(name="Invite moi !") if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') return await ctx.send(embed = embed) From 718ac774d2ac7f194b9f067c8d8582abc05436cf Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 1 Jun 2021 00:27:16 +0200 Subject: [PATCH 091/286] ajout commande random --- src/cogs/fun.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/cogs/fun.py b/src/cogs/fun.py index c68ff7c..5e95f04 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -178,3 +178,30 @@ class Fun(commands.Cog): return await ctx.send("".join(message).replace("\\N", "\n").replace("\\n", "\n")) else: return await ctx.send("Le message ne contient aucun texte.", delete_after = 5) + + @commands.command(name='random', aliases=['randint']) + async def _random(self, ctx, *n): + """Tire au hasard un chiffre entre 1 et n (par défaut n=10)\n ➡ Syntaxe: {PREFIX}random/randint [n]""" + fromSlash = False + if len(n) > 0: + if n[-1] == True: + fromSlash = n[-1] + n = n[:-1] + if len(n) > 0: + try: + n = int(n[0]) + except: + return await ctx.send("Veuillez renseigner un chiffre valide.") + else: + n = 10 + + resultat = randint(1, n) + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + return await ctx.send(embed = discord.Embed().set_author(name = f"Tu as tiré le chiffre {resultat} !")) + @cog_ext.cog_slash(name="random", description = "Tire au hasard un chiffre entre 1 et n (par défaut n=10)") + async def __random(self, ctx, n: int = None): + if n == None: + await self._random(ctx, True) + else: + await self._random(ctx, n, True) From 06462290d5947ad5b17820d651a6b2882904a625 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 1 Jun 2021 00:51:43 +0200 Subject: [PATCH 092/286] fix cat and dog for private server --- src/cogs/confreriedukassoulait.py | 4 ++-- src/cogs/help.py | 2 +- src/cogs/internet.py | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/cogs/confreriedukassoulait.py b/src/cogs/confreriedukassoulait.py index 14815d9..bec9ea7 100644 --- a/src/cogs/confreriedukassoulait.py +++ b/src/cogs/confreriedukassoulait.py @@ -119,6 +119,6 @@ class ConfrerieDuKassoulait(commands.Cog): "kotsur", "bisad", "büsi", "chatz", "paka", "muc", "poonai", "puunay", "kocour", "kocka", "maa-oh", "kedi", "kit", "con mêo", "tchèt", "mouss", "ologbo", "kats", "猫", "кот", "고양이", "poticha", "😼", "ʇɐɥɔ"] if message.content.lower() in chiens: - await Internet()._dog(await self.client.get_context(message)) + await Internet(self.client)._dog(self, await self.client.get_context(message)) if message.content.lower() in chats: - await Internet()._cat(await self.client.get_context(message)) + await Internet(self.client)._cat(self, await self.client.get_context(message)) diff --git a/src/cogs/help.py b/src/cogs/help.py index cbf8473..6face42 100644 --- a/src/cogs/help.py +++ b/src/cogs/help.py @@ -69,7 +69,7 @@ class Help(commands.Cog): if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') await ctx.send('', embed = halp) - @cog_ext.cog_slash(name="help", description = "Envois un meme de reddit.") + @cog_ext.cog_slash(name="help", description = "Affiche toutes les commandes du bot.") async def __help(self, ctx, cog = None): ctx.prefix = "/" if cog == None: diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 1d240fb..248cddf 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -18,7 +18,7 @@ class Internet(commands.Cog): @commands.command(name='memes', aliases = ['meme']) async def _memes(self, ctx, *args): - """Envois un meme de reddit.\n ➡ Syntaxe: {PREFIX}memes/meme [subreddit]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Envoie un meme de reddit.\n ➡ Syntaxe: {PREFIX}memes/meme [subreddit]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" fromSlash = False if len(args) > 0: if args[-1] == True: @@ -62,7 +62,7 @@ class Internet(commands.Cog): print(f"Error in _memes command = args: {args}, subreddit: {subredditchoix}, error: {error}") await ctx.message.add_reaction(emoji = '❌') return await ctx.send(f"Ce subreddit est interdit, mis en quarantaine ou n'existe pas. ({subredditchoix})") - @cog_ext.cog_slash(name="meme", description = "Envois un meme de reddit.") + @cog_ext.cog_slash(name="meme", description = "Envoie un meme de reddit.") async def __memes(self, ctx, subreddit = None): if subreddit == None: return await self._memes(ctx, True) From 65c01f47bd67caec84a951fd0cbe1fbc981d4623 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 1 Jun 2021 01:01:54 +0200 Subject: [PATCH 093/286] suppression du double message quand un meme de reddit ne rentre pas dans un embed --- src/cogs/internet.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 248cddf..cda9fd9 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -51,8 +51,7 @@ class Internet(commands.Cog): embed.set_image(url = submission.url) message = await ctx.send(embed = embed) else: - await ctx.send(f"```r/{subredditchoix} pour {ctx.author.name}```\n{submission.url}") - message = await ctx.send("```Meme de Reddit```") + message = await ctx.send(f"```r/{subredditchoix} pour {ctx.author.name}```\n{submission.url}") if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') await message.add_reaction('👍') From 6776f34d111b97cc7d814b65d372e85872fa798d Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 1 Jun 2021 01:13:07 +0200 Subject: [PATCH 094/286] update subreddit + fix error meme for slash commands --- src/cogs/internet.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/cogs/internet.py b/src/cogs/internet.py index cda9fd9..3a68c1b 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -32,9 +32,9 @@ class Internet(commands.Cog): if args: # s'il y a un subreddit de défini subredditchoix = args else: # s'il n'y en a pas - subredditchoix = choice(['memes', 'anime_irl', 'goodanimemes', 'BikiniclienttomTwitter', 'dankmemes', 'DeepFried', + subredditchoix = choice(['memes', 'goodanimemes', 'BikiniclienttomTwitter', 'dankmemes', 'DeepFried', 'educationalmemes', 'funny', 'marvelmemes', 'me_irl', 'meme', 'MemeEconomy', 'Memes_Of_The_Dank', 'MinecraftMemes', - 'physicsmemes', 'reactiongifs', 'blackpeopletwitter', 'metal_me_irl', 'bee_irl', '195', 'shittyadviceanimals', 'meirl', + 'physicsmemes', 'blackpeopletwitter', 'metal_me_irl', '195', 'shittyadviceanimals', 'meirl', '2meirl4meirl', 'AdviceAnimals', 'weirdmemes']) try: @@ -59,7 +59,8 @@ class Internet(commands.Cog): except Exception as error: print(f"Error in _memes command = args: {args}, subreddit: {subredditchoix}, error: {error}") - await ctx.message.add_reaction(emoji = '❌') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '❌') return await ctx.send(f"Ce subreddit est interdit, mis en quarantaine ou n'existe pas. ({subredditchoix})") @cog_ext.cog_slash(name="meme", description = "Envoie un meme de reddit.") async def __memes(self, ctx, subreddit = None): From 67f3b694ab9d0b0cd8bc673a1051fc25c27a9241 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 1 Jun 2021 01:30:56 +0200 Subject: [PATCH 095/286] ajout mots --- src/cogs/confreriedukassoulait.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cogs/confreriedukassoulait.py b/src/cogs/confreriedukassoulait.py index bec9ea7..d28e8a2 100644 --- a/src/cogs/confreriedukassoulait.py +++ b/src/cogs/confreriedukassoulait.py @@ -109,7 +109,7 @@ class ConfrerieDuKassoulait(commands.Cog): @commands.Cog.listener() async def on_message(self, message): if message.channel.id == 770805818487865404 or message.channel.id == 772239638240165928: # Le groupe de l'amour ❤❤ -- channel chien/chat - chiens = ["dog", "chien", "potichien"] + chiens = ["dog", "chien", "potichien", "doggo"] chats = ["kat", "mace", "kater", "katze", "sinta", "minoos", "cat", "qitt", "besseh", "katu", "caun", "kazh", "bisig", "moggy", "kotka", "maow", "gat", "we'sa", "guigna", "kodkod", "mao", "koyangi", "ghjattu", "míw", "pussi", "gato", "gata", "kato", "kass", "domadh", "demmat", "kissa", "chat", "minou", "piscín", "cath", "k'at'a", "muca", "gali", @@ -117,7 +117,7 @@ class ConfrerieDuKassoulait(commands.Cog): "gatto", "gattina", "neko", "chma", "pising", "feles", "felix", "kakis", "katé", "qattus", "qattusa", "ngeru", "miz", "felino", "felina", "muur", "katt", "shimii", "billi", "gorbe", "pusa", "kot", "giat", "pisica", "koshka", "pusi", "macka", "mizhu", "kotsur", "bisad", "büsi", "chatz", "paka", "muc", "poonai", "puunay", "kocour", "kocka", "maa-oh", "kedi", "kit", "con mêo", - "tchèt", "mouss", "ologbo", "kats", "猫", "кот", "고양이", "poticha", "😼", "ʇɐɥɔ"] + "tchèt", "mouss", "ologbo", "kats", "猫", "кот", "고양이", "poticha", "😼", "ʇɐɥɔ", "chaton"] if message.content.lower() in chiens: await Internet(self.client)._dog(self, await self.client.get_context(message)) if message.content.lower() in chats: From 380814c9554a6c27b60d274da0b4354b07bd3f32 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 1 Jun 2021 01:31:24 +0200 Subject: [PATCH 096/286] changes on reaction in meme and remove old subreddit --- src/cogs/internet.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 3a68c1b..8aa89dc 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -32,7 +32,7 @@ class Internet(commands.Cog): if args: # s'il y a un subreddit de défini subredditchoix = args else: # s'il n'y en a pas - subredditchoix = choice(['memes', 'goodanimemes', 'BikiniclienttomTwitter', 'dankmemes', 'DeepFried', + subredditchoix = choice(['memes', 'goodanimemes', 'dankmemes', 'DeepFried', 'educationalmemes', 'funny', 'marvelmemes', 'me_irl', 'meme', 'MemeEconomy', 'Memes_Of_The_Dank', 'MinecraftMemes', 'physicsmemes', 'blackpeopletwitter', 'metal_me_irl', '195', 'shittyadviceanimals', 'meirl', '2meirl4meirl', 'AdviceAnimals', 'weirdmemes']) @@ -54,8 +54,8 @@ class Internet(commands.Cog): message = await ctx.send(f"```r/{subredditchoix} pour {ctx.author.name}```\n{submission.url}") if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') - await message.add_reaction('👍') - return await message.add_reaction('👎') + await message.add_reaction('🔺') + return await message.add_reaction('🔻') except Exception as error: print(f"Error in _memes command = args: {args}, subreddit: {subredditchoix}, error: {error}") From 2eb182b73db8c34d807c83088256cae1e764784b Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 1 Jun 2021 21:18:02 +0200 Subject: [PATCH 097/286] fix random command with n < 1 --- src/cogs/fun.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/cogs/fun.py b/src/cogs/fun.py index 5e95f04..9348b57 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -195,7 +195,10 @@ class Fun(commands.Cog): else: n = 10 - resultat = randint(1, n) + x = 1 + if x > n: + x, n = n, x + resultat = randint(x, n) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') return await ctx.send(embed = discord.Embed().set_author(name = f"Tu as tiré le chiffre {resultat} !")) From e1e51379540be547de0ca3db564a8c1fe1261405 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 1 Jun 2021 21:21:13 +0200 Subject: [PATCH 098/286] removing autopublish and adding it to my personal cog --- src/cogs/autopublish.py | 15 --------------- src/cogs/confreriedukassoulait.py | 5 ++++- src/main.py | 1 - 3 files changed, 4 insertions(+), 17 deletions(-) delete mode 100644 src/cogs/autopublish.py diff --git a/src/cogs/autopublish.py b/src/cogs/autopublish.py deleted file mode 100644 index 8c71223..0000000 --- a/src/cogs/autopublish.py +++ /dev/null @@ -1,15 +0,0 @@ -from discord.ext import commands - -def setup(client): - client.add_cog(Autopublish(client)) - -class Autopublish(commands.Cog): - """Autopublish.""" - - def __init__(self, client): - self.client = client - - @commands.Cog.listener() - async def on_message(self, message): - if message.author.id == 786897204816117771 and message.author.name == "GitHub" and message.author.bot: - await message.publish() diff --git a/src/cogs/confreriedukassoulait.py b/src/cogs/confreriedukassoulait.py index d28e8a2..4fcdf62 100644 --- a/src/cogs/confreriedukassoulait.py +++ b/src/cogs/confreriedukassoulait.py @@ -105,9 +105,12 @@ class ConfrerieDuKassoulait(commands.Cog): # info sur la personne qui a supprimé ne fonctionne pas si il a supprimé un message auparavant (les logs se rajoute a un log deja existant) - # autre serveur @commands.Cog.listener() async def on_message(self, message): + if message.author.id == 786897204816117771 and message.author.name == "GitHub" and message.author.bot: # Autopublish + await message.publish() + + # autre serveur if message.channel.id == 770805818487865404 or message.channel.id == 772239638240165928: # Le groupe de l'amour ❤❤ -- channel chien/chat chiens = ["dog", "chien", "potichien", "doggo"] chats = ["kat", "mace", "kater", "katze", "sinta", "minoos", "cat", "qitt", "besseh", "katu", "caun", "kazh", diff --git a/src/main.py b/src/main.py index 039d094..9a74c3b 100644 --- a/src/main.py +++ b/src/main.py @@ -18,7 +18,6 @@ client.load_extension("cogs.internet") client.load_extension("cogs.music") client.load_extension("cogs.games") client.load_extension("cogs.fun") -client.load_extension("cogs.autopublish") client.load_extension("cogs.school") client.load_extension("cogs.confreriedukassoulait") # you can remove this cogs, only for my private guild print("Terminé !") From a5c4ed0312f7c97890824b54bc5acb3c87a0045c Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 2 Jun 2021 23:10:18 +0200 Subject: [PATCH 099/286] =?UTF-8?q?ajout=20du=20support=20avec=20plusieurs?= =?UTF-8?q?=20unit=C3=A9s=20dans=20le=20remind?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/utils.py | 30 ++++++------------------------ src/utils/core.py | 25 +++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 24 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index d7450bd..7d8e1c0 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -9,7 +9,8 @@ from datetime import datetime from pytz import timezone from discord_slash import cog_ext import shlex -from utils.core import map_list_among_us, get_age, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick, ageLayout +from utils.core import map_list_among_us, get_age, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs +from utils.core import cleanUser, userOrNick, ageLayout, stringTempsVersSecondes def setup(client): client.add_cog(Utils(client)) @@ -484,37 +485,18 @@ class Utils(commands.Cog): reminder = None embed = discord.Embed(color = 0xC41B1B) - seconds = 0 - timestamp = datetime.utcnow() mention = False if reminder: if time.lower().endswith("@"): time = time[:-1] mention = True - try: - if time.lower().endswith("d"): - seconds += int(time[:-1]) * 60 * 60 * 24 - _seconds = seconds // 60 // 60 // 24 - counter = f"{_seconds} jour{'s' if _seconds > 1 else ''}" - if time.lower().endswith("h"): - seconds += int(time[:-1]) * 60 * 60 - _seconds = seconds // 60 // 60 - counter = f"{_seconds} heure{'s' if _seconds > 1 else ''}" - elif time.lower().endswith("m"): - seconds += int(time[:-1]) * 60 - _seconds = seconds // 60 - counter = f"{_seconds} minute{'s' if _seconds > 1 else ''}" - elif time.lower().endswith("s"): - seconds += int(time[:-1]) - counter = f"{seconds} seconde{'s' if seconds > 1 else ''}" - except: - pass + seconds = stringTempsVersSecondes(time) if seconds == 0: embed.add_field(name="Attention", value="Mauvais format pour le temps, `d` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (ne fonctionne qu'avec une seule unité)\nMet un `@` accolée à l'unité pour mentionner les gens mentionner dans ton message.") elif seconds > 7776000: # 90 * 60 * 60 * 24 embed.add_field(name="Attention", value="Tu as spécifié une durée trop longue, la durée maximum étant de 90 jours.") else: - await ctx.send(f"Ok, je t'en parles dans {counter} !") + await ctx.send(f"Ok, je t'en parles dans {time} !") await asyncio.sleep(seconds) message = ctx.author.mention if mention: @@ -526,8 +508,8 @@ class Utils(commands.Cog): await ctx.message.add_reaction(emoji = '✅') except: pass - finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = timestamp, color = discord.Colour.random()) - finalEmbed.set_footer(text=f"Message d'il y a {counter}") + finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = datetime.utcnow(), color = discord.Colour.random()) + finalEmbed.set_footer(text=f"Message d'il y a {time}") links = "" findedURLs = getURLsInString(reminder) diff --git a/src/utils/core.py b/src/utils/core.py index 14945c8..d322bde 100644 --- a/src/utils/core.py +++ b/src/utils/core.py @@ -151,3 +151,28 @@ def ligneFormatage(ligne): for balises in liste_balise: ligne = ligne.replace(balises[0], balises[1]) return ligne + +def stringTempsVersSecondes(time): + conversionTemps = { + "86400": ["j", "d"], + "3600": ["h"], + "60": ["m"], + "1": ["s", ""] + } + + valeursMultiplicateur = "" + for i in conversionTemps.values(): + for j in i: + valeursMultiplicateur += f"{j}|" + match = re.findall(f'([0-9]+)({valeursMultiplicateur[:-1]})?', time) + + if not match: + return "Veuillez entrer un temps valide." + + remindertime = 0 + for i in match: + for tempsEnSeconde, nomCommun in conversionTemps.items(): + if i[1] in nomCommun: + remindertime += int(tempsEnSeconde) * int(i[0]) + + return remindertime From 39988aae7067c0c709799aa3b3a7dfd7afa7b6b3 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 2 Jun 2021 23:12:40 +0200 Subject: [PATCH 100/286] =?UTF-8?q?possibilit=C3=A9=20de=20ne=20pas=20mett?= =?UTF-8?q?re=20de=20message=20dans=20le=20reminder?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/utils.py | 74 ++++++++++++++++++++++++----------------------- 1 file changed, 38 insertions(+), 36 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 7d8e1c0..6d05684 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -486,42 +486,44 @@ class Utils(commands.Cog): embed = discord.Embed(color = 0xC41B1B) mention = False - if reminder: - if time.lower().endswith("@"): - time = time[:-1] - mention = True - seconds = stringTempsVersSecondes(time) - if seconds == 0: - embed.add_field(name="Attention", value="Mauvais format pour le temps, `d` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (ne fonctionne qu'avec une seule unité)\nMet un `@` accolée à l'unité pour mentionner les gens mentionner dans ton message.") - elif seconds > 7776000: # 90 * 60 * 60 * 24 - embed.add_field(name="Attention", value="Tu as spécifié une durée trop longue, la durée maximum étant de 90 jours.") - else: - await ctx.send(f"Ok, je t'en parles dans {time} !") - await asyncio.sleep(seconds) - message = ctx.author.mention - if mention: - mentionList = getMentionInString(reminder) - for i in mentionList: - message += f" {i}" - try: - if fromSlash != True: - await ctx.message.add_reaction(emoji = '✅') - except: - pass - finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = datetime.utcnow(), color = discord.Colour.random()) - finalEmbed.set_footer(text=f"Message d'il y a {time}") - - links = "" - findedURLs = getURLsInString(reminder) - for i in range(0, len(findedURLs)): - links += f"[Lien {i + 1}]({findedURLs[i]}) · " - if len(findedURLs) > 0: - finalEmbed.add_field(name = f"Lien{'s' if len(findedURLs) > 1 else ''}", value = links[:-3]) - - return await ctx.send(message, embed = finalEmbed) + if not reminder: + reminder = "Notification" + if time.lower().endswith("@"): + time = time[:-1] + mention = True + seconds = stringTempsVersSecondes(time) + if seconds == 0: + embed.add_field(name="Attention", value="Mauvais format pour le temps, `d` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde\nMet un `@` accolée à l'unité pour mentionner les gens mentionner dans ton message.") + elif seconds > 7776000: # 90 * 60 * 60 * 24 + embed.add_field(name="Attention", value="Tu as spécifié une durée trop longue, la durée maximum étant de 90 jours.") else: - embed.add_field(name="Attention", value="Mauvaise syntaxe : reminder ") + await ctx.send(f"Ok, je t'en parles dans {time} !") + await asyncio.sleep(seconds) + message = ctx.author.mention + if mention: + mentionList = getMentionInString(reminder) + for i in mentionList: + message += f" {i}" + try: + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + except: + pass + finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = datetime.utcnow(), color = discord.Colour.random()) + finalEmbed.set_footer(text=f"Message d'il y a {time}") + + links = "" + findedURLs = getURLsInString(reminder) + for i in range(0, len(findedURLs)): + links += f"[Lien {i + 1}]({findedURLs[i]}) · " + if len(findedURLs) > 0: + finalEmbed.add_field(name = f"Lien{'s' if len(findedURLs) > 1 else ''}", value = links[:-3]) + + return await ctx.send(message, embed = finalEmbed) await ctx.send(embed = embed) @cog_ext.cog_slash(name="reminder", description = "Met en place un rappel.") - async def __reminder(self, ctx, time, reminder): - return await self._reminder(ctx, time, reminder, True) + async def __reminder(self, ctx, time, reminder = None): + if reminder == None: + return await self._reminder(ctx, time, True) + else: + return await self._reminder(ctx, time, reminder, True) From 1c156e7c774ba449c426d47d60fcfed06e3a21a6 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 2 Jun 2021 23:14:52 +0200 Subject: [PATCH 101/286] update help command for reminder --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 6d05684..6fc1e5c 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -473,7 +473,7 @@ class Utils(commands.Cog): @commands.command(name='reminder', aliases=["remind", "remindme"]) async def _reminder(self, ctx, time, *reminder): - """Met en place un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminder/remind/remindme [@] """ + """Met en place un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminder/remind/remindme [@] [message] """ fromSlash = False if len(reminder) > 0: if reminder[-1] == True: From 891195b1d50b7cd96ca0c41329ca439ed7d9c4a0 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 2 Jun 2021 23:40:22 +0200 Subject: [PATCH 102/286] bump to 1.4 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 253b63d..db4e45a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Bot developed with [discord.py](https://github.com/Rapptz/discord.py) (rewrite) - FRENCH -[![Version](https://img.shields.io/badge/version-1.3-green?style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/releases/latest) +[![Version](https://img.shields.io/badge/version-1.4-green?style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/releases/latest) [![Docker Stars](https://img.shields.io/docker/stars/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/r/mylloon/kassoubot) [![Docker Pulls](https://img.shields.io/docker/pulls/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/r/mylloon/kassoubot) [![Github stars](https://img.shields.io/github/stars/Confrerie-du-Kassoulait/kassoubot?label=Github%20Stars&style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/stargazers) From 6f507b8d29a10fd2378b5eabf18d37ad555e3457 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 08:07:53 +0200 Subject: [PATCH 103/286] adding sqlite3 database --- .gitignore | 1 + README.md | 5 +++-- docker-compose.yml | 2 ++ src/utils/db.py | 3 +++ 4 files changed, 9 insertions(+), 2 deletions(-) create mode 100644 src/utils/db.py diff --git a/.gitignore b/.gitignore index 05faf8d..18e5665 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ update/ __pycache__/ .envrc +src/db/* diff --git a/README.md b/README.md index db4e45a..5677b68 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ [![Github forks](https://img.shields.io/github/forks/Confrerie-du-Kassoulait/KassouBot?label=Github%20Forks&style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/network) ## __Setting up__ -You have to replace `TOKEN_DISCORD`, `PREFIX`, `TOKEN_GENIUS`, `TOKEN_REDDIT_CLIENT_ID`, `TOKEN_REDDIT_CLIENT_SECRET`, `TOKEN_REDDIT_USER_AGENT` and [`TIMEZONE`](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) with your desired values. +You have to replace `TOKEN_DISCORD`, `PREFIX`, `TOKEN_GENIUS`, `TOKEN_REDDIT_CLIENT_ID`, `TOKEN_REDDIT_CLIENT_SECRET`, `TOKEN_REDDIT_USER_AGENT` and [`TIMEZONE`](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) with your desired values. You must also specify a path to the folder where the database will be. With a [docker-compose](https://github.com/Confrerie-du-Kassoulait/KassouBot/blob/master/docker-compose.yml) or in command line: ``` @@ -20,7 +20,8 @@ docker run -d \ --TOKEN_REDDIT_CLIENT_SECRET="yourRedditClientSecret" \ --TOKEN_REDDIT_USER_AGENT="yourRedditUserAgent" \ --TIMEZONE="yourTimezone" \ - --PREFIX="yourPrefix" + --PREFIX="yourPrefix" \ + -v /here/your/path/:/src/db/ ``` To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and here are the instructions: ![instructions](https://i.imgur.com/tEzYKDA.png) diff --git a/docker-compose.yml b/docker-compose.yml index 390527a..5aea38c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -11,4 +11,6 @@ services: - TOKEN_REDDIT_USER_AGENT=yourRedditUserAgent - TIMEZONE=yourTimezone # More info here: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones - PREFIX=yourPrefix + volumes: + - /here/your/path/bot.sqlite3:/src/db/bot.sqlite3 restart: unless-stopped diff --git a/src/utils/db.py b/src/utils/db.py new file mode 100644 index 0000000..a3f49ca --- /dev/null +++ b/src/utils/db.py @@ -0,0 +1,3 @@ +import sqlite3 + +con = sqlite3.connect('../db/bot.sqlite3') From 3bb98edef4c7cb95bbd8a145ae5aedbd1d1c4920 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 08:30:17 +0200 Subject: [PATCH 104/286] creating db if not existing --- src/utils/db.py | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/utils/db.py b/src/utils/db.py index a3f49ca..18eb5b2 100644 --- a/src/utils/db.py +++ b/src/utils/db.py @@ -1,3 +1,26 @@ import sqlite3 +from pathlib import Path -con = sqlite3.connect('../db/bot.sqlite3') +class Database(): + + def __init__(self): + path = Path("src/db/bot.sqlite3").absolute() + if not self.isDatabaseExists(path): + self.createDB(path) + self.con = sqlite3.connect(path) + print("DB Open") + + def isDatabaseExists(self, path): + try: + Path(path).resolve(strict = True) + except FileNotFoundError: + return False + else: + return True + + def createDB(self, path): + print("Creating DB...") + open(path, "x") + + +Database() From 768b1b5cf6c8160680b703f05ab79b1557353bd8 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 08:40:40 +0200 Subject: [PATCH 105/286] removing useless parentheses --- src/utils/db.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/utils/db.py b/src/utils/db.py index 18eb5b2..bc280c8 100644 --- a/src/utils/db.py +++ b/src/utils/db.py @@ -1,7 +1,7 @@ import sqlite3 from pathlib import Path -class Database(): +class Database: def __init__(self): path = Path("src/db/bot.sqlite3").absolute() @@ -21,6 +21,3 @@ class Database(): def createDB(self, path): print("Creating DB...") open(path, "x") - - -Database() From 23f35535a3777cfb7a47d3033498c6d744048aed Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 08:47:47 +0200 Subject: [PATCH 106/286] sync with readme --- docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-compose.yml b/docker-compose.yml index 5aea38c..26d38b1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -12,5 +12,5 @@ services: - TIMEZONE=yourTimezone # More info here: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones - PREFIX=yourPrefix volumes: - - /here/your/path/bot.sqlite3:/src/db/bot.sqlite3 + - /here/your/path/:/src/db/ restart: unless-stopped From 28f2e1da8945ed757b8f1f441cdd0462eb3a021f Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 09:03:01 +0200 Subject: [PATCH 107/286] removing useless package --- src/utils/db.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/utils/db.py b/src/utils/db.py index bc280c8..6a7f21e 100644 --- a/src/utils/db.py +++ b/src/utils/db.py @@ -1,10 +1,9 @@ import sqlite3 -from pathlib import Path class Database: def __init__(self): - path = Path("src/db/bot.sqlite3").absolute() + path = "src/db/bot.sqlite3" if not self.isDatabaseExists(path): self.createDB(path) self.con = sqlite3.connect(path) @@ -12,7 +11,7 @@ class Database: def isDatabaseExists(self, path): try: - Path(path).resolve(strict = True) + open(path, "r") except FileNotFoundError: return False else: From d26e5763a96157245b1becedc067613b36fb153e Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 09:08:50 +0200 Subject: [PATCH 108/286] =?UTF-8?q?pr=C3=A9cision=20lancement=20en=20local?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 5677b68..4822a6c 100644 --- a/README.md +++ b/README.md @@ -32,9 +32,13 @@ To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and - In the [Discord Dev Portal](https://discord.com/developers/applications) create an application, and make sure it's a `Bot` (third tab). - To invite it, go to the `OAuth2` (second tab) tab, select the scopes `bot` (required) and `applications.commands` (for the slashs commands) and in the bot permissions select `Administrator` (You can select manually at your own risk). -- You have the link above between the two blocks scope and permissions. +- You have the link to copy above between the two blocks `scopes` and `permissions`. - If you need help, you can [join my Discord](https://discord.gg/Z5ePxH4). ## __Features__ Everything is explained by doing the `help` command. + +## __Run in local__ +If u want to run it without Docker, I personally use [direnv](https://direnv.net/) to store variables and have them only in the working folder. +Simply run python3 `src/main.py` to launch the bot in the repo folder. From f8a49495f7c4496465d7e47d186a6ea3d9143737 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 09:10:58 +0200 Subject: [PATCH 109/286] better en --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4822a6c..f0a728d 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,6 @@ To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and Everything is explained by doing the `help` command. -## __Run in local__ +## __Launching locally__ If u want to run it without Docker, I personally use [direnv](https://direnv.net/) to store variables and have them only in the working folder. Simply run python3 `src/main.py` to launch the bot in the repo folder. From 0562b5d04f51d90061ddb11f027caac7a9aaf584 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 09:12:31 +0200 Subject: [PATCH 110/286] =?UTF-8?q?better=20en=C2=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f0a728d..64bd553 100644 --- a/README.md +++ b/README.md @@ -40,5 +40,5 @@ To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and Everything is explained by doing the `help` command. ## __Launching locally__ -If u want to run it without Docker, I personally use [direnv](https://direnv.net/) to store variables and have them only in the working folder. +If you want to run it without Docker, I personally use [direnv](https://direnv.net/) to store variables and have them only in the working folder. Simply run python3 `src/main.py` to launch the bot in the repo folder. From 5ca726bf7ca49b3691913bb08f6627413f96c719 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 09:16:38 +0200 Subject: [PATCH 111/286] adding newline --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 64bd553..1632c37 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ [![Github forks](https://img.shields.io/github/forks/Confrerie-du-Kassoulait/KassouBot?label=Github%20Forks&style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/network) ## __Setting up__ -You have to replace `TOKEN_DISCORD`, `PREFIX`, `TOKEN_GENIUS`, `TOKEN_REDDIT_CLIENT_ID`, `TOKEN_REDDIT_CLIENT_SECRET`, `TOKEN_REDDIT_USER_AGENT` and [`TIMEZONE`](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) with your desired values. You must also specify a path to the folder where the database will be. +You have to replace `TOKEN_DISCORD`, `PREFIX`, `TOKEN_GENIUS`, `TOKEN_REDDIT_CLIENT_ID`, `TOKEN_REDDIT_CLIENT_SECRET`, `TOKEN_REDDIT_USER_AGENT` and [`TIMEZONE`](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) with your desired values. You must also specify a path to the folder where the database will be.\ With a [docker-compose](https://github.com/Confrerie-du-Kassoulait/KassouBot/blob/master/docker-compose.yml) or in command line: ``` From fc805d9b8ef2febffe64da79e3e49169fa9c880b Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 10:33:32 +0200 Subject: [PATCH 112/286] =?UTF-8?q?ajout=20m=C3=A9thode=20pour=20faire=20d?= =?UTF-8?q?es=20requetes=20SQL?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/db.py | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/src/utils/db.py b/src/utils/db.py index 6a7f21e..dd45314 100644 --- a/src/utils/db.py +++ b/src/utils/db.py @@ -1,15 +1,23 @@ import sqlite3 class Database: - def __init__(self): - path = "src/db/bot.sqlite3" - if not self.isDatabaseExists(path): - self.createDB(path) - self.con = sqlite3.connect(path) - print("DB Open") + self.curseur = self.createConnection("src/db/bot.sqlite3").cursor() - def isDatabaseExists(self, path): + def createConnection(self, path): + """Connexion à une base de donnée SQLite""" + if not self.isFileExists(path): + open(path, "x") + connnexion = None + try: + connnexion = sqlite3.connect(path) + print(f"Database connected with SQLite v{sqlite3.version}") + except sqlite3.Error as e: + print(e) + return connnexion + + def isFileExists(self, path): + """Vérifie qu'un fichier existe""" try: open(path, "r") except FileNotFoundError: @@ -17,6 +25,9 @@ class Database: else: return True - def createDB(self, path): - print("Creating DB...") - open(path, "x") + def requete(self, requete): + """Reqête vers la base de données""" + try: + self.curseur.execute(requete) + except sqlite3.Error as e: + print(e) From 55774937823bc9b21f727787ef93c088f7f7b1a0 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 10:54:03 +0200 Subject: [PATCH 113/286] adding custom values to request method --- src/utils/db.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/utils/db.py b/src/utils/db.py index dd45314..e878a65 100644 --- a/src/utils/db.py +++ b/src/utils/db.py @@ -2,7 +2,8 @@ import sqlite3 class Database: def __init__(self): - self.curseur = self.createConnection("src/db/bot.sqlite3").cursor() + self.connexion = self.createConnection(r"src/db/bot.sqlite3") + self.curseur = self.connexion.cursor() def createConnection(self, path): """Connexion à une base de donnée SQLite""" @@ -11,7 +12,6 @@ class Database: connnexion = None try: connnexion = sqlite3.connect(path) - print(f"Database connected with SQLite v{sqlite3.version}") except sqlite3.Error as e: print(e) return connnexion @@ -25,9 +25,14 @@ class Database: else: return True - def requete(self, requete): - """Reqête vers la base de données""" + def requete(self, requete, valeurs = None): + """Envois une requête vers la base de données""" try: - self.curseur.execute(requete) + if valeurs: + self.curseur.execute(requete, valeurs) + else: + self.curseur.execute(requete) + self.connexion.commit() + return self.curseur.lastrowid except sqlite3.Error as e: print(e) From 6624e36a85f38c9a2e756db7c3a85686946b7770 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 11:41:30 +0200 Subject: [PATCH 114/286] cursor only inside methods --- src/utils/db.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/utils/db.py b/src/utils/db.py index e878a65..1dd211e 100644 --- a/src/utils/db.py +++ b/src/utils/db.py @@ -3,7 +3,6 @@ import sqlite3 class Database: def __init__(self): self.connexion = self.createConnection(r"src/db/bot.sqlite3") - self.curseur = self.connexion.cursor() def createConnection(self, path): """Connexion à une base de donnée SQLite""" @@ -28,11 +27,12 @@ class Database: def requete(self, requete, valeurs = None): """Envois une requête vers la base de données""" try: + curseur = self.connexion.cursor() if valeurs: - self.curseur.execute(requete, valeurs) + curseur.execute(requete, valeurs) else: - self.curseur.execute(requete) + curseur.execute(requete) self.connexion.commit() - return self.curseur.lastrowid + curseur.close() except sqlite3.Error as e: print(e) From 13a1b23724b4ba7d44ac0d31ad6fc863dd6eeb32 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 11:41:51 +0200 Subject: [PATCH 115/286] adding reminder class --- src/utils/reminder.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/utils/reminder.py diff --git a/src/utils/reminder.py b/src/utils/reminder.py new file mode 100644 index 0000000..5bd0fe7 --- /dev/null +++ b/src/utils/reminder.py @@ -0,0 +1,34 @@ +from db import Database + +class Reminder(Database): + def creationTable(self): + requete = """ + CREATE TABLE IF NOT EXISTS reminder ( + id INTEGER PRIMARY KEY, + guild_id INTEGER, + channel_id INTEGER, + mention_bool INTEGER, + reminder_str TEXT, + creation_str INTEGER, + expiration_int INTEGER, + user_id INTEGER + ); + """ + self.requete(requete) + + def ajoutReminder(self, guildID, channelID, mention, reminder, creation, expiration, userID): + requete = """ + INSERT INTO reminder ( + guild_id, channel_id, mention_bool, reminder_str, creation_str, expiration_int, user_id + ) VALUES ( + ?, ?, ?, ?, ?, ?, ? + ); + """ + self.requete(requete, (guildID, channelID, mention, reminder, creation, expiration, userID)) + + def suppressionReminder(self, id): + requete = """ + DELETE FROM reminder + WHERE id = ? + """ + self.requete(requete, id) From bd730bb0725a26d3b2785455c12997043b1dc03c Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 12:20:29 +0200 Subject: [PATCH 116/286] adding sqlite in features --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1632c37..56b69a1 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,8 @@ To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and ## __Features__ -Everything is explained by doing the `help` command. +- Everything is explained by doing the `help` command. +- Using SQLite for the database ## __Launching locally__ If you want to run it without Docker, I personally use [direnv](https://direnv.net/) to store variables and have them only in the working folder. From cc33f260787b9c8cb944ca2d9323425710423f61 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 12:21:00 +0200 Subject: [PATCH 117/286] creating reminder table at loading --- src/main.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main.py b/src/main.py index 9a74c3b..5db30ed 100644 --- a/src/main.py +++ b/src/main.py @@ -6,6 +6,7 @@ import os from discord_slash import SlashCommand from discord.ext import commands from utils.core import userOrNick, goodTimezone +from utils.reminder import Reminder customPrefix = os.environ['PREFIX'] customTimezone = os.environ['TIMEZONE'] @@ -20,6 +21,7 @@ client.load_extension("cogs.games") client.load_extension("cogs.fun") client.load_extension("cogs.school") client.load_extension("cogs.confreriedukassoulait") # you can remove this cogs, only for my private guild +Reminder().creationTable() print("Terminé !") @client.event From d0feaf53be15ec6b40de3003a2c0ccbde58a6d47 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 12:22:12 +0200 Subject: [PATCH 118/286] adding reminder to the table instead of using asyncio sleep + using a core function to get actual time --- src/cogs/utils.py | 64 +++++++++++++++++++++++++---------------------- 1 file changed, 34 insertions(+), 30 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 6fc1e5c..69b0a17 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -10,7 +10,8 @@ from pytz import timezone from discord_slash import cog_ext import shlex from utils.core import map_list_among_us, get_age, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs -from utils.core import cleanUser, userOrNick, ageLayout, stringTempsVersSecondes +from utils.core import cleanUser, userOrNick, ageLayout, stringTempsVersSecondes, nowTimestamp +from utils.reminder import Reminder def setup(client): client.add_cog(Utils(client)) @@ -38,7 +39,7 @@ class Utils(commands.Cog): if arg == 'help': return await ctx.send(embed = discord.Embed(color = discord.Colour.random(), description = ":hourglass: correspond au temps entre deux battements de cœurs\n\n:stopwatch: correspond au temps que met le client a calculer le ping\n\n:heartbeat: correspond au temps que met le client a réagir au messages")) else: - now = int(round(time.time() * 1000)) + now = int(nowTimestamp()) if fromSlash != True: ping = now - int(round(ctx.message.created_at.timestamp() * 1000)) else: @@ -51,7 +52,7 @@ class Utils(commands.Cog): await ctx.message.add_reaction(emoji = '✅') @cog_ext.cog_slash(name="ping", description = "Affiche mon ping.") async def __ping(self, ctx, arg = None): - ctx.slash_created_at = int(datetime.now(timezone(self.customTimezone)).timestamp()) + ctx.slash_created_at = int(nowTimestamp()) if arg == None: return await self._ping(ctx, True) else: @@ -225,7 +226,7 @@ class Utils(commands.Cog): await ctx.message.delete() embed = discord.Embed(description = text, color = discord.Colour.random()) embed.set_author(name = f"Mémo noté depuis {ctx.guild.name}", icon_url = ctx.author.avatar_url) - embed.set_footer(text = f'📝 le {datetime.now(timezone(self.customTimezone)).strftime("%d/%m/%Y à %H:%M:%S")}') + embed.set_footer(text = f'📝 le {nowTimestamp().strftime("%d/%m/%Y à %H:%M:%S")}') await ctx.author.send(embed = embed) return await ctx.send("Tu viens de recevoir ton mémo !", delete_after = 5) @_memo.error @@ -485,45 +486,48 @@ class Utils(commands.Cog): reminder = None embed = discord.Embed(color = 0xC41B1B) - mention = False + mention = 0 if not reminder: reminder = "Notification" if time.lower().endswith("@"): time = time[:-1] - mention = True + mention = 1 seconds = stringTempsVersSecondes(time) if seconds == 0: embed.add_field(name="Attention", value="Mauvais format pour le temps, `d` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde\nMet un `@` accolée à l'unité pour mentionner les gens mentionner dans ton message.") elif seconds > 7776000: # 90 * 60 * 60 * 24 embed.add_field(name="Attention", value="Tu as spécifié une durée trop longue, la durée maximum étant de 90 jours.") else: - await ctx.send(f"Ok, je t'en parles dans {time} !") - await asyncio.sleep(seconds) - message = ctx.author.mention - if mention: - mentionList = getMentionInString(reminder) - for i in mentionList: - message += f" {i}" - try: - if fromSlash != True: - await ctx.message.add_reaction(emoji = '✅') - except: - pass - finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = datetime.utcnow(), color = discord.Colour.random()) - finalEmbed.set_footer(text=f"Message d'il y a {time}") - - links = "" - findedURLs = getURLsInString(reminder) - for i in range(0, len(findedURLs)): - links += f"[Lien {i + 1}]({findedURLs[i]}) · " - if len(findedURLs) > 0: - finalEmbed.add_field(name = f"Lien{'s' if len(findedURLs) > 1 else ''}", value = links[:-3]) - - return await ctx.send(message, embed = finalEmbed) - await ctx.send(embed = embed) + now = int(nowTimestamp()) + Reminder().ajoutReminder(ctx.guild.id, ctx.channel.id, mention, reminder, now, now + seconds, ctx.author.id) + return await ctx.send(f"Ok, je t'en parles dans {time} !") @cog_ext.cog_slash(name="reminder", description = "Met en place un rappel.") async def __reminder(self, ctx, time, reminder = None): if reminder == None: return await self._reminder(ctx, time, True) else: return await self._reminder(ctx, time, reminder, True) + + + # message = ctx.author.mention + # if mention == 1: + # mentionList = getMentionInString(reminder) + # for i in mentionList: + # message += f" {i}" + # try: + # if fromSlash != True: + # await ctx.message.add_reaction(emoji = '✅') + # except: + # pass + # finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = datetime.utcnow(), color = discord.Colour.random()) + # finalEmbed.set_footer(text=f"Message d'il y a {time}") + + # links = "" + # findedURLs = getURLsInString(reminder) + # for i in range(0, len(findedURLs)): + # links += f"[Lien {i + 1}]({findedURLs[i]}) · " + # if len(findedURLs) > 0: + # finalEmbed.add_field(name = f"Lien{'s' if len(findedURLs) > 1 else ''}", value = links[:-3]) + + # return await ctx.send(message, embed = finalEmbed) + # await ctx.send(embed = embed) From 99765c7b9eb288fdd558c6019a26a127e421b938 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 12:22:41 +0200 Subject: [PATCH 119/286] get actual time --- src/utils/core.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/utils/core.py b/src/utils/core.py index d322bde..4c90217 100644 --- a/src/utils/core.py +++ b/src/utils/core.py @@ -2,9 +2,12 @@ import re import json import requests import time +import os from pytz import timezone from datetime import datetime +myTimezone = os.environ['TIMEZONE'] + def goodTimezone(date, type, tz): """renvoie une date en fonction d'un timezone""" if type == 0: @@ -176,3 +179,6 @@ def stringTempsVersSecondes(time): remindertime += int(tempsEnSeconde) * int(i[0]) return remindertime + +def nowTimestamp(): + return datetime.now(timezone(myTimezone)).timestamp() From c296bb35a94df1672b4e676658d76e56530facd5 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 12:23:32 +0200 Subject: [PATCH 120/286] right import + good name of columns in table + commentary + 2 methods --- src/utils/reminder.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/utils/reminder.py b/src/utils/reminder.py index 5bd0fe7..4e4bfd2 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -1,7 +1,8 @@ -from db import Database +from utils.db import Database class Reminder(Database): def creationTable(self): + """Créer la table qui stocker les reminders""" requete = """ CREATE TABLE IF NOT EXISTS reminder ( id INTEGER PRIMARY KEY, @@ -9,7 +10,7 @@ class Reminder(Database): channel_id INTEGER, mention_bool INTEGER, reminder_str TEXT, - creation_str INTEGER, + creation_int INTEGER, expiration_int INTEGER, user_id INTEGER ); @@ -17,9 +18,10 @@ class Reminder(Database): self.requete(requete) def ajoutReminder(self, guildID, channelID, mention, reminder, creation, expiration, userID): + """Ajoute un reminder""" requete = """ INSERT INTO reminder ( - guild_id, channel_id, mention_bool, reminder_str, creation_str, expiration_int, user_id + guild_id, channel_id, mention_bool, reminder_str, creation_int, expiration_int, user_id ) VALUES ( ?, ?, ?, ?, ?, ?, ? ); @@ -27,8 +29,17 @@ class Reminder(Database): self.requete(requete, (guildID, channelID, mention, reminder, creation, expiration, userID)) def suppressionReminder(self, id): + """Supprime un reminder""" requete = """ DELETE FROM reminder WHERE id = ? """ self.requete(requete, id) + + def listeReminder(self, userID = None): + """Retourne la liste des reminders, si un userID est mentionné, retourne la liste de cet utilisateur""" + return + + def recuperationReminder(self, id): + """Récupère les informations d'un reminder""" + return From 81f865b10238d81af499210a8d7ffea533911fbc Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 12:33:43 +0200 Subject: [PATCH 121/286] backtracking nowtimestamp method --- src/cogs/utils.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 69b0a17..06bb025 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -39,7 +39,7 @@ class Utils(commands.Cog): if arg == 'help': return await ctx.send(embed = discord.Embed(color = discord.Colour.random(), description = ":hourglass: correspond au temps entre deux battements de cœurs\n\n:stopwatch: correspond au temps que met le client a calculer le ping\n\n:heartbeat: correspond au temps que met le client a réagir au messages")) else: - now = int(nowTimestamp()) + now = int(round(time.time() * 1000)) if fromSlash != True: ping = now - int(round(ctx.message.created_at.timestamp() * 1000)) else: @@ -52,7 +52,7 @@ class Utils(commands.Cog): await ctx.message.add_reaction(emoji = '✅') @cog_ext.cog_slash(name="ping", description = "Affiche mon ping.") async def __ping(self, ctx, arg = None): - ctx.slash_created_at = int(nowTimestamp()) + ctx.slash_created_at = int(datetime.now(timezone(self.customTimezone)).timestamp()) if arg == None: return await self._ping(ctx, True) else: @@ -226,7 +226,7 @@ class Utils(commands.Cog): await ctx.message.delete() embed = discord.Embed(description = text, color = discord.Colour.random()) embed.set_author(name = f"Mémo noté depuis {ctx.guild.name}", icon_url = ctx.author.avatar_url) - embed.set_footer(text = f'📝 le {nowTimestamp().strftime("%d/%m/%Y à %H:%M:%S")}') + embed.set_footer(text = f'📝 le {datetime.now(timezone(self.customTimezone)).strftime("%d/%m/%Y à %H:%M:%S")}') await ctx.author.send(embed = embed) return await ctx.send("Tu viens de recevoir ton mémo !", delete_after = 5) @_memo.error From e6c6456803ffbedf8173ed37748f2e51b532ac86 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 14:24:36 +0200 Subject: [PATCH 122/286] =?UTF-8?q?ajout=20des=20r=C3=A9cup=C3=A9rations?= =?UTF-8?q?=20des=20informations=20de=20la=20db?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/reminder.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/utils/reminder.py b/src/utils/reminder.py index 4e4bfd2..8cdc18d 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -6,7 +6,7 @@ class Reminder(Database): requete = """ CREATE TABLE IF NOT EXISTS reminder ( id INTEGER PRIMARY KEY, - guild_id INTEGER, + message_id INTEGER, channel_id INTEGER, mention_bool INTEGER, reminder_str TEXT, @@ -17,16 +17,16 @@ class Reminder(Database): """ self.requete(requete) - def ajoutReminder(self, guildID, channelID, mention, reminder, creation, expiration, userID): + def ajoutReminder(self, messageID, channelID, mention, reminder, creation, expiration, userID): """Ajoute un reminder""" requete = """ INSERT INTO reminder ( - guild_id, channel_id, mention_bool, reminder_str, creation_int, expiration_int, user_id + message_id, channel_id, mention_bool, reminder_str, creation_int, expiration_int, user_id ) VALUES ( ?, ?, ?, ?, ?, ?, ? ); """ - self.requete(requete, (guildID, channelID, mention, reminder, creation, expiration, userID)) + self.requete(requete, (messageID, channelID, mention, reminder, creation, expiration, userID)) def suppressionReminder(self, id): """Supprime un reminder""" @@ -34,12 +34,16 @@ class Reminder(Database): DELETE FROM reminder WHERE id = ? """ - self.requete(requete, id) + self.requete(requete, [id]) def listeReminder(self, userID = None): """Retourne la liste des reminders, si un userID est mentionné, retourne la liste de cet utilisateur""" return - def recuperationReminder(self, id): - """Récupère les informations d'un reminder""" - return + def recuperationExpiration(self, time): + """Récupère les reminders qui sont arrivés à expiration et ses infos""" + requete = """ + SELECT channel_id, mention_bool, reminder_str, creation_int, user_id, id, message_id FROM reminder + WHERE expiration_int < ? + """ + return self.affichageResultat(self.requete(requete, [time])) From 05bb9101b833d4a47f039b13b3e306eef15482f0 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 14:25:24 +0200 Subject: [PATCH 123/286] =?UTF-8?q?sortie=20des=20r=C3=A9sultats=20de=20la?= =?UTF-8?q?=20db?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/db.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/utils/db.py b/src/utils/db.py index 1dd211e..94940af 100644 --- a/src/utils/db.py +++ b/src/utils/db.py @@ -33,6 +33,16 @@ class Database: else: curseur.execute(requete) self.connexion.commit() - curseur.close() + return (curseur, curseur.lastrowid) except sqlite3.Error as e: print(e) + + def affichageResultat(self, curseur): + """Affiche le résultat d'une requête""" + tableau = [] + if curseur == None: + return tableau + lignes = curseur[0].fetchall() + for ligne in lignes: + tableau.append(ligne) + return tableau From 102fb48d91b5584119774bac81e0d8e65e05f048 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 14:26:14 +0200 Subject: [PATCH 124/286] adding methods for timestamp --- src/utils/core.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/utils/core.py b/src/utils/core.py index 4c90217..f008b79 100644 --- a/src/utils/core.py +++ b/src/utils/core.py @@ -180,5 +180,11 @@ def stringTempsVersSecondes(time): return remindertime -def nowTimestamp(): +def nowTimestampCustom(): return datetime.now(timezone(myTimezone)).timestamp() + +def nowTimestampUTC(): + return datetime.utcnow().timestamp() + +def intToTimestamp(int): + return datetime.fromtimestamp(int) From 2cd81f944479b78c28100e2a9e01cfde3483906e Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 14:26:51 +0200 Subject: [PATCH 125/286] =?UTF-8?q?impl=C3=A9mentation=20de=20la=20db=20da?= =?UTF-8?q?ns=20le=20reminder?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/utils.py | 64 ++++++++++++++++++++++++++++------------------- 1 file changed, 38 insertions(+), 26 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 06bb025..2d28577 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -2,15 +2,14 @@ import discord import time import os import re -import asyncio -from discord.ext import commands +from discord.ext import commands, tasks from random import randint, shuffle from datetime import datetime from pytz import timezone from discord_slash import cog_ext import shlex from utils.core import map_list_among_us, get_age, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs -from utils.core import cleanUser, userOrNick, ageLayout, stringTempsVersSecondes, nowTimestamp +from utils.core import cleanUser, userOrNick, ageLayout, stringTempsVersSecondes, nowTimestampCustom, intToTimestamp, nowTimestampUTC from utils.reminder import Reminder def setup(client): @@ -22,6 +21,7 @@ class Utils(commands.Cog): def __init__(self, client): self.client = client self.customTimezone = os.environ['TIMEZONE'] + self._reminderLoop.start() @commands.command(name='ping') async def _ping(self, ctx, *arg): @@ -498,9 +498,13 @@ class Utils(commands.Cog): elif seconds > 7776000: # 90 * 60 * 60 * 24 embed.add_field(name="Attention", value="Tu as spécifié une durée trop longue, la durée maximum étant de 90 jours.") else: - now = int(nowTimestamp()) - Reminder().ajoutReminder(ctx.guild.id, ctx.channel.id, mention, reminder, now, now + seconds, ctx.author.id) + now = int(nowTimestampUTC()) + messageID = None + if fromSlash != True: + messageID = ctx.message.id + Reminder().ajoutReminder(messageID, ctx.channel.id, mention, reminder, now, now + seconds, ctx.author.id) return await ctx.send(f"Ok, je t'en parles dans {time} !") + await ctx.send(embed = embed) @cog_ext.cog_slash(name="reminder", description = "Met en place un rappel.") async def __reminder(self, ctx, time, reminder = None): if reminder == None: @@ -508,26 +512,34 @@ class Utils(commands.Cog): else: return await self._reminder(ctx, time, reminder, True) - - # message = ctx.author.mention - # if mention == 1: - # mentionList = getMentionInString(reminder) - # for i in mentionList: - # message += f" {i}" - # try: - # if fromSlash != True: - # await ctx.message.add_reaction(emoji = '✅') - # except: - # pass - # finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = datetime.utcnow(), color = discord.Colour.random()) - # finalEmbed.set_footer(text=f"Message d'il y a {time}") + @tasks.loop(minutes = 1) + async def _reminderLoop(self): + expiration = Reminder().recuperationExpiration(int(nowTimestampUTC())) + for expired in expiration: + message = f"<@{expired[4]}>" + reminder = expired[2] + if expired[1] == 1: + mentionList = getMentionInString(reminder) + for i in mentionList: + message += f" {i}" + channel = self.client.get_channel(expired[0]) + try: + sourceMessage = await channel.fetch_message(expired[6]) + await sourceMessage.add_reaction(emoji = '✅') + except: + pass + finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = intToTimestamp(expired[3]), color = discord.Colour.random()) + finalEmbed.set_footer(text=f"Message d'il y a {int(nowTimestampUTC()) - expired[3]} secondes") - # links = "" - # findedURLs = getURLsInString(reminder) - # for i in range(0, len(findedURLs)): - # links += f"[Lien {i + 1}]({findedURLs[i]}) · " - # if len(findedURLs) > 0: - # finalEmbed.add_field(name = f"Lien{'s' if len(findedURLs) > 1 else ''}", value = links[:-3]) + links = "" + findedURLs = getURLsInString(reminder) + for i in range(0, len(findedURLs)): + links += f"[Lien {i + 1}]({findedURLs[i]}) · " + if len(findedURLs) > 0: + finalEmbed.add_field(name = f"Lien{'s' if len(findedURLs) > 1 else ''}", value = links[:-3]) + await channel.send(message, embed = finalEmbed) + Reminder().suppressionReminder(expired[5]) - # return await ctx.send(message, embed = finalEmbed) - # await ctx.send(embed = embed) + @_reminderLoop.before_loop + async def __avant_reminderLoop(self): + await self.client.wait_until_ready() From 08bedb2c5d4d3477813fdf20ed8567862c62a75f Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 16:34:28 +0200 Subject: [PATCH 126/286] ajout des jours heures et minutes dans la notification du reminder --- src/cogs/utils.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 2d28577..1f90ed6 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -4,7 +4,7 @@ import os import re from discord.ext import commands, tasks from random import randint, shuffle -from datetime import datetime +from datetime import datetime, timedelta from pytz import timezone from discord_slash import cog_ext import shlex @@ -529,7 +529,7 @@ class Utils(commands.Cog): except: pass finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = intToTimestamp(expired[3]), color = discord.Colour.random()) - finalEmbed.set_footer(text=f"Message d'il y a {int(nowTimestampUTC()) - expired[3]} secondes") + finalEmbed.set_footer(text=f"Message d'il y a {str(timedelta(seconds = int(nowTimestampUTC()) - expired[3])).replace('days', 'jours')} secondes") links = "" findedURLs = getURLsInString(reminder) From 38057e610a011773700f4af44c04e9372c694c7b Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 20:14:45 +0200 Subject: [PATCH 127/286] meilleur affichage du temps --- src/cogs/utils.py | 6 +++--- src/utils/core.py | 18 +++++++++++++++++- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 1f90ed6..55b87ba 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -9,7 +9,7 @@ from pytz import timezone from discord_slash import cog_ext import shlex from utils.core import map_list_among_us, get_age, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs -from utils.core import cleanUser, userOrNick, ageLayout, stringTempsVersSecondes, nowTimestampCustom, intToTimestamp, nowTimestampUTC +from utils.core import cleanUser, userOrNick, ageLayout, stringTempsVersSecondes, timedeltaToString, intToTimestamp, nowTimestampUTC from utils.reminder import Reminder def setup(client): @@ -503,7 +503,7 @@ class Utils(commands.Cog): if fromSlash != True: messageID = ctx.message.id Reminder().ajoutReminder(messageID, ctx.channel.id, mention, reminder, now, now + seconds, ctx.author.id) - return await ctx.send(f"Ok, je t'en parles dans {time} !") + return await ctx.send(f"Ok, je t'en parles dans {timedeltaToString(seconds)} !") await ctx.send(embed = embed) @cog_ext.cog_slash(name="reminder", description = "Met en place un rappel.") async def __reminder(self, ctx, time, reminder = None): @@ -529,7 +529,7 @@ class Utils(commands.Cog): except: pass finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = intToTimestamp(expired[3]), color = discord.Colour.random()) - finalEmbed.set_footer(text=f"Message d'il y a {str(timedelta(seconds = int(nowTimestampUTC()) - expired[3])).replace('days', 'jours')} secondes") + finalEmbed.set_footer(text=f"Message d'il y a {timedeltaToString(int(nowTimestampUTC()) - expired[3])}") links = "" findedURLs = getURLsInString(reminder) diff --git a/src/utils/core.py b/src/utils/core.py index f008b79..809804a 100644 --- a/src/utils/core.py +++ b/src/utils/core.py @@ -4,7 +4,7 @@ import requests import time import os from pytz import timezone -from datetime import datetime +from datetime import datetime, timedelta myTimezone = os.environ['TIMEZONE'] @@ -188,3 +188,19 @@ def nowTimestampUTC(): def intToTimestamp(int): return datetime.fromtimestamp(int) + +def timedeltaToString(time): + age = str(timedelta(seconds = time)).replace('days, ', 'jours, :').split(':') + if len(age) == 4: + a = [1, 1, 1, 1] # a pour affichage + if len(age) == 3: + a = [0, 1, 1, 1] + age.insert(0, None) + for i in range(1, 4): + if int(age[i]) == 0: + a[i] = 0 + age[0] = age[0] if a[0] == 1 else '' + age[1] = f"{age[1]}h " if a[1] == 1 else '' + age[2] = f"{age[2]}m " if a[2] == 1 else '' + age[3] = f"{age[3]}s" if a[3] == 1 else '' + return ''.join(age) From c11af6ebee436e7915133b8c4ad03bb4ca0dea1a Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 3 Jun 2021 20:34:07 +0200 Subject: [PATCH 128/286] ajout marge d'erreur --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 55b87ba..b5ed657 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -503,7 +503,7 @@ class Utils(commands.Cog): if fromSlash != True: messageID = ctx.message.id Reminder().ajoutReminder(messageID, ctx.channel.id, mention, reminder, now, now + seconds, ctx.author.id) - return await ctx.send(f"Ok, je t'en parles dans {timedeltaToString(seconds)} !") + return await ctx.send(f"Ok, je t'en parles dans {timedeltaToString(seconds)} ± 1min !") await ctx.send(embed = embed) @cog_ext.cog_slash(name="reminder", description = "Met en place un rappel.") async def __reminder(self, ctx, time, reminder = None): From 5cd3ef088dc62f01e734e45d91d3a8f5b9cd006e Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 4 Jun 2021 14:09:02 +0200 Subject: [PATCH 129/286] ajout aliase "rappel" a la commande "reminder" --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index b5ed657..2ce0e81 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -472,7 +472,7 @@ class Utils(commands.Cog): args = shlex.split(args) return await self._avis(ctx, *args, True) - @commands.command(name='reminder', aliases=["remind", "remindme"]) + @commands.command(name='reminder', aliases=["remind", "remindme", "rappel"]) async def _reminder(self, ctx, time, *reminder): """Met en place un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminder/remind/remindme [@] [message] """ fromSlash = False From c249ece3a51517f78f9c604280a0ddf31e1a454a Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 6 Jun 2021 23:46:41 +0200 Subject: [PATCH 130/286] goodtimezone better args --- src/cogs/confreriedukassoulait.py | 4 ++-- src/main.py | 6 +++--- src/utils/core.py | 6 +++++- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/cogs/confreriedukassoulait.py b/src/cogs/confreriedukassoulait.py index 4fcdf62..2e0bf86 100644 --- a/src/cogs/confreriedukassoulait.py +++ b/src/cogs/confreriedukassoulait.py @@ -96,9 +96,9 @@ class ConfrerieDuKassoulait(commands.Cog): embed.set_author(name = userOrNick(message.author), icon_url = message.author.avatar_url) if not user_suppressed: - embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1, customTimezone)}\nSupprimé le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") + embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, customTimezone, 1)}\nSupprimé le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") else: - embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, 1, customTimezone)}\nSupprimé par {userOrNick(user_suppressed)} le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") + embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, customTimezone, 1)}\nSupprimé par {userOrNick(user_suppressed)} le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") await channel.send(embed = embed) # ne fonctionne pas quand un message a été supprimé avant que le bot ai démarré diff --git a/src/main.py b/src/main.py index 5db30ed..3adaaf1 100644 --- a/src/main.py +++ b/src/main.py @@ -110,14 +110,14 @@ async def on_message(message): embed.set_author(name = "Citation", icon_url = msgID.author.avatar_url) icon_url = message.author.avatar_url - date_1 = goodTimezone(msgID.created_at, 0, customTimezone) + date_1 = goodTimezone(msgID.created_at, customTimezone) edit = "" if msgID.edited_at: - date_edit = goodTimezone(msgID.edited_at, 0, customTimezone) + date_edit = goodTimezone(msgID.edited_at, customTimezone) edit = f" et modifié le {date_edit[0][8:]}/{date_edit[0][5:-3]}/{date_edit[0][:4]} à {date_edit[1]}" messageDuBas = f"Posté le {date_1[0][8:]}/{date_1[0][5:-3]}/{date_1[0][:4]} à {date_1[1]}{edit}" - date_2 = goodTimezone(message.created_at, 0, customTimezone) + date_2 = goodTimezone(message.created_at, customTimezone) date_2 = f"{date_2[0][8:]}/{date_2[0][5:-3]}/{date_2[0][:4]} à {date_2[1]}" if auteur == "Auteur": diff --git a/src/utils/core.py b/src/utils/core.py index 809804a..0dde06e 100644 --- a/src/utils/core.py +++ b/src/utils/core.py @@ -8,7 +8,7 @@ from datetime import datetime, timedelta myTimezone = os.environ['TIMEZONE'] -def goodTimezone(date, type, tz): +def goodTimezone(date, tz, type = 0): """renvoie une date en fonction d'un timezone""" if type == 0: return str(timezone(tz).fromutc(date))[:-13].replace('-', '/').split() @@ -204,3 +204,7 @@ def timedeltaToString(time): age[2] = f"{age[2]}m " if a[2] == 1 else '' age[3] = f"{age[3]}s" if a[3] == 1 else '' return ''.join(age) + +def timestampFR(timestamp): + date_edit = str(timestamp).replace('-', '/').split(' ') + return f"{date_edit[0][8:]}/{date_edit[0][5:-3]}/{date_edit[0][:4]} à {date_edit[1]}" From ca845fe704eae39348b44efa554f22777d596c6f Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 6 Jun 2021 23:47:10 +0200 Subject: [PATCH 131/286] ajout du reminderlist --- src/cogs/utils.py | 79 ++++++++++++++++++++++++++++++++----------- src/utils/reminder.py | 16 +++++---- 2 files changed, 70 insertions(+), 25 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 2ce0e81..80f7ecc 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -2,22 +2,22 @@ import discord import time import os import re +import shlex from discord.ext import commands, tasks from random import randint, shuffle -from datetime import datetime, timedelta +from datetime import datetime from pytz import timezone from discord_slash import cog_ext -import shlex +from utils.reminder import Reminder from utils.core import map_list_among_us, get_age, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs from utils.core import cleanUser, userOrNick, ageLayout, stringTempsVersSecondes, timedeltaToString, intToTimestamp, nowTimestampUTC -from utils.reminder import Reminder +from utils.core import timestampFR def setup(client): client.add_cog(Utils(client)) class Utils(commands.Cog): """Commandes essentielles.""" - def __init__(self, client): self.client = client self.customTimezone = os.environ['TIMEZONE'] @@ -140,6 +140,7 @@ class Utils(commands.Cog): await ctx.send(embed = embed) @_calc.error async def _calc_error(self, ctx, error): + print(error) await ctx.send("Tu n'as pas spécifié de calcul.") @cog_ext.cog_slash(name="calc", description = "Calculatrice.") async def __calc(self, ctx, calcul): @@ -150,44 +151,45 @@ class Utils(commands.Cog): """Informations pour bien éditer son texte.⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" if fromSlash == None: fromSlash = False - syntaxe = "-----------------------------------------------------\n" - syntaxe += discord.utils.escape_markdown("```Js\n") + separateur = "-----------------------------------------------------\n" + syntaxe = separateur + syntaxe += discord.utils.escape_markdown("```js\n") syntaxe += discord.utils.escape_markdown("//code en js (possible de remplacer 'js' par d'autres languages . adaptez le !)\n") syntaxe += discord.utils.escape_markdown('console.log("hi");\n') syntaxe += discord.utils.escape_markdown("```\n") - syntaxe += "```Js\n" + syntaxe += "```js\n" syntaxe += "//code en js (possible de remplacer 'js' par d'autres languages . adaptez le !)\n" syntaxe += 'console.log("hi");\n' syntaxe += "```\n" syntaxe += "Si ton code est trop long, mets le sur \n" - syntaxe += "-----------------------------------------------------\n" + syntaxe += separateur syntaxe += discord.utils.escape_markdown("`code sur une seule ligne`\n") syntaxe += "`code sur une seule ligne`\n" - syntaxe += "-----------------------------------------------------\n" + syntaxe += separateur syntaxe += discord.utils.escape_markdown("*texte en italique*\n") syntaxe += "*texte en italique*\n" - syntaxe += "-----------------------------------------------------\n" + syntaxe += separateur syntaxe += discord.utils.escape_markdown("**text en gras**\n") syntaxe += "**text en gras**\n" - syntaxe += "-----------------------------------------------------\n" + syntaxe += separateur syntaxe += discord.utils.escape_markdown("<>\n") syntaxe += "Un lien entre crochet, ça empêche Discord de rajouté son intégration automatique (mais le lien fonctionnera toujours).\n" - syntaxe += "-----------------------------------------------------\n" + syntaxe += separateur syntaxe += discord.utils.escape_markdown("__texte souligné__\n") syntaxe += "__texte souligné__\n" - syntaxe += "-----------------------------------------------------\n" + syntaxe += separateur syntaxe += discord.utils.escape_markdown("~~texte barré~~\n") syntaxe += "~~texte barré~~\n" - syntaxe += "-----------------------------------------------------\n" + syntaxe += separateur syntaxe += discord.utils.escape_markdown("~~__***text en italique-gras-souligné-barré***__~~\n") syntaxe += "~~__***text en italique-gras-souligné-barré***__~~\n" - syntaxe += "-----------------------------------------------------\n" + syntaxe += separateur syntaxe += discord.utils.escape_markdown("\:joy: <- l'emoji ne va pas fonctionné grâce au \ \n") syntaxe += "\:joy: <- l'emoji ne va pas fonctionné grâce au \ \n" - syntaxe += "-----------------------------------------------------\n" + syntaxe += separateur syntaxe += discord.utils.escape_markdown("> cette ligne est cité\npas celle là\n") syntaxe += "> cette ligne est cité\npas celle là\n" - syntaxe += "-----------------------------------------------------\n" + syntaxe += separateur syntaxe += discord.utils.escape_markdown(">>> cette ligne est cité\ncelle là aussi (et elles le seront toutes!)\n") syntaxe += ">>> cette ligne est cité\ncelle là aussi (et elles le seront toutes!)\n" try: @@ -503,7 +505,7 @@ class Utils(commands.Cog): if fromSlash != True: messageID = ctx.message.id Reminder().ajoutReminder(messageID, ctx.channel.id, mention, reminder, now, now + seconds, ctx.author.id) - return await ctx.send(f"Ok, je t'en parles dans {timedeltaToString(seconds)} ± 1min !") + return await ctx.send(f"Ok, je t'en parles dans {timedeltaToString(seconds)} avec 1min de retard maximum.") await ctx.send(embed = embed) @cog_ext.cog_slash(name="reminder", description = "Met en place un rappel.") async def __reminder(self, ctx, time, reminder = None): @@ -539,7 +541,46 @@ class Utils(commands.Cog): finalEmbed.add_field(name = f"Lien{'s' if len(findedURLs) > 1 else ''}", value = links[:-3]) await channel.send(message, embed = finalEmbed) Reminder().suppressionReminder(expired[5]) - @_reminderLoop.before_loop async def __avant_reminderLoop(self): await self.client.wait_until_ready() + + @commands.command(name='reminderlist', aliases=["remindlist", "rl", "rappeliste"]) + async def _reminderlist(self, ctx, *utilisateur): + """Affiche la liste des rappels d'un utilisateur.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminderlist/rl/remindlist/rappeliste [utilisateur] """ + fromSlash = False + if len(utilisateur) > 0: + if utilisateur[-1] == True: + fromSlash = utilisateur[-1] + utilisateur = utilisateur[:-1] + if len(utilisateur) > 0: + utilisateur = int(getMentionInString(utilisateur[0])[0][3:][:-1]) + else: + utilisateur = ctx.author.id + + reminders = Reminder().listeReminder(utilisateur) + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + embed = discord.Embed(description = f"**Rappel{'s' if len(reminders) > 1 else ''} de <@{utilisateur}>**", color = discord.Colour.random()) + embed.set_thumbnail(url = self.client.get_user(utilisateur).avatar_url_as(size = 32)) + if len(reminders) > 0: + for reminder in reminders: + texte = reminder[0] + if len(texte) > 1024: + texte = f"{texte[:1021]}..." + expiration = reminder[2] - int(nowTimestampUTC()) + if expiration > 0: + expiration = f"Expire dans {timedeltaToString(expiration)} +1min de retard max." + else: + expiration = f"A déjà expiré." + embed.add_field(value = texte, name = f"Fais le {timestampFR(intToTimestamp(reminder[1]))}\n{expiration}", inline = False) + else: + embed.add_field(name = "\u200b", value = "Vous n'avez aucun rappels en attente !") + await ctx.send(embed = embed) + + @cog_ext.cog_slash(name="reminderlist", description = "Affiche la liste des rappels d'un utilisateur.") + async def __reminderlist(self, ctx, utilisateur = None): + if utilisateur == None: + return await self._reminderlist(ctx, True) + else: + return await self._reminderlist(ctx, utilisateur, True) diff --git a/src/utils/reminder.py b/src/utils/reminder.py index 8cdc18d..e7c7a6c 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -17,7 +17,7 @@ class Reminder(Database): """ self.requete(requete) - def ajoutReminder(self, messageID, channelID, mention, reminder, creation, expiration, userID): + def ajoutReminder(self, messageID = int, channelID = int, mention = int, reminder = str, creation = int, expiration = int, userID = int): """Ajoute un reminder""" requete = """ INSERT INTO reminder ( @@ -28,7 +28,7 @@ class Reminder(Database): """ self.requete(requete, (messageID, channelID, mention, reminder, creation, expiration, userID)) - def suppressionReminder(self, id): + def suppressionReminder(self, id = int): """Supprime un reminder""" requete = """ DELETE FROM reminder @@ -36,11 +36,15 @@ class Reminder(Database): """ self.requete(requete, [id]) - def listeReminder(self, userID = None): - """Retourne la liste des reminders, si un userID est mentionné, retourne la liste de cet utilisateur""" - return + def listeReminder(self, userID = int): + """Retourne la liste des reminders d'un utilisateur""" + requete = """ + SELECT reminder_str, creation_int, expiration_int FROM reminder + WHERE user_id = ? + """ + return self.affichageResultat(self.requete(requete, [userID])) - def recuperationExpiration(self, time): + def recuperationExpiration(self, time = int): """Récupère les reminders qui sont arrivés à expiration et ses infos""" requete = """ SELECT channel_id, mention_bool, reminder_str, creation_int, user_id, id, message_id FROM reminder From 664fdfcdb69636f046a13dde96e2a8fdfd117729 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 00:02:34 +0200 Subject: [PATCH 132/286] =?UTF-8?q?d=C3=A9placement=20de=20citation=20vers?= =?UTF-8?q?=20son=20cogs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/citation.py | 96 ++++++++++++++++++++++++++++++++++++++++++++ src/main.py | 82 +------------------------------------ 2 files changed, 97 insertions(+), 81 deletions(-) create mode 100644 src/cogs/citation.py diff --git a/src/cogs/citation.py b/src/cogs/citation.py new file mode 100644 index 0000000..34757e2 --- /dev/null +++ b/src/cogs/citation.py @@ -0,0 +1,96 @@ +import discord +import re +import os +from discord.ext import commands +customTimezone = os.environ['TIMEZONE'] +from utils.core import goodTimezone, userOrNick + +def setup(client): + client.add_cog(Citation(client)) + +class Citation(commands.Cog): + """Gère le système de citation.""" + def __init__(self, client): + self.client = client + + @commands.Cog.listener() + async def on_message(self, message): + urls = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', message.content) + httpsString = "https://" + channelsString = "discord.com/channels/" + for i in range(len(urls)): + if urls[i].startswith(f"{httpsString}{channelsString}") or urls[i].startswith(f"{httpsString}ptb.{channelsString}") or urls[i].startswith(f"{httpsString}canary.{channelsString}"): + link = urls[i] + linkURL = link + if link.startswith(f"{httpsString}{channelsString}"): + link = f'000{link}' + if link.startswith(f"{httpsString}ptb.{channelsString}"): + link = link[1:] + if link.startswith(f"{httpsString}canary.{channelsString}"): + link = link[4:] + if "@me" in urls[i]: + return await message.channel.send("Je ne cite pas les messages privés.", delete_after = 5) + try: + if int(link[32:-38]) == message.guild.id: + msgID = await self.client.get_channel(int(link[51:-19])).fetch_message(int(link[70:])) + couleur = 0x2f3136 + msgFiles = msgID.attachments + imageExtensions = ["jpg", "jpeg", "png", "webp", "gif"] + desc = msgID.content + if len(msgFiles) > 1: + listOfFiles = "" + for i in range(0, len(msgFiles)): + listOfFiles = f"{listOfFiles}, {msgFiles[i].filename}" + listOfFiles = listOfFiles[2:] + if len(msgID.content) > 0: + desc = f"{msgID.content}\n\nIl y a plusieurs fichiers dans ce message : {listOfFiles}" + else: + desc = f"Il y a plusieurs fichiers dans ce message : {listOfFiles}" + else: + if len(msgFiles) == 1: + if msgFiles[0].filename[-4:].split('.')[1] in imageExtensions: + if not len(msgID.content) > 0: + desc = f"Une image jointe : {msgFiles[0].filename}" + else: + linkFile = msgFiles[0].url + if not len(msgID.content) > 0: + desc = f"Un fichier joint : {msgFiles[0].filename}" + embed = discord.Embed(description = desc, colour = couleur) + auteur = "Auteur" + if message.author == msgID.author: + auteur = "Auteur & Citateur" + embed.add_field(name = auteur, value = msgID.author.mention, inline=True) + try: + if len(msgFiles) == 1: + if msgFiles[0].filename[-4:].split('.')[1] in imageExtensions: + embed.set_image(url=msgFiles[0].url) + else: + embed.add_field(name = "Fichier", value = f"[Lien]({linkFile})", inline=True) + except: + pass + embed.add_field(name = "Message", value = f"{msgID.channel.mention} - [Lien Message]({linkURL})", inline=True) + embed.set_author(name = "Citation", icon_url = msgID.author.avatar_url) + icon_url = message.author.avatar_url + + date_1 = goodTimezone(msgID.created_at, customTimezone) + edit = "" + if msgID.edited_at: + date_edit = goodTimezone(msgID.edited_at, customTimezone) + edit = f" et modifié le {date_edit[0][8:]}/{date_edit[0][5:-3]}/{date_edit[0][:4]} à {date_edit[1]}" + messageDuBas = f"Posté le {date_1[0][8:]}/{date_1[0][5:-3]}/{date_1[0][:4]} à {date_1[1]}{edit}" + + date_2 = goodTimezone(message.created_at, customTimezone) + date_2 = f"{date_2[0][8:]}/{date_2[0][5:-3]}/{date_2[0][:4]} à {date_2[1]}" + + if auteur == "Auteur": + messageDuBas = messageDuBas + f"\nCité par {userOrNick(message.author)} le {date_2}" + embed.set_footer(icon_url = icon_url, text = messageDuBas) + if message.content == linkURL.replace(' ',''): + await message.channel.send(embed = embed) + await message.delete() + else: + await message.reply(embed = embed, mention_author = False) + except Exception as e: + e = str(e) + if not "invalid literal for int() with base 10:" in e or not "404 Not Found (error code: 10008)" in e: # faute de frappe / message supprimé + print(e) diff --git a/src/main.py b/src/main.py index 3adaaf1..bc5d479 100644 --- a/src/main.py +++ b/src/main.py @@ -20,6 +20,7 @@ client.load_extension("cogs.music") client.load_extension("cogs.games") client.load_extension("cogs.fun") client.load_extension("cogs.school") +client.load_extension("cogs.citation") client.load_extension("cogs.confreriedukassoulait") # you can remove this cogs, only for my private guild Reminder().creationTable() print("Terminé !") @@ -51,87 +52,6 @@ async def on_message(message): ctx = await client.get_context(message) prefix = await client.get_prefix(message) await ctx.send(f">>> Coucou !\nMon préfix est `{prefix}` et ma commande d'aide est `{prefix}help`") - - """citation""" - urls = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', message.content) - httpsString = "https://" - channelsString = "discord.com/channels/" - for i in range(len(urls)): - if urls[i].startswith(f"{httpsString}{channelsString}") or urls[i].startswith(f"{httpsString}ptb.{channelsString}") or urls[i].startswith(f"{httpsString}canary.{channelsString}"): - link = urls[i] - linkURL = link - if link.startswith(f"{httpsString}{channelsString}"): - link = f'000{link}' - if link.startswith(f"{httpsString}ptb.{channelsString}"): - link = link[1:] - if link.startswith(f"{httpsString}canary.{channelsString}"): - link = link[4:] - if "@me" in urls[i]: - return await message.channel.send("Je ne cite pas les messages privés.", delete_after = 5) - try: - if int(link[32:-38]) == message.guild.id: - msgID = await client.get_channel(int(link[51:-19])).fetch_message(int(link[70:])) - couleur = 0x2f3136 - msgFiles = msgID.attachments - imageExtensions = ["jpg", "jpeg", "png", "webp", "gif"] - desc = msgID.content - if len(msgFiles) > 1: - listOfFiles = "" - for i in range(0, len(msgFiles)): - listOfFiles = f"{listOfFiles}, {msgFiles[i].filename}" - listOfFiles = listOfFiles[2:] - if len(msgID.content) > 0: - desc = f"{msgID.content}\n\nIl y a plusieurs fichiers dans ce message : {listOfFiles}" - else: - desc = f"Il y a plusieurs fichiers dans ce message : {listOfFiles}" - else: - if len(msgFiles) == 1: - if msgFiles[0].filename[-4:].split('.')[1] in imageExtensions: - if not len(msgID.content) > 0: - desc = f"Une image jointe : {msgFiles[0].filename}" - else: - linkFile = msgFiles[0].url - if not len(msgID.content) > 0: - desc = f"Un fichier joint : {msgFiles[0].filename}" - embed = discord.Embed(description = desc, colour = couleur) - auteur = "Auteur" - if message.author == msgID.author: - auteur = "Auteur & Citateur" - embed.add_field(name = auteur, value = msgID.author.mention, inline=True) - try: - if len(msgFiles) == 1: - if msgFiles[0].filename[-4:].split('.')[1] in imageExtensions: - embed.set_image(url=msgFiles[0].url) - else: - embed.add_field(name = "Fichier", value = f"[Lien]({linkFile})", inline=True) - except: - pass - embed.add_field(name = "Message", value = f"{msgID.channel.mention} - [Lien Message]({linkURL})", inline=True) - embed.set_author(name = "Citation", icon_url = msgID.author.avatar_url) - icon_url = message.author.avatar_url - - date_1 = goodTimezone(msgID.created_at, customTimezone) - edit = "" - if msgID.edited_at: - date_edit = goodTimezone(msgID.edited_at, customTimezone) - edit = f" et modifié le {date_edit[0][8:]}/{date_edit[0][5:-3]}/{date_edit[0][:4]} à {date_edit[1]}" - messageDuBas = f"Posté le {date_1[0][8:]}/{date_1[0][5:-3]}/{date_1[0][:4]} à {date_1[1]}{edit}" - - date_2 = goodTimezone(message.created_at, customTimezone) - date_2 = f"{date_2[0][8:]}/{date_2[0][5:-3]}/{date_2[0][:4]} à {date_2[1]}" - - if auteur == "Auteur": - messageDuBas = messageDuBas + f"\nCité par {userOrNick(message.author)} le {date_2}" - embed.set_footer(icon_url = icon_url, text = messageDuBas) - if message.content == linkURL.replace(' ',''): - await message.channel.send(embed = embed) - await message.delete() - else: - await message.reply(embed = embed, mention_author = False) - except Exception as e: - e = str(e) - if not "invalid literal for int() with base 10:" in e or not "404 Not Found (error code: 10008)" in e: # faute de frappe / message supprimé - print(e) print("Connexion à Discord...", end = " ") client.run(os.environ['TOKEN_DISCORD']) From 340cdb6ea05c521b6756d1f96935f54a430020a9 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 00:03:54 +0200 Subject: [PATCH 133/286] suppression espace --- src/cogs/confreriedukassoulait.py | 1 - src/cogs/fun.py | 1 - src/cogs/games.py | 1 - src/cogs/help.py | 1 - src/cogs/internet.py | 1 - src/cogs/school.py | 1 - src/cogs/utils.py | 1 - 7 files changed, 7 deletions(-) diff --git a/src/cogs/confreriedukassoulait.py b/src/cogs/confreriedukassoulait.py index 2e0bf86..6019b02 100644 --- a/src/cogs/confreriedukassoulait.py +++ b/src/cogs/confreriedukassoulait.py @@ -14,7 +14,6 @@ def setup(client): class ConfrerieDuKassoulait(commands.Cog): """Unique pour le serveur Discord "La confrérie du Kassoulait".""" - def __init__(self, client): self.client = client diff --git a/src/cogs/fun.py b/src/cogs/fun.py index 9348b57..7541f77 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -11,7 +11,6 @@ def setup(client): class Fun(commands.Cog): """Commandes plutôt fun.""" - def __init__(self, client): self.client = client diff --git a/src/cogs/games.py b/src/cogs/games.py index 97a02fe..195ca1b 100644 --- a/src/cogs/games.py +++ b/src/cogs/games.py @@ -9,7 +9,6 @@ def setup(client): class Games(commands.Cog): """Commandes relatives aux jeux.""" - def __init__(self, client): self.client = client self.guessing_game = {} diff --git a/src/cogs/help.py b/src/cogs/help.py index 6face42..35b670d 100644 --- a/src/cogs/help.py +++ b/src/cogs/help.py @@ -7,7 +7,6 @@ def setup(client): class Help(commands.Cog): """Commandes relatives à l'aide utilisateur.""" - def __init__(self, client): self.client = client self.client.remove_command("help") diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 8aa89dc..8143faa 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -12,7 +12,6 @@ def setup(client): class Internet(commands.Cog): """Commandes relatives à ce qui provient d'internet.""" - def __init__(self, client): self.client = client diff --git a/src/cogs/school.py b/src/cogs/school.py index caf7557..9ab66a6 100644 --- a/src/cogs/school.py +++ b/src/cogs/school.py @@ -7,7 +7,6 @@ def setup(client): class School(commands.Cog): """Commandes relatives aux cours.""" - def __init__(self, client): self.client = client diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 80f7ecc..e1efc1e 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -577,7 +577,6 @@ class Utils(commands.Cog): else: embed.add_field(name = "\u200b", value = "Vous n'avez aucun rappels en attente !") await ctx.send(embed = embed) - @cog_ext.cog_slash(name="reminderlist", description = "Affiche la liste des rappels d'un utilisateur.") async def __reminderlist(self, ctx, utilisateur = None): if utilisateur == None: From e9fed9ac5ca1810bb8122788c8b254b80d843cf9 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 00:06:04 +0200 Subject: [PATCH 134/286] suppression d'import inutile --- src/main.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main.py b/src/main.py index bc5d479..a4d246f 100644 --- a/src/main.py +++ b/src/main.py @@ -1,11 +1,9 @@ print("Chargement des extensions & librairie...", end = " ") import discord -import re import os from discord_slash import SlashCommand from discord.ext import commands -from utils.core import userOrNick, goodTimezone from utils.reminder import Reminder customPrefix = os.environ['PREFIX'] customTimezone = os.environ['TIMEZONE'] From d8b2c003ccdd93bc6a9db4c0510e332cdb256cf0 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 00:59:17 +0200 Subject: [PATCH 135/286] meilleur slash args --- src/cogs/utils.py | 44 +++++++++++++++++++++++++++----------------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index e1efc1e..923f1e9 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -2,7 +2,6 @@ import discord import time import os import re -import shlex from discord.ext import commands, tasks from random import randint, shuffle from datetime import datetime @@ -50,7 +49,7 @@ class Utils(commands.Cog): await message.edit(embed = discord.Embed(color = discord.Colour.random(), description = f':hourglass: {round(self.client.latency * 1000)} ms\n\n:stopwatch: {ping2} ms\n\n:heartbeat: {ping} ms')) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') - @cog_ext.cog_slash(name="ping", description = "Affiche mon ping.") + @cog_ext.cog_slash(name="ping", description = "Affiche mon ping, mettre 'help' en argument pour connaître à quoi correspond les données.") async def __ping(self, ctx, arg = None): ctx.slash_created_at = int(datetime.now(timezone(self.customTimezone)).timestamp()) if arg == None: @@ -289,7 +288,7 @@ class Utils(commands.Cog): @commands.command(name='amongus') async def _amongus(self, ctx, *map): - """Affiche la carte voulue d'Among Us.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}amongus ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Affiche la carte voulue d'Among Us.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}amongus ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" fromSlash = False if len(map) > 0: if map[-1] == True: @@ -343,7 +342,7 @@ class Utils(commands.Cog): await ctx.invoke(self.client.get_command("amongus")) else: await ctx.message.add_reaction(emoji = '❓') - @cog_ext.cog_slash(name="amongus", description = "Affiche la carte voulue d'Among Us.") + @cog_ext.cog_slash(name="amongus", description = "Affiche la carte voulue d'Among Us. Carte dispo : ") async def __amongus(self, ctx, map): return await self._amongus(ctx, map, True) @@ -396,7 +395,7 @@ class Utils(commands.Cog): if len(args) > 0: if args[-1] == True: fromSlash = args[-1] - args = args[:-1] + args = args[0] args = list(args) if len(args) > 2: @@ -435,12 +434,21 @@ class Utils(commands.Cog): else: return await ctx.send(f"Désolé, mais tu as mis trop de possibilités (maximum : 20)") else: - return await ctx.send(f'Désolé, mais il manque des arguments : `{ctx.prefix}sondage "" "" "" ""`') + return await ctx.send(f'Désolé, mais il manque des arguments : `{ctx.prefix}sondage "" "" "" ""`') @cog_ext.cog_slash(name="sondage", description = "Fais un sondage.") - async def __sondage(self, ctx, args): + async def __sondage(self, ctx, question, prop1, prop2, prop3 = None, prop4 = None, + prop5 = None, prop6 = None, prop7 = None, prop8 = None, prop9 = None, prop10 = None, + prop11 = None, prop12 = None, prop13 = None, prop14 = None, prop15 = None, prop16 = None, + prop17 = None, prop18 = None, prop19 = None, prop20 = None): ctx.prefix = "/" - args = shlex.split(args) - return await self._sondage(ctx, *args, True) + args = [question, prop1, prop2, prop3, prop4, prop5, prop6, prop7, prop8, + prop9, prop10, prop11, prop12, prop13, prop14, prop15, prop16, + prop17, prop18, prop19, prop20] + for i in range(3, 20): # suppression des None + if args[i] == None: + args = args[:i] + break + return await self._sondage(ctx, args, True) @commands.command(name='avis', aliases=['vote']) async def _avis(self, ctx, *args): @@ -449,7 +457,7 @@ class Utils(commands.Cog): if len(args) > 0: if args[-1] == True: fromSlash = args[-1] - args = args[:-1] + args = args[0] args = list(args) if len(args) > 2 or len(args) == 0: @@ -469,10 +477,12 @@ class Utils(commands.Cog): await message.add_reaction(emoji = i) if fromSlash != True: return await ctx.message.delete() - @cog_ext.cog_slash(name="avis", description = "Demande un avis.") - async def __avis(self, ctx, args): - args = shlex.split(args) - return await self._avis(ctx, *args, True) + @cog_ext.cog_slash(name="avis", description = "Demande un avis, si 2 arguments, alors l'argument 1 est le titre, sinon c'est la demande.") + async def __avis(self, ctx, titreoudemande, demande = None): + args = [titreoudemande, demande] + if args[1] == None: + args = args[:1] + return await self._avis(ctx, args, True) @commands.command(name='reminder', aliases=["remind", "remindme", "rappel"]) async def _reminder(self, ctx, time, *reminder): @@ -578,8 +588,8 @@ class Utils(commands.Cog): embed.add_field(name = "\u200b", value = "Vous n'avez aucun rappels en attente !") await ctx.send(embed = embed) @cog_ext.cog_slash(name="reminderlist", description = "Affiche la liste des rappels d'un utilisateur.") - async def __reminderlist(self, ctx, utilisateur = None): - if utilisateur == None: + async def __reminderlist(self, ctx, user = None): + if user == None: return await self._reminderlist(ctx, True) else: - return await self._reminderlist(ctx, utilisateur, True) + return await self._reminderlist(ctx, user, True) From e19f0d75562d2a9f535cc8a58a41ffc94da8a3b9 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 01:12:42 +0200 Subject: [PATCH 136/286] suppression S --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 923f1e9..f60eb65 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -585,7 +585,7 @@ class Utils(commands.Cog): expiration = f"A déjà expiré." embed.add_field(value = texte, name = f"Fais le {timestampFR(intToTimestamp(reminder[1]))}\n{expiration}", inline = False) else: - embed.add_field(name = "\u200b", value = "Vous n'avez aucun rappels en attente !") + embed.add_field(name = "\u200b", value = "Vous n'avez aucun rappel en attente !") await ctx.send(embed = embed) @cog_ext.cog_slash(name="reminderlist", description = "Affiche la liste des rappels d'un utilisateur.") async def __reminderlist(self, ctx, user = None): From 0323aeae46a33b7a6633ae7db3c8ca06bcc787d6 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 09:56:50 +0200 Subject: [PATCH 137/286] suppression try except dans loop reminder --- src/cogs/utils.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index f60eb65..5ff85f6 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -515,7 +515,7 @@ class Utils(commands.Cog): if fromSlash != True: messageID = ctx.message.id Reminder().ajoutReminder(messageID, ctx.channel.id, mention, reminder, now, now + seconds, ctx.author.id) - return await ctx.send(f"Ok, je t'en parles dans {timedeltaToString(seconds)} avec 1min de retard maximum.") + return await ctx.send(f"Ok, je t'en parles dans {timedeltaToString(seconds)} avec 1m de retard maximum.") await ctx.send(embed = embed) @cog_ext.cog_slash(name="reminder", description = "Met en place un rappel.") async def __reminder(self, ctx, time, reminder = None): @@ -535,11 +535,10 @@ class Utils(commands.Cog): for i in mentionList: message += f" {i}" channel = self.client.get_channel(expired[0]) - try: - sourceMessage = await channel.fetch_message(expired[6]) + sourceMessage = expired[6] + if sourceMessage != None: + sourceMessage = await channel.fetch_message(sourceMessage) await sourceMessage.add_reaction(emoji = '✅') - except: - pass finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = intToTimestamp(expired[3]), color = discord.Colour.random()) finalEmbed.set_footer(text=f"Message d'il y a {timedeltaToString(int(nowTimestampUTC()) - expired[3])}") @@ -580,12 +579,13 @@ class Utils(commands.Cog): texte = f"{texte[:1021]}..." expiration = reminder[2] - int(nowTimestampUTC()) if expiration > 0: - expiration = f"Expire dans {timedeltaToString(expiration)} +1min de retard max." + expiration = f"Expire dans {timedeltaToString(expiration)} +1m de retard max." else: expiration = f"A déjà expiré." embed.add_field(value = texte, name = f"Fais le {timestampFR(intToTimestamp(reminder[1]))}\n{expiration}", inline = False) else: embed.add_field(name = "\u200b", value = "Vous n'avez aucun rappel en attente !") + embed.set_footer(text = "Les rappels qui ont déjà expirés vont apparaître dans quelques instants.") await ctx.send(embed = embed) @cog_ext.cog_slash(name="reminderlist", description = "Affiche la liste des rappels d'un utilisateur.") async def __reminderlist(self, ctx, user = None): From fd0151d2abfd03af97cacd3b6b8708f4f9e5e3f7 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 20:29:32 +0200 Subject: [PATCH 138/286] larger icon in reminderlist --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 5ff85f6..3a695de 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -571,7 +571,7 @@ class Utils(commands.Cog): if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') embed = discord.Embed(description = f"**Rappel{'s' if len(reminders) > 1 else ''} de <@{utilisateur}>**", color = discord.Colour.random()) - embed.set_thumbnail(url = self.client.get_user(utilisateur).avatar_url_as(size = 32)) + embed.set_thumbnail(url = self.client.get_user(utilisateur).avatar_url_as(size = 64)) if len(reminders) > 0: for reminder in reminders: texte = reminder[0] From aec56fd0fc57cf850561e8301f8bb0c65dfbe692 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 20:29:59 +0200 Subject: [PATCH 139/286] using right tz for reminderlist --- src/utils/core.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/utils/core.py b/src/utils/core.py index 0dde06e..21948de 100644 --- a/src/utils/core.py +++ b/src/utils/core.py @@ -1,8 +1,8 @@ import re import json import requests -import time import os +from time import time from pytz import timezone from datetime import datetime, timedelta @@ -120,7 +120,7 @@ def removeStartEndSpacesString(string): def randomImage(link): """Récupération d'une image aléatoirement⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - temps_requete = int(round(time.time() * 1000)) + temps_requete = int(round(time() * 1000)) try: request_data = requests.get(link) except Exception as e: @@ -134,7 +134,7 @@ def randomImage(link): except Exception as e: raise Exception(f"Erreur lors de la transformation les données de {link} en json : {e}") - temps_requete = int(round(time.time() * 1000)) - temps_requete + temps_requete = int(round(time() * 1000)) - temps_requete return (json_data, temps_requete) def retirerDoublons(liste): @@ -183,6 +183,9 @@ def stringTempsVersSecondes(time): def nowTimestampCustom(): return datetime.now(timezone(myTimezone)).timestamp() +def UTCTimestampToCustomTimestamp(timestamp): + return timezone(myTimezone).fromutc(timestamp) + def nowTimestampUTC(): return datetime.utcnow().timestamp() @@ -206,5 +209,7 @@ def timedeltaToString(time): return ''.join(age) def timestampFR(timestamp): - date_edit = str(timestamp).replace('-', '/').split(' ') - return f"{date_edit[0][8:]}/{date_edit[0][5:-3]}/{date_edit[0][:4]} à {date_edit[1]}" + date_edit = str(UTCTimestampToCustomTimestamp(timestamp)).replace('-', '/').split(' ') + date = date_edit[0] + heure = date_edit[1].split('+')[0] + return f"{date[8:]}/{date[5:-3]}/{date[:4]} à {heure}" From 4440372dbb2a1ad3e3baea8e8db4d4eb6c956199 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 21:32:14 +0200 Subject: [PATCH 140/286] gestion erreur quand message inexistant lors d'une erreur (slash command) --- src/main.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main.py b/src/main.py index a4d246f..cd2539e 100644 --- a/src/main.py +++ b/src/main.py @@ -36,7 +36,8 @@ async def on_ready(): async def on_command_error(ctx, error): if not ctx.invoked_with.startswith(customPrefix): print(error) - await ctx.message.add_reaction(emoji = '❓') + if "discord.errors.NotFound" in str(error) == False: + await ctx.message.add_reaction(emoji = '❓') @client.event async def on_message(message): From acc8da8be364130a2848d8a8cccd404e5e6db09d Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 21:33:20 +0200 Subject: [PATCH 141/286] =?UTF-8?q?d=C3=A9placement=20m=C3=A9thode=20en=20?= =?UTF-8?q?rapport=20avec=20le=20temps=20dans=20un=20fichier=20a=20part?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/citation.py | 3 +- src/cogs/confreriedukassoulait.py | 3 +- src/cogs/utils.py | 35 +++++---- src/utils/core.py | 106 --------------------------- src/utils/time.py | 114 ++++++++++++++++++++++++++++++ 5 files changed, 135 insertions(+), 126 deletions(-) create mode 100644 src/utils/time.py diff --git a/src/cogs/citation.py b/src/cogs/citation.py index 34757e2..2eb8732 100644 --- a/src/cogs/citation.py +++ b/src/cogs/citation.py @@ -3,7 +3,8 @@ import re import os from discord.ext import commands customTimezone = os.environ['TIMEZONE'] -from utils.core import goodTimezone, userOrNick +from utils.core import userOrNick +from utils.time import goodTimezone def setup(client): client.add_cog(Citation(client)) diff --git a/src/cogs/confreriedukassoulait.py b/src/cogs/confreriedukassoulait.py index 6019b02..393da6b 100644 --- a/src/cogs/confreriedukassoulait.py +++ b/src/cogs/confreriedukassoulait.py @@ -6,7 +6,8 @@ from random import choice from datetime import datetime from pytz import timezone customTimezone = os.environ['TIMEZONE'] -from utils.core import goodTimezone, userOrNick +from utils.core import userOrNick +from utils.time import goodTimezone from cogs.internet import Internet def setup(client): diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 3a695de..c3c1833 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -1,5 +1,4 @@ import discord -import time import os import re from discord.ext import commands, tasks @@ -8,9 +7,9 @@ from datetime import datetime from pytz import timezone from discord_slash import cog_ext from utils.reminder import Reminder -from utils.core import map_list_among_us, get_age, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs -from utils.core import cleanUser, userOrNick, ageLayout, stringTempsVersSecondes, timedeltaToString, intToTimestamp, nowTimestampUTC -from utils.core import timestampFR +from utils.core import map_list_among_us, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs +from utils.core import cleanUser, userOrNick +from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString, timestampScreen, getAge, ageLayout, nowCustom def setup(client): client.add_cog(Utils(client)) @@ -36,22 +35,22 @@ class Utils(commands.Cog): arg = None if arg == 'help': - return await ctx.send(embed = discord.Embed(color = discord.Colour.random(), description = ":hourglass: correspond au temps entre deux battements de cœurs\n\n:stopwatch: correspond au temps que met le client a calculer le ping\n\n:heartbeat: correspond au temps que met le client a réagir au messages")) + return await ctx.send(embed = discord.Embed(color = discord.Colour.random(), description = ":hourglass: correspond au temps entre deux battements de cœurs\n\n:heartbeat: correspond au temps que met le client a réagir au messages (0 est normal lors de l'utilisation d'une commande slash)\n\n:stopwatch: correspond au temps que met le client a calculer le ping")) else: - now = int(round(time.time() * 1000)) + now = int(round(nowCustom() * 1000)) if fromSlash != True: ping = now - int(round(ctx.message.created_at.timestamp() * 1000)) else: ping = now - int(round(ctx.slash_created_at * 1000)) embed = discord.Embed(description = 'Pinging...') message = await ctx.send(embed = embed) - ping2 = int(round(time.time() * 1000)) - now - await message.edit(embed = discord.Embed(color = discord.Colour.random(), description = f':hourglass: {round(self.client.latency * 1000)} ms\n\n:stopwatch: {ping2} ms\n\n:heartbeat: {ping} ms')) + ping2 = int(round(nowCustom() * 1000)) - now + await message.edit(embed = discord.Embed(color = discord.Colour.random(), description = f':hourglass: {round(self.client.latency * 1000)} ms\n\n:heartbeat: {ping} ms\n\n:stopwatch: {ping2} ms')) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') @cog_ext.cog_slash(name="ping", description = "Affiche mon ping, mettre 'help' en argument pour connaître à quoi correspond les données.") async def __ping(self, ctx, arg = None): - ctx.slash_created_at = int(datetime.now(timezone(self.customTimezone)).timestamp()) + ctx.slash_created_at = nowCustom() if arg == None: return await self._ping(ctx, True) else: @@ -227,7 +226,7 @@ class Utils(commands.Cog): await ctx.message.delete() embed = discord.Embed(description = text, color = discord.Colour.random()) embed.set_author(name = f"Mémo noté depuis {ctx.guild.name}", icon_url = ctx.author.avatar_url) - embed.set_footer(text = f'📝 le {datetime.now(timezone(self.customTimezone)).strftime("%d/%m/%Y à %H:%M:%S")}') + embed.set_footer(text = f'📝 le {timestampScreen(intToDatetime(nowUTC()))}') await ctx.author.send(embed = embed) return await ctx.send("Tu viens de recevoir ton mémo !", delete_after = 5) @_memo.error @@ -368,14 +367,14 @@ class Utils(commands.Cog): value = str(user[0].created_at.astimezone(timezone(self.customTimezone)))[:-13].replace('-', '/').split() embed.add_field(name = "Compte créé le", value = f"{value[0][8:]}/{value[0][5:-3]}/{value[0][:4]} à {value[1]}") - embed.add_field(name = "Âge du compte", value = ageLayout(get_age(user[0].created_at))) + embed.add_field(name = "Âge du compte", value = ageLayout(getAge(user[0].created_at))) embed.add_field(name = "Mention", value = user[0].mention) value = str(user[0].joined_at.astimezone(timezone(self.customTimezone)))[:-13].replace('-', '/').split() embed.add_field(name = "Serveur rejoint le", value = f"{value[0][8:]}/{value[0][5:-3]}/{value[0][:4]} à {value[1]}") - embed.add_field(name = "Est sur le serveur depuis", value = ageLayout(get_age(user[0].joined_at))) + embed.add_field(name = "Est sur le serveur depuis", value = ageLayout(getAge(user[0].joined_at))) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') return await ctx.send(embed = embed) @@ -510,7 +509,7 @@ class Utils(commands.Cog): elif seconds > 7776000: # 90 * 60 * 60 * 24 embed.add_field(name="Attention", value="Tu as spécifié une durée trop longue, la durée maximum étant de 90 jours.") else: - now = int(nowTimestampUTC()) + now = int(nowUTC()) messageID = None if fromSlash != True: messageID = ctx.message.id @@ -526,7 +525,7 @@ class Utils(commands.Cog): @tasks.loop(minutes = 1) async def _reminderLoop(self): - expiration = Reminder().recuperationExpiration(int(nowTimestampUTC())) + expiration = Reminder().recuperationExpiration(int(nowUTC())) for expired in expiration: message = f"<@{expired[4]}>" reminder = expired[2] @@ -539,8 +538,8 @@ class Utils(commands.Cog): if sourceMessage != None: sourceMessage = await channel.fetch_message(sourceMessage) await sourceMessage.add_reaction(emoji = '✅') - finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = intToTimestamp(expired[3]), color = discord.Colour.random()) - finalEmbed.set_footer(text=f"Message d'il y a {timedeltaToString(int(nowTimestampUTC()) - expired[3])}") + finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = intToDatetime(expired[3]), color = discord.Colour.random()) + finalEmbed.set_footer(text=f"Message d'il y a {timedeltaToString(int(nowUTC()) - expired[3])}") links = "" findedURLs = getURLsInString(reminder) @@ -577,12 +576,12 @@ class Utils(commands.Cog): texte = reminder[0] if len(texte) > 1024: texte = f"{texte[:1021]}..." - expiration = reminder[2] - int(nowTimestampUTC()) + expiration = reminder[2] - int(nowUTC()) if expiration > 0: expiration = f"Expire dans {timedeltaToString(expiration)} +1m de retard max." else: expiration = f"A déjà expiré." - embed.add_field(value = texte, name = f"Fais le {timestampFR(intToTimestamp(reminder[1]))}\n{expiration}", inline = False) + embed.add_field(value = texte, name = f"Fais le {timestampScreen(intToDatetime(reminder[1]))}\n{expiration}", inline = False) else: embed.add_field(name = "\u200b", value = "Vous n'avez aucun rappel en attente !") embed.set_footer(text = "Les rappels qui ont déjà expirés vont apparaître dans quelques instants.") diff --git a/src/utils/core.py b/src/utils/core.py index 21948de..3577f4e 100644 --- a/src/utils/core.py +++ b/src/utils/core.py @@ -1,19 +1,7 @@ import re import json import requests -import os from time import time -from pytz import timezone -from datetime import datetime, timedelta - -myTimezone = os.environ['TIMEZONE'] - -def goodTimezone(date, tz, type = 0): - """renvoie une date en fonction d'un timezone""" - if type == 0: - return str(timezone(tz).fromutc(date))[:-13].replace('-', '/').split() - elif type == 1: - return str(timezone(tz).fromutc(date))[:-13].replace('-', '/').replace(' ', ' à ') def map_list_among_us(map): """Sélecteur de map pour la commande amongus⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" @@ -26,41 +14,6 @@ def map_list_among_us(map): return maps["skeld"] + maps["mira"] + maps["polus"] + maps["airship"] return maps[map] -def get_age(date): - """Recupère un age précisément à la seconde près""" - joursRestants = datetime.now() - date - years = joursRestants.total_seconds() / (365.242 * 24 * 3600) - months = (years - int(years)) * 12 - days = (months - int(months)) * (365.242 / 12) - hours = (days - int(days)) * 24 - minutes = (hours - int(hours)) * 60 - seconds = (minutes - int(minutes)) * 60 - return (int(years), int(months), int(days), int(hours), int(minutes), int(seconds)) - -def ageLayout(tuple): - """avec la méthode 'get_age', permet de mettre en forme un âge⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - time = {} - time[0], time[1], time[2], time[3], time[4], time[5] = "an", "mois", "jour", "heure", "minute", "seconde" - for i in range(len(tuple)): - if tuple[i] > 1 and i != 1: - time[i] = time[i] + "s" - message = "" - if tuple[5] > 0: # pour les secondes - affichage = [5] # on affiche que : seconde - if tuple[4] > 0: - affichage = [4, 5] # on affiche : minute + seconde - if tuple[3] > 0: - affichage = [3, 4, 5] # on affiche : heure + minute + seconde - if tuple[2] > 0: - affichage = [2, 3, 4] # on affiche : jour + heure + minute - if tuple[1] > 0: - affichage = [1, 2, 3] # on affiche : mois + jour + heure - if tuple[0] > 0: - affichage = [0, 1, 3] # on affiche : an + mois + heure - for i in affichage: - message = message + f", {tuple[i]} {time[i]}" - return message[2:] - def userOrNick(user): """Affiche le pseudo et/ou le surnom""" if user == None: @@ -154,62 +107,3 @@ def ligneFormatage(ligne): for balises in liste_balise: ligne = ligne.replace(balises[0], balises[1]) return ligne - -def stringTempsVersSecondes(time): - conversionTemps = { - "86400": ["j", "d"], - "3600": ["h"], - "60": ["m"], - "1": ["s", ""] - } - - valeursMultiplicateur = "" - for i in conversionTemps.values(): - for j in i: - valeursMultiplicateur += f"{j}|" - match = re.findall(f'([0-9]+)({valeursMultiplicateur[:-1]})?', time) - - if not match: - return "Veuillez entrer un temps valide." - - remindertime = 0 - for i in match: - for tempsEnSeconde, nomCommun in conversionTemps.items(): - if i[1] in nomCommun: - remindertime += int(tempsEnSeconde) * int(i[0]) - - return remindertime - -def nowTimestampCustom(): - return datetime.now(timezone(myTimezone)).timestamp() - -def UTCTimestampToCustomTimestamp(timestamp): - return timezone(myTimezone).fromutc(timestamp) - -def nowTimestampUTC(): - return datetime.utcnow().timestamp() - -def intToTimestamp(int): - return datetime.fromtimestamp(int) - -def timedeltaToString(time): - age = str(timedelta(seconds = time)).replace('days, ', 'jours, :').split(':') - if len(age) == 4: - a = [1, 1, 1, 1] # a pour affichage - if len(age) == 3: - a = [0, 1, 1, 1] - age.insert(0, None) - for i in range(1, 4): - if int(age[i]) == 0: - a[i] = 0 - age[0] = age[0] if a[0] == 1 else '' - age[1] = f"{age[1]}h " if a[1] == 1 else '' - age[2] = f"{age[2]}m " if a[2] == 1 else '' - age[3] = f"{age[3]}s" if a[3] == 1 else '' - return ''.join(age) - -def timestampFR(timestamp): - date_edit = str(UTCTimestampToCustomTimestamp(timestamp)).replace('-', '/').split(' ') - date = date_edit[0] - heure = date_edit[1].split('+')[0] - return f"{date[8:]}/{date[5:-3]}/{date[:4]} à {heure}" diff --git a/src/utils/time.py b/src/utils/time.py new file mode 100644 index 0000000..341e7bb --- /dev/null +++ b/src/utils/time.py @@ -0,0 +1,114 @@ +from os import environ +from pytz import timezone +from datetime import datetime, timedelta +from re import findall + +myTimezone = environ['TIMEZONE'] + +def stringTempsVersSecondes(time): + """Convertis une durée rentrée par un utilisateur en string vers des secondes en int""" + conversionTemps = { + "86400": ["j", "d"], + "3600": ["h"], + "60": ["m"], + "1": ["s", ""] + } + + valeursMultiplicateur = "" + for i in conversionTemps.values(): + for j in i: + valeursMultiplicateur += f"{j}|" + match = findall(f'([0-9]+)({valeursMultiplicateur[:-1]})?', time) + + if not match: + return "Veuillez entrer un temps valide." + + remindertime = 0 + for i in match: + for tempsEnSeconde, nomCommun in conversionTemps.items(): + if i[1] in nomCommun: + remindertime += int(tempsEnSeconde) * int(i[0]) + + return remindertime + +def nowCustom(): + """Heure de maintenant avec fuseau horaire local en float""" + return datetime.now(timezone(myTimezone)).timestamp() + +def nowUTC(): + """Heure de maintenant en UTC en float""" + return datetime.utcnow().timestamp() + +def UTCDatetimeToCustomDatetime(datetime): + """Conversion d'une timestamp UTC en timestamp local en datetime""" + return timezone(myTimezone).fromutc(datetime) + +def intToDatetime(intOrFloat): + """Convertis un int ou float en Datetime""" + return datetime.fromtimestamp(intOrFloat) + +def timestampScreen(timestamp): + """Affichage d'une timestamp""" + date_edit = str(UTCDatetimeToCustomDatetime(timestamp)).replace('-', '/').split(' ') + date = date_edit[0] + heure = date_edit[1].split('+')[0] + return f"{date[8:]}/{date[5:-3]}/{date[:4]} à {heure.split('.')[0]}" + +def timedeltaToString(time): + """Différence entre une heure en seconde et maintenant""" + age = str(timedelta(seconds = time)).replace('days, ', 'jours, :').split(':') + if len(age) == 4: + a = [1, 1, 1, 1] # a pour affichage + if len(age) == 3: + a = [0, 1, 1, 1] + age.insert(0, None) + for i in range(1, 4): + if int(age[i]) == 0: + a[i] = 0 + age[0] = age[0] if a[0] == 1 else '' + age[1] = f"{age[1]}h " if a[1] == 1 else '' + age[2] = f"{age[2]}m " if a[2] == 1 else '' + age[3] = f"{age[3]}s" if a[3] == 1 else '' + return ''.join(age) + +def getAge(date): + """Recupère un age précisément à la seconde près""" + joursRestants = datetime.now() - date + years = joursRestants.total_seconds() / (365.242 * 24 * 3600) + months = (years - int(years)) * 12 + days = (months - int(months)) * (365.242 / 12) + hours = (days - int(days)) * 24 + minutes = (hours - int(hours)) * 60 + seconds = (minutes - int(minutes)) * 60 + return (int(years), int(months), int(days), int(hours), int(minutes), int(seconds)) + +def ageLayout(tuple): + """avec la méthode 'getAge', permet de mettre en forme un âge⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + time = {} + time[0], time[1], time[2], time[3], time[4], time[5] = "an", "mois", "jour", "heure", "minute", "seconde" + for i in range(len(tuple)): + if tuple[i] > 1 and i != 1: + time[i] = time[i] + "s" + message = "" + if tuple[5] > 0: # pour les secondes + affichage = [5] # on affiche que : seconde + if tuple[4] > 0: + affichage = [4, 5] # on affiche : minute + seconde + if tuple[3] > 0: + affichage = [3, 4, 5] # on affiche : heure + minute + seconde + if tuple[2] > 0: + affichage = [2, 3, 4] # on affiche : jour + heure + minute + if tuple[1] > 0: + affichage = [1, 2, 3] # on affiche : mois + jour + heure + if tuple[0] > 0: + affichage = [0, 1, 3] # on affiche : an + mois + heure + for i in affichage: + message = message + f", {tuple[i]} {time[i]}" + return message[2:] + +def goodTimezone(date, tz, type = 0): + """Renvoie une date en fonction d'un timezone""" + if type == 0: + return str(timezone(tz).fromutc(date))[:-13].replace('-', '/').split() + elif type == 1: + return str(timezone(tz).fromutc(date))[:-13].replace('-', '/').replace(' ', ' à ') From c3d653fd914feeafeea8ac8eb64e024d116ac47a Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 21:51:58 +0200 Subject: [PATCH 142/286] useless import --- src/cogs/utils.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index c3c1833..88539c5 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -3,7 +3,6 @@ import os import re from discord.ext import commands, tasks from random import randint, shuffle -from datetime import datetime from pytz import timezone from discord_slash import cog_ext from utils.reminder import Reminder From f697ff0643b1d0bf3c7f854dcc3781e8bfcd1e05 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 21:52:40 +0200 Subject: [PATCH 143/286] using utils.time and better display of time in on_message_delete --- src/cogs/confreriedukassoulait.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/cogs/confreriedukassoulait.py b/src/cogs/confreriedukassoulait.py index 393da6b..2075c7b 100644 --- a/src/cogs/confreriedukassoulait.py +++ b/src/cogs/confreriedukassoulait.py @@ -3,11 +3,9 @@ import re import os from discord.ext import commands from random import choice -from datetime import datetime -from pytz import timezone customTimezone = os.environ['TIMEZONE'] from utils.core import userOrNick -from utils.time import goodTimezone +from utils.time import nowCustom, intToDatetime, nowUTC, timestampScreen from cogs.internet import Internet def setup(client): @@ -87,7 +85,7 @@ class ConfrerieDuKassoulait(commands.Cog): user_suppressed = None async for entry in message.guild.audit_logs(limit=1): - if (datetime.now() - entry.created_at).seconds < 5 and str(entry.action) == 'AuditLogAction.message_delete': + if (intToDatetime(nowCustom()) - entry.created_at).seconds < 5 and str(entry.action) == 'AuditLogAction.message_delete': user_suppressed = entry.user channel = self.client.get_channel(742588187456831659) @@ -96,9 +94,9 @@ class ConfrerieDuKassoulait(commands.Cog): embed.set_author(name = userOrNick(message.author), icon_url = message.author.avatar_url) if not user_suppressed: - embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, customTimezone, 1)}\nSupprimé le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") + embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {timestampScreen(message.created_at)}\nSupprimé le {timestampScreen(intToDatetime(nowUTC()))}") else: - embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {goodTimezone(message.created_at, customTimezone, 1)}\nSupprimé par {userOrNick(user_suppressed)} le {datetime.now(timezone(customTimezone)).strftime('%d/%m/%Y à %H:%M:%S')}") + embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {timestampScreen(message.created_at)}\nSupprimé par {userOrNick(user_suppressed)} le {timestampScreen(intToDatetime(nowUTC()))}") await channel.send(embed = embed) # ne fonctionne pas quand un message a été supprimé avant que le bot ai démarré From b9393a87e0a6bcc9d9fbd2763f1b3066dd05bf7e Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 21:58:34 +0200 Subject: [PATCH 144/286] replace deprecated method --- src/cogs/citation.py | 16 ++++++---------- src/utils/time.py | 7 ------- 2 files changed, 6 insertions(+), 17 deletions(-) diff --git a/src/cogs/citation.py b/src/cogs/citation.py index 2eb8732..aeb0cdc 100644 --- a/src/cogs/citation.py +++ b/src/cogs/citation.py @@ -4,7 +4,7 @@ import os from discord.ext import commands customTimezone = os.environ['TIMEZONE'] from utils.core import userOrNick -from utils.time import goodTimezone +from utils.time import timestampScreen def setup(client): client.add_cog(Citation(client)) @@ -73,18 +73,14 @@ class Citation(commands.Cog): embed.set_author(name = "Citation", icon_url = msgID.author.avatar_url) icon_url = message.author.avatar_url - date_1 = goodTimezone(msgID.created_at, customTimezone) - edit = "" if msgID.edited_at: - date_edit = goodTimezone(msgID.edited_at, customTimezone) - edit = f" et modifié le {date_edit[0][8:]}/{date_edit[0][5:-3]}/{date_edit[0][:4]} à {date_edit[1]}" - messageDuBas = f"Posté le {date_1[0][8:]}/{date_1[0][5:-3]}/{date_1[0][:4]} à {date_1[1]}{edit}" - - date_2 = goodTimezone(message.created_at, customTimezone) - date_2 = f"{date_2[0][8:]}/{date_2[0][5:-3]}/{date_2[0][:4]} à {date_2[1]}" + edit = f" et modifié le {timestampScreen(msgID.edited_at)}" + else: + edit = "" + messageDuBas = f"Posté le {timestampScreen(msgID.created_at)}{edit}" if auteur == "Auteur": - messageDuBas = messageDuBas + f"\nCité par {userOrNick(message.author)} le {date_2}" + messageDuBas = messageDuBas + f"\nCité par {userOrNick(message.author)} le {timestampScreen(message.created_at)}" embed.set_footer(icon_url = icon_url, text = messageDuBas) if message.content == linkURL.replace(' ',''): await message.channel.send(embed = embed) diff --git a/src/utils/time.py b/src/utils/time.py index 341e7bb..10950f6 100644 --- a/src/utils/time.py +++ b/src/utils/time.py @@ -105,10 +105,3 @@ def ageLayout(tuple): for i in affichage: message = message + f", {tuple[i]} {time[i]}" return message[2:] - -def goodTimezone(date, tz, type = 0): - """Renvoie une date en fonction d'un timezone""" - if type == 0: - return str(timezone(tz).fromutc(date))[:-13].replace('-', '/').split() - elif type == 1: - return str(timezone(tz).fromutc(date))[:-13].replace('-', '/').replace(' ', ' à ') From 7c1c34272a3a9da1b644920a77aa213e2a05da53 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 22:08:35 +0200 Subject: [PATCH 145/286] better import --- src/cogs/confreriedukassoulait.py | 6 ++---- src/cogs/fun.py | 4 ++-- src/cogs/internet.py | 4 ++-- src/cogs/utils.py | 18 ++++++++---------- 4 files changed, 14 insertions(+), 18 deletions(-) diff --git a/src/cogs/confreriedukassoulait.py b/src/cogs/confreriedukassoulait.py index 2075c7b..cb2d5c1 100644 --- a/src/cogs/confreriedukassoulait.py +++ b/src/cogs/confreriedukassoulait.py @@ -1,9 +1,7 @@ import discord -import re -import os +from re import findall from discord.ext import commands from random import choice -customTimezone = os.environ['TIMEZONE'] from utils.core import userOrNick from utils.time import nowCustom, intToDatetime, nowUTC, timestampScreen from cogs.internet import Internet @@ -79,7 +77,7 @@ class ConfrerieDuKassoulait(commands.Cog): if not ( message.content.startswith(f"{prefix}note") or message.content.startswith(f"{prefix}memo") or - len(re.findall(".com/channels/", message.content)) != 0 or + len(findall(".com/channels/", message.content)) != 0 or self.client.user.id is message.author.id ): user_suppressed = None diff --git a/src/cogs/fun.py b/src/cogs/fun.py index 7541f77..8c53864 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -1,5 +1,5 @@ import discord -import re +from re import findall from discord.ext import commands from random import randint, choice from datetime import timedelta @@ -161,7 +161,7 @@ class Fun(commands.Cog): final_message = message.content suite_auteur = message.author - urls = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', final_message) + urls = findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', final_message) for i in range (0, len(urls)): final_message = final_message.replace(urls[i], '') diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 8143faa..b99d794 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -1,6 +1,6 @@ import discord import feedparser -import os +from os import environ from discord.ext import commands from random import choice from asyncpraw import Reddit @@ -37,7 +37,7 @@ class Internet(commands.Cog): '2meirl4meirl', 'AdviceAnimals', 'weirdmemes']) try: - async with Reddit(client_id = os.environ['TOKEN_REDDIT_CLIENT_ID'], client_secret = os.environ['TOKEN_REDDIT_CLIENT_SECRET'], user_agent = f"disreddit /u/{os.environ['TOKEN_REDDIT_USER_AGENT']}, http://localhost:8080") as reddit: + async with Reddit(client_id = environ['TOKEN_REDDIT_CLIENT_ID'], client_secret = environ['TOKEN_REDDIT_CLIENT_SECRET'], user_agent = f"disreddit /u/{environ['TOKEN_REDDIT_USER_AGENT']}, http://localhost:8080") as reddit: subreddit = await reddit.subreddit(subredditchoix) # récupération du subreddit hot = subreddit.top(limit = 20) # récupération des memes avec une limite aux 10 premiers memes all_subs = [item async for item in hot] # liste des memes diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 88539c5..bab3081 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -1,13 +1,12 @@ import discord -import os -import re +from os import environ, path +from re import findall from discord.ext import commands, tasks from random import randint, shuffle from pytz import timezone from discord_slash import cog_ext from utils.reminder import Reminder -from utils.core import map_list_among_us, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs -from utils.core import cleanUser, userOrNick +from utils.core import map_list_among_us, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString, timestampScreen, getAge, ageLayout, nowCustom def setup(client): @@ -17,7 +16,7 @@ class Utils(commands.Cog): """Commandes essentielles.""" def __init__(self, client): self.client = client - self.customTimezone = os.environ['TIMEZONE'] + self.customTimezone = environ['TIMEZONE'] self._reminderLoop.start() @commands.command(name='ping') @@ -260,9 +259,8 @@ class Utils(commands.Cog): voice = len(voice_channels) nombreServeur = len(self.client.guilds) - with open(os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "README.md"), "r") as file: - for versionNumber in re.findall(r'https://img.shields.io/badge/version-(\d+\.\d+)', file.readlines()[2]): - version = versionNumber + with open(path.join(path.dirname(path.dirname(path.dirname(__file__))), "README.md"), "r") as file: + version = findall(r'https://img.shields.io/badge/version-(\d+\.\d+)', file.readlines()[2])[0] embed.add_field(name = "Dev", value = f"[{appinfo.owner}](https://github.com/Mylloon)") embed.add_field(name = f"Serveur{'s' if nombreServeur > 1 else ''}", value = f"`{nombreServeur}`") @@ -398,7 +396,7 @@ class Utils(commands.Cog): args = list(args) if len(args) > 2: question = args[0] - for i in re.findall(r'\d+', question): + for i in findall(r'\d+', question): question = cleanUser(ctx, question, i) propositions = args[1:] if len(propositions) <= 20: @@ -465,7 +463,7 @@ class Utils(commands.Cog): titre = "Nouveau vote" else: # si titre défini titre = args[0] - for findedId in re.findall(r'\d+', titre): # récupération mention dans titre + for findedId in findall(r'\d+', titre): # récupération mention dans titre titre = cleanUser(ctx, titre, findedId) args = args[1:] embed = discord.Embed(title = titre, description = cleanCodeStringWithMentionAndURLs(args[0]), color = discord.Colour.random()).set_footer(text = f"Sondage de {userOrNick(ctx.author)}", icon_url = ctx.author.avatar_url) From e2e2e928d06a4043f9e6956d0ed29c4a1b636994 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 22:10:06 +0200 Subject: [PATCH 146/286] useless timezone --- src/cogs/citation.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/cogs/citation.py b/src/cogs/citation.py index aeb0cdc..8c75922 100644 --- a/src/cogs/citation.py +++ b/src/cogs/citation.py @@ -1,8 +1,6 @@ import discord import re -import os from discord.ext import commands -customTimezone = os.environ['TIMEZONE'] from utils.core import userOrNick from utils.time import timestampScreen From 1c79ffb4fd2c2d7621803e1d3ae3677c40442002 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 22:14:48 +0200 Subject: [PATCH 147/286] =?UTF-8?q?utilisation=20du=20bon=20fuseau=20horai?= =?UTF-8?q?re=20et=20meilleur=20systeme=20pour=20l'affichage=20des=20donn?= =?UTF-8?q?=C3=A9es?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/utils.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index bab3081..18e08d6 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -361,15 +361,13 @@ class Utils(commands.Cog): embed.add_field(name = "ID", value = user[0].id) - value = str(user[0].created_at.astimezone(timezone(self.customTimezone)))[:-13].replace('-', '/').split() - embed.add_field(name = "Compte créé le", value = f"{value[0][8:]}/{value[0][5:-3]}/{value[0][:4]} à {value[1]}") + embed.add_field(name = "Compte créé le", value = timestampScreen(user[0].created_at)) embed.add_field(name = "Âge du compte", value = ageLayout(getAge(user[0].created_at))) embed.add_field(name = "Mention", value = user[0].mention) - value = str(user[0].joined_at.astimezone(timezone(self.customTimezone)))[:-13].replace('-', '/').split() - embed.add_field(name = "Serveur rejoint le", value = f"{value[0][8:]}/{value[0][5:-3]}/{value[0][:4]} à {value[1]}") + embed.add_field(name = "Serveur rejoint le", value = timestampScreen(user[0].joined_at)) embed.add_field(name = "Est sur le serveur depuis", value = ageLayout(getAge(user[0].joined_at))) if fromSlash != True: From 016727a36ad82e3e559b7d0ca45c608ec8ea749f Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 23:34:39 +0200 Subject: [PATCH 148/286] suppression import inutile --- src/cogs/utils.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 18e08d6..a4e73e4 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -3,7 +3,6 @@ from os import environ, path from re import findall from discord.ext import commands, tasks from random import randint, shuffle -from pytz import timezone from discord_slash import cog_ext from utils.reminder import Reminder from utils.core import map_list_among_us, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick From ce855a0b98bf6379d4057d1921cc9e37c2a4dbbb Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 7 Jun 2021 23:55:19 +0200 Subject: [PATCH 149/286] better import --- src/cogs/citation.py | 4 ++-- src/cogs/fun.py | 4 ++-- src/cogs/games.py | 2 +- src/cogs/internet.py | 4 ++-- src/cogs/music.py | 12 ++++++------ src/main.py | 7 +++---- 6 files changed, 16 insertions(+), 17 deletions(-) diff --git a/src/cogs/citation.py b/src/cogs/citation.py index 8c75922..b29c717 100644 --- a/src/cogs/citation.py +++ b/src/cogs/citation.py @@ -1,5 +1,5 @@ import discord -import re +from re import findall from discord.ext import commands from utils.core import userOrNick from utils.time import timestampScreen @@ -14,7 +14,7 @@ class Citation(commands.Cog): @commands.Cog.listener() async def on_message(self, message): - urls = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', message.content) + urls = findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', message.content) httpsString = "https://" channelsString = "discord.com/channels/" for i in range(len(urls)): diff --git a/src/cogs/fun.py b/src/cogs/fun.py index 8c53864..0003251 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -2,9 +2,9 @@ import discord from re import findall from discord.ext import commands from random import randint, choice -from datetime import timedelta from discord_slash import cog_ext from utils.core import retirerDoublons +from utils.time import intToDatetime def setup(client): client.add_cog(Fun(client)) @@ -142,7 +142,7 @@ class Fun(commands.Cog): """Se moque du message précédent. - Slash command not available⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" first = 0 suite_auteur = None - temps_limite = (await ctx.message.channel.history(limit = 2).flatten())[1].created_at - timedelta(minutes = 5) + temps_limite = intToDatetime((await ctx.message.channel.history(limit = 2).flatten())[1].created_at.timestamp() - 300) # on retire 5 minutes (5 x 60 secondes) final_message = "" async for message in ctx.message.channel.history(limit = 20, after = temps_limite, oldest_first = False): if first == 0: diff --git a/src/cogs/games.py b/src/cogs/games.py index 195ca1b..b89b4de 100644 --- a/src/cogs/games.py +++ b/src/cogs/games.py @@ -1,7 +1,7 @@ import discord +import asyncio from discord.ext import commands from random import randint, choice -import asyncio from discord_slash import cog_ext def setup(client): diff --git a/src/cogs/internet.py b/src/cogs/internet.py index b99d794..f355691 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -1,5 +1,5 @@ import discord -import feedparser +from feedparser import parse from os import environ from discord.ext import commands from random import choice @@ -193,7 +193,7 @@ class Internet(commands.Cog): embed = discord.Embed(title = "Liste des sources", color = discord.Colour.random(), description = ", ".join([key.capitalize() for key in rss_website.keys()])) return await ctx.send(embed = embed) - newsfeed = feedparser.parse(rss_website[choix_site]) + newsfeed = parse(rss_website[choix_site]) info = choice([newsfeed.entries[i] for i in range(0, 10 if len(newsfeed.entries) > 10 else len(newsfeed.entries))]) desc = "Pas de description trouvée." if "

" in info.description or "" in info.description else info.description diff --git a/src/cogs/music.py b/src/cogs/music.py index b871d73..fc92fc7 100644 --- a/src/cogs/music.py +++ b/src/cogs/music.py @@ -18,11 +18,11 @@ from async_timeout import timeout from discord.ext import commands # Genius API -import lyricsgenius -import time -import os -genius = lyricsgenius.Genius(os.environ['TOKEN_GENIUS']) +from lyricsgenius import Genius +from os import environ from utils.core import ligneFormatage, userOrNick +from utils.time import nowCustom +genius = Genius(environ['TOKEN_GENIUS']) # Silence useless bug reports messages youtube_dl.utils.bug_reports_message = lambda: '' @@ -498,7 +498,7 @@ class Music(commands.Cog): message = await ctx.send(f":mag: **Cherche les paroles romanisées de ** `{song.replace(' romanized', '')}`") else: message = await ctx.send(f":mag: **Cherche les paroles de ** `{song}`") - temps_requete = int(round(time.time() * 1000)) + temps_requete = int(round(nowCustom() * 1000)) song_genius = genius.search_song(song) couleur_embed = discord.Colour.random() try: @@ -531,7 +531,7 @@ class Music(commands.Cog): await ctx.send(embed = embed) lignetotal = f"{ligneFormatage(ligne)}" - temps_requete = int(round(time.time() * 1000)) - temps_requete + temps_requete = int(round(nowCustom() * 1000)) - temps_requete footer_embed = f"Pour {userOrNick(ctx.author)} par Genius en {round(temps_requete / 1000, 2)} s." await ctx.message.add_reaction(emoji = '✅') if premierembed == True: diff --git a/src/main.py b/src/main.py index cd2539e..fee6cdb 100644 --- a/src/main.py +++ b/src/main.py @@ -1,12 +1,11 @@ print("Chargement des extensions & librairie...", end = " ") import discord -import os +from os import environ from discord_slash import SlashCommand from discord.ext import commands from utils.reminder import Reminder -customPrefix = os.environ['PREFIX'] -customTimezone = os.environ['TIMEZONE'] +customPrefix = environ['PREFIX'] client = commands.Bot(command_prefix = customPrefix, case_insensitive = True, intents = discord.Intents.all()) slash = SlashCommand(client, sync_commands = True) @@ -53,4 +52,4 @@ async def on_message(message): await ctx.send(f">>> Coucou !\nMon préfix est `{prefix}` et ma commande d'aide est `{prefix}help`") print("Connexion à Discord...", end = " ") -client.run(os.environ['TOKEN_DISCORD']) +client.run(environ['TOKEN_DISCORD']) From 2ed8cffeaf6bc5667f44273e9c5770732feed2b3 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 00:02:03 +0200 Subject: [PATCH 150/286] absolute path for docker hub --- README.md | 2 +- docker-compose.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 56b69a1..97089a1 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ With a [docker-compose](https://github.com/Confrerie-du-Kassoulait/KassouBot/blo ``` docker run -d \ --name="KassouBot" \ - mylloon/kassoubot \ + index.docker.io/mylloon/kassoubot \ --TOKEN_DISCORD="yourTokenDiscord" \ --TOKEN_GENIUS="yourTokenGenius" \ --TOKEN_REDDIT_CLIENT_ID="yourRedditClientID" \ diff --git a/docker-compose.yml b/docker-compose.yml index 26d38b1..c3258d7 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,7 +1,7 @@ version: "2.1" services: kassoubot: - image: mylloon/kassoubot + image: index.docker.io/mylloon/kassoubot container_name: KassouBot environment: - TOKEN_DISCORD=yourTokenDiscord From 7cb1bcc22d7f30ba1e563b397237191bd1862b94 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 00:02:35 +0200 Subject: [PATCH 151/286] adding "." --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 97089a1..4979679 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and ## __Features__ - Everything is explained by doing the `help` command. -- Using SQLite for the database +- Using SQLite for the database. ## __Launching locally__ If you want to run it without Docker, I personally use [direnv](https://direnv.net/) to store variables and have them only in the working folder. From c5823d8fa7bf0e180a0f92a604aeb2e4dc4d85d5 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 00:22:01 +0200 Subject: [PATCH 152/286] =?UTF-8?q?moins=20de=20r=C3=A9p=C3=A9tition=20+?= =?UTF-8?q?=20affichage=20plus=20coh=C3=A9rent?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/time.py | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/src/utils/time.py b/src/utils/time.py index 10950f6..39f4c30 100644 --- a/src/utils/time.py +++ b/src/utils/time.py @@ -90,18 +90,13 @@ def ageLayout(tuple): if tuple[i] > 1 and i != 1: time[i] = time[i] + "s" message = "" - if tuple[5] > 0: # pour les secondes - affichage = [5] # on affiche que : seconde + if tuple[5] > 0: + affichage = [5] if tuple[4] > 0: - affichage = [4, 5] # on affiche : minute + seconde - if tuple[3] > 0: - affichage = [3, 4, 5] # on affiche : heure + minute + seconde - if tuple[2] > 0: - affichage = [2, 3, 4] # on affiche : jour + heure + minute - if tuple[1] > 0: - affichage = [1, 2, 3] # on affiche : mois + jour + heure - if tuple[0] > 0: - affichage = [0, 1, 3] # on affiche : an + mois + heure + affichage = [4, 5] + for i in [3, 0]: + if tuple[i] > 0: + affichage = [i, i + 1, i + 2] for i in affichage: message = message + f", {tuple[i]} {time[i]}" return message[2:] From 4d3e562710d020a876b652149c708cbda732ecfb Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 00:44:11 +0200 Subject: [PATCH 153/286] fix display and using right tz --- src/utils/time.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utils/time.py b/src/utils/time.py index 39f4c30..b53e8f5 100644 --- a/src/utils/time.py +++ b/src/utils/time.py @@ -73,7 +73,7 @@ def timedeltaToString(time): def getAge(date): """Recupère un age précisément à la seconde près""" - joursRestants = datetime.now() - date + joursRestants = intToDatetime(nowCustom()) - date years = joursRestants.total_seconds() / (365.242 * 24 * 3600) months = (years - int(years)) * 12 days = (months - int(months)) * (365.242 / 12) @@ -94,7 +94,7 @@ def ageLayout(tuple): affichage = [5] if tuple[4] > 0: affichage = [4, 5] - for i in [3, 0]: + for i in range(3, 0, -1): if tuple[i] > 0: affichage = [i, i + 1, i + 2] for i in affichage: From ea2c6d725afd084e9e0ad22de989106d1bf2de21 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 00:54:31 +0200 Subject: [PATCH 154/286] give datetime with right tz --- src/cogs/utils.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index a4e73e4..63bce56 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -6,7 +6,7 @@ from random import randint, shuffle from discord_slash import cog_ext from utils.reminder import Reminder from utils.core import map_list_among_us, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick -from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString, timestampScreen, getAge, ageLayout, nowCustom +from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString, timestampScreen, getAge, ageLayout, nowCustom, UTCDatetimeToCustomDatetime def setup(client): client.add_cog(Utils(client)) @@ -362,13 +362,13 @@ class Utils(commands.Cog): embed.add_field(name = "Compte créé le", value = timestampScreen(user[0].created_at)) - embed.add_field(name = "Âge du compte", value = ageLayout(getAge(user[0].created_at))) + embed.add_field(name = "Âge du compte", value = ageLayout(getAge(UTCDatetimeToCustomDatetime(user[0].created_at)))) embed.add_field(name = "Mention", value = user[0].mention) embed.add_field(name = "Serveur rejoint le", value = timestampScreen(user[0].joined_at)) - embed.add_field(name = "Est sur le serveur depuis", value = ageLayout(getAge(user[0].joined_at))) + embed.add_field(name = "Est sur le serveur depuis", value = ageLayout(getAge(UTCDatetimeToCustomDatetime(user[0].joined_at)))) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') return await ctx.send(embed = embed) From 5bdeb7a4d72af6b0a6d8eefcf80a70425112f1a8 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 01:28:39 +0200 Subject: [PATCH 155/286] fix tz in whois command --- src/cogs/utils.py | 6 +++--- src/utils/time.py | 9 +++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 63bce56..a4e73e4 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -6,7 +6,7 @@ from random import randint, shuffle from discord_slash import cog_ext from utils.reminder import Reminder from utils.core import map_list_among_us, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick -from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString, timestampScreen, getAge, ageLayout, nowCustom, UTCDatetimeToCustomDatetime +from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString, timestampScreen, getAge, ageLayout, nowCustom def setup(client): client.add_cog(Utils(client)) @@ -362,13 +362,13 @@ class Utils(commands.Cog): embed.add_field(name = "Compte créé le", value = timestampScreen(user[0].created_at)) - embed.add_field(name = "Âge du compte", value = ageLayout(getAge(UTCDatetimeToCustomDatetime(user[0].created_at)))) + embed.add_field(name = "Âge du compte", value = ageLayout(getAge(user[0].created_at))) embed.add_field(name = "Mention", value = user[0].mention) embed.add_field(name = "Serveur rejoint le", value = timestampScreen(user[0].joined_at)) - embed.add_field(name = "Est sur le serveur depuis", value = ageLayout(getAge(UTCDatetimeToCustomDatetime(user[0].joined_at)))) + embed.add_field(name = "Est sur le serveur depuis", value = ageLayout(getAge(user[0].joined_at))) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') return await ctx.send(embed = embed) diff --git a/src/utils/time.py b/src/utils/time.py index b53e8f5..64442a2 100644 --- a/src/utils/time.py +++ b/src/utils/time.py @@ -72,18 +72,19 @@ def timedeltaToString(time): return ''.join(age) def getAge(date): - """Recupère un age précisément à la seconde près""" - joursRestants = intToDatetime(nowCustom()) - date + """Recupère un âge précisément à la seconde près""" + heureAjouter = int(str(UTCDatetimeToCustomDatetime(intToDatetime(nowUTC()))).split('+')[1].split(':')[0]) + joursRestants = intToDatetime(nowUTC()) - date years = joursRestants.total_seconds() / (365.242 * 24 * 3600) months = (years - int(years)) * 12 days = (months - int(months)) * (365.242 / 12) hours = (days - int(days)) * 24 minutes = (hours - int(hours)) * 60 seconds = (minutes - int(minutes)) * 60 - return (int(years), int(months), int(days), int(hours), int(minutes), int(seconds)) + return (int(years), int(months), int(days), int(hours) + heureAjouter, int(minutes), int(seconds)) def ageLayout(tuple): - """avec la méthode 'getAge', permet de mettre en forme un âge⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" + """Avec la méthode `getAge`, permet de mettre en forme un âge⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" time = {} time[0], time[1], time[2], time[3], time[4], time[5] = "an", "mois", "jour", "heure", "minute", "seconde" for i in range(len(tuple)): From 049536d2b100a190aa571a1350b804861471c5fc Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 01:51:53 +0200 Subject: [PATCH 156/286] ultime fix tz --- src/utils/time.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/utils/time.py b/src/utils/time.py index 64442a2..4e75dda 100644 --- a/src/utils/time.py +++ b/src/utils/time.py @@ -73,9 +73,10 @@ def timedeltaToString(time): def getAge(date): """Recupère un âge précisément à la seconde près""" - heureAjouter = int(str(UTCDatetimeToCustomDatetime(intToDatetime(nowUTC()))).split('+')[1].split(':')[0]) - joursRestants = intToDatetime(nowUTC()) - date - years = joursRestants.total_seconds() / (365.242 * 24 * 3600) + now = intToDatetime(nowUTC()) + heureAjouter = int(str(UTCDatetimeToCustomDatetime(now)).split('+')[1].split(':')[0]) + joursRestants = now - date + years = joursRestants.total_seconds() / (365.242 * 24 * 60 * 60) months = (years - int(years)) * 12 days = (months - int(months)) * (365.242 / 12) hours = (days - int(days)) * 24 @@ -95,7 +96,7 @@ def ageLayout(tuple): affichage = [5] if tuple[4] > 0: affichage = [4, 5] - for i in range(3, 0, -1): + for i in range(3, -1, -1): if tuple[i] > 0: affichage = [i, i + 1, i + 2] for i in affichage: From adb79dd6543d5cbd7d6b00de374e262cc8fe9af5 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 02:14:44 +0200 Subject: [PATCH 157/286] using right tz for the 5th times >:( --- src/utils/time.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/utils/time.py b/src/utils/time.py index 4e75dda..2f68c5c 100644 --- a/src/utils/time.py +++ b/src/utils/time.py @@ -72,17 +72,15 @@ def timedeltaToString(time): return ''.join(age) def getAge(date): - """Recupère un âge précisément à la seconde près""" - now = intToDatetime(nowUTC()) - heureAjouter = int(str(UTCDatetimeToCustomDatetime(now)).split('+')[1].split(':')[0]) - joursRestants = now - date + """Décompose la différence entre une date et maintenant avec les bons timezone""" + joursRestants = UTCDatetimeToCustomDatetime(intToDatetime(nowUTC())) - UTCDatetimeToCustomDatetime(date) years = joursRestants.total_seconds() / (365.242 * 24 * 60 * 60) months = (years - int(years)) * 12 days = (months - int(months)) * (365.242 / 12) hours = (days - int(days)) * 24 minutes = (hours - int(hours)) * 60 seconds = (minutes - int(minutes)) * 60 - return (int(years), int(months), int(days), int(hours) + heureAjouter, int(minutes), int(seconds)) + return (int(years), int(months), int(days), int(hours), int(minutes), int(seconds)) def ageLayout(tuple): """Avec la méthode `getAge`, permet de mettre en forme un âge⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" From 19cb329436b1f41d4da06a38553267c5b0d612f4 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 10:44:56 +0200 Subject: [PATCH 158/286] correction ajout reaction en erreur --- src/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.py b/src/main.py index fee6cdb..5550251 100644 --- a/src/main.py +++ b/src/main.py @@ -35,7 +35,7 @@ async def on_ready(): async def on_command_error(ctx, error): if not ctx.invoked_with.startswith(customPrefix): print(error) - if "discord.errors.NotFound" in str(error) == False: + if ctx.message: await ctx.message.add_reaction(emoji = '❓') @client.event From 77c5ffbdcf4d298898e4c06351256854c158be22 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 10:45:38 +0200 Subject: [PATCH 159/286] gestion erreur --- src/cogs/utils.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index a4e73e4..c4f1d0e 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -498,6 +498,8 @@ class Utils(commands.Cog): time = time[:-1] mention = 1 seconds = stringTempsVersSecondes(time) + if type(seconds) != int: + return await ctx.send(seconds) if seconds == 0: embed.add_field(name="Attention", value="Mauvais format pour le temps, `d` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde\nMet un `@` accolée à l'unité pour mentionner les gens mentionner dans ton message.") elif seconds > 7776000: # 90 * 60 * 60 * 24 @@ -510,6 +512,10 @@ class Utils(commands.Cog): Reminder().ajoutReminder(messageID, ctx.channel.id, mention, reminder, now, now + seconds, ctx.author.id) return await ctx.send(f"Ok, je t'en parles dans {timedeltaToString(seconds)} avec 1m de retard maximum.") await ctx.send(embed = embed) + @_reminder.error + async def _reminder_error(self, ctx, error): + if 'time is a required argument that is missing.' in str(error): + await ctx.send("Tu n'as pas spécifié de durée.") @cog_ext.cog_slash(name="reminder", description = "Met en place un rappel.") async def __reminder(self, ctx, time, reminder = None): if reminder == None: From eb02269bbb812bb5ee4d28164ee2ecb2f332e3e0 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 10:46:03 +0200 Subject: [PATCH 160/286] =?UTF-8?q?d=C3=A9placement=20url=20de=20connexion?= =?UTF-8?q?=20de=20la=20base=20de=20donn=C3=A9e?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/db.py | 4 ++-- src/utils/reminder.py | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/utils/db.py b/src/utils/db.py index 94940af..32412e6 100644 --- a/src/utils/db.py +++ b/src/utils/db.py @@ -1,8 +1,8 @@ import sqlite3 class Database: - def __init__(self): - self.connexion = self.createConnection(r"src/db/bot.sqlite3") + def __init__(self, urlDatabase): + self.connexion = self.createConnection(urlDatabase) def createConnection(self, path): """Connexion à une base de donnée SQLite""" diff --git a/src/utils/reminder.py b/src/utils/reminder.py index e7c7a6c..dd03c15 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -1,6 +1,9 @@ from utils.db import Database class Reminder(Database): + def __init__(self): + super().__init__(r"src/db/bot.sqlite3") + def creationTable(self): """Créer la table qui stocker les reminders""" requete = """ From 2af04ba300c96620ea1846c88fe2e712844a3a77 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 11:18:09 +0200 Subject: [PATCH 161/286] force right type in requete --- src/utils/db.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/utils/db.py b/src/utils/db.py index 32412e6..275171b 100644 --- a/src/utils/db.py +++ b/src/utils/db.py @@ -1,7 +1,7 @@ import sqlite3 class Database: - def __init__(self, urlDatabase): + def __init__(self, urlDatabase: str): self.connexion = self.createConnection(urlDatabase) def createConnection(self, path): @@ -29,6 +29,8 @@ class Database: try: curseur = self.connexion.cursor() if valeurs: + if type(valeurs) not in [list, tuple]: + valeurs = [valeurs] curseur.execute(requete, valeurs) else: curseur.execute(requete) From 4d4574ae0deb5cc3bce6540bb76d6dacfad8b631 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 11:18:30 +0200 Subject: [PATCH 162/286] add guildID --- src/cogs/utils.py | 4 ++-- src/utils/reminder.py | 21 +++++++++++---------- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index c4f1d0e..02b2a5d 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -509,7 +509,7 @@ class Utils(commands.Cog): messageID = None if fromSlash != True: messageID = ctx.message.id - Reminder().ajoutReminder(messageID, ctx.channel.id, mention, reminder, now, now + seconds, ctx.author.id) + Reminder().ajoutReminder(messageID, ctx.channel.id, mention, reminder, now, now + seconds, ctx.author.id, ctx.guild.id) return await ctx.send(f"Ok, je t'en parles dans {timedeltaToString(seconds)} avec 1m de retard maximum.") await ctx.send(embed = embed) @_reminder.error @@ -566,7 +566,7 @@ class Utils(commands.Cog): else: utilisateur = ctx.author.id - reminders = Reminder().listeReminder(utilisateur) + reminders = Reminder().listeReminder(utilisateur, ctx.guild.id) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') embed = discord.Embed(description = f"**Rappel{'s' if len(reminders) > 1 else ''} de <@{utilisateur}>**", color = discord.Colour.random()) diff --git a/src/utils/reminder.py b/src/utils/reminder.py index dd03c15..0f8d9f4 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -15,21 +15,22 @@ class Reminder(Database): reminder_str TEXT, creation_int INTEGER, expiration_int INTEGER, - user_id INTEGER + user_id INTEGER, + guild_id INTEGER ); """ self.requete(requete) - def ajoutReminder(self, messageID = int, channelID = int, mention = int, reminder = str, creation = int, expiration = int, userID = int): + def ajoutReminder(self, messageID = int, channelID = int, mention = int, reminder = str, creation = int, expiration = int, userID = int, guildID = int): """Ajoute un reminder""" requete = """ INSERT INTO reminder ( - message_id, channel_id, mention_bool, reminder_str, creation_int, expiration_int, user_id + message_id, channel_id, mention_bool, reminder_str, creation_int, expiration_int, user_id, guild_id ) VALUES ( - ?, ?, ?, ?, ?, ?, ? + ?, ?, ?, ?, ?, ?, ?, ? ); """ - self.requete(requete, (messageID, channelID, mention, reminder, creation, expiration, userID)) + self.requete(requete, [messageID, channelID, mention, reminder, creation, expiration, userID, guildID]) def suppressionReminder(self, id = int): """Supprime un reminder""" @@ -37,15 +38,15 @@ class Reminder(Database): DELETE FROM reminder WHERE id = ? """ - self.requete(requete, [id]) + self.requete(requete, id) - def listeReminder(self, userID = int): + def listeReminder(self, userID = int, guildID = int): """Retourne la liste des reminders d'un utilisateur""" requete = """ SELECT reminder_str, creation_int, expiration_int FROM reminder - WHERE user_id = ? + WHERE user_id = ? AND guild_id = ? """ - return self.affichageResultat(self.requete(requete, [userID])) + return self.affichageResultat(self.requete(requete, [userID, guildID])) def recuperationExpiration(self, time = int): """Récupère les reminders qui sont arrivés à expiration et ses infos""" @@ -53,4 +54,4 @@ class Reminder(Database): SELECT channel_id, mention_bool, reminder_str, creation_int, user_id, id, message_id FROM reminder WHERE expiration_int < ? """ - return self.affichageResultat(self.requete(requete, [time])) + return self.affichageResultat(self.requete(requete, time)) From 9677f3534d0a34f5ba1367f38d720d1bb0f42c48 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 20:08:25 +0200 Subject: [PATCH 163/286] ajout aliase dispo dans le message d'aide --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 02b2a5d..2754808 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -479,7 +479,7 @@ class Utils(commands.Cog): @commands.command(name='reminder', aliases=["remind", "remindme", "rappel"]) async def _reminder(self, ctx, time, *reminder): - """Met en place un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminder/remind/remindme [@] [message] """ + """Met en place un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminder/remind/remindme/rappel [@] [message] """ fromSlash = False if len(reminder) > 0: if reminder[-1] == True: From a758d1c18ccf71c673748a283e00b08befc4287f Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 22:15:09 +0200 Subject: [PATCH 164/286] creationtable reminder in ready() --- src/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.py b/src/main.py index 5550251..8bfe4e2 100644 --- a/src/main.py +++ b/src/main.py @@ -19,7 +19,6 @@ client.load_extension("cogs.fun") client.load_extension("cogs.school") client.load_extension("cogs.citation") client.load_extension("cogs.confreriedukassoulait") # you can remove this cogs, only for my private guild -Reminder().creationTable() print("Terminé !") @client.event @@ -29,6 +28,7 @@ async def on_connect(): @client.event async def on_ready(): await client.change_presence(status = discord.Status.online, activity = discord.Activity(name = f"{customPrefix}help", type = discord.ActivityType.playing)) + Reminder().creationTable() print("Bot prêt.") @client.event From 064b9b8f4f180c9ae8211a3ae5487502672800a1 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 22:17:59 +0200 Subject: [PATCH 165/286] ignore file instead of folder --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 18e5665..0196d05 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,4 @@ update/ __pycache__/ .envrc -src/db/* +*.sqlite3 From f7ad046304d64eda48f540c993780981eb1c17a3 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 22:19:11 +0200 Subject: [PATCH 166/286] adding temp file --- src/db/temp | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 src/db/temp diff --git a/src/db/temp b/src/db/temp new file mode 100644 index 0000000..e69de29 From 4899904e985c51cefcf085e56ceb594ee1c9997e Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 22:20:24 +0200 Subject: [PATCH 167/286] removing temp file --- src/db/temp | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 src/db/temp diff --git a/src/db/temp b/src/db/temp deleted file mode 100644 index e69de29..0000000 From 137c646cb54d6e1ec0f746c20fd6ed818f350c08 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 8 Jun 2021 22:23:11 +0200 Subject: [PATCH 168/286] adding gitkeep --- src/db/.gitkeep | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 src/db/.gitkeep diff --git a/src/db/.gitkeep b/src/db/.gitkeep new file mode 100644 index 0000000..e69de29 From 3e1336b8b884dacc932a1fdc4ec12d8e5cc3d603 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 10 Jun 2021 10:26:11 +0200 Subject: [PATCH 169/286] remove spaces at end of string --- src/utils/time.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/time.py b/src/utils/time.py index 2f68c5c..15ba954 100644 --- a/src/utils/time.py +++ b/src/utils/time.py @@ -69,7 +69,7 @@ def timedeltaToString(time): age[1] = f"{age[1]}h " if a[1] == 1 else '' age[2] = f"{age[2]}m " if a[2] == 1 else '' age[3] = f"{age[3]}s" if a[3] == 1 else '' - return ''.join(age) + return ''.join(age).strip(' ') def getAge(date): """Décompose la différence entre une date et maintenant avec les bons timezone""" From 37a17b8095b9ea269988cd8a8316cbf7e6430c6b Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 10 Jun 2021 11:15:49 +0200 Subject: [PATCH 170/286] boucle for pour le chargement des cogs --- src/main.py | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/src/main.py b/src/main.py index 8bfe4e2..05c3edc 100644 --- a/src/main.py +++ b/src/main.py @@ -1,7 +1,7 @@ print("Chargement des extensions & librairie...", end = " ") import discord -from os import environ +from os import environ, listdir from discord_slash import SlashCommand from discord.ext import commands from utils.reminder import Reminder @@ -10,15 +10,9 @@ customPrefix = environ['PREFIX'] client = commands.Bot(command_prefix = customPrefix, case_insensitive = True, intents = discord.Intents.all()) slash = SlashCommand(client, sync_commands = True) -client.load_extension("cogs.help") -client.load_extension("cogs.utils") -client.load_extension("cogs.internet") -client.load_extension("cogs.music") -client.load_extension("cogs.games") -client.load_extension("cogs.fun") -client.load_extension("cogs.school") -client.load_extension("cogs.citation") -client.load_extension("cogs.confreriedukassoulait") # you can remove this cogs, only for my private guild +for file in listdir("src/cogs"): + if file.endswith(".py") and file.startswith("-") == False: + client.load_extension(f"cogs.{file[:-3]}") print("Terminé !") @client.event From f6d911b13735fa20a2865ef7b73b889c7f9b5abe Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 11 Jun 2021 11:09:20 +0200 Subject: [PATCH 171/286] update path --- src/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.py b/src/main.py index 05c3edc..1ef1d68 100644 --- a/src/main.py +++ b/src/main.py @@ -10,7 +10,7 @@ customPrefix = environ['PREFIX'] client = commands.Bot(command_prefix = customPrefix, case_insensitive = True, intents = discord.Intents.all()) slash = SlashCommand(client, sync_commands = True) -for file in listdir("src/cogs"): +for file in listdir("cogs"): if file.endswith(".py") and file.startswith("-") == False: client.load_extension(f"cogs.{file[:-3]}") print("Terminé !") From 3dd361be25e8e9cd1e2d54b8a9d5cff8a2228c10 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 11 Jun 2021 11:15:26 +0200 Subject: [PATCH 172/286] update path --- README.md | 2 +- src/utils/reminder.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4979679..38a4ddf 100644 --- a/README.md +++ b/README.md @@ -42,4 +42,4 @@ To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and ## __Launching locally__ If you want to run it without Docker, I personally use [direnv](https://direnv.net/) to store variables and have them only in the working folder. -Simply run python3 `src/main.py` to launch the bot in the repo folder. +Simply run `python3 main.py` in `src` folder to launch the bot in the repo folder. diff --git a/src/utils/reminder.py b/src/utils/reminder.py index 0f8d9f4..e6beeb7 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -2,7 +2,7 @@ from utils.db import Database class Reminder(Database): def __init__(self): - super().__init__(r"src/db/bot.sqlite3") + super().__init__(r"db/bot.sqlite3") def creationTable(self): """Créer la table qui stocker les reminders""" From be5df2cfdbb4c9fb14b9630790f2bd1c094cc883 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 13 Jun 2021 22:41:05 +0200 Subject: [PATCH 173/286] update path db --- README.md | 2 +- docker-compose.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 38a4ddf..cff5ea4 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ docker run -d \ --TOKEN_REDDIT_USER_AGENT="yourRedditUserAgent" \ --TIMEZONE="yourTimezone" \ --PREFIX="yourPrefix" \ - -v /here/your/path/:/src/db/ + -v /here/your/path/:/db ``` To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and here are the instructions: ![instructions](https://i.imgur.com/tEzYKDA.png) diff --git a/docker-compose.yml b/docker-compose.yml index c3258d7..fc49407 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -12,5 +12,5 @@ services: - TIMEZONE=yourTimezone # More info here: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones - PREFIX=yourPrefix volumes: - - /here/your/path/:/src/db/ + - /here/your/path/:/db restart: unless-stopped From 531dad68c2918de5f7ca8838f0d6a2fe96f07c15 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 13 Jun 2021 23:38:06 +0200 Subject: [PATCH 174/286] =?UTF-8?q?gestion=20erreur=20utilisateur=20non=20?= =?UTF-8?q?renseign=C3=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/utils.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 2754808..061bc89 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -562,7 +562,10 @@ class Utils(commands.Cog): fromSlash = utilisateur[-1] utilisateur = utilisateur[:-1] if len(utilisateur) > 0: - utilisateur = int(getMentionInString(utilisateur[0])[0][3:][:-1]) + try: + utilisateur = int(getMentionInString(utilisateur[0])[0][3:][:-1]) + except: + return await ctx.send("L'utilisateur renseigné n'a pas été trouvé.") else: utilisateur = ctx.author.id From 0c88a842c963c31e2d9f487daeb7f560a07b515c Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 14 Jun 2021 00:37:55 +0200 Subject: [PATCH 175/286] update database, recreate yours after this! --- src/utils/reminder.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/utils/reminder.py b/src/utils/reminder.py index e6beeb7..082ebb8 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -11,7 +11,7 @@ class Reminder(Database): id INTEGER PRIMARY KEY, message_id INTEGER, channel_id INTEGER, - mention_bool INTEGER, + extrarg_id INTEGER, reminder_str TEXT, creation_int INTEGER, expiration_int INTEGER, @@ -25,7 +25,7 @@ class Reminder(Database): """Ajoute un reminder""" requete = """ INSERT INTO reminder ( - message_id, channel_id, mention_bool, reminder_str, creation_int, expiration_int, user_id, guild_id + message_id, channel_id, extrarg_id, reminder_str, creation_int, expiration_int, user_id, guild_id ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ? ); @@ -43,7 +43,7 @@ class Reminder(Database): def listeReminder(self, userID = int, guildID = int): """Retourne la liste des reminders d'un utilisateur""" requete = """ - SELECT reminder_str, creation_int, expiration_int FROM reminder + SELECT reminder_str, creation_int, expiration_int, id FROM reminder WHERE user_id = ? AND guild_id = ? """ return self.affichageResultat(self.requete(requete, [userID, guildID])) @@ -51,7 +51,7 @@ class Reminder(Database): def recuperationExpiration(self, time = int): """Récupère les reminders qui sont arrivés à expiration et ses infos""" requete = """ - SELECT channel_id, mention_bool, reminder_str, creation_int, user_id, id, message_id FROM reminder + SELECT channel_id, extrarg_id, reminder_str, creation_int, user_id, id, message_id FROM reminder WHERE expiration_int < ? """ return self.affichageResultat(self.requete(requete, time)) From 77bcbb3f70c69f93e1f0136921966d7ea2a430b9 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 14 Jun 2021 00:41:05 +0200 Subject: [PATCH 176/286] affichage de l'id du reminder --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 061bc89..ba7dcf6 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -584,7 +584,7 @@ class Utils(commands.Cog): expiration = f"Expire dans {timedeltaToString(expiration)} +1m de retard max." else: expiration = f"A déjà expiré." - embed.add_field(value = texte, name = f"Fais le {timestampScreen(intToDatetime(reminder[1]))}\n{expiration}", inline = False) + embed.add_field(value = texte, name = f"#{reminder[3]} • Fais le {timestampScreen(intToDatetime(reminder[1]))}\n{expiration}", inline = False) else: embed.add_field(name = "\u200b", value = "Vous n'avez aucun rappel en attente !") embed.set_footer(text = "Les rappels qui ont déjà expirés vont apparaître dans quelques instants.") From 8e0f0670627a4e5e4fb47dd9465f75c5361b8a5c Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 14 Jun 2021 00:59:32 +0200 Subject: [PATCH 177/286] ajout du reminderdelete --- src/cogs/utils.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index ba7dcf6..22902dc 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -595,3 +595,33 @@ class Utils(commands.Cog): return await self._reminderlist(ctx, True) else: return await self._reminderlist(ctx, user, True) + + @commands.command(name='reminderdelete', aliases=["reminddelete", "rd"]) + async def _reminderdelete(self, ctx, *id): + """Suppprime un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminderdelete/rd """ + fromSlash = False + if len(id) > 0: + if id[-1] == True: + fromSlash = id[-1] + id = id[:-1] + if len(id) > 0: + try: + id = int(id[0]) + except: + return await ctx.send("L'ID renseigné n'est pas valide.") + else: + return await ctx.send("Veuillez renseigner un ID.") + + verification = Reminder().appartenanceReminder(ctx.author.id, id) + if verification: + Reminder().suppressionReminder(id) + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + return await ctx.send(f"Reminder **#{id}** supprimé !") + else: + if fromSlash != True: + await ctx.message.add_reaction(emoji = '❌') + return await ctx.send("Rappel non trouvé ou qui ne vous appartiens pas.") + @cog_ext.cog_slash(name="reminderdelete", description = "Suppprime un rappel.") + async def __reminderdelete(self, ctx, id): + return await self._reminderdelete(ctx, id, True) From 7d06794d93bb7011bb6e1192b53ec9edc102be24 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 14 Jun 2021 01:00:10 +0200 Subject: [PATCH 178/286] =?UTF-8?q?ajout=20m=C3=A9thode=20pour=20v=C3=A9ri?= =?UTF-8?q?fier=20l'appartenance=20d'un=20rappel=20=C3=A0=20un=20user?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/reminder.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/utils/reminder.py b/src/utils/reminder.py index 082ebb8..487e406 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -5,7 +5,7 @@ class Reminder(Database): super().__init__(r"db/bot.sqlite3") def creationTable(self): - """Créer la table qui stocker les reminders""" + """Créer la table qui stocker les reminders.""" requete = """ CREATE TABLE IF NOT EXISTS reminder ( id INTEGER PRIMARY KEY, @@ -22,7 +22,7 @@ class Reminder(Database): self.requete(requete) def ajoutReminder(self, messageID = int, channelID = int, mention = int, reminder = str, creation = int, expiration = int, userID = int, guildID = int): - """Ajoute un reminder""" + """Ajoute un reminder.""" requete = """ INSERT INTO reminder ( message_id, channel_id, extrarg_id, reminder_str, creation_int, expiration_int, user_id, guild_id @@ -33,7 +33,7 @@ class Reminder(Database): self.requete(requete, [messageID, channelID, mention, reminder, creation, expiration, userID, guildID]) def suppressionReminder(self, id = int): - """Supprime un reminder""" + """Supprime un reminder.""" requete = """ DELETE FROM reminder WHERE id = ? @@ -41,7 +41,7 @@ class Reminder(Database): self.requete(requete, id) def listeReminder(self, userID = int, guildID = int): - """Retourne la liste des reminders d'un utilisateur""" + """Retourne la liste des reminders d'un utilisateur.""" requete = """ SELECT reminder_str, creation_int, expiration_int, id FROM reminder WHERE user_id = ? AND guild_id = ? @@ -49,9 +49,21 @@ class Reminder(Database): return self.affichageResultat(self.requete(requete, [userID, guildID])) def recuperationExpiration(self, time = int): - """Récupère les reminders qui sont arrivés à expiration et ses infos""" + """Récupère les reminders qui sont arrivés à expiration et ses infos.""" requete = """ SELECT channel_id, extrarg_id, reminder_str, creation_int, user_id, id, message_id FROM reminder WHERE expiration_int < ? """ return self.affichageResultat(self.requete(requete, time)) + + def appartenanceReminder(self, user = int, id = int): + """Vérifie qu'un rappel appartiens à un utilisateur. Renvois False si le rappel n'existe pas.""" + requete = """ + SELECT user_id, id, message_id FROM reminder + WHERE id = ? AND user_id = ? + """ + resultat = self.affichageResultat(self.requete(requete, [id, user])) + if len(resultat) > 0: + return True + else: + return False From 51c545535aa935a6ce87ef3335820c7a1c4571fa Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 14 Jun 2021 01:52:09 +0200 Subject: [PATCH 179/286] envoie message en DM quand salon indisponible reminder --- src/cogs/utils.py | 37 ++++++++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 22902dc..bf4126c 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -499,6 +499,8 @@ class Utils(commands.Cog): mention = 1 seconds = stringTempsVersSecondes(time) if type(seconds) != int: + if fromSlash != True: + await ctx.message.add_reaction(emoji = '❓') return await ctx.send(seconds) if seconds == 0: embed.add_field(name="Attention", value="Mauvais format pour le temps, `d` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde\nMet un `@` accolée à l'unité pour mentionner les gens mentionner dans ton message.") @@ -527,27 +529,40 @@ class Utils(commands.Cog): async def _reminderLoop(self): expiration = Reminder().recuperationExpiration(int(nowUTC())) for expired in expiration: - message = f"<@{expired[4]}>" reminder = expired[2] - if expired[1] == 1: - mentionList = getMentionInString(reminder) - for i in mentionList: - message += f" {i}" + userID = expired[4] channel = self.client.get_channel(expired[0]) - sourceMessage = expired[6] - if sourceMessage != None: - sourceMessage = await channel.fetch_message(sourceMessage) - await sourceMessage.add_reaction(emoji = '✅') finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = intToDatetime(expired[3]), color = discord.Colour.random()) + if channel == None: + user = self.client.get_user(userID) + if user == None: # si l'utilisateur n'est pas trouvé + return Reminder().suppressionReminder(expired[5]) + channel = await user.create_dm() + userID = None + finalEmbed.add_field(name = "Info", value = "Message envoyé en DM car le salon n'est plus disponible.") + else: + sourceMessage = expired[6] + if sourceMessage != None: + sourceMessage = await channel.fetch_message(sourceMessage) + await sourceMessage.add_reaction(emoji = '✅') finalEmbed.set_footer(text=f"Message d'il y a {timedeltaToString(int(nowUTC()) - expired[3])}") - links = "" findedURLs = getURLsInString(reminder) for i in range(0, len(findedURLs)): links += f"[Lien {i + 1}]({findedURLs[i]}) · " if len(findedURLs) > 0: finalEmbed.add_field(name = f"Lien{'s' if len(findedURLs) > 1 else ''}", value = links[:-3]) - await channel.send(message, embed = finalEmbed) + message = "" + if userID != None: + message = f"<@{userID}>" + if expired[1] == 1: + mentionList = getMentionInString(reminder) + for i in mentionList: + message += f" {i}" + try: + await channel.send(message, embed = finalEmbed) + except: # les DM sont fermés + return Reminder().suppressionReminder(expired[5]) Reminder().suppressionReminder(expired[5]) @_reminderLoop.before_loop async def __avant_reminderLoop(self): From 63d16746f0dfe9cc03c7aeade6cdf13ffe279029 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 14 Jun 2021 02:09:46 +0200 Subject: [PATCH 180/286] reminder help --- src/cogs/utils.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index bf4126c..a6a699f 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -494,14 +494,17 @@ class Utils(commands.Cog): mention = 0 if not reminder: reminder = "Notification" - if time.lower().endswith("@"): - time = time[:-1] - mention = 1 - seconds = stringTempsVersSecondes(time) - if type(seconds) != int: - if fromSlash != True: - await ctx.message.add_reaction(emoji = '❓') - return await ctx.send(seconds) + if time == "help": + seconds = 0 + else: + if time.lower().endswith("@"): + time = time[:-1] + mention = 1 + seconds = stringTempsVersSecondes(time) + if type(seconds) != int: + if fromSlash != True: + await ctx.message.add_reaction(emoji = '❓') + return await ctx.send(seconds) if seconds == 0: embed.add_field(name="Attention", value="Mauvais format pour le temps, `d` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde\nMet un `@` accolée à l'unité pour mentionner les gens mentionner dans ton message.") elif seconds > 7776000: # 90 * 60 * 60 * 24 From 60b4bcb0dc500ff8485d204fad9164151ecdea43 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 14 Jun 2021 02:15:04 +0200 Subject: [PATCH 181/286] update help message --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index a6a699f..e0b3118 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -506,7 +506,7 @@ class Utils(commands.Cog): await ctx.message.add_reaction(emoji = '❓') return await ctx.send(seconds) if seconds == 0: - embed.add_field(name="Attention", value="Mauvais format pour le temps, `d` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde\nMet un `@` accolée à l'unité pour mentionner les gens mentionner dans ton message.") + embed.add_field(name="Attention", value="Format pour le temps : `d` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde\nMet un `@` accolée à l'unité pour mentionner les gens mentionner dans ton message.") elif seconds > 7776000: # 90 * 60 * 60 * 24 embed.add_field(name="Attention", value="Tu as spécifié une durée trop longue, la durée maximum étant de 90 jours.") else: From e2c1971dfdd7ccbafc1e11b5bcd187347081e596 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 14 Jun 2021 21:52:25 +0200 Subject: [PATCH 182/286] bot deaf in voicechannel --- src/cogs/music.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cogs/music.py b/src/cogs/music.py index fc92fc7..2320c8d 100644 --- a/src/cogs/music.py +++ b/src/cogs/music.py @@ -315,6 +315,7 @@ class Music(commands.Cog): return ctx.voice_state.voice = await destination.connect() + await ctx.guild.change_voice_state(channel = destination, self_mute = False, self_deaf = True) @commands.command(name='stop', aliases=['disconnect', 'dc']) async def _leave(self, ctx: commands.Context): From 5ca4f3ed8c59b62b6dc455bc158e3871b368f491 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 14 Jun 2021 23:14:31 +0200 Subject: [PATCH 183/286] ajout exeption dans tiledeltatostring --- src/utils/time.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/time.py b/src/utils/time.py index 15ba954..ced905a 100644 --- a/src/utils/time.py +++ b/src/utils/time.py @@ -56,7 +56,7 @@ def timestampScreen(timestamp): def timedeltaToString(time): """Différence entre une heure en seconde et maintenant""" - age = str(timedelta(seconds = time)).replace('days, ', 'jours, :').split(':') + age = str(timedelta(seconds = time)).replace('days, ', 'jours, :').replace('day, ', 'jour, :').split(':') if len(age) == 4: a = [1, 1, 1, 1] # a pour affichage if len(age) == 3: From 2d21d9276ba020e45bb1fb006e82eb327cedba9b Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 15 Jun 2021 09:10:34 +0200 Subject: [PATCH 184/286] better replace --- src/utils/time.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/time.py b/src/utils/time.py index ced905a..bc99ef6 100644 --- a/src/utils/time.py +++ b/src/utils/time.py @@ -56,7 +56,7 @@ def timestampScreen(timestamp): def timedeltaToString(time): """Différence entre une heure en seconde et maintenant""" - age = str(timedelta(seconds = time)).replace('days, ', 'jours, :').replace('day, ', 'jour, :').split(':') + age = str(timedelta(seconds = time)).replace('day', 'jour').replace(', ', ', :').split(':') if len(age) == 4: a = [1, 1, 1, 1] # a pour affichage if len(age) == 3: From d473651a6c5759ed4af3a3feb1808c729e31d511 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 15 Jun 2021 09:12:34 +0200 Subject: [PATCH 185/286] replace mention by extrarg --- src/cogs/utils.py | 6 +++--- src/utils/reminder.py | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index e0b3118..92b4b85 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -491,7 +491,7 @@ class Utils(commands.Cog): reminder = None embed = discord.Embed(color = 0xC41B1B) - mention = 0 + extrarg = 0 if not reminder: reminder = "Notification" if time == "help": @@ -499,7 +499,7 @@ class Utils(commands.Cog): else: if time.lower().endswith("@"): time = time[:-1] - mention = 1 + extrarg = 1 seconds = stringTempsVersSecondes(time) if type(seconds) != int: if fromSlash != True: @@ -514,7 +514,7 @@ class Utils(commands.Cog): messageID = None if fromSlash != True: messageID = ctx.message.id - Reminder().ajoutReminder(messageID, ctx.channel.id, mention, reminder, now, now + seconds, ctx.author.id, ctx.guild.id) + Reminder().ajoutReminder(messageID, ctx.channel.id, extrarg, reminder, now, now + seconds, ctx.author.id, ctx.guild.id) return await ctx.send(f"Ok, je t'en parles dans {timedeltaToString(seconds)} avec 1m de retard maximum.") await ctx.send(embed = embed) @_reminder.error diff --git a/src/utils/reminder.py b/src/utils/reminder.py index 487e406..bf0ce16 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -21,7 +21,7 @@ class Reminder(Database): """ self.requete(requete) - def ajoutReminder(self, messageID = int, channelID = int, mention = int, reminder = str, creation = int, expiration = int, userID = int, guildID = int): + def ajoutReminder(self, messageID = int, channelID = int, extrarg = int, reminder = str, creation = int, expiration = int, userID = int, guildID = int): """Ajoute un reminder.""" requete = """ INSERT INTO reminder ( @@ -30,7 +30,7 @@ class Reminder(Database): ?, ?, ?, ?, ?, ?, ?, ? ); """ - self.requete(requete, [messageID, channelID, mention, reminder, creation, expiration, userID, guildID]) + self.requete(requete, [messageID, channelID, extrarg, reminder, creation, expiration, userID, guildID]) def suppressionReminder(self, id = int): """Supprime un reminder.""" From c92bfb93d66006d500ec61ce6baabfcf87a4c286 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 15 Jun 2021 09:22:34 +0200 Subject: [PATCH 186/286] =?UTF-8?q?ajout=20commentaires=20+=20fix=20bug=20?= =?UTF-8?q?quand=20message=20supprim=C3=A9=20+=20preparation=20ajout=20nou?= =?UTF-8?q?velle=20feature?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/utils.py | 47 +++++++++++++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 18 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 92b4b85..b736750 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -500,13 +500,16 @@ class Utils(commands.Cog): if time.lower().endswith("@"): time = time[:-1] extrarg = 1 + if time.lower().endswith("P"): + time = time[:-1] + extrarg = 2 seconds = stringTempsVersSecondes(time) if type(seconds) != int: if fromSlash != True: await ctx.message.add_reaction(emoji = '❓') return await ctx.send(seconds) if seconds == 0: - embed.add_field(name="Attention", value="Format pour le temps : `d` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde\nMet un `@` accolée à l'unité pour mentionner les gens mentionner dans ton message.") + embed.add_field(name="Attention", value="Format pour le temps : `d` ou `j` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (légères variances acceptés aussi).\nMet un `@` accolée aux temps pour mentionner les gens mentionner dans ton message.\nMet un `P` accolée au temps pour que le bot te DM au lieu de t'envoyer un message dans ce salon.") elif seconds > 7776000: # 90 * 60 * 60 * 24 embed.add_field(name="Attention", value="Tu as spécifié une durée trop longue, la durée maximum étant de 90 jours.") else: @@ -530,43 +533,51 @@ class Utils(commands.Cog): @tasks.loop(minutes = 1) async def _reminderLoop(self): - expiration = Reminder().recuperationExpiration(int(nowUTC())) - for expired in expiration: - reminder = expired[2] - userID = expired[4] - channel = self.client.get_channel(expired[0]) + expiration = Reminder().recuperationExpiration(int(nowUTC())) # on récupères les éléments expirés + for expired in expiration: # on regarde tout les éléments expirés + reminder = expired[2] # message + userID = expired[4] # personne qui a fait le rappel + channel = self.client.get_channel(expired[0]) # salon du message finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = intToDatetime(expired[3]), color = discord.Colour.random()) - if channel == None: + if channel == None: # si le salon n'existe plus user = self.client.get_user(userID) if user == None: # si l'utilisateur n'est pas trouvé - return Reminder().suppressionReminder(expired[5]) - channel = await user.create_dm() + return Reminder().suppressionReminder(expired[5]) # suppression du rappel + channel = await user.create_dm() # envoie en DM userID = None finalEmbed.add_field(name = "Info", value = "Message envoyé en DM car le salon n'est plus disponible.") else: sourceMessage = expired[6] - if sourceMessage != None: - sourceMessage = await channel.fetch_message(sourceMessage) - await sourceMessage.add_reaction(emoji = '✅') + if sourceMessage != None: # vérification message avec slash command + try: + sourceMessage = await channel.fetch_message(sourceMessage) # récupération message + except: + sourceMessage = None # message a été supprimé + if sourceMessage != None: + await sourceMessage.add_reaction(emoji = '✅') # ajout réaction finalEmbed.set_footer(text=f"Message d'il y a {timedeltaToString(int(nowUTC()) - expired[3])}") links = "" findedURLs = getURLsInString(reminder) - for i in range(0, len(findedURLs)): + for i in range(0, len(findedURLs)): # ajout de field "lien" pour pouvoir cliquer sur les liens facilement links += f"[Lien {i + 1}]({findedURLs[i]}) · " if len(findedURLs) > 0: finalEmbed.add_field(name = f"Lien{'s' if len(findedURLs) > 1 else ''}", value = links[:-3]) message = "" - if userID != None: + if userID != None: # metion de l'utilisateur si le message n'est pas en DM message = f"<@{userID}>" - if expired[1] == 1: + if expired[1] == 1: # s'il faut mentionner les personnes dans le message mentionList = getMentionInString(reminder) for i in mentionList: message += f" {i}" + elif expired[1] == 2: # s'il faut envoyer en DM le message + mentionList = getMentionInString(reminder) + for i in mentionList: + message += f" {i}x" try: - await channel.send(message, embed = finalEmbed) + await channel.send(message, embed = finalEmbed) # envoie du rappel except: # les DM sont fermés - return Reminder().suppressionReminder(expired[5]) - Reminder().suppressionReminder(expired[5]) + pass + return Reminder().suppressionReminder(expired[5]) # suppression du rappel @_reminderLoop.before_loop async def __avant_reminderLoop(self): await self.client.wait_until_ready() From 3e7220d7ae4909b026c41b0f7d1bba2f9ba6c875 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 15 Jun 2021 09:27:08 +0200 Subject: [PATCH 187/286] ajout commentaires --- src/cogs/utils.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index b736750..34a9aab 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -544,11 +544,12 @@ class Utils(commands.Cog): if user == None: # si l'utilisateur n'est pas trouvé return Reminder().suppressionReminder(expired[5]) # suppression du rappel channel = await user.create_dm() # envoie en DM - userID = None + userID = None # plus de mention + sourceMessage = None # plus de message source finalEmbed.add_field(name = "Info", value = "Message envoyé en DM car le salon n'est plus disponible.") else: sourceMessage = expired[6] - if sourceMessage != None: # vérification message avec slash command + if sourceMessage != None: # vérification message avec slash command et que si c'est pas en DM try: sourceMessage = await channel.fetch_message(sourceMessage) # récupération message except: From 20acf896dfecb858ca4998e9a52fe9acb2cd2faa Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 15 Jun 2021 13:06:47 +0200 Subject: [PATCH 188/286] fix error when there is not ! in mention --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 34a9aab..adb1631 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -593,7 +593,7 @@ class Utils(commands.Cog): utilisateur = utilisateur[:-1] if len(utilisateur) > 0: try: - utilisateur = int(getMentionInString(utilisateur[0])[0][3:][:-1]) + utilisateur = int(getMentionInString(utilisateur[0])[0][2:][:-1].replace("!", "")) except: return await ctx.send("L'utilisateur renseigné n'a pas été trouvé.") else: From 8c0b1f8ec23577ce9747322f6e52b3fd445abb71 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 15 Jun 2021 20:25:01 +0200 Subject: [PATCH 189/286] suppression limite 90j pour reminder --- src/cogs/utils.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index adb1631..edc43ad 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -509,9 +509,11 @@ class Utils(commands.Cog): await ctx.message.add_reaction(emoji = '❓') return await ctx.send(seconds) if seconds == 0: - embed.add_field(name="Attention", value="Format pour le temps : `d` ou `j` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (légères variances acceptés aussi).\nMet un `@` accolée aux temps pour mentionner les gens mentionner dans ton message.\nMet un `P` accolée au temps pour que le bot te DM au lieu de t'envoyer un message dans ce salon.") - elif seconds > 7776000: # 90 * 60 * 60 * 24 - embed.add_field(name="Attention", value="Tu as spécifié une durée trop longue, la durée maximum étant de 90 jours.") + embed.add_field(name="Attention", value= + "Format pour le temps : `d` ou `j` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (légères variances acceptés aussi). \ + \nMet un `@` accolée aux temps pour mentionner les gens mentionner dans ton message. \ + \nMet un `P` accolée au temps pour que le bot te DM au lieu de t'envoyer un message dans ce salon." + ) else: now = int(nowUTC()) messageID = None From 9b77418728c12f585eb35b3bc577f84eb098ac93 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 15 Jun 2021 20:37:58 +0200 Subject: [PATCH 190/286] ajout reminder dans les DM --- src/cogs/utils.py | 23 ++++++++++++++--------- src/utils/reminder.py | 2 +- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index edc43ad..51e6e95 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -492,17 +492,19 @@ class Utils(commands.Cog): embed = discord.Embed(color = 0xC41B1B) extrarg = 0 + guildID = ctx.guild.id # can be set to 0 if its a DM message, so it can be see from anywhere if not reminder: reminder = "Notification" if time == "help": seconds = 0 else: - if time.lower().endswith("@"): + if time.endswith("@"): time = time[:-1] extrarg = 1 - if time.lower().endswith("P"): + if time.lower().endswith("p") or time.lower().endswith("d"): time = time[:-1] extrarg = 2 + guildID = 0 seconds = stringTempsVersSecondes(time) if type(seconds) != int: if fromSlash != True: @@ -512,14 +514,14 @@ class Utils(commands.Cog): embed.add_field(name="Attention", value= "Format pour le temps : `d` ou `j` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (légères variances acceptés aussi). \ \nMet un `@` accolée aux temps pour mentionner les gens mentionner dans ton message. \ - \nMet un `P` accolée au temps pour que le bot te DM au lieu de t'envoyer un message dans ce salon." + \nMet un `P` ou `D` accolée au temps pour que le bot te DM au lieu de t'envoyer un message dans ce salon." ) else: now = int(nowUTC()) messageID = None if fromSlash != True: messageID = ctx.message.id - Reminder().ajoutReminder(messageID, ctx.channel.id, extrarg, reminder, now, now + seconds, ctx.author.id, ctx.guild.id) + Reminder().ajoutReminder(messageID, ctx.channel.id, extrarg, reminder, now, now + seconds, ctx.author.id, guildID) return await ctx.send(f"Ok, je t'en parles dans {timedeltaToString(seconds)} avec 1m de retard maximum.") await ctx.send(embed = embed) @_reminder.error @@ -541,7 +543,14 @@ class Utils(commands.Cog): userID = expired[4] # personne qui a fait le rappel channel = self.client.get_channel(expired[0]) # salon du message finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = intToDatetime(expired[3]), color = discord.Colour.random()) - if channel == None: # si le salon n'existe plus + if expired[1] == 2: # s'il faut envoyer en DM le message + user = self.client.get_user(userID) + if user == None: # si l'utilisateur n'est pas trouvé + return Reminder().suppressionReminder(expired[5]) # suppression du rappel + channel = await user.create_dm() # envoie en DM + userID = None # plus de mention + sourceMessage = None # plus de message source + elif channel == None: # si le salon n'existe plus user = self.client.get_user(userID) if user == None: # si l'utilisateur n'est pas trouvé return Reminder().suppressionReminder(expired[5]) # suppression du rappel @@ -572,10 +581,6 @@ class Utils(commands.Cog): mentionList = getMentionInString(reminder) for i in mentionList: message += f" {i}" - elif expired[1] == 2: # s'il faut envoyer en DM le message - mentionList = getMentionInString(reminder) - for i in mentionList: - message += f" {i}x" try: await channel.send(message, embed = finalEmbed) # envoie du rappel except: # les DM sont fermés diff --git a/src/utils/reminder.py b/src/utils/reminder.py index bf0ce16..c0419f5 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -44,7 +44,7 @@ class Reminder(Database): """Retourne la liste des reminders d'un utilisateur.""" requete = """ SELECT reminder_str, creation_int, expiration_int, id FROM reminder - WHERE user_id = ? AND guild_id = ? + WHERE user_id = ? AND (guild_id = ? OR guild_id = 0) """ return self.affichageResultat(self.requete(requete, [userID, guildID])) From 90e719241b3bf8fb33c8e383ad21c6542118f365 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 15 Jun 2021 21:15:29 +0200 Subject: [PATCH 191/286] =?UTF-8?q?ajout=20fonction=20pour=20passer=20r?= =?UTF-8?q?=C3=A9cup=C3=A9rer=20l'id=20d'une=20mention=20+=20meilleur=20ag?= =?UTF-8?q?encement=20du=20code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/confreriedukassoulait.py | 1 - src/cogs/fun.py | 16 ++++++---------- src/cogs/games.py | 4 ++-- src/cogs/utils.py | 15 +++++++++------ src/utils/core.py | 3 +++ 5 files changed, 20 insertions(+), 19 deletions(-) diff --git a/src/cogs/confreriedukassoulait.py b/src/cogs/confreriedukassoulait.py index cb2d5c1..b7dd776 100644 --- a/src/cogs/confreriedukassoulait.py +++ b/src/cogs/confreriedukassoulait.py @@ -100,7 +100,6 @@ class ConfrerieDuKassoulait(commands.Cog): # ne fonctionne pas quand un message a été supprimé avant que le bot ai démarré # info sur la personne qui a supprimé ne fonctionne pas si il a supprimé un message auparavant (les logs se rajoute a un log deja existant) - @commands.Cog.listener() async def on_message(self, message): if message.author.id == 786897204816117771 and message.author.name == "GitHub" and message.author.bot: # Autopublish diff --git a/src/cogs/fun.py b/src/cogs/fun.py index 0003251..b6f8572 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -3,7 +3,7 @@ from re import findall from discord.ext import commands from random import randint, choice from discord_slash import cog_ext -from utils.core import retirerDoublons +from utils.core import retirerDoublons, mentionToUser from utils.time import intToDatetime def setup(client): @@ -26,29 +26,25 @@ class Fun(commands.Cog): user = ctx.author if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') - return await ctx.send(f"T'as {randint(randint(-100,0),220)} IQ {user.mention} !") + return await ctx.send(f"T'as {randint(randint(-100, 0), 220)} de QI {user.mention} !") else: user = user[0] try: - user2 = user - user2 = user2[2:-1] - user2 = user2.replace("!","") - user2 = int(user2) - user2 = self.client.get_user(user2) + user2 = self.client.get_user(mentionToUser(user)) if user2.id == self.client.user.id: if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') - return await ctx.send(f"Bah... pas ouf... j'ai juste 100000 de QI :/") + return await ctx.send(f"Bah euh... j'ai que (au moins) 100 000 de QI :/") else: if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') message = await ctx.send("...") - return await message.edit(content = f"{user2.mention} a {randint(randint(-100,0),220)} de QI !") + return await message.edit(content = f"{user2.mention} a {randint(randint(-100,0),220)} de QI !") except: if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') message = await ctx.send("...") - return await message.edit(content = f"{user} a {randint(randint(-100,0),220)} de QI !") + return await message.edit(content = f"{user} a {randint(randint(-100, 0), 220)} de QI !") @cog_ext.cog_slash(name="iq", description = "Calcule ton QI.") async def __iq(self, ctx, user = None): if user == None: diff --git a/src/cogs/games.py b/src/cogs/games.py index b89b4de..4594bf1 100644 --- a/src/cogs/games.py +++ b/src/cogs/games.py @@ -61,7 +61,7 @@ class Games(commands.Cog): return await ctx.send("Tu es déjà en partie.") guess = 5 self.guessing_game[str(ctx.author.id)] = guess - number = randint(1,100) + number = randint(1, 100) message = f"Choisis un nombre entre 1 et 100 {ctx.author.mention}." await ctx.send(message) while self.guessing_game[str(ctx.author.id)] != 0: @@ -111,7 +111,7 @@ class Games(commands.Cog): fromSlash = False if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') - return await ctx.send(f"{'Pile' if randint(0,1) == 1 else 'Face'} !") + return await ctx.send(f"{'Pile' if randint(0, 1) == 1 else 'Face'} !") @cog_ext.cog_slash(name="pileouface", description = "Pile ou face.") async def __pileouface(self, ctx): await self._pileouface(ctx, True) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 51e6e95..b9e0220 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -5,7 +5,7 @@ from discord.ext import commands, tasks from random import randint, shuffle from discord_slash import cog_ext from utils.reminder import Reminder -from utils.core import map_list_among_us, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick +from utils.core import map_list_among_us, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick, mentionToUser from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString, timestampScreen, getAge, ageLayout, nowCustom def setup(client): @@ -32,7 +32,11 @@ class Utils(commands.Cog): arg = None if arg == 'help': - return await ctx.send(embed = discord.Embed(color = discord.Colour.random(), description = ":hourglass: correspond au temps entre deux battements de cœurs\n\n:heartbeat: correspond au temps que met le client a réagir au messages (0 est normal lors de l'utilisation d'une commande slash)\n\n:stopwatch: correspond au temps que met le client a calculer le ping")) + return await ctx.send(embed = discord.Embed(color = discord.Colour.random(), description = + ":hourglass: correspond au temps entre deux battements de cœurs\n\n \ + :heartbeat: correspond au temps que met le client a réagir au messages (0 est normal lors de l'utilisation d'une commande slash)\n\n \ + :stopwatch: correspond au temps que met le client a calculer le ping" + )) else: now = int(round(nowCustom() * 1000)) if fromSlash != True: @@ -53,7 +57,6 @@ class Utils(commands.Cog): else: return await self._ping(ctx, arg, True) - @commands.command(name='avatar') async def _avatar(self, ctx, *user): """Affiche ton avatar ou celui que tu mentionnes.\n ➡ Syntaxe: {PREFIX}avatar [user]""" @@ -70,7 +73,7 @@ class Utils(commands.Cog): if user == None: user = ctx.author else: - user = self.client.get_user(int(user[2:-1].replace("!",""))) + user = self.client.get_user(mentionToUser(user)) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') embed = discord.Embed(description = f"[lien vers la photo de profil]({user.avatar_url}) de {user.mention}", color = discord.Colour.random()) @@ -372,7 +375,7 @@ class Utils(commands.Cog): if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') return await ctx.send(embed = embed) - return await ctx.send(f"Tu mentionnes trop d'utilisateurs : `{ctx.prefix}whois [@Membre]`") + return await ctx.send(f"Tu mentionnes trop d'utilisateurs : `{ctx.prefix}whois [@membre]`") @cog_ext.cog_slash(name="whois", description = "Affiche les infos sur l'utilisateur.") async def __whois(self, ctx, user: discord.Member = None): ctx.prefix = "/" # pas sûr que ce soit utile @@ -600,7 +603,7 @@ class Utils(commands.Cog): utilisateur = utilisateur[:-1] if len(utilisateur) > 0: try: - utilisateur = int(getMentionInString(utilisateur[0])[0][2:][:-1].replace("!", "")) + utilisateur = mentionToUser(getMentionInString(utilisateur[0])[0]) except: return await ctx.send("L'utilisateur renseigné n'a pas été trouvé.") else: diff --git a/src/utils/core.py b/src/utils/core.py index 3577f4e..c0fcdfb 100644 --- a/src/utils/core.py +++ b/src/utils/core.py @@ -107,3 +107,6 @@ def ligneFormatage(ligne): for balises in liste_balise: ligne = ligne.replace(balises[0], balises[1]) return ligne + +def mentionToUser(mention: str): + return int(mention[2:-1].replace("!","")) From 2cca50a3273be00b3f8cff22b2c70f7ee4ca6c09 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 15 Jun 2021 21:35:39 +0200 Subject: [PATCH 192/286] aliase QI --- src/cogs/fun.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/fun.py b/src/cogs/fun.py index b6f8572..6dc5e58 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -14,7 +14,7 @@ class Fun(commands.Cog): def __init__(self, client): self.client = client - @commands.command(name='iq') + @commands.command(name='iq', aliases=["qi"]) async def _iq(self, ctx, *user): """Calcule ton QI.\n ➡ Syntaxe: {PREFIX}iq [user]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" fromSlash = False From 00e672184909aac9bed6d4506f58bb2bad525892 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 15 Jun 2021 21:36:29 +0200 Subject: [PATCH 193/286] interference avec les jours et l'aliase D pour le reminder dans les DM --- src/cogs/utils.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index b9e0220..990e9f7 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -504,7 +504,7 @@ class Utils(commands.Cog): if time.endswith("@"): time = time[:-1] extrarg = 1 - if time.lower().endswith("p") or time.lower().endswith("d"): + if time.lower().endswith("p"): time = time[:-1] extrarg = 2 guildID = 0 @@ -517,7 +517,7 @@ class Utils(commands.Cog): embed.add_field(name="Attention", value= "Format pour le temps : `d` ou `j` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (légères variances acceptés aussi). \ \nMet un `@` accolée aux temps pour mentionner les gens mentionner dans ton message. \ - \nMet un `P` ou `D` accolée au temps pour que le bot te DM au lieu de t'envoyer un message dans ce salon." + \nMet un `P` accolée au temps pour que le bot te DM au lieu de t'envoyer un message dans ce salon." ) else: now = int(nowUTC()) From ea6c6c050476798f0f4a65cbb4d5156a50c6a49a Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 15 Jun 2021 21:41:11 +0200 Subject: [PATCH 194/286] =?UTF-8?q?ajout=20limite=2050=20ans=20pour=20pr?= =?UTF-8?q?=C3=A9venir=20bug=20python=20int=20trop=20grand?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/utils.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 990e9f7..410383c 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -519,6 +519,8 @@ class Utils(commands.Cog): \nMet un `@` accolée aux temps pour mentionner les gens mentionner dans ton message. \ \nMet un `P` accolée au temps pour que le bot te DM au lieu de t'envoyer un message dans ce salon." ) + elif seconds > (50 * (86400 * 365.242)): # 50 ans + embed.add_field(name="Attention", value="Tu as spécifié une durée trop longue, la durée maximum étant de 50 ans.") else: now = int(nowUTC()) messageID = None From d0c0d00653b714326cda6d5f92e14e784601ee53 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 15 Jun 2021 21:47:04 +0200 Subject: [PATCH 195/286] changement slash command name memo to note --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 410383c..c92d497 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -233,7 +233,7 @@ class Utils(commands.Cog): async def _memo_error(self, ctx, error): if str(error) == "text is a required argument that is missing.": await ctx.send(f"Vous devez renseigner un message : `{ctx.prefix}memo/note ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢`.") - @cog_ext.cog_slash(name="memo", description = "T'envoie un petit memo par message privé.") + @cog_ext.cog_slash(name="note", description = "T'envoie un petit memo par message privé.") async def __memo(self, ctx, memo): return await self._memo(ctx, memo, True) From 80abb0cce515e5776e993852fcfeb669884c42bd Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 15 Jun 2021 21:51:07 +0200 Subject: [PATCH 196/286] update requirements to latest version --- requirements.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/requirements.txt b/requirements.txt index 2b3444a..8cbaf25 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,7 @@ -discord.py[voice]==1.7.2 # discord +discord.py[voice]==1.7.3 # discord pytz==2021.1 # timezone asyncpraw==7.2.0 # reddit -youtube-dl==2021.4.26 # music +youtube-dl==2021.6.6 # music lyricsgenius==3.0.1 # lyrics -feedparser==6.0.2 # rss feed (news) -discord-py-slash-command==1.2.0 # slash commands +feedparser==6.0.6 # rss feed (news) +discord-py-slash-command==1.2.2 # slash commands From 5d9be532901232d4c7c0ca842753a364bf86d686 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 16 Jun 2021 01:20:42 +0200 Subject: [PATCH 197/286] =?UTF-8?q?ajout=20guild=20pour=20=C3=A9viter=20de?= =?UTF-8?q?=20supprimer=20le=20mauvais=20reminder?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/utils.py | 4 ++-- src/utils/reminder.py | 16 +++++++--------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index c92d497..dea0949 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -654,7 +654,7 @@ class Utils(commands.Cog): else: return await ctx.send("Veuillez renseigner un ID.") - verification = Reminder().appartenanceReminder(ctx.author.id, id) + verification = Reminder().appartenanceReminder(ctx.author.id, id, ctx.guild.id) if verification: Reminder().suppressionReminder(id) if fromSlash != True: @@ -663,7 +663,7 @@ class Utils(commands.Cog): else: if fromSlash != True: await ctx.message.add_reaction(emoji = '❌') - return await ctx.send("Rappel non trouvé ou qui ne vous appartiens pas.") + return await ctx.send("Rappel non trouvé, pas sur le bon serveur ou qui ne vous appartiens pas.") @cog_ext.cog_slash(name="reminderdelete", description = "Suppprime un rappel.") async def __reminderdelete(self, ctx, id): return await self._reminderdelete(ctx, id, True) diff --git a/src/utils/reminder.py b/src/utils/reminder.py index c0419f5..6e262f7 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -56,14 +56,12 @@ class Reminder(Database): """ return self.affichageResultat(self.requete(requete, time)) - def appartenanceReminder(self, user = int, id = int): - """Vérifie qu'un rappel appartiens à un utilisateur. Renvois False si le rappel n'existe pas.""" + def appartenanceReminder(self, user = int, id = int, guildID = int): + """Vérifie qu'un rappel appartiens à un utilisateur et que la guilde soit la bonne. Renvois False si le rappel n'existe pas.""" requete = """ - SELECT user_id, id, message_id FROM reminder - WHERE id = ? AND user_id = ? + SELECT EXISTS ( + SELECT 1 FROM reminder + WHERE id = ? AND user_id = ? AND (guild_id = ? OR guild_id = 0) + ) """ - resultat = self.affichageResultat(self.requete(requete, [id, user])) - if len(resultat) > 0: - return True - else: - return False + return True if self.affichageResultat(self.requete(requete, [id, user, guildID]))[0][0] == 1 else False From a71cc40ac1e4119a7f99a7a4fd19b1331d9e6e5d Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 16 Jun 2021 13:59:32 +0200 Subject: [PATCH 198/286] ajout subreddit --- src/cogs/internet.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/internet.py b/src/cogs/internet.py index f355691..0ac3a37 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -34,7 +34,7 @@ class Internet(commands.Cog): subredditchoix = choice(['memes', 'goodanimemes', 'dankmemes', 'DeepFried', 'educationalmemes', 'funny', 'marvelmemes', 'me_irl', 'meme', 'MemeEconomy', 'Memes_Of_The_Dank', 'MinecraftMemes', 'physicsmemes', 'blackpeopletwitter', 'metal_me_irl', '195', 'shittyadviceanimals', 'meirl', - '2meirl4meirl', 'AdviceAnimals', 'weirdmemes']) + '2meirl4meirl', 'AdviceAnimals', 'weirdmemes', 'LeagueOfMemes']) try: async with Reddit(client_id = environ['TOKEN_REDDIT_CLIENT_ID'], client_secret = environ['TOKEN_REDDIT_CLIENT_SECRET'], user_agent = f"disreddit /u/{environ['TOKEN_REDDIT_USER_AGENT']}, http://localhost:8080") as reddit: From 277258a984f972d83b2d6d7d141be51fd34b23b6 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 16 Jun 2021 14:01:55 +0200 Subject: [PATCH 199/286] =?UTF-8?q?pr=C3=A9cisions=20message=20reminder?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/utils.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index dea0949..b5c1973 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -496,6 +496,7 @@ class Utils(commands.Cog): embed = discord.Embed(color = 0xC41B1B) extrarg = 0 guildID = ctx.guild.id # can be set to 0 if its a DM message, so it can be see from anywhere + destination = "ici" if not reminder: reminder = "Notification" if time == "help": @@ -508,6 +509,7 @@ class Utils(commands.Cog): time = time[:-1] extrarg = 2 guildID = 0 + destination = "en MP" seconds = stringTempsVersSecondes(time) if type(seconds) != int: if fromSlash != True: @@ -527,7 +529,7 @@ class Utils(commands.Cog): if fromSlash != True: messageID = ctx.message.id Reminder().ajoutReminder(messageID, ctx.channel.id, extrarg, reminder, now, now + seconds, ctx.author.id, guildID) - return await ctx.send(f"Ok, je t'en parles dans {timedeltaToString(seconds)} avec 1m de retard maximum.") + return await ctx.send(f"Ok, je t'en parles {destination} dans {timedeltaToString(seconds)} avec 1m de retard maximum.") await ctx.send(embed = embed) @_reminder.error async def _reminder_error(self, ctx, error): From 22e6d73a368ab224fa21ede13150ca49e3170546 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 21 Jun 2021 23:55:27 +0200 Subject: [PATCH 200/286] =?UTF-8?q?suppression=20message=20au=20d=C3=A9mar?= =?UTF-8?q?rage=20+=20role=20r=C3=A8gles=20+=20changement=20DM=20de=20bien?= =?UTF-8?q?vneue?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/confreriedukassoulait.py | 31 +++++-------------------------- 1 file changed, 5 insertions(+), 26 deletions(-) diff --git a/src/cogs/confreriedukassoulait.py b/src/cogs/confreriedukassoulait.py index b7dd776..269b777 100644 --- a/src/cogs/confreriedukassoulait.py +++ b/src/cogs/confreriedukassoulait.py @@ -14,11 +14,6 @@ class ConfrerieDuKassoulait(commands.Cog): def __init__(self, client): self.client = client - @commands.Cog.listener() - async def on_ready(self): - channel = self.client.get_channel(742564480050790512) - await channel.send("Le bot a bien démarré.") - @commands.Cog.listener() async def on_member_join(self, member): if member.guild.id == 441208120644075520: # Confrérie du Kassoulait @@ -27,12 +22,12 @@ class ConfrerieDuKassoulait(commands.Cog): else: role = discord.utils.get(member.guild.roles, name = "Copain") await member.add_roles(role) - try: - await member.send(f"Coucou **{member.name}** sur {member.guild.name} ! 🥰\n\nTu as le rôle **{role}** 💖!") + try: # DM possiblement fermé + await member.send(f"Coucou **{member.name}** sur {member.guild.name} ! 🥰\n\nJ'te donne le rôle de **{role}** 💖!") except: pass channel = self.client.get_channel(741639570172674120) # salons des arrivées - switch = [ + msgBienvenue = [ f"Bienvenue, {member.mention}. On espère que tu as apporté de la pizza.", f"C'est un plaisir de te voir, {member.mention}.", f"{member.mention} vient juste d'arriver !", @@ -46,29 +41,13 @@ class ConfrerieDuKassoulait(commands.Cog): f"{member.mention} a rejoint le groupe." ] message = await channel.send("...") # évite d'envoyer une notification - await message.edit(content = choice(switch)) + await message.edit(content = choice(msgBienvenue)) @commands.Cog.listener() async def on_member_remove(self, member): if member.guild.id == 441208120644075520: # Confrérie du Kassoulait channel = self.client.get_channel(741639570172674120) # salons des arrivées - await channel.send(f"{member.mention} vient de quitter le serveur.") - - @commands.Cog.listener() - async def on_raw_reaction_add(self, payload): - if payload.message_id == 644922358745792512: # Règles de la Confrérie du Kassoulait - if payload.emoji.name == '✅': - role = discord.utils.get(payload.member.guild.roles, name="règles-acceptés") - await payload.member.add_roles(role) - - @commands.Cog.listener() - async def on_raw_reaction_remove(self, payload): - if payload.message_id == 644922358745792512: # Règles de la Confrérie du Kassoulait - if payload.emoji.name == '✅': - guild = discord.utils.find(lambda g : g.id == payload.guild_id, self.client.guilds) - member = discord.utils.find(lambda m: m.id == payload.user_id, guild.members) - role = discord.utils.get(guild.roles, name="règles-acceptés") - await member.remove_roles(role) + await channel.send(f"{member.mention} ({member.name}) vient de quitter le serveur.") @commands.Cog.listener() async def on_message_delete(self, message): From d0b3a904b020c0282be74e9afdb5df4443450be3 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 22 Jun 2021 00:06:56 +0200 Subject: [PATCH 201/286] changement message de bienvenue --- src/cogs/confreriedukassoulait.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/confreriedukassoulait.py b/src/cogs/confreriedukassoulait.py index 269b777..23cb1e0 100644 --- a/src/cogs/confreriedukassoulait.py +++ b/src/cogs/confreriedukassoulait.py @@ -23,7 +23,7 @@ class ConfrerieDuKassoulait(commands.Cog): role = discord.utils.get(member.guild.roles, name = "Copain") await member.add_roles(role) try: # DM possiblement fermé - await member.send(f"Coucou **{member.name}** sur {member.guild.name} ! 🥰\n\nJ'te donne le rôle de **{role}** 💖!") + await member.send(f"Coucou **{member.name}** dans **{member.guild.name}** ! 🥰\n\nJ'te donne le rôle de **{role}** 💖!") except: pass channel = self.client.get_channel(741639570172674120) # salons des arrivées From 1520fa7495d901c4b4b6bb355ecd244af8456a08 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 22 Jun 2021 13:24:35 +0200 Subject: [PATCH 202/286] bump to 1.5 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cff5ea4..4a807b1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Bot developed with [discord.py](https://github.com/Rapptz/discord.py) (rewrite) - FRENCH -[![Version](https://img.shields.io/badge/version-1.4-green?style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/releases/latest) +[![Version](https://img.shields.io/badge/version-1.5-green?style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/releases/latest) [![Docker Stars](https://img.shields.io/docker/stars/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/r/mylloon/kassoubot) [![Docker Pulls](https://img.shields.io/docker/pulls/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/r/mylloon/kassoubot) [![Github stars](https://img.shields.io/github/stars/Confrerie-du-Kassoulait/kassoubot?label=Github%20Stars&style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/stargazers) From 904149fcb0f75b9f60c77a8f241416f6a8b76b3e Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 22 Jun 2021 14:02:42 +0200 Subject: [PATCH 203/286] ajout commande changelogs --- src/cogs/utils.py | 35 +++++++++++++++++++++++++++++++---- src/utils/core.py | 13 +++++++++++++ 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index b5c1973..92a8463 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -5,7 +5,7 @@ from discord.ext import commands, tasks from random import randint, shuffle from discord_slash import cog_ext from utils.reminder import Reminder -from utils.core import map_list_among_us, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick, mentionToUser +from utils.core import map_list_among_us, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick, mentionToUser, getChangelogs from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString, timestampScreen, getAge, ageLayout, nowCustom def setup(client): @@ -482,7 +482,7 @@ class Utils(commands.Cog): @commands.command(name='reminder', aliases=["remind", "remindme", "rappel"]) async def _reminder(self, ctx, time, *reminder): - """Met en place un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminder/remind/remindme/rappel [@] [message] """ + """Met en place un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminder/remind/remindme/rappel [@] [message]""" fromSlash = False if len(reminder) > 0: if reminder[-1] == True: @@ -599,7 +599,7 @@ class Utils(commands.Cog): @commands.command(name='reminderlist', aliases=["remindlist", "rl", "rappeliste"]) async def _reminderlist(self, ctx, *utilisateur): - """Affiche la liste des rappels d'un utilisateur.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminderlist/rl/remindlist/rappeliste [utilisateur] """ + """Affiche la liste des rappels d'un utilisateur.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminderlist/rl/remindlist/rappeliste [utilisateur]""" fromSlash = False if len(utilisateur) > 0: if utilisateur[-1] == True: @@ -642,7 +642,7 @@ class Utils(commands.Cog): @commands.command(name='reminderdelete', aliases=["reminddelete", "rd"]) async def _reminderdelete(self, ctx, *id): - """Suppprime un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminderdelete/rd """ + """Suppprime un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminderdelete/rd """ fromSlash = False if len(id) > 0: if id[-1] == True: @@ -669,3 +669,30 @@ class Utils(commands.Cog): @cog_ext.cog_slash(name="reminderdelete", description = "Suppprime un rappel.") async def __reminderdelete(self, ctx, id): return await self._reminderdelete(ctx, id, True) + + @commands.command(name='changelogs', aliases=["changelog", "changement", "changements"]) + async def _changelogs(self, ctx, *version): + """Affiche les changements de la dernière version ou d'une version précise.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}changelogs/changelog/changement/changements [version] """ + fromSlash = False + if len(version) > 0: + if version[-1] == True: + fromSlash = version[-1] + version = version[:-1] + if len(version) > 0: + version = version[0] + else: + version = 'latest' + changes = getChangelogs(version) + if changes == None: + if fromSlash != True: + await ctx.message.add_reaction(emoji = '❌') + return await ctx.send("Veuillez renseigner un numéro de version valide et existant.") + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + await ctx.send(f"url: {changes[0]}\nnum de version: {changes[1]}\ntaille du message de changements: {len(changes[2])}") + @cog_ext.cog_slash(name="changelogs", description = "Affiche les changements de la dernière version ou d'une version précise.") + async def __changelogs(self, ctx, version: int = None): + if version == None: + return await self._reminderlist(ctx, True) + else: + return await self._reminderlist(ctx, version, True) diff --git a/src/utils/core.py b/src/utils/core.py index c0fcdfb..460170e 100644 --- a/src/utils/core.py +++ b/src/utils/core.py @@ -109,4 +109,17 @@ def ligneFormatage(ligne): return ligne def mentionToUser(mention: str): + """Récupère une mention et renvois son ID""" return int(mention[2:-1].replace("!","")) + +def getChangelogs(version = 'latest'): + """Récupère les changements d'une version (par défaut, la dernière en date) et renvois dans l'ordre : url, n° version, changements""" + if version != 'latest': + version = f'tags/v{version}' + changements = requests.get(f"https://api.github.com/repos/Confrerie-du-Kassoulait/KassouBot/releases/{version}").json() + try: + changements["message"] # renvois None si aucune version correspondante n'a été trouvée + return None + except: + pass + return (changements["html_url"], changements["tag_name"][1:], changements["body"]) From 331d4623a4a38537a145ad16f90c5e83f60bcf7f Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 22 Jun 2021 14:03:36 +0200 Subject: [PATCH 204/286] ajout commentaire reminderloop --- src/cogs/utils.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 92a8463..a37a398 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -544,6 +544,7 @@ class Utils(commands.Cog): @tasks.loop(minutes = 1) async def _reminderLoop(self): + """Méthode qui se répète toute les minutes pour vérifier si des rappels n'ont pas expirés, si expirés, les envoient.""" expiration = Reminder().recuperationExpiration(int(nowUTC())) # on récupères les éléments expirés for expired in expiration: # on regarde tout les éléments expirés reminder = expired[2] # message From 0b186bd7ec63694cdbb05528d1f98366956ef11a Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 22 Jun 2021 15:12:10 +0200 Subject: [PATCH 205/286] ajout exeption api rate limited --- src/utils/core.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/utils/core.py b/src/utils/core.py index 460170e..c5bd7f8 100644 --- a/src/utils/core.py +++ b/src/utils/core.py @@ -118,8 +118,10 @@ def getChangelogs(version = 'latest'): version = f'tags/v{version}' changements = requests.get(f"https://api.github.com/repos/Confrerie-du-Kassoulait/KassouBot/releases/{version}").json() try: - changements["message"] # renvois None si aucune version correspondante n'a été trouvée - return None + if changements["message"].startswith("API"): # renvois 0 si c'est une erreur API + return 0 + else: # renvois None si aucune version correspondante n'a été trouvée + return None except: pass - return (changements["html_url"], changements["tag_name"][1:], changements["body"]) + return [changements["html_url"], changements["tag_name"][1:], changements["body"]] From 7f4ad7c109abad35195213fc636aa15eab7dec06 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 22 Jun 2021 15:12:52 +0200 Subject: [PATCH 206/286] commande changelogs fonctionnelle + ajout des changements si disponible dans la commande info --- src/cogs/utils.py | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index a37a398..40f910f 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -269,9 +269,12 @@ class Utils(commands.Cog): embed.add_field(name = f"Membre{'s' if total_unique > 1 else ''}", value = f"`{total_unique}` au total\n`{total_online}` en ligne") embed.add_field(name = f"Salon{'s' if (text + voice) > 1 else ''}", value = f"`{text}` textuel{'s' if text > 1 else ''}\n`{voice}` voca{'ux' if voice > 1 else 'l'}") embed.add_field(name = "Prefix", value = f"`{ctx.prefix}`") - embed.add_field(name = "Code source", value = f"[Lien Github](https://github.com/Confrerie-du-Kassoulait/KassouBot/)") + embed.add_field(name = "Code source", value = "[Lien Github](https://github.com/Confrerie-du-Kassoulait/KassouBot/)") embed.add_field(name = "Timezone", value = f"`{self.customTimezone}`") embed.add_field(name = "Version", value = f"`{version}`") + changes = getChangelogs(version) + if changes != None and changes != 0: + embed.add_field(name = "Changements", value = f"[Lien Github]({changes[0]})") embed.set_footer(text = f"Basé sur discord.py {discord.__version__}") try: if fromSlash != True: @@ -673,7 +676,7 @@ class Utils(commands.Cog): @commands.command(name='changelogs', aliases=["changelog", "changement", "changements"]) async def _changelogs(self, ctx, *version): - """Affiche les changements de la dernière version ou d'une version précise.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}changelogs/changelog/changement/changements [version] """ + """Affiche les changements de la dernière version ou d'une version précise.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}changelogs/changelog/changement/changements [version]""" fromSlash = False if len(version) > 0: if version[-1] == True: @@ -684,16 +687,24 @@ class Utils(commands.Cog): else: version = 'latest' changes = getChangelogs(version) - if changes == None: + if changes == None or changes == 0: if fromSlash != True: await ctx.message.add_reaction(emoji = '❌') - return await ctx.send("Veuillez renseigner un numéro de version valide et existant.") + if changes == None: + message = "Veuillez renseigner un numéro de version valide et existant." + else: + message = "Trop de requêtes sur l'API de Github, réessayez plus tard." + return await ctx.send(message) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') - await ctx.send(f"url: {changes[0]}\nnum de version: {changes[1]}\ntaille du message de changements: {len(changes[2])}") + if len(changes[2]) > 2048: + changes[2] = f"{changes[2][:1900]}..." + embed = discord.Embed(description = f"[lien vers la page Github]({changes[0]})\n\n{changes[2]}", color = discord.Colour.random()) + embed.set_author(name = f"Changements de la v{changes[1]}") + await ctx.send(embed = embed) @cog_ext.cog_slash(name="changelogs", description = "Affiche les changements de la dernière version ou d'une version précise.") - async def __changelogs(self, ctx, version: int = None): + async def __changelogs(self, ctx, version = None): if version == None: - return await self._reminderlist(ctx, True) + return await self._changelogs(ctx, True) else: - return await self._reminderlist(ctx, version, True) + return await self._changelogs(ctx, version, True) From 0975ed075ad4ce41d0062af4df76737cfce38df7 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 22 Jun 2021 18:42:49 +0200 Subject: [PATCH 207/286] double pic --- src/cogs/confreriedukassoulait.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cogs/confreriedukassoulait.py b/src/cogs/confreriedukassoulait.py index 23cb1e0..36e9392 100644 --- a/src/cogs/confreriedukassoulait.py +++ b/src/cogs/confreriedukassoulait.py @@ -97,5 +97,7 @@ class ConfrerieDuKassoulait(commands.Cog): "tchèt", "mouss", "ologbo", "kats", "猫", "кот", "고양이", "poticha", "😼", "ʇɐɥɔ", "chaton"] if message.content.lower() in chiens: await Internet(self.client)._dog(self, await self.client.get_context(message)) + await Internet(self.client)._dog(self, await self.client.get_context(message)) if message.content.lower() in chats: await Internet(self.client)._cat(self, await self.client.get_context(message)) + await Internet(self.client)._cat(self, await self.client.get_context(message)) From 5729084235636c0b0e5e8faeba0d6f74874f9325 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 22 Jun 2021 18:48:10 +0200 Subject: [PATCH 208/286] better mutliple pics --- src/cogs/confreriedukassoulait.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cogs/confreriedukassoulait.py b/src/cogs/confreriedukassoulait.py index 36e9392..45b51ed 100644 --- a/src/cogs/confreriedukassoulait.py +++ b/src/cogs/confreriedukassoulait.py @@ -96,8 +96,8 @@ class ConfrerieDuKassoulait(commands.Cog): "kotsur", "bisad", "büsi", "chatz", "paka", "muc", "poonai", "puunay", "kocour", "kocka", "maa-oh", "kedi", "kit", "con mêo", "tchèt", "mouss", "ologbo", "kats", "猫", "кот", "고양이", "poticha", "😼", "ʇɐɥɔ", "chaton"] if message.content.lower() in chiens: - await Internet(self.client)._dog(self, await self.client.get_context(message)) - await Internet(self.client)._dog(self, await self.client.get_context(message)) + for _ in range(0, 2): + await Internet(self.client)._dog(self, await self.client.get_context(message)) if message.content.lower() in chats: - await Internet(self.client)._cat(self, await self.client.get_context(message)) - await Internet(self.client)._cat(self, await self.client.get_context(message)) + for _ in range(0, 2): + await Internet(self.client)._cat(self, await self.client.get_context(message)) From 94f3fa2428ac02da853e9e99422097f09b4cff99 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 23 Jun 2021 21:02:17 +0200 Subject: [PATCH 209/286] update dependencies --- requirements.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/requirements.txt b/requirements.txt index 8cbaf25..faa329d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,7 @@ discord.py[voice]==1.7.3 # discord pytz==2021.1 # timezone -asyncpraw==7.2.0 # reddit +asyncpraw==7.3.0 # reddit youtube-dl==2021.6.6 # music lyricsgenius==3.0.1 # lyrics -feedparser==6.0.6 # rss feed (news) -discord-py-slash-command==1.2.2 # slash commands +feedparser==6.0.8 # rss feed (news) +discord-py-slash-command==2.0.1 # slash commands From e5d33198417aca8ae5bdee0045dcdb914fa68112 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 23 Jun 2021 21:11:17 +0200 Subject: [PATCH 210/286] =?UTF-8?q?ajout=20m=C3=A9thode=20v=C3=A9rificatio?= =?UTF-8?q?n=20slashCommand?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/core.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/utils/core.py b/src/utils/core.py index c5bd7f8..fd3545d 100644 --- a/src/utils/core.py +++ b/src/utils/core.py @@ -125,3 +125,18 @@ def getChangelogs(version = 'latest'): except: pass return [changements["html_url"], changements["tag_name"][1:], changements["body"]] + +def isSlash(arg): + """Regarde si la commande viens d'un slash ou pas, retourne l'argument sans le 'True' si c'est le cas""" + fromSlash = False + fullarg = arg + if len(arg) > 0: + if arg[-1] == True or arg[-1] == None: + fromSlash = arg[-1] + fullarg = arg[:-1] + if len(fullarg) == 0: + arg = None + else: + arg = arg[0] + + return (arg, fromSlash, fullarg) From a46cb38b2d7a0dde77c2853b05c68157430930cc Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 23 Jun 2021 21:12:29 +0200 Subject: [PATCH 211/286] =?UTF-8?q?utilisation=20nouvelle=20m=C3=A9thode?= =?UTF-8?q?=20pour=20les=20slashcommands=20et=20changement=20complet=20de?= =?UTF-8?q?=20la=20commande=20NSFW?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/internet.py | 96 ++++++++++++++++++-------------------------- 1 file changed, 38 insertions(+), 58 deletions(-) diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 0ac3a37..924da3f 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -5,7 +5,7 @@ from discord.ext import commands from random import choice from asyncpraw import Reddit from discord_slash import cog_ext -from utils.core import randomImage +from utils.core import randomImage, isSlash def setup(client): client.add_cog(Internet(client)) @@ -18,15 +18,7 @@ class Internet(commands.Cog): @commands.command(name='memes', aliases = ['meme']) async def _memes(self, ctx, *args): """Envoie un meme de reddit.\n ➡ Syntaxe: {PREFIX}memes/meme [subreddit]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - fromSlash = False - if len(args) > 0: - if args[-1] == True: - fromSlash = args[-1] - args = args[:-1] - if len(args) > 0: - args = args[0] - else: - args = None + args, fromSlash, _ = isSlash(args) if args: # s'il y a un subreddit de défini subredditchoix = args @@ -35,6 +27,9 @@ class Internet(commands.Cog): 'educationalmemes', 'funny', 'marvelmemes', 'me_irl', 'meme', 'MemeEconomy', 'Memes_Of_The_Dank', 'MinecraftMemes', 'physicsmemes', 'blackpeopletwitter', 'metal_me_irl', '195', 'shittyadviceanimals', 'meirl', '2meirl4meirl', 'AdviceAnimals', 'weirdmemes', 'LeagueOfMemes']) + + if fromSlash != None and subredditchoix == "nsfw": # demande de nsfw sans passé par la commande appropriée + return await ctx.send(f"Désolé, tu demandes du nsfw... Fais plutôt **{ctx.prefix}sexe**.") try: async with Reddit(client_id = environ['TOKEN_REDDIT_CLIENT_ID'], client_secret = environ['TOKEN_REDDIT_CLIENT_SECRET'], user_agent = f"disreddit /u/{environ['TOKEN_REDDIT_USER_AGENT']}, http://localhost:8080") as reddit: @@ -43,18 +38,28 @@ class Internet(commands.Cog): all_subs = [item async for item in hot] # liste des memes submission = choice(all_subs) # choix aléatoire - image = ["png", "jpg", "jpeg", "bmp", "gif"] + image = ["png", "jpg", "jpeg", "bmp", "gif"] # gifv not working if submission.url[-3:] in image: - embed = discord.Embed(title = f"r/{subredditchoix} pour {ctx.author.name}", color = discord.Colour.random(), description = f"[lien du meme]({submission.url})") - embed.set_footer(text = f"Meme de Reddit") + if fromSlash != None: + footer = "Meme de Reddit" + memeOuImage = "[lien du meme]" + else: + footer = "NSFW de Reddit" + memeOuImage = "[lien de l'image]" + embed = discord.Embed(title = f"r/{subredditchoix} pour {ctx.author.name}", color = discord.Colour.random(), description = f"{memeOuImage}({submission.url})") + embed.set_footer(text = footer) embed.set_image(url = submission.url) message = await ctx.send(embed = embed) else: - message = await ctx.send(f"```r/{subredditchoix} pour {ctx.author.name}```\n{submission.url}") - if fromSlash != True: + if fromSlash != None: + message = await ctx.send(f"`r/{subredditchoix} pour {ctx.author.name}`\n{submission.url}") + else: + message = await ctx.send(f"`{subredditchoix.capitalize()} pour {ctx.author.name}`\n{submission.url}") + if fromSlash != True and fromSlash != None: await ctx.message.add_reaction(emoji = '✅') - await message.add_reaction('🔺') - return await message.add_reaction('🔻') + if fromSlash != None: + for emoji in ['🔺', '🔻']: + await message.add_reaction(emoji) except Exception as error: print(f"Error in _memes command = args: {args}, subreddit: {subredditchoix}, error: {error}") @@ -63,14 +68,17 @@ class Internet(commands.Cog): return await ctx.send(f"Ce subreddit est interdit, mis en quarantaine ou n'existe pas. ({subredditchoix})") @cog_ext.cog_slash(name="meme", description = "Envoie un meme de reddit.") async def __memes(self, ctx, subreddit = None): + ctx.prefix = "/" if subreddit == None: return await self._memes(ctx, True) else: return await self._memes(ctx, subreddit, True) @commands.command(name='cat', aliases = ['chat']) - async def _cat(self, ctx, fromSlash = False): + async def _cat(self, ctx, fromSlash = None): """Te montre un magnifique chat.\n ➡ Syntaxe: {PREFIX}cat/chat""" + if fromSlash != True: + fromSlash = False if ctx.author.nick: name = f"{ctx.author.nick} ({ctx.author.name}#{ctx.author.discriminator})" @@ -91,7 +99,7 @@ class Internet(commands.Cog): @commands.command(name='dog', aliases = ['chien']) async def _dog(self, ctx, fromSlash = None): """Te montre un magnifique chien.\n ➡ Syntaxe: {PREFIX}dog/chien""" - if fromSlash == None: + if fromSlash != True: fromSlash = False if ctx.author.nick: @@ -111,57 +119,29 @@ class Internet(commands.Cog): return await self._dog(ctx, True) @commands.command(name='sexe', aliases=['sexes', 'nude', 'nudes', 'nsfw']) - async def _sexe(self, ctx, *choice_of_nsfw): - """Envois une image coquine. (NSFW)\n ➡ Syntaxe: {PREFIX}sexe/sexes/nude/nudes [butts/boobs]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - fromSlash = False - if len(choice_of_nsfw) > 0: - if choice_of_nsfw[-1] == True: - fromSlash = choice_of_nsfw[-1] - choice_of_nsfw = choice_of_nsfw[:-1] - if len(choice_of_nsfw) > 0: - choice_of_nsfw = choice_of_nsfw[0] - else: - choice_of_nsfw = None - - liste_hot = ['butts', 'boobs'] - if choice_of_nsfw == 'butt': - choice_of_nsfw = 'butts' - if choice_of_nsfw == 'boob': - choice_of_nsfw = 'boobs' - if choice_of_nsfw in liste_hot: - pass - else: - choice_of_nsfw = choice(liste_hot) + async def _sexe(self, ctx, fromSlash = None): + """Envois une image coquine. (NSFW)\n ➡ Syntaxe: {PREFIX}sexe/sexes/nude/nudes""" + if fromSlash != True: + fromSlash = False if ctx.channel.is_nsfw(): - embed = discord.Embed(title = f"{choice_of_nsfw.capitalize()} pour {ctx.author.name}", colour = discord.Colour.random()) - nsfw = randomImage(f'http://api.o{choice_of_nsfw}.ru/noise/') - embed.set_image(url = f"http://media.o{choice_of_nsfw}.ru/{nsfw[0][0]['preview']}") - embed.set_footer(text = f"o{choice_of_nsfw}.ru a pris {nsfw[1]} ms pour sortir l'image n°{nsfw[0][1]}-{nsfw[1]}.") if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') - await ctx.send(embed = embed) + else: + ctx.prefix = "/" + return await self._memes(ctx, "nsfw", None) else: if fromSlash != True: await ctx.message.add_reaction(emoji = '❌') await ctx.send(f"Désolé mais je n'envois ce genre de message seulement dans les salons NSFW !") @cog_ext.cog_slash(name="sexe", description = "Envois une image coquine. (NSFW)") - async def __sexe(self, ctx, buttsorboobs = None): - if buttsorboobs == None: - return await self._sexe(ctx, True) - else: - return await self._sexe(ctx, buttsorboobs, True) + async def __sexe(self, ctx): + return await self._sexe(ctx, True) @commands.command(name='news', aliases=['rss']) async def _news(self, ctx, *arg): """Info random dans le domaine de l'informatique\n ➡ Syntaxe: {PREFIX}news/rss [site/liste]""" - fromSlash = False - if len(arg) > 0: - if arg[-1] == True: - fromSlash = arg[-1] - arg = arg[:-1] - if len(arg) > 0: - arg = arg[0] - else: + arg, fromSlash, _ = isSlash(arg) + if arg == None: arg = "" rss_website = { From 3cd0f482b82fc0ed6eb13cc3a9b3294b28cdebb3 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 23 Jun 2021 21:22:59 +0200 Subject: [PATCH 212/286] =?UTF-8?q?ajout=20nouvelle=20m=C3=A9thode=20isSla?= =?UTF-8?q?sh=20+=20fix=20bug=20chifumi?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/games.py | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/cogs/games.py b/src/cogs/games.py index 4594bf1..a15804b 100644 --- a/src/cogs/games.py +++ b/src/cogs/games.py @@ -3,6 +3,7 @@ import asyncio from discord.ext import commands from random import randint, choice from discord_slash import cog_ext +from utils.core import isSlash def setup(client): client.add_cog(Games(client)) @@ -16,28 +17,27 @@ class Games(commands.Cog): @commands.command(name='chifumi', aliases = ["shifumi", "ppc"]) async def _chifumi(self, ctx, *choix): """Un simple Chifumi contre le bot.\n ➡ Syntaxe: {PREFIX}chifumi/shifumi/ppc """ - fromSlash = False - if len(choix) < 1: + choix, fromSlash, _ = isSlash(choix) + if choix == None: raise ModuleNotFoundError - if choix[-1] == True: - fromSlash = choix[-1] - choix = choix[0] choix_jeu = ["Pierre ✊", "Papier 🧻", "Ciseaux ✂"] orditxt = choice(choix_jeu) ordi = choix_jeu.index(orditxt) - PIERRE = 0 - PAPIER = 1 - CISEAUX = 2 + pierre = 0 + papier = 1 + ciseaux = 2 choix = choix.lower() if choix == "pierre": - choix = PIERRE - if choix == "papier" or choix == "feuille": - choix = PAPIER - if choix == "ciseaux" or choix == "ciseau": - choix = CISEAUX + choix = pierre + elif choix == "papier" or choix == "feuille": + choix = papier + elif choix == "ciseaux" or choix == "ciseau": + choix = ciseaux + else: + return await ctx.send("Je n'ai pas compris ce que tu as joué, réessaie.") description = (f"{choix_jeu[choix][:-1]} VS {choix_jeu[ordi][:-1]}\n\n**" f"{('Égalité !', 'Tu as perdu !', 'Tu as gagné !')[(choix != ordi) + ((choix > ordi and ordi +1 == choix) or (choix < ordi and choix + ordi == 2))]}**") @@ -107,7 +107,7 @@ class Games(commands.Cog): @commands.command(name='pileouface', aliases=['pf']) async def _pileouface(self, ctx, fromSlash = None): """Pile ou face.\n ➡ Syntaxe: {PREFIX}pileouface/pf""" - if fromSlash == None: + if fromSlash != True: fromSlash = False if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') From 3f02ece95d17fd3358d55c91fa99144b58f9d1ad Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 23 Jun 2021 21:27:56 +0200 Subject: [PATCH 213/286] =?UTF-8?q?utilisation=20de=20la=20nouvelle=20m?= =?UTF-8?q?=C3=A9thode=20isSlash?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/fun.py | 29 +++++------- src/cogs/help.py | 9 ++-- src/cogs/school.py | 13 ++---- src/cogs/utils.py | 110 +++++++++++---------------------------------- 4 files changed, 43 insertions(+), 118 deletions(-) diff --git a/src/cogs/fun.py b/src/cogs/fun.py index 6dc5e58..196fdaf 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -3,7 +3,7 @@ from re import findall from discord.ext import commands from random import randint, choice from discord_slash import cog_ext -from utils.core import retirerDoublons, mentionToUser +from utils.core import retirerDoublons, mentionToUser, isSlash from utils.time import intToDatetime def setup(client): @@ -17,11 +17,8 @@ class Fun(commands.Cog): @commands.command(name='iq', aliases=["qi"]) async def _iq(self, ctx, *user): """Calcule ton QI.\n ➡ Syntaxe: {PREFIX}iq [user]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - fromSlash = False - if len(user) > 0: - if user[-1] == True: - fromSlash = user[-1] - user = user[:-1] + _, fromSlash, user = isSlash(user) + if len(user) == 0: user = ctx.author if fromSlash != True: @@ -55,11 +52,8 @@ class Fun(commands.Cog): @commands.command(name='love') async def _love(self, ctx, *users: discord.Member): """Découvre la probabilité que ces deux personnes se mettent en couple.\n ➡ Syntaxe: {PREFIX}love """ - fromSlash = False - if len(users) > 0: - if users[-1] == True: - fromSlash = users[-1] - users = users[:-1] + _, fromSlash, users = isSlash(users) + if len(users) == 2 or len(users) == 1: UneDemande = False if len(users) == 1: @@ -116,7 +110,7 @@ class Fun(commands.Cog): @commands.command(name='8ball', aliases=['8b', '8balls']) async def _8ball(self, ctx, fromSlash = None): """Répond à ta question 🔮.\n ➡ Syntaxe: {PREFIX}8ball/8b⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - if fromSlash == None: + if fromSlash != True: fromSlash = False reponses=["c'est sûr.","il en est décidément ainsi.","incontestablement.","oui sans aucun doute.","tu peux t'y fier.","tel que je le vois, oui.","c'est le plus probable.", "cela montre de bonnes perspectives.","certes.","les signes indiquent que oui.","ma réponse est oui.","ta question est trop floue, réessaie.","redemandes plus tard stp.", @@ -177,14 +171,11 @@ class Fun(commands.Cog): @commands.command(name='random', aliases=['randint']) async def _random(self, ctx, *n): """Tire au hasard un chiffre entre 1 et n (par défaut n=10)\n ➡ Syntaxe: {PREFIX}random/randint [n]""" - fromSlash = False - if len(n) > 0: - if n[-1] == True: - fromSlash = n[-1] - n = n[:-1] - if len(n) > 0: + n, fromSlash, _ = isSlash(n) + + if n: try: - n = int(n[0]) + n = int(n) except: return await ctx.send("Veuillez renseigner un chiffre valide.") else: diff --git a/src/cogs/help.py b/src/cogs/help.py index 35b670d..2e83bfb 100644 --- a/src/cogs/help.py +++ b/src/cogs/help.py @@ -1,6 +1,7 @@ import discord from discord.ext import commands from discord_slash import cog_ext +from utils.core import isSlash def setup(client): client.add_cog(Help(client)) @@ -14,11 +15,7 @@ class Help(commands.Cog): @commands.command(name='help') async def _help(self, ctx, *cog): """Affiche toutes les commandes du bot.\n ➡ Syntaxe: {PREFIX}help [catégorie]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - fromSlash = False - if len(cog) > 0: - if cog[-1] == True: - fromSlash = cog[-1] - cog = cog[:-1] + _, fromSlash, cog = isSlash(cog) if not cog: # Liste des Cog halp = discord.Embed(title = 'Liste des catégories et commandes sans catégorie', @@ -79,7 +76,7 @@ class Help(commands.Cog): @commands.command(name='invite') async def _invite(self, ctx, fromSlash = None): """Invite ce bot sur ton serveur !""" - if fromSlash == None: + if fromSlash != True: fromSlash = False embed = discord.Embed(description = f"[Lien vers l'invitation Discord](https://discord.com/api/oauth2/authorize?client_id={self.client.user.id}&permissions=8&scope=bot%20applications.commands)").set_author(name="Invite moi !") if fromSlash != True: diff --git a/src/cogs/school.py b/src/cogs/school.py index 9ab66a6..a07e472 100644 --- a/src/cogs/school.py +++ b/src/cogs/school.py @@ -1,6 +1,7 @@ import discord from discord.ext import commands from discord_slash import cog_ext +from utils.core import isSlash def setup(client): client.add_cog(School(client)) @@ -14,15 +15,7 @@ class School(commands.Cog): # @commands.has_any_role("Professeur", "professeur", "Prof", "prof") async def _appel(self, ctx, *voice_channel: int): """Fais l'appel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}appel [ID salon vocal]""" - fromSlash = False - if len(voice_channel) > 0: - if voice_channel[-1] == True: - fromSlash = voice_channel[-1] - voice_channel = voice_channel[:-1] - if len(voice_channel) > 0: - voice_channel = voice_channel[0] - else: - voice_channel = None + voice_channel, fromSlash, _ = isSlash(voice_channel) voice_channels = [] voice_channels.extend(ctx.guild.voice_channels) @@ -77,7 +70,7 @@ class School(commands.Cog): @commands.command(name='getid', hidden = True) async def _getid(self, ctx, fromSlash = None): """Tuto vidéo sur comment récupérer l'ID d'un utilisateur/salon⁢⁢⁢⁢⁢""" - if fromSlash == None: + if fromSlash != True: fromSlash = False if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 40f910f..c1ab702 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -5,7 +5,7 @@ from discord.ext import commands, tasks from random import randint, shuffle from discord_slash import cog_ext from utils.reminder import Reminder -from utils.core import map_list_among_us, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick, mentionToUser, getChangelogs +from utils.core import map_list_among_us, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick, mentionToUser, getChangelogs, isSlash from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString, timestampScreen, getAge, ageLayout, nowCustom def setup(client): @@ -20,16 +20,7 @@ class Utils(commands.Cog): @commands.command(name='ping') async def _ping(self, ctx, *arg): - """Affiche mon ping.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}ping [help]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - fromSlash = False - if len(arg) > 0: - if arg[-1] == True: - fromSlash = arg[-1] - arg = arg[:-1] - if len(arg) > 0: - arg = arg[0] - else: - arg = None + arg, fromSlash, _ = isSlash(arg) if arg == 'help': return await ctx.send(embed = discord.Embed(color = discord.Colour.random(), description = @@ -60,15 +51,7 @@ class Utils(commands.Cog): @commands.command(name='avatar') async def _avatar(self, ctx, *user): """Affiche ton avatar ou celui que tu mentionnes.\n ➡ Syntaxe: {PREFIX}avatar [user]""" - fromSlash = False - if len(user) > 0: - if user[-1] == True: - fromSlash = user[-1] - user = user[:-1] - if len(user) > 0: - user = user[0] - else: - user = None + user, fromSlash, _ = isSlash(user) if user == None: user = ctx.author @@ -90,14 +73,8 @@ class Utils(commands.Cog): @commands.command(name='calc') async def _calc(self, ctx, *calcul): """Calculatrice.\n ➡ Syntaxe: {PREFIX}calc ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - fromSlash = False - if len(calcul) > 0: - if calcul[-1] == True: - fromSlash = calcul[-1] - calcul = calcul[:-1] - if len(calcul) > 0: - calcul = calcul[0] - else: + calcul, fromSlash, _ = isSlash(calcul) + if calcul == None: raise ModuleNotFoundError equation = calcul.replace('^', '**').replace('x', '*').replace('×', '*').replace('÷', '/').replace('≥', '>=').replace('≤', '<=') @@ -137,8 +114,7 @@ class Utils(commands.Cog): await ctx.message.add_reaction(emoji = '✅') await ctx.send(embed = embed) @_calc.error - async def _calc_error(self, ctx, error): - print(error) + async def _calc_error(self, ctx, _): await ctx.send("Tu n'as pas spécifié de calcul.") @cog_ext.cog_slash(name="calc", description = "Calculatrice.") async def __calc(self, ctx, calcul): @@ -147,7 +123,7 @@ class Utils(commands.Cog): @commands.command(name='syntax') async def _syntax(self, ctx, fromSlash = None): """Informations pour bien éditer son texte.⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - if fromSlash == None: + if fromSlash != True: fromSlash = False separateur = "-----------------------------------------------------\n" syntaxe = separateur @@ -203,11 +179,7 @@ class Utils(commands.Cog): @commands.command(name='memo', aliases = ['note']) async def _memo(self, ctx, *text): """T'envoie un petit memo par message privé.\n ➡ Syntaxe: {PREFIX}memo/note ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - fromSlash = False - if len(text) > 0: - if text[-1] == True: - fromSlash = text[-1] - text = text[:-1] + _, fromSlash, text = isSlash(text) if len(text) > 0: text = " ".join(text) else: @@ -240,7 +212,7 @@ class Utils(commands.Cog): @commands.command(name='infos', aliases = ['info']) async def _infos(self, ctx, fromSlash = None): """Donne des infos sur le bot.\n ➡ Syntaxe: {PREFIX}infos/info⁢""" - if fromSlash == None: + if fromSlash != True: fromSlash = False appinfo = await self.client.application_info() @@ -290,11 +262,7 @@ class Utils(commands.Cog): @commands.command(name='amongus') async def _amongus(self, ctx, *map): """Affiche la carte voulue d'Among Us.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}amongus ⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - fromSlash = False - if len(map) > 0: - if map[-1] == True: - fromSlash = map[-1] - map = map[:-1] + _, fromSlash, map = isSlash(map) if len(map) > 0: map = " ".join(map) else: @@ -345,16 +313,13 @@ class Utils(commands.Cog): await ctx.message.add_reaction(emoji = '❓') @cog_ext.cog_slash(name="amongus", description = "Affiche la carte voulue d'Among Us. Carte dispo : ") async def __amongus(self, ctx, map): + ctx.prefix = "/" return await self._amongus(ctx, map, True) @commands.command(name='whois') async def _whois(self, ctx, *user: discord.Member): """Affiche les infos sur l'utilisateur.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}whois [user]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" - fromSlash = False - if len(user) > 0: - if user[-1] == True: - fromSlash = user[-1] - user = user[:-1] + _, fromSlash, user = isSlash(user) if len(user) <= 1: if user == (): @@ -390,17 +355,16 @@ class Utils(commands.Cog): @commands.command(name='sondage') async def _sondage(self, ctx, *args): """Fais un sondage.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}sondage "" "" "" "" """ - fromSlash = False - if len(args) > 0: - if args[-1] == True: - fromSlash = args[-1] - args = args[0] + _, fromSlash, args = isSlash(args) + if type(args[0]) == list: + args = args[0] args = list(args) if len(args) > 2: question = args[0] for i in findall(r'\d+', question): - question = cleanUser(ctx, question, i) + if len(str(i)) == 18: # id de 18 chiffres + question = cleanUser(ctx, question, i) propositions = args[1:] if len(propositions) <= 20: message = "" @@ -452,11 +416,9 @@ class Utils(commands.Cog): @commands.command(name='avis', aliases=['vote']) async def _avis(self, ctx, *args): """Demande un avis.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}avis/vote "[Titre]" "" """ - fromSlash = False - if len(args) > 0: - if args[-1] == True: - fromSlash = args[-1] - args = args[0] + _, fromSlash, args = isSlash(args) + if type(args[0]) == list: + args = args[0] args = list(args) if len(args) > 2 or len(args) == 0: @@ -486,11 +448,7 @@ class Utils(commands.Cog): @commands.command(name='reminder', aliases=["remind", "remindme", "rappel"]) async def _reminder(self, ctx, time, *reminder): """Met en place un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminder/remind/remindme/rappel [@] [message]""" - fromSlash = False - if len(reminder) > 0: - if reminder[-1] == True: - fromSlash = reminder[-1] - reminder = reminder[:-1] + _, fromSlash, reminder = isSlash(reminder) if len(reminder) > 0: reminder = " ".join(reminder) else: @@ -604,11 +562,7 @@ class Utils(commands.Cog): @commands.command(name='reminderlist', aliases=["remindlist", "rl", "rappeliste"]) async def _reminderlist(self, ctx, *utilisateur): """Affiche la liste des rappels d'un utilisateur.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminderlist/rl/remindlist/rappeliste [utilisateur]""" - fromSlash = False - if len(utilisateur) > 0: - if utilisateur[-1] == True: - fromSlash = utilisateur[-1] - utilisateur = utilisateur[:-1] + _, fromSlash, utilisateur = isSlash(utilisateur) if len(utilisateur) > 0: try: utilisateur = mentionToUser(getMentionInString(utilisateur[0])[0]) @@ -647,12 +601,8 @@ class Utils(commands.Cog): @commands.command(name='reminderdelete', aliases=["reminddelete", "rd"]) async def _reminderdelete(self, ctx, *id): """Suppprime un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminderdelete/rd """ - fromSlash = False - if len(id) > 0: - if id[-1] == True: - fromSlash = id[-1] - id = id[:-1] - if len(id) > 0: + id, fromSlash, _ = isSlash(id) + if id: try: id = int(id[0]) except: @@ -677,16 +627,10 @@ class Utils(commands.Cog): @commands.command(name='changelogs', aliases=["changelog", "changement", "changements"]) async def _changelogs(self, ctx, *version): """Affiche les changements de la dernière version ou d'une version précise.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}changelogs/changelog/changement/changements [version]""" - fromSlash = False - if len(version) > 0: - if version[-1] == True: - fromSlash = version[-1] - version = version[:-1] - if len(version) > 0: - version = version[0] - else: + version, fromSlash, _ = isSlash(version) + if not version: version = 'latest' - changes = getChangelogs(version) + changes = getChangelogs(version.replace(',', '.')) if changes == None or changes == 0: if fromSlash != True: await ctx.message.add_reaction(emoji = '❌') From c898c62a41577c275c31c077f5158d1af4d26636 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 24 Jun 2021 13:10:07 +0200 Subject: [PATCH 214/286] =?UTF-8?q?ajout=20des=20messages=20cach=C3=A9s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/fun.py | 6 +++--- src/cogs/games.py | 12 +++++++----- src/cogs/help.py | 10 +++++++--- src/cogs/internet.py | 8 ++++---- src/cogs/school.py | 10 +++++----- src/cogs/utils.py | 34 ++++++++++++++++++---------------- src/utils/core.py | 12 ++++++++++++ 7 files changed, 56 insertions(+), 36 deletions(-) diff --git a/src/cogs/fun.py b/src/cogs/fun.py index 196fdaf..0b51bff 100644 --- a/src/cogs/fun.py +++ b/src/cogs/fun.py @@ -3,7 +3,7 @@ from re import findall from discord.ext import commands from random import randint, choice from discord_slash import cog_ext -from utils.core import retirerDoublons, mentionToUser, isSlash +from utils.core import retirerDoublons, mentionToUser, isSlash, mySendHidden from utils.time import intToDatetime def setup(client): @@ -65,7 +65,7 @@ class Fun(commands.Cog): if users[0] == users[1]: if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') - return await ctx.send("Je suis sûr que cette personne s'aime ! :angry:") + return await mySendHidden(ctx, fromSlash, "Je suis sûr que cette personne s'aime ! :angry:") if users[0].nick: user1 = list(users[0].nick) else: @@ -177,7 +177,7 @@ class Fun(commands.Cog): try: n = int(n) except: - return await ctx.send("Veuillez renseigner un chiffre valide.") + return await mySendHidden(ctx, fromSlash, "Veuillez renseigner un chiffre valide.") else: n = 10 diff --git a/src/cogs/games.py b/src/cogs/games.py index a15804b..9b81e80 100644 --- a/src/cogs/games.py +++ b/src/cogs/games.py @@ -3,7 +3,7 @@ import asyncio from discord.ext import commands from random import randint, choice from discord_slash import cog_ext -from utils.core import isSlash +from utils.core import isSlash, mySendHidden def setup(client): client.add_cog(Games(client)) @@ -37,7 +37,7 @@ class Games(commands.Cog): elif choix == "ciseaux" or choix == "ciseau": choix = ciseaux else: - return await ctx.send("Je n'ai pas compris ce que tu as joué, réessaie.") + return await mySendHidden(ctx, fromSlash, "Je n'ai pas compris ce que tu as joué, réessaie.") description = (f"{choix_jeu[choix][:-1]} VS {choix_jeu[ordi][:-1]}\n\n**" f"{('Égalité !', 'Tu as perdu !', 'Tu as gagné !')[(choix != ordi) + ((choix > ordi and ordi +1 == choix) or (choix < ordi and choix + ordi == 2))]}**") @@ -55,10 +55,12 @@ class Games(commands.Cog): return await self._chifumi(ctx, choix, True) @commands.command(name='plusoumoins', aliases = ['+ou-', '+-']) - async def _plusoumoins(self, ctx): + async def _plusoumoins(self, ctx, fromSlash = None): """Un plus ou moins entre 1 et 100.\n ➡ Syntaxe: {PREFIX}plusoumoins/+ou-/+-⁢⁢⁢⁢⁢""" + if fromSlash != True: + fromSlash = False if str(ctx.author.id) in self.guessing_game: - return await ctx.send("Tu es déjà en partie.") + return await mySendHidden(ctx, fromSlash, "Tu es déjà en partie.") guess = 5 self.guessing_game[str(ctx.author.id)] = guess number = randint(1, 100) @@ -102,7 +104,7 @@ class Games(commands.Cog): await ctx.send(f"T'as pas trouvé {ctx.author.mention}... dommage, c'était {number}.") @cog_ext.cog_slash(name="plusoumoins", description = "Un plus ou moins entre 1 et 100.") async def __plusoumoins(self, ctx): - await self._plusoumoins(ctx) + await self._plusoumoins(ctx, True) @commands.command(name='pileouface', aliases=['pf']) async def _pileouface(self, ctx, fromSlash = None): diff --git a/src/cogs/help.py b/src/cogs/help.py index 2e83bfb..34297a1 100644 --- a/src/cogs/help.py +++ b/src/cogs/help.py @@ -1,7 +1,7 @@ import discord from discord.ext import commands from discord_slash import cog_ext -from utils.core import isSlash +from utils.core import isSlash, mySendHidden def setup(client): client.add_cog(Help(client)) @@ -17,6 +17,7 @@ class Help(commands.Cog): """Affiche toutes les commandes du bot.\n ➡ Syntaxe: {PREFIX}help [catégorie]⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" _, fromSlash, cog = isSlash(cog) + erreur = False if not cog: # Liste des Cog halp = discord.Embed(title = 'Liste des catégories et commandes sans catégorie', description = f'Utilisez `{ctx.prefix}help [catégorie]` pour en savoir plus sur elles et leur commande.', @@ -42,6 +43,7 @@ class Help(commands.Cog): await ctx.send(embed = halp) else: # Avertissement si il y a trop d'arguments dans la variable cog if len(cog) > 1: + await ctx.message.add_reaction(emoji = '❌') halp = discord.Embed(title = 'Erreur !', description = "Tu as renseigné trop d'arguments !", color = 0xC41B1B) await ctx.send(embed = halp) else: # Liste des commandes avec cogs. @@ -59,12 +61,14 @@ class Help(commands.Cog): halp.add_field(name = f"`{ctx.prefix}{c.name}` - {str(c.help).split(backslash)[0]}", value = f"{''.join(cmds_help)}\u200b", inline = False) found = True if not found: # Rappel si le cog n'existe pas. - await ctx.message.add_reaction(emoji = '❌') + if fromSlash != True: + await ctx.message.add_reaction(emoji = '❌') halp = discord.Embed(title = 'Erreur !', description = f"Qu'est ce que {cog[0]} ?", color = 0xC41B1B) + erreur = True else: if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') - await ctx.send('', embed = halp) + await mySendHidden(ctx, erreur, embed = halp) @cog_ext.cog_slash(name="help", description = "Affiche toutes les commandes du bot.") async def __help(self, ctx, cog = None): ctx.prefix = "/" diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 924da3f..52c2cb2 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -5,7 +5,7 @@ from discord.ext import commands from random import choice from asyncpraw import Reddit from discord_slash import cog_ext -from utils.core import randomImage, isSlash +from utils.core import randomImage, isSlash, mySendHidden def setup(client): client.add_cog(Internet(client)) @@ -29,7 +29,7 @@ class Internet(commands.Cog): '2meirl4meirl', 'AdviceAnimals', 'weirdmemes', 'LeagueOfMemes']) if fromSlash != None and subredditchoix == "nsfw": # demande de nsfw sans passé par la commande appropriée - return await ctx.send(f"Désolé, tu demandes du nsfw... Fais plutôt **{ctx.prefix}sexe**.") + return await mySendHidden(ctx, fromSlash, f"Désolé, tu demandes du nsfw... Fais plutôt **{ctx.prefix}sexe**.") try: async with Reddit(client_id = environ['TOKEN_REDDIT_CLIENT_ID'], client_secret = environ['TOKEN_REDDIT_CLIENT_SECRET'], user_agent = f"disreddit /u/{environ['TOKEN_REDDIT_USER_AGENT']}, http://localhost:8080") as reddit: @@ -65,7 +65,7 @@ class Internet(commands.Cog): print(f"Error in _memes command = args: {args}, subreddit: {subredditchoix}, error: {error}") if fromSlash != True: await ctx.message.add_reaction(emoji = '❌') - return await ctx.send(f"Ce subreddit est interdit, mis en quarantaine ou n'existe pas. ({subredditchoix})") + return await mySendHidden(ctx, fromSlash, f"Ce subreddit est interdit, mis en quarantaine ou n'existe pas. ({subredditchoix})") @cog_ext.cog_slash(name="meme", description = "Envoie un meme de reddit.") async def __memes(self, ctx, subreddit = None): ctx.prefix = "/" @@ -132,7 +132,7 @@ class Internet(commands.Cog): else: if fromSlash != True: await ctx.message.add_reaction(emoji = '❌') - await ctx.send(f"Désolé mais je n'envois ce genre de message seulement dans les salons NSFW !") + await mySendHidden(ctx, fromSlash, f"Désolé mais je n'envois ce genre de message seulement dans les salons NSFW !") @cog_ext.cog_slash(name="sexe", description = "Envois une image coquine. (NSFW)") async def __sexe(self, ctx): return await self._sexe(ctx, True) diff --git a/src/cogs/school.py b/src/cogs/school.py index a07e472..c54bde5 100644 --- a/src/cogs/school.py +++ b/src/cogs/school.py @@ -1,7 +1,7 @@ import discord from discord.ext import commands from discord_slash import cog_ext -from utils.core import isSlash +from utils.core import isSlash, mySendHidden def setup(client): client.add_cog(School(client)) @@ -23,14 +23,14 @@ class School(commands.Cog): await ctx.message.add_reaction(emoji = "✅") limite_voice_channels = 7 if len(voice_channels) > limite_voice_channels and not voice_channel: - return await ctx.send(f"""Désolé mais il y a plus de {limite_voice_channels} salons vocaux sur ce serveur, utilisez plutôt `{ctx.prefix}appel {{ID salon vocal}}`. + return await mySendHidden(ctx, fromSlash, f"""Désolé mais il y a plus de {limite_voice_channels} salons vocaux sur ce serveur, utilisez plutôt `{ctx.prefix}appel {{ID salon vocal}}`. \nPour savoir comment récuperer l'id d'un salon vous pouvez faire `{ctx.prefix}getid`.""") if voice_channel: canal = self.client.get_channel(voice_channel) if canal.type.__str__() == "voice": voice_channels = [canal] else: - return await ctx.send("Tu as spécifié un channel textuelle et non vocal.") + return await mySendHidden(ctx, fromSlash, "Tu as spécifié un channel textuelle et non vocal.") if len(voice_channels) > 0: embed = discord.Embed(title = "Réagissez à ce message avec ✋ pour signaler votre présence.", description = f"(attention, je réagis aussi) — Demandeur : {ctx.author.mention}") for channel in voice_channels: @@ -51,7 +51,7 @@ class School(commands.Cog): message = await ctx.send("Aucun salon vocal dans ce serveur, réagissez à ce message avec ✋ pour signaler votre présence (attention, je réagis aussi).") await message.add_reaction(emoji = "✋") @_appel.error - async def _appel_error(self, ctx, error): + async def _appel_error(self, ctx, _): # if isinstance(error, commands.CheckFailure): # await ctx.send("Tu n'as pas la permission de faire cette commande, demande à un professeur.") # else: @@ -74,7 +74,7 @@ class School(commands.Cog): fromSlash = False if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') - return await ctx.send("Explication sur comment récuperer l'ID d'un utilisateur/salon : https://cdn.discordapp.com/attachments/640312926892195842/780802253258358834/GetID.mp4") + return await mySendHidden(ctx, fromSlash, "Explication sur comment récuperer l'ID d'un utilisateur/salon : https://cdn.discordapp.com/attachments/640312926892195842/780802253258358834/GetID.mp4") @cog_ext.cog_slash(name="getid", description = "Tuto vidéo sur comment récupérer l'ID d'un utilisateur/salon⁢⁢⁢⁢⁢") async def __getid(self, ctx): return await self._getid(ctx, True) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index c1ab702..1b8144c 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -5,7 +5,8 @@ from discord.ext import commands, tasks from random import randint, shuffle from discord_slash import cog_ext from utils.reminder import Reminder -from utils.core import map_list_among_us, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick, mentionToUser, getChangelogs, isSlash +from utils.core import map_list_among_us, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick +from utils.core import mySendHidden, mentionToUser, getChangelogs, isSlash from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString, timestampScreen, getAge, ageLayout, nowCustom def setup(client): @@ -23,7 +24,7 @@ class Utils(commands.Cog): arg, fromSlash, _ = isSlash(arg) if arg == 'help': - return await ctx.send(embed = discord.Embed(color = discord.Colour.random(), description = + return await mySendHidden(ctx, fromSlash, embed = discord.Embed(color = discord.Colour.random(), description = ":hourglass: correspond au temps entre deux battements de cœurs\n\n \ :heartbeat: correspond au temps que met le client a réagir au messages (0 est normal lors de l'utilisation d'une commande slash)\n\n \ :stopwatch: correspond au temps que met le client a calculer le ping" @@ -96,9 +97,9 @@ class Utils(commands.Cog): else: answer = str(eval(equation)) except ZeroDivisionError: - return await ctx.send("Tu ne peux pas divisé par 0.") + return await mySendHidden(ctx, fromSlash, "Tu ne peux pas diviser par 0.") except TypeError: - return await ctx.send("Requête de calcul invalide.") + return await mySendHidden(ctx, fromSlash, "Requête de calcul invalide.") if '.' in answer: aftercomma = answer.split(".")[1] if len(aftercomma) > 2: @@ -171,7 +172,7 @@ class Utils(commands.Cog): await ctx.message.add_reaction(emoji = '✅') except: pass - await ctx.send(syntaxe) + await mySendHidden(ctx, fromSlash, syntaxe) @cog_ext.cog_slash(name="syntax", description = "Informations pour bien éditer son texte.") async def __syntax(self, ctx): return await self._syntax(ctx, True) @@ -188,11 +189,11 @@ class Utils(commands.Cog): if len(text) <= 5: if fromSlash != True: await ctx.message.add_reaction(emoji = '❌') - return await ctx.send("Ta note doit au moins faire 5 caractères.") + return await mySendHidden(ctx, fromSlash, "Ta note doit au moins faire 5 caractères.") elif len(text) >= 2048: if fromSlash != True: await ctx.message.add_reaction(emoji = '❌') - return await ctx.send("Ta note doit faire moins de 2048 caractères.") + return await ctx.send(ctx, fromSlash, message = "Ta note doit faire moins de 2048 caractères.") else: if fromSlash != True: await ctx.message.delete() @@ -200,7 +201,8 @@ class Utils(commands.Cog): embed.set_author(name = f"Mémo noté depuis {ctx.guild.name}", icon_url = ctx.author.avatar_url) embed.set_footer(text = f'📝 le {timestampScreen(intToDatetime(nowUTC()))}') await ctx.author.send(embed = embed) - return await ctx.send("Tu viens de recevoir ton mémo !", delete_after = 5) + + return await mySendHidden(ctx, fromSlash, "Tu viens de recevoir ton mémo !", delete_after = 5) @_memo.error async def _memo_error(self, ctx, error): if str(error) == "text is a required argument that is missing.": @@ -297,7 +299,7 @@ class Utils(commands.Cog): await ctx.message.add_reaction(emoji = '✅') await ctx.send(embed = embed) else: - await ctx.send(f"`{ctx.prefix}amongus `") + await mySendHidden(ctx, fromSlash, f"`{ctx.prefix}amongus `") @commands.command(name='among', hidden = True) async def _among(self, ctx, *, args = ""): """Raccourci à la commande amongus⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" @@ -475,7 +477,7 @@ class Utils(commands.Cog): if type(seconds) != int: if fromSlash != True: await ctx.message.add_reaction(emoji = '❓') - return await ctx.send(seconds) + return await mySendHidden(ctx, fromSlash, seconds) if seconds == 0: embed.add_field(name="Attention", value= "Format pour le temps : `d` ou `j` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (légères variances acceptés aussi). \ @@ -490,8 +492,8 @@ class Utils(commands.Cog): if fromSlash != True: messageID = ctx.message.id Reminder().ajoutReminder(messageID, ctx.channel.id, extrarg, reminder, now, now + seconds, ctx.author.id, guildID) - return await ctx.send(f"Ok, je t'en parles {destination} dans {timedeltaToString(seconds)} avec 1m de retard maximum.") - await ctx.send(embed = embed) + return await mySendHidden(ctx, fromSlash, f"Ok, je t'en parles {destination} dans {timedeltaToString(seconds)} avec 1m de retard maximum.") + await mySendHidden(ctx, fromSlash, embed = embed) @_reminder.error async def _reminder_error(self, ctx, error): if 'time is a required argument that is missing.' in str(error): @@ -567,7 +569,7 @@ class Utils(commands.Cog): try: utilisateur = mentionToUser(getMentionInString(utilisateur[0])[0]) except: - return await ctx.send("L'utilisateur renseigné n'a pas été trouvé.") + return await mySendHidden(ctx, fromSlash, "L'utilisateur renseigné n'a pas été trouvé.") else: utilisateur = ctx.author.id @@ -606,7 +608,7 @@ class Utils(commands.Cog): try: id = int(id[0]) except: - return await ctx.send("L'ID renseigné n'est pas valide.") + return await mySendHidden(ctx, fromSlash, "L'ID renseigné n'est pas valide.") else: return await ctx.send("Veuillez renseigner un ID.") @@ -619,7 +621,7 @@ class Utils(commands.Cog): else: if fromSlash != True: await ctx.message.add_reaction(emoji = '❌') - return await ctx.send("Rappel non trouvé, pas sur le bon serveur ou qui ne vous appartiens pas.") + return await mySendHidden(ctx, fromSlash, "Rappel non trouvé, pas sur le bon serveur ou qui ne vous appartiens pas.") @cog_ext.cog_slash(name="reminderdelete", description = "Suppprime un rappel.") async def __reminderdelete(self, ctx, id): return await self._reminderdelete(ctx, id, True) @@ -638,7 +640,7 @@ class Utils(commands.Cog): message = "Veuillez renseigner un numéro de version valide et existant." else: message = "Trop de requêtes sur l'API de Github, réessayez plus tard." - return await ctx.send(message) + return await mySendHidden(ctx, fromSlash, message) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') if len(changes[2]) > 2048: diff --git a/src/utils/core.py b/src/utils/core.py index fd3545d..eb1af2c 100644 --- a/src/utils/core.py +++ b/src/utils/core.py @@ -140,3 +140,15 @@ def isSlash(arg): arg = arg[0] return (arg, fromSlash, fullarg) + +async def mySendHidden( + ctx, fromSlash, message = None, tts = False, embed = None, file = None, files = None, + delete_after = None, allowed_mentions = None): + if fromSlash == True: # can't delete hidden message + await ctx.send( # sending hidden message + content = message, tts = tts, embed = embed, file = file, files = files, + delete_after = None, allowed_mentions = allowed_mentions, hidden = fromSlash) + else: + await ctx.send( # sending normal message + content = message, tts = tts, embed = embed, file = file, files = files, + delete_after = delete_after, allowed_mentions = allowed_mentions) From 1e27e1a5e9d7927ad2dec5f4e8561c34755cf342 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 24 Jun 2021 13:13:42 +0200 Subject: [PATCH 215/286] useless word --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 1b8144c..a9922da 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -193,7 +193,7 @@ class Utils(commands.Cog): elif len(text) >= 2048: if fromSlash != True: await ctx.message.add_reaction(emoji = '❌') - return await ctx.send(ctx, fromSlash, message = "Ta note doit faire moins de 2048 caractères.") + return await ctx.send(ctx, fromSlash, "Ta note doit faire moins de 2048 caractères.") else: if fromSlash != True: await ctx.message.delete() From 7306ab84ab560103611e79e012aa3f76a2346bb6 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 24 Jun 2021 13:17:20 +0200 Subject: [PATCH 216/286] message lors de la deconnexion --- src/main.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main.py b/src/main.py index 1ef1d68..9eb647f 100644 --- a/src/main.py +++ b/src/main.py @@ -19,6 +19,10 @@ print("Terminé !") async def on_connect(): print(f"Connecté !") +@client.event +async def on_disconnect(): + print(f"Déconnecté.") + @client.event async def on_ready(): await client.change_presence(status = discord.Status.online, activity = discord.Activity(name = f"{customPrefix}help", type = discord.ActivityType.playing)) From 21916b9935ead0175c7c661375125aacfb6b9719 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 24 Jun 2021 16:00:37 +0200 Subject: [PATCH 217/286] =?UTF-8?q?using=20lambda=20method=20bc=20it's=20s?= =?UTF-8?q?tyl=C3=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/games.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/cogs/games.py b/src/cogs/games.py index 9b81e80..3b17871 100644 --- a/src/cogs/games.py +++ b/src/cogs/games.py @@ -68,10 +68,7 @@ class Games(commands.Cog): await ctx.send(message) while self.guessing_game[str(ctx.author.id)] != 0: try: - def check(message): - if message.author.bot == False: - return str(message.author.id) in self.guessing_game - msg = await self.client.wait_for('message', check = check, timeout = 30) + msg = await self.client.wait_for('message', check = lambda message: str(message.author.id) in self.guessing_game if message.author.bot == False else None, timeout = 30) except asyncio.TimeoutError: del self.guessing_game[str(ctx.author.id)] return await ctx.send(f"Tu as mis trop de temps a répondre {ctx.author.mention}. La réponse était {number}.") From 79d81411663535f5e7c970685c7338f618cdef9e Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 24 Jun 2021 22:48:10 +0200 Subject: [PATCH 218/286] adding message when bot reconnect --- src/main.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main.py b/src/main.py index 9eb647f..52f00c7 100644 --- a/src/main.py +++ b/src/main.py @@ -23,6 +23,10 @@ async def on_connect(): async def on_disconnect(): print(f"Déconnecté.") +@client.event +async def on_resumed(): + print(f"Reconnecté !") + @client.event async def on_ready(): await client.change_presence(status = discord.Status.online, activity = discord.Activity(name = f"{customPrefix}help", type = discord.ActivityType.playing)) From b057da66273205df93dbe1323ed57c110b5692af Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 25 Jun 2021 22:14:47 +0200 Subject: [PATCH 219/286] =?UTF-8?q?ajout=20id=20de=2017=20chiffres=20et=20?= =?UTF-8?q?d=C3=A9placement=20du=20test=20dans=20la=20m=C3=A9thode=20clean?= =?UTF-8?q?User?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/utils.py | 3 +-- src/utils/core.py | 2 ++ 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index a9922da..6c5386c 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -365,8 +365,7 @@ class Utils(commands.Cog): if len(args) > 2: question = args[0] for i in findall(r'\d+', question): - if len(str(i)) == 18: # id de 18 chiffres - question = cleanUser(ctx, question, i) + question = cleanUser(ctx, question, i) propositions = args[1:] if len(propositions) <= 20: message = "" diff --git a/src/utils/core.py b/src/utils/core.py index eb1af2c..d4d23b7 100644 --- a/src/utils/core.py +++ b/src/utils/core.py @@ -26,6 +26,8 @@ def userOrNick(user): def cleanUser(ctx, stringMessage, stringID): """récupère l'utilisateur avec son id""" stringMessage = stringMessage.replace("<@!", "").replace(">", "").replace("<@", "") # améliorer ça avec du regex + if len(str(stringMessage)) not in (17, 18): # si ce n'est pas un ID valide + return stringMessage associatedID = userOrNick(ctx.author.guild.get_member(int(stringID))) try: stringMessage = stringMessage.replace(stringID, associatedID) From 637e6102cc3b6a4061f008b3ae381ce7528e67cf Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 28 Jun 2021 12:38:11 +0200 Subject: [PATCH 220/286] new command minecraft to get color code ig --- src/cogs/utils.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 6c5386c..9eba40d 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -653,3 +653,15 @@ class Utils(commands.Cog): return await self._changelogs(ctx, True) else: return await self._changelogs(ctx, version, True) + + @commands.command(name='minecraft', aliases=["codecouleurminecraft", "minecraftcodecouleur"]) + async def _minecraft(self, ctx, fromSlash = None): + """Affiche le code couleur utilisé dans Minecraft.\n ➡ Syntaxe: {PREFIX}minecraft/codecouleurminecraft/minecraftcodecouleur""" + if fromSlash != True: + fromSlash = False + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + return await ctx.send("https://imgr.search.brave.com/5-k6Lgh0OyRI8IVwhiBrNRmlY94utGxSX0k9tvtpqiA/fit/590/150/no/1/aHR0cDovL2kuaW1n/dXIuY29tL3Azd2lz/OVAucG5n") + @cog_ext.cog_slash(name="minecraft", description = "Affiche le code couleur utilisé dans Minecraft.") + async def __minecraft(self, ctx): + return await self._minecraft(ctx, True) From 074d55783ab12206e80caa4b9fd0026acc26cf8c Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 2 Jul 2021 20:11:11 +0200 Subject: [PATCH 221/286] ajout taille image --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4a807b1..4c4135f 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,9 @@ [![Version](https://img.shields.io/badge/version-1.5-green?style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/releases/latest) [![Docker Stars](https://img.shields.io/docker/stars/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/r/mylloon/kassoubot) [![Docker Pulls](https://img.shields.io/docker/pulls/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/r/mylloon/kassoubot) -[![Github stars](https://img.shields.io/github/stars/Confrerie-du-Kassoulait/kassoubot?label=Github%20Stars&style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/stargazers) -[![Github forks](https://img.shields.io/github/forks/Confrerie-du-Kassoulait/KassouBot?label=Github%20Forks&style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/network) +[![Docker Image Size](https://img.shields.io/docker/image-size/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/r/mylloon/kassoubot) +[![Github Stars](https://img.shields.io/github/stars/Confrerie-du-Kassoulait/kassoubot?label=Github%20Stars&style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/stargazers) +[![Github Forks](https://img.shields.io/github/forks/Confrerie-du-Kassoulait/KassouBot?label=Github%20Forks&style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/network) ## __Setting up__ You have to replace `TOKEN_DISCORD`, `PREFIX`, `TOKEN_GENIUS`, `TOKEN_REDDIT_CLIENT_ID`, `TOKEN_REDDIT_CLIENT_SECRET`, `TOKEN_REDDIT_USER_AGENT` and [`TIMEZONE`](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) with your desired values. You must also specify a path to the folder where the database will be.\ From 84d367818908d46327fc8289f069bc414e261528 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 01:08:44 +0200 Subject: [PATCH 222/286] Update for Gitlab --- README.md | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 4c4135f..83adbce 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,7 @@ # Bot developed with [discord.py](https://github.com/Rapptz/discord.py) (rewrite) - FRENCH -[![Version](https://img.shields.io/badge/version-1.5-green?style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/releases/latest) -[![Docker Stars](https://img.shields.io/docker/stars/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/r/mylloon/kassoubot) -[![Docker Pulls](https://img.shields.io/docker/pulls/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/r/mylloon/kassoubot) -[![Docker Image Size](https://img.shields.io/docker/image-size/mylloon/kassoubot?style=for-the-badge)](https://hub.docker.com/r/mylloon/kassoubot) -[![Github Stars](https://img.shields.io/github/stars/Confrerie-du-Kassoulait/kassoubot?label=Github%20Stars&style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/stargazers) -[![Github Forks](https://img.shields.io/github/forks/Confrerie-du-Kassoulait/KassouBot?label=Github%20Forks&style=for-the-badge)](https://github.com/Confrerie-du-Kassoulait/KassouBot/network) +[![Version](https://img.shields.io/badge/version-1.5-green?style=for-the-badge)](https://gitlab.com/ConfrerieDuKassoulait/KassouBot/-/releases) +[![Build](https://img.shields.io/gitlab/pipeline/ConfrerieDuKassoulait/KassouBot/main?style=for-the-badge)](https://gitlab.com/ConfrerieDuKassoulait/KassouBot/container_registry) ## __Setting up__ You have to replace `TOKEN_DISCORD`, `PREFIX`, `TOKEN_GENIUS`, `TOKEN_REDDIT_CLIENT_ID`, `TOKEN_REDDIT_CLIENT_SECRET`, `TOKEN_REDDIT_USER_AGENT` and [`TIMEZONE`](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) with your desired values. You must also specify a path to the folder where the database will be.\ From ede3b27046f6bde353ddfc966e423697274aa3c1 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 01:08:51 +0200 Subject: [PATCH 223/286] Build Image --- .gitlab-ci.yml | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 .gitlab-ci.yml diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..c5633ea --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,65 @@ +############################################################### +# Setting I use for cleaning up image tags # +# - Running cleanup every day # +# - Keeping 1 tag per image name matching : (?:v.+|dev) # +# - Removing tags older than 7 days matching the default : .* # +############################################################### + +image: docker:stable + +stages: + - build + - push + +services: + - docker:dind + +before_script: + - echo -n $CI_JOB_TOKEN | docker login -u gitlab-ci-token --password-stdin $CI_REGISTRY + +Build: + stage: build + script: + - docker pull $CI_REGISTRY_IMAGE:latest || true + - > + docker build + --pull + --build-arg VCS_REF=$CI_COMMIT_SHA + --build-arg VCS_URL=$CI_PROJECT_URL + --cache-from $CI_REGISTRY_IMAGE:latest + --tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA + . + - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA + +Push latest: + variables: + GIT_STRATEGY: none + stage: push + only: + - main + script: + - docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA + - docker tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA $CI_REGISTRY_IMAGE:latest + - docker push $CI_REGISTRY_IMAGE:latest + +Push dev: + variables: + GIT_STRATEGY: none + stage: push + only: + - dev + script: + - docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA + - docker tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA $CI_REGISTRY_IMAGE:dev + - docker push $CI_REGISTRY_IMAGE:dev + +Push tag: + variables: + GIT_STRATEGY: none + stage: push + only: + - tags + script: + - docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA + - docker tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME + - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME From ef84f8ded18b73d1b8a33f68b28eefe30d25d409 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 01:18:43 +0200 Subject: [PATCH 224/286] useless file --- CODE_OF_CONDUCT.md | 128 --------------------------------------------- 1 file changed, 128 deletions(-) delete mode 100644 CODE_OF_CONDUCT.md diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index 18c9147..0000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,128 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, religion, or sexual identity -and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. - -## Our Standards - -Examples of behavior that contributes to a positive environment for our -community include: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the - overall community - -Examples of unacceptable behavior include: - -* The use of sexualized language or imagery, and sexual attention or - advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email - address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official e-mail address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -. -All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. - -## Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: - -### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series -of actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or -permanent ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within -the community. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.0, available at -https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. - -Community Impact Guidelines were inspired by [Mozilla's code of conduct -enforcement ladder](https://github.com/mozilla/diversity). - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see the FAQ at -https://www.contributor-covenant.org/faq. Translations are available at -https://www.contributor-covenant.org/translations. From 06ebf2bb1ca227bfd825e1a56f7c5b3f353bb59b Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 01:19:13 +0200 Subject: [PATCH 225/286] using new docker image --- README.md | 4 ++-- docker-compose.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 83adbce..8428119 100644 --- a/README.md +++ b/README.md @@ -5,12 +5,12 @@ ## __Setting up__ You have to replace `TOKEN_DISCORD`, `PREFIX`, `TOKEN_GENIUS`, `TOKEN_REDDIT_CLIENT_ID`, `TOKEN_REDDIT_CLIENT_SECRET`, `TOKEN_REDDIT_USER_AGENT` and [`TIMEZONE`](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) with your desired values. You must also specify a path to the folder where the database will be.\ -With a [docker-compose](https://github.com/Confrerie-du-Kassoulait/KassouBot/blob/master/docker-compose.yml) or in command line: +With a [docker-compose](https://gitlab.com/ConfrerieDuKassoulait/KassouBot/-/blob/main/docker-compose.yml) or in command line: ``` docker run -d \ --name="KassouBot" \ - index.docker.io/mylloon/kassoubot \ + registry.gitlab.com/confreriedukassoulait/kassoubot \ --TOKEN_DISCORD="yourTokenDiscord" \ --TOKEN_GENIUS="yourTokenGenius" \ --TOKEN_REDDIT_CLIENT_ID="yourRedditClientID" \ diff --git a/docker-compose.yml b/docker-compose.yml index fc49407..40001f6 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,7 +1,7 @@ version: "2.1" services: kassoubot: - image: index.docker.io/mylloon/kassoubot + image: registry.gitlab.com/confreriedukassoulait/kassoubot container_name: KassouBot environment: - TOKEN_DISCORD=yourTokenDiscord From 604be563826f7d7e9e90f9d6d47920358404ee61 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 01:19:19 +0200 Subject: [PATCH 226/286] using gitlab --- src/cogs/utils.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 9eba40d..6ad36bf 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -238,17 +238,17 @@ class Utils(commands.Cog): with open(path.join(path.dirname(path.dirname(path.dirname(__file__))), "README.md"), "r") as file: version = findall(r'https://img.shields.io/badge/version-(\d+\.\d+)', file.readlines()[2])[0] - embed.add_field(name = "Dev", value = f"[{appinfo.owner}](https://github.com/Mylloon)") + embed.add_field(name = "Dev", value = f"[{appinfo.owner}](https://gitlab.com/Mylloon)") embed.add_field(name = f"Serveur{'s' if nombreServeur > 1 else ''}", value = f"`{nombreServeur}`") embed.add_field(name = f"Membre{'s' if total_unique > 1 else ''}", value = f"`{total_unique}` au total\n`{total_online}` en ligne") embed.add_field(name = f"Salon{'s' if (text + voice) > 1 else ''}", value = f"`{text}` textuel{'s' if text > 1 else ''}\n`{voice}` voca{'ux' if voice > 1 else 'l'}") embed.add_field(name = "Prefix", value = f"`{ctx.prefix}`") - embed.add_field(name = "Code source", value = "[Lien Github](https://github.com/Confrerie-du-Kassoulait/KassouBot/)") + embed.add_field(name = "Code source", value = "[Lien Gitlab](https://gitlab.com/ConfrerieDuKassoulait/KassouBot)") embed.add_field(name = "Timezone", value = f"`{self.customTimezone}`") embed.add_field(name = "Version", value = f"`{version}`") changes = getChangelogs(version) if changes != None and changes != 0: - embed.add_field(name = "Changements", value = f"[Lien Github]({changes[0]})") + embed.add_field(name = "Changements", value = f"[Lien Gitlab]({changes[0]})") embed.set_footer(text = f"Basé sur discord.py {discord.__version__}") try: if fromSlash != True: From b15c73554d825239c441ecb61c113ba8374ef55f Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 01:22:02 +0200 Subject: [PATCH 227/286] using dev cache --- .gitlab-ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index c5633ea..4bb615a 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -20,13 +20,13 @@ before_script: Build: stage: build script: - - docker pull $CI_REGISTRY_IMAGE:latest || true + - docker pull $CI_REGISTRY_IMAGE:dev || true - > docker build --pull --build-arg VCS_REF=$CI_COMMIT_SHA --build-arg VCS_URL=$CI_PROJECT_URL - --cache-from $CI_REGISTRY_IMAGE:latest + --cache-from $CI_REGISTRY_IMAGE:dev --tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA . - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA From 49c3f53f420dea248448e19ac57cdbb8d1f0f9a6 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 01:29:59 +0200 Subject: [PATCH 228/286] check dev branch for build badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8428119..0281955 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Bot developed with [discord.py](https://github.com/Rapptz/discord.py) (rewrite) - FRENCH [![Version](https://img.shields.io/badge/version-1.5-green?style=for-the-badge)](https://gitlab.com/ConfrerieDuKassoulait/KassouBot/-/releases) -[![Build](https://img.shields.io/gitlab/pipeline/ConfrerieDuKassoulait/KassouBot/main?style=for-the-badge)](https://gitlab.com/ConfrerieDuKassoulait/KassouBot/container_registry) +[![Build](https://img.shields.io/gitlab/pipeline/ConfrerieDuKassoulait/KassouBot/dev?style=for-the-badge)](https://gitlab.com/ConfrerieDuKassoulait/KassouBot/container_registry) ## __Setting up__ You have to replace `TOKEN_DISCORD`, `PREFIX`, `TOKEN_GENIUS`, `TOKEN_REDDIT_CLIENT_ID`, `TOKEN_REDDIT_CLIENT_SECRET`, `TOKEN_REDDIT_USER_AGENT` and [`TIMEZONE`](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) with your desired values. You must also specify a path to the folder where the database will be.\ From 66c2e2c2411fa564285abbdb1c9e98870dcaa0b2 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 03:05:41 +0200 Subject: [PATCH 229/286] change gitlab changelogs + new loading of env variables --- src/utils/core.py | 49 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 34 insertions(+), 15 deletions(-) diff --git a/src/utils/core.py b/src/utils/core.py index d4d23b7..38617e5 100644 --- a/src/utils/core.py +++ b/src/utils/core.py @@ -1,7 +1,9 @@ -import re import json import requests +from re import findall from time import time +from os import environ, path +from dotenv import load_dotenv def map_list_among_us(map): """Sélecteur de map pour la commande amongus⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" @@ -53,7 +55,7 @@ def cleanCodeStringWithMentionAndURLs(string): def getMentionInString(string): """récupère les mentions dans un string⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" findedMention = [] - for findingMention in re.findall(r'<@[!]?\d*>', string): # récupération mention dans le string + for findingMention in findall(r'<@[!]?\d*>', string): # récupération mention dans le string findedMention.append(findingMention) findedMention = list(dict.fromkeys(findedMention)) # suppression doublon de mention dans la liste return findedMention @@ -61,7 +63,7 @@ def getMentionInString(string): def getURLsInString(string): """récupère les liens dans un string""" findedURLs = [] - for findingMention in re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', string): # récupération URLs dans le string + for findingMention in findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', string): # récupération URLs dans le string findedURLs.append(findingMention) return findedURLs @@ -114,19 +116,23 @@ def mentionToUser(mention: str): """Récupère une mention et renvois son ID""" return int(mention[2:-1].replace("!","")) -def getChangelogs(version = 'latest'): +def getChangelogs(version = 'actual'): """Récupère les changements d'une version (par défaut, la dernière en date) et renvois dans l'ordre : url, n° version, changements""" - if version != 'latest': - version = f'tags/v{version}' - changements = requests.get(f"https://api.github.com/repos/Confrerie-du-Kassoulait/KassouBot/releases/{version}").json() - try: - if changements["message"].startswith("API"): # renvois 0 si c'est une erreur API - return 0 - else: # renvois None si aucune version correspondante n'a été trouvée - return None - except: - pass - return [changements["html_url"], changements["tag_name"][1:], changements["body"]] + if version == 'actual': + version = getActualVersion() + changements = requests.get(f"https://gitlab.com/api/v4/projects/28424435/releases/v{version}") + + if changements.status_code != 200: # si pas valide + return [changements.status_code] + else: + code = 200 + + changements = changements.json() + return [code, changements["_links"]["self"], changements["tag_name"][1:], changements["description"]] + +def getActualVersion(): + with open(path.join(path.dirname(path.dirname(path.dirname(__file__))), "README.md"), "r") as file: + return findall(r'https://img.shields.io/badge/version-(\d+\.\d+)', file.readlines()[2])[0] def isSlash(arg): """Regarde si la commande viens d'un slash ou pas, retourne l'argument sans le 'True' si c'est le cas""" @@ -154,3 +160,16 @@ async def mySendHidden( await ctx.send( # sending normal message content = message, tts = tts, embed = embed, file = file, files = files, delete_after = delete_after, allowed_mentions = allowed_mentions) + +def load(variables): + """Load env variables""" + keys = {} + load_dotenv() # load .env file + for var in variables: + try: + keys[var] = environ[var] + except KeyError: + print(f"Please set the environment variable {var} (.env file supported)") + exit(1) + + return keys From 54bee59aa80f3103a8ce2ca136b990acb98a9ce5 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 03:17:37 +0200 Subject: [PATCH 230/286] using new .env system --- .gitignore | 2 +- README.md | 2 +- requirements.txt | 1 + src/cogs/internet.py | 6 +++--- src/cogs/music.py | 6 +++--- src/main.py | 8 +++++--- src/utils/time.py | 4 ++-- 7 files changed, 16 insertions(+), 13 deletions(-) diff --git a/.gitignore b/.gitignore index 0196d05..b59abca 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ .vscode/ update/ __pycache__/ -.envrc +.env *.sqlite3 diff --git a/README.md b/README.md index 0281955..b161e72 100644 --- a/README.md +++ b/README.md @@ -38,5 +38,5 @@ To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and - Using SQLite for the database. ## __Launching locally__ -If you want to run it without Docker, I personally use [direnv](https://direnv.net/) to store variables and have them only in the working folder. +If you want to run it without Docker, create an .env file to store variables in the root folder. Simply run `python3 main.py` in `src` folder to launch the bot in the repo folder. diff --git a/requirements.txt b/requirements.txt index faa329d..cb82009 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,3 +5,4 @@ youtube-dl==2021.6.6 # music lyricsgenius==3.0.1 # lyrics feedparser==6.0.8 # rss feed (news) discord-py-slash-command==2.0.1 # slash commands +python_dotenv==0.19.0 # using .env file diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 52c2cb2..8f7acb0 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -1,11 +1,10 @@ import discord from feedparser import parse -from os import environ from discord.ext import commands from random import choice from asyncpraw import Reddit from discord_slash import cog_ext -from utils.core import randomImage, isSlash, mySendHidden +from utils.core import randomImage, isSlash, mySendHidden, load def setup(client): client.add_cog(Internet(client)) @@ -14,6 +13,7 @@ class Internet(commands.Cog): """Commandes relatives à ce qui provient d'internet.""" def __init__(self, client): self.client = client + self.keys = load(["TOKEN_REDDIT_CLIENT_ID", "TOKEN_REDDIT_CLIENT_SECRET", "TOKEN_REDDIT_USER_AGENT"]) @commands.command(name='memes', aliases = ['meme']) async def _memes(self, ctx, *args): @@ -32,7 +32,7 @@ class Internet(commands.Cog): return await mySendHidden(ctx, fromSlash, f"Désolé, tu demandes du nsfw... Fais plutôt **{ctx.prefix}sexe**.") try: - async with Reddit(client_id = environ['TOKEN_REDDIT_CLIENT_ID'], client_secret = environ['TOKEN_REDDIT_CLIENT_SECRET'], user_agent = f"disreddit /u/{environ['TOKEN_REDDIT_USER_AGENT']}, http://localhost:8080") as reddit: + async with Reddit(client_id = self.keys['TOKEN_REDDIT_CLIENT_ID'], client_secret = self.keys['TOKEN_REDDIT_CLIENT_SECRET'], user_agent = f"disreddit /u/{self.keys['TOKEN_REDDIT_USER_AGENT']}, http://localhost:8080") as reddit: subreddit = await reddit.subreddit(subredditchoix) # récupération du subreddit hot = subreddit.top(limit = 20) # récupération des memes avec une limite aux 10 premiers memes all_subs = [item async for item in hot] # liste des memes diff --git a/src/cogs/music.py b/src/cogs/music.py index 2320c8d..d7a75cd 100644 --- a/src/cogs/music.py +++ b/src/cogs/music.py @@ -19,10 +19,10 @@ from discord.ext import commands # Genius API from lyricsgenius import Genius -from os import environ -from utils.core import ligneFormatage, userOrNick +from utils.core import ligneFormatage, userOrNick, load from utils.time import nowCustom -genius = Genius(environ['TOKEN_GENIUS']) + +genius = Genius(load(["TOKEN_GENIUS"])["TOKEN_GENIUS"]) # Silence useless bug reports messages youtube_dl.utils.bug_reports_message = lambda: '' diff --git a/src/main.py b/src/main.py index 52f00c7..0591b55 100644 --- a/src/main.py +++ b/src/main.py @@ -1,11 +1,13 @@ print("Chargement des extensions & librairie...", end = " ") import discord -from os import environ, listdir +from os import listdir from discord_slash import SlashCommand from discord.ext import commands from utils.reminder import Reminder -customPrefix = environ['PREFIX'] +from utils.core import load +keys = load(["PREFIX", "TOKEN_DISCORD"]) +customPrefix = keys["PREFIX"] client = commands.Bot(command_prefix = customPrefix, case_insensitive = True, intents = discord.Intents.all()) slash = SlashCommand(client, sync_commands = True) @@ -54,4 +56,4 @@ async def on_message(message): await ctx.send(f">>> Coucou !\nMon préfix est `{prefix}` et ma commande d'aide est `{prefix}help`") print("Connexion à Discord...", end = " ") -client.run(environ['TOKEN_DISCORD']) +client.run(keys["TOKEN_DISCORD"]) diff --git a/src/utils/time.py b/src/utils/time.py index bc99ef6..a293d51 100644 --- a/src/utils/time.py +++ b/src/utils/time.py @@ -1,9 +1,9 @@ -from os import environ from pytz import timezone from datetime import datetime, timedelta from re import findall +from utils.core import load -myTimezone = environ['TIMEZONE'] +myTimezone = load(["TIMEZONE"])["TIMEZONE"] def stringTempsVersSecondes(time): """Convertis une durée rentrée par un utilisateur en string vers des secondes en int""" From 155ff9244e7b578e82a9589150ebab624ee63518 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 03:24:53 +0200 Subject: [PATCH 231/286] using new gitlab webhook --- src/cogs/confreriedukassoulait.py | 49 ++++++++++++++++--------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/src/cogs/confreriedukassoulait.py b/src/cogs/confreriedukassoulait.py index 45b51ed..a1be41b 100644 --- a/src/cogs/confreriedukassoulait.py +++ b/src/cogs/confreriedukassoulait.py @@ -51,37 +51,40 @@ class ConfrerieDuKassoulait(commands.Cog): @commands.Cog.listener() async def on_message_delete(self, message): - if message.author.guild.id == 441208120644075520: # Confrérie du Kassoulait - prefix = await self.client.get_prefix(message) - if not ( - message.content.startswith(f"{prefix}note") or - message.content.startswith(f"{prefix}memo") or - len(findall(".com/channels/", message.content)) != 0 or - self.client.user.id is message.author.id - ): - user_suppressed = None + try: + if message.author.guild.id == 441208120644075520: # Confrérie du Kassoulait + prefix = await self.client.get_prefix(message) + if not ( + message.content.startswith(f"{prefix}note") or + message.content.startswith(f"{prefix}memo") or + len(findall(".com/channels/", message.content)) != 0 or + self.client.user.id is message.author.id + ): + user_suppressed = None - async for entry in message.guild.audit_logs(limit=1): - if (intToDatetime(nowCustom()) - entry.created_at).seconds < 5 and str(entry.action) == 'AuditLogAction.message_delete': - user_suppressed = entry.user + async for entry in message.guild.audit_logs(limit=1): + if (intToDatetime(nowCustom()) - entry.created_at).seconds < 5 and str(entry.action) == 'AuditLogAction.message_delete': + user_suppressed = entry.user - channel = self.client.get_channel(742588187456831659) - embed = discord.Embed(description = f"{message.content}") + channel = self.client.get_channel(742588187456831659) + embed = discord.Embed(description = f"{message.content}") - embed.set_author(name = userOrNick(message.author), icon_url = message.author.avatar_url) + embed.set_author(name = userOrNick(message.author), icon_url = message.author.avatar_url) - if not user_suppressed: - embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {timestampScreen(message.created_at)}\nSupprimé le {timestampScreen(intToDatetime(nowUTC()))}") - else: - embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {timestampScreen(message.created_at)}\nSupprimé par {userOrNick(user_suppressed)} le {timestampScreen(intToDatetime(nowUTC()))}") + if not user_suppressed: + embed.set_footer(text = f"Channel: #{message.channel.name} | Date : {timestampScreen(message.created_at)}\nSupprimé le {timestampScreen(intToDatetime(nowUTC()))}") + else: + embed.set_footer(icon_url = user_suppressed.avatar_url, text = f"Channel: #{message.channel.name} | Date : {timestampScreen(message.created_at)}\nSupprimé par {userOrNick(user_suppressed)} le {timestampScreen(intToDatetime(nowUTC()))}") - await channel.send(embed = embed) - # ne fonctionne pas quand un message a été supprimé avant que le bot ai démarré - # info sur la personne qui a supprimé ne fonctionne pas si il a supprimé un message auparavant (les logs se rajoute a un log deja existant) + await channel.send(embed = embed) + # ne fonctionne pas quand un message a été supprimé avant que le bot ai démarré + # info sur la personne qui a supprimé ne fonctionne pas si il a supprimé un message auparavant (les logs se rajoute a un log deja existant) + except: # ignore error when deleting webhook message + pass @commands.Cog.listener() async def on_message(self, message): - if message.author.id == 786897204816117771 and message.author.name == "GitHub" and message.author.bot: # Autopublish + if message.author.id == 869726667294248970 and message.author.bot: # Autopublish await message.publish() # autre serveur From 92fe7a0e92adf202a7fe30084b3d5b3695e8cae0 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 03:26:21 +0200 Subject: [PATCH 232/286] change gitlab changelogs + new loading of env variables part. 2 --- src/cogs/utils.py | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 6ad36bf..d95618e 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -1,12 +1,10 @@ import discord -from os import environ, path -from re import findall from discord.ext import commands, tasks from random import randint, shuffle from discord_slash import cog_ext from utils.reminder import Reminder from utils.core import map_list_among_us, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick -from utils.core import mySendHidden, mentionToUser, getChangelogs, isSlash +from utils.core import mySendHidden, mentionToUser, getChangelogs, getActualVersion, isSlash, load from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString, timestampScreen, getAge, ageLayout, nowCustom def setup(client): @@ -16,7 +14,7 @@ class Utils(commands.Cog): """Commandes essentielles.""" def __init__(self, client): self.client = client - self.customTimezone = environ['TIMEZONE'] + self.customTimezone = load(["TIMEZONE"])["TIMEZONE"] self._reminderLoop.start() @commands.command(name='ping') @@ -235,8 +233,7 @@ class Utils(commands.Cog): voice = len(voice_channels) nombreServeur = len(self.client.guilds) - with open(path.join(path.dirname(path.dirname(path.dirname(__file__))), "README.md"), "r") as file: - version = findall(r'https://img.shields.io/badge/version-(\d+\.\d+)', file.readlines()[2])[0] + version = getActualVersion() embed.add_field(name = "Dev", value = f"[{appinfo.owner}](https://gitlab.com/Mylloon)") embed.add_field(name = f"Serveur{'s' if nombreServeur > 1 else ''}", value = f"`{nombreServeur}`") @@ -247,8 +244,8 @@ class Utils(commands.Cog): embed.add_field(name = "Timezone", value = f"`{self.customTimezone}`") embed.add_field(name = "Version", value = f"`{version}`") changes = getChangelogs(version) - if changes != None and changes != 0: - embed.add_field(name = "Changements", value = f"[Lien Gitlab]({changes[0]})") + if changes[0] == 200: + embed.add_field(name = "Changements", value = f"[Lien Gitlab]({changes[1]})") embed.set_footer(text = f"Basé sur discord.py {discord.__version__}") try: if fromSlash != True: @@ -630,22 +627,25 @@ class Utils(commands.Cog): """Affiche les changements de la dernière version ou d'une version précise.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}changelogs/changelog/changement/changements [version]""" version, fromSlash, _ = isSlash(version) if not version: - version = 'latest' + version = 'actual' changes = getChangelogs(version.replace(',', '.')) - if changes == None or changes == 0: + if changes[0] != 200: if fromSlash != True: await ctx.message.add_reaction(emoji = '❌') - if changes == None: - message = "Veuillez renseigner un numéro de version valide et existant." + if changes[0] == 404: + message = "Veuillez renseigner un numéro de version valide et existant. Peut-être que vous utilisez une version de développement." + elif changes[0] == 429: + message = "Trop de requêtes sur l'API de Gitlab, réessayez plus tard." else: - message = "Trop de requêtes sur l'API de Github, réessayez plus tard." + message = f"Erreur API inconnue ({changes[0]})." return await mySendHidden(ctx, fromSlash, message) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') - if len(changes[2]) > 2048: - changes[2] = f"{changes[2][:1900]}..." - embed = discord.Embed(description = f"[lien vers la page Github]({changes[0]})\n\n{changes[2]}", color = discord.Colour.random()) - embed.set_author(name = f"Changements de la v{changes[1]}") + changements = changes[3].replace("## ", "◦ ").replace("# ", "• ") + if len(changements) > 2048: + changements = f"{changements[:1900]}..." + embed = discord.Embed(description = f"[lien vers la page Gitlab]({changes[1]})\n\n{changements}", color = discord.Colour.random()) + embed.set_author(name = f"Changements de la v{changes[2]}") await ctx.send(embed = embed) @cog_ext.cog_slash(name="changelogs", description = "Affiche les changements de la dernière version ou d'une version précise.") async def __changelogs(self, ctx, version = None): From 16fd995e96e872813beee1c221b2188d949da92d Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 13:34:23 +0200 Subject: [PATCH 233/286] Better changelogs display in infos command + difference between host and dev --- src/cogs/utils.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index d95618e..000b9e2 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -235,17 +235,21 @@ class Utils(commands.Cog): version = getActualVersion() - embed.add_field(name = "Dev", value = f"[{appinfo.owner}](https://gitlab.com/Mylloon)") + dev = self.client.get_user(158260864623968257) + + embed.add_field(name = "Dev", value = f"[{dev.name}](https://gitlab.com/Mylloon)") + embed.add_field(name = "Host", value = appinfo.owner.mention) embed.add_field(name = f"Serveur{'s' if nombreServeur > 1 else ''}", value = f"`{nombreServeur}`") embed.add_field(name = f"Membre{'s' if total_unique > 1 else ''}", value = f"`{total_unique}` au total\n`{total_online}` en ligne") embed.add_field(name = f"Salon{'s' if (text + voice) > 1 else ''}", value = f"`{text}` textuel{'s' if text > 1 else ''}\n`{voice}` voca{'ux' if voice > 1 else 'l'}") embed.add_field(name = "Prefix", value = f"`{ctx.prefix}`") embed.add_field(name = "Code source", value = "[Lien Gitlab](https://gitlab.com/ConfrerieDuKassoulait/KassouBot)") embed.add_field(name = "Timezone", value = f"`{self.customTimezone}`") - embed.add_field(name = "Version", value = f"`{version}`") changes = getChangelogs(version) + version = f"`{getActualVersion()}`" if changes[0] == 200: - embed.add_field(name = "Changements", value = f"[Lien Gitlab]({changes[1]})") + version = f"[{version}]({changes[1]})" + embed.add_field(name = "Version", value = version) embed.set_footer(text = f"Basé sur discord.py {discord.__version__}") try: if fromSlash != True: From ecfa9bf1b2ebece734c50acf07cf8b30f9d50c79 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 13:57:32 +0200 Subject: [PATCH 234/286] best field name --- src/cogs/utils.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 000b9e2..2ef3f99 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -238,7 +238,7 @@ class Utils(commands.Cog): dev = self.client.get_user(158260864623968257) embed.add_field(name = "Dev", value = f"[{dev.name}](https://gitlab.com/Mylloon)") - embed.add_field(name = "Host", value = appinfo.owner.mention) + embed.add_field(name = "Hébergeur", value = appinfo.owner.mention) embed.add_field(name = f"Serveur{'s' if nombreServeur > 1 else ''}", value = f"`{nombreServeur}`") embed.add_field(name = f"Membre{'s' if total_unique > 1 else ''}", value = f"`{total_unique}` au total\n`{total_online}` en ligne") embed.add_field(name = f"Salon{'s' if (text + voice) > 1 else ''}", value = f"`{text}` textuel{'s' if text > 1 else ''}\n`{voice}` voca{'ux' if voice > 1 else 'l'}") @@ -246,7 +246,7 @@ class Utils(commands.Cog): embed.add_field(name = "Code source", value = "[Lien Gitlab](https://gitlab.com/ConfrerieDuKassoulait/KassouBot)") embed.add_field(name = "Timezone", value = f"`{self.customTimezone}`") changes = getChangelogs(version) - version = f"`{getActualVersion()}`" + version = f"`{version}`" if changes[0] == 200: version = f"[{version}]({changes[1]})" embed.add_field(name = "Version", value = version) From da5e3d35277ba1e8f0d3bc757fd57ecedc3d55cb Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 13:59:43 +0200 Subject: [PATCH 235/286] showing discriminator --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 2ef3f99..b233611 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -237,7 +237,7 @@ class Utils(commands.Cog): dev = self.client.get_user(158260864623968257) - embed.add_field(name = "Dev", value = f"[{dev.name}](https://gitlab.com/Mylloon)") + embed.add_field(name = "Dev", value = f"[{dev}](https://gitlab.com/Mylloon)") embed.add_field(name = "Hébergeur", value = appinfo.owner.mention) embed.add_field(name = f"Serveur{'s' if nombreServeur > 1 else ''}", value = f"`{nombreServeur}`") embed.add_field(name = f"Membre{'s' if total_unique > 1 else ''}", value = f"`{total_unique}` au total\n`{total_online}` en ligne") From d88812cf607d8ebc7cdcb3af7d6764c99e6bb6bf Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 14:03:06 +0200 Subject: [PATCH 236/286] fix #6 --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index b233611..60bc816 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -606,7 +606,7 @@ class Utils(commands.Cog): id, fromSlash, _ = isSlash(id) if id: try: - id = int(id[0]) + id = int(id) except: return await mySendHidden(ctx, fromSlash, "L'ID renseigné n'est pas valide.") else: From 571eb580cf1507664984d708639132527d154430 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 14:20:43 +0200 Subject: [PATCH 237/286] return ID of created reminder --- src/utils/reminder.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/utils/reminder.py b/src/utils/reminder.py index 6e262f7..659ac21 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -31,6 +31,7 @@ class Reminder(Database): ); """ self.requete(requete, [messageID, channelID, extrarg, reminder, creation, expiration, userID, guildID]) + return self.affichageResultat(self.requete("SELECT last_insert_rowid();")) def suppressionReminder(self, id = int): """Supprime un reminder.""" From 66b993b765aa937f2fba3f647adcc9630f8b95eb Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 14:21:09 +0200 Subject: [PATCH 238/286] showing id of created reminder + broadcast all expired reminder at once --- src/cogs/utils.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 60bc816..6f09019 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -491,8 +491,8 @@ class Utils(commands.Cog): messageID = None if fromSlash != True: messageID = ctx.message.id - Reminder().ajoutReminder(messageID, ctx.channel.id, extrarg, reminder, now, now + seconds, ctx.author.id, guildID) - return await mySendHidden(ctx, fromSlash, f"Ok, je t'en parles {destination} dans {timedeltaToString(seconds)} avec 1m de retard maximum.") + reminderID = Reminder().ajoutReminder(messageID, ctx.channel.id, extrarg, reminder, now, now + seconds, ctx.author.id, guildID) + return await mySendHidden(ctx, fromSlash, f"Ton reminder `{reminderID[0][0]}` est enrengistré !, je t'en parles {destination} dans {timedeltaToString(seconds)} avec 1m de retard maximum.") await mySendHidden(ctx, fromSlash, embed = embed) @_reminder.error async def _reminder_error(self, ctx, error): @@ -556,7 +556,7 @@ class Utils(commands.Cog): await channel.send(message, embed = finalEmbed) # envoie du rappel except: # les DM sont fermés pass - return Reminder().suppressionReminder(expired[5]) # suppression du rappel + Reminder().suppressionReminder(expired[5]) # suppression du rappel @_reminderLoop.before_loop async def __avant_reminderLoop(self): await self.client.wait_until_ready() From cdac6ff88ecefbf81bdadf91e3ca936b5293657f Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 14:28:48 +0200 Subject: [PATCH 239/286] more clarity in messages --- src/cogs/utils.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 6f09019..92bf050 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -492,7 +492,7 @@ class Utils(commands.Cog): if fromSlash != True: messageID = ctx.message.id reminderID = Reminder().ajoutReminder(messageID, ctx.channel.id, extrarg, reminder, now, now + seconds, ctx.author.id, guildID) - return await mySendHidden(ctx, fromSlash, f"Ton reminder `{reminderID[0][0]}` est enrengistré !, je t'en parles {destination} dans {timedeltaToString(seconds)} avec 1m de retard maximum.") + return await mySendHidden(ctx, fromSlash, f"Ton reminder `{reminderID[0][0]}` est enrengistré, je te notifie {destination} dans {timedeltaToString(seconds)} (avec 1m de retard maximum).") await mySendHidden(ctx, fromSlash, embed = embed) @_reminder.error async def _reminder_error(self, ctx, error): @@ -585,13 +585,13 @@ class Utils(commands.Cog): texte = f"{texte[:1021]}..." expiration = reminder[2] - int(nowUTC()) if expiration > 0: - expiration = f"Expire dans {timedeltaToString(expiration)} +1m de retard max." + expiration = f"Expire dans {timedeltaToString(expiration)}" else: expiration = f"A déjà expiré." embed.add_field(value = texte, name = f"#{reminder[3]} • Fais le {timestampScreen(intToDatetime(reminder[1]))}\n{expiration}", inline = False) else: embed.add_field(name = "\u200b", value = "Vous n'avez aucun rappel en attente !") - embed.set_footer(text = "Les rappels qui ont déjà expirés vont apparaître dans quelques instants.") + embed.set_footer(text = "Les rappels qui ont déjà expirés vont apparaître dans quelques instants.\nIls peuvent avoir jusqu'à 1 minute de retard maximum.") await ctx.send(embed = embed) @cog_ext.cog_slash(name="reminderlist", description = "Affiche la liste des rappels d'un utilisateur.") async def __reminderlist(self, ctx, user = None): From ebfb34d4996a0654027db79be3034be41a0559a3 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 14:40:43 +0200 Subject: [PATCH 240/286] precision on how to launch the bot locally --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b161e72..b7b08dd 100644 --- a/README.md +++ b/README.md @@ -39,4 +39,5 @@ To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and ## __Launching locally__ If you want to run it without Docker, create an .env file to store variables in the root folder. -Simply run `python3 main.py` in `src` folder to launch the bot in the repo folder. +Install ffmpeg by doing `sudo apt install ffmpeg` and all the requirements by doing `python3 -m pip install -r requirements.txt` +Simply run `python3 main.py` inside the `src` folder to launch the bot in the repo folder. From 2c917f466ed0ac87430b6c16f4f588217655862e Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 14:40:53 +0200 Subject: [PATCH 241/286] fix #5 --- src/cogs/music.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cogs/music.py b/src/cogs/music.py index d7a75cd..3dccf3e 100644 --- a/src/cogs/music.py +++ b/src/cogs/music.py @@ -550,4 +550,6 @@ class Music(commands.Cog): @commands.command(name='lyricsromanized', aliases = ['lr', 'lyricromanized'], hidden = True) async def _lyricsromanized(self, ctx, *, song: str = None): + if not song and ctx.voice_state.is_playing: + song = f"{ctx.voice_state.current.title()}" await ctx.invoke(self.client.get_command("lyrics"), song = f"{song} romanized" if song else song) From 14002799a35e7dc51c105e35b34469c65c6c50f1 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 21:09:37 +0200 Subject: [PATCH 242/286] bold ID --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 92bf050..0c3e832 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -492,7 +492,7 @@ class Utils(commands.Cog): if fromSlash != True: messageID = ctx.message.id reminderID = Reminder().ajoutReminder(messageID, ctx.channel.id, extrarg, reminder, now, now + seconds, ctx.author.id, guildID) - return await mySendHidden(ctx, fromSlash, f"Ton reminder `{reminderID[0][0]}` est enrengistré, je te notifie {destination} dans {timedeltaToString(seconds)} (avec 1m de retard maximum).") + return await mySendHidden(ctx, fromSlash, f"Ton reminder **`{reminderID[0][0]}`** est enrengistré, je te notifie {destination} dans {timedeltaToString(seconds)} (avec 1m de retard maximum).") await mySendHidden(ctx, fromSlash, embed = embed) @_reminder.error async def _reminder_error(self, ctx, error): From 6dab13b309d8739223c9e17ee934fa8c781e4f59 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 21:47:59 +0200 Subject: [PATCH 243/286] Adding page to reminderlist --- src/cogs/utils.py | 55 +++++++++++++++++++++++++++-------------------- 1 file changed, 32 insertions(+), 23 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 0c3e832..3c04fdf 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -562,43 +562,52 @@ class Utils(commands.Cog): await self.client.wait_until_ready() @commands.command(name='reminderlist', aliases=["remindlist", "rl", "rappeliste"]) - async def _reminderlist(self, ctx, *utilisateur): + async def _reminderlist(self, ctx, *arg): """Affiche la liste des rappels d'un utilisateur.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminderlist/rl/remindlist/rappeliste [utilisateur]""" - _, fromSlash, utilisateur = isSlash(utilisateur) - if len(utilisateur) > 0: + _, fromSlash, arg = isSlash(arg) + utilisateur = ctx.author.id + page = 1 + if len(arg) > 0: try: - utilisateur = mentionToUser(getMentionInString(utilisateur[0])[0]) + utilisateur = mentionToUser(getMentionInString(arg[0])[0]) except: - return await mySendHidden(ctx, fromSlash, "L'utilisateur renseigné n'a pas été trouvé.") - else: - utilisateur = ctx.author.id + try: + page = int(arg[0]) + except: + return await mySendHidden(ctx, fromSlash, "Veuillez renseigné un utilisateur ou un numéro de page valide.") reminders = Reminder().listeReminder(utilisateur, ctx.guild.id) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') - embed = discord.Embed(description = f"**Rappel{'s' if len(reminders) > 1 else ''} de <@{utilisateur}>**", color = discord.Colour.random()) + + pageMAX = -(-len(reminders) // 5) + embed = discord.Embed(description = f"**Rappel{'s' if len(reminders) > 1 else ''} de <@{utilisateur}>** • Page {page}/{pageMAX}", color = discord.Colour.random()) embed.set_thumbnail(url = self.client.get_user(utilisateur).avatar_url_as(size = 64)) - if len(reminders) > 0: - for reminder in reminders: - texte = reminder[0] - if len(texte) > 1024: - texte = f"{texte[:1021]}..." - expiration = reminder[2] - int(nowUTC()) - if expiration > 0: - expiration = f"Expire dans {timedeltaToString(expiration)}" - else: - expiration = f"A déjà expiré." - embed.add_field(value = texte, name = f"#{reminder[3]} • Fais le {timestampScreen(intToDatetime(reminder[1]))}\n{expiration}", inline = False) + limit = 5 * page + if len(reminders) > 0 and page <= pageMAX: + curseur = limit - 4 + for reminder in reminders[limit - 5:]: + if curseur <= limit: + texte = reminder[0] + if len(texte) > 1024: + texte = f"{texte[:1021]}..." + expiration = reminder[2] - int(nowUTC()) + if expiration > 0: + expiration = f"Expire dans {timedeltaToString(expiration)}" + else: + expiration = f"A déjà expiré." + embed.add_field(value = texte, name = f"#{reminder[3]} • Fais le {timestampScreen(intToDatetime(reminder[1]))}\n{expiration}", inline = False) + curseur += 1 else: - embed.add_field(name = "\u200b", value = "Vous n'avez aucun rappel en attente !") + embed.add_field(name = "\u200b", value = f"L'utilisateur n'a aucun rappel en attente ou page n°{page} vide !") embed.set_footer(text = "Les rappels qui ont déjà expirés vont apparaître dans quelques instants.\nIls peuvent avoir jusqu'à 1 minute de retard maximum.") await ctx.send(embed = embed) @cog_ext.cog_slash(name="reminderlist", description = "Affiche la liste des rappels d'un utilisateur.") - async def __reminderlist(self, ctx, user = None): - if user == None: + async def __reminderlist(self, ctx, userorpage = None): + if userorpage == None: return await self._reminderlist(ctx, True) else: - return await self._reminderlist(ctx, user, True) + return await self._reminderlist(ctx, userorpage, True) @commands.command(name='reminderdelete', aliases=["reminddelete", "rd"]) async def _reminderdelete(self, ctx, *id): From 6a9d5f9d25c0e9faf69c0bf427dbc686e1ce3b38 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 22:06:28 +0200 Subject: [PATCH 244/286] link of publication instead of link of image --- src/cogs/internet.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/internet.py b/src/cogs/internet.py index 8f7acb0..650d389 100644 --- a/src/cogs/internet.py +++ b/src/cogs/internet.py @@ -46,7 +46,7 @@ class Internet(commands.Cog): else: footer = "NSFW de Reddit" memeOuImage = "[lien de l'image]" - embed = discord.Embed(title = f"r/{subredditchoix} pour {ctx.author.name}", color = discord.Colour.random(), description = f"{memeOuImage}({submission.url})") + embed = discord.Embed(title = f"r/{subredditchoix} pour {ctx.author.name}", color = discord.Colour.random(), description = f"{memeOuImage}(https://www.reddit.com{submission.permalink})") embed.set_footer(text = footer) embed.set_image(url = submission.url) message = await ctx.send(embed = embed) From 0c0d26a324683dc9c6610fa3d0a4f62470b32c3b Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 22:13:58 +0200 Subject: [PATCH 245/286] add channel used in info command + improve regex --- src/cogs/utils.py | 4 ++-- src/utils/core.py | 6 +++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 3c04fdf..c875c3c 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -4,7 +4,7 @@ from random import randint, shuffle from discord_slash import cog_ext from utils.reminder import Reminder from utils.core import map_list_among_us, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick -from utils.core import mySendHidden, mentionToUser, getChangelogs, getActualVersion, isSlash, load +from utils.core import mySendHidden, mentionToUser, getChangelogs, getActualVersion, isSlash, load, devOrStableChannel from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString, timestampScreen, getAge, ageLayout, nowCustom def setup(client): @@ -249,7 +249,7 @@ class Utils(commands.Cog): version = f"`{version}`" if changes[0] == 200: version = f"[{version}]({changes[1]})" - embed.add_field(name = "Version", value = version) + embed.add_field(name = "Version", value = f"{version} ({devOrStableChannel()})") embed.set_footer(text = f"Basé sur discord.py {discord.__version__}") try: if fromSlash != True: diff --git a/src/utils/core.py b/src/utils/core.py index 38617e5..84f0d08 100644 --- a/src/utils/core.py +++ b/src/utils/core.py @@ -132,7 +132,11 @@ def getChangelogs(version = 'actual'): def getActualVersion(): with open(path.join(path.dirname(path.dirname(path.dirname(__file__))), "README.md"), "r") as file: - return findall(r'https://img.shields.io/badge/version-(\d+\.\d+)', file.readlines()[2])[0] + return findall(r'https:\/\/img.shields.io\/badge\/version-(\d+\.\d+)-green\?style=for-the-badge\)', file.readlines()[2])[0] + +def devOrStableChannel(): + with open(path.join(path.dirname(path.dirname(path.dirname(__file__))), "README.md"), "r") as file: + return findall(r'https:\/\/img.shields.io\/gitlab\/pipeline\/ConfrerieDuKassoulait\/KassouBot\/([a-z]+)\?style=for-the-badge\)]', file.readlines()[3])[0] def isSlash(arg): """Regarde si la commande viens d'un slash ou pas, retourne l'argument sans le 'True' si c'est le cas""" From 03bc6f893798d8699803fae95284c4135db93115 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 22:18:34 +0200 Subject: [PATCH 246/286] replace branch name "main" per "stable" in info command --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index c875c3c..29e8536 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -249,7 +249,7 @@ class Utils(commands.Cog): version = f"`{version}`" if changes[0] == 200: version = f"[{version}]({changes[1]})" - embed.add_field(name = "Version", value = f"{version} ({devOrStableChannel()})") + embed.add_field(name = "Version", value = f"{version} ({devOrStableChannel().replace("main", "stable")})") embed.set_footer(text = f"Basé sur discord.py {discord.__version__}") try: if fromSlash != True: From ed9c78e31cdd77c647e331a367ec6a020a75b252 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 22:25:18 +0200 Subject: [PATCH 247/286] migrate reminder in another file --- src/cogs/reminder.py | 202 +++++++++++++++++++++++++++++++++++++++++++ src/cogs/utils.py | 198 ++---------------------------------------- 2 files changed, 207 insertions(+), 193 deletions(-) create mode 100644 src/cogs/reminder.py diff --git a/src/cogs/reminder.py b/src/cogs/reminder.py new file mode 100644 index 0000000..721452c --- /dev/null +++ b/src/cogs/reminder.py @@ -0,0 +1,202 @@ +import discord +from discord.ext import commands, tasks +from discord_slash import cog_ext +from utils.reminder import Reminder +from utils.core import getURLsInString, getMentionInString, isSlash, mySendHidden, mentionToUser, cleanCodeStringWithMentionAndURLs +from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString, timestampScreen + +def setup(client): + client.add_cog(Reminder(client)) + +class Reminder(commands.Cog): + """Commandes relatives aux cours.""" + def __init__(self, client): + self.client = client + + @commands.command(name='reminder', aliases=["remind", "remindme", "rappel"]) + async def _reminder(self, ctx, time, *reminder): + """Met en place un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminder/remind/remindme/rappel [@] [message]""" + _, fromSlash, reminder = isSlash(reminder) + if len(reminder) > 0: + reminder = " ".join(reminder) + else: + reminder = None + + embed = discord.Embed(color = 0xC41B1B) + extrarg = 0 + guildID = ctx.guild.id # can be set to 0 if its a DM message, so it can be see from anywhere + destination = "ici" + if not reminder: + reminder = "Notification" + if time == "help": + seconds = 0 + else: + if time.endswith("@"): + time = time[:-1] + extrarg = 1 + if time.lower().endswith("p"): + time = time[:-1] + extrarg = 2 + guildID = 0 + destination = "en MP" + seconds = stringTempsVersSecondes(time) + if type(seconds) != int: + if fromSlash != True: + await ctx.message.add_reaction(emoji = '❓') + return await mySendHidden(ctx, fromSlash, seconds) + if seconds == 0: + embed.add_field(name="Attention", value= + "Format pour le temps : `d` ou `j` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (légères variances acceptés aussi). \ + \nMet un `@` accolée aux temps pour mentionner les gens mentionner dans ton message. \ + \nMet un `P` accolée au temps pour que le bot te DM au lieu de t'envoyer un message dans ce salon." + ) + elif seconds > (50 * (86400 * 365.242)): # 50 ans + embed.add_field(name="Attention", value="Tu as spécifié une durée trop longue, la durée maximum étant de 50 ans.") + else: + now = int(nowUTC()) + messageID = None + if fromSlash != True: + messageID = ctx.message.id + reminderID = Reminder().ajoutReminder(messageID, ctx.channel.id, extrarg, reminder, now, now + seconds, ctx.author.id, guildID) + return await mySendHidden(ctx, fromSlash, f"Ton reminder **`{reminderID[0][0]}`** est enrengistré, je te notifie {destination} dans {timedeltaToString(seconds)} (avec 1m de retard maximum).") + await mySendHidden(ctx, fromSlash, embed = embed) + @_reminder.error + async def _reminder_error(self, ctx, error): + if 'time is a required argument that is missing.' in str(error): + await ctx.send("Tu n'as pas spécifié de durée.") + @cog_ext.cog_slash(name="reminder", description = "Met en place un rappel.") + async def __reminder(self, ctx, time, reminder = None): + if reminder == None: + return await self._reminder(ctx, time, True) + else: + return await self._reminder(ctx, time, reminder, True) + + @tasks.loop(minutes = 1) + async def _reminderLoop(self): + """Méthode qui se répète toute les minutes pour vérifier si des rappels n'ont pas expirés, si expirés, les envoient.""" + expiration = Reminder().recuperationExpiration(int(nowUTC())) # on récupères les éléments expirés + for expired in expiration: # on regarde tout les éléments expirés + reminder = expired[2] # message + userID = expired[4] # personne qui a fait le rappel + channel = self.client.get_channel(expired[0]) # salon du message + finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = intToDatetime(expired[3]), color = discord.Colour.random()) + if expired[1] == 2: # s'il faut envoyer en DM le message + user = self.client.get_user(userID) + if user == None: # si l'utilisateur n'est pas trouvé + return Reminder().suppressionReminder(expired[5]) # suppression du rappel + channel = await user.create_dm() # envoie en DM + userID = None # plus de mention + sourceMessage = None # plus de message source + elif channel == None: # si le salon n'existe plus + user = self.client.get_user(userID) + if user == None: # si l'utilisateur n'est pas trouvé + return Reminder().suppressionReminder(expired[5]) # suppression du rappel + channel = await user.create_dm() # envoie en DM + userID = None # plus de mention + sourceMessage = None # plus de message source + finalEmbed.add_field(name = "Info", value = "Message envoyé en DM car le salon n'est plus disponible.") + else: + sourceMessage = expired[6] + if sourceMessage != None: # vérification message avec slash command et que si c'est pas en DM + try: + sourceMessage = await channel.fetch_message(sourceMessage) # récupération message + except: + sourceMessage = None # message a été supprimé + if sourceMessage != None: + await sourceMessage.add_reaction(emoji = '✅') # ajout réaction + finalEmbed.set_footer(text=f"Message d'il y a {timedeltaToString(int(nowUTC()) - expired[3])}") + links = "" + findedURLs = getURLsInString(reminder) + for i in range(0, len(findedURLs)): # ajout de field "lien" pour pouvoir cliquer sur les liens facilement + links += f"[Lien {i + 1}]({findedURLs[i]}) · " + if len(findedURLs) > 0: + finalEmbed.add_field(name = f"Lien{'s' if len(findedURLs) > 1 else ''}", value = links[:-3]) + message = "" + if userID != None: # metion de l'utilisateur si le message n'est pas en DM + message = f"<@{userID}>" + if expired[1] == 1: # s'il faut mentionner les personnes dans le message + mentionList = getMentionInString(reminder) + for i in mentionList: + message += f" {i}" + try: + await channel.send(message, embed = finalEmbed) # envoie du rappel + except: # les DM sont fermés + pass + Reminder().suppressionReminder(expired[5]) # suppression du rappel + @_reminderLoop.before_loop + async def __avant_reminderLoop(self): + await self.client.wait_until_ready() + + @commands.command(name='reminderlist', aliases=["remindlist", "rl", "rappeliste"]) + async def _reminderlist(self, ctx, *arg): + """Affiche la liste des rappels d'un utilisateur.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminderlist/rl/remindlist/rappeliste [utilisateur]""" + _, fromSlash, arg = isSlash(arg) + utilisateur = ctx.author.id + page = 1 + if len(arg) > 0: + try: + utilisateur = mentionToUser(getMentionInString(arg[0])[0]) + except: + try: + page = int(arg[0]) + except: + return await mySendHidden(ctx, fromSlash, "Veuillez renseigné un utilisateur ou un numéro de page valide.") + + reminders = Reminder().listeReminder(utilisateur, ctx.guild.id) + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + + pageMAX = -(-len(reminders) // 5) + embed = discord.Embed(description = f"**Rappel{'s' if len(reminders) > 1 else ''} de <@{utilisateur}>** • Page {page}/{pageMAX}", color = discord.Colour.random()) + embed.set_thumbnail(url = self.client.get_user(utilisateur).avatar_url_as(size = 64)) + limit = 5 * page + if len(reminders) > 0 and page <= pageMAX: + curseur = limit - 4 + for reminder in reminders[limit - 5:]: + if curseur <= limit: + texte = reminder[0] + if len(texte) > 1024: + texte = f"{texte[:1021]}..." + expiration = reminder[2] - int(nowUTC()) + if expiration > 0: + expiration = f"Expire dans {timedeltaToString(expiration)}" + else: + expiration = f"A déjà expiré." + embed.add_field(value = texte, name = f"#{reminder[3]} • Fais le {timestampScreen(intToDatetime(reminder[1]))}\n{expiration}", inline = False) + curseur += 1 + else: + embed.add_field(name = "\u200b", value = f"L'utilisateur n'a aucun rappel en attente ou page n°{page} vide !") + embed.set_footer(text = "Les rappels qui ont déjà expirés vont apparaître dans quelques instants.\nIls peuvent avoir jusqu'à 1 minute de retard maximum.") + await ctx.send(embed = embed) + @cog_ext.cog_slash(name="reminderlist", description = "Affiche la liste des rappels d'un utilisateur.") + async def __reminderlist(self, ctx, userorpage = None): + if userorpage == None: + return await self._reminderlist(ctx, True) + else: + return await self._reminderlist(ctx, userorpage, True) + + @commands.command(name='reminderdelete', aliases=["reminddelete", "rd"]) + async def _reminderdelete(self, ctx, *id): + """Suppprime un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminderdelete/rd """ + id, fromSlash, _ = isSlash(id) + if id: + try: + id = int(id) + except: + return await mySendHidden(ctx, fromSlash, "L'ID renseigné n'est pas valide.") + else: + return await ctx.send("Veuillez renseigner un ID.") + + verification = Reminder().appartenanceReminder(ctx.author.id, id, ctx.guild.id) + if verification: + Reminder().suppressionReminder(id) + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') + return await ctx.send(f"Reminder **#{id}** supprimé !") + else: + if fromSlash != True: + await ctx.message.add_reaction(emoji = '❌') + return await mySendHidden(ctx, fromSlash, "Rappel non trouvé, pas sur le bon serveur ou qui ne vous appartiens pas.") + @cog_ext.cog_slash(name="reminderdelete", description = "Suppprime un rappel.") + async def __reminderdelete(self, ctx, id): + return await self._reminderdelete(ctx, id, True) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 29e8536..65a54fe 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -1,11 +1,11 @@ import discord -from discord.ext import commands, tasks +from discord.ext import commands from random import randint, shuffle +from re import findall from discord_slash import cog_ext -from utils.reminder import Reminder -from utils.core import map_list_among_us, getURLsInString, getMentionInString, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick +from utils.core import map_list_among_us, cleanCodeStringWithMentionAndURLs, cleanUser, userOrNick from utils.core import mySendHidden, mentionToUser, getChangelogs, getActualVersion, isSlash, load, devOrStableChannel -from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString, timestampScreen, getAge, ageLayout, nowCustom +from utils.time import nowUTC, intToDatetime, timestampScreen, getAge, ageLayout, nowCustom def setup(client): client.add_cog(Utils(client)) @@ -249,7 +249,7 @@ class Utils(commands.Cog): version = f"`{version}`" if changes[0] == 200: version = f"[{version}]({changes[1]})" - embed.add_field(name = "Version", value = f"{version} ({devOrStableChannel().replace("main", "stable")})") + embed.add_field(name = "Version", value = f"{version} ({devOrStableChannel().replace('main', 'stable')})") embed.set_footer(text = f"Basé sur discord.py {discord.__version__}") try: if fromSlash != True: @@ -447,194 +447,6 @@ class Utils(commands.Cog): args = args[:1] return await self._avis(ctx, args, True) - @commands.command(name='reminder', aliases=["remind", "remindme", "rappel"]) - async def _reminder(self, ctx, time, *reminder): - """Met en place un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminder/remind/remindme/rappel [@] [message]""" - _, fromSlash, reminder = isSlash(reminder) - if len(reminder) > 0: - reminder = " ".join(reminder) - else: - reminder = None - - embed = discord.Embed(color = 0xC41B1B) - extrarg = 0 - guildID = ctx.guild.id # can be set to 0 if its a DM message, so it can be see from anywhere - destination = "ici" - if not reminder: - reminder = "Notification" - if time == "help": - seconds = 0 - else: - if time.endswith("@"): - time = time[:-1] - extrarg = 1 - if time.lower().endswith("p"): - time = time[:-1] - extrarg = 2 - guildID = 0 - destination = "en MP" - seconds = stringTempsVersSecondes(time) - if type(seconds) != int: - if fromSlash != True: - await ctx.message.add_reaction(emoji = '❓') - return await mySendHidden(ctx, fromSlash, seconds) - if seconds == 0: - embed.add_field(name="Attention", value= - "Format pour le temps : `d` ou `j` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (légères variances acceptés aussi). \ - \nMet un `@` accolée aux temps pour mentionner les gens mentionner dans ton message. \ - \nMet un `P` accolée au temps pour que le bot te DM au lieu de t'envoyer un message dans ce salon." - ) - elif seconds > (50 * (86400 * 365.242)): # 50 ans - embed.add_field(name="Attention", value="Tu as spécifié une durée trop longue, la durée maximum étant de 50 ans.") - else: - now = int(nowUTC()) - messageID = None - if fromSlash != True: - messageID = ctx.message.id - reminderID = Reminder().ajoutReminder(messageID, ctx.channel.id, extrarg, reminder, now, now + seconds, ctx.author.id, guildID) - return await mySendHidden(ctx, fromSlash, f"Ton reminder **`{reminderID[0][0]}`** est enrengistré, je te notifie {destination} dans {timedeltaToString(seconds)} (avec 1m de retard maximum).") - await mySendHidden(ctx, fromSlash, embed = embed) - @_reminder.error - async def _reminder_error(self, ctx, error): - if 'time is a required argument that is missing.' in str(error): - await ctx.send("Tu n'as pas spécifié de durée.") - @cog_ext.cog_slash(name="reminder", description = "Met en place un rappel.") - async def __reminder(self, ctx, time, reminder = None): - if reminder == None: - return await self._reminder(ctx, time, True) - else: - return await self._reminder(ctx, time, reminder, True) - - @tasks.loop(minutes = 1) - async def _reminderLoop(self): - """Méthode qui se répète toute les minutes pour vérifier si des rappels n'ont pas expirés, si expirés, les envoient.""" - expiration = Reminder().recuperationExpiration(int(nowUTC())) # on récupères les éléments expirés - for expired in expiration: # on regarde tout les éléments expirés - reminder = expired[2] # message - userID = expired[4] # personne qui a fait le rappel - channel = self.client.get_channel(expired[0]) # salon du message - finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = intToDatetime(expired[3]), color = discord.Colour.random()) - if expired[1] == 2: # s'il faut envoyer en DM le message - user = self.client.get_user(userID) - if user == None: # si l'utilisateur n'est pas trouvé - return Reminder().suppressionReminder(expired[5]) # suppression du rappel - channel = await user.create_dm() # envoie en DM - userID = None # plus de mention - sourceMessage = None # plus de message source - elif channel == None: # si le salon n'existe plus - user = self.client.get_user(userID) - if user == None: # si l'utilisateur n'est pas trouvé - return Reminder().suppressionReminder(expired[5]) # suppression du rappel - channel = await user.create_dm() # envoie en DM - userID = None # plus de mention - sourceMessage = None # plus de message source - finalEmbed.add_field(name = "Info", value = "Message envoyé en DM car le salon n'est plus disponible.") - else: - sourceMessage = expired[6] - if sourceMessage != None: # vérification message avec slash command et que si c'est pas en DM - try: - sourceMessage = await channel.fetch_message(sourceMessage) # récupération message - except: - sourceMessage = None # message a été supprimé - if sourceMessage != None: - await sourceMessage.add_reaction(emoji = '✅') # ajout réaction - finalEmbed.set_footer(text=f"Message d'il y a {timedeltaToString(int(nowUTC()) - expired[3])}") - links = "" - findedURLs = getURLsInString(reminder) - for i in range(0, len(findedURLs)): # ajout de field "lien" pour pouvoir cliquer sur les liens facilement - links += f"[Lien {i + 1}]({findedURLs[i]}) · " - if len(findedURLs) > 0: - finalEmbed.add_field(name = f"Lien{'s' if len(findedURLs) > 1 else ''}", value = links[:-3]) - message = "" - if userID != None: # metion de l'utilisateur si le message n'est pas en DM - message = f"<@{userID}>" - if expired[1] == 1: # s'il faut mentionner les personnes dans le message - mentionList = getMentionInString(reminder) - for i in mentionList: - message += f" {i}" - try: - await channel.send(message, embed = finalEmbed) # envoie du rappel - except: # les DM sont fermés - pass - Reminder().suppressionReminder(expired[5]) # suppression du rappel - @_reminderLoop.before_loop - async def __avant_reminderLoop(self): - await self.client.wait_until_ready() - - @commands.command(name='reminderlist', aliases=["remindlist", "rl", "rappeliste"]) - async def _reminderlist(self, ctx, *arg): - """Affiche la liste des rappels d'un utilisateur.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminderlist/rl/remindlist/rappeliste [utilisateur]""" - _, fromSlash, arg = isSlash(arg) - utilisateur = ctx.author.id - page = 1 - if len(arg) > 0: - try: - utilisateur = mentionToUser(getMentionInString(arg[0])[0]) - except: - try: - page = int(arg[0]) - except: - return await mySendHidden(ctx, fromSlash, "Veuillez renseigné un utilisateur ou un numéro de page valide.") - - reminders = Reminder().listeReminder(utilisateur, ctx.guild.id) - if fromSlash != True: - await ctx.message.add_reaction(emoji = '✅') - - pageMAX = -(-len(reminders) // 5) - embed = discord.Embed(description = f"**Rappel{'s' if len(reminders) > 1 else ''} de <@{utilisateur}>** • Page {page}/{pageMAX}", color = discord.Colour.random()) - embed.set_thumbnail(url = self.client.get_user(utilisateur).avatar_url_as(size = 64)) - limit = 5 * page - if len(reminders) > 0 and page <= pageMAX: - curseur = limit - 4 - for reminder in reminders[limit - 5:]: - if curseur <= limit: - texte = reminder[0] - if len(texte) > 1024: - texte = f"{texte[:1021]}..." - expiration = reminder[2] - int(nowUTC()) - if expiration > 0: - expiration = f"Expire dans {timedeltaToString(expiration)}" - else: - expiration = f"A déjà expiré." - embed.add_field(value = texte, name = f"#{reminder[3]} • Fais le {timestampScreen(intToDatetime(reminder[1]))}\n{expiration}", inline = False) - curseur += 1 - else: - embed.add_field(name = "\u200b", value = f"L'utilisateur n'a aucun rappel en attente ou page n°{page} vide !") - embed.set_footer(text = "Les rappels qui ont déjà expirés vont apparaître dans quelques instants.\nIls peuvent avoir jusqu'à 1 minute de retard maximum.") - await ctx.send(embed = embed) - @cog_ext.cog_slash(name="reminderlist", description = "Affiche la liste des rappels d'un utilisateur.") - async def __reminderlist(self, ctx, userorpage = None): - if userorpage == None: - return await self._reminderlist(ctx, True) - else: - return await self._reminderlist(ctx, userorpage, True) - - @commands.command(name='reminderdelete', aliases=["reminddelete", "rd"]) - async def _reminderdelete(self, ctx, *id): - """Suppprime un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminderdelete/rd """ - id, fromSlash, _ = isSlash(id) - if id: - try: - id = int(id) - except: - return await mySendHidden(ctx, fromSlash, "L'ID renseigné n'est pas valide.") - else: - return await ctx.send("Veuillez renseigner un ID.") - - verification = Reminder().appartenanceReminder(ctx.author.id, id, ctx.guild.id) - if verification: - Reminder().suppressionReminder(id) - if fromSlash != True: - await ctx.message.add_reaction(emoji = '✅') - return await ctx.send(f"Reminder **#{id}** supprimé !") - else: - if fromSlash != True: - await ctx.message.add_reaction(emoji = '❌') - return await mySendHidden(ctx, fromSlash, "Rappel non trouvé, pas sur le bon serveur ou qui ne vous appartiens pas.") - @cog_ext.cog_slash(name="reminderdelete", description = "Suppprime un rappel.") - async def __reminderdelete(self, ctx, id): - return await self._reminderdelete(ctx, id, True) - @commands.command(name='changelogs', aliases=["changelog", "changement", "changements"]) async def _changelogs(self, ctx, *version): """Affiche les changements de la dernière version ou d'une version précise.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}changelogs/changelog/changement/changements [version]""" From 2660b3284ac2c65ba9f1c709ac95c5ed408b458e Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 22:31:47 +0200 Subject: [PATCH 248/286] fix bug due to transition --- src/cogs/reminder.py | 7 ++++--- src/cogs/utils.py | 1 - 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cogs/reminder.py b/src/cogs/reminder.py index 721452c..1cb2bc0 100644 --- a/src/cogs/reminder.py +++ b/src/cogs/reminder.py @@ -6,12 +6,13 @@ from utils.core import getURLsInString, getMentionInString, isSlash, mySendHidde from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString, timestampScreen def setup(client): - client.add_cog(Reminder(client)) + client.add_cog(ReminderDiscord(client)) -class Reminder(commands.Cog): - """Commandes relatives aux cours.""" +class ReminderDiscord(commands.Cog): + """Commandes relatives aux reminder.""" def __init__(self, client): self.client = client + self._reminderLoop.start() @commands.command(name='reminder', aliases=["remind", "remindme", "rappel"]) async def _reminder(self, ctx, time, *reminder): diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 65a54fe..6d79604 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -15,7 +15,6 @@ class Utils(commands.Cog): def __init__(self, client): self.client = client self.customTimezone = load(["TIMEZONE"])["TIMEZONE"] - self._reminderLoop.start() @commands.command(name='ping') async def _ping(self, ctx, *arg): From a4a5c7abcb4d627e641428d6bb83af378201c55b Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 28 Jul 2021 22:36:30 +0200 Subject: [PATCH 249/286] go trough page of other user in reminderlist --- src/cogs/reminder.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/cogs/reminder.py b/src/cogs/reminder.py index 1cb2bc0..51dfc60 100644 --- a/src/cogs/reminder.py +++ b/src/cogs/reminder.py @@ -134,14 +134,18 @@ class ReminderDiscord(commands.Cog): _, fromSlash, arg = isSlash(arg) utilisateur = ctx.author.id page = 1 + erreur = False if len(arg) > 0: - try: - utilisateur = mentionToUser(getMentionInString(arg[0])[0]) - except: + for i in range(0, len(arg)): try: - page = int(arg[0]) + utilisateur = mentionToUser(getMentionInString(arg[i])[0]) except: - return await mySendHidden(ctx, fromSlash, "Veuillez renseigné un utilisateur ou un numéro de page valide.") + try: + page = int(arg[i]) + except: + erreur = True + if erreur == True: + return await mySendHidden(ctx, fromSlash, "Veuillez renseigné un utilisateur ou un numéro de page valide.") reminders = Reminder().listeReminder(utilisateur, ctx.guild.id) if fromSlash != True: From cdbdefb9fce92458e646ef4586eaa600bc6683ac Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 29 Jul 2021 01:11:59 +0200 Subject: [PATCH 250/286] Update cleaning up settings --- .gitlab-ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 4bb615a..35ed9e3 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,7 +1,7 @@ ############################################################### # Setting I use for cleaning up image tags # -# - Running cleanup every day # -# - Keeping 1 tag per image name matching : (?:v.+|dev) # +# - Running cleanup every week # +# - Keeping 1 tag per image name matching : (?:v.\d+|dev) # # - Removing tags older than 7 days matching the default : .* # ############################################################### From 56be762445d135abc470e5a774ed361353a22ba4 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 29 Jul 2021 01:52:21 +0200 Subject: [PATCH 251/286] force value instead of making them as default --- src/utils/reminder.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/utils/reminder.py b/src/utils/reminder.py index 659ac21..9145ccd 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -21,7 +21,7 @@ class Reminder(Database): """ self.requete(requete) - def ajoutReminder(self, messageID = int, channelID = int, extrarg = int, reminder = str, creation = int, expiration = int, userID = int, guildID = int): + def ajoutReminder(self, messageID: int, channelID: int, extrarg: int, reminder: str, creation: int, expiration: int, userID: int, guildID: int): """Ajoute un reminder.""" requete = """ INSERT INTO reminder ( @@ -33,7 +33,7 @@ class Reminder(Database): self.requete(requete, [messageID, channelID, extrarg, reminder, creation, expiration, userID, guildID]) return self.affichageResultat(self.requete("SELECT last_insert_rowid();")) - def suppressionReminder(self, id = int): + def suppressionReminder(self, id: int): """Supprime un reminder.""" requete = """ DELETE FROM reminder @@ -41,7 +41,7 @@ class Reminder(Database): """ self.requete(requete, id) - def listeReminder(self, userID = int, guildID = int): + def listeReminder(self, userID: int, guildID: int): """Retourne la liste des reminders d'un utilisateur.""" requete = """ SELECT reminder_str, creation_int, expiration_int, id FROM reminder @@ -49,7 +49,7 @@ class Reminder(Database): """ return self.affichageResultat(self.requete(requete, [userID, guildID])) - def recuperationExpiration(self, time = int): + def recuperationExpiration(self, time: int): """Récupère les reminders qui sont arrivés à expiration et ses infos.""" requete = """ SELECT channel_id, extrarg_id, reminder_str, creation_int, user_id, id, message_id FROM reminder @@ -57,7 +57,7 @@ class Reminder(Database): """ return self.affichageResultat(self.requete(requete, time)) - def appartenanceReminder(self, user = int, id = int, guildID = int): + def appartenanceReminder(self, userID: int, id: int, guildID: int): """Vérifie qu'un rappel appartiens à un utilisateur et que la guilde soit la bonne. Renvois False si le rappel n'existe pas.""" requete = """ SELECT EXISTS ( @@ -65,4 +65,4 @@ class Reminder(Database): WHERE id = ? AND user_id = ? AND (guild_id = ? OR guild_id = 0) ) """ - return True if self.affichageResultat(self.requete(requete, [id, user, guildID]))[0][0] == 1 else False + return True if self.affichageResultat(self.requete(requete, [id, userID, guildID]))[0][0] == 1 else False From b70d5c5055dd445061de8b9028b07bc0a9132030 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 29 Jul 2021 12:12:39 +0200 Subject: [PATCH 252/286] Adding tutorial How to get genius token --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b7b08dd..b5309cc 100644 --- a/README.md +++ b/README.md @@ -22,9 +22,10 @@ docker run -d \ ``` To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and here are the instructions: ![instructions](https://i.imgur.com/tEzYKDA.png) - *redirection uri (for copy/paste) : http://localhost:8080* +To find Genius token, go to [this site](https://genius.com/api-clients), `login to your account` and on the left select `New API Client`. Fill the field with what you want then click `Save`. Now your token is the `CLIENT ACCESS TOKEN`. + ## __Add the bot to your server__ - In the [Discord Dev Portal](https://discord.com/developers/applications) create an application, and make sure it's a `Bot` (third tab). From 775cd7df267dcc064cba5a76c80c3b5ff1d1a9a8 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 29 Jul 2021 12:17:21 +0200 Subject: [PATCH 253/286] Fix bug Genius --- src/cogs/music.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cogs/music.py b/src/cogs/music.py index 3dccf3e..0493898 100644 --- a/src/cogs/music.py +++ b/src/cogs/music.py @@ -506,7 +506,8 @@ class Music(commands.Cog): paroles = song_genius.lyrics except: await ctx.message.add_reaction(emoji = '❌') - return await message.edit(content = f"Pas de résultats trouvés pour `{song}`.") + return await message.edit(content = f"Pas de résultats trouvés pour `{song}`.") + paroles.replace("EmbedShare URLCopyEmbedCopy", "") # Fix temporaire bug Genius lignetotal = "" premierembed = True if len(paroles) > 7500: From d0619fa95066a999af7f0adbad193da1ea0d86dd Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 29 Jul 2021 12:26:25 +0200 Subject: [PATCH 254/286] force markdown and better fix for the genius bug --- src/cogs/music.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cogs/music.py b/src/cogs/music.py index 0493898..9ed9af9 100644 --- a/src/cogs/music.py +++ b/src/cogs/music.py @@ -22,7 +22,9 @@ from lyricsgenius import Genius from utils.core import ligneFormatage, userOrNick, load from utils.time import nowCustom +from re import sub genius = Genius(load(["TOKEN_GENIUS"])["TOKEN_GENIUS"]) +genius.response_format = "markdown" # Silence useless bug reports messages youtube_dl.utils.bug_reports_message = lambda: '' @@ -507,7 +509,7 @@ class Music(commands.Cog): except: await ctx.message.add_reaction(emoji = '❌') return await message.edit(content = f"Pas de résultats trouvés pour `{song}`.") - paroles.replace("EmbedShare URLCopyEmbedCopy", "") # Fix temporaire bug Genius + paroles = sub(r"3?EmbedShare URLCopyEmbedCopy", "", paroles) # Fix temporaire bug Genius lignetotal = "" premierembed = True if len(paroles) > 7500: From f46165da55db8c1c86dac49f10258aa4df55c898 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 29 Jul 2021 20:35:39 +0200 Subject: [PATCH 255/286] precision on late only if minus than 1 hour --- src/cogs/reminder.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/reminder.py b/src/cogs/reminder.py index 51dfc60..823e75c 100644 --- a/src/cogs/reminder.py +++ b/src/cogs/reminder.py @@ -59,7 +59,7 @@ class ReminderDiscord(commands.Cog): if fromSlash != True: messageID = ctx.message.id reminderID = Reminder().ajoutReminder(messageID, ctx.channel.id, extrarg, reminder, now, now + seconds, ctx.author.id, guildID) - return await mySendHidden(ctx, fromSlash, f"Ton reminder **`{reminderID[0][0]}`** est enrengistré, je te notifie {destination} dans {timedeltaToString(seconds)} (avec 1m de retard maximum).") + return await mySendHidden(ctx, fromSlash, f"Ton reminder **`#{reminderID[0][0]}`** est enrengistré, je te notifie {destination} dans {timedeltaToString(seconds)}{'' if seconds >= 3600 else ' (avec 1m de retard maximum)'}.") await mySendHidden(ctx, fromSlash, embed = embed) @_reminder.error async def _reminder_error(self, ctx, error): From 5ca258ef4feb323aefa35da12d6e2549cd7b5007 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 29 Jul 2021 20:42:08 +0200 Subject: [PATCH 256/286] remove parenthesis in the is playing state in lyrics --- src/cogs/music.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cogs/music.py b/src/cogs/music.py index 9ed9af9..d841112 100644 --- a/src/cogs/music.py +++ b/src/cogs/music.py @@ -496,7 +496,7 @@ class Music(commands.Cog): """Affiche les paroles de la musique en cours, ou de la chanson spécifiée.\n ➡ Syntaxe: {PREFIX}lyrics/lyric/l (musique)⁢⁢⁢⁢⁢⁢⁢⁢⁢⁢""" if song or ctx.voice_state.is_playing: if not song: - song = f"{ctx.voice_state.current.title()}" + song = sub(r"(\ )?\(.*\)", "", ctx.voice_state.current.title()) if " romanized" in song: message = await ctx.send(f":mag: **Cherche les paroles romanisées de ** `{song.replace(' romanized', '')}`") else: @@ -554,5 +554,5 @@ class Music(commands.Cog): @commands.command(name='lyricsromanized', aliases = ['lr', 'lyricromanized'], hidden = True) async def _lyricsromanized(self, ctx, *, song: str = None): if not song and ctx.voice_state.is_playing: - song = f"{ctx.voice_state.current.title()}" + song = sub(r"(\ )?\(.*\)", "", ctx.voice_state.current.title()) await ctx.invoke(self.client.get_command("lyrics"), song = f"{song} romanized" if song else song) From 2b9edd0f4ebd902bbba3bcacdcdbf70abc6832b8 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 29 Jul 2021 20:45:39 +0200 Subject: [PATCH 257/286] move loop to top of file --- src/cogs/reminder.py | 112 +++++++++++++++++++++---------------------- 1 file changed, 56 insertions(+), 56 deletions(-) diff --git a/src/cogs/reminder.py b/src/cogs/reminder.py index 823e75c..a36a008 100644 --- a/src/cogs/reminder.py +++ b/src/cogs/reminder.py @@ -13,6 +13,62 @@ class ReminderDiscord(commands.Cog): def __init__(self, client): self.client = client self._reminderLoop.start() + + @tasks.loop(minutes = 1) + async def _reminderLoop(self): + """Méthode qui se répète toute les minutes pour vérifier si des rappels n'ont pas expirés, si expirés, les envoient.""" + expiration = Reminder().recuperationExpiration(int(nowUTC())) # on récupères les éléments expirés + for expired in expiration: # on regarde tout les éléments expirés + reminder = expired[2] # message + userID = expired[4] # personne qui a fait le rappel + channel = self.client.get_channel(expired[0]) # salon du message + finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = intToDatetime(expired[3]), color = discord.Colour.random()) + if expired[1] == 2: # s'il faut envoyer en DM le message + user = self.client.get_user(userID) + if user == None: # si l'utilisateur n'est pas trouvé + return Reminder().suppressionReminder(expired[5]) # suppression du rappel + channel = await user.create_dm() # envoie en DM + userID = None # plus de mention + sourceMessage = None # plus de message source + elif channel == None: # si le salon n'existe plus + user = self.client.get_user(userID) + if user == None: # si l'utilisateur n'est pas trouvé + return Reminder().suppressionReminder(expired[5]) # suppression du rappel + channel = await user.create_dm() # envoie en DM + userID = None # plus de mention + sourceMessage = None # plus de message source + finalEmbed.add_field(name = "Info", value = "Message envoyé en DM car le salon n'est plus disponible.") + else: + sourceMessage = expired[6] + if sourceMessage != None: # vérification message avec slash command et que si c'est pas en DM + try: + sourceMessage = await channel.fetch_message(sourceMessage) # récupération message + except: + sourceMessage = None # message a été supprimé + if sourceMessage != None: + await sourceMessage.add_reaction(emoji = '✅') # ajout réaction + finalEmbed.set_footer(text=f"Message d'il y a {timedeltaToString(int(nowUTC()) - expired[3])}") + links = "" + findedURLs = getURLsInString(reminder) + for i in range(0, len(findedURLs)): # ajout de field "lien" pour pouvoir cliquer sur les liens facilement + links += f"[Lien {i + 1}]({findedURLs[i]}) · " + if len(findedURLs) > 0: + finalEmbed.add_field(name = f"Lien{'s' if len(findedURLs) > 1 else ''}", value = links[:-3]) + message = "" + if userID != None: # metion de l'utilisateur si le message n'est pas en DM + message = f"<@{userID}>" + if expired[1] == 1: # s'il faut mentionner les personnes dans le message + mentionList = getMentionInString(reminder) + for i in mentionList: + message += f" {i}" + try: + await channel.send(message, embed = finalEmbed) # envoie du rappel + except: # les DM sont fermés + pass + Reminder().suppressionReminder(expired[5]) # suppression du rappel + @_reminderLoop.before_loop + async def __avant_reminderLoop(self): + await self.client.wait_until_ready() @commands.command(name='reminder', aliases=["remind", "remindme", "rappel"]) async def _reminder(self, ctx, time, *reminder): @@ -72,62 +128,6 @@ class ReminderDiscord(commands.Cog): else: return await self._reminder(ctx, time, reminder, True) - @tasks.loop(minutes = 1) - async def _reminderLoop(self): - """Méthode qui se répète toute les minutes pour vérifier si des rappels n'ont pas expirés, si expirés, les envoient.""" - expiration = Reminder().recuperationExpiration(int(nowUTC())) # on récupères les éléments expirés - for expired in expiration: # on regarde tout les éléments expirés - reminder = expired[2] # message - userID = expired[4] # personne qui a fait le rappel - channel = self.client.get_channel(expired[0]) # salon du message - finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = intToDatetime(expired[3]), color = discord.Colour.random()) - if expired[1] == 2: # s'il faut envoyer en DM le message - user = self.client.get_user(userID) - if user == None: # si l'utilisateur n'est pas trouvé - return Reminder().suppressionReminder(expired[5]) # suppression du rappel - channel = await user.create_dm() # envoie en DM - userID = None # plus de mention - sourceMessage = None # plus de message source - elif channel == None: # si le salon n'existe plus - user = self.client.get_user(userID) - if user == None: # si l'utilisateur n'est pas trouvé - return Reminder().suppressionReminder(expired[5]) # suppression du rappel - channel = await user.create_dm() # envoie en DM - userID = None # plus de mention - sourceMessage = None # plus de message source - finalEmbed.add_field(name = "Info", value = "Message envoyé en DM car le salon n'est plus disponible.") - else: - sourceMessage = expired[6] - if sourceMessage != None: # vérification message avec slash command et que si c'est pas en DM - try: - sourceMessage = await channel.fetch_message(sourceMessage) # récupération message - except: - sourceMessage = None # message a été supprimé - if sourceMessage != None: - await sourceMessage.add_reaction(emoji = '✅') # ajout réaction - finalEmbed.set_footer(text=f"Message d'il y a {timedeltaToString(int(nowUTC()) - expired[3])}") - links = "" - findedURLs = getURLsInString(reminder) - for i in range(0, len(findedURLs)): # ajout de field "lien" pour pouvoir cliquer sur les liens facilement - links += f"[Lien {i + 1}]({findedURLs[i]}) · " - if len(findedURLs) > 0: - finalEmbed.add_field(name = f"Lien{'s' if len(findedURLs) > 1 else ''}", value = links[:-3]) - message = "" - if userID != None: # metion de l'utilisateur si le message n'est pas en DM - message = f"<@{userID}>" - if expired[1] == 1: # s'il faut mentionner les personnes dans le message - mentionList = getMentionInString(reminder) - for i in mentionList: - message += f" {i}" - try: - await channel.send(message, embed = finalEmbed) # envoie du rappel - except: # les DM sont fermés - pass - Reminder().suppressionReminder(expired[5]) # suppression du rappel - @_reminderLoop.before_loop - async def __avant_reminderLoop(self): - await self.client.wait_until_ready() - @commands.command(name='reminderlist', aliases=["remindlist", "rl", "rappeliste"]) async def _reminderlist(self, ctx, *arg): """Affiche la liste des rappels d'un utilisateur.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminderlist/rl/remindlist/rappeliste [utilisateur]""" From 1f3dbcb6b6d402a10b2828cef2eb85841b67649e Mon Sep 17 00:00:00 2001 From: Mylloon Date: Thu, 29 Jul 2021 23:25:28 +0200 Subject: [PATCH 258/286] Add reaction for changing pages in reminderlist --- src/cogs/reminder.py | 50 ++++++++++++++++------------------- src/utils/reminder.py | 61 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 28 deletions(-) diff --git a/src/cogs/reminder.py b/src/cogs/reminder.py index a36a008..03187bd 100644 --- a/src/cogs/reminder.py +++ b/src/cogs/reminder.py @@ -3,7 +3,7 @@ from discord.ext import commands, tasks from discord_slash import cog_ext from utils.reminder import Reminder from utils.core import getURLsInString, getMentionInString, isSlash, mySendHidden, mentionToUser, cleanCodeStringWithMentionAndURLs -from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString, timestampScreen +from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString def setup(client): client.add_cog(ReminderDiscord(client)) @@ -24,14 +24,14 @@ class ReminderDiscord(commands.Cog): channel = self.client.get_channel(expired[0]) # salon du message finalEmbed = discord.Embed(description = cleanCodeStringWithMentionAndURLs(reminder), timestamp = intToDatetime(expired[3]), color = discord.Colour.random()) if expired[1] == 2: # s'il faut envoyer en DM le message - user = self.client.get_user(userID) + user = self.client.get_user(userID) if user == None: # si l'utilisateur n'est pas trouvé return Reminder().suppressionReminder(expired[5]) # suppression du rappel channel = await user.create_dm() # envoie en DM userID = None # plus de mention sourceMessage = None # plus de message source elif channel == None: # si le salon n'existe plus - user = self.client.get_user(userID) + user = self.client.get_user(userID) if user == None: # si l'utilisateur n'est pas trouvé return Reminder().suppressionReminder(expired[5]) # suppression du rappel channel = await user.create_dm() # envoie en DM @@ -132,13 +132,13 @@ class ReminderDiscord(commands.Cog): async def _reminderlist(self, ctx, *arg): """Affiche la liste des rappels d'un utilisateur.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminderlist/rl/remindlist/rappeliste [utilisateur]""" _, fromSlash, arg = isSlash(arg) - utilisateur = ctx.author.id + utilisateur = ctx.author page = 1 erreur = False if len(arg) > 0: for i in range(0, len(arg)): try: - utilisateur = mentionToUser(getMentionInString(arg[i])[0]) + utilisateur = self.client.get_user(mentionToUser(getMentionInString(arg[i])[0])) except: try: page = int(arg[i]) @@ -147,32 +147,14 @@ class ReminderDiscord(commands.Cog): if erreur == True: return await mySendHidden(ctx, fromSlash, "Veuillez renseigné un utilisateur ou un numéro de page valide.") - reminders = Reminder().listeReminder(utilisateur, ctx.guild.id) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') - pageMAX = -(-len(reminders) // 5) - embed = discord.Embed(description = f"**Rappel{'s' if len(reminders) > 1 else ''} de <@{utilisateur}>** • Page {page}/{pageMAX}", color = discord.Colour.random()) - embed.set_thumbnail(url = self.client.get_user(utilisateur).avatar_url_as(size = 64)) - limit = 5 * page - if len(reminders) > 0 and page <= pageMAX: - curseur = limit - 4 - for reminder in reminders[limit - 5:]: - if curseur <= limit: - texte = reminder[0] - if len(texte) > 1024: - texte = f"{texte[:1021]}..." - expiration = reminder[2] - int(nowUTC()) - if expiration > 0: - expiration = f"Expire dans {timedeltaToString(expiration)}" - else: - expiration = f"A déjà expiré." - embed.add_field(value = texte, name = f"#{reminder[3]} • Fais le {timestampScreen(intToDatetime(reminder[1]))}\n{expiration}", inline = False) - curseur += 1 - else: - embed.add_field(name = "\u200b", value = f"L'utilisateur n'a aucun rappel en attente ou page n°{page} vide !") - embed.set_footer(text = "Les rappels qui ont déjà expirés vont apparaître dans quelques instants.\nIls peuvent avoir jusqu'à 1 minute de retard maximum.") - await ctx.send(embed = embed) + embed, pageMAX = Reminder().embedListe(utilisateur, ctx.guild.id, page) + message = await ctx.send(embed = embed) + if pageMAX > 1: + for emoji in ["⬅️", "➡️"]: + await message.add_reaction(emoji) @cog_ext.cog_slash(name="reminderlist", description = "Affiche la liste des rappels d'un utilisateur.") async def __reminderlist(self, ctx, userorpage = None): if userorpage == None: @@ -180,6 +162,18 @@ class ReminderDiscord(commands.Cog): else: return await self._reminderlist(ctx, userorpage, True) + @commands.Cog.listener() + async def on_raw_reaction_add(self, payload): + message, embed = await Reminder().listReaction(self.client, payload) + if message: + await message.edit(embed = embed) + + @commands.Cog.listener() + async def on_raw_reaction_remove(self, payload): + message, embed = await Reminder().listReaction(self.client, payload) + if message: + await message.edit(embed = embed) + @commands.command(name='reminderdelete', aliases=["reminddelete", "rd"]) async def _reminderdelete(self, ctx, *id): """Suppprime un rappel.⁢⁢⁢⁢⁢\n ➡ Syntaxe: {PREFIX}reminderdelete/rd """ diff --git a/src/utils/reminder.py b/src/utils/reminder.py index 9145ccd..e11ee7f 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -1,4 +1,7 @@ from utils.db import Database +from discord import Embed, Colour +from utils.time import nowUTC, intToDatetime, timedeltaToString, timestampScreen +from re import findall class Reminder(Database): def __init__(self): @@ -66,3 +69,61 @@ class Reminder(Database): ) """ return True if self.affichageResultat(self.requete(requete, [id, userID, guildID]))[0][0] == 1 else False + + def embedListe(self, utilisateur, guildID, page, color = None): + """Fais l'embed d'une page pour l'affichage de la liste des reminders d'un utilisateur""" + reminders = self.listeReminder(utilisateur.id, guildID) + + pageMAX = -(-len(reminders) // 5) + if color == None: + color = Colour.random() + embed = Embed(description = f"**Rappel{'s' if len(reminders) > 1 else ''} de {utilisateur.mention}** • Page {page}/{pageMAX}", color = color) + embed.set_thumbnail(url = utilisateur.avatar_url_as(size = 64)) + limit = 5 * page + if len(reminders) > 0 and page <= pageMAX: + curseur = limit - 4 + for reminder in reminders[limit - 5:]: + if curseur <= limit: + texte = reminder[0] + if len(texte) > 1024: + texte = f"{texte[:1021]}..." + expiration = reminder[2] - int(nowUTC()) + if expiration > 0: + expiration = f"Expire dans {timedeltaToString(expiration)}" + else: + expiration = f"A déjà expiré." + embed.add_field(value = texte, name = f"#{reminder[3]} • Fais le {timestampScreen(intToDatetime(reminder[1]))}\n{expiration}", inline = False) + curseur += 1 + else: + embed.add_field(name = "\u200b", value = f"L'utilisateur n'a aucun rappel en attente ou page n°{page} vide !") + embed.set_footer(text = "Les rappels qui ont déjà expirés vont apparaître dans quelques instants.\nIls peuvent avoir jusqu'à 1 minute de retard maximum.") + return (embed, pageMAX) + + async def listReaction(self, client, payload): + if payload.emoji.name in ["⬅️", "➡️"]: + if payload.event_type == "REACTION_ADD": + if payload.member.bot == True: + return False, False + channel = client.get_channel(payload.channel_id) + message = await channel.fetch_message(payload.message_id) + if message.author.id != client.user.id and len(message.embeds) == 0: # vérification message du bot + au moins 1 embed + return False, False + embed = message.embeds[0].to_dict() + if "description" in embed: # si c'est un embed avec une description + if len(findall(r"\*\*Rappels? de <@\!?\d+>\*\* • Page \d+\/\d+", embed["description"])) == 1: # si c'est le bon embed + infoDescription = findall(r"\*\*Rappels? de <@\!?(\d+)>\*\* • Page (\d+)\/(\d+)", embed["description"])[0] + utilisateur = client.get_user(int(infoDescription[0])) + page = int(infoDescription[1]) + if payload.emoji.name == "⬅️": + if page > 1: + page -= 1 + else: + return False, False + if payload.emoji.name == "➡️": + if page + 1 <= int(infoDescription[2]): + page += 1 + else: + return False, False + embed, _ = Reminder().embedListe(utilisateur, payload.guild_id, page, embed["color"]) + return message, embed + return False, False From e67cc0d542cfe6de7cfdb3f34d92b6e1988f5dde Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 30 Jul 2021 12:47:14 +0200 Subject: [PATCH 259/286] better comma placement --- src/utils/time.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/utils/time.py b/src/utils/time.py index a293d51..2315dfd 100644 --- a/src/utils/time.py +++ b/src/utils/time.py @@ -56,7 +56,8 @@ def timestampScreen(timestamp): def timedeltaToString(time): """Différence entre une heure en seconde et maintenant""" - age = str(timedelta(seconds = time)).replace('day', 'jour').replace(', ', ', :').split(':') + age = str(timedelta(seconds = time)).replace('day', 'jour').replace(', ', ':').split(':') + print(age) if len(age) == 4: a = [1, 1, 1, 1] # a pour affichage if len(age) == 3: @@ -66,7 +67,7 @@ def timedeltaToString(time): if int(age[i]) == 0: a[i] = 0 age[0] = age[0] if a[0] == 1 else '' - age[1] = f"{age[1]}h " if a[1] == 1 else '' + age[1] = f", {age[1]}h " if a[1] == 1 else '' age[2] = f"{age[2]}m " if a[2] == 1 else '' age[3] = f"{age[3]}s" if a[3] == 1 else '' return ''.join(age).strip(' ') From 79ec9cdc57a5e8298bf485c3f813981e871e683f Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 30 Jul 2021 12:47:28 +0200 Subject: [PATCH 260/286] remove print --- src/utils/time.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/utils/time.py b/src/utils/time.py index 2315dfd..6d91a79 100644 --- a/src/utils/time.py +++ b/src/utils/time.py @@ -57,7 +57,6 @@ def timestampScreen(timestamp): def timedeltaToString(time): """Différence entre une heure en seconde et maintenant""" age = str(timedelta(seconds = time)).replace('day', 'jour').replace(', ', ':').split(':') - print(age) if len(age) == 4: a = [1, 1, 1, 1] # a pour affichage if len(age) == 3: From bdc17c1fefa0b9178c8eadc05f7a09c57dee2a5a Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 30 Jul 2021 12:59:53 +0200 Subject: [PATCH 261/286] update reminderlist even when the pageMAX in the message is less or equal than 1 --- src/utils/reminder.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/utils/reminder.py b/src/utils/reminder.py index e11ee7f..288bf85 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -73,7 +73,7 @@ class Reminder(Database): def embedListe(self, utilisateur, guildID, page, color = None): """Fais l'embed d'une page pour l'affichage de la liste des reminders d'un utilisateur""" reminders = self.listeReminder(utilisateur.id, guildID) - + pageMAX = -(-len(reminders) // 5) if color == None: color = Colour.random() @@ -123,7 +123,11 @@ class Reminder(Database): if page + 1 <= int(infoDescription[2]): page += 1 else: - return False, False + pageMAX = -(-len(self.listeReminder(utilisateur.id, payload.guild_id)) // 5) + if pageMAX > 1: + page += 1 + else: + return False, False embed, _ = Reminder().embedListe(utilisateur, payload.guild_id, page, embed["color"]) return message, embed return False, False From b0ed0c918e1e339d184d7f4754e99d2aa970953f Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 30 Jul 2021 13:13:29 +0200 Subject: [PATCH 262/286] better check for the call in the db --- src/utils/reminder.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/utils/reminder.py b/src/utils/reminder.py index 288bf85..1041501 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -123,9 +123,11 @@ class Reminder(Database): if page + 1 <= int(infoDescription[2]): page += 1 else: - pageMAX = -(-len(self.listeReminder(utilisateur.id, payload.guild_id)) // 5) - if pageMAX > 1: - page += 1 + if len(findall(r"L'utilisateur n'a aucun rappel en attente ou page n°\d+ vide !", embed["fields"][0]["value"])) == 1: + if len(self.listeReminder(utilisateur.id, payload.guild_id)) > 0: + page += 1 + else: + return False, False else: return False, False embed, _ = Reminder().embedListe(utilisateur, payload.guild_id, page, embed["color"]) From 69ea7bf5db58f339b518a7497ee480710e5a36e7 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 30 Jul 2021 13:14:36 +0200 Subject: [PATCH 263/286] going back while being in page 1 reach the last page (no call in DB) --- src/utils/reminder.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/utils/reminder.py b/src/utils/reminder.py index 1041501..90d4da3 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -118,7 +118,10 @@ class Reminder(Database): if page > 1: page -= 1 else: - return False, False + if int(infoDescription[2]) > 1: + page += 1 + else: + return False, False if payload.emoji.name == "➡️": if page + 1 <= int(infoDescription[2]): page += 1 From 6f6bd3ac11fa62e84270c78f95d4b0fee3065df0 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 30 Jul 2021 13:57:23 +0200 Subject: [PATCH 264/286] adding refresh button --- src/cogs/reminder.py | 12 ++-- src/utils/reminder.py | 138 +++++++++++++++++++++++------------------- 2 files changed, 84 insertions(+), 66 deletions(-) diff --git a/src/cogs/reminder.py b/src/cogs/reminder.py index 03187bd..33aed37 100644 --- a/src/cogs/reminder.py +++ b/src/cogs/reminder.py @@ -1,7 +1,7 @@ import discord from discord.ext import commands, tasks from discord_slash import cog_ext -from utils.reminder import Reminder +from utils.reminder import Reminder, embedListe, listReaction from utils.core import getURLsInString, getMentionInString, isSlash, mySendHidden, mentionToUser, cleanCodeStringWithMentionAndURLs from utils.time import stringTempsVersSecondes, nowUTC, intToDatetime, timedeltaToString @@ -150,9 +150,11 @@ class ReminderDiscord(commands.Cog): if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') - embed, pageMAX = Reminder().embedListe(utilisateur, ctx.guild.id, page) + embed, pageMAX, refresh = embedListe(utilisateur, ctx.guild.id, page) message = await ctx.send(embed = embed) - if pageMAX > 1: + if refresh: + await message.add_reaction("🔄") + elif pageMAX > 1: for emoji in ["⬅️", "➡️"]: await message.add_reaction(emoji) @cog_ext.cog_slash(name="reminderlist", description = "Affiche la liste des rappels d'un utilisateur.") @@ -164,13 +166,13 @@ class ReminderDiscord(commands.Cog): @commands.Cog.listener() async def on_raw_reaction_add(self, payload): - message, embed = await Reminder().listReaction(self.client, payload) + message, embed = await listReaction(self.client, payload) if message: await message.edit(embed = embed) @commands.Cog.listener() async def on_raw_reaction_remove(self, payload): - message, embed = await Reminder().listReaction(self.client, payload) + message, embed = await listReaction(self.client, payload) if message: await message.edit(embed = embed) diff --git a/src/utils/reminder.py b/src/utils/reminder.py index 90d4da3..6576e0e 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -70,69 +70,85 @@ class Reminder(Database): """ return True if self.affichageResultat(self.requete(requete, [id, userID, guildID]))[0][0] == 1 else False - def embedListe(self, utilisateur, guildID, page, color = None): - """Fais l'embed d'une page pour l'affichage de la liste des reminders d'un utilisateur""" - reminders = self.listeReminder(utilisateur.id, guildID) +def embedListe(utilisateur, guildID, page, color = None): + """Fais l'embed d'une page pour l'affichage de la liste des reminders d'un utilisateur.""" + reminders = Reminder().listeReminder(utilisateur.id, guildID) - pageMAX = -(-len(reminders) // 5) - if color == None: - color = Colour.random() - embed = Embed(description = f"**Rappel{'s' if len(reminders) > 1 else ''} de {utilisateur.mention}** • Page {page}/{pageMAX}", color = color) - embed.set_thumbnail(url = utilisateur.avatar_url_as(size = 64)) - limit = 5 * page - if len(reminders) > 0 and page <= pageMAX: - curseur = limit - 4 - for reminder in reminders[limit - 5:]: - if curseur <= limit: - texte = reminder[0] - if len(texte) > 1024: - texte = f"{texte[:1021]}..." - expiration = reminder[2] - int(nowUTC()) - if expiration > 0: - expiration = f"Expire dans {timedeltaToString(expiration)}" - else: - expiration = f"A déjà expiré." - embed.add_field(value = texte, name = f"#{reminder[3]} • Fais le {timestampScreen(intToDatetime(reminder[1]))}\n{expiration}", inline = False) - curseur += 1 - else: - embed.add_field(name = "\u200b", value = f"L'utilisateur n'a aucun rappel en attente ou page n°{page} vide !") - embed.set_footer(text = "Les rappels qui ont déjà expirés vont apparaître dans quelques instants.\nIls peuvent avoir jusqu'à 1 minute de retard maximum.") - return (embed, pageMAX) + pageMAX = -(-len(reminders) // 5) + if pageMAX > 1: + refresh = False + else: + refresh = True + if color == None: + color = Colour.random() + embed = Embed(description = f"**Rappel{'s' if len(reminders) > 1 else ''} de {utilisateur.mention}** • Page {page}/{pageMAX}", color = color) + embed.set_thumbnail(url = utilisateur.avatar_url_as(size = 64)) + limit = 5 * page + if len(reminders) > 0 and page <= pageMAX: + curseur = limit - 4 + for reminder in reminders[limit - 5:]: + if curseur <= limit: + texte = reminder[0] + if len(texte) > 1024: + texte = f"{texte[:1021]}..." + expiration = reminder[2] - int(nowUTC()) + if expiration > 0: + expiration = f"Expire dans {timedeltaToString(expiration)}" + else: + expiration = f"A déjà expiré." + embed.add_field(value = texte, name = f"#{reminder[3]} • Fais le {timestampScreen(intToDatetime(reminder[1]))}\n{expiration}", inline = False) + curseur += 1 + else: + embed.add_field(name = "\u200b", value = f"L'utilisateur n'a aucun rappel en attente ou page n°{page} vide !") + embed.set_footer(text = "Les rappels qui ont déjà expirés vont apparaître dans quelques instants.\nIls peuvent avoir jusqu'à 1 minute de retard maximum.") + return (embed, pageMAX, refresh) - async def listReaction(self, client, payload): - if payload.emoji.name in ["⬅️", "➡️"]: - if payload.event_type == "REACTION_ADD": - if payload.member.bot == True: - return False, False - channel = client.get_channel(payload.channel_id) - message = await channel.fetch_message(payload.message_id) - if message.author.id != client.user.id and len(message.embeds) == 0: # vérification message du bot + au moins 1 embed +async def listReaction(client, payload): + """Gère le changement de page du reminderlist avec les réactions.""" + if payload.emoji.name in ["⬅️", "🔄", "➡️"]: + if payload.event_type == "REACTION_ADD": + if payload.member.bot == True: return False, False - embed = message.embeds[0].to_dict() - if "description" in embed: # si c'est un embed avec une description - if len(findall(r"\*\*Rappels? de <@\!?\d+>\*\* • Page \d+\/\d+", embed["description"])) == 1: # si c'est le bon embed - infoDescription = findall(r"\*\*Rappels? de <@\!?(\d+)>\*\* • Page (\d+)\/(\d+)", embed["description"])[0] - utilisateur = client.get_user(int(infoDescription[0])) - page = int(infoDescription[1]) - if payload.emoji.name == "⬅️": - if page > 1: - page -= 1 - else: - if int(infoDescription[2]) > 1: - page += 1 - else: - return False, False - if payload.emoji.name == "➡️": - if page + 1 <= int(infoDescription[2]): + channel = client.get_channel(payload.channel_id) + message = await channel.fetch_message(payload.message_id) + if message.author.id != client.user.id and len(message.embeds) == 0: # vérification message du bot + au moins 1 embed + return False, False + embed = message.embeds[0].to_dict() + if "description" in embed: # si c'est un embed avec une description + if len(findall(r"\*\*Rappels? de <@\!?\d+>\*\* • Page \d+\/\d+", embed["description"])) == 1: # si c'est le bon embed + infoDescription = findall(r"\*\*Rappels? de <@\!?(\d+)>\*\* • Page (\d+)\/(\d+)", embed["description"])[0] + utilisateur = client.get_user(int(infoDescription[0])) + page = int(infoDescription[1]) + if payload.emoji.name == "⬅️": + if page > 1: + page -= 1 + else: + if int(infoDescription[2]) > 1: page += 1 else: - if len(findall(r"L'utilisateur n'a aucun rappel en attente ou page n°\d+ vide !", embed["fields"][0]["value"])) == 1: - if len(self.listeReminder(utilisateur.id, payload.guild_id)) > 0: - page += 1 - else: - return False, False - else: - return False, False - embed, _ = Reminder().embedListe(utilisateur, payload.guild_id, page, embed["color"]) - return message, embed - return False, False + return False, False + if payload.emoji.name == "➡️": + if page + 1 <= int(infoDescription[2]): + page += 1 + else: + return False, False + if payload.emoji.name == "🔄": + reminders = Reminder().listeReminder(utilisateur.id, payload.guild_id) + if len(reminders) > 0: + page = 1 + if -(-len(reminders) // 5) > 1 and message.reactions[0] != "⬅️": + for emoji in ["⬅️", "➡️"]: + await message.add_reaction(emoji) + else: + return False, False + embed, _, refresh = embedListe(utilisateur, payload.guild_id, page, embed["color"]) + if refresh: + await message.add_reaction("🔄") + else: + for reaction in message.reactions: + if str(reaction) == "🔄": + users = await reaction.users().flatten() + for user in users: + await message.remove_reaction("🔄", user) + return message, embed + return False, False From 377496b979ac2e948e4111cfc5a2694615420a47 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 30 Jul 2021 20:05:04 +0200 Subject: [PATCH 265/286] fix backward at page 1 not going to last page --- src/utils/reminder.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/reminder.py b/src/utils/reminder.py index 6576e0e..ec507fe 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -124,7 +124,7 @@ async def listReaction(client, payload): page -= 1 else: if int(infoDescription[2]) > 1: - page += 1 + page = int(infoDescription[2]) else: return False, False if payload.emoji.name == "➡️": From 12d4c833dde4f0117f4228f7162dbae2ac1401f7 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 30 Jul 2021 20:07:05 +0200 Subject: [PATCH 266/286] link of the right branch in link --- src/cogs/utils.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index 6d79604..b61de7d 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -236,19 +236,21 @@ class Utils(commands.Cog): dev = self.client.get_user(158260864623968257) + devOrMain = devOrStableChannel() + embed.add_field(name = "Dev", value = f"[{dev}](https://gitlab.com/Mylloon)") embed.add_field(name = "Hébergeur", value = appinfo.owner.mention) embed.add_field(name = f"Serveur{'s' if nombreServeur > 1 else ''}", value = f"`{nombreServeur}`") embed.add_field(name = f"Membre{'s' if total_unique > 1 else ''}", value = f"`{total_unique}` au total\n`{total_online}` en ligne") embed.add_field(name = f"Salon{'s' if (text + voice) > 1 else ''}", value = f"`{text}` textuel{'s' if text > 1 else ''}\n`{voice}` voca{'ux' if voice > 1 else 'l'}") embed.add_field(name = "Prefix", value = f"`{ctx.prefix}`") - embed.add_field(name = "Code source", value = "[Lien Gitlab](https://gitlab.com/ConfrerieDuKassoulait/KassouBot)") + embed.add_field(name = "Code source", value = f"[Lien Gitlab](https://gitlab.com/ConfrerieDuKassoulait/KassouBot/-/tree/{devOrMain})") embed.add_field(name = "Timezone", value = f"`{self.customTimezone}`") changes = getChangelogs(version) version = f"`{version}`" if changes[0] == 200: version = f"[{version}]({changes[1]})" - embed.add_field(name = "Version", value = f"{version} ({devOrStableChannel().replace('main', 'stable')})") + embed.add_field(name = "Version", value = f"{version} ({devOrMain.replace('main', 'stable')})") embed.set_footer(text = f"Basé sur discord.py {discord.__version__}") try: if fromSlash != True: From a7b1defaad74b3a45e9b414268b02f677af9e259 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 30 Jul 2021 20:30:03 +0200 Subject: [PATCH 267/286] removing a call to the database --- src/cogs/reminder.py | 2 +- src/utils/reminder.py | 28 ++++++++++++++++------------ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/src/cogs/reminder.py b/src/cogs/reminder.py index 33aed37..984f95d 100644 --- a/src/cogs/reminder.py +++ b/src/cogs/reminder.py @@ -150,7 +150,7 @@ class ReminderDiscord(commands.Cog): if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') - embed, pageMAX, refresh = embedListe(utilisateur, ctx.guild.id, page) + embed, pageMAX, refresh = await embedListe(utilisateur, ctx.guild.id, page) message = await ctx.send(embed = embed) if refresh: await message.add_reaction("🔄") diff --git a/src/utils/reminder.py b/src/utils/reminder.py index ec507fe..2a9a6d3 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -70,11 +70,19 @@ class Reminder(Database): """ return True if self.affichageResultat(self.requete(requete, [id, userID, guildID]))[0][0] == 1 else False -def embedListe(utilisateur, guildID, page, color = None): +async def embedListe(utilisateur, guildID, page, color = None, refresh_message = None): """Fais l'embed d'une page pour l'affichage de la liste des reminders d'un utilisateur.""" reminders = Reminder().listeReminder(utilisateur.id, guildID) - pageMAX = -(-len(reminders) // 5) + + if refresh_message: + if len(reminders) > 0: + if pageMAX > 1 and refresh_message.reactions[0] != "⬅️": + for emoji in ["⬅️", "➡️"]: + await refresh_message.add_reaction(emoji) + else: + return (False, False, False) + if pageMAX > 1: refresh = False else: @@ -119,6 +127,7 @@ async def listReaction(client, payload): infoDescription = findall(r"\*\*Rappels? de <@\!?(\d+)>\*\* • Page (\d+)\/(\d+)", embed["description"])[0] utilisateur = client.get_user(int(infoDescription[0])) page = int(infoDescription[1]) + refresh_message = None if payload.emoji.name == "⬅️": if page > 1: page -= 1 @@ -133,16 +142,11 @@ async def listReaction(client, payload): else: return False, False if payload.emoji.name == "🔄": - reminders = Reminder().listeReminder(utilisateur.id, payload.guild_id) - if len(reminders) > 0: - page = 1 - if -(-len(reminders) // 5) > 1 and message.reactions[0] != "⬅️": - for emoji in ["⬅️", "➡️"]: - await message.add_reaction(emoji) - else: - return False, False - embed, _, refresh = embedListe(utilisateur, payload.guild_id, page, embed["color"]) - if refresh: + refresh_message = message + embed, _, refresh = await embedListe(utilisateur, payload.guild_id, page, embed["color"], refresh_message) + if embed == False: + return False, False + if refresh == True: await message.add_reaction("🔄") else: for reaction in message.reactions: From 9e8045fe739821fc5470f3a4c7e1822cd07906b6 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 30 Jul 2021 20:32:23 +0200 Subject: [PATCH 268/286] =?UTF-8?q?ajout=20r=C3=A9action=20=E2=9C=85=20lor?= =?UTF-8?q?s=20de=20l'ajout=20d'un=20reminder?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cogs/reminder.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cogs/reminder.py b/src/cogs/reminder.py index 984f95d..acb9f1e 100644 --- a/src/cogs/reminder.py +++ b/src/cogs/reminder.py @@ -115,6 +115,8 @@ class ReminderDiscord(commands.Cog): if fromSlash != True: messageID = ctx.message.id reminderID = Reminder().ajoutReminder(messageID, ctx.channel.id, extrarg, reminder, now, now + seconds, ctx.author.id, guildID) + if fromSlash != True: + await ctx.message.add_reaction(emoji = '✅') return await mySendHidden(ctx, fromSlash, f"Ton reminder **`#{reminderID[0][0]}`** est enrengistré, je te notifie {destination} dans {timedeltaToString(seconds)}{'' if seconds >= 3600 else ' (avec 1m de retard maximum)'}.") await mySendHidden(ctx, fromSlash, embed = embed) @_reminder.error From 05de1704f9970399fa80b056656db94c5fcc8aa7 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 30 Jul 2021 20:59:02 +0200 Subject: [PATCH 269/286] same for the next arrow going to first page when triggered at last page --- src/utils/reminder.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/utils/reminder.py b/src/utils/reminder.py index 2a9a6d3..8af5cb3 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -140,7 +140,10 @@ async def listReaction(client, payload): if page + 1 <= int(infoDescription[2]): page += 1 else: - return False, False + if page > 1: + page = 1 + else: + return False, False if payload.emoji.name == "🔄": refresh_message = message embed, _, refresh = await embedListe(utilisateur, payload.guild_id, page, embed["color"], refresh_message) From d3c609f21bcc7ec2b18005e5f3386e40b0c456da Mon Sep 17 00:00:00 2001 From: Mylloon Date: Fri, 30 Jul 2021 21:06:20 +0200 Subject: [PATCH 270/286] =?UTF-8?q?add=20comment=20+=20fix=20v=C3=A9rifica?= =?UTF-8?q?tion=20message=20du=20bot=20+=20au=20moins=201=20embed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/reminder.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/utils/reminder.py b/src/utils/reminder.py index 8af5cb3..e20c232 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -113,13 +113,14 @@ async def embedListe(utilisateur, guildID, page, color = None, refresh_message = async def listReaction(client, payload): """Gère le changement de page du reminderlist avec les réactions.""" + print(payload) if payload.emoji.name in ["⬅️", "🔄", "➡️"]: if payload.event_type == "REACTION_ADD": - if payload.member.bot == True: + if payload.member.bot == True: # vérifie que c'est pas un bot qui a réagit return False, False channel = client.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) - if message.author.id != client.user.id and len(message.embeds) == 0: # vérification message du bot + au moins 1 embed + if message.author.id != client.user.id or len(message.embeds) == 0: # vérification message du bot + au moins 1 embed return False, False embed = message.embeds[0].to_dict() if "description" in embed: # si c'est un embed avec une description From e599ce93753e982029833efe77f0a35f881a5f3f Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 1 Aug 2021 20:27:04 +0200 Subject: [PATCH 271/286] add env example --- .envexample | 7 +++++++ README.md | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 .envexample diff --git a/.envexample b/.envexample new file mode 100644 index 0000000..9e0ff7a --- /dev/null +++ b/.envexample @@ -0,0 +1,7 @@ +TOKEN_DISCORD= +TOKEN_GENIUS= +TOKEN_REDDIT_CLIENT_ID= +TOKEN_REDDIT_CLIENT_SECRET= +TOKEN_REDDIT_USER_AGENT= +TIMEZONE= +PREFIX= diff --git a/README.md b/README.md index b5309cc..b1e1af0 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,6 @@ To find Genius token, go to [this site](https://genius.com/api-clients), `login - Using SQLite for the database. ## __Launching locally__ -If you want to run it without Docker, create an .env file to store variables in the root folder. +If you want to run it without Docker, create an .env file to store variables in the root folder (there is an example [here](https://gitlab.com/ConfrerieDuKassoulait/KassouBot/-/blob/main/.envexample). Install ffmpeg by doing `sudo apt install ffmpeg` and all the requirements by doing `python3 -m pip install -r requirements.txt` Simply run `python3 main.py` inside the `src` folder to launch the bot in the repo folder. From 4c4d0fe138c7e802f9890f2791123cb6e6af9a66 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 1 Aug 2021 20:27:27 +0200 Subject: [PATCH 272/286] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b1e1af0..2f19dfc 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,6 @@ To find Genius token, go to [this site](https://genius.com/api-clients), `login - Using SQLite for the database. ## __Launching locally__ -If you want to run it without Docker, create an .env file to store variables in the root folder (there is an example [here](https://gitlab.com/ConfrerieDuKassoulait/KassouBot/-/blob/main/.envexample). +If you want to run it without Docker, create an .env file to store variables in the root folder (there is an example [here](https://gitlab.com/ConfrerieDuKassoulait/KassouBot/-/blob/main/.envexample)). Install ffmpeg by doing `sudo apt install ffmpeg` and all the requirements by doing `python3 -m pip install -r requirements.txt` Simply run `python3 main.py` inside the `src` folder to launch the bot in the repo folder. From 6483358978d7efc090f058a2c3b75a6d490c2bee Mon Sep 17 00:00:00 2001 From: Mylloon Date: Sun, 1 Aug 2021 20:51:08 +0200 Subject: [PATCH 273/286] sending hidden message if possible when deleting a reminder --- src/cogs/reminder.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/reminder.py b/src/cogs/reminder.py index acb9f1e..a170756 100644 --- a/src/cogs/reminder.py +++ b/src/cogs/reminder.py @@ -195,7 +195,7 @@ class ReminderDiscord(commands.Cog): Reminder().suppressionReminder(id) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') - return await ctx.send(f"Reminder **#{id}** supprimé !") + return await mySendHidden(ctx, fromSlash, f"Reminder **#{id}** supprimé !") else: if fromSlash != True: await ctx.message.add_reaction(emoji = '❌') From c09c791f1213ec33cae7d7f29351fef78f14edf4 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 2 Aug 2021 10:48:53 +0200 Subject: [PATCH 274/286] remove print --- src/utils/reminder.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/utils/reminder.py b/src/utils/reminder.py index e20c232..bef2316 100644 --- a/src/utils/reminder.py +++ b/src/utils/reminder.py @@ -113,7 +113,6 @@ async def embedListe(utilisateur, guildID, page, color = None, refresh_message = async def listReaction(client, payload): """Gère le changement de page du reminderlist avec les réactions.""" - print(payload) if payload.emoji.name in ["⬅️", "🔄", "➡️"]: if payload.event_type == "REACTION_ADD": if payload.member.bot == True: # vérifie que c'est pas un bot qui a réagit From e801be83621057a3dfcae5615d32adffb8da7fe6 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 2 Aug 2021 11:11:02 +0200 Subject: [PATCH 275/286] fix bug d'affichage avec les heures du reminder --- src/utils/time.py | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/src/utils/time.py b/src/utils/time.py index 6d91a79..5c04ae8 100644 --- a/src/utils/time.py +++ b/src/utils/time.py @@ -1,6 +1,6 @@ from pytz import timezone from datetime import datetime, timedelta -from re import findall +from re import findall, sub from utils.core import load myTimezone = load(["TIMEZONE"])["TIMEZONE"] @@ -56,20 +56,21 @@ def timestampScreen(timestamp): def timedeltaToString(time): """Différence entre une heure en seconde et maintenant""" - age = str(timedelta(seconds = time)).replace('day', 'jour').replace(', ', ':').split(':') - if len(age) == 4: - a = [1, 1, 1, 1] # a pour affichage + age = sub(r' days?, ', ':', str(timedelta(seconds = time))).split(':') + affichage = [1, 1, 1, 1] # len(age) == 4 if len(age) == 3: - a = [0, 1, 1, 1] + affichage = [0, 1, 1, 1] age.insert(0, None) - for i in range(1, 4): + for i in range(1, len(affichage)): if int(age[i]) == 0: - a[i] = 0 - age[0] = age[0] if a[0] == 1 else '' - age[1] = f", {age[1]}h " if a[1] == 1 else '' - age[2] = f"{age[2]}m " if a[2] == 1 else '' - age[3] = f"{age[3]}s" if a[3] == 1 else '' - return ''.join(age).strip(' ') + affichage[i] = 0 + age[0] = f"{age[0]} jour{'s' if int(age[0]) > 1 else ''}" if affichage[0] == 1 else '' + age[1] = f"{age[1]}h" if affichage[1] == 1 else '' + age[2] = f"{age[2]}m" if affichage[2] == 1 else '' + age[3] = f"{age[3]}s" if affichage[3] == 1 else '' + while "" in age: + age.remove("") + return ', '.join(age).strip(' ') def getAge(date): """Décompose la différence entre une date et maintenant avec les bons timezone""" From 45634ba7746fd58b1fdaa3c299c922bab5f85f71 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 2 Aug 2021 11:17:00 +0200 Subject: [PATCH 276/286] Adding bug template --- .gitlab/issue_templates/bug.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .gitlab/issue_templates/bug.md diff --git a/.gitlab/issue_templates/bug.md b/.gitlab/issue_templates/bug.md new file mode 100644 index 0000000..ca68780 --- /dev/null +++ b/.gitlab/issue_templates/bug.md @@ -0,0 +1,13 @@ +## Quick Information +- **Python version:** +- **Bot version:** +- **Client device where the bug occurred:** Computer / Mobile + +## What Happened? +... + +## Expected result +... + +## Steps to reproduce +... From e8303ed05266942565d8aa85fd88a07989dadce7 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 2 Aug 2021 11:18:44 +0200 Subject: [PATCH 277/286] Adding some help to fill the fields --- .gitlab/issue_templates/bug.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitlab/issue_templates/bug.md b/.gitlab/issue_templates/bug.md index ca68780..9a872db 100644 --- a/.gitlab/issue_templates/bug.md +++ b/.gitlab/issue_templates/bug.md @@ -1,6 +1,6 @@ ## Quick Information -- **Python version:** -- **Bot version:** +- **Python version:** +- **Bot version:** - **Client device where the bug occurred:** Computer / Mobile ## What Happened? From c123d04631daecae0c3eed46c745b3f1b1b3fb00 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 2 Aug 2021 11:58:22 +0200 Subject: [PATCH 278/286] Adding weeks and years to reminder --- src/cogs/reminder.py | 5 +++-- src/utils/time.py | 20 +++++++++++++++++--- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/cogs/reminder.py b/src/cogs/reminder.py index a170756..a6ac5ff 100644 --- a/src/cogs/reminder.py +++ b/src/cogs/reminder.py @@ -102,8 +102,9 @@ class ReminderDiscord(commands.Cog): await ctx.message.add_reaction(emoji = '❓') return await mySendHidden(ctx, fromSlash, seconds) if seconds == 0: - embed.add_field(name="Attention", value= - "Format pour le temps : `d` ou `j` pour jour, `h` pour heure, `m` pour minute, `s` pour seconde (légères variances acceptés aussi). \ + embed.add_field(name="Informations", value= + "Format pour le temps : `y` ou `a` pour année, `w` pour semaine, `d` ou `j` pour jour, \ + \n`h` pour heure, `m` pour minute, `s` pour seconde (légères variances acceptés aussi).\n \ \nMet un `@` accolée aux temps pour mentionner les gens mentionner dans ton message. \ \nMet un `P` accolée au temps pour que le bot te DM au lieu de t'envoyer un message dans ce salon." ) diff --git a/src/utils/time.py b/src/utils/time.py index 5c04ae8..6ef3293 100644 --- a/src/utils/time.py +++ b/src/utils/time.py @@ -8,12 +8,13 @@ myTimezone = load(["TIMEZONE"])["TIMEZONE"] def stringTempsVersSecondes(time): """Convertis une durée rentrée par un utilisateur en string vers des secondes en int""" conversionTemps = { + "31536000 ": ["y", "a"], + "604800": ["w"], "86400": ["j", "d"], "3600": ["h"], "60": ["m"], "1": ["s", ""] } - valeursMultiplicateur = "" for i in conversionTemps.values(): for j in i: @@ -57,14 +58,27 @@ def timestampScreen(timestamp): def timedeltaToString(time): """Différence entre une heure en seconde et maintenant""" age = sub(r' days?, ', ':', str(timedelta(seconds = time))).split(':') - affichage = [1, 1, 1, 1] # len(age) == 4 + affichage = [1, 1, 1, 1] if len(age) == 3: affichage = [0, 1, 1, 1] age.insert(0, None) for i in range(1, len(affichage)): if int(age[i]) == 0: affichage[i] = 0 - age[0] = f"{age[0]} jour{'s' if int(age[0]) > 1 else ''}" if affichage[0] == 1 else '' + if affichage[0] == 1: + day = int(age[0]) # récupération du nombre de jour + year = day // 365 # ajout du nombre d'année + day -= year * 365 # suppression des années dans le nombre de jour + week = day // 7 # ajout du nombres de semaines + day -= week * 7 # suppression des semaines dans le nombre du jour + yearINT = year # besoin pour le message age[0] final + year = f"{year} an{'s' if year > 1 else ''}" if year > 0 else "" + weekINT = week # besoin pour le message age[0] final + week = f"{week} semaine{'s' if week > 1 else ''}" if week > 0 else "" + day = f"{day} jour{'s' if day > 1 else ''}" if day > 0 else "" + age[0] = f"{year}{', ' if yearINT > 0 else ''}{week}{', ' if weekINT > 0 else ''}{day}" + else: + age[0] = "" age[1] = f"{age[1]}h" if affichage[1] == 1 else '' age[2] = f"{age[2]}m" if affichage[2] == 1 else '' age[3] = f"{age[3]}s" if affichage[3] == 1 else '' From e494990673a3fdf98520a2c44191808ad6d525e1 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 2 Aug 2021 12:26:18 +0200 Subject: [PATCH 279/286] Added possibility to disable cogs with an environment variable (mainly for Docker) --- README.md | 3 +++ src/main.py | 13 +++++++++++-- src/utils/core.py | 12 +++++++++--- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 2f19dfc..fc26105 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,9 @@ docker run -d \ -v /here/your/path/:/db ``` +You can add the environment variable `DEACTIVATE` to disable some cogs (separate the cogs with commas and no spaces between). +You may have to recreate the container on Docker to re-enable the disabled cogs. + To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and here are the instructions: ![instructions](https://i.imgur.com/tEzYKDA.png) *redirection uri (for copy/paste) : http://localhost:8080* diff --git a/src/main.py b/src/main.py index 0591b55..2069206 100644 --- a/src/main.py +++ b/src/main.py @@ -1,17 +1,26 @@ print("Chargement des extensions & librairie...", end = " ") import discord -from os import listdir +from os import listdir, rename, getcwd from discord_slash import SlashCommand from discord.ext import commands from utils.reminder import Reminder from utils.core import load -keys = load(["PREFIX", "TOKEN_DISCORD"]) +keys = load(["PREFIX", "TOKEN_DISCORD", "DEACTIVATION"]) customPrefix = keys["PREFIX"] client = commands.Bot(command_prefix = customPrefix, case_insensitive = True, intents = discord.Intents.all()) slash = SlashCommand(client, sync_commands = True) +if keys["DEACTIVATION"] != "None": + path = getcwd() + for file in keys["DEACTIVATION"]: + try: + rename(f"{path}/cogs/{file}.py", f"{path}/cogs/-{file}.py") # désactivation + except: + print(f"\nNo file {file} found, check your \"DEACTIVATION\" variable.") + exit(1) + for file in listdir("cogs"): if file.endswith(".py") and file.startswith("-") == False: client.load_extension(f"cogs.{file[:-3]}") diff --git a/src/utils/core.py b/src/utils/core.py index 84f0d08..56e8098 100644 --- a/src/utils/core.py +++ b/src/utils/core.py @@ -171,9 +171,15 @@ def load(variables): load_dotenv() # load .env file for var in variables: try: - keys[var] = environ[var] + res = environ[var] + if var == "DEACTIVATION": + res = list(set(res.split(',')) - {""}) # create a list for the cogs we need to deactivate and remove blank channels and doubles + keys[var] = res except KeyError: - print(f"Please set the environment variable {var} (.env file supported)") - exit(1) + if var == "DEACTIVATION": + keys[var] = "None" + else: + print(f"Please set the environment variable {var} (.env file supported)") + exit(1) return keys From 9d56e1d3cdd27ab408f6cd805557a5dd3619741e Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 2 Aug 2021 12:37:07 +0200 Subject: [PATCH 280/286] fix variable name --- src/main.py | 6 +++--- src/utils/core.py | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main.py b/src/main.py index 2069206..ab5a5e7 100644 --- a/src/main.py +++ b/src/main.py @@ -12,13 +12,13 @@ customPrefix = keys["PREFIX"] client = commands.Bot(command_prefix = customPrefix, case_insensitive = True, intents = discord.Intents.all()) slash = SlashCommand(client, sync_commands = True) -if keys["DEACTIVATION"] != "None": +if keys["DEACTIVATE"] != "None": path = getcwd() - for file in keys["DEACTIVATION"]: + for file in keys["DEACTIVATE"]: try: rename(f"{path}/cogs/{file}.py", f"{path}/cogs/-{file}.py") # désactivation except: - print(f"\nNo file {file} found, check your \"DEACTIVATION\" variable.") + print(f"\nNo file {file} found, check your \"DEACTIVATE\" variable.") exit(1) for file in listdir("cogs"): diff --git a/src/utils/core.py b/src/utils/core.py index 56e8098..7000f9f 100644 --- a/src/utils/core.py +++ b/src/utils/core.py @@ -172,11 +172,11 @@ def load(variables): for var in variables: try: res = environ[var] - if var == "DEACTIVATION": + if var == "DEACTIVATE": res = list(set(res.split(',')) - {""}) # create a list for the cogs we need to deactivate and remove blank channels and doubles keys[var] = res except KeyError: - if var == "DEACTIVATION": + if var == "DEACTIVATE": keys[var] = "None" else: print(f"Please set the environment variable {var} (.env file supported)") From 480c9d631deca99e9f827da8f506a9fb611ae7e6 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 2 Aug 2021 12:38:34 +0200 Subject: [PATCH 281/286] remove useless message --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index fc26105..78edf9e 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,6 @@ docker run -d \ ``` You can add the environment variable `DEACTIVATE` to disable some cogs (separate the cogs with commas and no spaces between). -You may have to recreate the container on Docker to re-enable the disabled cogs. To find reddit tokens, go to [this site](https://www.reddit.com/prefs/apps) and here are the instructions: ![instructions](https://i.imgur.com/tEzYKDA.png) *redirection uri (for copy/paste) : http://localhost:8080* From 473f432fb6afe85876d96218fe1f6feb4af2ab9c Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 2 Aug 2021 12:50:08 +0200 Subject: [PATCH 282/286] remove newline --- src/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.py b/src/main.py index ab5a5e7..1332852 100644 --- a/src/main.py +++ b/src/main.py @@ -18,7 +18,7 @@ if keys["DEACTIVATE"] != "None": try: rename(f"{path}/cogs/{file}.py", f"{path}/cogs/-{file}.py") # désactivation except: - print(f"\nNo file {file} found, check your \"DEACTIVATE\" variable.") + print(f"No file {file} found, check your \"DEACTIVATE\" variable.") exit(1) for file in listdir("cogs"): From 52c9817fc5911dd3fb59f6773b6fce081200c8d1 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 2 Aug 2021 12:50:38 +0200 Subject: [PATCH 283/286] change variable, sorry --- src/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.py b/src/main.py index 1332852..ca32f38 100644 --- a/src/main.py +++ b/src/main.py @@ -6,7 +6,7 @@ from discord_slash import SlashCommand from discord.ext import commands from utils.reminder import Reminder from utils.core import load -keys = load(["PREFIX", "TOKEN_DISCORD", "DEACTIVATION"]) +keys = load(["PREFIX", "TOKEN_DISCORD", "DEACTIVATE"]) customPrefix = keys["PREFIX"] client = commands.Bot(command_prefix = customPrefix, case_insensitive = True, intents = discord.Intents.all()) From 84baa4c429ed7f7d1505665909acd94aebd1ca40 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 2 Aug 2021 23:50:20 +0200 Subject: [PATCH 284/286] Change message of new reminder --- src/cogs/reminder.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/reminder.py b/src/cogs/reminder.py index a6ac5ff..a8fc8e5 100644 --- a/src/cogs/reminder.py +++ b/src/cogs/reminder.py @@ -118,7 +118,7 @@ class ReminderDiscord(commands.Cog): reminderID = Reminder().ajoutReminder(messageID, ctx.channel.id, extrarg, reminder, now, now + seconds, ctx.author.id, guildID) if fromSlash != True: await ctx.message.add_reaction(emoji = '✅') - return await mySendHidden(ctx, fromSlash, f"Ton reminder **`#{reminderID[0][0]}`** est enrengistré, je te notifie {destination} dans {timedeltaToString(seconds)}{'' if seconds >= 3600 else ' (avec 1m de retard maximum)'}.") + return await mySendHidden(ctx, fromSlash, f"Reminder **`#{reminderID[0][0]}`** enrengistré ! Notification {destination} dans {timedeltaToString(seconds)}{'' if seconds >= 3600 else ' (avec 1m de retard maximum)'}.") await mySendHidden(ctx, fromSlash, embed = embed) @_reminder.error async def _reminder_error(self, ctx, error): From d01fb02267f6a81bec9f77a9319ab6339bcbc421 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Mon, 2 Aug 2021 23:50:30 +0200 Subject: [PATCH 285/286] Adding discord link instead of Gitlab link --- src/cogs/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/utils.py b/src/cogs/utils.py index b61de7d..543a694 100644 --- a/src/cogs/utils.py +++ b/src/cogs/utils.py @@ -238,7 +238,7 @@ class Utils(commands.Cog): devOrMain = devOrStableChannel() - embed.add_field(name = "Dev", value = f"[{dev}](https://gitlab.com/Mylloon)") + embed.add_field(name = "Dev", value = f"[{dev}](https://discord.gg/Z5ePxH4)") embed.add_field(name = "Hébergeur", value = appinfo.owner.mention) embed.add_field(name = f"Serveur{'s' if nombreServeur > 1 else ''}", value = f"`{nombreServeur}`") embed.add_field(name = f"Membre{'s' if total_unique > 1 else ''}", value = f"`{total_unique}` au total\n`{total_online}` en ligne") From 93c2b5e61084a0f9a1ccb41331a87e6e813f209a Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 4 Aug 2021 09:35:09 +0200 Subject: [PATCH 286/286] Modification on reminder message confirmation --- src/cogs/reminder.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cogs/reminder.py b/src/cogs/reminder.py index a8fc8e5..47a032a 100644 --- a/src/cogs/reminder.py +++ b/src/cogs/reminder.py @@ -82,7 +82,7 @@ class ReminderDiscord(commands.Cog): embed = discord.Embed(color = 0xC41B1B) extrarg = 0 guildID = ctx.guild.id # can be set to 0 if its a DM message, so it can be see from anywhere - destination = "ici" + destination = "dans ce salon" if not reminder: reminder = "Notification" if time == "help":