Skip to content

Instantly share code, notes, and snippets.

@Jia35

Jia35/app.py Secret

Created August 18, 2019 01:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jia35/a0e169545bb0a13a8ace41dac4891d7c to your computer and use it in GitHub Desktop.
Save Jia35/a0e169545bb0a13a8ace41dac4891d7c to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
from flask import Flask, request
from ey_bot import EyBot
app = Flask(__name__)
ey_bot = EyBot(ACCESS_TOKEN, APP_SECRET)
@app.route('/', methods=['GET', 'POST'])
def home():
return 'ok!!!'
@app.route('/callback', methods=['POST'])
def webhook_handler():
if request.method == "POST":
if ey_bot.verify_webhook(request):
msg = json.loads(request.data.decode("UTF-8"))
ey_bot.respond(msg)
else:
print("SHA1簽章錯誤,來源有問題")
return 'ok'
if __name__ == "__main__":
app.debug = True
app.run()
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import requests
import hmac, hashlib
class EyBot(object):
def __init__(self, token, secret):
self.token = token
self.secret = secret
self.bot_url = "https://us-central1-hahamut-8888.cloudfunctions.net/messagePush?access_token=" + self.token
def verify_webhook(self, request):
real_signature = request.headers.get('x-baha-data-signature')
expected_signature = "sha1=" + hmac.new(self.secret.encode(), request.data, hashlib.sha1).hexdigest()
# print("real_signature= ", real_signature)
# print("expected_signature= ", expected_signature)
return expected_signature == real_signature
def respond(self, msg):
msg = msg["messaging"][0]
print(msg)
sender_id = msg.get("sender_id")
message = msg.get("message")
text = message.get("text")
# 回覆文字
self.reply_text(sender_id, text)
# 回覆貼圖
self.reply_sticker(sender_id, ["30", "07"])
def reply_text(self, chat_id, reply_msg):
send_obj = {
"recipient": {
"id": chat_id
},
"message": {
"type": "text",
"text": str(reply_msg)
}
}
self.reply(send_obj)
def reply_sticker(self, chat_id, sticker_num):
send_obj = {
"recipient": {
"id": chat_id
},
"message": {
"type": "sticker",
"sticker_group": sticker_num[0],
"sticker_id": sticker_num[1]
}
}
self.reply(send_obj)
def reply(self, send_obj):
headers = {'Content-type': 'application/json; charset=UTF-8'}
_ = requests.post(self.bot_url, data=json.dumps(send_obj), headers=headers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment