-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
368 lines (337 loc) · 12.7 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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import asyncio
import json
import logging
import sys
from datetime import datetime
from typing import Optional
import aiomysql
import discord
from aiohttp import ClientSession
from discord.ext import commands
from discord.ext.commands import when_mentioned_or
from src.constants import *
from src.db import Pool
from src.utils import dctt
from discord_slash import SlashCommand
MAX_RETRIES = 10
INTENTS = discord.Intents(
guild_messages=True,
guild_reactions=True,
presences=True,
messages=True,
# emojis=True,
guilds=True,
members=True
)
# INTENTS = discord.Intents.all()
logger = logging.getLogger("lyvego")
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(
filename='lyvego.log',
encoding='utf-8',
mode='w'
)
handler.setFormatter(logging.Formatter(
'%(asctime)s:%(levelname)s:%(name)s: %(message)s'
)
)
logger.addHandler(handler)
class Lyvego(commands.AutoShardedBot, Pool):
__slots__ = (
"http_session",
"pool",
"red",
"green",
"blue",
"color",
"color_str",
"locales",
"lyvego_url",
"start_time",
"_debug",
"slash"
)
def __init__(self, *args, **kwargs):
self._debug = kwargs.get("debug", False)
super().__init__(
command_prefix=self._get_prefix,
case_insensitive=True,
activity=discord.Game(
name="Starting..."
),
status=discord.Status.dnd,
# member_cache_flags=discord.MemberCacheFlags.from_intents(INTENTS),
intents=INTENTS
)
self.slash = SlashCommand(
self,
sync_commands=True,
sync_on_cog_reload=True
)
super(Pool, self).__init__()
self.http_session = None
self.pool = None
self.red = 0xde1616
self.green = 0x17ad3f
self.blue = 0x158ed4
self.color = 0x6441a5
self.color_str = str(hex(self.color))[2:]
self.start_time = datetime.utcnow()
self.locales = {}
self.lyvego_url = "https://lyvego.com"
self.load_locales()
self.remove_command("help")
self.load_cogs()
async def _get_prefix(self, bot, message):
try:
prefix = await self.getg_prefix(message.guild.id)
except:
prefix = "!!"
return when_mentioned_or(prefix)(bot, message)
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_guild_join(self, guild: discord.Guild):
icon = None
try:
acc = 0
backoff_time = 2
# try:
# icon = guild.icon_url
# except:
# icon = None
r = await self.http_session.request(
method="POST",
url="https://api.lyvego.com/v1/bot/server",
headers={"Authorization": AUTHORIZATION},
json={
"discord_id": guild.id,
"owner_id": guild.owner_id,
"name": guild.name,
"icon": icon,
"region": guild.region.name
}
)
while r.status not in range(200, 300) and acc < MAX_RETRIES:
r = await self.http_session.request(
method="POST",
url="https://api.lyvego.com/v1/bot/server",
headers={"Authorization": AUTHORIZATION},
json={
"discord_id": guild.id,
"owner_id": guild.owner_id,
"name": guild.name,
"icon": icon,
"region": guild.region.name
}
)
await asyncio.sleep(backoff_time)
backoff_time *= 1.12
acc += 1
except:
print(f"{guild.name} cannot be added to the DB", file=sys.stderr)
chan_logger = self.get_channel(739633667906732143)
embed = discord.Embed(
title="Bot added to " + guild.name,
timestamp=dctt(),
color=self.color
)
embed.add_field(
name="<:users:693053423494365214> Members",
value=len(guild.members)
)
embed.add_field(
name="<:hashtag:693056105076621342> Channels",
value=len(guild.channels)
)
embed.set_thumbnail(url=guild.icon_url)
embed.set_footer(icon_url=guild.me.avatar_url)
await chan_logger.send(embed=embed)
async def on_guild_remove(self, guild: discord.Guild):
try:
await self.http_session.request(
method="DELETE",
url=f"{API_ROOT}bot/server/{guild.id}",
headers={"Authorization": AUTHORIZATION}
)
except Exception as e:
logger.exception(e, exc_info=True)
async def on_command_error(self, ctx: commands.Context, error: commands.CommandError):
if str(ctx.command) in ("help"):
return
if isinstance(error, commands.CommandOnCooldown):
try:
await ctx.message.add_reaction("<a:loading:709745917343039530>")
except:
pass
lang = await self.getg_lang(ctx.guild.id)
await ctx.send(self.locales[lang]["error_ratelimited"].format(ctx.author.mention, error.retry_after))
else:
try:
await ctx.message.add_reaction("<a:wrong_checkmark:709737435889664112>")
except:
pass
try:
await ctx.send(error.original)
except AttributeError:
await ctx.send(error)
@staticmethod
def _value_exist(L, v):
try:
return isinstance(L.index(v), int)
except ValueError:
return False
async def _verify_servers(self):
servers = await self.get_guilds_registered()
bot_guilds_ids = []
acc_removed = 0
acc_added = 0
icon = None
for bguild in self.guilds:
bot_guilds_ids.append(str(bguild.id))
if not self._value_exist(servers, str(bguild.id)):
try:
# try:
# icon = bguild.icon_url
# except:
# icon = None
acc_added += 1
await self.http_session.request(
method="POST",
url=f"{API_ROOT}bot/server",
headers={"Authorization": AUTHORIZATION},
json={
"discord_id": bguild.id,
"owner_id": bguild.owner_id,
"name": bguild.name,
"icon": None,
"region": bguild.region.name
}
)
logger.info(f"{bguild.id} added by verifier")
await asyncio.sleep(.2)
except Exception as e:
logger.exception(e, exc_info=True)
for bdsid in servers:
if not self._value_exist(bot_guilds_ids, bdsid):
try:
acc_removed += 1
# await self.http_session.request(
# method="DELETE",
# url=f"{API_ROOT}bot/server/{bdsid}",
# headers={"Authorization": AUTHORIZATION}
# )
# logger.info(f"{bdsid} removed by verifier")
except Exception as e:
logger.exception(e, exc_info=True)
await asyncio.sleep(1)
logger.info(
f"{acc_removed} / {len(self.guilds)} should be REMOVED and {acc_added} / {len(self.guilds)} should be ADDED")
def load_locales(self):
for file in os.listdir("locales/"):
with open(f"locales/{file}", "r") as f:
self.locales[file[:2]] = json.load(f)
async def update_role(self, member: discord.Member, is_adding):
try:
role_name = await self.get_server_role_activity(member.guild.id)
except:
return
role = discord.utils.get(member.guild.roles, name=role_name)
if role != None:
if is_adding:
await member.add_roles(role, reason=self.locales["activity_start_streaming"])
else:
await member.remove_roles(role, reason=self.locales["activity_stop_streaming"])
async def on_member_update(self, before: discord.Member, after: discord.Member):
# print(before.name, before.activities, after.activities, sep="\n")
# print(f"{before.name} : streaming : {isinstance(before.activity, discord.Streaming)}, {isinstance(after.activity, discord.Streaming)}")
if isinstance(after.activity, discord.Streaming) and isinstance(before.activity, discord.Streaming) is False:
await self.update_role(after, True)
elif isinstance(before.activity, discord.Streaming) and isinstance(after.activity, discord.Streaming) is False:
await self.update_role(after, False)
async def on_message(self, message: discord.Message):
if message.author.bot:
return
await self.process_commands(message)
async def startup_tasks(self):
if self.http_session is None:
# Create http session
self.http_session = ClientSession(loop=self.loop)
try:
# Create pool
if self.pool is None:
try:
self.pool = await aiomysql.create_pool(
host=HOST,
port=PORT,
user=DB_USER,
password=PASSWORD,
db=DB_USER,
loop=self.loop,
autocommit=True
)
# TODO : make more secure way to verify guilds
if not self._debug:
self.loop.create_task(self._verify_servers())
logger.info("Pool created")
except Exception as e:
logger.exception(e, exc_info=True)
except Exception as e:
logger.exception(e, exc_info=True)
async def on_ready(self):
await self.startup_tasks()
await self.change_presence(
activity=discord.Activity(
name="!!help | lyvego.com",
type=discord.ActivityType.watching
)
)
logger.info("Lyvego ready")
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("Lyvego has been shutted down")
sys.exit(0)
def run(self, *args, **kwargs):
try:
super().run(TOKEN if not self._debug else TOKEN_DEBUG, *args, **kwargs)
except KeyboardInterrupt:
self._exit()
# async def run(self, token, *args, **kwargs):
# try:
# await self.start(token, *args, **kwargs)
# except KeyboardInterrupt:
# self._exit()
def multi_tokens_runner(loop: asyncio.AbstractEventLoop, bot: Lyvego, *tokens):
for token in tokens:
loop.create_task(bot.run(token, reconnect=True))
logger.info(f"BOT {token} is now running")
if __name__ == "__main__":
debug = False
if not debug:
try:
# Debugger
import sentry_sdk
from sentry_sdk.integrations.aiohttp import AioHttpIntegration
sentry_sdk.init(
SENTRY_TOKEN,
traces_sample_rate=1.0,
integrations=[AioHttpIntegration()]
)
except Exception as e:
logger.exception(e, exc_info=True)
bot = Lyvego(debug=debug)
bot.run(reconnect=True)