From 5128bf1a64463e7420c6b6cd29b5415f2240d921 Mon Sep 17 00:00:00 2001 From: Swapnil Agarwal Date: Tue, 1 Nov 2016 18:20:19 +0000 Subject: [PATCH] Add Quick Replies support --- jarvis.py | 21 +++++++++++---------- modules/__init__.py | 1 + templates/quick_replies.py | 18 ++++++++++++++++++ 3 files changed, 30 insertions(+), 10 deletions(-) create mode 100644 templates/quick_replies.py diff --git a/jarvis.py b/jarvis.py index a3c5d2b6..cc59783d 100644 --- a/jarvis.py +++ b/jarvis.py @@ -29,22 +29,23 @@ def webhook(): messaging_events = data['entry'][0]['messaging'] for event in messaging_events: sender = event['sender']['id'] + message = None if 'message' in event and 'text' in event['message']: - text = event['message']['text'] - payload = { - 'recipient': { - 'id': sender - }, - 'message': modules.search(text) - } - r = requests.post('https://graph.facebook.com/v2.6/me/messages', params={'access_token': ACCESS_TOKEN}, json=payload) + if 'quick_reply' in event['message'] and 'payload' in event['message']['quick_reply']: + quick_reply_payload = event['message']['quick_reply']['payload'] + message = modules.search(quick_reply_payload, postback=True) + else: + text = event['message']['text'] + message = modules.search(text) if 'postback' in event and 'payload' in event['postback']: - postback = event['postback']['payload'] + postback_payload = event['postback']['payload'] + message = modules.search(postback_payload, postback=True) + if message is not None: payload = { 'recipient': { 'id': sender }, - 'message': modules.search(postback, postback=True) + 'message': message } r = requests.post('https://graph.facebook.com/v2.6/me/messages', params={'access_token': ACCESS_TOKEN}, json=payload) return '' # 200 OK diff --git a/modules/__init__.py b/modules/__init__.py index 30165912..6bca602e 100644 --- a/modules/__init__.py +++ b/modules/__init__.py @@ -1,4 +1,5 @@ import config +import json import os import requests import sys diff --git a/templates/quick_replies.py b/templates/quick_replies.py new file mode 100644 index 00000000..682f9371 --- /dev/null +++ b/templates/quick_replies.py @@ -0,0 +1,18 @@ +from copy import deepcopy as copy + +QUICK_REPLIES_LIMIT = 10 +TITLE_CHARACTER_LIMIT = 20 +PAYLOAD_CHARACTER_LIMIT = 1000 + +def add_quick_reply(message, title='', payload=''): + message_with_quick_reply = copy(message) + if 'quick_replies' not in message_with_quick_reply: + message_with_quick_reply['quick_replies'] = [] + if len(message_with_quick_reply['quick_replies']) < QUICK_REPLIES_LIMIT: + quick_reply = {} + # TODO: location + image_url + quick_reply['content_type'] = 'text' + quick_reply['title'] = title[:TITLE_CHARACTER_LIMIT] + quick_reply['payload'] = payload[:PAYLOAD_CHARACTER_LIMIT] + message_with_quick_reply['quick_replies'].append(quick_reply) + return message_with_quick_reply