forked from yukuku/telebot
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main_fb.py
executable file
·329 lines (296 loc) · 11.1 KB
/
main_fb.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# -*- coding: utf-8 -*-
from google.appengine.api import urlfetch
from main_exception import SafeRequestHandler
import jsonUtil
import logging
import key
import requests
import json
json_headers = {'Content-type': 'application/json'}
def setGetStartedButton():
from main import tell_admin
response_data = {
"get_started": {
"payload":"START"
}
}
response_data_str = json.dumps(response_data)
try:
logging.info('sending menu with json: {}'.format(response_data))
resp = requests.post(key.FACEBOOK_PROFILE_API_URL, data=response_data_str, headers=json_headers)
logging.info('responding to request: {}'.format(resp.text))
tell_admin('Response to GetStartedButton: {}'.format(resp.text))
return resp.status_code == 200
except:
report_exception()
def setFB_Menu():
setMenu(['INIZIO','IMPOSTAZIONI','AIUTO','STOP'])
def setMenu(menu_items):
from main import tell_admin
response_data = {
"persistent_menu": [
{
"locale": "default",
"composer_input_disabled": False, #Set to true to disable user input in the menu. This means users will only be able to interact with your bot via the menu, postbacks, buttons, and webviews.
"call_to_actions": [
{
"title": "Opzioni",
"type": "nested",
"call_to_actions": [
{
"type": "postback",
"title": i,
"payload": i,
}
for i in menu_items
]
},
{
"title": "Links",
"type": "nested",
"call_to_actions": [
{
"type": "web_url",
"title": "Telegram bot",
"url": "https://t.me/PickMeUp_bot",
"webview_height_ratio": "tall" # compact, tall, full
},
{
"type": "web_url",
"title": "Website",
"url": "http://pickmeup.trentino.it",
"webview_height_ratio": "tall" # compact, tall, full
}
]
},
]
},
#{
# "locale": "default",
# "composer_input_disabled": False #Set to true to disable user input in the menu. This means users will only be able to interact with your bot via the menu, postbacks, buttons, and webviews.
#}
]
}
response_data_str = json.dumps(response_data)
try:
logging.info('sending menu with json: {}'.format(response_data))
resp = requests.post(key.FACEBOOK_PROFILE_API_URL, data=response_data_str, headers=json_headers)
logging.info('responding to request: {}'.format(resp.text))
tell_admin('Response to set persisten menu: {}'.format(resp.text))
return resp.status_code == 200
except:
report_exception()
def sendMsgRequest(p, request_data):
if key.APPLICATION == 'tiramisu-telegram':
return
request_data_str = json.dumps(request_data)
try:
logging.info('responding to request with message: {}'.format(request_data))
resp = requests.post(key.FACEBOOK_MSG_API_URL, data=request_data_str, headers=json_headers)
logging.info('responding to request: {}'.format(resp.text))
logging.info('status code: {}'.format(resp.status_code))
code = resp.status_code
if code == 403:
# Disabled user
p.setEnabled(False, put=True)
# logging.info('Disabled user: ' + p.getFirstNameLastNameUserName())
return code == 200
except:
report_exception()
def sendMessage(p, msg):
msg = msg.replace('*','')
request_data = {
"recipient": {
"id": p.chat_id
},
"message": {
"text": msg,
}
}
logging.info('message request (simple): {}'.format(request_data))
return sendMsgRequest(p, request_data)
# max 11 reply_items
def sendMessageWithQuickReplies(p, msg, reply_items):
msg = msg.replace('*', '')
request_data = {
"recipient": {
"id": p.chat_id
},
"message": {
"text": msg,
"quick_replies": [
{
"content_type": "text",
"title": i,
"payload": i
}
for i in reply_items
]
}
}
logging.info('message request with quick replies: {}'.format(request_data))
return sendMsgRequest(p, request_data)
# max 3 button_items
def sendMessageWithButtons(p, msg, button_items):
msg = msg.replace('*', '')
request_data = {
"recipient": {
"id": p.chat_id
},
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "button",
"text": msg,
"buttons": [
{
"type": "postback",
"title": i,
"payload": i
}
for i in button_items
]
}
}
}
}
logging.info('message request with buttons: {}'.format(request_data))
return sendMsgRequest(p, request_data)
def sendMessageWithList(p, msg, button_items):
from main import tell_admin
msg = msg.replace('*', '')
request_data = {
"recipient": {
"id": p.chat_id
},
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "list",
"top_element_style": "compact", # large, compact
"elements": [
{
"title": i,
"subtitle": i,
"default_action": {
"type": "postback",
"payload": i
}
}
for i in button_items
]
}
}
}
}
logging.info('message request with list: {}'.format(request_data))
request_data_str = json.dumps(request_data)
try:
logging.info('responding to request with message: {}'.format(request_data))
resp = requests.post(key.FACEBOOK_MSG_API_URL, data=request_data_str, headers=json_headers)
tell_admin('response to request with list: {}'.format(resp.text))
logging.info('status code: {}'.format(resp.status_code))
code = resp.status_code
if code == 403:
# Disabled user
p.setEnabled(False, put=True)
# logging.info('Disabled user: ' + p.getFirstNameLastNameUserName())
return code == 200
except:
report_exception()
def sendPhotoUrl(p, url):
request_data = {
"recipient": {
"id": p.chat_id
},
"message": {
"attachment": {
"type": "file",
"payload": {
"url": url
}
}
}
}
logging.info('send photo (url) request: {}'.format(request_data))
return sendMsgRequest(p, request_data)
def sendPhotoData(p, file_data, filename):
request_data = {
"recipient": json.dumps(
{
"id": p.chat_id
}
),
"message": json.dumps(
{
"attachment": {
"type": "image",
"payload": {}
}
}
)
}
files = {
"filedata": (filename, file_data, 'image/png')
}
try:
logging.info('sending photo data: {}'.format(request_data))
resp = requests.post(key.FACEBOOK_MSG_API_URL, data=request_data, files=files)
logging.info('responding to photo request: {}'.format(resp.text))
return resp.status_code == 200
except:
report_exception()
def getUserInfo(user_id):
url = key.FACEBOOK_BASE_API + \
'/{}?fields=first_name,last_name,profile_pic,locale,timezone,gender' \
'&access_token={}'.format(user_id, key.FACEBOOK_PAGE_ACCESS_TOKEN)
logging.debug('Sending user info request: {}'.format(url))
r = requests.get(url)
json = r.json()
first_name = json.get('first_name', None)
last_name = json.get('last_name', None)
logging.debug('Getting first name = {} and last name = {}'.format(first_name, last_name))
return first_name, last_name
class WebhookHandler(SafeRequestHandler):
# to confirm the webhook url
def get(self):
#urlfetch.set_default_fetch_deadline(60)
logging.info('verification request: {}'.format(self.request.body))
verify_token = self.request.get('hub.verify_token')
if verify_token == key.FACEBOOK_VERIFY_TOKEN:
challenge = self.request.get('hub.challenge')
self.response.write(challenge)
else:
self.response.http_status_message(403)
# to handle user interaction
def post(self):
from main import dealWithUserInteraction
#urlfetch.set_default_fetch_deadline(60)
body = jsonUtil.json_loads_byteified(self.request.body)
logging.info('request body: {}'.format(body))
messaging = body['entry'][0]['messaging'][0]
chat_id = messaging['sender']['id']
text = messaging.get('message', {}).get('text', '')
if text=='':
text = messaging.get('postback', {}).get('payload', '')
#attachment = messaging.get('message', {}).get('attachments', [{}])[0]
#voice_url = attachment.get('payload',{}).get('url',None) if attachment.get('type',None)=='audio' else None
location = messaging.get('message', {}).get('attachments', [{}])[0].get('payload', {}).get('coordinates', None)
# {"lat": 46.0, "long": 11.1}
if location:
location = {'latitude': location['lat'], 'longitude': location['long'] }
# we need this as fb is send all sort of notification when user is active without sending any message
if text=='' and location is None:
return
name, last_name = getUserInfo(chat_id)
dealWithUserInteraction(chat_id, name=name, last_name=last_name, username=None,
application='messenger', text=text,
location=location, contact=None, photo=None, document=None, voice=None)
def report_exception():
from main import tell_admin
import traceback
msg = "❗ Detected Exception: " + traceback.format_exc()
tell_admin(msg)
logging.error(msg)