forked from Iriskin0/Chat-Wars-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·813 lines (724 loc) · 34.4 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
#!/usr/bin/python3
# coding=utf-8
from pytg.sender import Sender
from pytg.receiver import Receiver
from pytg.utils import coroutine
from collections import deque
from time import time, sleep
from getopt import getopt
from datetime import datetime
import sys
import os
import re
import _thread
import random
import pytz
import configparser
pathname = os.path.dirname(sys.argv[0])
fullpath = os.path.abspath(pathname)
# username игрового бота
bot_username = 'ChatWarsBot'
# ваш username или username человека, который может отправлять запросы этому скрипту
admin_username = ''
# username бота и/или человека, которые будут отправлять приказы
order_usernames = ''
# имя замка
castle_name = 'blue'
captcha_bot = 'ChatWarsCaptchaBot'
stock_bot = 'PenguindrumStockBot'
trade_bot = 'ChatWarsTradeBot'
# путь к сокет файлу
socket_path = ''
# хост чтоб слушать telegram-cli
host = 'localhost'
# порт по которому слушать
port = 1338
# скидывание денег покупкой/продажей шлемов
donate_buying = False
# включить прокачку при левелапе
lvl_up = 'lvl_off'
# имя группы
group_name = ''
build_targed = '/build_hq'
baseconfig = configparser.SafeConfigParser()
config = configparser.SafeConfigParser()
# user_id бота, используется для поиска конфига
bot_user_id = ''
# читаем базовые конфиги из файла
baseconfig.read(fullpath + '/config.cfg')
if baseconfig.has_section('base'):
castle_name=baseconfig.get('base','castle_name')
admin_username=baseconfig.get('base','admin_username')
order_usernames=baseconfig.get('base','order_usernames')
host=baseconfig.get('base','host')
port=baseconfig.get('base','port')
socket_path=baseconfig.get('base','socket_path')
group_name=baseconfig.get('base','group_name')
opts, args = getopt(sys.argv[1:], 'a:o:c:s:h:p:g:b:l:n', ['admin=', 'order=', 'castle=', 'socket=', 'host=', 'port=',
'gold=', 'buy=', 'lvlup=', 'group_name='])
for opt, arg in opts:
if opt in ('-a', '--admin'):
admin_username = arg
elif opt in ('-o', '--order'):
order_usernames = arg.split(',')
elif opt in ('-c', '--castle'):
castle_name = arg
elif opt in ('-s', '--socket'):
socket_path = arg
elif opt in ('-h', '--host'):
host = arg
elif opt in ('-p', '--port'):
port = int(arg)
elif opt in ('-g', '--gold'):
gold_to_left = int(arg)
elif opt in ('-b', '--buy'):
donate_buying = bool(arg)
elif opt in ('-l', '--lvlup'):
lvl_up = arg
elif opt in ('-n', '--group_name'):
group_name = arg
# сохраняем базовые параметры в файл
if baseconfig.has_section('base'):
baseconfig.remove_section('base')
baseconfig.add_section('base')
baseconfig.set('base','castle_name',str(castle_name))
baseconfig.set('base','admin_username',str(admin_username))
baseconfig.set('base','order_usernames',str(order_usernames))
baseconfig.set('base','host',str(host))
baseconfig.set('base','port',str(port))
baseconfig.set('base','socket_path',str(socket_path))
baseconfig.set('base','group_name',str(group_name))
with open(fullpath + '/config.cfg','w+') as cfgfile:
baseconfig.write(cfgfile)
orders = {
'red': '🇮🇲',
'black': '🇬🇵',
'white': '🇨🇾',
'yellow': '🇻🇦',
'blue': '🇪🇺',
'mint': '🇲🇴',
'twilight': '🇰🇮',
'lesnoi_fort': '🌲Лесной форт',
'les': '🌲Лес',
'gorni_fort': '⛰Горный форт',
'gora': '⛰',
'cover': '🛡 Защита',
'attack': '⚔ Атака',
'cover_symbol': '🛡',
'hero': '🏅Герой',
'corovan': '/go',
'peshera': '🕸Пещера',
'quests': '🗺 Квесты',
'castle_menu': '🏰Замок',
'lavka': '🏚Лавка',
'snaraga': 'Снаряжение',
'shlem': 'Шлем',
'sell': 'Скупка предметов',
'lvl_def': '+1 🛡Защита',
'lvl_atk': '+1 ⚔Атака',
'lvl_off': 'Выключен'
}
captcha_answers = {
# блядь, кольцов, ну и хуйню же ты придумал
'watermelon_n_cherry': '🍉🍒',
'bread_n_cheese': '🍞🧀',
'cheese': '🧀',
'pizza': '🍕',
'hotdog': '🌭',
'eggplant_n_carrot': '🍆🥕',
'dog': '🐕',
'horse': '🐎',
'goat': '🐐',
'cat': '🐈',
'pig': '🐖',
'squirrel': '🐿'
}
builds = {
'stash': '/build_stash',
'sentries': '/build_sentries',
'monument': '/build_monument',
'warriors': '/build_warriors',
'teaparty': '/build_teaparty',
'hq': '/build_hq',
'gladiators': '/build_gladiators',
'wall': '/build_wall',
'ambar': '/build_ambar'
}
arena_cover = ['🛡головы', '🛡корпуса', '🛡ног']
arena_attack = ['🗡в голову', '🗡по корпусу', '🗡по ногам']
# поменять blue на red, black, white, yellow в зависимости от вашего замка
castle = orders[castle_name]
# текущий приказ на атаку/защиту, по умолчанию всегда защита, трогать не нужно
current_order = {'time': 0, 'order': castle}
# задаем получателя ответов бота: админ или группа
if group_name =='':
pref = '@'
msg_receiver = admin_username
else:
pref = ''
msg_receiver = group_name
sender = Sender(sock=socket_path) if socket_path else Sender(host=host,port=port)
action_list = deque([])
log_list = deque([], maxlen=30)
lt_arena = 0
get_info_diff = 360
hero_message_id = 0
last_captcha_id = 0
gold_to_left = 0
bot_enabled = True
arena_enabled = True
les_enabled = True
peshera_enabled = False
corovan_enabled = True
order_enabled = True
auto_def_enabled = True
donate_enabled = False
quest_fight_enabled = True
build_enabled = False
build_target = '/build_hq'
twinkstock_enabled = False
arena_running = False
arena_delay = False
arena_delay_day = -1
tz = pytz.timezone('Europe/Moscow')
@coroutine
def work_with_message(receiver):
global bot_user_id
while True:
msg = (yield)
try:
if msg['event'] == 'message' and 'text' in msg and msg['peer'] is not None:
if bot_user_id == '' and msg['sender']['username'] == bot_username:
bot_user_id = msg['receiver']['peer_id']
log('user_id найден: {0}'.format(bot_user_id))
config.read(fullpath + '/bot_cfg/' + str(bot_user_id) + '.cfg')
if config.has_section(str(bot_user_id)):
log('Конфиг найден')
read_config()
log('Конфиг загружен')
else:
log('Конфиг не найден')
write_config()
log('Новый конфиг создан')
# Проверяем наличие юзернейма, чтобы не вываливался Exception
if 'username' in msg['sender']:
parse_text(msg['text'], msg['sender']['username'], msg['id'])
except Exception as err:
log('Ошибка coroutine: {0}'.format(err))
def queue_worker():
global get_info_diff
global arena_delay
global arena_delay_day
global tz
lt_info = 0
# гребаная магия
print(sender.contacts_search(bot_username))
print(sender.contacts_search(captcha_bot))
print(sender.contacts_search(stock_bot))
print(sender.contacts_search(trade_bot))
sleep(3)
while True:
try:
if time() - lt_info > get_info_diff:
if arena_delay and arena_delay_day != datetime.now(tz).day:
arena_delay = False
lt_info = time()
get_info_diff = random.randint(900, 1200)
if bot_enabled:
send_msg('@', bot_username, orders['hero'])
continue
if len(action_list):
log('Отправляем ' + action_list[0])
send_msg('@', bot_username, action_list.popleft())
sleep_time = random.randint(2, 5)
sleep(sleep_time)
except Exception as err:
log('Ошибка очереди: {0}'.format(err))
def read_config():
global config
global bot_user_id
global bot_enabled
global arena_enabled
global les_enabled
global peshera_enabled
global corovan_enabled
global auto_def_enabled
global donate_enabled
global donate_buying
global lvl_up
global quest_fight_enabled
global build_enabled
global build_target
section=str(bot_user_id)
bot_enabled=config.getboolean(section, 'bot_enabled')
arena_enabled=config.getboolean(section, 'arena_enabled')
les_enabled=config.getboolean(section, 'les_enabled')
peshera_enabled=config.getboolean(section, 'peshera_enabled')
corovan_enabled=config.getboolean(section, 'corovan_enabled')
auto_def_enabled=config.getboolean(section, 'auto_def_enabled')
donate_enabled=config.getboolean(section, 'donate_enabled')
donate_buying=config.getboolean(section, 'donate_buying')
lvl_up=config.get(section, 'lvl_up')
quest_fight_enabled=config.getboolean(section, 'quest_fight_enabled')
build_enabled=config.getboolean(section, 'build_enabled')
build_target=config.get(section, 'build_target')
def write_config():
global config
global bot_user_id
global bot_enabled
global arena_enabled
global les_enabled
global peshera_enabled
global corovan_enabled
global auto_def_enabled
global donate_enabled
global donate_buying
global lvl_up
global quest_fight_enabled
global build_enabled
global build_target
section=str(bot_user_id)
if config.has_section(section):
config.remove_section(section)
config.add_section(section)
config.set(section, 'bot_enabled', str(bot_enabled))
config.set(section, 'arena_enabled', str(arena_enabled))
config.set(section, 'les_enabled', str(les_enabled))
config.set(section, 'peshera_enabled', str(peshera_enabled))
config.set(section, 'corovan_enabled', str(corovan_enabled))
config.set(section, 'auto_def_enabled', str(auto_def_enabled))
config.set(section, 'donate_enabled', str(donate_enabled))
config.set(section, 'donate_buying', str(donate_buying))
config.set(section, 'lvl_up', str(lvl_up))
config.set(section, 'quest_fight_enabled', str(quest_fight_enabled))
config.set(section, 'build_enabled', str(build_enabled))
config.set(section, 'build_target', str(build_target))
with open(fullpath + '/bot_cfg/' + str(bot_user_id) + '.cfg','w+') as configfile:
config.write(configfile)
def parse_text(text, username, message_id):
global lt_arena
global hero_message_id
global bot_enabled
global arena_enabled
global les_enabled
global peshera_enabled
global corovan_enabled
global order_enabled
global auto_def_enabled
global donate_enabled
global donate_buying
global last_captcha_id
global arena_delay
global arena_delay_day
global tz
global arena_running
global lvl_up
global pref
global msg_receiver
global quest_fight_enabled
global build_enabled
global build_target
global twinkstock_enabled
if bot_enabled and username == bot_username:
log('Получили сообщение от бота. Проверяем условия')
if text.find('🌟Поздравляем! Новый уровень!') != -1 and lvl_up != 'lvl_off':
log('получили уровень - {0}'.format(orders[lvl_up]))
action_list.append('/level_up')
action_list.append(orders[lvl_up])
elif "На выходе из замка охрана никого не пропускает" in text:
# send_msg('@', admin_username, "Командир, у нас проблемы с капчой! #captcha " + '|'.join(captcha_answers.keys()))
# fwd('@', admin_username, message_id)
action_list.clear()
bot_enabled = False
last_captcha_id = message_id
fwd('@', captcha_bot, message_id)
elif 'Не умничай!' in text or 'Ты долго думал, аж вспотел от напряжения' in text:
send_msg('@', admin_username, "Командир, у нас проблемы с капчой! #captcha " + '|'.join(captcha_answers.keys()))
bot_enabled = False
if last_captcha_id != 0:
fwd('@', admin_username, message_id)
else:
send_msg('@', admin_username, 'Капча не найдена?')
elif 'На сегодня ты уже своё отвоевал. Приходи завтра.' in text:
arena_delay = True
arena_delay_day = datetime.now(tz).day
log("Отдыхаем денек от арены")
arena_running = False
elif 'Ты пошел строить:' in text:
log("Ушли строить")
elif 'В казне недостаточно' in text:
log("Стройка не удалась, в замке нет денег")
elif corovan_enabled and text.find(' /go') != -1:
action_list.append(orders['corovan'])
elif text.find('Битва семи замков через') != -1:
hero_message_id = message_id
m = re.search('Битва семи замков через(?: ([0-9]+)ч){0,1}(?: ([0-9]+)){0,1}', text)
if not m.group(1):
if m.group(2) and int(m.group(2)) <= 59:
state = re.search('Состояние:\n(.*)', text).group(1)
if auto_def_enabled and time() - current_order['time'] > 3600 and 'Отдых' in state:
if donate_enabled:
gold = int(re.search('💰(-?[0-9]+)', text).group(1))
inv = re.search('🎒Рюкзак: ([0-9]+)/([0-9]+)', text)
log('Рюкзак: {0} / {1}'.format(inv.group(1),inv.group(2)))
if int(inv.group(1)) == int(inv.group(2)):
log('Полный рюкзак - Донат в лавку отключен')
donate_buying = False
if gold > gold_to_left:
if donate_buying:
log('Донат {0} золота в лавку'.format(gold-gold_to_left))
action_list.append(orders['castle_menu'])
action_list.append(orders['lavka'])
action_list.append(orders['shlem'])
while (gold-gold_to_left) >= 35:
gold -= 35
action_list.append('/buy_helmet2')
while (gold-gold_to_left) > 0:
gold -= 1
action_list.append('/buy_helmet1')
action_list.append('/sell_206')
else:
log('Донат {0} золота в казну замка'.format(gold-gold_to_left))
action_list.append('/donate {0}'.format(gold-gold_to_left))
update_order(castle)
return
log('Времени достаточно')
gold = int(re.search('💰(-?[0-9]+)', text).group(1))
endurance = int(re.search('Выносливость: ([0-9]+)', text).group(1))
log('Золото: {0}, выносливость: {1}'.format(gold, endurance))
inv = re.search('🎒Рюкзак: ([0-9]+)/([0-9]+)', text)
log('Рюкзак: {0} / {1}'.format(inv.group(1),inv.group(2)))
if text.find('🛌Отдых') == -1:
log('Чем-то занят, ждём')
else:
if text.find('🛌Отдых') != -1 and arena_running:
arena_running = False
if peshera_enabled and endurance >= 2:
if les_enabled:
action_list.append(orders['quests'])
action_list.append(random.choice([orders['peshera'], orders['les']]))
else:
action_list.append(orders['quests'])
action_list.append(orders['peshera'])
elif les_enabled and not peshera_enabled and endurance >= 1 and orders['les'] not in action_list:
action_list.append(orders['quests'])
action_list.append(orders['les'])
elif arena_enabled and not arena_delay and gold >= 5 and not arena_running:
curhour = datetime.now(tz).hour
if 9 <= curhour <= 23:
log('Включаем флаг - арена запущена')
arena_running = True
action_list.append(orders['castle_menu'])
action_list.append('📯Арена')
action_list.append('🔎Поиск соперника')
log('Топаем на арену')
else:
log('По часам не проходим на арену. Сейчас ' + str(curhour) + ' часов')
if build_enabled:
log('Пойдем строить')
action_list.append(orders['castle_menu'])
action_list.append('🏘Постройки')
action_list.append('🚧Стройка')
action_list.append(build_target)
elif build_enabled:
log('Пойдем строить')
action_list.append(orders['castle_menu'])
action_list.append('🏘Постройки')
action_list.append('🚧Стройка')
action_list.append(build_target)
elif arena_enabled and text.find('выбери точку атаки и точку защиты') != -1:
arena_running = True #на случай, если арена запущена руками
lt_arena = time()
attack_chosen = arena_attack[random.randint(0, 2)]
cover_chosen = arena_cover[random.randint(0, 2)]
log('Атака: {0}, Защита: {1}'.format(attack_chosen, cover_chosen))
sleep(random.randint(2,6))
if random.randint(0,1):
action_list.append(attack_chosen)
action_list.append(cover_chosen)
else:
action_list.append(cover_chosen)
action_list.append(attack_chosen)
elif text.find('Победил воин') != -1 or text.find('Ничья') != -1:
log('Выключаем флаг - арена закончилась')
arena_running = False
elif quest_fight_enabled and text.find('/fight') != -1:
c = re.search('(\/fight.*)', text).group(1)
action_list.append(c)
fwd(pref, msg_receiver, message_id)
elif username == 'ChatWarsCaptchaBot':
if len(text) <= 4 and text in captcha_answers.values():
sleep(3)
action_list.append(text)
bot_enabled = True
elif username == 'ChatWarsTradeBot' and twinkstock_enabled:
if text.find('Твой склад с материалами') != -1:
stock_id = message_id
fwd('@','PenguindrumStockBot',stock_id)
twinkstock_enabled = False
send_msg(pref, msg_receiver, 'Сток обновлен')
else:
if bot_enabled and order_enabled and username in order_usernames:
if text.find(orders['red']) != -1:
update_order(orders['red'])
elif text.find(orders['black']) != -1:
update_order(orders['black'])
elif text.find(orders['white']) != -1:
update_order(orders['white'])
elif text.find(orders['yellow']) != -1:
update_order(orders['yellow'])
elif text.find(orders['blue']) != -1:
update_order(orders['blue'])
elif text.find(orders['mint']) != -1:
update_order(orders['mint'])
elif text.find(orders['twilight']) != -1:
update_order(orders['twilight'])
elif text.find('🌲') != -1:
update_order(orders['lesnoi_fort'])
elif text.find('⛰') != -1:
update_order(orders['gorni_fort'])
elif text.find('🛡') != -1:
update_order(castle)
elif quest_fight_enabled and text.find('/fight') != -1:
c = re.search('(\/fight.*)', text).group(1)
action_list.append(c)
# send_msg(pref, admin_username, 'Получили команду ' + current_order['order'] + ' от ' + username)
if username == admin_username:
if text == '#help':
send_msg(pref, msg_receiver, '\n'.join([
'#enable_bot - Включить бота',
'#disable_bot - Выключить бота',
'#enable_arena - Включить арену',
'#disable_arena - Выключить арену',
'#enable_les - Включить лес',
'#disable_les - Выключить лес',
'#enable_peshera - Включить пещеры',
'#disable_peshera - Выключить пещеры',
'#enable_corovan - Включить корован',
'#disable_corovan - Выключить корован',
'#enable_order - Включить приказы',
'#disable_order - Выключить приказы',
'#enable_auto_def - Включить авто деф',
'#disable_auto_def - Выключить авто деф',
'#enable_donate - Включить донат',
'#disable_donate - Выключить донат',
'#enable_quest_fight - Включить битву во время квестов',
'#disable_quest_fight - Выключить битву во время квестов',
'#enable_buy - Включить донат в лавку вместо казны',
'#disable_buy - Вылючить донат в лавку вместо казны',
"#lvl_atk - качать атаку",
"#lvl_def - качать защиту",
"#lvl_off - ничего не качать",
'#status - Получить статус',
'#hero - Получить информацию о герое',
'#push_order - Добавить приказ ({0})'.format(','.join(orders)),
'#order - Дебаг, последняя команда защиты/атаки замка',
'#log - Дебаг, последние 30 сообщений из лога',
'#time - Дебаг, текущее время',
'#lt_arena - Дебаг, последняя битва на арене',
'#get_info_diff - Дебаг, последняя разница между запросами информации о герое',
'#ping - Дебаг, проверить жив ли бот',
'#enable_build - Включить постройки',
'#disable_build - Выключить постройки',
'#build_target - указать цель постройки ({0})'.format(','.join(builds)),
'#stock - Обновить стоки',
]))
# Вкл/выкл бота
elif text == '#enable_bot':
bot_enabled = True
write_config()
send_msg(pref, msg_receiver, 'Бот успешно включен')
elif text == '#disable_bot':
bot_enabled = False
write_config()
send_msg(pref, msg_receiver, 'Бот успешно выключен')
# отправка стока
elif text == '#stock':
twinkstock_enabled = True
send_msg('@','ChatWarsTradeBot','/start')
# Вкл/выкл арены
elif text == '#enable_arena':
arena_enabled = True
write_config()
send_msg(pref, msg_receiver, 'Арена успешно включена')
elif text == '#disable_arena':
arena_enabled = False
write_config()
send_msg(pref, msg_receiver, 'Арена успешно выключена')
# Вкл/выкл леса
elif text == '#enable_les':
les_enabled = True
write_config()
send_msg(pref, msg_receiver, 'Лес успешно включен')
elif text == '#disable_les':
les_enabled = False
write_config()
send_msg(pref, msg_receiver, 'Лес успешно выключен')
# Вкл/выкл пещеры
elif text == '#enable_peshera':
peshera_enabled = True
write_config()
send_msg(pref, msg_receiver, 'Пещеры успешно включены')
elif text == '#disable_peshera':
peshera_enabled = False
write_config()
send_msg(pref, msg_receiver, 'Пещеры успешно выключены')
# Вкл/выкл корована
elif text == '#enable_corovan':
corovan_enabled = True
write_config()
send_msg(pref, msg_receiver, 'Корованы успешно включены')
elif text == '#disable_corovan':
corovan_enabled = False
write_config()
send_msg(pref, msg_receiver, 'Корованы успешно выключены')
# Вкл/выкл команд
elif text == '#enable_order':
order_enabled = True
send_msg(pref, msg_receiver, 'Приказы успешно включены')
elif text == '#disable_order':
order_enabled = False
send_msg(pref, msg_receiver, 'Приказы успешно выключены')
# Вкл/выкл авто деф
elif text == '#enable_auto_def':
auto_def_enabled = True
write_config()
send_msg(pref, msg_receiver, 'Авто деф успешно включен')
elif text == '#disable_auto_def':
auto_def_enabled = False
write_config()
send_msg(pref, msg_receiver, 'Авто деф успешно выключен')
# Вкл/выкл авто донат
elif text == '#enable_donate':
donate_enabled = True
write_config()
send_msg(pref, msg_receiver, 'Донат успешно включен')
elif text == '#disable_donate':
donate_enabled = False
write_config()
send_msg(pref, msg_receiver, 'Донат успешно выключен')
# Вкл/выкл донат в лавку
elif text == '#enable_buy':
donate_buying = True
write_config()
send_msg(pref, msg_receiver, 'Донат в лавку успешно включен')
elif text == '#disable_buy':
donate_buying = False
write_config()
send_msg(pref, msg_receiver, 'Донат в лавку успешно выключен')
# Вкл/выкл битву по время квеста
elif text == '#enable_quest_fight':
quest_fight_enabled = True
write_config()
send_msg(pref, msg_receiver, 'Битва включена')
elif text == '#disable_quest_fight':
quest_fight_enabled = False
write_config()
send_msg(pref, msg_receiver, 'Битва отключена')
# что качать при левелапе
elif text == '#lvl_atk':
lvl_up = 'lvl_atk'
write_config()
send_msg(pref, msg_receiver, 'Качаем атаку')
elif text == '#lvl_def':
lvl_up = 'lvl_def'
write_config()
send_msg(pref, msg_receiver, 'Качаем защиту')
elif text == '#lvl_off':
lvl_up = 'lvl_off'
write_config()
send_msg(pref, msg_receiver, 'Не качаем ничего')
# Получить статус
elif text == '#status':
send_msg(pref, msg_receiver, '\n'.join([
'🤖Бот включен: {0}',
'📯Арена включена: {1}',
'🔎Сейчас на арене: {2}',
'🌲Лес включен: {3}',
'🕸Пещеры включены: {4}',
'🐫Корованы включены: {5}',
'🇪🇺Приказы включены: {6}',
'🛡Авто деф включен: {7}',
'💰Донат включен: {8}',
'🏚Донат в лавку вместо казны: {9}',
'🌟Левелап: {10}',
'🏘Постройка включена: {11}',
'🚧Цель постройки: {12}',
]).format(bot_enabled, arena_enabled, arena_running, les_enabled, peshera_enabled, corovan_enabled, order_enabled,
auto_def_enabled, donate_enabled, donate_buying,orders[lvl_up],build_enabled,build_target))
# Информация о герое
elif text == '#hero':
if hero_message_id == 0:
send_msg(pref, msg_receiver, 'Информация о герое пока еще недоступна')
else:
fwd(pref, msg_receiver, hero_message_id)
# Получить лог
elif text == '#log':
send_msg(pref, msg_receiver, '\n'.join(log_list))
log_list.clear()
elif text == '#lt_arena':
send_msg(pref, msg_receiver, str(lt_arena))
elif text == '#order':
text_date = datetime.fromtimestamp(current_order['time']).strftime('%Y-%m-%d %H:%M:%S')
send_msg(pref, msg_receiver, current_order['order'] + ' ' + text_date)
elif text == '#time':
text_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
send_msg(pref, msg_receiver, text_date)
elif text == '#ping':
send_msg(pref, msg_receiver, '#pong')
elif text == '#get_info_diff':
send_msg(pref, msg_receiver, str(get_info_diff))
elif text.startswith('#push_order'):
command = text.split(' ')[1]
if command in orders:
update_order(orders[command])
send_msg(pref, msg_receiver, 'Команда ' + command + ' применена')
else:
send_msg(pref, msg_receiver, 'Команда ' + command + ' не распознана')
elif text.startswith('#build_target'):
command = text.split(' ')[1]
if command in builds:
build_target = builds[command]
send_msg(pref, msg_receiver, 'Постройка ' + builds[command] + ' установлена')
write_config()
else:
send_msg(pref, msg_receiver, 'Постройка ' + command + ' не распознана')
elif text.startswith('#captcha'):
command = text.split(' ')[1]
if command in captcha_answers:
action_list.append(captcha_answers[command])
bot_enabled = True
send_msg('@', admin_username, 'Команда ' + command + ' применена')
else:
send_msg('@', admin_username, 'Команда ' + command + ' не распознана')
# Вкл/выкл построек
elif text == '#enable_build':
build_enabled = True
write_config()
send_msg(pref, msg_receiver, 'Постройка успешно включена')
elif text == '#disable_build':
build_enabled = False
write_config()
send_msg(pref, msg_receiver, 'Постройка успешно выключена')
def send_msg(pref, to, message):
sender.send_msg(pref + to, message)
def fwd(pref, to, message_id):
sender.fwd(pref + to, message_id)
def update_order(order):
current_order['order'] = order
current_order['time'] = time()
if order == castle:
action_list.append(orders['cover'])
else:
action_list.append(orders['attack'])
action_list.append(order)
def log(text):
message = '{0:%Y-%m-%d+ %H:%M:%S}'.format(datetime.now()) + ' ' + text
print(message)
log_list.append(message)
if __name__ == '__main__':
receiver = Receiver(sock=socket_path) if socket_path else Receiver(port=port)
receiver.start() # start the Connector.
_thread.start_new_thread(queue_worker, ())
receiver.message(work_with_message(receiver))
receiver.stop()