-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlambda_function.py
294 lines (262 loc) · 11.8 KB
/
lambda_function.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
import boto3
import json
import random
import os
botToken = os.environ['BOT_TOKEN']
headers = {'Content-Type': 'application/json'}
tableName = os.environ['TABLE_NAME']
idFileAudio = os.environ['ID_AUDIO']
idFileVoice = os.environ['ID_VOICE']
random_li = ['Hello bro.', 'Yo whats up.', 'Whats up man.']
# polls_li = {chat_id: {message_id:
# {reply_id: reply_id, username:username, value:value, n_votes: n_votes}}
# value = sum(Votes) / (3 * nVotes)
polls_li = {}
keyboard = {"inline_keyboard": [[{"text": "Very bad", "callback_data": "0"}], [{"text": "Not that good", "callback_data": "1"}], [{"text": "It's ok", "callback_data": "2"}], [{"text": "So nice!", "callback_data": "3"}]]}
########################################################################
########################## REQUEST HANDLERS ##########################
########################################################################
# This functions decide what to do, depending on the request received
# MAIN FUNCTION, THIS ONE WILL DIRECLY COMUNICATE WITH AWS AND TRANSLATE THE HTTP REQUESTS
def lambda_handler(event, context):
# get http request from Telegram Server
data = json.loads(event["body"])
# response treating, add many update types as you want to handle. Here i handle only "message" and "callback_query"
if 'message' in data:
response = handleMessage(data)
elif 'callback_query' in data:
response = handleCallbackQuery(data)
else:
# Default response if we don't have anything to say.
# 'statusCode': '200' means that we read the UPDATE, so Telegram wont
# send it again. MUST HAVE
response = {
'statusCode': '200',
'headers': headers
}
return response
# This function handle an update with type "MESSAGE", depending on what is written on "text" field", it will answer
def handleMessage(update):
global blackList_li
global cdKeyboard
global polls_li
global talker
global talkerCounter
sender = update['message']['from']
messageId = update['message']['message_id']
chatId = update['message']['chat']['id']
response = {
'statusCode': '200',
'headers': headers
}
if 'text' in update['message']:
text = update['message']['text']
print(str(update["update_id"]) + " TEXT detected --> " + sender['first_name'] + ": " + text)
#################### ADD YOUR CODE HERE!!!!!!!!!!!
###
if ('mappa italia' == text) | ('Mappa italia' == text) | ('Mappa Italia' == text) | ('mappa Italia' == text):
response = sendPhoto(chatId, "AgADBAAD-KsxG15jyVPdctQFXg0YDFJHJhoABBE172LbwlnNTCYDAAEC")
elif ('Make a poll about this' == text) & ('reply_to_message' in update['message']):
replieduser = update['message']['reply_to_message']['from']['first_name']
response = sendKeyboard(chatId, 'What do you think about ' + replieduser + 'said?',
keyboard, update['message']['reply_to_message']['message_id'], True)
elif '👀' == text:
response = sendAudio(chatId, idFileAudio)
elif ('hello' in text) | ('Hello' in text):
response = sendVoice(chatId, idFileVoice)
elif ('random message' in text) | ('Random message' in text):
answer = random.choice(random_li)
response = sendMessage(chatId, answer)
elif ('hello bot' in text) | ('Hello bot' in text):
response = sendMessage(chatId, 'Did i hear my name?',messageId, True)
elif ((text == 'Results?') | (text == 'results?')) & ('reply_to_message' in update['message']):
response = sendPollSolution(chatId, update['message']['reply_to_message']['message_id'])
###
#################### ADD YOUR CODE HERE!!!!!!!!!!!
return response
# This function handle an update with type "CALLBACK_QUERY", it is used for collecting polls' votes
def handleCallbackQuery(update):
response = {
'statusCode': '200',
'headers': headers
}
chatId = update['callback_query']['message']['chat']['id']
messageId = update['callback_query']['message']['message_id']
replyId = update['callback_query']['message']['reply_to_message']['message_id']
username = update['callback_query']['message']['reply_to_message']['from']['first_name']
voteFrom = update['callback_query']['from']['first_name']
data = update['callback_query']['data']
#################### ADD YOUR CODE HERE!!!!!!!!!!!
###
print(str(update["update_id"]) + " VOTE detected --> chat_id = " + str(chatId) + ", message_id = " + str(messageId)
+ ", from = " + voteFrom + ", vote = " + str(data))
if username == voteFrom:
print("You can't vote here! " + username)
else:
insertVoteDynamo(chatId, messageId, replyId, username, voteFrom, data, '0')
###
#################### ADD YOUR CODE HERE!!!!!!!!!!!
return response
#########################################################################
########################## ANSWER GENERATORS ##########################
#########################################################################
# This functions generates http responses that we will send to Telegram Server.
def sendMessage(chatId, text, replyId=0, replyMode=False):
print('chatID = ' + str(chatId) + ', text = ' + text)
if replyMode:
response = {
'statusCode': '200',
'body': json.dumps(
{'method': 'sendMessage', 'chat_id': chatId, 'text': text, 'reply_to_message_id': replyId}),
'headers': headers
}
else:
response = {
'statusCode': '200',
'body': json.dumps({'method': 'sendMessage', 'chat_id': chatId, 'text': text}),
'headers': headers
}
return response
def sendKeyboard(chatId, text, keyboard, replyId=0, replyMode=False):
print('chatID = ' + str(chatId) + ', text and keyboard = ' + text)
print(keyboard)
if replyMode:
response = {
'statusCode': '200',
'body': json.dumps(
{'method': 'sendMessage', 'chat_id': chatId, 'text': text, 'reply_markup': json.dumps(keyboard),
'reply_to_message_id': replyId}),
'headers': headers
}
else:
response = {
'statusCode': '200',
'body': json.dumps(
{'method': 'sendMessage', 'chat_id': chatId, 'text': text, 'reply_markup': json.dumps(keyboard)}),
'headers': headers
}
return response
# polls_li = {chat_id: {message_id:
# {reply_id: reply_id, username:username, value:value, n_votes: n_votes}}
# value = sum(Votes) / (3 * nVotes)
def sendPollSolution(chatId, messagePollId):
poll = readDynamo(chatId, messagePollId)
if poll != None:
votes = poll['votes']["M"]
nVotes = 0
totalValue = 0
for vote in votes:
nVotes = nVotes + 1
totalValue = totalValue + int(votes[vote]['S'])
result = int(totalValue * 100 / (nVotes * 3))
if result < 25:
response = sendMessage(chatId, "Result: " + str(result) + "%" + ".Very bad bro.", polls_li[chatId][messagePollId]['reply_id'], True)
elif result < 50:
response = sendMessage(chatId, "Result: " + str(result) + "%" + ". Mmh not the best choice.", polls_li[chatId][messagePollId]['reply_id'], True)
elif result < 75:
response = sendMessage(chatId, "Result: " + str(result) + "%" + ". Good, keep on that point.", polls_li[chatId][messagePollId]['reply_id'], True)
else:
response = sendMessage(chatId, "Result: " + str(result) + "%" + ". Nice! you are the best.", polls_li[chatId][messagePollId]['reply_id'], True)
else:
response = sendMessage(chatId, "Go team! vote the poll", polls_li[chatId][messagePollId]['reply_id'], True)
return response
def sendVoice(chatId, voice, replyId=0, replyMode=False):
print('chatID = ' + str(chatId) + ', voice = ' + voice)
if replyMode:
response = {
'statusCode': '200',
'body': json.dumps(
{'method': 'sendVoice', 'chat_id': chatId, 'voice': voice, 'reply_to_message_id': replyId}),
'headers': headers
}
else:
response = {
'statusCode': '200',
'body': json.dumps({'method': 'sendVoice', 'chat_id': chatId, 'voice': voice}),
'headers': headers
}
return response
def sendVideo(chatId, video, replyId=0, replyMode=False):
print('chatID = ' + str(chatId) + ', video = ' + video)
if replyMode:
response = {
'statusCode': '200',
'body': json.dumps(
{'method': 'sendVideo', 'chat_id': chatId, 'video': video, 'reply_to_message_id': replyId}),
'headers': headers
}
else:
response = {
'statusCode': '200',
'body': json.dumps({'method': 'sendVideo', 'chat_id': chatId, 'video': video}),
'headers': headers
}
return response
def sendAudio(chatId, audio, replyId=0, replyMode=False):
print('chatID = ' + str(chatId) + ', audio = ' + audio)
if replyMode:
response = {
'statusCode': '200',
'body': json.dumps(
{'method': 'sendAudio', 'chat_id': chatId, 'audio': audio, 'reply_to_message_id': replyId}),
'headers': headers
}
else:
response = {
'statusCode': '200',
'body': json.dumps({'method': 'sendAudio', 'chat_id': chatId, 'audio': audio}),
'headers': headers
}
return response
def sendPhoto(chatId, photo, replyId=0, replyMode=False):
print('chatID = ' + str(chatId) + ', photo = ' + photo)
if replyMode:
response = {
'statusCode': '200',
'body': json.dumps(
{'method': 'sendPhoto', 'chat_id': chatId, 'photo': photo, 'reply_to_message_id': replyId}),
'headers': headers
}
else:
response = {
'statusCode': '200',
'body': json.dumps({'method': 'sendPhoto', 'chat_id': chatId, 'photo': photo}),
'headers': headers
}
return response
###########################################################################
########################## DYNAMO COMUNICATION ##########################
###########################################################################
# This functions read and write on DynamoDB.
def insertVoteDynamo(chatId, messageId, replyId, username, voteFrom, data, type):
dynamo = boto3.client('dynamodb')
chatIdmessageId = str(chatId) + str(messageId)
poll = dynamo.get_item(TableName=tableName, Key={'ChatIDmessageID': {'S': chatIdmessageId}})
print(poll)
if 'Item' in poll:
print("Adding new vote")
if voteFrom in poll["Item"]['votes']["M"]:
print("Changing vote --> From " + voteFrom + " vote " + data)
poll["Item"]['votes']["M"][voteFrom] = {'S': data}
item = poll["Item"]
dynamo.put_item(TableName=tableName, Item=item)
else:
print("Creating new poll")
item = {
'ChatIDmessageID': {'S': chatIdmessageId},
'chat_id': {'S': str(chatId)},
'reply_id': {'S': str(replyId)},
'username': {'S': username},
'votes': {'M':
{voteFrom: {'S': data}}
},
'type': {'S': type}
}
dynamo.put_item(Item=item, TableName=tableName)
def readDynamo(chatId, messageId):
dynamo = boto3.client('dynamodb')
chatIdmessageId = str(chatId) + str(messageId)
poll = dynamo.get_item(TableName=tableName, Key={'ChatIDmessageID': {'S': chatIdmessageId}})
if 'Item' in poll:
return poll["Item"]
return None