8. Recall
How we get a web page?
We type an url address (ip address)
onto the location bar
Chrome sends a request to the server
Server responses us with corresponded
return
9. Web server
To finish a web request, you need
An IP address
A Server
Accept HTTP Protocol
10. HTTP
A way to communicate with server
A general way to exchange information
Ask for resources from server (request)
Server returns if a request is valid
(response)
15. HTTPS
What is HTTPS? HTTP with Secure
Why HTTPS
Make you info secure
Create a security tunnel before data transfer
How to setup it? It’s complicated…
22. First web server
#!/usr/bin/env python
from flask import Flask
from flask import abort
from flask import request
app = Flask(__name__)
@app.route("/version", methods=['GET'])
def version():
if request.method == 'GET':
return "0.1"
else:
abort(404)
if __name__ == "__main__":
app.run(port=11123)
23. Try telnet to your web
server
$ telnet localhost 11123
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
GET /version HTTP/1.1
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 3
Server: Werkzeug/0.12.1 Python/3.5.2
Date: Sun, 16 Apr 2017 15:54:35 GMT
0.1Connection closed by foreign host.
(enter)
26. What we have to do?
Set up you account on Facebook
Write a web server
27. 1. Go https://developers.facebook.com
2. My Apps —> Add a New App
3. Add Product —> Messenger —> Get Started
4. Setup Webhooks, you need
a. A callback url (require HTTPS)
b. A random string as the token
5. Subscription Fields: messages, messaging_postbacks
How to setup a bot (I)
29. Echo Bot
A web call accept requests from FB
Parse data from FB
Return a text response to FB
30. How to setup a bot (II)
1. Create a fan page
2. Create a new App in “facebook developers” page
a. Category :
Brand or Product / App Page
3. Back to developer page:
a. Generate page access token
b. Subscribe messages from your page
37. Send text function
import requests
PAGE_TOKEN = "your-page-access-token"
FB_MESSENGER_URI = "https://graph.facebook.com/v2.6/
me/messages?access_token=" + PAGE_TOKEN
def send_text(reply_token, text):
data = {
"recipient": {"id": reply_token},
"message": {"text": text}
}
r = requests.post(FB_MESSENGER_URI, json=data)
if r.status_code != requests.codes.ok:
print(r.content)
38. Return messages to a user
def fb_post_handler(req):
print req.get_data()
resp_body = req.get_json()
for entry in resp_body["entry"]:
for msg in entry["messaging"]:
sender = msg['sender']['id']
if 'message' in msg:
if msg['message'].get('is_echo'):
return ""
if 'text' not in msg[‘message']:
return ""
text = msg['message']['text']
send_text(sender, text)
return ""
40. Messenger Profile
Facebook provides some API call for us to
configure the BOT environment
•Greeting - A help message to show a user
what the purpose of the bot is
•Get Started - Setup the postback message
when a user is first login
•Persistent Menu
43. Get Started
curl -X POST
'https://graph.facebook.com/v2.6/me/
messenger_profile?access_token=<your-page-access-
token>'
-H 'content-type: application/json'
-d '{
"get_started":{
"payload":"GET_STARTED"
}
}'
44. POSTBACK
Some user-defined words which
represents some kinds of events have
been triggered.
For example, once a new user starts
chatting with the bot, a predefined
postback message will sent to your
server.
46. Handle the POSTBACK
def fb_post_handler(req):
print req.get_data()
resp_body = req.get_json()
for entry in resp_body["entry"]:
for msg in entry["messaging"]:
sender = msg['sender']['id']
if 'message' in msg:
if msg['message'].get('is_echo'):
return ""
text = msg['message']['text']
send_text(sender, text)
elif 'postback' in msg:
if msg['postback']['payload'] == "GET_STARTED":
send_text(sender, 'welcome')
return ""
50. Image
{
"title": "BTC - USD",
"image_url": "<image url>",
"subtitle": "The currency between BTC and USD"
}
51. Send Template Function
def send_template_message(user_id, elements):
data = {
"recipient":{
"id": user_id
},
"message":{
"attachment": {
"type":"template",
"payload":{
"template_type":"generic",
"elements": elements
}
}
}
}
r = requests.post(FB_MESSENGER_URI, json=data)
if r.status_code != requests.codes.ok:
print(r.content)
52. def fb_post_handler(req):
. . .
for entry in resp_body["entry"]:
for msg in entry["messaging"]:
sender = msg['sender']['id']
if 'message' in msg:
. . .
text = msg['message']['text']
if text == "btcusd":
element = [{
"title":"<title>",
"image_url":"<url>",
"subtitle":"<sub title>"
}]
send_template_message(sender, element)
else:
send_text(sender, text)
elif 'postback' in msg:
. . .
63. Handle quick replies
response
. . .
if 'message' in msg:
if msg['message'].get('is_echo'):
return ""
if 'text' not in msg['message']:
return ""
if 'quick_reply' in msg['message']:
reply = msg["message"]["quick_reply"]
if reply['payload'] == "QUERY_CURRENCY":
send_text(sender, "This function is not worked yet.", None)
elif reply['payload'] == "CANCEL":
send_text(sender, "No problem.", None)
return ""
text = msg['message']['text']
if text == “btcusd":
. . .