Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hello from serverless messanger chatbot. Read more: http://qooba.net/index.php/2018/07/22/hello-from-serverless-messanger-chatbot/
"""messanger chatbot"""
import binascii
import hmac
import json
import os
import urllib
from hashlib import sha1
verify_token = os.environ["verify_token"]
access_token = os.environ["access_token"]
app_secret = os.environ["app_secret"]
# lambda entry point
def lambda_handler(event, context):
"""lambda entrypoint"""
print(event)
try:
query_string_parameters = event["queryStringParameters"]
if query_string_parameters != None:
hub_mode = query_string_parameters["hub.mode"]
hub_challenge = query_string_parameters["hub.challenge"]
hub_verify_token = query_string_parameters["hub.verify_token"]
# handling verification request
if hub_mode == "subscribe" and verify_token == hub_verify_token:
return {
'statusCode': 200,
'body': hub_challenge,
'headers': {
'Content-Type': 'text/plain'
}
}
body = event["body"]
headers = event["headers"]
# here we verify the webhook signature
if headers["X-Hub-Signature"].replace('sha1=', '') != hmac_sha1(body):
return {'statusCode': 200}
# finally we parse the message
for entry in json.loads(body)["entry"]:
for message in entry["messaging"]:
if message.get("message", None) != None:
publish_message(message)
except Exception as ex:
print(ex)
return {'statusCode': 200}
def publish_message(message):
"""publish message"""
base_url = 'https://graph.facebook.com/v2.6/me/messages?access_token={}'
url = base_url.format(access_token)
sender_id = message['sender']['id']
# here we parse the message intent
if parse_intent(message) == 'hungry':
text = "Bon Appetit :)"
else:
text = "Hello from serverless messanger chatbot !!!"
my_message = {"recipient": {"id": sender_id}, "message": {"text": text}}
req = urllib.request.Request(url)
data = urllib.parse.urlencode(my_message).encode('utf-8')
urllib.request.urlopen(req, data=data)
def parse_intent(message):
try:
nlp = message['message']['nlp']
intent = nlp['entities']['intent'][0]['value']
return intent
except KeyError:
return None
def hmac_sha1(input_str):
"""calculate hmac"""
raw = input_str.encode("utf-8")
key = app_secret.encode('utf-8')
hashed = hmac.new(key, raw, sha1)
return str(binascii.hexlify(hashed.digest())).lstrip('b').strip("'")
{
"object": "page",
"entry": [
{
"id": "*********************",
"time": 1532132321321,
"messaging": [
{
"sender": {
"id": "****************"
},
"recipient": {
"id": "*****************"
},
"timestamp": 1532123213213,
"message": {
"mid": "***************************",
"seq": 222222,
"text": "I want to eat pizza",
"nlp": {
"entities": {
"dish": [
{
"confidence": 0.91639471779845,
"value": "pizza",
"type": "value",
"_entity": "dish",
"_body": "pizza",
"_start": 15,
"_end": 20
}
],
"intent": [
{
"confidence": 0.99276725775628,
"value": "hungry",
"_entity": "intent"
}
]
}
}
}
}
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment