-
Notifications
You must be signed in to change notification settings - Fork 10
/
bot.py
executable file
·233 lines (198 loc) · 8.17 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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
os.chdir(os.path.dirname(os.path.realpath(__file__)))
import telebot
from telebot import apihelper
import re
import argparse
import logger
import requests.exceptions
from ASFConnector import ASFConnector
_REGEX_CDKEY = re.compile(r'\w{5}-\w{5}-\w{5}')
_REGEX_COMMAND_BOT_ARGS = r'^[/!]\w+\s*(?P<bot>\w+)?\s+(?P<arg>.*)'
_REGEX_COMMAND_RAW = r'^[/!](?P<input>(?P<command>\w+).*)'
_REGEX_COMMAND = r'^[/!]\w+\s*(?P<bot>\w+)?'
_ENV_TELEGRAM_BOT_TOKEN = "TELEGRAM_BOT_TOKEN"
_ENV_TELEGRAM_USER_ALIAS = "TELEGRAM_USER_ALIAS"
_ENV_TELEGRAM_PROXY = "TELEGRAM_PROXY"
_ENV_ASF_IPC_HOST = "ASF_IPC_HOST"
_ENV_ASF_IPC_PORT = "ASF_IPC_PORT"
_ENV_ASF_IPC_PASSWORD = "ASF_IPC_PASSWORD"
LOG = logger.set_logger('ASFBot')
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbosity", help="Defines log verbosity",
choices=['CRITICAL', 'ERROR', 'WARN', 'INFO', 'DEBUG'], default='INFO')
parser.add_argument("--host", help="ASF IPC host. Default: 127.0.0.1", default='127.0.0.1')
parser.add_argument("--port", help="ASF IPC port. Default: 1242", default='1242')
parser.add_argument("--password", help="ASF IPC password.", default=None)
parser.add_argument("--token", type=str,
help="Telegram API token given by @botfather.", default=None)
parser.add_argument("--proxy", help="Use a proxy to connect to Telegram. Format: "
"<protocol>://<host>:<port>. For example: http://192.168.1.1:7890"
, default=None)
parser.add_argument("--alias", type=str, help="Telegram alias of the bot owner.", default=None)
args = parser.parse_args()
logger.set_level(args.verbosity)
# Telegram related environment variables.
try:
args.token = os.environ[_ENV_TELEGRAM_BOT_TOKEN]
except KeyError as key_error:
if not args.token:
LOG.critical(
"No telegram bot token provided. Please do so using --token argument or %s environment variable.",
_ENV_TELEGRAM_BOT_TOKEN)
exit(1)
try:
args.alias = os.environ[_ENV_TELEGRAM_USER_ALIAS]
except KeyError as key_error:
if not args.alias:
LOG.critical(
"No telegram user alias provided. Please do so using --alias argument or %s environment variable.",
_ENV_TELEGRAM_USER_ALIAS)
exit(1)
try:
args.proxy = os.environ[_ENV_TELEGRAM_PROXY]
except KeyError as key_error:
pass
# ASF IPC related environment variables.
try:
args.host = os.environ[_ENV_ASF_IPC_HOST]
except KeyError as key_error:
pass
try:
args.port = os.environ[_ENV_ASF_IPC_PORT]
except KeyError as key_error:
pass
try:
args.password = os.environ[_ENV_ASF_IPC_PASSWORD]
except KeyError as key_error:
if not args.password:
LOG.debug("No IPC Password provided.")
pass
# Sanitize input
if args.alias[0] == '@':
args.alias = args.alias[1:]
args.token = args.token.strip()
args.alias = args.alias.strip()
args.host = args.host.strip()
args.port = args.port.strip()
if args.password:
args.password = args.password.strip()
if args.proxy:
args.proxy = args.proxy.strip()
LOG.info("Starting up bot...")
LOG.debug("Telegram token: %s", args.token)
LOG.debug("Telegram Proxy %s", args.proxy)
LOG.debug("User alias: %s", args.alias)
LOG.debug("ASF IPC host: %s", args.host)
LOG.debug("ASF IPC port: %s", args.port)
asf_connector = ASFConnector(args.host, args.port, password=args.password)
try:
asf_info = asf_connector.get_asf_info()
LOG.info('ASF Instance replied: {}'.format(asf_info['Message']))
if not asf_info['Success']:
LOG.warning('ASF Instance message was unsuccesful. %s', str(asf_info))
except Exception as e:
LOG.error("Couldn't communicate with ASF. Host: '%s' Port: '%s' \n %s",
args.host, args.port, str(e))
if args.proxy and args.proxy != '' and '://' in args.proxy:
protocol, url = args.proxy.split('://', 1)
apihelper.proxy = {
protocol: url
}
LOG.info(f"Using proxy to connect to Telegram: {protocol}://{apihelper.proxy[protocol]}")
elif args.proxy and args.proxy != '' and '://' not in args.proxy:
LOG.error(f"Invalid proxy provided: {args.proxy}. Skipping...")
bot = telebot.TeleBot(args.token)
def is_user_message(message):
""" Returns if a message is from the owner of the bot comparing it to the user alias provided on startup. """
username = message.chat.username
return username == args.alias
@bot.message_handler(func=is_user_message, commands=['status'])
def status_command(message):
LOG.debug("Received status message: %s", str(message))
try:
match = re.search(_REGEX_COMMAND, message.text)
if not match:
reply_to(message, "Invalid command. Usage:\n<code>/status <bot></code>")
return
bot_arg = match.group('bot') if match.group('bot') else 'ASF'
response = asf_connector.get_bot_info(bot_arg)
LOG.info("Response to status message: %s", str(response))
reply_to(message, "<code>" + str(response) + "</code>")
except requests.HTTPError as http_error:
LOG.exception(http_error)
response = http_error.response
status_code = response.status_code
except requests.ConnectionError as connection_error:
LOG.exception(connection_error)
error_message = str(connection_error.args[0].reason.args[0]).split('>:')[1]
error_response = "Couldn't reach the ASF instance: <code>{}</code>".format(error_message)
reply_to(message, error_response)
except Exception as ex:
reply_to(message, "There was an unexpected error. Please check the logs for more info.")
LOG.exception(ex)
@bot.message_handler(commands=['redeem'])
def redeem_command(message):
LOG.debug("Received redeem message: %s", str(message))
match = re.search(_REGEX_COMMAND_BOT_ARGS, message.text)
if not match:
reply_to(message, "Missing arguments. Usage:\n<code>/redeem <bot> <keys></code>")
return
bots = match.group('bot') if match.group('bot') else 'ASF'
keys = match.group('arg')
response = asf_connector.bot_redeem(bots, keys)
LOG.info("Response to redeem message: %s", str(response))
reply_to(message, "<code>" + str(response) + "</code>")
@bot.message_handler(func=is_user_message, regexp=_REGEX_COMMAND_RAW)
def command_handler(message):
"""
Handler only for unsupported commands.
"""
LOG.debug("Received command: %s", str(message))
match = re.search(_REGEX_COMMAND_RAW, message.text)
if not match:
reply_to(message, "Invalid command.")
return
command = match.group('input')
try:
asf_response = asf_connector.send_command(command)
LOG.info("Command: {}. Response: {}".format(message.text, asf_response))
response = replace_html_entities(asf_response)
except requests.exceptions.HTTPError as ex:
status_code = ex.response.status_code
LOG.error(ex)
response = 'Error sending command. ASF status code: <code>{}</code>'.format(status_code)
reply_to(message, response)
@bot.message_handler(content_types=['text'])
def check_for_cdkeys(message):
"""
Sync handler for the rest of the messages. It searchs for cdkeys and redeems them.
"""
cdkeys = set(_REGEX_CDKEY.findall(message.text))
if len(cdkeys) > 0:
response = asf_connector.bot_redeem('ASF', cdkeys)
reply_to(message, "<code>" + str(response) + "</code>")
else:
LOG.debug("Bypassed message: %s \n from user alias %s.",
message.text, message.chat.username)
def reply_to(message, text, sanitize=False, **kwargs):
if sanitize:
text = replace_html_entities(text)
try:
bot.reply_to(message, text, parse_mode="html", **kwargs)
except Exception as ex:
bot.reply_to(message, "There was a Telegram error sending the message:\n" + text +
". \n Check the bot log for more details.")
LOG.exception(ex)
def replace_html_entities(message: str):
return message.replace('&', '&').replace('<', '<').replace('>', '>')
try:
LOG.debug("Polling started")
bot.infinity_polling()
except KeyboardInterrupt:
LOG.info("Exiting...")
exit(0)
except Exception as e:
LOG.exception(e)