-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessenger.py
359 lines (277 loc) · 13.1 KB
/
messenger.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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# coding: utf-8
import os
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0,parentdir)
import json
from config import CONFIG
from fbmq import Attachment, Template, QuickReply, NotificationType
from fbpage import page
from liloFetch import *
USER_SEQ = {}
rapi = rAPI_Service()
article_Service = articleService()
@page.handle_optin
def received_authentication(event):
sender_id = event.sender_id
recipient_id = event.recipient_id
time_of_auth = event.timestamp
pass_through_param = event.optin.get("ref")
print("Received authentication for user %s and page %s with pass "
"through param '%s' at %s" % (sender_id, recipient_id, pass_through_param, time_of_auth))
page.send(sender_id, "Authentication successful")
@page.handle_echo
def received_echo(event):
message = event.message
message_id = message.get("mid")
app_id = message.get("app_id")
metadata = message.get("metadata")
print("page id : %s , %s" % (page.page_id, page.page_name))
print("Received echo for message %s and app %s with metadata %s" % (message_id, app_id, metadata))
@page.handle_message
def received_message(event):
sender_id = event.sender_id
recipient_id = event.recipient_id
time_of_message = event.timestamp
message = event.message
print("Received message for user %s and page %s at %s with message:"
% (sender_id, recipient_id, time_of_message))
print(message)
seq = message.get("seq", 0)
message_id = message.get("mid")
app_id = message.get("app_id")
metadata = message.get("metadata")
message_text = message.get("text")
message_attachments = message.get("attachments")
quick_reply = message.get("quick_reply")
seq_id = sender_id + ':' + recipient_id
if USER_SEQ.get(seq_id, -1) >= seq:
print("Ignore duplicated request")
return None
else:
USER_SEQ[seq_id] = seq
if quick_reply:
quick_reply_payload = quick_reply.get('payload')
print("quick reply for message %s with payload %s" % (message_id, quick_reply_payload))
page.send(sender_id, "Quick reply tapped")
if message_text:
send_message(sender_id, message_text)
elif message_attachments:
page.send(sender_id, "Message with attachment received")
@page.handle_delivery
def received_delivery_confirmation(event):
delivery = event.delivery
message_ids = delivery.get("mids")
watermark = delivery.get("watermark")
if message_ids:
for message_id in message_ids:
print("Received delivery confirmation for message ID: %s" % message_id)
print("All message before %s were delivered." % watermark)
@page.handle_postback
def received_postback(event):
sender_id = event.sender_id
recipient_id = event.recipient_id
time_of_postback = event.timestamp
payload = event.postback_payload
print("Received postback for user %s and page %s with payload '%s' at %s"
% (sender_id, recipient_id, payload, time_of_postback))
page.send(sender_id, "Postback called")
@page.handle_read
def received_message_read(event):
watermark = event.read.get("watermark")
seq = event.read.get("seq")
print("Received message read event for watermark %s and sequence number %s" % (watermark, seq))
@page.handle_account_linking
def received_account_link(event):
sender_id = event.sender_id
status = event.account_linking.get("status")
auth_code = event.account_linking.get("authorization_code")
print("Received account link event with for user %s with status %s and auth code %s "
% (sender_id, status, auth_code))
def send_message(recipient_id, text, redditSubmission = None):
# If we receive a text message, check to see if it matches any special
# keywords and send back the corresponding example. Otherwise, just echo
# the text we received.
special_keywords = {
"/image": send_image,
"/gif": send_gif,
"/audio": send_audio,
"/video": send_video,
"/file": send_file,
"/button": send_button,
"/generic": send_generic,
"/receipt": send_receipt,
"/quickReply": send_quick_reply,
"/readReceipt": send_read_receipt,
"/typingOn": send_typing_on,
"/typingOff": send_typing_off,
"/accountLinking": send_account_linking,
}
reddit_keywords = {
"/reddit": get_reddit_post,
}
if text in special_keywords:
if redditSubmission is None:
special_keywords[text](recipient_id)
else:
special_keywords[text](recipient_id, redditSubmission)
elif "/reddit" in text:
sub = text.replace("/reddit", "").strip(" ")
microarticle_type = 'filtered'
while microarticle_type is 'filtered':
microarticle, microarticle_type = get_reddit_post(sub)
send_reddit_post(recipient_id, microarticle, microarticle_type)
else:
page.send(recipient_id, text, callback=send_text_callback, notification_type=NotificationType.REGULAR)
def get_reddit_post(text):
print("[i] Getting article...")
print("[i] User Text:\t" + str(text))
user_input = text.replace('/','')
sub_check = rapi.check_sub_exists(user_input)
sampleArticle = False
article_type = False
print("[i] Sub Check:\t" + str(sub_check))
while article_type is False:
if sub_check:
sampleArticle = rapi.sample_article(user_input)
else:
sampleArticle = rapi.sample_article('theonion')
article_type = article_Service.type_check(sampleArticle)
return sampleArticle, article_type
def send_reddit_post(recipient_id, microarticle, microarticle_type):
#sends user the text message provided via input response parameter
print("[i] Formatting Article...")
response = article_Service.format_article(microarticle, microarticle_type)
print("[i] " + microarticle_type + " SRC:\t" + str(microarticle.domain))
if microarticle_type == "image":
image_formats = ['.gif','.jpg','.jpeg','.png']
if microarticle.url[-4:] in image_formats:
page.send(recipient_id, Attachment.Image(str(microarticle.url)))
elif microarticle.url[-4:] == ".gifv":
page.send(recipient_id, Attachment.Video(str(microarticle.url)))
else:
page.send(recipient_id, Attachment.Image(str(microarticle.url)))
elif microarticle_type == "video":
page.send(recipient_id, Attachment.Video(str(microarticle.url)))
elif microarticle_type == "article":
print("[i] Response:")
pprint.pprint(response)
page.send(recipient_id, Template.Generic([
Template.GenericElement(microarticle.title,
subtitle= response[0].get('subtitle'),
item_url= microarticle.url,
image_url= microarticle.thumbnail,
buttons=[
Template.ButtonShare(),
Template.ButtonWeb("Open Web URL", microarticle.url)
]),
]))
print("[i] Response sent...")
return "success"
def send_text_callback(payload, response):
print("SEND CALLBACK")
def send_image(recipient):
page.send(recipient, Attachment.Image(CONFIG['SERVER_URL'] + "/assets/rift.png"))
def send_gif(recipient):
page.send(recipient, Attachment.Image(CONFIG['SERVER_URL'] + "/assets/instagram_logo.gif"))
def send_audio(recipient):
page.send(recipient, Attachment.Audio(CONFIG['SERVER_URL'] + "/assets/sample.mp3"))
def send_video(recipient):
page.send(recipient, Attachment.Video(CONFIG['SERVER_URL'] + "/assets/allofus480.mov"))
def send_file(recipient):
page.send(recipient, Attachment.File(CONFIG['SERVER_URL'] + "/assets/test.txt"))
def send_button(recipient):
"""
Shortcuts are supported
page.send(recipient, Template.Buttons("hello", [
{'type': 'web_url', 'title': 'Open Web URL', 'value': 'https://www.oculus.com/en-us/rift/'},
{'type': 'postback', 'title': 'tigger Postback', 'value': 'DEVELOPED_DEFINED_PAYLOAD'},
{'type': 'phone_number', 'title': 'Call Phone Number', 'value': '+16505551234'},
]))
"""
page.send(recipient, Template.Buttons("hello", [
Template.ButtonWeb("Open Web URL", "https://www.oculus.com/en-us/rift/"),
Template.ButtonPostBack("trigger Postback", "DEVELOPED_DEFINED_PAYLOAD"),
Template.ButtonPhoneNumber("Call Phone Number", "+16505551234")
]))
@page.callback(['DEVELOPED_DEFINED_PAYLOAD'])
def callback_clicked_button(payload, event):
print(payload, event)
def send_generic(recipient):
page.send(recipient, Template.Generic([
Template.GenericElement("rift",
subtitle="Next-generation virtual reality",
item_url="https://www.oculus.com/en-us/rift/",
image_url=CONFIG['SERVER_URL'] + "/assets/rift.png",
buttons=[
Template.ButtonWeb("Open Web URL", "https://www.oculus.com/en-us/rift/"),
Template.ButtonPostBack("tigger Postback", "DEVELOPED_DEFINED_PAYLOAD"),
Template.ButtonPhoneNumber("Call Phone Number", "+16505551234")
]),
Template.GenericElement("touch",
subtitle="Your Hands, Now in VR",
item_url="https://www.oculus.com/en-us/touch/",
image_url=CONFIG['SERVER_URL'] + "/assets/touch.png",
buttons=[
{'type': 'web_url', 'title': 'Open Web URL',
'value': 'https://www.oculus.com/en-us/rift/'},
{'type': 'postback', 'title': 'tigger Postback',
'value': 'DEVELOPED_DEFINED_PAYLOAD'},
{'type': 'phone_number', 'title': 'Call Phone Number', 'value': '+16505551234'},
])
]))
def send_receipt(recipient):
receipt_id = "order1357"
element = Template.ReceiptElement(title="Oculus Rift",
subtitle="Includes: headset, sensor, remote",
quantity=1,
price=599.00,
currency="USD",
image_url=CONFIG['SERVER_URL'] + "/assets/riftsq.png"
)
address = Template.ReceiptAddress(street_1="1 Hacker Way",
street_2="",
city="Menlo Park",
postal_code="94025",
state="CA",
country="US")
summary = Template.ReceiptSummary(subtotal=698.99,
shipping_cost=20.00,
total_tax=57.67,
total_cost=626.66)
adjustment = Template.ReceiptAdjustment(name="New Customer Discount", amount=-50)
page.send(recipient, Template.Receipt(recipient_name='Peter Chang',
order_number=receipt_id,
currency='USD',
payment_method='Visa 1234',
timestamp="1428444852",
elements=[element],
address=address,
summary=summary,
adjustments=[adjustment]))
def send_quick_reply(recipient):
"""
shortcuts are supported
page.send(recipient, "What's your favorite movie genre?",
quick_replies=[{'title': 'Action', 'payload': 'PICK_ACTION'},
{'title': 'Comedy', 'payload': 'PICK_COMEDY'}, ],
metadata="DEVELOPER_DEFINED_METADATA")
"""
page.send(recipient, "What's your favorite movie genre?",
quick_replies=[QuickReply(title="Action", payload="PICK_ACTION"),
QuickReply(title="Comedy", payload="PICK_COMEDY")],
metadata="DEVELOPER_DEFINED_METADATA")
@page.callback(['PICK_ACTION'])
def callback_picked_genre(payload, event):
print(payload, event)
def send_read_receipt(recipient):
page.mark_seen(recipient)
def send_typing_on(recipient):
page.typing_on(recipient)
def send_typing_off(recipient):
page.typing_off(recipient)
def send_account_linking(recipient):
page.send(recipient, Template.AccountLink(text="Welcome. Link your account.",
account_link_url=CONFIG['SERVER_URL'] + "/authorize",
account_unlink_button=True))
def send_text_message(recipient, text):
page.send(recipient, text, metadata="DEVELOPER_DEFINED_METADATA")