-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1837 lines (1543 loc) · 65.8 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
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
#!/usr/bin/env python3
from aiogram import Bot, Dispatcher, F
from aiogram.types import (Message, InlineKeyboardButton, InlineKeyboardMarkup, LabeledPrice, PreCheckoutQuery,
CallbackQuery)
from aiogram.utils.markdown import hbold, hlink
from babel.numbers import get_currency_symbol
from asyncio import run as async_run
from asyncio import sleep as asleep
from asyncio import gather, get_event_loop, create_task, CancelledError, all_tasks, current_task
from time import time as unixtime
from dotenv import dotenv_values
from applib.strings import *
from applib import *
from aiopg import Cursor
from random import randint, choice
from typing import Dict
from signal import SIGINT, SIGTERM
from re import IGNORECASE
from html import escape
import json
from os import environ
from google.cloud import dialogflow
from google.api_core.exceptions import InvalidArgument
from google.oauth2 import service_account
with open(dialog_flow_file) as f:
environ["GOOGLE_APPLICATION_CREDENTIALS"] = str(dialog_flow_file)
DIALOGFLOW_PROJECT_ID = "small-talk-rwvf"
DIALOGFLOW_LANGUAGE_CODE = 'ru'
SESSION_ID = 'me'
credentials = service_account.Credentials.from_service_account_file(dialog_flow_file)
sessionClient = dialogflow.SessionsClient(credentials=credentials)
secrets: Dict[str, str | None] = dotenv_values('.env')
TOKEN: str = secrets["BOT_TOKEN"] # type: ignore
bot: Bot = Bot(TOKEN)
dp = Dispatcher(bot=bot)
# TelegramBot = require('node-telegram-bot-api');
# sqlite3 = require('sqlite3').verbose();
# dialogflow = require('@google-cloud/dialogflow').v2beta1;
# const sharp = require('sharp');
# const fs = require('fs')
event_coin_path = './rate.txt'
# logf(chatCompletion.choices[0].message.content);
payment_token = "284685063:TEST:Y2YxMWE3NmJkODRh"
admins_id = [1432248216, 1300210900]
# credentials = require('./key.json')
projectId = 'small-talk-rwvf'
vid250 = './250videocards.png'
clans = ("отсутствует",)
lastToId = 0
startTime = unixtime()
cooldownPeriod = 5000
# region ----- Without using DB
#@dp.message(F.text.regexp(r'(?i)^(\/start|меню)(\s|$)', flags=IGNORECASE))
@dp.message(F.text.regexp(r'(?i)^(\/start(?:@[\w]+)?|меню)(\s|$)', flags=IGNORECASE))
async def start(message: Message):
user_name = message.from_user.first_name
try:
await message.reply(
start_text(user_name),
allow_sending_without_reply=True,
parse_mode="markdown",
reply_markup=InlineKeyboardMarkup(
inline_keyboard=start_keyboard(InlineKeyboardButton))
)
except Exception as e:
await logf(e)
await message.reply(f"❌ Произошла ошибка!\n <code>{e}</code>",
allow_sending_without_reply=True,
parse_mode='HTML')
@dp.message(F.text.regexp(r'(?i)^(\/ping(?:@[\w]+)?|пинг)(\s|$)', flags=IGNORECASE))
async def ping(message: Message):
start_time = unixtime()
try:
reply_message = await bot.send_message(message.chat.id, '🔄 *Пинг...*')
end_time = unixtime()
ping_time = round((end_time - start_time) * 1000, 2)
await bot.edit_message_text(
f"🚀 *Понг!* \n💡 *Задержка:* {ping_time}ms",
chat_id=message.chat.id,
message_id=reply_message.message_id,
parse_mode="markdown")
except Exception as e:
await bot.send_message(message.chat.id, f"Произошла ошибка: {str(e)}")
# @dp.message(F.text.startswith("/test") | F.text.lower().startswith('тест'))
# async def test(message: Message):
# await bot.send_message(message.chat.id, f"Тест вывод: {1}")
@dp.message(F.text.regexp(r'(?i)^(\/donate(?:@[\w]+)?|донат)(\s|$)', flags=IGNORECASE))
async def donate(message: Message):
try:
assert message.from_user is not None
user_id = message.from_user.id
user_name = message.from_user.first_name
if await check_flood_wait(user_id):
warning = await message.reply(
f'🚫 <a href="tg://user?id={user_id}">{escape(user_name)}</a>, '
f'Вы отправляете слишком много сообщений. Пожалуйста, подождите немного.',
parse_mode="HTML"
)
await asleep(3)
await bot.delete_message(warning.chat.id, warning.message_id)
return
await message.reply(
donate_text(),
allow_sending_without_reply=True,
parse_mode="markdown",
reply_markup=InlineKeyboardMarkup(
inline_keyboard=donate_keyboard(InlineKeyboardButton, prices)
)
)
except Exception as e:
await bot.edit_message_text(
f'❌ Произошла ошибка!\n{e}',
chat_id=message.chat.id,
message_id=message.message_id,
)
await logf(e)
@dp.message(F.text.regexp(r'(?i)^(\/shop(?:@[\w]+)?|магазин)(\s|$)', flags=IGNORECASE))
async def shop(message: Message):
assert message.from_user is not None
user_id = message.from_user.id
user_name = message.from_user.first_name
ecoin = await ecoin_to_bucks(1)
if await check_flood_wait(user_id):
warning = await message.reply(
f'🚫 <a href="tg://user?id={user_id}">{escape(user_name)}</a>, '
f'Вы отправляете слишком много сообщений. Пожалуйста, подождите немного.',
parse_mode="HTML"
)
await asleep(3)
await bot.delete_message(warning.chat.id, warning.message_id)
return
try:
await message.reply(
shop_text(),
allow_sending_without_reply=True,
parse_mode="markdown",
reply_markup=InlineKeyboardMarkup(
inline_keyboard=shop_keyboard(InlineKeyboardButton, ecoin)
)
)
except Exception as e:
await logf(e)
await message.reply(f"❌ Произошла ошибка!\n <code>{e}</code>",
allow_sending_without_reply=True,
parse_mode='HTML')
@dp.message(F.text.regexp(r'(?i)^(\/rate(?:@[\w]+)?|курс|екоин)(\s|$)', flags=IGNORECASE))
async def show_rate(message: Message):
rate = await ecoin_to_bucks(1)
await message.reply(
rate_text(rate),
allow_sending_without_reply=True,
parse_mode='HTML'
)
@dp.message(F.text.regexp(r'(?i)^(\/event(?:@[\w]+)?|ивент|ярмарка|рождество)(\s|$)', flags=IGNORECASE))
async def christmas_fair(message: Message):
assert message.from_user is not None
user_id = message.from_user.id
user_name = message.from_user.first_name
ecoin = await ecoin_to_bucks(1)
if await check_flood_wait(user_id):
warning = await message.reply(
f'🚫 <a href="tg://user?id={user_id}">{escape(user_name)}</a>, '
f'Вы отправляете слишком много сообщений. Пожалуйста, подождите немного.',
parse_mode="HTML"
)
await asleep(3)
await bot.delete_message(warning.chat.id, warning.message_id)
return
try:
await message.reply(
christmas_fair_text(),
allow_sending_without_reply=True,
parse_mode="markdown",
reply_markup=InlineKeyboardMarkup(
inline_keyboard=christmas_fair_keyboard(InlineKeyboardButton)
)
)
except Exception as e:
await logf(e)
await message.reply(f"❌ Произошла ошибка!\n <code>{e}</code>",
allow_sending_without_reply=True,
parse_mode='HTML')
# endregion
# region ----- With using DB
@dp.channel_post()
@with_db(False)
async def handle_channel_post(cur: Cursor, load: Message, post: Message):
channel_id = -1001643266914
if post.chat.id != channel_id:
return
if post.text.startswith('/log'):
return
await cur.execute("SELECT id, posting FROM users")
users = await cur.fetchall()
message_id_to_forward = post.message_id
for user in users:
user_id, posting = user['id'], user['posting']
if posting == 0:
await logf(f"Пользователь {user_id} не подписан на рассылку.")
else:
try:
await bot.forward_message(user_id, channel_id, message_id_to_forward)
await logf(f"Сообщение отправлено пользователю {user_id}.")
except Exception as error:
await logf(f"Ошибка при пересылке сообщения пользователю с ID {user_id}: {error}")
await cur.execute("UPDATE users SET posting = 0 WHERE id = %s", (user_id,))
await cur.execute("SELECT id FROM groups")
groups = await cur.fetchall()
for group in groups:
group_id = group['id']
try:
await bot.forward_message(group_id, channel_id, message_id_to_forward)
await logf(f"Сообщение отправлено в группу {group_id}.")
except Exception as error:
await logf(f"Ошибка при пересылке сообщения в группу с ID {group_id}: {error}")
@dp.message(F.text.regexp(r'(?i)^(\/cash(?:@[\w]+)?|баланс)(\s|$)', flags=IGNORECASE))
@with_db(True)
async def get_cash(cur: Cursor, load: Message, message: Message):
try:
assert message.from_user is not None
user_id = message.from_user.id
user_name = message.from_user.first_name
if await check_flood_wait(user_id):
await bot.edit_message_text(
f'🚫 <a href="tg://user?id={user_id}">{escape(user_name)}</a>, Вы отправляете слишком много сообщений. Пожалуйста, подождите немного.',
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="HTML"
)
await asleep(3)
await bot.delete_message(load.chat.id, load.message_id)
return
await cur.execute(
"SELECT cash, event, bitcoins, level FROM users WHERE id=%s",
(user_id,))
row = await cur.fetchone()
if row is None:
await bot.edit_message_text(
"❌ Не найдено данных для пользователя.",
chat_id=load.chat.id,
message_id=load.message_id)
return
if not await check_account(cur, message):
return
cash = format_num(row["cash"])
ecoin = format_num(row["bitcoins"])
cash_text = f"{cash} $"
ecoins_text = f"{ecoin} ₠"
await bot.edit_message_text(
balance_text(cash_text, ecoins_text, row["event"], row["level"]),
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="markdown"
)
except Exception as e:
await bot.send_message(message.chat.id,
f"❌ Произошла ошибка!\n <code>{e}</code>",
parse_mode='HTML')
raise e
@dp.message(F.text.regexp(r'^(\/farming(?:@[\w]+)?|фарм)(\s|$)', flags=IGNORECASE))
@with_db(True)
async def farm(cur: Cursor, load: Message, message: Message):
try:
assert message.from_user is not None
user_id = message.from_user.id
user_name = message.from_user.first_name
if await check_flood_wait(user_id):
await bot.edit_message_text(
f'🚫 <a href="tg://user?id={user_id}">{escape(user_name)}</a>, Вы отправляете слишком много сообщений. Пожалуйста, подождите немного.',
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="HTML"
)
await asleep(3)
await bot.delete_message(load.chat.id, load.message_id)
return
await cur.execute(
"SELECT isvip, videocards, last_farming_time, event, level, boost FROM users WHERE id = %s",
(message.from_user.id,))
row = await cur.fetchone()
if not await check_account(cur, message):
return
is_vip = vip_rangs[row['isvip']]
videocards: int = row['videocards']
last_farming_time = row['last_farming_time']
time_now = unixtime()
if time_now - last_farming_time < farming_timers[row['isvip']]:
time_to_use = farming_timers[row['isvip']] - (time_now - last_farming_time)
await bot.edit_message_text(
farm_text_failure(time_to_use),
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="markdown"
)
return
random_cash = int(randint(1000, 10000))
random_cash *= multiplies[row['isvip']]
random_cash *= videocards if videocards else 1
random_cash += random_cash * row["boost"]
multiply_text = multiplies[row['isvip']] * videocards
text_video = videocards if videocards else 'Нет. \n💠Используется встроенное графическое ядро.'
rate, farmed_amount = await read_eventcoin()
cryptocoins = random_cash / rate
tokens_received = generate_event_tokens(row['level'], row["boost"])
await cur.execute("UPDATE users SET event = event + %s WHERE id = %s", (tokens_received, user_id))
farmed_amount += random_cash
await write_eventcoin(rate, farmed_amount)
await bot.edit_message_text(
farm_text_success(
cryptocoins,
is_vip,
str(text_video),
multiply_text,
row["boost"],
tokens_received
),
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="markdown"
)
await logf(
f"{message.from_user.first_name} - {format_time(int(time_now))}, Link - 'tg://user?id={message.from_user.id}'"
)
await cur.execute(
'UPDATE users SET last_farming_time = %s, bitcoins = bitcoins + %s WHERE id = %s',
(time_now, cryptocoins, message.from_user.id))
await update_quest(user_id, 'farming', 1)
if tokens_received:
await update_quest(user_id, 'earn_tokens', tokens_received)
except Exception as e:
await bot.edit_message_text(
f'❌ Произошла ошибка!\n{e}',
chat_id=load.chat.id,
message_id=load.message_id,
)
await logf(e)
@dp.message(F.text.regexp(r'(?i)^(\/quests(?:@[\w]+)?|квесты|задания)(\s|$)', flags=IGNORECASE))
@with_db(True)
async def quests(cur: Cursor, load: Message, message: Message):
try:
assert message.from_user is not None
user_id = message.from_user.id
user_name = message.from_user.first_name
if await check_flood_wait(user_id):
await bot.edit_message_text(
f'🚫 <a href="tg://user?id={user_id}">{escape(user_name)}</a>, вы отправляете слишком много сообщений. Подождите немного.',
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="HTML"
)
await asleep(3)
await bot.delete_message(load.chat.id, load.message_id)
return
await cur.execute(
"SELECT id FROM users WHERE id=%s",
(user_id,)
)
row = await cur.fetchone()
if not row or not await check_account(cur, message):
await bot.edit_message_text(
"❌ Данные пользователя не найдены.",
chat_id=load.chat.id,
message_id=load.message_id
)
return
link = f'<a href="tg://user?id={user_id}">{escape(user_name)}</a>'
quests_text = await get_quests(
user_id=user_id,
link=link
)
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[InlineKeyboardButton(
text="✅ Забрать награду",
callback_data=f"collect_reward"
)]
])
await bot.edit_message_text(
quests_text,
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="HTML",
reply_markup=keyboard if keyboard.inline_keyboard else None
)
except Exception as e:
await bot.send_message(
chat_id=message.chat.id,
text=f"❌ Произошла ошибка!\n<code>{escape(str(e))}</code>",
parse_mode="HTML"
)
raise e
@dp.message(F.text.regexp(r'(?i)^(\/rich_top(?:@[\w]+)?|топ богачей|топ богатых|богатые)(\s|$)', flags=IGNORECASE))
@with_db(True)
async def rich_top(cur, load: Message, message: Message):
try:
assert message.from_user is not None
user_id = message.from_user.id
user_name = message.from_user.first_name
if await check_flood_wait(user_id):
await bot.edit_message_text(
f'🚫 <a href="tg://user?id={user_id}">{escape(user_name)}</a>, Вы отправляете слишком много сообщений. Пожалуйста, подождите немного.',
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="HTML"
)
await asleep(3)
await bot.delete_message(load.chat.id, load.message_id)
return
await cur.execute("SELECT name, cash, id, tag FROM users ORDER BY cash DESC LIMIT 10")
users_row = await cur.fetchall()
keyboard = top_keyboard(users_row, InlineKeyboardButton, "$")
await bot.edit_message_text(
rich_text(),
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="HTML",
reply_markup=InlineKeyboardMarkup(
inline_keyboard=keyboard
)
)
except Exception as e:
await bot.edit_message_text(
f'❌ Произошла ошибка!\n{e}',
chat_id=load.chat.id,
message_id=load.message_id,
)
await logf(e)
@dp.message(F.text.regexp(r'(?i)^(\/crypto_top(?:@[\w]+)?|топ крипта|топ майнеры|майнеры)(\s|$)', flags=IGNORECASE))
@with_db(True)
async def rich_top(cur, load: Message, message: Message):
try:
assert message.from_user is not None
user_id = message.from_user.id
user_name = message.from_user.first_name
if await check_flood_wait(user_id):
await bot.edit_message_text(
f'🚫 <a href="tg://user?id={user_id}">{escape(user_name)}</a>, Вы отправляете слишком много сообщений. Пожалуйста, подождите немного.',
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="HTML"
)
await asleep(3)
await bot.delete_message(load.chat.id, load.message_id)
return
await cur.execute("SELECT name, bitcoins, id, tag FROM users ORDER BY bitcoins DESC LIMIT 10")
users_row = await cur.fetchall()
keyboard = top_keyboard(users_row, InlineKeyboardButton, "₠")
await bot.edit_message_text(
crypto_text(),
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="HTML",
reply_markup=InlineKeyboardMarkup(
inline_keyboard=keyboard
)
)
except Exception as e:
await bot.edit_message_text(
f'❌ Произошла ошибка!\n{e}',
chat_id=load.chat.id,
message_id=load.message_id,
)
await logf(e)
@dp.message(F.text.regexp(r'(?i)^(\/dice(?:@[\w]+)?|кубик|кости)(\s|$)', flags=IGNORECASE))
@with_db(True)
async def dice(cur, load: Message, message: Message):
try:
assert message.from_user is not None
user_id = message.from_user.id
first_name = message.from_user.first_name
await cur.execute("SELECT cash FROM users WHERE id = %s", (user_id,))
user = await cur.fetchone()
if not await check_account(cur, message):
return
balance = user['cash']
if await check_flood_wait(user_id):
warning = await message.reply(
f"🚫 <a href=tg://user?id={user_id}>{escape(first_name)}</a>, "
f"Вы отправляете слишком много сообщений. Пожалуйста, подождите немного.",
parse_mode="HTML"
)
await asleep(3)
await bot.delete_message(warning.chat.id, warning.message_id)
return
try:
parts = message.text.split()
bid = int(parts[1])
dice_value = int(parts[2])
if not await validate_bid(bid, balance):
if bid < 10:
await send_error_reply(
message,
"⚠️ *Ошибка!* \nСтавка должна быть не меньше 10!",
f"{message.text.split(' ')[0]} [ставка] [1-6]"
)
await bot.delete_message(
chat_id=load.chat.id,
message_id=load.message_id,
)
else:
await bot.edit_message_text(
"🚫 *Недостаточно денег!* 💸\n"
"Пожалуйста, внесите средства на свой счёт, чтобы продолжить игру.",
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="markdown"
)
return
if not await validate_dice_value(dice_value):
await send_error_reply(
message,
"⚠️ *Ошибка!* \nЧисло должно быть от 1 до 6! 🎲",
f"{message.text.split(' ')[0]} [ставка] [1-6]"
)
await bot.delete_message(
chat_id=load.chat.id,
message_id=load.message_id,
)
return
except (IndexError, ValueError):
await message.reply(
"⚠️ *Ошибка!* \n"
"Введите ставку и число от 1 до 6! 🎯\n"
f"Использование: `{message.text.split(' ')[0]} [ставка] [1-6]`",
parse_mode="markdown"
)
return
try:
await bot.delete_message(
load.chat.id,
load.message_id
)
spin = await bot.send_dice(
message.chat.id,
emoji="🎲",
allow_sending_without_reply=True,
reply_to_message_id=message.message_id
)
value = spin.dice.value
if value == dice_value:
result_text = (
f"🎉 *Везение!* \n\nВы выиграли: +{format_num(bid)}💸\n\n"
f"💰 Ваш баланс теперь: {format_num(balance + bid)}$"
)
await cur.execute(
"UPDATE users SET cash = cash + %s WHERE id = %s",
(bid, user_id)
)
else:
result_text = (
f"😞 *Мимо!* \n\nВы проиграли: -{format_num(bid)}💸\n\n"
f"💰 Ваш баланс теперь: {format_num(balance - bid)}$")
await cur.execute(
"UPDATE users SET cash = cash - %s WHERE id = %s",
(bid, user_id)
)
await asleep(4)
await update_quest(user_id, "spent", bid)
await bot.send_message(
message.chat.id,
result_text,
allow_sending_without_reply=True,
reply_to_message_id=spin.message_id,
parse_mode="markdown"
)
except Exception as e:
await message.reply(
f"❌ Произошла ошибка!\n<code>{e}</code>",
parse_mode='HTML'
)
except Exception as e:
await bot.edit_message_text(
f'❌ Произошла ошибка!\n{e}',
chat_id=load.chat.id,
message_id=load.message_id,
)
await logf(e)
@dp.message(F.text.regexp(
r'(?i)^(\/basketball(?:@[\w]+)?|\/darts(?:@[\w]+)?|\/football(?:@[\w]+)?|\/bowling(?:@['
r'\w]+)?|\/spin(?:@[\w]+)?|баскетбол|дартс|футбол|боулинг|спин|казино)(\s|$)',
flags=IGNORECASE)
)
@with_db(True)
async def game_handler(cur, load: Message, message: Message):
try:
assert message.from_user is not None
user_id = message.from_user.id
await cur.execute("SELECT cash FROM users WHERE id = %s", (user_id,))
user = await cur.fetchone()
if not await check_account(cur, message):
return
balance = user['cash']
if await check_flood_wait(user_id):
warning = await message.reply(
"🚫 Вы отправляете слишком много сообщений. Пожалуйста, подождите немного.",
parse_mode="markdown"
)
await asleep(3)
await bot.delete_message(warning.chat.id, warning.message_id)
return
try:
await bot.delete_message(
load.chat.id,
load.message_id
)
bid = int(message.text.split()[1])
if bid < 10:
await send_error_reply(
message,
"⚠️ *Ошибка!* \nСтавка должна быть не меньше 10!",
f"{message.text.split(' ')[0]} [ставка]"
)
return
if bid > balance:
await message.reply(
"🚫 *Недостаточно денег!* 💸\nПополните счёт, чтобы продолжить игру.",
parse_mode="markdown"
)
return
except (IndexError, ValueError):
await message.reply(
"⚠️ *Ошибка!* \nВведите ставку как целое число!\n"
f"Использование: `{message.text.split(' ')[0]} [ставка]`",
parse_mode="markdown"
)
return
try:
emoji = await get_emoji(message.text.split(' ')[0])
spin = await bot.send_dice(
message.chat.id,
emoji=emoji,
allow_sending_without_reply=True,
reply_to_message_id=message.message_id
)
value = spin.dice.value
emoji = spin.dice.emoji
obtaining, nb = await get_result(emoji, value, bid, balance, user_id)
await asleep(4)
await cur.execute(
"UPDATE users SET cash = cash + %s WHERE id = %s",
(nb, user_id)
)
await bot.send_message(
message.chat.id,
obtaining,
reply_to_message_id=spin.message_id,
parse_mode="markdown"
)
except Exception as e:
await message.reply(f"❌ Произошла ошибка!\n <code>{e}</code>", parse_mode='HTML')
except Exception as e:
await bot.edit_message_text(
f'❌ Произошла ошибка!\n{e}',
chat_id=load.chat.id,
message_id=load.message_id,
)
await logf(e)
@dp.message(F.text.regexp(r'(?i)^(\/profile(?:@[\w]+)?|профиль)(\s|$)', flags=IGNORECASE))
@with_db(True)
async def profile(cur: Cursor, load: Message, message: Message):
try:
assert message.from_user is not None
user_id = message.from_user.id
user_name = message.from_user.first_name
if await check_flood_wait(user_id):
await bot.edit_message_text(
f'🚫 <a href="tg://user?id={user_id}">{escape(user_name)}</a>, Вы отправляете слишком много сообщений. Пожалуйста, подождите немного.',
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="HTML"
)
await asleep(3)
await bot.delete_message(load.chat.id, load.message_id)
return
if message.entities and len(message.entities) > 1 and message.entities[1].type == "mention":
username = message.text[
message.entities[1].offset + 1:message.entities[1].offset + message.entities[1].length]
user_query = "SELECT name, id, cash, isvip, videocards, clan, tag, bitcoins FROM users WHERE mention = %s"
user_param = (username,)
elif message.reply_to_message:
user_id = message.reply_to_message.from_user.id
user_query = "SELECT name, id, cash, isvip, videocards, clan, tag, bitcoins FROM users WHERE id = %s"
user_param = (user_id,)
else:
await bot.edit_message_text(
"❗️ Команда должна писаться в ответ на сообщение или содержать упоминание пользователя!",
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="HTML"
)
return
await cur.execute(user_query, user_param)
user = await cur.fetchone()
if not user:
await message.reply(
"❌ У этого пользователя нет аккаунта!",
allow_sending_without_reply=True
)
return
if user["clan"] == 0:
current_clan = "отсутствует"
else:
await cur.execute("SELECT name FROM clans WHERE owner= %s", (user["clan"],))
clan_data = await cur.fetchone()
current_clan = clan_data["name"] if clan_data else "нет"
user_name = message.reply_to_message.from_user.first_name if message.reply_to_message else f"@{username}"
link = hlink(user_name, f'tg://user?id={user["id"]}')
"""profile_result = (
f"👤 {hlink(user_name, f'tg://user?id={user["id"]}')}"
f"\n<b>Профиль</b> пользователя {hbold(user['name'])}: \n"
f"\n🏰 Клан: {hbold(current_clan)}"
f"\n🏷 Префикс: {hbold(user['tag'])}"
f"\n📇 Псевдоним: {hbold(user['name'])}"
f"\n🆔 ID: {user['id']}"
f"\n💵 Баланс: {format_num(user['cash'])}$"
f"\n💳 ECoins: {format_num(user['bitcoins'])}₠"
f"\n🖥 Видеокарты: {user['videocards']} шт."
f"\n🪪 Пропуск: {vip_rangs[user['isvip']]}"
)"""
profile_result = profile_text(hlink(user_name, f'tg://user?id={user["id"]}'), hbold, user, current_clan)
invite_keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[InlineKeyboardButton(text="✉️ Пригласить в клан", callback_data=f"clan_invite_{user['id']}")]
] if user["clan"] == 0 else [
[InlineKeyboardButton(text=f"🏰 {current_clan}", callback_data=f'clan_show_info_{user["clan"]}')]
]
)
await bot.edit_message_text(
profile_result,
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="HTML",
reply_markup=invite_keyboard
)
except Exception as e:
await bot.edit_message_text(
f'❌ Произошла ошибка!\n{e}',
chat_id=load.chat.id,
message_id=load.message_id,
)
await logf(e)
@dp.message(F.text.regexp(r'(?i)^(\/clans(?:@[\w]+)?|кланы)(\s|$)', flags=IGNORECASE))
@with_db(True)
async def top_clans(cur: Cursor, load: Message, message: Message):
try:
assert message.from_user is not None
user_id = message.from_user.id
user_name = message.from_user.first_name
if await check_flood_wait(user_id):
await bot.edit_message_text(
f'🚫 <a href="tg://user?id={user_id}">{escape(user_name)}</a>, Вы отправляете слишком много сообщений. Пожалуйста, подождите немного.',
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="HTML"
)
await asleep(3)
await bot.delete_message(load.chat.id, load.message_id)
return
await cur.execute("SELECT name, money, type, owner FROM clans ORDER BY money DESC LIMIT 10")
clans_row = await cur.fetchall()
keyboard = clans_keyboard(clans_row, InlineKeyboardButton)
await bot.edit_message_text(
clans_text(),
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="HTML",
reply_markup=InlineKeyboardMarkup(
inline_keyboard=keyboard
)
)
except Exception as e:
await bot.edit_message_text(
f'❌ Произошла ошибка!\n{e}',
chat_id=load.chat.id,
message_id=load.message_id,
)
await logf(e)
@dp.message(F.text.regexp(r'(?i)^(\/clan(?:@[\w]+)?|клан|мой клан)(\s|$)', flags=IGNORECASE))
@with_db(True)
async def clan(cur: Cursor, load: Message, message: Message):
try:
assert message.from_user is not None
user_id = message.from_user.id
user_name = message.from_user.first_name
if await check_flood_wait(user_id):
await bot.edit_message_text(
f'🚫 <a href="tg://user?id={user_id}">{escape(user_name)}</a>, Вы отправляете слишком много сообщений. Пожалуйста, подождите немного.',
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="HTML"
)
await asleep(3)
await bot.delete_message(load.chat.id, load.message_id)
return
if not await check_account(cur, message):
return
await cur.execute("SELECT clan FROM users WHERE id = %s", (message.from_user.id,))
user = await cur.fetchone()
await cur.execute("SELECT name, id FROM users WHERE id = %s", (user["clan"],))
owner_row = await cur.fetchone()
await cur.execute("SELECT * FROM clans WHERE owner = %s", (user["clan"],))
clan_row = await cur.fetchone()
owner_link = hlink(owner_row["name"], f'tg://user?id={owner_row["id"]}')
members = await get_clan_members(clan_id=clan_row['owner'])
keyboard = clan_keyboard(clan_row, InlineKeyboardButton)
await bot.edit_message_text(
clan_text(clan_row, owner_link, members),
chat_id=load.chat.id,
message_id=load.message_id,
parse_mode="HTML",
reply_markup=InlineKeyboardMarkup(
inline_keyboard=keyboard
)
)
except Exception as e:
await bot.edit_message_text(
f'❌ Произошла ошибка!\n{e}',
chat_id=load.chat.id,
message_id=load.message_id,
)
await logf(e)
@dp.message(F.text.regexp(r'(?i)^(\/buyCrypto(?:@[\w]+)?|купить крипту|купить екоин)(\s|$)', flags=IGNORECASE))
@with_db(True)
async def buy_crypto(cur: Cursor, load: Message, message: Message):
try:
ecoins = int(message.text.split()[1])
except (ValueError, IndexError):
await bot.edit_message_text(
text="❌ Введенное вами значение не является числом!",
chat_id=load.chat.id,
message_id=load.message_id
)
return
try:
if ecoins <= 0:
await bot.edit_message_text(
text="❌ Нельзя продать число меньше или равное нулю!",
chat_id=load.chat.id,
message_id=load.message_id
)
return
bucks = await ecoin_to_bucks(ecoins)
user_id = message.from_user.id
await cur.execute("SELECT cash, bitcoins FROM users WHERE id=%s", (user_id,))
row = await cur.fetchone()
if not await check_account(cur, message):
return