-
Notifications
You must be signed in to change notification settings - Fork 3
/
handler.py
80 lines (62 loc) · 1.98 KB
/
handler.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
import json
import logging
import os
from uspqueuebot.credentials import ADMIN_CHAT_ID
import telegram
from uspqueuebot.main import main
# Logging is cool!
logger = logging.getLogger()
if logger.handlers:
for handler in logger.handlers:
logger.removeHandler(handler)
logging.basicConfig(level=logging.INFO)
OK_RESPONSE = {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps('ok')
}
ERROR_RESPONSE = {
'statusCode': 400,
'body': json.dumps('Oops, something went wrong!')
}
def configure_telegram():
"""
Configures the bot with a Telegram Token.
Returns a bot instance.
"""
TELEGRAM_TOKEN = os.environ.get('TELEGRAM_TOKEN')
if not TELEGRAM_TOKEN:
logger.error('The TELEGRAM_TOKEN must be set')
raise NotImplementedError
return telegram.Bot(TELEGRAM_TOKEN)
def set_webhook(event, context):
"""
Sets the Telegram bot webhook.
"""
logger.info('Event: {}'.format(event))
bot = configure_telegram()
url = 'https://{}/{}/'.format(
event.get('headers').get('Host'),
event.get('requestContext').get('stage'),
)
webhook = bot.set_webhook(url)
if webhook:
return OK_RESPONSE
return ERROR_RESPONSE
def webhook(event, context):
"""
Runs the Telegram webhook.
https://python-telegram-bot.readthedocs.io/en/stable/telegram.bot.html
"""
bot = configure_telegram()
if event.get('httpMethod') == 'POST' and event.get('body'):
logger.info('Message received')
body = telegram.Update.de_json(json.loads(event.get('body')), bot).to_dict()
try:
main(bot, body)
except Exception as error:
error_message = "There is an unhandled exception, please debug immediately.\n" + error.__str__()
bot.send_message(chat_id=ADMIN_CHAT_ID, text=error_message)
logger.error(error_message + '\nEvent: {}'.format(body))
return OK_RESPONSE
return ERROR_RESPONSE