-
Notifications
You must be signed in to change notification settings - Fork 0
/
main
executable file
·420 lines (346 loc) · 11.9 KB
/
main
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
#!/usr/bin/env python3
#TODO:
# logging non funziona giusto
# addreact non funziona in più server
# canale bot-log
# addreact è brutto quando rispondi ai PM
from cst_logging import log_async, output_channel, output_channels_add, indent_level_push, indent_level_pop, indent_level_reset
from botTalk import getresponse, talkbot_init, talkbot_exit
# from stringOps import replace
from timecheck import TimeCheckLoop, AddNewReminder, SetReminderFunction
from quotes import getquote
from common import *
import discord
import os
import sys as sus
from threading import Thread
with open("TOKEN") as f:
TOKEN = f.read(-1)
from er import er as er
from er import ID10T_Exception
import random
from excFormatter import Format
#define the client
client = discord.Client(
intents=discord.Intents.all()
)
def cls():
import platform #cpcls
os.system("cls" if platform.system() == "Windows" else "clear")
def shell():
while True:
inp = input(">>> ")
if inp == "exit": break
os.system(inp)
#funcs
def GetChannel(name : str) -> discord.TextChannel:
for channel in client.get_all_channels():
if channel.name == name:
return channel
return None
def GetUser(name : str) -> discord.User:
for user in client.get_all_members():
if user.name == name:
return user
return None
def GetRole(name: str) -> discord.Role:
pass
def GetEmote(name : str) -> discord.Emoji:
for emote in client.emojis:
if emote.name == name:
return emote
return None
def GetPing(name : str) -> str:
return "<@!" + str(GetUser(name).id) + ">"
def GetChannelLink(name : str) -> str:
return GetChannel(name).mention
def GetPingVictim(servername: str) -> str:
user_dict = {
"Movimento Indipendentista del Candystan" : "afflo",
"GliUbriachiDelSabatoSera" : "Borsez",
}
return GetPing(user_dict[servername])
# def sendlog_noasync(message):
# import asyncio
# asyncio.run(SendLog(message))
async def SendLog(message):
await GetChannel(BOT_LOG_CHANNEL).send(message)
async def PingBorse(channel):
await channel.send(GetPing("Borsez"))
async def PingVictim(channel):
await channel.send(GetPingVictim(channel.guild.name))
# def exit():
# sus.setrecursionlimit(10**8)
# exit()
#events
@client.event
async def on_ready():
print(f'successfully logged in as {client.user}')
#set this
global SELF_PING
SELF_PING = GetPing(client.user.name)
from time import time
random.seed(time())
#aggiunge un collegamento a generale alle info del bot. non possiamo settarlo insieme al resto del messaggio perché il client non è attivo
global BOT_INFO
BOT_INFO = BOT_INFO.replace("#", GetChannelLink("bot-tests"))
updatereactions()
#funziona solo se il bot è connesso a un server solo
if MODS == []:
for member in discord.utils.get(await client.guilds[0].fetch_roles(), name="mod").members:
if not member == client.user:
MODS.append(member)
#ENDIF
await SendLog(INIT_SUCC_MSG)
def updatereactions():
global REACTIONS
with open(REACTIONS_FILE) as rfile:
import ast
_ = "{" + "".join(rfile.readlines(-1)) + "}"
REACTIONS = ast.literal_eval(_)
@client.event
async def on_message(message: discord.Message):
indent_level_reset()
#è
try:
# if message.author.id == 886477323812110356:
# await message.channel.send(random.choice(["shut up", "dumbass", "fuck off", "i'll ban you", f"imagine being {message.author.mention}", "learn to write idiot", "", "i'll fucking turn you off if you don't shut up now", f"\"{message.author.mention}\" means 'idiot' in ancient Latin", "excuse me, i couldn't find any sign of intelligence in your message"]))
# return
if isinstance(message.channel, discord.DMChannel):
await respond_pm(message)
else:
if message.author == client.user:
return
await log_async("received message:")
indent_level_push()
await log_async(message.content)
channel: discord.TextChannel = message.channel
contl: str = message.content.lower()
#se è un comando normale
if message.content.startswith(COMMAND_PREFIX):
channel: discord.TextChannel = message.channel
msg: str = message.content[len(COMMAND_PREFIX):] #teniamo solo il comando in se in modo che non dobbiamo preoccuparci del prefisso se cambia
tokens = msg.split(" ")
try:
await NormalCommands(tokens, message, channel)
except NotImplementedError:
await channel.send("il comando non funziona ancora, quindi non puoi usarlo")
if random.randint(0,3) == 0: await channel.send("coglione")
return
# #se è un comando superuser
# elif message.content.startswith(SUPERUSER_PREFIX):
# await SuperuserCommands(message)
# return
if DO_CHATBOT is True:
#if we get a ping we call cleverbot chat
if SELF_PING in message.content or client.user.mention in message.content:
async with message.channel.typing():
#await channel.send(random.choice(PING_ANSWERS) if random.randint(0, len(PING_ANSWERS) + 1) != 0 else message.author.mention)
await log_async("initiating chat")
msg: str = message.content
#cambiamo dal ping a un nome generico, in modo che quella stringa di numeri non mandi in palla l'IA
if client.user.mention in msg:
msg = msg.replace(client.user.mention, "")
else: #if either of the two always
msg = msg.replace(SELF_PING, "")
#sostituisci eventuali menzioni
for member in message.guild.members:
if member.mention in msg:
msg = msg.replace(member.mention, member.display_name)
response = await getresponse(msg)
await log_async("out of getresponse function")
await message.reply(response, mention_author=False)
return
#END
#END
#these are absolutely necessary
import re
if re.search(u'[\u4e00-\u9fff]+', message.content) is not None:
await channel.send(random.choice(CHINESE_ANSWERS))
if "python" in contl:
await channel.send(random.choice(PYTHON_ANSWERS))
if "gatt" in contl:
await PingBorse(channel)
if "grazie" in contl:
await message.reply(random.choice(RISPOSTE_GRAZIE))
if "1984" in contl:
await channel.send("https://c.tenor.com/KpzU7TGzfEcAAAAM/1984-skander.gif")
if "chad" in contl:
await channel.send("https://tenor.com/view/gigachad-chad-gif-20773266")
#aiuto a parte il comando
if contl in ["help", "aiuto"]:
await channel.send(HELP_MSG_2)
#END WITH
#invalid commando
except ID10T_Exception:
await channel.send(er())
#un altro problemo
except Exception as e:
await channel.send(er())
await SendLog(f"il seguente messaggio ha causato un problema:\n{message.content}\n\nl'errore:\n" + Format(e))
async def respond_pm(message: discord.Message): #TODO: rendere il no una risposta utile
if message.author in MODS:
if message.content.lower().startswith("y"):
try:
reaction = (await message.channel.fetch_message(message.reference.message_id)).content
reaction = reaction.split("\n") #TODO: rendere il messaggio cambiabile e farlo comunque funzionare
if reaction[1] in REACTIONS.keys():
await message.channel.send("è già stata aggiunta")
return
with open(REACTIONS_FILE, "a") as file:
file.write(f'"{reaction[1]}" : "{reaction[2]}",\n')
except Exception as e:
import excFormatter
await log_async("error:\n" + excFormatter.Format(e), do_indent=False)
else:
await message.channel.send("successfully added!")
await log_async("nuova reazione tenor aggiunta")
updatereactions()
async def NormalCommands(tokens: list[str], message: discord.Message, channel: discord.TextChannel):
match tokens[0]:
case "superuser":
await SuperuserCommands(tokens[1:], message, channel)
case "help":
msg = HELP_MSG.replace("@", GetPingVictim(channel.guild.name))
await channel.send(msg)
await channel.send("reazioni:\n\t" + "\n\t".join(REACTIONS.keys()))
case "info":
await channel.send(BOT_INFO)
case "echo":
await channel.send("".join(tokens[1:]))
await message.delete()
case "ping":
await log_async("comedy genius")
if len(tokens) == 1: #no parameters
await PingVictim(channel)
else:
tot = int(tokens[1])
if tot < 1: raise
for i in range(tot):
await PingVictim(channel)
case "quote":
if len(tokens) == 1: #no parameters
await channel.send(getquote())
else:
tot = int(tokens[1])
if tot < 1: raise
for i in range(tot):
await channel.send(getquote())
case "remindme":
#TODO
raise NotImplementedError
case "user":
await channel.send(f"{message.author.display_name} ({message.author.id})")
case "channel":
await channel.send(f"{message.channel} ({message.channel.id})")
case "sus":
await channel.send(random.choice(SUS_ANS))
case "addreact":
#TODO
raise NotImplementedError
name, link = tokens[1], tokens[2]
updatereactions()
if name in REACTIONS.keys():
await message.channel.send("ce n'è già una con quel nome")
return
for mod in MODS:
await mod.send(f"{message.author.name} ha chiesto di aggiungere una reazione:\n{name}\n{link}")
await mod.send("accetta? [y/n] (rispondi al primo messaggio)")
case other:
updatereactions()
if other in REACTIONS:
await channel.send(REACTIONS[tokens[0]])
else:
raise ID10T_Exception
#END commands
async def SuperuserCommands(tokens: list[str], message: discord.Message, channel: discord.TextChannel):
try:
await log_async("in superuser function")
msg = " ".join(tokens)
params = " ".join(tokens[1:])
if message.author.id not in SUPERUSER_IDS:
await channel.send(random.choice(INVALID_SUPER_ID))
await log_async(f"{message.author} tried executing a superuser command")
return
await log_async("executing superuser command")
await log_async(f"{message.author} is executing a superuser command: '" + message.content + "'")
match tokens[0]:
case "reboot":
await log_async("restarting...")
global BOT_RETURN_CODE
BOT_RETURN_CODE = return_codes.reboot
#exit from the current session. this returns to client.run() instead of the line after this
await shutdown()
case "shutdown":
await log_async("shutting down...")
await shutdown()
case "exec":
await log_async("executing:\t>>>\t" + params)
exec(params)
await log_async("end of exec")
case "pm":
tokens2 = params.split(";")
username = GetUser(tokens2[0])
emssage = str(eval(tokens2[1]))
await pm(username, emssage)
case "ban":
await GetUser(params).ban()
case "kick":
await GetUser(params).kick()
case "shell":
os.system(params)
except Exception as e:
await log_async(f"Errore nell'uso del comando superuser {msg}:\n" + Format(e), do_indent=False)
#END superuser
async def pm(user, message):
await user.send(message)
async def shutdown():
indent_level_reset()
if DO_CHATBOT is True:
talkbot_exit()
await log_async("talkbot closed")
await client.close()
#END
@client.event
async def on_member_join(member: discord.User):
await GetChannel("generale").send("@everyone è arrivato " + member.mention)
@client.event
async def on_member_remove(member: discord.User):
pass
def SendReminder(user, message):
import asyncio
asyncio.run(GetChannel("promemoria").send(GetUser(user).mention + "\n" + message))
def main():
cls()
output_channels_add(output_channel(
function=print,
))
#TODO:
# output_channels_add(output_channel(
# function=SendLog,
# indent_str="* * * * ",
# ))
#can't use `log`, bot isn't on
print("starting...")
try:
# SetReminderFunction(SendReminder)
# timecheckthread = Thread(target=TimeCheckLoop)
# timecheckthread.start()
if DO_CHATBOT is True:
try:
talkbot_init()
except Exception as e:
printerror("\n" + excFormatter.Format(e))
#main client
client.run(TOKEN)
if BOT_RETURN_CODE == return_codes.reboot:
cmd = ["python3"] + sus.argv
os.execv(sus.executable, cmd)
except Exception as e:
import excFormatter
printerror("\n" + excFormatter.Format(e))
exit()
#value can be edited by everyone. will be checked on exit from the client for various things
BOT_RETURN_CODE = return_codes.none
if __name__ == "__main__":
main()