-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.py
114 lines (94 loc) · 2.65 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
import logging
import re
import telebot
import views
from settings import TOKEN, SUPPORT_CHAT_ID
botlogger = logging.getLogger('botlogger')
# Setting bot
bot = telebot.TeleBot(TOKEN)
tblogger = telebot.logger
telebot.logger.setLevel(logging.INFO)
def run_long_polling():
"""
Start the bot in long-polling mode
"""
botlogger.info('Starting polling...')
bot.infinity_polling(skip_pending=True)
#
# MESSAGE HANDLERS
#
@bot.message_handler(commands=['start', 'help'])
def answer_start(message):
"""
Bot sends general help page and basic bot info
"""
bot.send_message(
message.from_user.id,
views.hello(message.from_user.username),
parse_mode='HTML',
)
send_to_support(views.user_connected(message))
@bot.message_handler(chat_types='private')
def redirect_message_to_admins(message):
"""
Bot redirects user request to admin group.
WARNING: At the end of the redirected message bot
will add <user_id> of the user who sent
the message. This is to ensure that chain of
redirection will not brake.
"""
send_to_support(
views.redirect_user_message(message, add_id=True))
@bot.message_handler(chat_types='group')
def reply_back_to_user(message):
"""
Bot redirects admin answers to the user. When replying,
bot will parse <user_id> from original message that was
added to it.
"""
if (
message.reply_to_message is not None
and message.reply_to_message.from_user.is_bot
):
user_id = parse_user_id(message.reply_to_message.text)
bot.send_message(
user_id,
message.text,
)
#
# HELPERS
#
def reply(to_message: object, with_message: str):
"""
Reply to given incoming message with outcoming message
(with Telegram reply wrapper).
* to_message: the original message object
came to bot from user
* with_message: answer the bot should send to
the author of incoming_message
"""
bot.reply_to(
to_message,
with_message,
parse_mode='HTML'
)
def send_to_support(outcoming_message: str):
"""
Send message (without Telegram reply wrapper).
* outcoming_message: answer the bot should send to
the author of incoming_message
"""
bot.send_message(
SUPPORT_CHAT_ID,
outcoming_message,
parse_mode='HTML'
)
def parse_user_id(message: str):
"""
Parse message text and find user id.
"""
mtch: re.Match = re.match(r'.*id=(?P<id>\d+).*', message, re.S)
if mtch:
return mtch.group('id')
if __name__ == '__main__':
run_long_polling()