This repository has been archived by the owner on Jul 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
453 lines (411 loc) · 14.9 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
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
import datetime
import json
import logging
import os
import mysql.connector
import nextcord
import pyrogram
import requests
from nextcord.ext import commands
from nextcord.ui import *
import tempfile
configFile = json.load(open("config.json"))
messageFile = json.load(open("messagetable.json"))
logging.basicConfig(
format=configFile["logging"]["loggingFormat"],
level=logging.INFO
if configFile["logging"]["loggingLevel"].lower() == "info"
else logging.DEBUG,
)
tgInstance = pyrogram.Client(
"Discogram",
api_id=configFile["telegram"]["api_id"],
api_hash=configFile["telegram"]["api_hash"],
)
discordClient = commands.Bot(command_prefix="$")
class sendMessage(nextcord.ui.Modal):
def __init__(self):
self.stringsDict = messageFile["modals"]["sendMessage"]
super().__init__(self.stringsDict["modalTitle"])
self.username = nextcord.ui.TextInput(
label=self.stringsDict["UsernameLabel"],
placeholder=self.stringsDict["UsernamePlaceholder"],
required=True,
max_length=32,
)
self.add_item(self.username)
self.text = nextcord.ui.TextInput(
label=self.stringsDict["TextLabel"],
placeholder=self.stringsDict["TextPlaceholder"],
style=nextcord.TextInputStyle.paragraph,
min_length=2,
max_length=500,
required=True
)
self.add_item(self.text)
async def callback(self, interaction: nextcord.Interaction) -> None:
try:
id = await tgInstance.resolve_peer(self.username.value)
await tgInstance.send_message(
"-100" + str(id.channel_id)
if type(id) == pyrogram.raw.types.InputPeerChannel
else id.user_id,
self.text.value,
)
except Exception as e:
await interaction.send(
messageFile["errorMessage"] + str(e), ephemeral=True
)
try:
id.user_id
await on_forced_ticket(
id.user_id,
interaction.user.name,
self.username.value,
self.text.value,
True
)
await interaction.send(self.stringsDict["MessageSentResponse"], ephemeral=True)
except Exception as e:
await interaction.send(
messageFile["errorMessage"] + str(e), ephemeral=True
)
class cronologiaModal(nextcord.ui.Modal):
def __init__(self):
self.stringsDict = messageFile["modals"]["cronologia"]
super().__init__(self.stringsDict["modalTitle"])
self.username = nextcord.ui.TextInput(
label=self.stringsDict["UsernameLabel"],
placeholder=self.stringsDict["UsernamePlaceholder"],
required=True,
max_length=32,
)
self.add_item(self.username)
self.messaggi = nextcord.ui.TextInput(
label=self.stringsDict["MessagesLabel"],
placeholder=self.stringsDict["MessagesPlaceholder"],
required=True,
max_length=32,
)
self.add_item(self.messaggi)
async def callback(self, interaction: nextcord.Interaction) -> None:
try:
messages = []
i = 0
messlist = 0
if int(self.messaggi.value) == -1:
lim = 999999999
else:
lim = int(self.messaggi.value)
async for mess in tgInstance.get_chat_history(
self.username.value, limit=lim
):
messlist+=1
async for message in tgInstance.get_chat_history(
self.username.value, limit=lim
):
messages.append(
eval(f"""f'''{self.stringsDict['MessageTemplate']}'''""")
)
i += 1
messages.reverse()
await interaction.send(self.stringsDict["MessagesPrefix"] + "".join(messages))
except Exception as e:
await interaction.send(
messageFile["errorMessage"] + str(e), ephemeral=True
)
def conndb():
db_conn = mysql.connector.connect(user='root', password='REDACTED',
host='127.0.0.1',
database='discogramTickets')
cur = db_conn.cursor(buffered=True)
return db_conn, cur
def fetchone(cur, what, where, whereval, orderstr):
cur.execute(
f"""SELECT {what} FROM tickets WHERE {where} = '{whereval}' {orderstr} limit 1"""
)
res = cur.fetchone()
try:
return res[0]
except:
return None
def insert(cur, values):
cur.execute(f"""INSERT INTO tickets VALUES {values}""")
async def on_forced_ticket(id, name, username, content, is_dm):
db_conn, cur = conndb()
res = fetchone(cur, "is_closed", "user_id", str(id), "ORDER BY date DESC")
channel = discordClient.get_channel(configFile["discord"]["channel_id"])
if res is None or res == "True":
cur.execute("select id from tickets order by date desc")
res = cur.fetchone()
message_res = await channel.send(
eval(f"f'{messageFile['forcedTicketTemplate']}'")
)
to_add = (
0
if res == None
else int(res[0].replace(configFile["discord"]["IDPrefix"], ""))
)
ticket_id = configFile["discord"]["IDPrefix"] + str(1 + to_add)
await message_res.create_thread(name=f"{ticket_id}")
insert(
cur,
f"""('{ticket_id}',
{message_res.id},
{int(datetime.datetime.now().timestamp())},
{id},
'{content}',
'false',
'{'true' if is_dm else 'false'}')""",
)
db_conn.commit()
else:
mess_id = fetchone(cur, "message_id", "user_id", str(id), "ORDER BY date DESC")
try:
await channel.get_thread(mess_id).send(content)
except nextcord.errors.HTTPException:
pass
cur.close()
db_conn.close()
async def on_tg_message(client, message, is_dm):
db_conn, cur = conndb()
res = fetchone(
cur, "is_closed", "user_id", str(message.from_user.id), "ORDER BY date DESC"
)
channel = discordClient.get_channel(configFile["discord"]["channel_id"])
print(res)
if (
message.from_user.id in configFile["discord"]["ignoreTGAuthor"]
):
pass
elif res is None or res == "True":
first_name, last_name, full_name = await welcomeAndInitNames(message)
cur.execute("select id from tickets order by date desc")
res = cur.fetchone()
message_res = await channel.send(
eval(f"f'{messageFile['startingMessageTemplate']}'")
)
to_add = (
0
if res == None
else int(res[0].replace(configFile["discord"]["IDPrefix"], ""))
)
ticket_id = configFile["discord"]["IDPrefix"] + str(1 + to_add)
await message_res.create_thread(name=f"{ticket_id}")
insert(
cur,
f"""('{ticket_id}',
{message_res.id},
{int(datetime.datetime.now().timestamp())},
{message.from_user.id},
'{message.text}',
'false',
'{'true' if is_dm else 'false'}')""",
)
db_conn.commit()
cur.close()
db_conn.close()
else:
mess_id = fetchone(
cur,
"message_id",
"user_id",
str(message.from_user.id),
"ORDER BY date DESC",
)
try:
await channel.get_thread(mess_id).send(message.text)
except nextcord.errors.HTTPException:
pass
cur.close()
db_conn.close()
async def welcomeAndInitNames(message):
await message.reply(messageFile["welcome"])
first_name = (
message.from_user.first_name if message.from_user.first_name is not None else ""
)
last_name = (
message.from_user.last_name if message.from_user.last_name is not None else ""
)
full_name = f"{first_name} {last_name}".replace(" ", " ")
return first_name, last_name, full_name
async def on_tg_message_media(client, message, is_dm):
db_conn, cur = conndb()
res = fetchone(
cur, "is_closed", "user_id", str(message.from_user.id), "ORDER BY date DESC"
)
channel = discordClient.get_channel(configFile["discord"]["channel_id"])
if res is None or res == "True":
first_name, last_name, full_name = await welcomeAndInitNames(message)
path = await tgInstance.download_media(message=message)
os.remove(path)
message_res = await channel.send(
eval(f"f'{messageFile['startingMessageTemplateMedia']}'"),
file=nextcord.File(path),
)
cur.execute("select id from tickets order by date desc")
res = cur.fetchone()
to_add = (
0
if res == None
else int(res[0].replace(configFile["discord"]["IDPrefix"], ""))
)
ticket_id = configFile["discord"]["IDPrefix"] + str(1 + to_add)
await message_res.create_thread(name=f"{ticket_id}")
insert(
cur,
f"""('{ticket_id}',
{message_res.id},
{int(datetime.datetime.now().timestamp())},
{message.from_user.id},
'{message.text}',
'false',
'{'true' if is_dm else 'false'}')""",
)
db_conn.commit()
else:
mess_id = fetchone(
cur,
"message_id",
"user_id",
str(message.from_user.id),
"ORDER BY date DESC",
)
path = await tgInstance.download_media(message=message
)
await channel.get_thread(mess_id).send(
message.caption, file=nextcord.File(path)
)
os.remove(path)
cur.close()
db_conn.close()
async def close_ticket(message, motivazione):
guild = discordClient.get_channel(configFile["discord"]["channel_id"])
db_conn, cur = conndb()
mess_id = fetchone(cur, "message_id", "id", message.channel.name, "")
thread = guild.get_thread(mess_id)
user_id = fetchone(cur, "user_id", "id", message.channel.name, "")
cur.execute(
f"""
UPDATE tickets
SET is_closed = "True"
WHERE id = '{message.channel.name}'
"""
)
db_conn.commit()
await message.reply("Ticket chiuso.")
motivoSuffix = (
f"\n\nMotivazione: {' '.join(motivazione) if motivazione != '' else ''}"
)
await tgInstance.send_message(
user_id, messageFile["closedTicketTG"] + motivoSuffix
)
await thread.edit(
name=thread.name + messageFile["closedThread"], archived=True, locked=True
)
cur.close()
db_conn.close()
@discordClient.event
async def on_message(message):
if (
message.content.startswith("/closeticket")
or message.content.startswith("/close")
and message.author.id != discordClient.application_id
):
try:
motivo = message.content.split(" ")[1:]
except:
motivo = ""
await close_ticket(message, motivo)
elif type(message.channel) == nextcord.channel.TextChannel:
pass
elif (
message.attachments != []
and type(message.channel) == nextcord.threads.Thread
and not message.content.startswith(configFile["discord"]["ignoreMessagePrefix"])
and message.author.id != discordClient.application_id
):
db_conn, cur = conndb()
ticket = fetchone(cur, "user_id", "id", message.channel.name, "")
for attachment in message.attachments:
open(os.path.join("./downloads", attachment.filename), "wb").write(
requests.get(attachment.url).content
)
if message.attachments[-1].url == attachment.url:
await tgInstance.send_document(
chat_id=ticket,
document=os.path.join("./downloads", attachment.filename),
caption=message.content,
)
else:
await tgInstance.send_document(
chat_id=ticket,
document=os.path.join("./downloads", attachment.filename),
caption=message.content
)
os.remove(os.path.join("./downloads", attachment.filename))
cur.close()
db_conn.close()
elif (
type(message.channel) == nextcord.threads.Thread
and not message.content.startswith(configFile["discord"]["ignoreMessagePrefix"])
and message.author.id != discordClient.application_id
):
db_conn, cur = conndb()
ticket = fetchone(cur, "user_id", "id", message.channel.name, "")
#print(cur.fetchone(), cur.fetchone())
try:
await tgInstance.send_message(chat_id=ticket, text=message.content)
except:
pass
cur.close()
db_conn.close()
@tgInstance.on_message(pyrogram.filters.private)
async def on_private_message(client, message):
if message.media:
await on_tg_message_media(client, message, True)
await on_tg_message(client, message, True)
@discordClient.slash_command(name="send", description="Manda un messaggio")
async def send(interaction: nextcord.Interaction):
modal = sendMessage()
try:
await interaction.response.send_modal(modal)
except Exception as e:
pass
@discordClient.slash_command(
name="cronologia", description="Guarda i primi 10 messaggi di una persona!"
)
async def cronologia(interaction: nextcord.Integration):
modal = cronologiaModal()
try:
await interaction.response.send_modal(modal)
except Exception as e:
pass
@discordClient.slash_command(name="block", description="Blocca l'utente")
async def block(interaction):
db_conn, cur = conndb()
channel = interaction.channel
if type(channel) == nextcord.Thread:
user_id = fetchone(cur, "user_id", "message_id", channel.id, "")
await tgInstance.block_user(user_id)
await interaction.response.send_message("Utente bloccato!")
else:
await interaction.response.send_message("Non sei in un thread!", epherimental=True)
@discordClient.slash_command(name="unblock", description="Sblocca l'utente")
async def unblock(interaction):
db_conn, cur = conndb()
channel = interaction.channel
if type(channel) == nextcord.Thread:
user_id = fetchone(cur, "user_id", "message_id", channel.id, "")
await tgInstance.unblock_user(user_id)
await interaction.response.send_message("Utente sbloccato!")
else:
await interaction.response.send_message("Non sei in un thread!", epherimental=True)
if __name__ == "__main__":
try:
os.mkdir("./downloads")
except FileExistsError:
pass
tgInstance.start()
discordClient.run(configFile["discord"]["token"])
os.rmdir("./downloads")