This repository has been archived by the owner on Nov 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathmain.py
executable file
·456 lines (345 loc) · 11.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
#!/usr/bin/python3
import config
import statistics
from telegram.ext.dispatcher import run_async
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram.ext import Job
from collections import deque
import tornamentmanager
import databasemanager
import usermanager
import telegram
import logging
import os
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger('rg')
question_filename = 'question.int'
question_yes = 388
question_no = 78
asked = [ ]
queue = deque([])
updater = Updater(config.TELEGRAM_TOKEN)
def queue_reply(bot, job):
try:
message = queue.popleft()
if message:
c_id, bot, txt, buttons, photo, repeat = message
_reply(c_id, bot, txt, buttons, photo, repeat)
except:
pass
@run_async
def _reply(c_id, bot, txt, buttons=None, photo=None, repeat=True):
if c_id == 0:
return
if buttons:
custom_keyboard = [ ]
for b in buttons:
if isinstance(b, list):
custom_keyboard.append(b)
else:
custom_keyboard.append([b])
reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, one_time_keyboard=True)
try:
bot.sendMessage(c_id, text=txt, reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN)
except Exception as e:
if not repeat:
raise e
if '429' in str(e):
send_job = Job(reply_job, 1, repeat=False, context=(c_id, bot, txt, buttons, photo))
updater.job_queue.put(send_job)
else:
raise e
elif len(txt) > 0:
bot.sendMessage(c_id, text=txt, parse_mode=telegram.ParseMode.MARKDOWN)
if photo:
bot.sendSticker(c_id, sticker=photo)
def reply_job(bot, job):
c_id, bot, txt, buttons, photo = job.context
reply(c_id, bot, txt, buttons, photo, repeat=False)
def reply(c_id, bot, txt, buttons=None, photo=None, repeat=True):
if c_id == 0:
return
queue.append([ c_id, bot, txt, buttons, photo, repeat ])
def start(bot, update):
c_id = update.message.chat_id
global msg, image, buttons
msg = ''
image = None
buttons = None
statistics.track(c_id, update.message, 'Start')
def rep(txt, btns=None, photo=None):
global msg, image, buttons
if len(msg) + len(txt) + 2 >= 4096:
reply(c_id, bot, msg, buttons, image)
msg = ''
image = None
buttons = None
msg += '\n\n'
msg += txt
if btns:
buttons = btns
if photo:
image = photo
username = ''
try:
username = bot.getChat(uid)['username']
except:
pass
usermanager.new_user(c_id, username if len(username) > 0 else None, rep)
if len(msg) > 0 or image:
reply(c_id, bot, msg, buttons, image)
def setname(bot, update):
txt = update.message.text
if len(txt) > len('/setname'):
statistics.track(update.message.chat_id, update.message, 'Setname')
name = txt[len('/setname')+1:]
usermanager.setname(update.message.chat_id, name)
bot.sendMessage(update.message.chat_id, text='Ну хорошо')
def debug_print(bot, update):
inf = usermanager.debug_info(update.message.chat_id)
bot.sendMessage(update.message.chat_id, text=inf)
def room(bot, update):
c_id = update.message.chat_id
if str(c_id) in config.MODERS_IDS:
cmd, room_type, name = update.message.text.split()
usermanager.open_room(c_id, lambda *a, **kw: reply(c_id, bot, *a, **kw), room_type, name)
else:
bot.sendMessage(update.message.chat_id, text='NO.')
def give(bot, update):
if str(update.message.chat_id) in config.MODERS_IDS:
cmd, item_type, name = update.message.text.split()
usermanager.give_item(update.message.chat_id, item_type, name)
else:
bot.sendMessage(update.message.chat_id, text='NO.')
def gold(bot, update):
if str(update.message.chat_id) in config.MODERS_IDS:
cmd, integer = update.message.text.split()
integer = int(integer)
user = usermanager.get_user(update.message.chat_id)
user.gold += integer
usermanager.save_user(user)
else:
bot.sendMessage(update.message.chat_id, text='NO.')
def pet(bot, update):
if str(update.message.chat_id) in config.MODERS_IDS:
cmd, pet, name = update.message.text.split()
usermanager.new_pet(update.message.chat_id, pet, name)
else:
bot.sendMessage(update.message.chat_id, text='NO.')
@run_async
def notify(bot, update):
if str(update.message.chat_id) in config.ADMINS_IDS:
msg = update.message.text[len('/notify'):]
logger.info(msg)
for user_id in usermanager.get_telegram_users():
try:
bot.sendMessage(user_id, text=msg)
except:
logger.info('Couldn\'t send message to {0}'.format(user_id))
else:
bot.sendMessage(update.message.chat_id, text='NO.')
def save_question():
with open(question_filename, 'w') as f:
f.write('{0} {1}\n'.format(question_yes, question_no))
f.write(' '.join(asked))
def zero(bot, update):
global question_yes, question_no, asked
if str(update.message.chat_id) in config.ADMINS_IDS:
question_yes = 0
question_no = 0
asked = [ ]
save_question()
else:
bot.sendMessage(update.message.chat_id, text='NO.')
def question_status(bot, update):
msg ='Да: {0}\nНет: {1}'.format(question_yes, question_no)
bot.sendMessage(update.message.chat_id, text=msg)
def yes(bot, update):
global question_yes, asked
uid = str(update.message.chat_id)
if uid in asked:
bot.sendMessage(update.message.chat_id, text='Только 1 раз ;)')
else:
question_yes += 1
bot.sendMessage(update.message.chat_id, text='Голос учтен. Чтобы посмотреть результат, используй /question_status')
asked.append(uid)
save_question()
def no(bot, update):
global question_no, asked
uid = str(update.message.chat_id)
if uid in asked:
bot.sendMessage(update.message.chat_id, text='Только 1 раз ;)')
else:
question_no += 1
bot.sendMessage(update.message.chat_id, text='Голос учтен. Чтобы посмотреть результат, используй /question_status')
asked.append(uid)
save_question()
def update_tornament(bot, job):
global uid, msg, image, buttons
uid = 0
msg = ''
image = None
buttons = None
def rep(c_id, txt, btns=None, photo=None):
global uid, msg, image, buttons
if uid != 0 and c_id != uid:
reply(uid, bot, msg, buttons, image)
msg = ''
image = None
buttons = None
uid = c_id
msg += '\n\n'
msg += txt
if btns:
buttons = btns
if photo:
image = photo
tornamentmanager.update(rep)
if len(msg) > 0 or image:
reply(uid, bot, msg, buttons, image)
@run_async
def divine_intervention(bot, job):
logger.info('Divine intervention!')
for uid in usermanager.get_telegram_users():
global msg, image, buttons
msg = ''
image = None
buttons = None
def rep(txt, btns=None, photo=None):
global msg, image, buttons
if len(msg) + len(txt) + 2 >= 4096:
reply(uid, bot, msg, buttons, image)
msg = ''
image = None
buttons = None
msg += '\n\n'
msg += txt
if btns:
buttons = btns
if photo:
image = photo
usermanager.divine_intervention(uid, rep)
if len(msg) > 0 or image:
reply(uid, bot, msg, buttons, image)
def msg(bot, update):
c_id = update.message.chat_id
statistics.track(c_id, update.message)
global msg, image, buttons
msg = ''
image = None
buttons = None
def rep(txt, btns=None, photo=None):
global msg, image, buttons
if len(msg) + len(txt) + 2 >= 4096:
_reply(c_id, bot, msg, buttons, image)
msg = ''
image = None
buttons = None
msg += '\n\n'
msg += txt
if btns:
buttons = btns
if photo:
image = photo
usermanager.message(c_id, rep, update.message.text)
if len(msg) > 0 or image:
global updater
_reply(c_id, bot, msg, buttons, image)
@run_async
def leaderboard(bot, update):
c_id = update.message.chat_id
lb = databasemanager.ROOMS_TABLE
cnt = 10
if len(update.message.text.split(' ')) >= 2:
lb = update.message.text.split(' ')[1]
if len(update.message.text.split(' ')) >= 3:
try:
cnt_ = int(update.message.text.split(' ')[2])
if cnt_ > 0:
cnt = cnt_
except:
pass
res = databasemanager.get_leaderboard(lb, count=cnt)
msg = ''
if lb == 'death':
for i, r in enumerate(res):
msg += '{0}. {1}: {2}\n'.format(i + 1, r['death_reason'], round(r['count']))
else:
for i, r in enumerate(res):
uid = r['uid']
name = r['name']
score = round(r['score'])
username = bot.getChat(uid)['username']
death_reason = None
if 'death_reason' in r:
death_reason = r['death_reason']
table_name = "{0}".format(name)
if len(username) > 0:
table_name += ' (@{0})'.format(username)
msg += '{0}. {1}: {2}'.format(i + 1, table_name, score)
if death_reason is not None:
msg += '\nПричина смерти: ' + death_reason
msg += '\n'
bot.sendMessage(update.message.chat_id, text=msg)
def stop(bot, update):
statistics.track(update.message.chat_id, update.message, 'Stop')
usermanager.delete(update.message.chat_id)
def cesar(bot, update):
v = databasemanager.get_variable('ces', def_val=True)
databasemanager.set_variable('ces', not v)
@run_async
def rate(bot, update):
c_id = update.message.chat_id
link = statistics.get_link(c_id)
bot.sendMessage(update.message.chat_id, text='Держи ссылку ;)\n\n{0}'.format(link))
def error_callback(bot, update, error):
error_msg = 'User "%s" had error "%s"' % (update.message.chat_id, error)
if '429' in str(error):
logger.warn('429!')
else:
logger.warn(error_msg)
msg = 'Ошибка внутри сервера. Если это мешает играть, сообщите @yegorf1'
bot.sendMessage(update.message.chat_id, text=msg)
bot.sendMessage(update.message.chat_id,
text='```text\n{0}\n```'.format(error_msg),
parse_mode=telegram.ParseMode.MARKDOWN)
def main():
if os.path.isfile(question_filename):
with open(question_filename, 'r') as f:
question_yes, question_no = map(int, f.readline().split())
asked = f.readline().split()
if not os.path.isdir(config.USERS_PATH):
logger.info('Creating users directory')
os.makedirs(config.USERS_PATH)
logger.info('Creating Updater...')
updater.dispatcher.add_handler(CommandHandler('leaderboard', leaderboard))
updater.dispatcher.add_handler(CommandHandler('setname', setname))
updater.dispatcher.add_handler(CommandHandler('notify', notify))
updater.dispatcher.add_handler(CommandHandler('debug', debug_print))
updater.dispatcher.add_handler(CommandHandler('cesar', cesar))
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CommandHandler('rate', rate))
updater.dispatcher.add_handler(CommandHandler('stop', stop))
updater.dispatcher.add_handler(CommandHandler('room', room))
updater.dispatcher.add_handler(CommandHandler('give', give))
updater.dispatcher.add_handler(CommandHandler('gold', gold))
updater.dispatcher.add_handler(CommandHandler('pet', pet))
updater.dispatcher.add_handler(CommandHandler('question_status', question_status))
updater.dispatcher.add_handler(CommandHandler('zero', zero))
updater.dispatcher.add_handler(CommandHandler('yes', yes))
updater.dispatcher.add_handler(CommandHandler('no', no))
updater.dispatcher.add_handler(MessageHandler(False, msg))
updater.dispatcher.add_error_handler(error_callback)
intervention_job = Job(divine_intervention, 3 * 60 * 60.0)
update_tornament_job = Job(update_tornament, 10.0)
updater.job_queue.put(intervention_job)
updater.job_queue.put(update_tornament_job)
queue_job = Job(queue_reply, 0.035)
updater.job_queue.put(queue_job)
logger.info('Starting polling...')
updater.start_polling()
logger.info('Bot now officially started!')
updater.idle()
if __name__ == '__main__':
main()