-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
435 lines (332 loc) · 12.3 KB
/
bot.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
"""
All the work of the bot happens in this file.
The business logic of tower checking is not defined here, only the
interface of interaction with the bot.
"""
import asyncio
from functools import wraps, partial
from typing import Coroutine, Callable
from telegram import Update, Message, Bot
from telegram.constants import ParseMode
from telegram.ext.filters import BaseFilter, MessageFilter, ChatType, COMMAND
from telegram.ext import (
Application,
CommandHandler,
MessageHandler,
CallbackContext,
)
from messages import *
from config import Args, Params
from observer import Observer
from periodic import everyday_cron, add_action, is_same_day_today, is_next_day_today
UNTRACEABLE_CHATS = (Args.NULL_CHAT, )
class NotTrackFilter(MessageFilter):
"""
A filter that ignores messages that come in the standard untraceable
chats.
"""
def filter(self, message: Message) -> bool:
return message.chat.id not in UNTRACEABLE_CHATS
class CommandWithName(MessageFilter):
"""
The command should only be with the bot`s name:
/command@name_bot
"""
def filter(self, message: Message) -> bool:
command = message.text.splitlines()[0].split(" ")[0]
return command.endswith(Args.BOT_USERNAME)
class NewMessage(BaseFilter):
"""
Filter for only new messages (bicycle?)
"""
def check_update(self, update: Update):
return bool(update.message)
NOTRACK_FILTER = NotTrackFilter()
COMMAND_WITH_NAME = CommandWithName()
NEW_MESSAGE = NewMessage()
def private_checker(func: Callable):
"""
Decorator, which allows the execution of the function only in private
messages. Otherwise, the stub "refer to private messages" will be
returned.
"""
@wraps(func)
async def wrapped(update: Update, context: CallbackContext):
if ChatType.PRIVATE.filter(update.message):
return await func(update, context)
return await update.effective_chat.send_message(MSG_only_for_private)
return wrapped
def group_checker(func: Callable):
"""
A decorator that allows the execution of the function only in groups.
Otherwise, a "this works only in groups" stub will be returned.
"""
@wraps(func)
async def wrapped(update: Update, context: CallbackContext):
if ChatType.GROUPS.filter(update.message):
return await func(update, context)
return await update.effective_chat.send_message(MSG_only_for_groups)
return wrapped
def wednesday_checker(func: Callable):
"""
Decorator, which allows the execution of the function only on
Wednesdays. Otherwise, the "this only works on Wednesdays" stub will
return.
It is directly related to the `WEDNESDAY_MODE` parameter (if it is
inactive, the decorator is just ignored).
"""
if not Params.ONEDAY_MODE:
return func
@wraps(func)
async def wrapped(update: Update, context: CallbackContext):
# `observer.is_enable == True` only on Wednesdays
if not observer.is_enable:
return await update.effective_chat.send_message(MSG_not_wednesday)
return await func(update, context)
return wrapped
def ignore_checker(func: Callable):
"""
Decorator, which ignores all messages in chats with the observer
disabled.
"""
@wraps(func)
async def wrapped(update: Update, context: CallbackContext):
if not observer.is_looked(update.effective_chat.id):
return
if observer.get(update.effective_chat.id).is_disable:
return
return await func(update, context)
return wrapped
# === handlers =========================================================
@private_checker
async def start(update: Update, context: CallbackContext):
"""
Standard welcome for the bot.
"""
await update.effective_chat.send_message(
MSG_start,
parse_mode=ParseMode.HTML,
)
@private_checker
async def help(update: Update, context: CallbackContext):
"""
Standard help for the bot.
"""
await update.effective_chat.send_message(
MSG_help,
parse_mode=ParseMode.HTML,
disable_web_page_preview=True,
)
async def get_ords(update: Update, context: CallbackContext):
"""
Hidden command for convenient letter checking.
Returns ASCII codes of non-space letters from the received message.
"""
letters = update.message.text.removeprefix("/get_ords")
letters = letters.replace("\n", "").replace("\t", "").replace(" ", "")
if not letters:
return await update.effective_chat.send_message(MSG_get_ords_no_text)
if len(letters) > 30:
return await update.effective_chat.send_message(MSG_get_ords_too_long)
ords = "\n".join(
f"{let} : {ord(let)}"
for let in letters
)
await update.effective_chat.send_message(ords)
@group_checker
@wednesday_checker
async def enable(update: Update, context: CallbackContext):
"""
Activates the bot in the groups where it was called.
If the bot has already been turned off today, it cannot be turned on
again.
"""
chat_id = update.effective_chat.id
if observer.is_looked(chat_id):
msg = (
MSG_enable_but_disable
if observer.get(chat_id).is_disable else
MSG_enable_already
)
return await update.effective_chat.send_message(msg)
observer.add(chat_id)
await update.effective_chat.send_message(MSG_enable)
@group_checker
@wednesday_checker
async def disable(update: Update, context: CallbackContext):
"""
Turns off the bot in the selected groups.
You can not turn it back on the same day!
"""
chat_id = update.effective_chat.id
if not observer.is_looked(chat_id):
return await update.effective_chat.send_message(MSG_disable_not_enable)
if observer.get(chat_id).is_disable:
return await update.effective_chat.send_message(MSG_disable_already)
observer.get(chat_id).set(is_disable=True)
await update.effective_chat.send_message(MSG_disable)
async def dont_understand(update: Update, context: CallbackContext):
"""
Stub to all messages.
"""
await update.effective_chat.send_message(MSG_dont_understand)
@ignore_checker
async def standard_message(update: Update, context: CallbackContext):
"""
Executes all tower observation logic.
The handler is used only for groups that have tower observation
enabled.
The algorithm is as follows:
- the message is checked if it is another letter or not
- the tower has fallen, it is notified
- otherwise the letter is added to the tower
- if the tower is assembled, it is notified
- if it is time to automatically crash the tower, then it crashes the tower
"""
chat = observer.get(update.effective_chat.id)
# check for a letter
# code will be returned if the trigger is not the expected letter
code = (await chat.tower.check_correct(update))
if code is not None:
# if the trigger is not important or there are no letters anyway,
# there is no reason to do anything
is_scip_update = (code == "ignore") or (len(chat.tower) == 0)
if is_scip_update:
return
# if the tower is small or the message needs to be ignored,
# there is no need to notify the fall
is_show_msg = len(chat.tower) >= Params.MINIMAL_CHECK_LEN
# nullify the tower and notifying of this
chat.nullify()
if is_show_msg:
incorrect_codes = {
"fall": MSG_fall,
"fall_edited": MSG_fall_edited,
"fall_repetition": MSG_fall_repetition,
}
return await update.effective_chat.send_message(incorrect_codes[code])
else:
return
# add a letter to the tower
letter = (
update.message.text,
update.message.from_user.id,
update.message.id,
)
chat.add_letter(letter)
if chat.tower.is_completed:
# if the tower is seemingly complete, extra checks still need to be done
code_completion = (await chat.tower.check_after_completion(update))
if code_completion is not None:
# it turns out the tower cracked somewhere during the building
incorrect_codes = {
"fail_similar": MSG_fail_similar,
"fall_deleted": MSG_fall_deleted,
}
return await update.effective_chat.send_message(incorrect_codes[code_completion])
# if the tower is built, then it's a win
chat.nullify()
chat.set(is_built=True)
return await update.effective_chat.send_message(
MSG_tower_success,
parse_mode="html"
)
# if the tower needs to be crashed, then crash it
if chat.is_need_to_crash:
msg = MSG_crashes[chat.crash_type]
chat.nullify()
chat.set(crash_times=chat.crash_times+1)
return await update.effective_chat.send_message(msg)
# === cron =============================================================
async def only_wednesday_work_switch():
"""
Turns the bot on if it's Wednesday and off if it's Thursday.
"""
if is_same_day_today():
observer.is_enable = True
elif is_next_day_today():
observer.is_enable = False
end_day_message = (
MSG_wednesday_end
if Params.ONEDAY_MODE else
MSG_day_end
)
async def send_end_day_message():
"""
Notifies all chats that the day is over and clears all towers
information.
"""
if not observer.is_enable:
# if the bot is disabled, nothing needs to do
return
send_msg_coros = [
bot.send_message(chat_id, end_day_message)
for chat_id in observer.all_chats
]
await asyncio.gather(*send_msg_coros)
observer.delete_all()
# === bot run ==========================================================
def create_app(token: str):
"""
Bot initialization and start function.
Adds the next commands:
- /start - just a standard hello, available only in private messages
- /help - help message, available only in private messages
- /enable@name_bot - starts tower observation, works only in groups
- /please_disable@name_bot - stops the observation, works only in groups
Also adds two handlers, one for private messages and one for groups.
The private message handler just returns an "I don't understand" stub.
The handler in groups controls the process of building the towers.
"""
app = Application.builder().token(token).build()
command_filter = COMMAND & (
(NOTRACK_FILTER & ChatType.GROUPS & COMMAND_WITH_NAME) # only with bot_name in groups
| ChatType.PRIVATE
)
command_handler = partial(CommandHandler, filters=command_filter, block=False)
message_handler = partial(MessageHandler, block=False)
app.add_handler(command_handler("start", start))
app.add_handler(command_handler("help", help))
app.add_handler(command_handler("enable", enable))
app.add_handler(command_handler("please_disable", disable))
app.add_handler(CommandHandler("get_ords", get_ords, NEW_MESSAGE & COMMAND & ChatType.PRIVATE, block=False))
app.add_handler(message_handler(NEW_MESSAGE & ChatType.PRIVATE, dont_understand))
app.add_handler(message_handler(NOTRACK_FILTER & ChatType.GROUPS, standard_message))
return app
async def run_app(token: str):
"""
Coroutine, which starts the program and keeps it running.
"""
app = create_app(token)
global bot
bot = app.bot
updates = [
Update.MESSAGE,
Update.EDITED_MESSAGE,
Update.POLL,
Update.POLL_ANSWER,
Update.CHAT_MEMBER,
Update.CHAT_JOIN_REQUEST,
]
await app.initialize()
await app.updater.start_polling(allowed_updates=updates)
await app.start()
print("Bot is running!")
async def pulling(*coros: Coroutine):
"""
Just a small extra function that run all the necessary coroutines of
the bot and does not let the program stop.
"""
await asyncio.gather(*coros)
while True:
await asyncio.sleep(1)
# ===
bot: Bot
if __name__ == "__main__":
observer = Observer()
run_coro = run_app(Args.TOKEN)
add_action(send_end_day_message)
if Params.ONEDAY_MODE:
add_action(only_wednesday_work_switch)
cron_coro = everyday_cron()
asyncio.run(pulling(run_coro, cron_coro))