-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfacebook_custom.py
339 lines (274 loc) · 12.2 KB
/
facebook_custom.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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import hashlib
import hmac
import logging
import six
from fbmessenger import (
BaseMessenger, elements, MessengerClient, attachments)
from flask import Blueprint, request, jsonify
from typing import Text, List, Dict, Any, Callable
from numpy import unicode
from rasa_core.channels.channel import UserMessage, OutputChannel
from rasa_core.channels.rest import HttpInputComponent
import re
import messages
import properties
import csv
import datetime
logger = logging.getLogger(__name__)
class Messenger(BaseMessenger):
"""Implement a fbmessenger to parse incoming webhooks and send msgs."""
def __init__(self, page_access_token, on_new_message):
# type: (Text, Callable[[UserMessage], None]) -> None
self.page_access_token = page_access_token
self.on_new_message = on_new_message
super(Messenger, self).__init__(self.page_access_token)
@staticmethod
def _is_audio_message(message):
# type: (Dict[Text, Any]) -> bool
"""Check if the users message is a recorced voice message."""
return (message.get('message') and
message['message'].get('attachments') and
message['message']['attachments'][0]['type'] == 'audio')
@staticmethod
def _is_user_message(message):
# type: (Dict[Text, Any]) -> bool
"""Check if the message is a message from the user"""
return (message.get('message') and
message['message'].get('text') and
not message['message'].get("is_echo"))
def message(self, message):
# type: (Dict[Text, Any]) -> None
"""Handle an incoming event from the fb webhook."""
if self._is_user_message(message):
text = message['message']['text']
elif self._is_audio_message(message):
attachment = message['message']['attachments'][0]
text = attachment['payload']['url']
else:
logger.warn("Received a message from facebook that we can not "
"handle. Message: {}".format(message))
return
self._handle_user_message(text, self.get_user_id())
def postback(self, message):
# type: (Dict[Text, Any]) -> None
"""Handle a postback (e.g. quick reply button)."""
text = message['postback']['payload']
self._handle_user_message(text, self.get_user_id())
def _handle_user_message(self, text, sender_id):
# type: (Text, Text) -> None
"""Pass on the text to the dialogue engine for processing."""
out_channel = MessengerBot(self.client)
user_msg = UserMessage(text, out_channel, sender_id)
try:
self.on_new_message(user_msg)
except Exception as e:
logger.exception("Exception when trying to handle webhook "
"for facebook message.")
pass
def delivery(self, message):
# type: (Dict[Text, Any]) -> None
"""Do nothing. Method to handle `message_deliveries`"""
pass
def read(self, message):
# type: (Dict[Text, Any]) -> None
"""Do nothing. Method to handle `message_reads`"""
pass
def account_linking(self, message):
# type: (Dict[Text, Any]) -> None
"""Do nothing. Method to handle `account_linking`"""
pass
def optin(self, message):
# type: (Dict[Text, Any]) -> None
"""Do nothing. Method to handle `messaging_optins`"""
pass
class MessengerBot(OutputChannel):
"""A bot that uses fb-messenger to communicate."""
@classmethod
def name(cls):
return "facebook"
def __init__(self, messenger_client):
# type: (MessengerClient) -> None
self.messenger_client = messenger_client
super(MessengerBot, self).__init__()
def send(self, recipient_id, element):
# type: (Text, Any) -> None
"""Sends a message to the recipient using the messenger client."""
# this is a bit hacky, but the client doesn't have a proper API to
# send messages but instead expects the incoming sender to be present
# which we don't have as it is stored in the input channel.
self.messenger_client.send(element.to_dict(),
{"sender": {"id": recipient_id}},
'RESPONSE')
def send_text_message(self, recipient_id, message):
# type: (Text, Text) -> None
"""Send a message through this channel."""
if (re.match("^{}".format(messages.log_header), message)):
save_log(message, recipient_id, messages.user_debug)
else:
logger.info("Sending message: " + message)
message = save_log(message, recipient_id, messages.user_bot)
message = message.replace('*', '')
self.send(recipient_id, elements.Text(text=message))
def send_image_url(self, recipient_id, image_url):
# type: (Text, Text) -> None
"""Sends an image. Default will just post the url as a string."""
self.send(recipient_id, attachments.Image(url=image_url))
def send_text_with_buttons(self, recipient_id, text, buttons, **kwargs):
# type: (Text, Text, List[Dict[Text, Any]], **Any) -> None
"""Sends buttons to the output."""
# buttons is a list of tuples: [(option_name,payload)]
text = save_log(text, recipient_id, messages.user_bot)
text = text.replace('*', '')
for button in buttons:
save_log(button["title"], recipient_id, messages.user_bot)
if len(buttons) > 3:
# TODO Corregir
buttons = buttons[:3]
self._add_postback_info(buttons)
# Currently there is no predefined way to create a message with
# buttons in the fbmessenger framework - so we need to create the
# payload on our own
payload = {
"attachment": {
"type": "template",
"payload": {
"template_type": "button",
"text": text,
"buttons": buttons
}
}
}
self.messenger_client.send(payload,
{"sender": {"id": recipient_id}},
'RESPONSE')
def send_custom_message(self, recipient_id, elements):
# type: (Text, List[Dict[Text, Any]]) -> None
"""Sends elements to the output."""
for element in elements:
self._add_postback_info(element['buttons'])
payload = {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": elements
}
}
}
self.messenger_client.send(payload,
self._recipient_json(recipient_id),
'RESPONSE')
@staticmethod
def _add_postback_info(buttons):
# type: (List[Dict[Text, Any]]) -> None
"""Set the button type to postback for all buttons. Happens in place."""
for button in buttons:
button['type'] = "postback"
@staticmethod
def _recipient_json(recipient_id):
# type: (Text) -> Dict[Text, Dict[Text, Text]]
"""Generate the response json for the recipient expected by FB."""
return {"sender": {"id": recipient_id}}
class FacebookInput(HttpInputComponent):
"""Facebook input channel implementation. Based on the HTTPInputChannel."""
@classmethod
def name(cls):
return "facebook"
def __init__(self, fb_verify, fb_secret, fb_access_token):
# type: (Text, Text, Text) -> None
"""Create a facebook input channel.
Needs a couple of settings to properly authenticate and validate
messages. Details to setup:
https://github.com/rehabstudio/fbmessenger#facebook-app-setup
:param fb_verify: FB Verification string
(can be chosen by yourself on webhook creation)
:param fb_secret: facebook application secret
:param fb_access_token: access token to post in the name of the FB page
"""
self.fb_verify = fb_verify
self.fb_secret = fb_secret
self.fb_access_token = fb_access_token
def blueprint(self, on_new_message):
fb_webhook = Blueprint('fb_webhook', __name__)
@fb_webhook.route("/", methods=['GET'])
def health():
return jsonify({"status": "ok"})
@fb_webhook.route("/webhook", methods=['GET'])
def token_verification():
if request.args.get("hub.verify_token") == self.fb_verify:
return request.args.get("hub.challenge")
else:
logger.warn("Invalid fb verify token! Make sure this matches "
"your webhook settings on the facebook app.")
return "failure, invalid token"
@fb_webhook.route("/webhook", methods=['POST'])
def webhook():
if not self.check_has_not_exceeded_time(request.data):
return "Exceeded time"
signature = request.headers.get("X-Hub-Signature") or ''
if not self.validate_hub_signature(self.fb_secret, request.data,
signature):
logger.warn("Wrong fb secret! Make sure this matches the "
"secret in your facebook app settings")
return "not validated"
messenger = Messenger(self.fb_access_token, on_new_message)
messenger.handle(request.get_json(force=True))
return "success"
return fb_webhook
@staticmethod
def validate_hub_signature(app_secret, request_payload,
hub_signature_header):
"""Makes sure the incoming webhook requests are properly signed.
:param app_secret: Secret Key for application
:param request_payload: request body
:param hub_signature_header: X-Hub-Signature header sent with request
:return: boolean indicated that hub signature is validated
"""
try:
hash_method, hub_signature = hub_signature_header.split('=')
except Exception:
pass
else:
digest_module = getattr(hashlib, hash_method)
if six.PY2:
# noinspection PyCompatibility
hmac_object = hmac.new(
str(app_secret),
unicode(request_payload), digest_module)
else:
hmac_object = hmac.new(
bytearray(app_secret, 'utf8'),
request_payload, digest_module)
generated_hash = hmac_object.hexdigest()
if hub_signature == generated_hash:
return True
return False
@staticmethod
def check_has_not_exceeded_time(message):
try:
facebook_timestamp_in_milliseconds = request.get_json(force=True)['entry'][0]['messaging'][0]['timestamp']
facebook_timestamp_in_seconds = facebook_timestamp_in_milliseconds / 1000.0
return (datetime.datetime.now() - datetime.datetime.fromtimestamp(facebook_timestamp_in_seconds)) < datetime.timedelta(minutes=properties.discard_messages_timemout)
except Exception:
return False
def save_log(text, sender_id, user):
message_match = re.match("^(ERROR_LUGAR: |ERROR_FECHA: |ERROR_ENTENDER: |ERROR_DUDA: )?(.*)", text)
type_message = ""
if (message_match[1]):
text = message_match[2]
type_message=message_match[1].replace(": ", "")
try:
with open(get_log_filename(), 'a', newline='') as csvfile:
log = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_ALL)
log.writerow([sender_id, user, type_message, str(datetime.datetime.now()), text])
except Exception as e:
logger.error("Error al guardar log. {}".format(e))
return ""
print(text)
return text
def get_log_filename():
return properties.logs_path + str(datetime.date.today().isocalendar()[0]) + "_facebook_" + str(datetime.date.today().isocalendar()[1]) + ".csv"