-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.py
234 lines (204 loc) · 9.24 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import discord
from discord import message
from discord.ext import commands
from discord_slash import SlashCommand
import traceback
import logging
import sys
import os
from src.database import DB
from src.constants import BOT
from typing import Optional
import datetime as dt
logger = logging.getLogger("licence")
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(
filename='licence.log',
encoding='utf-8',
mode='w'
)
handler.setFormatter(logging.Formatter(
'%(asctime)s:%(levelname)s:%(name)s: %(message)s'
))
logger.addHandler(handler)
class Licence(commands.AutoShardedBot, DB):
def __init__(self, *args, **kwargs):
intents = discord.Intents.default()
intents.members = True
super().__init__(
activity=discord.Game(
name="Starting..."
),
status=discord.Status.dnd,
command_prefix="uca",
intents=intents
)
self.slash = SlashCommand(
self,
sync_commands=True,
sync_on_cog_reload=True
)
super(DB, self).__init__()
self.remove_command("help")
self._color = 0x007fa3
self._footer_text = "Licence Informatique@UCA"
self._icon_url = "https://usercontent.stantabcorp.com/~thibault/46d34e1eccb244ceabd468f3d597e853-logo-rond-l.png"
self.load_cogs()
def _exit(self):
try:
self.loop.run_until_complete(self._close())
logger.info("Pool closed")
except Exception as e:
logger.exception(e, exc_info=True)
sys.exit(1)
finally:
logger.info("Licence has been shutted down")
sys.exit(0)
def run(self, *args, **kwargs):
try:
super().run(BOT, *args, **kwargs)
except KeyboardInterrupt:
self._exit()
@property
def color(self):
return self._color
async def on_member_join(self, member):
if member.dm_channel is None:
await member.create_dm()
channel = member.dm_channel
embed = discord.Embed(
color=self.color,
description="Bienvenue sur le discord **Licence Informatique@UCA** ce lieu a pour vocation d'être ta place de communication avec les autres étudiants et les professeurs durant ta licence.\n\nCe serveur est gérer par des étudiants et il se doit de rester un espace propre, pour cela, nous avons mis en places quelques règles que tu retrouveras dans <#743452204207439913>.\n\nN’oublie pas de choisir également un rôle pour avoir accès à tes cours dans <#748152325654446110>.\n\n**Un petit mot sur moi :** Mes créateurs, ne sont plus en licence et pour certains plus à l’université. C’est pour cela qu’ils ont besoin de toi afin que tu me maintiennes et que je continue à fonctionner pour tous les étudiants, je suis fait en Python et tu vas voir c’est simple, tout ce passe sur github : [https://github.com/thibaultjunin/discord-licence](https://github.com/thibaultjunin/discord-licence)\n**On compte sur toi !**",
timestamp=dt.datetime.utcnow()
)
embed.set_author(
name="Bienvenue sur le discord de la licence informatique à l'Université Côte d'Azur !",
icon_url=self.icon_url
)
embed.set_thumbnail(url=self.icon_url)
embed.set_footer(
text=self.footer_text,
icon_url=self.icon_url
)
await channel.send(embed=embed)
def load_cogs(self, reloading: Optional[bool] = False):
for file in os.listdir("cogs/"):
try:
if file.endswith(".py"):
if reloading:
self.reload_extension(f'cogs.{file[:-3]}')
else:
self.load_extension(f'cogs.{file[:-3]}')
logger.info(f"{file} loaded")
except Exception:
logger.exception(f"Fail to load {file}")
async def on_ready(self):
await self.init()
await self.change_presence(
activity=None,
status=discord.Status.online
)
await self.set_up_role_on_start()
logger.info("Licence ready")
@property
def footer_text(self):
return self._footer_text
@property
def icon_url(self):
return self._icon_url
async def set_up_role_on_start(self):
guilds = self.guilds
for guild in guilds:
guild: discord.Guild
row = await self.get_all_by_guild(guild.id)
users_roles_deleted = []
for r in row:
message_id = r['message_id']
channel_id = r['channel_id']
channel: discord.TextChannel = guild.get_channel(channel_id)
try:
message: discord.Message = await channel.fetch_message(message_id)
reactions = message.reactions
for reaction in reactions:
users = await reaction.users().flatten()
for user in users:
if not user == self.user and user not in users_roles_deleted:
roles_user = user.roles
roles = []
for role in roles_user:
if not role.permissions.administrator and role.name != '@everyone':
roles.append(role)
await user.remove_roles(*roles)
users_roles_deleted.append(user)
logger.info(f"remove all roles of {user}")
except Exception as e:
logger.exception("\n".join(traceback.format_exception(type(e), e, e.__traceback__)))
for r in row:
message_id = r['message_id']
channel_id = r['channel_id']
channel: discord.TextChannel = guild.get_channel(channel_id)
try:
message: discord.Message = await channel.fetch_message(message_id)
reactions = message.reactions
for reaction in reactions:
users = await reaction.users().flatten()
for user in users:
if user != self.user:
role_id = await self.get_role_id_by_emoji_name(guild.id, reaction.emoji, message_id)
user: discord.Member
role: discord.Role = guild.get_role(role_id)
if not role in user.roles:
await user.add_roles(role)
logger.info(f"add role {role} to {user}")
except Exception as e:
logger.exception("\n".join(traceback.format_exception(type(e), e, e.__traceback__)))
async def on_command_error(self, ctx: commands.Context, error: commands.CommandError):
# Log every errors in the on_command_error event
logger.exception("\n".join(traceback.format_exception(type(error), error, error.__traceback__)))
# if isinstance(error, commands.CommandNotFound):
# return await ctx.send("Cette commande n'existe pas.")
# Handling Command Not Found Errors
# raise error
# embed = discord.Embed(
# title="Error",
# description=error,
# timestamp=dt.datetime.utcnow(),
# color=self.color
# )
# await ctx.send(embed=embed)
async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):
guild = await self.fetch_guild(payload.guild_id)
user: discord.Member = await guild.fetch_member(payload.user_id)
if user.bot:
return
if payload.emoji.is_custom_emoji():
role_id = await self.get_role_id(guild.id, payload.emoji.id, payload.message_id)
else:
role_id = await self.get_role_id_by_emoji_name(guild.id, str(payload.emoji.name), payload.message_id)
if role_id is None:
logger.info(f"{user} a ajouté une réaction inconnu au message.")
return
role: discord.Role = guild.get_role(role_id)
if role in user.roles:
return
await user.add_roles(role)
logger.info(
f"Le role {role.name} a été ajouté de l'utilisateur {user}")
async def on_raw_reaction_remove(self, payload: discord.RawReactionActionEvent):
guild = await self.fetch_guild(payload.guild_id)
user: discord.Member = await guild.fetch_member(payload.user_id)
if user.bot:
return
if payload.emoji.is_custom_emoji():
role_id = await self.get_role_id(guild.id, payload.emoji.id, payload.message_id)
else:
role_id = await self.get_role_id_by_emoji_name(guild.id, str(payload.emoji.name), payload.message_id)
if role_id is None:
return
role: discord.Role = guild.get_role(role_id)
await user.remove_roles(role)
logger.info(
f"Le role {role.name} a été supprimé de l'utilisateur {user}")
if __name__ == "__main__":
bot = Licence()
bot.run(reconnect=True)