-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.py
80 lines (61 loc) · 1.73 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 telegram
import os
import logging
import serverlessHandlers.HandleMessage as messageHandler
# 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 webhook(event, context):
"""
Runs the Telegram webhook.
"""
bot = configure_telegram()
logger.info('Event: {}'.format(event))
if event.get('httpMethod') == 'POST' and event.get('body'):
logger.info('Message received')
update = telegram.Update.de_json(json.loads(event.get('body')), bot)
chat_id = update.message.chat.id
text = update.message.text
message_id = update.message.message_id
user_firstname = update.message.from_user.first_name
# Entry point for incoming messages
messageHandler.HandleMessage(bot, chat_id, text, message_id, user_firstname)
return OK_RESPONSE
return ERROR_RESPONSE
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