-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfb.py
More file actions
149 lines (129 loc) · 4.5 KB
/
fb.py
File metadata and controls
149 lines (129 loc) · 4.5 KB
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
#!/usr/bin/env python
# coding:utf-8
# Messenger API integration
# We assume you have:
# * a Wit.ai bot setup (https://wit.ai/docs/quickstart)
# * a Messenger Platform setup (https://developers.facebook.com/docs/messenger-platform/quickstart)
# You need to `pip install the following dependencies: requests, bottle.
#
# 1. pip install requests bottle
# 2. You can run this on a cloud service provider like Heroku, Google Cloud Platform or AWS.
# Note that webhooks must have a valid SSL certificate, signed by a certificate authority and won't work on your localhost.
# 3. Set your environment variables e.g. WIT_TOKEN=your_wit_token
# FB_PAGE_TOKEN=your_page_token
# FB_VERIFY_TOKEN=your_verify_token
# 4. Run your server e.g. python examples/messenger.py {PORT}
# 5. Subscribe your page to the Webhooks using verify_token and `https://<your_host>/webhook` as callback URL.
# 6. Talk to your bot on Messenger!
import os
import requests
from sys import argv
from wit import Wit
from bottle import Bottle, request, debug
from bayesnet import BayesNet
# Wit.ai parameters
WIT_TOKEN = os.environ.get('WIT_TOKEN')
# Messenger API parameters
FB_PAGE_TOKEN = os.environ.get('FB_PAGE_TOKEN')
# A user secret to verify webhook get request.
FB_VERIFY_TOKEN = os.environ.get('FB_VERIFY_TOKEN')
# Setup Bottle Server
debug(True)
app = Bottle()
# Facebook Messenger GET Webhook
@app.get('/webhook')
def messenger_webhook():
"""
A webhook to return a challenge
"""
verify_token = request.query.get('hub.verify_token')
# check whether the verify tokens match
if verify_token == FB_VERIFY_TOKEN:
# respond with the challenge to confirm
challenge = request.query.get('hub.challenge')
return challenge
else:
return 'Invalid Request or Verification Token'
# Facebook Messenger POST Webhook
@app.post('/webhook')
def messenger_post():
"""
Handler for webhook (currently for postback and messages)
"""
data = request.json
if data['object'] == 'page':
for entry in data['entry']:
# get all the messages
messages = entry['messaging']
if messages[0]:
# Get the first message
message = messages[0]
# Yay! We got a new message!
# We retrieve the Facebook user ID of the sender
fb_id = message['sender']['id']
# We retrieve the message content
text = message['message']['text']
# Let's forward the message to the Wit.ai Bot Engine
# We handle the response in the function send()
client.run_actions(session_id=fb_id, message=text)
else:
# Returned another event
return 'Received Different Event'
return None
def fb_message(sender_id, text):
"""
Function for returning response to messenger
"""
data = {
'recipient': {'id': sender_id},
'message': {'text': text}
}
# Setup the query string with your PAGE TOKEN
qs = 'access_token=' + FB_PAGE_TOKEN
# Send POST request to messenger
resp = requests.post('https://graph.facebook.com/me/messages?' + qs,
json=data)
return resp.content
def first_entity_value(entities, entity):
"""
Returns first entity value
"""
if entity not in entities:
return None
val = entities[entity][0]['value']
if not val:
return None
return val['value'] if isinstance(val, dict) else val
def send(request, response):
"""
Sender function
"""
# We use the fb_id as equal to session_id
fb_id = request['session_id']
text = response['text']
# send message
fb_message(fb_id, text)
def get_forecast(request):
context = request['context']
entities = request['entities']
loc = first_entity_value(entities, 'location')
if loc:
# This is where we could use a weather service api to get the weather.
context['forecast'] = 'sunny'
if context.get('missingLocation') is not None:
del context['missingLocation']
else:
context['missingLocation'] = True
if context.get('forecast') is not None:
del context['forecast']
return context
# Setup Actions
actions = {
'send': send,
'getForecast': get_forecast,
}
# Setup Wit Client
client = Wit(access_token=WIT_TOKEN, actions=actions)
if __name__ == '__main__':
# Run Server
app.run(host='0.0.0.0', port=argv[1])