-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
613 lines (498 loc) Β· 20.1 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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
# Import Core Libraries
import hydrogram
import time
import config
import database
import asyncio
import os
import re
import random
from hydrogram import filters
from hydrogram.methods.utilities.idle import idle
from hydrogram.types import (
InlineKeyboardButton,
InlineKeyboardMarkup,
CallbackQuery,
Message,
)
from typing import Dict
# Initialize Client and Setup Memory
app = hydrogram.Client(
name=config.NAME,
api_id=config.API_ID,
api_hash=config.API_HASH,
bot_token=config.BOT_TOKEN,
)
p_app = hydrogram.Client(
name="p_" + config.NAME,
api_id=config.API_ID,
api_hash=config.API_HASH,
)
loop = asyncio.get_event_loop()
run = loop.run_until_complete
run(app.start())
run(p_app.start())
reply_mode: Dict[str, int] = {}
# Define Core functions
def sanitize_str(string: str) -> str:
## Sanitizes the string by only allowing alphanumeric characters and hyphens
return re.sub(pattern=r"[^a-zA-Z0-9-]", repl="", string=string)
def printlog(text: str) -> None:
## Prints the text to the console and logs it to a file
print(text)
if not os.path.exists("logs"):
os.mkdir("logs")
name = os.path.join("logs", time.strftime("%Y%m%d") + ".log")
with open(file=name, mode="a") as f:
f.write(f"[{time.strftime("%Y-%m-%d %H:%M:%S")}] {text}\n")
# Define Callback Functions
@app.on_message(filters=filters.command(commands=["start"]))
async def start(_, message: Message) -> None:
if len(message.command) == 1:
## Intro Function
await message.reply_text(
text="Hello there! I am TG-Chan Posting Bot. I can help you post anonymous messages to TG-Chan.\n\nTo get started, just send me a message to post on TG-Chan, to reply to an existing post, you can just click on the reply button on that post and send me a reply message\n\nYou can view the privacy policy using the /privacy command."
)
elif len(message.command) == 2:
## Media Function
file_path = "media/" + sanitize_str(string=message.command[1])
if file_path.endswith("-jpg"):
file_path = file_path[:-4] + ".jpg"
extension = "jpg"
elif file_path.endswith("-mp4"):
file_path = file_path[:-4] + ".mp4"
extension = "mp4"
else:
extension = None
if not os.path.exists(file_path):
await message.reply_text(
text=("Invalid media key! Please try again with a valid media key.")
)
return
if extension == "jpg":
msg = await message.reply_photo(
photo=file_path,
caption=(
f"Here is the photo you requested. It will be deleted in {config.AUTOPURGE_INTERVAL} seconds."
if config.AUTOPURGE_MEDIA
else "Here is the photo you requested."
),
)
elif extension == "mp4":
msg = await message.reply_video(
video=file_path,
caption=(
f"Here is the video you requested. It will be deleted in {config.AUTOPURGE_INTERVAL} seconds."
if config.AUTOPURGE_MEDIA
else "Here is the video you requested."
),
)
if config.AUTOPURGE_MEDIA:
await asyncio.sleep(config.AUTOPURGE_INTERVAL)
try:
await msg.delete()
except Exception:
return
else:
await message.reply_text(text=("Invalid syntax!"))
@app.on_message(
filters=filters.private
& ~filters.command(commands=["start", "delete", "privacy", "cancel"])
)
async def post(client: hydrogram.Client, message: Message) -> None:
## Post Function
uhash = database.hash(num=message.from_user.id)
text = "When you're ready, just click on the button down below to post your reply to TG-Chan!"
if uhash in reply_mode:
msg = await client.get_messages(
chat_id=config.POST_ID,
message_ids=reply_mode[uhash],
)
text += f"\n\nCurrently replying to the following message: {msg.link}"
await message.reply_text(
text=text,
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text="Post",
callback_data="post",
),
],
],
),
reply_to_message_id=message.id,
)
@app.on_message(filters=filters.command(commands=["delete"]))
async def delete(client: hydrogram.Client, message: Message) -> None:
db = database.load()
if len(message.command) != 3:
await message.reply_text(text=("Invalid syntax!"))
return
elif (
not message.command[1].isdigit()
or not message.command[2].replace("-", "").isnumeric()
):
await message.reply_text(text=("Invalid command!"))
return
try:
msg = await client.get_messages(
chat_id=config.POST_ID,
message_ids=int(message.command[1]),
)
shash = db["posts"][msg.id]["shash"]
except Exception:
await message.reply_text(
text=("Invalid message id! Please try again with a valid message id.")
)
return
if (
shash != database.hash(num=message.from_user.id + int(message.command[2]) - config.SEED)
and message.from_user.id != config.OWNER_ID
):
await message.reply_text(
text=(
"You are not authorized to delete this message! Please try again with a valid message id."
)
)
return
await p_app.delete_messages(
chat_id=config.POST_ID,
message_ids=msg.id,
)
database.remove_post(db=db, id=msg.id)
await message.reply_text(text=("The message has been successfully deleted!"))
printlog(f"User {shash} deleted a message with id {msg.id}!")
database.save(db=db)
@app.on_message(filters=filters.command(commands=["privacy"]))
async def privacy(_: hydrogram.Client, message: Message) -> None:
await message.reply_text(
text=(
"Privacy Policy:\n\n"
"1. Your messages are posted anonymously and are linked to your hash.\n"
"2. Your user id is not stored or used for any purpose other than generating your hash.\n"
"3. Your messages are not used for any other purpose than posting on TG-Chan.\n"
"4. Your messages are not used to track you or your activities on the bot.\n"
"5. Your hashes are generated in real-time for authentication and stored only for feedbacks.\n"
),
)
@app.on_callback_query()
async def callback(client: hydrogram.Client, callback: CallbackQuery) -> None:
db = database.load()
uhash = database.hash(num=callback.from_user.id)
if callback.data == "like":
if callback.message.id not in db["posts"]:
await callback.answer(text="Invalid message!")
return
if uhash in db["posts"][callback.message.id]["feedbacks"]:
if (
db["posts"][callback.message.id]["feedbacks"][uhash]
== database.Feedback.LIKE
):
dislike = 0
like = -1
db["posts"][callback.message.id]["rating"] -= 1
else:
db["posts"][callback.message.id]["rating"] += 2
dislike = -1
db["posts"][callback.message.id]["feedbacks"][
uhash
] = database.Feedback.LIKE
like = 1
else:
db["posts"][callback.message.id]["rating"] += 1
dislike = 0
db["posts"][callback.message.id]["feedbacks"][
uhash
] = database.Feedback.LIKE
like = 1
existing_reply_markup = callback.message.reply_markup.inline_keyboard
for row in existing_reply_markup:
for button in row:
if button.text.startswith("π"):
current = int(button.text.split(" : ")[1])
button.text = (
f"π : {current + like}" if current + like >= 0 else "π : 0"
)
elif button.text.startswith("π"):
current = int(button.text.split(" : ")[1])
button.text = (
f"π : {current + dislike}"
if current + dislike >= 0
else "π : 0"
)
try:
await callback.message.edit_reply_markup(
reply_markup=InlineKeyboardMarkup(inline_keyboard=existing_reply_markup)
)
except Exception:
pass
if db["posts"][callback.message.id]["rating"] >= config.AUTODELETE_LIKE_LIMIT:
if callback.message.id in db["autodelete"]:
del db["autodelete"][callback.message.id]
if db["posts"][callback.message.id]["rating"] >= config.PIN_LIKE_LIMIT:
await callback.message.pin()
if like == 1:
await callback.answer(text="Thanks for the feedback!")
else:
await callback.answer(text="Feedback removed!")
del db["posts"][callback.message.id]["feedbacks"][uhash]
elif callback.data == "dislike":
if callback.message.id not in db["posts"]:
await callback.answer(text="Invalid message!")
return
if uhash in db["posts"][callback.message.id]["feedbacks"]:
if (
db["posts"][callback.message.id]["feedbacks"][uhash]
== database.Feedback.DISLIKE
):
like = 0
dislike = -1
db["posts"][callback.message.id]["rating"] += 1
else:
db["posts"][callback.message.id]["rating"] -= 2
like = -1
dislike = 1
db["posts"][callback.message.id]["feedbacks"][
uhash
] = database.Feedback.DISLIKE
else:
db["posts"][callback.message.id]["rating"] -= 1
like = 0
dislike = 1
db["posts"][callback.message.id]["feedbacks"][
uhash
] = database.Feedback.DISLIKE
existing_reply_markup = callback.message.reply_markup.inline_keyboard
for row in existing_reply_markup:
for button in row:
if button.text.startswith("π"):
current = int(button.text.split(" : ")[1])
button.text = (
f"π : {current + like}" if current + like >= 0 else "π : 0"
)
elif button.text.startswith("π"):
current = int(button.text.split(" : ")[1])
button.text = (
f"π : {current + dislike}"
if current + dislike >= 0
else "π : 0"
)
try:
await callback.message.edit_reply_markup(
reply_markup=InlineKeyboardMarkup(inline_keyboard=existing_reply_markup)
)
except Exception:
pass
if db["posts"][callback.message.id]["rating"] <= -config.UNPIN_DISLIKE_LIMIT:
await callback.message.unpin()
if db["posts"][callback.message.id]["rating"] <= -config.DELETE_DISLIKE_LIMIT:
if callback.message.id in db["autodelete"]:
del db["autodelete"][callback.message.id]
await p_app.delete_messages(
chat_id=config.POST_ID,
message_ids=callback.message.id,
)
database.remove_post(db=db, id=callback.message.id)
if dislike == 1:
await callback.answer(text="Thanks for the feedback!")
else:
await callback.answer(text="Feedback removed!")
del db["posts"][callback.message.id]["feedbacks"][uhash]
elif callback.data == "reply":
if callback.message.id not in db["posts"]:
await callback.answer(text="Invalid message!")
return
reply_mode[uhash] = callback.message.id
await callback.answer(
text="Reply mode activated! Please send your reply message via bot. You can exit reply mode by sending /cancel."
)
return
elif callback.data == "post":
## Post Function
uhash = database.hash(num=callback.from_user.id)
if uhash in db["timings"] and callback.from_user.id != config.OWNER_ID:
if db["timings"][uhash] > time.time():
await callback.answer(
text=("Please wait for a while before posting another message!")
)
return
else:
del db["timings"][uhash]
else:
db["timings"][uhash] = time.time() + config.POST_INTERVAL
seed = random.randint(a=-999_999, b=999_999)
shash = database.hash(num=callback.from_user.id + seed)
reply_id = reply_mode.pop(uhash) if uhash in reply_mode else None
try:
if reply_id is not None:
await client.get_messages(
chat_id=config.POST_ID,
message_ids=reply_id,
)
except Exception as e:
print(f"Error: {e}")
await callback.answer(
text=("Invalid reply id! Please try again with a valid reply id.")
)
return
if len(db["autodelete"]) >= config.AUTODELETE_COUNT:
if reply_id == db["autodelete"][0]:
await callback.answer(
"Reply message is in the auto-delete queue! Please try again with a different message."
)
del db["reply_mode"][uhash]
msg_id = db["autodelete"].pop(0)
database.remove_post(db=db, id=msg_id)
printlog(text=f"Auto-deleting message with id {db['autodelete'][0]}!")
await p_app.delete_messages(
chat_id=config.POST_ID,
message_ids=msg_id,
)
message = callback.message.reply_to_message
if message.photo:
if message.photo.file_size > config.MAX_IMAGE_SIZE:
await message.reply_text(
text=(
"The image size is too large! Please try again with a smaller/compressed image or add a link to the image instead."
)
)
database.save(db=db)
return
await message.download(file_name=f"media/{shash}.jpg")
msg = await client.send_message(
reply_to_message_id=reply_id,
chat_id=config.POST_ID,
text=(
message.caption.markdown + f"\n\nHash: {shash}"
if message.caption
else f"\n\nHash: {shash}"
),
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text="View attached photo",
url=f"https://t.me/{config.BOT_USERNAME}?start={shash}-jpg",
),
],
[
InlineKeyboardButton(
text="π : 0",
callback_data="like",
),
InlineKeyboardButton(
text="π : 0",
callback_data="dislike",
),
InlineKeyboardButton(
text="Reply",
callback_data="reply",
),
],
],
),
)
database.add_post(db=db, id=msg.id, media=f"media/{shash}.jpg", shash=shash)
elif message.video:
if message.video.file_size > config.MAX_VIDEO_SIZE:
await message.reply_text(
text=(
"The video size is too large! Please try again with a smaller/compressed video or add a link to the video instead."
)
)
database.save(db=db)
return
await message.download(file_name=f"media/{shash}.mp4")
msg = await client.send_message(
reply_to_message_id=reply_id,
chat_id=config.POST_ID,
text=(
message.caption.markdown + f"\n\nHash: {shash}"
if message.caption
else f"\n\nHash: {shash}"
),
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text="View attached video",
url=f"https://t.me/{config.BOT_USERNAME}?start={shash}-mp4",
),
],
[
InlineKeyboardButton(
text="π : 0",
callback_data="like",
),
InlineKeyboardButton(
text="π : 0",
callback_data="dislike",
),
InlineKeyboardButton(
text="Reply",
callback_data="reply",
),
],
],
),
)
database.add_post(db=db, id=msg.id, media=f"media/{shash}.mp4", shash=shash)
elif message.text:
msg = await client.send_message(
reply_to_message_id=reply_id,
chat_id=config.POST_ID,
text=message.text.markdown + f"\n\nHash: {shash}",
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text="π : 0",
callback_data="like",
),
InlineKeyboardButton(
text="π : 0",
callback_data="dislike",
),
InlineKeyboardButton(
text="Reply",
callback_data="reply",
),
],
],
),
)
database.add_post(db=db, id=msg.id, shash=shash)
else:
await message.reply_text(
text=(
"Invalid message type! Please try again with a valid message type."
)
)
database.save(db=db)
return
db["autodelete"].append(msg.id)
await callback.message.edit_text(
text=(
f"Your [message](https://t.me/{config.POST_USERNAME}/{msg.id}) has been successfully posted!\n\nTo delete your post, use the `/delete {msg.id} {seed + config.SEED}` command."
)
)
printlog(f"{uhash} posted a message with id {msg.id}!")
else:
await callback.answer(text="Invalid action!")
database.save(db=db)
return
database.save(db=db)
@app.on_message(filters=filters.command(commands=["cancel"]))
async def cancel(_: hydrogram.Client, message: Message) -> None:
uhash = database.hash(num=message.from_user.id)
if uhash in reply_mode:
del reply_mode[uhash]
await message.reply_text(text="Reply mode deactivated!")
else:
await message.reply_text(text="You are not in reply mode!")
# Run the Bot
print("Bot is running!")
run(idle())
run(app.stop())
run(p_app.stop())