Created
December 15, 2016 02:46
-
-
Save ctosib/b5223137202539803bfa2adbca118ac0 to your computer and use it in GitHub Desktop.
第一隻練習的facebook bot機器人,使用者說什麼,機器人就說什麼
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#必須要import request,才可以在下面的程式碼當中抓到get or post的參數 | |
from flask import Flask,request | |
import json | |
import requests | |
app = Flask(__name__) | |
@app.route("/" ,methods=['GET']) | |
def hello(): | |
if request.args.get('hub.mode')=='subscribe' and request.args.get('hub.challenge'): | |
if request.args.get('hub.verify_token') == 'test123': | |
return request.args.get('hub.challenge'),200 | |
else: | |
return "mismatch",403 | |
return "hello world GET", 200 | |
@app.route("/", methods=['POST']) | |
def webhook(): | |
data = request.get_json() | |
if data["object"] == 'page': | |
for entry in data["entry"]: | |
for messaging_event in entry['messaging']: | |
if messaging_event.get('message'): | |
sender_id = messaging_event['sender']['id'] | |
recipient_id = messaging_event['recipient']['id'] | |
message_text = messaging_event['message']['text'] | |
send_message(sender_id,'you said:'+message_text) | |
return 'OK',200 | |
def send_message(sender_id,message_text): | |
params = {'access_token':'{my_token_get_by_application_setting}'} | |
headers = {"Content-Type":"application/json"} | |
data = json.dumps({ | |
"recipient":{ | |
"id":sender_id | |
}, | |
"message":{ | |
"text":message_text | |
} | |
}) | |
r = requests.post("https://graph.facebook.com/v2.6/me/messages", params=params, headers=headers, data=data) | |
if __name__=='__main__': | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment