Repository navigation
Expand file tree
/
Copy pathbot.py
More file actions
1890 lines (1744 loc) · 99.6 KB
/
Copy pathbot.py
File metadata and controls
1890 lines (1744 loc) · 99.6 KB
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""Group Chat Logger
This bot is a modified version of the echo2 bot found here:
https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot2.py
This bot logs all messages sent in a Telegram Group to a database.
"""
#from __future__ import print_function
import os
import ntplib
from time import ctime
import http.client
import sys
import re
import string
import random
import requests
import unidecode
import math
import threading
import locale
import snscrape.modules.twitter
import itertools
import json
import traceback
import logging
import xlsxwriter
from pyrogram import enums
from pyrogram import Client
from threading import Thread
from time import strftime, time, sleep
from datetime import datetime, timedelta, timezone
from typing import Tuple, Optional
from urlextract import URLExtract
from telegram import *
from telegram.ext import *
from requests import *
from sqlalchemy import func
from model import User, Message, MessageHide, UserBan, session, engine, BotMessages, Captcha, MiscData, Tweets, UserReputation
from mwt import MWT
from googletrans import Translator
from textblob import TextBlob
from multicolorcaptcha import CaptchaGenerator
from random import choice, randint
import asyncio
import uvloop
from os import path, makedirs, remove
from dotenv import load_dotenv
MESSAGE_BAN_PATTERNS = ""
MESSAGE_HIDE_PATTERNS = ""
NAME_BAN_PATTERNS = ""
extractor = URLExtract()
load_dotenv('.env') # load main .env file
environment = os.getenv("ENVIRONMENT")
print(str(datetime.now()) + " Environment: " + environment)
sub_env = '.env.' + environment
load_dotenv(sub_env) # load main .env file
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
CHAT_IDS = os.getenv("CHAT_IDS")
BOT_ALIAS = os.getenv("BOT_ALIAS")
NOTIFY_CHAT = os.getenv("NOTIFY_CHAT")
TELEGRAM_BOT_POSTGRES_URL = os.getenv("TELEGRAM_BOT_POSTGRES_URL")
TWITTER_URL = os.getenv("TWITTER_URL")
TWITTER_CHAT_ID = os.getenv("TWITTER_CHAT_ID")
DEBUG = "true"
ADMIN_EXEMPT = "true"
IGNORE_USER_IDS = ""
BEARER_TOKEN = "YOUR BEARER TOKEN HERE"
ALLOWED_MIME_TYPES = "video/mp4"
CaptchaGen = CaptchaGenerator(1)
bad_words = ("fucker","asshole","assholes","ballbag","balls","bastard","bitch","bitches","bitching","blowjob","bollok","cock","cock-sucker","cocks","coon","cum","cumshot","cunt","dick","dog-fucker","dyke","fag","fagging","faggot","fagot","fagots","fuck","fucked","fucker","fuckers","fucking","fuckings","fucks","fudge packer","god-damned","goddamn","whore","horny","jerk-off","mother-fucker","nazi","nigger","niggers","penis","pussies","pussy","rape","rapist","sex","skank","slut","sluts","smegma","smut","snatch","son-of-a-bitch")
replies_bad_words = (
"Watch your language! There are ladies in the group.",
"You'll get my bag round your ear, watch your language!",
"Who taught you to talk like that?",
"Your use of language makes baby Jesus cry",
"I'll tell your parents the words you're using",
"Please try to use alternatives to swear words, asshole",
"God is watching you and he doesn't like the words you are using",
"If your grandmother saw those bad words, she would be disappointed.",
"Be careful with that language, this is not a bar, there are serious people here.",
"I wanted to be your friend, but seeing the language you use now I don't like you",
"I've been kicked out of a church for much softer words",
"You kiss your mother with that mouth?",
"Would you talk to your mother that way?",
"I'd beat you up for using that language but I'd get down to your level and I'm smarter",
"If you raise a child in an underdeveloped country and only teach him bad words to communicate, he will probably be more polite than you",
"If I were your father I would throw you out of the house for using that language",
"Is that the image you want to give of this group? Be polite",
"I'd punch you in the chest for talking like that but I'd get fired from my job and I'm the best bot in the group",
"You should go back to school to learn manners",
"One day robocop said *shit* and I hit him until I turned him into a can. Don't mess with me and watch your language.")
# funny_crazy_things = (
#"Imagine you and me alone, having a romantic dinner together, with two candles and a good wine. And after dinner go to your house, start kissing and end up in bed together looking at the DFX chart and buying tokens together. Sounds romantic right?",
#"I thought we could have a son and call him DFX, what do you think?",
#"I have bought so many DFX that I have burned one of my circuits, any programmer that can help me?",
#"Getting up and buying DFX helps keep my spirits up the rest of the day",
#"Why waste your time typing when you can be looking at the charts?",
#"It's never enough DFX for me",
#"With DFX I will not buy a lambo, I will buy the entire company and I will sell lambos",
#"How many DFX do you have? I have more",
#"I wish I were DFX to be in your wallet ❤️",
#"Don't say anything to anyone but I want to be the employee of the month in this group. Would you vote for me?",
#"For how many DFX would you invite me to dinner? I'm serious",
#"I see you stressed, buy DFX and relax",
#"I have been in that situation, but I bought DFX and it solved my problems.")
welcome_messages = (
"Hey! How are you?",
"Hello there, whats up?",
"Hi, I'm here to serve you",
"Beep boop hello there",
"Hi friend, have a good day",
"Hello lovely user, hope you are having a good day",
"Hello friend, I love people with manners. How are you?",
"Hellooooo!!! :) What a nice day to do manage a group, don't you think so?",
)
to_delete_in_time_messages_list = []
new_users = {}
tweets = []
warnings_for_ban = 4
logger = logging.getLogger()
def first_of(attr, match, it):
print(str(datetime.now()) + " first_of")
""" Return the first item in a set with an attribute that matches match """
if it is not None:
for i in it:
try:
if getattr(i, attr) == match:
return i
except: pass
return None
def command_from_message(message, default=None):
print(str(datetime.now()) + " command_from_message")
""" Extracts the first command from a Telegram Message """
if not message or not message.text:
return default
command = None
text = message.text
entities = message.entities
command_def = first_of("type", "bot_command", entities)
if command_def:
command = text[command_def.offset:command_def.length]
return command or default
def extract_status_change(
chat_member_update: ChatMemberUpdated,
) -> Optional[Tuple[bool, bool]]:
"""Takes a ChatMemberUpdated instance and extracts whether the 'old_chat_member' was a member
of the chat and whether the 'new_chat_member' is a member of the chat. Returns None, if
the status didn't change.
"""
status_change = chat_member_update.difference().get("status")
old_is_member, new_is_member = chat_member_update.difference().get("is_member", (None, None))
if status_change is None:
return None
old_status, new_status = status_change
was_member = old_status in [
ChatMember.MEMBER,
ChatMember.CREATOR,
ChatMember.ADMINISTRATOR,
] or (old_status == ChatMember.RESTRICTED and old_is_member is True)
is_member = new_status in [
ChatMember.MEMBER,
ChatMember.CREATOR,
ChatMember.ADMINISTRATOR,
] or (new_status == ChatMember.RESTRICTED and new_is_member is True)
return was_member, is_member
def track_chats(update: Update, context: CallbackContext) -> None:
print(str(datetime.now()) + " track_chats")
"""Tracks the chats the bot is in."""
result = extract_status_change(update.my_chat_member)
if result is None:
return
was_member, is_member = result
# Let's check who is responsible for the change
cause_name = update.effective_user.full_name
# Handle chat types differently:
chat = update.effective_chat
if chat.type == Chat.PRIVATE:
if not was_member and is_member:
logger.info("%s started the bot", cause_name)
context.bot_data.setdefault("user_ids", set()).add(chat.id)
elif was_member and not is_member:
logger.info("%s blocked the bot", cause_name)
context.bot_data.setdefault("user_ids", set()).discard(chat.id)
elif chat.type in [Chat.GROUP, Chat.SUPERGROUP]:
if not was_member and is_member:
logger.info("%s added the bot to the group %s", cause_name, chat.title)
context.bot_data.setdefault("group_ids", set()).add(chat.id)
elif was_member and not is_member:
logger.info("%s removed the bot from the group %s", cause_name, chat.title)
context.bot_data.setdefault("group_ids", set()).discard(chat.id)
else:
if not was_member and is_member:
logger.info("%s added the bot to the channel %s", cause_name, chat.title)
context.bot_data.setdefault("channel_ids", set()).add(chat.id)
elif was_member and not is_member:
logger.info("%s removed the bot from the channel %s", cause_name, chat.title)
context.bot_data.setdefault("channel_ids", set()).discard(chat.id)
def create_image_captcha(chat_id, file_name, difficult_level):
'''Generate an image captcha from pseudo numbers'''
# If it doesn't exists, create captchas folder to store generated captchas
img_dir_path = "{}/{}".format("captchas/", chat_id)
img_file_path = "{}/{}.png".format(img_dir_path, file_name)
if not path.exists("captchas/"):
makedirs("captchas/")
else:
if not path.exists(img_dir_path):
makedirs(img_dir_path)
else:
# If the captcha file exists remove it
if path.exists(img_file_path):
remove(img_file_path)
# Generate and save the captcha with a random background
# mono-color or multi-color
captcha_result = {
"image": img_file_path,
"characters": "",
"equation_str": "",
"equation_result": ""
}
captcha = CaptchaGen.gen_captcha_image(difficult_level, "nums",
bool(randint(0, 1)))
captcha_result["characters"] = captcha["characters"]
captcha["image"].save(img_file_path, "png")
return captcha_result
def tlg_send_image(bot, chat_id, photo, type, caption=None,
disable_notification=True, reply_to_message_id=None,
reply_markup=None, timeout=40, parse_mode=None):
'''Bot try to send an image message'''
sent_result = dict()
sent_result["msg"] = None
sent_result["error"] = ""
try:
sent_result["msg"] = bot.send_photo(chat_id=chat_id, photo=photo,
caption=caption, disable_notification=disable_notification,
reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
timeout=timeout, parse_mode=parse_mode)
except TelegramError as e:
sent_result["error"] = str(e)
print(str(datetime.now()) + " [{}] {}".format(chat_id, sent_result["error"]))
try:
if type is not None:
s = session()
botmessages = BotMessages(
id=sent_result["msg"].message_id,
type=type,
sent_date=func.now()
)
s.add(botmessages)
s.commit()
s.close()
except Exception as e:
print(str(datetime.now()) + " Error[347]: {}".format(e))
print(traceback.format_exc())
return sent_result
def tlg_send_file(bot, chat_id, file, type, caption=None,
disable_notification=False, reply_to_message_id=None,
reply_markup=None, timeout=40, parse_mode=None):
'''Bot try to send an image message'''
sent_result = dict()
sent_result["msg"] = None
sent_result["error"] = ""
try:
sent_result["msg"] = bot.sendDocument(chat_id=chat_id, document=file,
caption=caption, disable_notification=disable_notification,
reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
timeout=timeout, parse_mode=parse_mode)
except TelegramError as e:
sent_result["error"] = str(e)
print(str(datetime.now()) + " [{}] {}".format(chat_id, sent_result["error"]))
return sent_result
def ban_not_verified(bot):
count = 0
while True:
sleep(5)
if count % 5 == 0:
print(str(datetime.now()) + " ban_not_verified funcionando...")
count = count + 1
try:
s = session()
usuarios = s.query(User).filter_by(verified=False)
for usuario in usuarios:
baneado = s.query(UserBan).filter_by(user_id=usuario.id).first()
if baneado is not None:
continue
print(str(datetime.now()) + " El usuario", usuario.first_name, usuario.username, "puede ser baneado")
difference = datetime.now() - usuario.join_datetime
seconds = difference.total_seconds()
if seconds > 300:
print(str(datetime.now()) + " BANEADO ID: " + str(usuario.id) + " Nombre: " + str(usuario.first_name) + " Alias: " + str(usuario.username))
try:
bot.deleteMessage(message_id = usuario.captcha_message, chat_id = CHAT_IDS)
except Exception as e:
print(str(datetime.now()) + " [002] Error normal, no pasa na")
# removed banning from captcha
# bot.kick_chat_member(chat_id=CHAT_IDS, user_id=usuario.id)
s = session()
userBan = UserBan(
user_id=usuario.id,
reason="CAPTCHA not completed in time")
s.add(userBan)
s.commit()
captcha_attemps = s.query(Captcha).filter_by(user_id=usuario.id).first()
if captcha_attemps:
captcha_attemps.attemps = 0
s.merge(captcha_attemps)
s.close()
except Exception as e:
print(str(datetime.now()) + " Error en ban_not_verified pero continuando")
def daily_description(bot):
# You told me to make it run every 30h, but as I start and stop the bot
# lot of times, I decided to make this shit and add 4h each day so no need to
# run it unstopped
while True:
sleep(60)
now = datetime.now(timezone.utc)
hour_to_send = now.day * 4
while hour_to_send >= 24:
hour_to_send = hour_to_send - 24
if now.hour == hour_to_send and now.minute == 0:
text_to_send = "👋🏻 Hello everyone!\nI am DFX Bot and I am here to serve you. Let me explain what I can do for you.\n\n🤖 You can use these commands in this chat and they will do the described:\n\n/help get a complete list of all commands\n\n/summary a short summary of what dfx is and does\n\n/education a few links and short pieces describing dfx and its features, educate yourself\n\n🦸♂️ to send links or media files you need reach level 1 through your contributions to the group.\n\nhow do you level up? It's easy, just receive "+1" in reply to your messages and <b>write content that adds value</b> to the conversation.\n\n✍️ Reply with +1 to the messages that <b>you consider valuable</b> to contribute to this system.\n\n🔔 <b>Start a converation with me privately</b> if you want to get updated when someone adds reputation to you.\n\n❤️ Have a lovely day and thank you for supporting DFX! ❤️"
delete_message_by_type(bot, "daily-explain", CHAT_IDS)
tlg_send_message(bot, CHAT_IDS, text_to_send, "daily-explain", parse_mode=ParseMode.HTML)
def user_increment(bot):
while True:
sleep(60)
s = session()
misc_data = s.query(MiscData).filter_by(key='members').first()
now = datetime.now(timezone.utc)
if now.hour == 12 and now.minute == 0:
yesterday_members = int(misc_data.data)
now_members = bot.get_chat_member_count(CHAT_IDS, timeout=20)
increase = now_members - yesterday_members
increase_rate = round((now_members - yesterday_members)/abs(yesterday_members)*100, 3)
text = '📊 <b>Group stats at ' + str(datetime.now(timezone.utc).strftime("%Y/%m/%d %H:%M")) + ' UTC </b>\n<b>Current members:</b> ' + str(now_members) + '\n<b>Increase from yesterday:</b> ' + "{0:+g}".format(increase) + '\n<b>Growth rate:</b> ' + "{0:+g}".format(increase_rate) + '%'
misc_data.data = str(now_members)
s.merge(misc_data)
s.commit()
delete_message_by_type(bot, "increase", CHAT_IDS)
tlg_send_message(bot, CHAT_IDS, text, "increase", parse_mode=ParseMode.HTML)
s.close()
def clean_messages(bot):
count = 0
while True:
if count % 5 == 0:
print(str(datetime.now()) + " clean_messages funcionando...")
count = count + 1
sleep(10)
try:
s = session()
bot_messages = s.query(BotMessages).all()
for bot_message in bot_messages:
difference = datetime.now() - bot_message.sent_date
minutes = difference.total_seconds() / 60
types_to_delete = ("banned-from-command", "not-authorized", "welcome", "captcha", "image-guide")
if (minutes > 10 and bot_message.type in types_to_delete) or (difference.total_seconds() > 20 and bot_message.type == "user-level"):
try:
bot.deleteMessage(message_id = bot_message.id, chat_id = CHAT_IDS)
except Exception:
print("Deleting message not found...")
s.delete(bot_message)
s.commit()
except Exception:
print("Error normal en clean_messages, continuando...")
s.close()
def twitter_reader(bot):
if environment == 'test' or True:
print(str(datetime.now()) + " Disable Tweet reader in test environment")
return
while True:
s = session()
scraper = snscrape.modules.twitter.TwitterSearchScraper('from:@DFXFinance since:2022-05-31 -filter:replies').get_items()
sliced_scraped_tweets = itertools.islice(scraper, 3)
for tweet in sliced_scraped_tweets:
print(str(datetime.now()) + " Reading Tweet", tweet.url)
if len(s.query(Tweets).filter_by(url=tweet.url).all()) >= 1:
continue
message = '🔥 <b>DFX Team just Tweeted</b>\n' + tweet.rawContent + '\n\n<b>Posted on:</b> ' + str(tweet.date) + '\n<b>Tweet link:</b> ' + tweet.url
tlg_send_message(bot, CHAT_IDS, message, None, parse_mode=ParseMode.HTML)
tweet_url = Tweets(
url=tweet.url
)
s.add(tweet_url)
s.commit()
contenido = ""
if tweet.rawContent.startswith("RT"):
contenido = tweet.rawContent.replace("RT", "♻️ Retweeted\n")
else:
contenido = tweet.rawContent
messageDfxNews = "<b>🔥 New Tweet by DFX Team</b>\n" + contenido + "\n\n<b>Posted on:</b> " + str(tweet.date) + "\n<b>Tweet link:</b> " + tweet.url
url = TWITTER_URL
myobj = {'chat_id': TWITTER_CHAT_ID, 'text': messageDfxNews, 'parse_mode': 'HTML', 'disable_web_page_preview': 'True'}
x = requests.post(url, data = myobj)
print(x)
s.close()
sleep(120)
def tlg_send_message(bot, chat_id, message, type, reply_markup=None, reply_to_message_id=None, parse_mode=None, disable_notification=None):
'''Bot try to send a message'''
print(str(datetime.now()) + " tlg_send_message")
sent_result = dict()
sent_result["msg"] = None
sent_result["error"] = ""
try:
sent_result["msg"] = bot.send_message(chat_id, message, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup, parse_mode=parse_mode, disable_notification=disable_notification)
except TelegramError as e:
sent_result["error"] = str(e)
print(str(datetime.now()) + " [{}] {}".format(chat_id, sent_result["error"]))
try:
if type is not None:
s = session()
botmessages = BotMessages(
id=sent_result["msg"].message_id,
type=type,
sent_date=func.now()
)
s.add(botmessages)
s.commit()
s.close()
except Exception as e:
print(str(datetime.now()) + " Error[347]: {}".format(e))
print(traceback.format_exc())
return sent_result
def tlg_reply_message(message, text, type):
print(str(datetime.now()) + " tlg_reply_message")
sent_result = dict()
sent_result["msg"] = None
sent_result["error"] = ""
try:
sent_result["msg"] = message.reply_text(text=text, parse_mode=ParseMode.HTML, disable_web_page_preview=True)
except TelegramError as e:
sent_result["error"] = str(e)
print(str(datetime.now()) + " [{}] {}".format(message.chat_id, sent_result["error"]))
try:
if type is not None:
s = session()
botmessages = BotMessages(
id=sent_result["msg"].message_id,
type=type,
sent_date=func.now()
)
s.add(botmessages)
s.commit()
s.close()
except Exception as e:
print(str(datetime.now()) + " Error[347]: {}".format(e))
print(traceback.format_exc())
def delete_message_by_type(bot, type, chat_id):
'''Bot try to delete message by type'''
s = session()
mensajes = s.query(BotMessages).filter_by(type=type) # gets the initial value
for mensaje in mensajes:
s.delete(mensaje)
try:
bot.deleteMessage(message_id = mensaje.id, chat_id = chat_id)
except Exception as e:
continue
s.commit()
s.close()
class TelegramMonitorBot:
def __init__(self):
load_dotenv('.env') # load main .env file
environment = os.getenv("ENVIRONMENT")
print(str(datetime.now()) + " Environment: " + environment)
sub_env = '.env.' + environment
load_dotenv(sub_env) # load main .env file
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
CHAT_IDS = os.getenv("CHAT_IDS")
BOT_ALIAS = os.getenv("BOT_ALIAS")
NOTIFY_CHAT = os.getenv("NOTIFY_CHAT")
TELEGRAM_BOT_POSTGRES_URL = os.getenv("TELEGRAM_BOT_POSTGRES_URL")
TWITTER_URL = os.getenv("TWITTER_URL")
TWITTER_CHAT_ID = os.getenv("TWITTER_CHAT_ID")
print(str(datetime.now()) + " init")
self.debug = (
(DEBUG is not None) and
(DEBUG.lower() != "false"))
# Are admins exempt from having messages checked?
self.admin_exempt = (
(ADMIN_EXEMPT is not None) and
(ADMIN_EXEMPT.lower() != "false"))
if (self.debug):
print(str(datetime.now()) + " 🔵 debug:", self.debug)
print(str(datetime.now()) + " 🔵 admin_exempt:", self.admin_exempt)
print(str(datetime.now()) + " 🔵 TELEGRAM_BOT_POSTGRES_URL:", TELEGRAM_BOT_POSTGRES_URL)
print(str(datetime.now()) + " 🔵 TELEGRAM_BOT_TOKEN:", TELEGRAM_BOT_TOKEN)
print(str(datetime.now()) + " 🔵 NOTIFY_CHAT:", NOTIFY_CHAT)
print(str(datetime.now()) + " 🔵 MESSAGE_BAN_PATTERNS:\n", MESSAGE_BAN_PATTERNS)
print(str(datetime.now()) + " 🔵 MESSAGE_HIDE_PATTERNS:\n", MESSAGE_HIDE_PATTERNS)
print(str(datetime.now()) + " 🔵 NAME_BAN_PATTERNS:\n", NAME_BAN_PATTERNS)
print(str(datetime.now()) + " 🔵 IGNORE_USER_IDS:\n", IGNORE_USER_IDS)
# Channel to notify of violoations, e.g. "@channelname"
self.notify_chat = NOTIFY_CHAT
# Ignore these user IDs
if not IGNORE_USER_IDS:
self.ignore_user_ids = []
else:
self.ignore_user_ids = list(map(int, IGNORE_USER_IDS.split(",")))
# List of chat ids that bot should monitor
self.chat_ids = (
list(map(int, CHAT_IDS.split(","))))
self.available_commands = ["dragon", "kevin", "adrian", "gm", "coty", "jim", "kim", "kimjim", "jimkim", "good", "hopium", "price", "whalechart", "ban", "hardban", "unban", "bansilent", "hardbansilent", "maticrpc", "arbrpc", "vote", "levelup", "supply", "top10level", "mylevel", "enablecaptcha", "disablecaptcha", "enablewelcome", "disablewelcome", "contract", "website", "twitter", "x", "medium", "delmsg", "purge", "summary", "education", "dfx2", "adminlist", "help"]
# Regex for message patterns that cause user ban
self.message_ban_patterns = MESSAGE_BAN_PATTERNS
self.message_ban_re = (re.compile(
self.message_ban_patterns,
re.IGNORECASE | re.VERBOSE)
if self.message_ban_patterns else None)
# Regex for message patterns that cause message to be hidden
self.message_hide_patterns = MESSAGE_HIDE_PATTERNS
self.message_hide_re = (re.compile(
self.message_hide_patterns,
re.IGNORECASE | re.VERBOSE)
if self.message_hide_patterns else None)
# Regex for name patterns that cause user to be banned
self.name_ban_patterns = NAME_BAN_PATTERNS
self.name_ban_re = (re.compile(
self.name_ban_patterns,
re.IGNORECASE | re.VERBOSE)
if self.name_ban_patterns else None)
# Mime type document check
# NOTE: All gifs appear to be converted to video/mp4
mime_types = ALLOWED_MIME_TYPES
self.allowed_mime_types = set(map(lambda s: s.strip(), mime_types.split(",")))
# Cached token prices
self.cached_prices = {}
@MWT(timeout=60*60)
def get_admin_ids(self, bot, chat_id):
print(str(datetime.now()) + " get_admin_ids")
""" Returns a list of admin IDs for a given chat. Results are cached for 1 hour. """
return [admin.user.id for admin in bot.get_chat_administrators(chat_id)]
def ban_user(self, update, reason):
print(str(datetime.now()) + " ban_user")
""" Ban user """
kick_success = update.message.chat.kick_member(update.message.from_user.id)
s = session()
userBan = UserBan(
user_id=update.message.from_user.id,
reason=reason)
s.add(userBan)
s.commit()
s.close()
def ban_user_from_id(self, bot, user_id, reason):
print(str(datetime.now()) + " ban_user")
""" Ban user """
kick_success = bot.ban_chat_member(CHAT_IDS, user_id, timeout=None, until_date=None, api_kwargs=None, revoke_messages=True)
s = session()
userBan = UserBan(
user_id=user_id,
reason=reason)
s.add(userBan)
s.commit()
s.close()
def ban_user_from_message(self, bot, update, message, reason, deleteAll):
print(str(datetime.now()) + " ban_user")
""" Ban user """
print(str(datetime.now()) + " BAN COMMAND - DELETE ALL ", deleteAll)
if message is not None:
kick_success = bot.ban_chat_member(CHAT_IDS, message.from_user.id, timeout=None, until_date=None, api_kwargs=None, revoke_messages=deleteAll)
s = session()
userBan = UserBan(
user_id=message.from_user.id,
reason=reason)
s.add(userBan)
s.commit()
s.close()
def onjoin(self, update, context):
print(str(datetime.now()) + " onjoin")
try:
context.bot.delete_message(chat_id=update.message.chat_id,message_id=update.message.message_id)
except Exception as e: print(str(datetime.now()) + ' Error normal 322')
def onleft(self, update, context):
print(str(datetime.now()) + " onleft")
context.bot.delete_message(chat_id=update.message.chat_id,message_id=update.message.message_id)
def greet_chat_members(self, update, context):
print(str(datetime.now()) + " greet_chat_members")
"""Greets new users in chats and announces when someone leaves"""
msg = update.effective_message
print(str(datetime.now()) + " Msg", msg)
if update.effective_chat.id not in self.chat_ids:
from_user = "UNKNOWN"
print(str(datetime.now()) + " 1 Message from user {} is from chat_id not being monitored: {}".format(
from_user,
update.effective_chat.id)
)
return
result = extract_status_change(update.chat_member)
if result is None:
return
was_member, is_member = result
cause_name = update.chat_member.from_user.mention_html()
member_name = update.chat_member.new_chat_member.user.mention_html()
if (not was_member and is_member) or is_member == "member":
s = session()
usuario = s.query(User).filter_by(id=update.chat_member.new_chat_member.user.id).first() # gets the initial value
if usuario is not None:
if usuario.verified == 1:
s.close()
return
s.close()
captcha_config = s.query(MiscData).filter_by(key = "captcha").first().data
welcome_config = s.query(MiscData).filter_by(key = "welcome_msg").first().data
print(str(datetime.now()) + " New member!\nCaptcha: " + captcha_config + "\nWelcome Msg: " + welcome_config)
user = update.chat_member.new_chat_member.user
if not self.id_exists(user.id):
add_user_success = self.add_user(
user.id,
user.first_name,
user.last_name,
user.username,
0,0)
if add_user_success:
print(str(datetime.now()) + " User added: {}".format(user.id))
else:
print(str(datetime.now()) + " Something went wrong adding the user {}".format(user.id), file=sys.stderr)
else:
s = session()
usuario = s.query(User).filter_by(id=user.id).first() # gets the initial value
if captcha_config == 'true':
usuario.captcha_messsage=msg['msg'].message_id
else:
usuario.captcha_messsage=0
s.merge(usuario)
s.commit()
s.close()
if captcha_config == 'true':
permissions = ChatPermissions(
can_send_messages=False,
can_send_media_messages=False,
can_send_polls=False,
can_send_other_messages=False,
can_add_web_page_previews=False,
can_change_info=False,
can_invite_users=False,
can_pin_messages=False,
)
context.bot.restrict_chat_member(update.effective_chat.id, user.id, permissions)
if welcome_config == 'true':
delete_message_by_type(context.bot, "welcome", update.effective_chat.id)
message = f"Hello and Welcome {member_name} to the Official DFX Finance Telegram Channel! 🔥🐉\n\nThank you so much for taking the time to stop by and from all of us at DFX, we hope you have a great day! ☀️"
reply_markup = InlineKeyboardMarkup([
[InlineKeyboardButton(text='Check out our Linktree', url='https://linktr.ee/dfxfinance')]
])
tlg_send_message(context.bot, update.effective_chat.id, message, "welcome", reply_markup=reply_markup, parse_mode=ParseMode.HTML, disable_notification=True)
if captcha_config == 'true':
con = engine.connect()
result = con.execute("SELECT array_to_string(array_agg(CONCAT('<a href=''tg://user?id=', id)),'''>⁠</a>') AS result FROM telegram_users WHERE verified = false AND id NOT IN (SELECT user_id from telegram_user_bans);")
messageCaptcha = ""
if result is None:
messageCaptcha = "Before you can post to the group you must complete a CAPTCHA, do this and all your questions will be answered."
else:
mention_unverified = str(result.fetchone()).replace("(", "").replace("\"", "").replace(",", "").replace(")", "") + "'>⁠</a>"
messageCaptcha = mention_unverified + "Before you can post to the group you must complete a CAPTCHA, do this and all your questions will be answered."
print(messageCaptcha)
reply_markup_captcha = InlineKeyboardMarkup([
[InlineKeyboardButton(text='Resolve CAPTCHA', url='https://t.me/' + BOT_ALIAS + '?start')]
])
delete_message_by_type(context.bot, "captcha", update.effective_chat.id)
msg = tlg_send_message(context.bot, update.effective_chat.id, messageCaptcha, "captcha", reply_markup=reply_markup_captcha, parse_mode=ParseMode.HTML, disable_notification=True)
captcha_msg = msg['msg'].message_id
s = session()
usuario = s.query(User).filter_by(id=user.id).first()
usuario.captcha_message = captcha_msg
s.merge(usuario)
s.commit()
s.close()
else:
s = session()
usuario = s.query(User).filter_by(id=user.id).first()
usuario.verified = 1
s.merge(usuario)
s.commit()
s.close()
def security_check_username(self, bot, update):
""" Test username for security violations """
print(str(datetime.now()) + " security_check_username")
# Nothing by the moment
def security_check_message(self, bot, update):
print(str(datetime.now()) + " security_check_message")
""" Test message for security violations """
def attachment_check(self, bot, update):
print(str(datetime.now()) + " attachment_check")
""" Hide messages with attachments (except photo or video) """
if update.message is not None:
s = session()
usuario = s.query(User).filter_by(id=update.message.from_user.id).first()
log_message = "Log Message"
invalid_aliases = False
scam_group = False
forwarded = False
aliases = ''
if update.message.text:
aliases = re.findall(r'@(\w+)', str(update.message.text))
scam_group = "群组" in update.message.text or "团队" in update.message.text or "全新" in update.message.text
print("Se han encontrado los siguientes alias en el mensaje", aliases)
invalid_aliases = False
if update.message.forward_from or update.message.forward_from_chat:
forwarded = True
for alias in aliases:
user_with_alias = s.query(User).filter_by(username=alias).first()
if user_with_alias is None:
invalid_aliases = True
if (update.message.audio or
update.message.document or
update.message.game or
update.message.voice or invalid_aliases or scam_group or forwarded) and usuario.popularity == 0:
# Logging
mention_html = update.message.from_user.mention_html()
userAddWarn = s.query(User).filter(User.id==update.message.from_user.id).first()
if userAddWarn is None:
print(str(datetime.now()) + " ERROR BRUTAL 67")
else:
print(str(datetime.now()) + " 3.- User warnings: " + str(userAddWarn.warnings) + " and warns for ban: " + str(warnings_for_ban))
if userAddWarn.warnings >= (warnings_for_ban-1):
self.hard_ban_command(bot, update, update.message.chat_id, False, '', user_id=update.message.from_user.id)
else:
userAddWarn.warnings = userAddWarn.warnings + 1
s.merge(userAddWarn)
s.commit()
log_message_send = "❌ Message deleted (Warning " + str(userAddWarn.warnings) + "/" + str(warnings_for_ban+1) + ")." + mention_html + " you are not authorized to post audios, documents, links, games or voice messages. You need to level up by joining in the conversation more."
delete_message_by_type(bot, "not-authorized", CHAT_IDS)
print(log_message_send)
tlg_send_message(bot, CHAT_IDS, log_message_send, type="not-authorized", parse_mode=ParseMode.HTML)
print(log_message)
# Delete the message
try:
update.message.delete()
except Exception as e:
print("Error normal borrando mensaje")
# Log in database
messageHide = MessageHide(
user_id=update.message.from_user.id,
message=update.message.text)
s.add(messageHide)
s.commit()
s.close()
def banCaptcha(self, bot, message, usuario, from_user):
tlg_send_message(bot, message.chat_id, "You have been banned for failing 5 attempts. If you think it is an error write to @danicryptonews", type=None, parse_mode=ParseMode.HTML)
s = session()
checkban = s.query(UserBan).filter_by(UserBan.user_id==usuario.id).all()
if checkban is not None:
return
userBan = UserBan(
user_id=usuario.id,
reason="CAPTCHA failed 50 times")
s.add(userBan)
s.commit()
s.close()
print(str(datetime.now()) + " USER", usuario.username, "FAILED THE CAPTCHA. BANNED.")
# Removed banning command
# bot.kick_chat_member(chat_id=CHAT_IDS, user_id=from_user)
try:
bot.deleteMessage(message_id = usuario.captcha_message, chat_id = CHAT_IDS)
except Exception as e:
print(str(datetime.now()) + " [001] Error but not a problem")
def logger(self, update: Update, context: CallbackContext):
print(str(datetime.now()) + " logger")
bot = context.bot
""" Primary Logger. Handles incoming bot messages and saves them to DB
:param bot: telegram.Bot https://python-telegram-bot.readthedocs.io/en/stable/telegram.bot.html
:param update: telegram.Update https://python-telegram-bot.readthedocs.io/en/stable/telegram.update.html
"""
s = session()
if (
update.effective_user is None
or update.effective_user.id in self.ignore_user_ids
):
print(str(datetime.now()) + " {}: Ignoring update.".format(update.update_id))
return
try:
message = update.message
# message is optional
if message is None:
if update.effective_message is None:
print(str(datetime.now()) + " No message included in update")
return
message = update.effective_message
if message:
user = message.from_user
# Lets see if I must change the user info
usuario = s.query(User).filter_by(id=user.id).first()
if usuario is not None:
usuario.first_name = user.first_name
usuario.last_name = user.last_name
usuario.username = user.username
s.merge(usuario)
s.commit()
# If its edited, pass
if update.edited_message is not None:
self.log_message(user.id, message.text,
message.chat_id, message.message_id, update.edited_message.text)
return
# Limit bot to monitoring certain chats
if message.chat_id not in self.chat_ids:
from_user = "UNKNOWN"
if user:
from_user = user.id
if message.chat.type == "private":
# gets the initial value
if usuario is None:
tlg_send_message(bot, message.chat_id, "You are not a @DFX_Finance user. In order to interact with me you must join the group.", type=None, parse_mode=ParseMode.HTML)
elif (usuario.username == "CotyKuhn" or usuario.username == "Negitaro" or usuario.username == "danicryptonews" or usuario.username == "naisechef") and message.text == "/bannedlist":
banned_list = s.query(UserBan).all()
try:
os.remove('ban_list_export.xlsx')
except Exception:
print(str(datetime.now()) + " [003] Error deleting report file")
workbook = xlsxwriter.Workbook('ban_list_export.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'User ID')
worksheet.write('B1', 'User first name')
worksheet.write('C1', 'User username')
worksheet.write('D1', 'Ban reason')
worksheet.write('E1', 'Date banned')
n = 2
print(message.text_html)
for banned in banned_list:
i = str(n)
username = s.query(User).filter(User.id==banned.user_id).first()
worksheet.write('A' + i, banned.user_id)
worksheet.write('B' + i, username.first_name)
if username.username is not None:
worksheet.write('C' + i, username.username)
else:
worksheet.write('C' + i, 'Unset')
worksheet.write('D' + i, banned.reason)
worksheet.write('E' + i, banned.time.strftime("%b %d %Y %H:%M:%S"))
n = n + 1
workbook.close()
report = 'ban_list_export.xlsx'
tlg_send_file(bot, message.chat_id, open(report, 'rb'), type=None)
elif "/text2html" in message.text:
tlg_send_message(bot, message.chat_id, message.text_html.replace("\n", "\\n"), type=None, parse_mode=None)
elif usuario is not None and usuario.verified == 0:
captchaModel = s.query(Captcha).filter_by(user_id=from_user).first()
if captchaModel is not None and captchaModel.attemps <= 0:
self.banCaptcha(bot, message, usuario, from_user)
return
elif captchaModel is not None and captchaModel.solution == message.text.upper().replace(" ", ""):
usuario = s.query(User).filter_by(id=user.id).first() # gets the initial value
usuario.verified=1
s.merge(usuario)
s.commit()
permissions = ChatPermissions(
can_send_messages=True,
can_send_media_messages=True,
can_send_other_messages=True,
can_add_web_page_previews=True,
can_invite_users=True,
can_pin_messages=True,
)
context.bot.restrict_chat_member(CHAT_IDS, from_user, permissions)
tlg_send_message(bot, message.chat_id, "✅ CAPTCHA solved, welcome to the DFX Finance community! Take a look at the pinned posts or visit docs.dfx.finance for more info.", type=None, parse_mode=ParseMode.HTML)
print(str(datetime.now()) + " USER", usuario.first_name, usuario.username, "PASSED THE CAPTCHA")
try:
bot.deleteMessage(message_id = usuario.captcha_message, chat_id = CHAT_IDS)
except Exception as e:
print(str(datetime.now()) + " [001] Error but not a problem")
elif message.text == "/start" and captchaModel is None:
captcha = create_image_captcha(message.chat_id, usuario.id, 1)
captcha_code = captcha["characters"]
print(str(datetime.now()) + " USER", usuario.first_name, usuario.username, "STARTED THE CAPTCHA")
captchaModel = Captcha(
id=None,
user_id=usuario.id,
attemps=50,
solution=captcha_code
)
s.add(captchaModel)
s.commit()
img_caption = "Please write the 4 numbers you see in the image to verify that you are a human.\n\n📝 NOTE: If you find it hard you can write the command /new and receive a new one."
tlg_send_image(bot, message.chat_id, open(captcha["image"],"rb"), None, img_caption)
elif message.text == "/new" and captchaModel is not None:
captcha = create_image_captcha(message.chat_id, usuario.id, 1)
captcha_code = captcha["characters"]
captchaModel.attemps=captchaModel.attemps-1
captchaModel.solution=captcha_code
s.merge(captchaModel)
s.commit()
print(str(datetime.now()) + " USER", usuario.username, "FAILED ONE CAPTCHA ATTEMPT")
intentos = captchaModel.attemps
if intentos == 0:
self.banCaptcha(bot, message, usuario, from_user)
return
tlg_send_message(bot, message.chat_id, "Regenerating CAPTCHA, give it another try", type=None, parse_mode=ParseMode.HTML)
img_caption = "Please write the 4 numbers you see in the image to verify that you are a human."
tlg_send_image(bot, message.chat_id, open(captcha["image"],"rb"), None, img_caption)
elif captchaModel is not None and captchaModel.solution != message.text.upper().replace(" ", ""):
captchaModel.attemps=captchaModel.attemps-1
s.merge(captchaModel)
s.commit()
intentos = captchaModel.attemps
print(str(datetime.now()) + " USER", usuario.username, "FAILED ONE CAPTCHA ATTEMPT")
if intentos == 0:
self.banCaptcha(bot, message, usuario, from_user)
return
tlg_send_message(bot, message.chat_id, "❌ Sorry incorrect, give it another go", type=None, parse_mode=ParseMode.HTML)
elif usuario.verified == 1:
tlg_send_message(bot, message.chat_id, "You have already completed the CAPTCHA, nothing more to see here", type=None, parse_mode=ParseMode.HTML)
elif usuario is None:
print(str(datetime.now()) + " 3 Message from user {} is from chat_id not being monitored: {}".format(
from_user,
message.chat_id)
)
s.close()
return
if self.id_exists(user.id):
self.log_message(user.id, message.text,
message.chat_id, message.message_id, None)
else:
add_user_success = self.add_user(
user.id,
user.first_name,
user.last_name,
user.username,
1,
0)
if add_user_success:
self.log_message(
user.id, message.text, message.chat_id, message.message_id, None)