-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
1162 lines (1000 loc) · 51.3 KB
/
bot.py
File metadata and controls
1162 lines (1000 loc) · 51.3 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
import telebot
from flask import Flask, request
import time
import requests
import re
import random
import threading
import os
# import sqlite3
import psycopg2
from telebot import types
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton, InputMediaPhoto, InputMediaVideo
bot_token = os.getenv("TOKEN")
server = Flask(__name__)
bot = telebot.TeleBot(token=bot_token)
# PostSql info
db_host = os.getenv("DB_HOST")
db_name = os.getenv("DB_NAME")
db_user = os.getenv("DB_USER")
db_pass = os.getenv("DB_PASS")
db_port = 5432
# Creating a database with tables if not exists.
# db = sqlite3.connect("TelegramBot.db")
db = psycopg2.connect(host=db_host, database=db_name, user=db_user, password=db_pass, port=db_port)
curs = db.cursor()
# Chats Table
curs.execute("""CREATE TABLE IF NOT EXISTS "chats" (
"chat_id" bigint NOT NULL UNIQUE,
"rules" TEXT DEFAULT 'There are no rules yet, please contact an admin to set them.',
"rank_delay" INTEGER NOT NULL DEFAULT 900,
"ranking_delay" INTEGER NOT NULL DEFAULT 1800,
"admins_delay" INTEGER NOT NULL DEFAULT 3600,
"rankuser_delay" INTEGER NOT NULL DEFAULT 120,
"ranking_time" bigint DEFAULT 1,
"admins_time" bigint DEFAULT 1,
"rank_on" INTEGER NOT NULL DEFAULT 1,
PRIMARY KEY("chat_id")
)""")
# Users Table
curs.execute("""CREATE TABLE IF NOT EXISTS "users" (
"chat_id" bigint NOT NULL,
"point" INTEGER DEFAULT 1,
"user_id" bigint NOT NULL,
"username" TEXT,
"firstname" TEXT,
"user_level" INTEGER,
"experience" INTEGER,
"invite_by" INTEGER,
"start_exp" INTEGER,
"warnings" INTEGER,
"exp_time" bigint,
"command_time" bigint,
"rank_time" bigint DEFAULT 1,
"rankuser_time" bigint DEFAULT 1,
"is_admin" boolean DEFAULT FALSE,
PRIMARY KEY("chat_id","user_id"),
FOREIGN KEY("chat_id") REFERENCES "chats"("chat_id") ON DELETE CASCADE
)""")
db.commit()
db.close()
# end of creating a database
@bot.edited_message_handler(content_types=["text"])
def edited_messages(message):
user_id = message.from_user.id
chat_id = message.chat.id
message_id = message.message_id
bot.send_message(chat_id, "Message -{}- Edited at {} from user |{}|".format(message_id, message.edit_date, user_id))
@bot.message_handler(commands=["start"])
def send_welcome(message):
username = ""
if not message.from_user.username:
username = message.from_user.username
else:
username = message.from_user.first_name
bot.reply_to(message, "Welcome @{}!".format(username))
@bot.message_handler(content_types=['new_chat_members'])
def new_member(message):
database = psycopg2.connect(host=db_host, database=db_name, user=db_user, password=db_pass, port=db_port)
chat_id = message.chat.id
new_members = message.new_chat_members
# checking new members to add for the level system and congrats
add_new_user(database, new_members, chat_id, message)
database.close()
@bot.message_handler(content_types=['left_chat_member'])
def member_left(message):
user = message.left_chat_member
if not user.is_bot:
if user.username is not None \
:
bot.send_message(message.chat.id, "@{} aka {} just left us 😒 cya next time"
.format(user.username, user.first_name))
else:
bot.send_message(message.chat.id, "{} just left us 😒 cya next time".format(user.first_name))
else:
chat_id = message.chat.id
m_id = message.message_id
username = user.username
bot.delete_message(chat_id, m_id)
bot.send_message(chat_id, "~ {} Fuck off ! \nno place for BOTS ~".format(username))
@bot.message_handler(func=lambda msg: msg.text is not None and msg.text[0] == "." and len(msg.text) > 2)
def on_command(message):
# when a command happen
if message.chat.type == "group" or message.chat.type == "supergroup":
database = psycopg2.connect(host=db_host, database=db_name, user=db_user, password=db_pass, port=db_port)
# getting data on the Message and the Chat
user_id = message.from_user.id
chat_id = message.chat.id
message_id = message.message_id
chat_name = message.chat.title
chat_admins = bot.get_chat_administrators(chat_id)
user_is_admin = False
user_is_bot = message.from_user.is_bot
# checking if the member who sent the message is admin
for chat_member in chat_admins:
if chat_member.user.id == user_id:
user_is_admin = True
# updating data in rare cases
update_data(database, chat_id, user_id, message, user_is_admin)
rank_on = select_query(database, "rank_on", "chats", "chat_id", chat_id)
if rank_on is None:
rank_on = 1
else:
rank_on = rank_on[0]
if passed_time(database, user_id, chat_id, "Command_time", 3) or user_is_admin:
# commands for the bot
is_command = False
command = message.text
if command[0:1] == ".":
is_command = True
# Help command
if is_command and command.lower() == ".help":
help_command(chat_id, message, user_is_admin)
set_time(database, user_id, chat_id, "command_time")
# Google Help
if message.text.startswith(".google ") and command.lower() :
google(chat_id, message)
# Rules command
if is_command and command.lower() == ".rules":
rules_command(chat_id, database)
set_time(database, user_id, chat_id, "command_time")
# Config command
if user_is_admin and is_command and command.lower() == ".config":
config_command(chat_id)
elif is_command and command.lower() == ".config":
bot.delete_message(chat_id, message_id)
# Admin Command
if is_command and command.lower() == ".admins":
# passed time since last admin command server side
admins_delay = select_query(database, "admins_delay", "chats", "chat_id", chat_id)[0]
if user_is_admin or passed_time(database, user_id, chat_id, "admins_time", admins_delay):
admin_command(chat_admins, chat_name, chat_id)
if not user_is_admin:
set_time(database, user_id, chat_id, "admins_time", "chats")
set_time(database, user_id, chat_id, "command_time")
# Bot Command
if is_command and command.lower() == ".botnet":
bot_command(message)
set_time(database, user_id, chat_id, "Command_time")
# Rank command
if rank_on == 1 and is_command and command.lower() == ".rank":
# passed time since last rank command
rank_command(database, message, user_id, chat_id)
set_time(database, user_id, chat_id, "Command_time")
# Ranking command
if rank_on == 1 and is_command and command.lower() == ".ranking":
# passed time since last ranking command server side
ranking_command(chat_id, message, chat_name)
set_time(database, user_id, chat_id, "Command_time")
# Point System
if is_command and command.lower() == ".rank_point":
rank_pont(chat_id, message, chat_name)
set_time(database, user_id, chat_id, "Command_time")
if user_is_admin and is_command and command.lower() == ".reset":
if user_is_admin:
reset_point(chat_id, message)
set_time(database, user_id, chat_id, "Command_time")
else:
bot.send_message(chat_id, "Just for admin !")
# ----commands with a parameter---- #
is_para_command, is_text_mention, is_mention, mentioned_user_admin = (False, False, False, False)
mentioned_user_id, mention_length, mention_offset = (0, 0, 0)
# Checking if there is a mention in the message
if message.entities is not None and len(message.entities) == 1:
if message.entities[0].type == "text_mention":
is_text_mention = True
elif message.entities[0].type == "mention":
is_mention = True
if is_text_mention:
mention_length = message.entities[0].length
mention_offset = message.entities[0].offset
mentioned_user_id = message.entities[0].user.id
for chat_member in chat_admins:
if chat_member.user.id == mentioned_user_id:
mentioned_user_admin = True
elif is_mention:
username = str(command.split()[1][1:])
mentioned_user_id, mentioned_user_admin = get_user_id(database, username, chat_id, chat_admins)
prefix = command[0:1]
command_len = len(command.split())
if prefix == "." and command_len == 2:
is_para_command = True
elif prefix == "." and is_text_mention and len(command) == (mention_offset + mention_length):
is_para_command = True
# Rank @user command
rank_user = rank_on == 1 and is_para_command and str(command.split()[0].lower()) == ".rank"
if rank_user:
rank_user_delay = select_query(database, "Ranking_delay", "Chats", "chat_id", chat_id)[0]
if user_is_admin or passed_time(database, user_id, chat_id, "RankUser_time", rank_user_delay):
rank_user_command(database, mentioned_user_id, message_id, chat_id)
if not user_is_admin:
set_time(database, user_id, chat_id, "RankUser_time")
set_time(database, user_id, chat_id, "Command_time")
else:
bot.delete_message(chat_id, message.message_id)
# Warn command - Admins command
warn = user_is_admin and is_para_command and str(command.split()[0].lower()) == ".warn"
if warn:
warn_command(database, message, mentioned_user_id, chat_id, mentioned_user_admin, mentioned_user_id)
elif is_para_command and warn:
bot.delete_message(chat_id, message.message_id)
# Ban command - Admins command
ban = user_is_admin and is_para_command and str(command.split()[0].lower()) == ".ban"
if ban:
if mentioned_user_id is user_is_admin:
bot.send_message(chat_id, "You cant ban an admin :/")
elif mentioned_user_id is not user_is_admin:
ban_user(database, chat_id, message, mentioned_user_id)
else:
bot.send_message(chat_id, "Couldn't find this user, make sure to mention him.")
bot.delete_message(chat_id, message.message_id)
elif is_para_command and ban:
bot.delete_message(chat_id, message.message_id)
# Unban command - Admins command
unban = user_is_admin and is_para_command and str(command.split()[0].lower()) == ".unban"
if unban:
unban_command(message, mentioned_user_id, chat_id, user_is_admin)
bot.delete_message(chat_id, message.message_id)
elif is_para_command and unban:
bot.delete_message(chat_id, message.message_id)
# Point System
point_up = user_is_admin and is_para_command and str(command.split()[0].lower()) == ".up_point"
if point_up and user_is_admin:
up_point(database, message, mentioned_user_id, chat_id)
elif is_para_command and point_up:
bot.delete_message(chat_id, message.message_id)
point_down = user_is_admin and is_para_command and str(command.split()[0].lower()) == ".down_point"
if point_down and user_is_admin:
down_point(database, message, mentioned_user_id, chat_id)
elif is_para_command and point_down:
bot.delete_message(chat_id, message.message_id)
# ----commands with multiple parameters---- #
is_config_command = False
config = str(command.split()[0].lower()) == ".config"
if prefix == "." and command_len == 3 and user_is_admin and config:
is_config_command = True
# Config Rules command
rules = config and command_len > 2 and str(command.split()[1].lower()) == "rules"
if user_is_admin and rules:
config_rules_command(database, command, chat_id)
bot.delete_message(chat_id, message.message_id)
# Config Rank command
rank = is_config_command and str(command.split()[1].lower()) == "rank"
if rank:
config_rank_command(database, chat_id, command)
# Config Ranking command
ranking = is_config_command and str(command.split()[1].lower()) == "ranking"
if ranking:
config_delay_command(database, "Ranking_delay", chat_id, command)
# Config rank_user command
rank = is_config_command and str(command.split()[1].lower()) == "rank_user"
if rank:
config_delay_command(database, "RankUser_delay", chat_id, command)
# Config Admins command
admins = is_config_command and str(command.split()[1].lower()) == "admins"
if admins:
config_delay_command(database, "Admins_delay", chat_id, command)
else:
bot.delete_message(chat_id, message_id)
database.close()
"""
@bot.message_handler(func=lambda msg: msg.text is not None and '@' in msg.text)
def at_answer(message):
texts = message.text.split()
at_text = find_at(texts)
page = requests.post("https://instagram.com/{}".format(at_text[1:]))
if re.search("The link you followed may be broken, or the page may have been removed.", page.text):
pass
else:
bot.reply_to(message, "https://instagram.com/{}".format(at_text[1:]))
"""
@bot.callback_query_handler(func=lambda call: True)
def callback_query(call):
database = psycopg2.connect(host=db_host, database=db_name, user=db_user, password=db_pass, port=db_port)
message_id = call.message.message_id
chat_id = call.message.chat.id
message = call.message
chat_name = call.message.chat.title
first_name = call.message.from_user.first_name
if call.data == "cb_refresh":
ranking = ranking_command(chat_id, message, chat_name, True)
t1 = threading.Timer(0, refresh, [message, ranking])
t1.start()
elif call.data == "cb_wait_refresh":
bot.answer_callback_query(call.id, "Wait until refresh delay done")
elif call.data == "help":
rules_command(chat_id, database)
bot_m = bot.edit_message_text("Welcome to the <b>{}</b> server!~ 👻 Script Kiddo"
.format(chat_id), chat_name, message_id, parse_mode="HTML")
t1 = threading.Timer(30, bot.delete_message, args=[chat_id, bot_m.message_id])
t1.start()
elif call.data == "cb_close":
bot.delete_message(chat_id, message_id)
try:
bot.delete_message(chat_id, message.reply_to_message.message_id)
except:
pass
def refresh(message, ranking):
timer_back = 5
while timer_back != 0:
try:
bot.edit_message_text(ranking, message.chat.id, message.message_id,
reply_markup=refresh_keyboard(timer_back), parse_mode="HTML")
time.sleep(1)
timer_back -= 1
if timer_back == 0:
bot.edit_message_text(ranking, message.chat.id, message.message_id,
reply_markup=ranking_keyboard(), parse_mode="HTML")
except:
break
@bot.message_handler(content_types=["text"])
def on_message(message):
# checking if the message is from a group
if message.chat.type == "group" or message.chat.type == "supergroup":
database = psycopg2.connect(host=db_host, database=db_name, user=db_user, password=db_pass, port=db_port)
# getting data on the Message and the Chat
user_id = message.from_user.id
username = message.from_user.username
first_name = message.from_user.first_name
chat_id = message.chat.id
user_is_admin = False
chat_admins = bot.get_chat_administrators(chat_id)
# checking if the member who sent the message is admin
for chat_member in chat_admins:
if chat_member.user.id == user_id:
user_is_admin = True
update_data(database, chat_id, user_id, message, user_is_admin)
rank_on = select_query(database, "Rank_on", "Chats", "chat_id", chat_id)[0]
if "t.me/" in message.text:
if message.from_user.id != chat_admins:
bot.delete_message(chat_id, message.message_id)
if message.entities:
virus_total(message, chat_id)
# level system
if rank_on == 1 and passed_time(database, user_id, chat_id, "Exp_time", 60):
update_admins(database, chat_id, chat_admins)
set_time(database, user_id, chat_id, "Exp_time")
add_experience(database, chat_id, user_id)
level_up(database, chat_id, user_id, username, first_name)
def virus_total(message, chat_id):
first_name = message.from_user.first_name
urls = []
for entity in message.entities:
if entity.type == "text_link":
urls.append(entity.url)
elif entity.type == "url":
urls.append(entity)
for entity in urls:
check = str(entity)
if check.startswith("http"):
url = entity
if url.startswith("http"):
virus_url = "https://www.virustotal.com/ui/search?query={}".format(url)
else:
virus_url = "https://www.virustotal.com/ui/search?query=https://{}".format(url)
try:
malware = int(requests.get(virus_url).json()['data'][0]['attributes']['last_analysis_stats']['malicious'])
if malware > 0:
len_url = len(url)
half = int(len_url / 2)
star = "*" * half
bot.send_message(chat_id, "{} Sent a Bad Link - '{}{}'".format(first_name, url[:-half], star))
bot.delete_message(chat_id, message.message_id)
except:
pass
else:
url = message.text[entity.offset:entity.offset + entity.length]
if url.startswith("http"):
virus_url = "https://www.virustotal.com/ui/search?query={}".format(url)
else:
virus_url = "https://www.virustotal.com/ui/search?query=https://{}".format(url)
try:
malware = int(requests.get(virus_url).json()['data'][0]['attributes']['last_analysis_stats']['malicious'])
if malware > 0:
len_url = len(url)
half = int(len_url / 2)
star = "*" * half
bot.send_message(chat_id, "@{} Sent a Bad Link - '{}{}'".format(first_name, url[:-half], star))
bot.delete_message(chat_id, message.message_id)
except:
pass
# start of commands section
def help_command(chat_id, message, user_is_admin):
if user_is_admin:
msg = "\n_---Bot Commands---_\n" \
"*.help* - _Show this help 🙃_\n" \
"*.admins* - _Pinging the admins in the server to get help_\n" \
"*.rank* - _Show your current level and experience_\n" \
"*.rank @username* - _Shows mentioned user rank_\n" \
"*.ranking* - _Show top 10 players in the server_\n" \
"*.rules* - _Show the rules of the server_\n" \
"*.google* - _Ask google please._\n" \
"*.rank_point* - _See the top 10 most added users._\n" \
"_---Admin Commands---_\n" \
"*.warn @username* - _Warning a username, in 3 warning might be kicked!_\n" \
"*.ban @username * - _Ban this user from the server_\n" \
"*.up_point @username* - _Add a point to the user_\n" \
"*.down_point @username * - _Reduce point to user_\n" \
"*.unban @username * - _Unban the user_\n" \
"*.config* - _Show commands to configure the bot for the server_\n" \
"*Support the bot and the developer by donating, pay as you want:* [Paypal](https://paypal.me/Shepurchys)"
else:
msg = "\n_---Bot Commands---_\n" \
"*.help* - _Show this help 🙃_\n" \
"*.admins* - _Pinging the admins in the server to get help_\n" \
"*.rank* - _Show your current level and experience_\n" \
"*.rank @username* - _Shows mentioned user rank_\n" \
"*.ranking* - _Show top 10 players in the server_\n" \
"*.rules* - _Show the rules of the server_\n" \
"*.google* - _Ask google please._\n" \
"*.rank_point* - _See the top 10 most added users._\n" \
"*Support the bot and the developer by donating, pay as you want:* [Paypal](https://paypal.me/Shepurchys)"
bot_m = bot.send_message(chat_id, msg, parse_mode="Markdown")
t1 = threading.Timer(30, bot.delete_message, args=[chat_id, bot_m.message_id])
t1.start()
t2 = threading.Timer(30, bot.delete_message, args=[chat_id, message.message_id])
t2.start()
def admin_command(chat_admins, chat_name, chat_id):
answer = "{} Server admins list:\n".format(chat_name)
for user in chat_admins:
admin = user
if admin.user.is_bot:
continue
if admin.user.username is not None:
admin_name = admin.user.username
else:
admin_name = admin.user.first_name
answer += "@{}\n".format(admin_name)
answer += "#Admin_on_his_way"
bot.send_message(chat_id, answer)
def rank_command(database, message, user_id, chat_id):
start_exp = select_query(database, "Start_exp", "Users", "user_id", user_id, "chat_id", chat_id)[0]
experience = select_query(database, "Experience", "Users", "user_id", user_id, "chat_id", chat_id)[0]
level = select_query(database, "user_level", "Users", "user_id", user_id, "chat_id", chat_id)[0]
# calculating experience to the next level
exp_now = experience
exp_left = 0
while not level < int(exp_now ** 0.25):
exp_left += 5
exp_now += 5
# calculating present and over all exp
exp_overall = (experience + exp_left) - start_exp
exp_present = ((experience - start_exp) / exp_overall) * 100
tabs = int(exp_present / 3.3) * "="
spaces = int(30 - int(exp_present / 3.3)) * " "
answer = "\n*You are level:* _{}_\n*Your experience is:* _{} / {}_\n" \
"*Experience to next level:* _{}_\n*Progress:* _{}%_ \n|{}{}|" \
.format((level - 1), int(experience - start_exp), int(exp_overall),
exp_left, int(exp_present), tabs, spaces)
bot_m = bot.send_message(chat_id, answer, reply_to_message_id=message.message_id, parse_mode="Markdown")
t1 = threading.Timer(10, bot.delete_message, args=[chat_id, bot_m.message_id])
t1.start()
t2 = threading.Timer(10, bot.delete_message, args=[chat_id, message.message_id])
t2.start()
def rank_user_command(database, username_user_id, message_id, chat_id):
username_user_id = select_query(database, "user_id", "users", "chat_id", chat_id, "user_id", username_user_id)
if username_user_id is not None:
username_user_id = username_user_id[0]
username = select_query(database, "username", "users", "chat_id", chat_id, "user_id", username_user_id)
if username != "None":
username = select_query(database, "firstname", "users", "chat_id", chat_id, "user_id", username_user_id)[0]
else:
username = username[0]
start_exp = select_query(database, "Start_exp", "Users", "user_id", username_user_id, "chat_id", chat_id)[0]
experience = select_query(database, "Experience", "Users", "user_id", username_user_id, "chat_id", chat_id)[0]
level = select_query(database, "user_level", "Users", "user_id", username_user_id, "chat_id", chat_id)[0]
# calculating experience to the next level
exp_now = experience
exp_left = 0
while not level < int(exp_now ** 0.25):
exp_left += 5
exp_now += 5
# calculating present and over all exp
exp_overall = (experience + exp_left) - start_exp
exp_present = ((experience - start_exp) / exp_overall) * 100
tabs = int(exp_present / 3.3) * "="
spaces = int(30 - int(exp_present / 3.3)) * " "
answer = "\n*{}'s level is:* _{}_\n*{}'s experience is:* _{} / {}_\n" \
"*Experience to next level:* _{}_\n*Progress:* _{}%_ \n|{}{}|" \
.format(username, (level - 1), username, int(experience - start_exp), int(exp_overall),
exp_left, int(exp_present), tabs, spaces)
bot_m = bot.send_message(chat_id, answer, reply_to_message_id=message_id, parse_mode="Markdown")
t1 = threading.Timer(10, bot.delete_message, args=[chat_id, bot_m.message_id])
t1.start()
t2 = threading.Timer(10, bot.delete_message, args=[chat_id, message_id])
t2.start()
else:
bot_m = bot.send_message(chat_id, "Couldn't find this user, make sure to mention him.",
reply_to_message_id=message_id)
t1 = threading.Timer(10, bot.delete_message, args=[chat_id, bot_m.message_id])
t1.start()
t2 = threading.Timer(10, bot.delete_message, args=[chat_id, message_id])
t2.start()
def config_command(chat_id):
msg = "_---Config Commands---_\n" \
"*.config rules <text>* - _Set/change the rules of the server.(max 5000 chars)_\n" \
"*.config rank <on/off>* - _Disable or enable the rank system of the server (default on)_\n" \
"*.config rank <seconds>* - _Delay between each command of the user in seconds(default 15 mins)_\n" \
"*.config rank_user <seconds>* - _Delay between each command of the user in seconds(default 15 mins)_\n" \
"*.config ranking <seconds>* - _Delay between each command for the server in seconds(default 30 mins)_\n" \
"*.config admins<seconds>* - _Delay between each command for the server in seconds(default 1 hour)_\n"
bot.send_message(chat_id, msg, parse_mode="Markdown")
def rules_command(chat_id, database):
rules = select_query(database, "Rules", "Chats", "chat_id", chat_id)[0]
bot.send_message(chat_id, rules)
def bot_command(message):
keyboard = types.InlineKeyboardMarkup()
keyboard.add(
types.InlineKeyboardButton(text="Send a message",
url="http://t.me/let_me_test_this_bot"))
bot.reply_to(message, "Press the button to start a"
" conversation with the bot", reply_markup=keyboard)
def unban_command(message, username_user_id, chat_id, username_is_admin):
if username_user_id is not None:
bot.unban_chat_member(chat_id, username_user_id)
else:
bot.send_message(chat_id, "Couldn't find this user, make sure to mention him.",
reply_to_message_id=message.message_id)
def warn_command(database, message, username_user_id, chat_id, username_is_admin, mentioned_user_id):
cursor = database.cursor()
username_user_id = select_query(database, "user_id", "users", "chat_id", chat_id, "user_id", username_user_id)
if username_user_id is not None and username_is_admin is False:
username_user_id = username_user_id[0]
username = select_query(database, "username", "users", "chat_id", chat_id, "user_id", username_user_id)
if username != "None":
username = select_query(database, "firstname", "users", "chat_id", chat_id, "user_id", username_user_id)[0]
else:
username = username[0]
warnings = select_query(database, "Warnings", "Users", "user_id", username_user_id, "chat_id", chat_id)[0]
warnings += 1
cursor.execute("UPDATE Users SET Warnings = {} WHERE chat_id = {} AND user_id = {}"
.format(warnings, chat_id, username_user_id))
database.commit()
if warnings >= 3:
msg = "{} you have <b>warned!</b>, you currently have <b>{}</b> warnings.\n"\
.format(username, warnings)
bot.send_message(chat_id, msg, parse_mode="HTML")
ban_user(database, chat_id, message, mentioned_user_id)
else:
msg = "{} you have <b>warned!</b>, you currently have <b>{}</b> warnings." \
.format(username, warnings)
bot.send_message(chat_id, msg, parse_mode="HTML")
elif username_user_id is not None and username_is_admin:
bot.send_message(chat_id, "You can't warn an admin!",
reply_to_message_id=message.message_id)
else:
bot.send_message(chat_id, "Couldn't find this user, make sure to mention him.",
reply_to_message_id=message.message_id)
def ranking_command(chat_id, message, chat_name, ret=False):
database = psycopg2.connect(host=db_host, database=db_name, user=db_user, password=db_pass, port=db_port)
cursor = database.cursor()
try:
results = cursor.execute(
"SELECT Username,Firstname,user_id,experience FROM Users WHERE chat_id = {} AND is_admin = False"
" ORDER BY Experience DESC LIMIT 10".format(chat_id))
results = cursor.fetchall()
except:
results = (["There are no users yet"])
ranking = "<i>Top 10 Users in {} Server</i> \n<b>Ranking:</b>\n".format(chat_name)
rank = 1
for user in results:
if user[0] != "None":
username = user[0]
else:
username = user[1]
exp = user[3]
if rank == 1:
ranking += "<b>{}. {} |{}| - 🥇</b>\n".format(rank, username, exp)
rank += 1
elif rank == 2:
ranking += "<b>{}. {} |{}| - 🥈</b>\n".format(rank, username, exp)
rank += 1
elif rank == 3:
ranking += "<b>{}. {} |{}| - 🥉</b>\n".format(rank, username, exp)
rank += 1
else:
ranking += "{}. {} |{}| \n".format(rank, username, exp)
rank += 1
if ret is False:
bot.send_message(chat_id, ranking, parse_mode="HTML",
reply_markup=ranking_keyboard(), reply_to_message_id=message.message_id)
else:
return ranking
# ---config commands---
def config_rules_command(database, command, chat_id):
cursor = database.cursor()
rules = command[14:]
if "'" in rules:
bot.send_message(chat_id, "Rules cannot included ' in it.")
else:
try:
cursor.execute("UPDATE Chats SET Rules = '{}' WHERE chat_id = {}".format(rules, chat_id))
except Exception as e:
bot.send_message(chat_id, "Error: {}".format(e))
database.commit()
def config_rank_command(database, chat_id, command):
cursor = database.cursor()
parameter = str(command.split()[2])
if parameter.isdecimal():
cursor.execute("UPDATE Chats SET Rank_delay = {} WHERE chat_id = {}".format(parameter, chat_id))
elif parameter.lower() == "on":
cursor.execute("UPDATE Chats SET Rank_on = '{}' WHERE chat_id = {}".format(1, chat_id))
elif parameter.lower() == "off":
cursor.execute("UPDATE Chats SET Rank_on = '{}' WHERE chat_id = {}".format(0, chat_id))
database.commit()
def config_delay_command(database, column, chat_id, command):
cursor = database.cursor()
parameter = str(command.split()[2])
if parameter.isdecimal():
cursor.execute("UPDATE Chats SET {} = {} WHERE chat_id = {}".format(column, parameter, chat_id))
database.commit()
# Point System
def up_point(database, message, user_id, chat_id):
curs = database.cursor()
username_user_id = select_query(database, "user_id", "users", "chat_id", chat_id, "user_id", user_id)
if username_user_id:
username_user_id = username_user_id[0]
username = select_query(database, "username", "users", "chat_id", chat_id, "user_id", username_user_id)
if username != "None":
username = select_query(database, "firstname", "users", "chat_id", chat_id, "user_id", username_user_id)[0]
else:
username = username[0]
point = select_query(database, "point", "users", "user_id", user_id, "chat_id", chat_id)[0]
point += 1
curs.execute("UPDATE users SET point = {} WHERE user_id = {} and chat_id = {}".format(point, user_id, chat_id))
database.commit()
bot_m = bot.send_message(chat_id, "Excellent @{} !\nYou got a point".format(username))
t1 = threading.Timer(10, bot.delete_message, args=[chat_id, bot_m.message_id])
t2 = threading.Timer(10, bot.delete_message, args=[chat_id, message.message_id])
t1.start()
t2.start()
else:
bot_m = bot.send_message(chat_id, "Couldn't find this user, make sure to mention him.",
reply_to_message_id=message.message_id)
t1 = threading.Timer(10, bot.delete_message, args=[chat_id, bot_m.message_id])
t2 = threading.Timer(10, bot.delete_message, args=[chat_id, message.message_id])
t1.start()
t2.start()
def reset_point(database, message):
database = psycopg2.connect(host=db_host, database=db_name, user=db_user, password=db_pass, port=db_port)
cursor = database.cursor()
chat_id = message.chat.id
cursor.execute("UPDATE users SET point = 0 WHERE chat_id = {}".format(chat_id))
database.commit()
bot_m = bot.send_message(chat_id, "Reset challenge .")
t1 = threading.Timer(1, bot.edit_message_text, args=["Reset challenge ...", chat_id, bot_m.message_id])
t1.start()
t2 = threading.Timer(1, bot.edit_message_text, args=["Reset complete !", chat_id, bot_m.message_id])
t2.start()
def reset_user_ban(database, message, mentioned_user_id):
database = psycopg2.connect(host=db_host, database=db_name, user=db_user, password=db_pass, port=db_port)
cursor = database.cursor()
chat_id = message.chat.id
cursor.execute("DELETE FROM users WHERE chat_id = {} and user_id = {}".format(chat_id, mentioned_user_id))
database.commit()
def down_point(database, message, mentioned_user_id, chat_id):
username_user_id = select_query(database, "user_id", "users", "chat_id", chat_id, "user_id", mentioned_user_id)
if username_user_id is not None:
username_user_id = username_user_id[0]
username = select_query(database, "username", "users", "chat_id", chat_id, "user_id", username_user_id)
if username != "None":
username = select_query(database, "firstname", "users", "chat_id", chat_id, "user_id", username_user_id)[0]
else:
username = username[0]
point = select_query(database, "point", "users", "user_id", mentioned_user_id, "chat_id", chat_id)[0]
if point != 0:
point -= 1
curs = database.cursor()
curs.execute(
"UPDATE users SET point = {} WHERE user_id = {} and chat_id = {}".format(point, mentioned_user_id, chat_id))
database.commit()
get_point = select_query(database, "point", "users", "user_id", mentioned_user_id, "chat_id", chat_id)[0]
if get_point < 0:
curs.execute(
"UPDATE users SET point = 0 WHERE user_id = {} and chat_id = {}".format(mentioned_user_id, chat_id))
database.commit()
bot_m = bot.send_message(chat_id, "Mmm.. @{} \nless one point".format(username))
t1 = threading.Timer(10, bot.delete_message, args=[chat_id, bot_m.message_id])
t1.start()
t2 = threading.Timer(10, bot.delete_message, args=[chat_id, message.message_id])
t2.start()
else:
bot_m = bot.send_message(chat_id, "Couldn't find this user, make sure to mention him.",
reply_to_message_id=message.message_id)
t1 = threading.Timer(10, bot.delete_message, args=[chat_id, bot_m.message_id])
t1.start()
t2 = threading.Timer(10, bot.delete_message, args=[chat_id, message.message_id])
t2.start()
def rank_pont(chat_id, message, chat_name):
database = psycopg2.connect(host=db_host, database=db_name, user=db_user, password=db_pass, port=db_port)
cursor = database.cursor()
try:
results = cursor.execute("SELECT Username,Firstname,user_id,point FROM Users WHERE chat_id = {}"
" ORDER BY point DESC LIMIT 10".format(chat_id))
results = cursor.fetchall()
except:
results = (["There are no users yet"])
ranking = "<i>Top 10 Users in {} Server</i> \n<b>From the last challenge:</b>\n".format(chat_name)
rank = 1
for user in results:
if user[0] != "None":
username = user[0]
else:
username = user[1]
point = user[3]
if rank == 1:
ranking += "<b>{}. {} |{}| - 🥇</b>\n".format(rank, username, point)
rank += 1
elif rank == 2:
ranking += "<b>{}. {} |{}| - 🥈</b>\n".format(rank, username, point)
rank += 1
elif rank == 3:
ranking += "<b>{}. {} |{}| - 🥉</b>\n".format(rank, username, point)
rank += 1
else:
ranking += "{}. {} |{}| \n".format(rank, username, point)
rank += 1
bot_m = bot.send_message(chat_id, ranking, parse_mode="HTML", reply_to_message_id=message.message_id)
t1 = threading.Timer(10, bot.delete_message, args=[chat_id, bot_m.message_id])
t1.start()
t2 = threading.Timer(10, bot.delete_message, args=[chat_id, message.message_id])
t2.start()
# end of commands section
def google(chat_id, message):
source = message.text
quest = source[8:]
url = "https://lmgtfy.com/?q="
for i in range(len(quest)):
quest = quest.replace(" ", "+")
print(quest)
url = url + quest
bot.send_message(chat_id, "It was hard but I succeeded ..\nFor you :\n{}".format(url))
# returning message if has @ in it
def find_at(msg):
for text in msg:
if "@" in text:
return text
def passed_time(database, user_id, chat_id, column, seconds, table="Users"):
if table == "Users":
old_time = select_query(database, column, table, "user_id", user_id, "chat_id", chat_id)[0]
else:
old_time = select_query(database, column, table, "chat_id", chat_id)[0]
time_passed = int(time.time() - old_time)
if time_passed >= seconds:
return True
else:
return False
def set_time(database, user_id, chat_id, column, table="Users"):
cursor = database.cursor()
if table == "Users":
cursor.execute("UPDATE {} SET {} = {} WHERE chat_id = {} AND user_id = {}"
.format(table, column, int(time.time()), chat_id, user_id))
else:
cursor.execute("UPDATE {} SET {} = {} WHERE chat_id = {}"
.format(table, column, int(time.time()), chat_id, user_id))
database.commit()
def get_user_id(database, username, chat_id, chat_admins):
user_id = select_query(database, "user_id", "Users", "Username", username, "chat_id", chat_id)
if user_id is not None:
user_admin = False
for chat_member in chat_admins:
if chat_member.user.id == user_id[0]:
user_admin = True
return user_id[0], user_admin
else:
return None, False
def select_query(database, column, table, column_name, column_value, column_name2=None, column_value2=None):
"""
:param database: Sqlite3 database
:param column: a string of the selected column to get info from ( to get all columns, string should be "all").
:param table: From which table
:param column_name: a string of the column you want to equal to a value ( username = )
:param column_value: the value of the column_name ( column_name = "drake")
:param column_name2: a string Optional - adds AND option to the query to check with another column
:param column_value2: Optional the value of column_name2
:return: None or results
"""
if type(column_value) == str:
column_value = "'{}'".format(column_value)
if type(column_value2) == str:
column_value2 = "'{}'".format(column_value2)
cursor = database.cursor()
if column.lower() == "all" and column_name2 is not None and column_value2 is not None:
cursor.execute("SELECT * FROM {} WHERE {} = {} AND {} = {}"
.format(table, column_name, column_value, column_name2, column_value2))
elif column.lower() == "all" and column_name2 is None and column_value2 is None:
cursor.execute("SELECT * FROM {} WHERE {} = {}"
.format(table, column_name, column_value))
elif column_name2 is None and column_value2 is None:
cursor.execute("SELECT {} FROM {} WHERE {} = {}"
.format(column, table, column_name, column_value))
else:
cursor.execute("SELECT {} FROM {} WHERE {} = {} AND {} = {}"
.format(column, table, column_name, column_value, column_name2, column_value2))
return cursor.fetchone()
# adding exp each message the user sent.
def add_experience(database, chat_id, user_id):
cursor = database.cursor()
experience = random.choice([15, 20, 25, 30])
current_experience = select_query(database, "Experience", "Users", "user_id", user_id, "chat_id", chat_id)[0]
final_exp = int(current_experience + experience)
cursor.execute("UPDATE Users SET Experience = {} WHERE chat_id = {} AND user_id = {}"
.format(final_exp, chat_id, user_id))
database.commit()
# checking every message if the user have leveled up
def level_up(database, chat_id, user_id, username, firstname):
cursor = database.cursor()
experience = select_query(database, "Experience", "Users", "user_id", user_id, "chat_id", chat_id)[0]
level = select_query(database, "user_level", "Users", "user_id", user_id, "chat_id", chat_id)[0]
# Updating level and start of exp to make calculations later.
def update_info():
cursor.execute("UPDATE Users SET user_level = {} WHERE chat_id = {} AND user_id = {}"
.format(level_end, chat_id, user_id))
cursor.execute("UPDATE Users SET Start_exp = {} WHERE chat_id = {} AND user_id = {}"
.format(experience, chat_id, user_id))
# Formula for how much exp needed to next level
level_end = int(experience ** 0.25)
# checking if he leveled up and congrats him if he has username or neither
if level < level_end and username is not None:
bot_m = bot.send_message(chat_id,
"@{} has leveled up to level {} Congratulations 👏".format(username, (level_end - 1)))
t1 = threading.Timer(10, bot.delete_message, args=[chat_id, bot_m.message_id])
t1.start()
update_info()
elif level < level_end:
bot_m = bot.send_message(chat_id,
"{} has leveled up to level {} Congratulations 👏".format(firstname, (level_end - 1)))
t1 = threading.Timer(10, bot.delete_message, args=[chat_id, bot_m.message_id])
t1.start()
update_info()
# updating every change to the database.
database.commit()
def update_admins(database, chat_id, chat_admins):
cursor = database.cursor()
for admin in chat_admins:
cursor.execute("UPDATE Users SET is_admin = True WHERE chat_id = {} AND user_id = {}"
.format(chat_id, admin.user.id))
database.commit()
cursor.execute("SELECT user_id FROM Users WHERE chat_id = {} AND is_admin = True"
.format(chat_id))
saved_admins = cursor.fetchall()
for user in saved_admins:
is_admin = False
for admin in chat_admins:
if admin.user.id == user[0]:
is_admin = True