Example: Chatlog webhook

This example contains a Python Flask-RESTful app that receives a webhook from Kindly. Upon receiving the webhook payload, the app sends a request to the Kindly API to get the entire chat log for the relevant conversation up to that point.

import os
import pprint

import requests

from flask import Flask
from flask_restful import Api, Resource, reqparse

app = Flask(__name__)
api = Api(app)

parser = reqparse.RequestParser()
parser.add_argument('message', type=str)
parser.add_argument('chatlog_api_url', type=str)


# Get your app key on the "Connect" page in the platform
KINDLY_API_KEY = os.environ.get('KINDLY_API_KEY')


class CreateTicketAPI(Resource):
    def post(self):
        """
        Incoming webhook from Kindly
        The request body is going to contain several fields,
        but the only one we're interested in right now is `_links` and the nested field `chat`.
        """

        args = parser.parse_args()
        chatlog_api_url = args._links.chat

        api_response = requests.get(
            url=chatlog_api_url,
            headers={
                'Authorization': KINDLY_API_KEY,
            }
        )

        if api_response.status_code != 200:
            # Uh-oh, did you set the right key?
            return {
                'reply': "Oops, something went wrong"
            }

        """
        parse the data in the response
        """
        chatlog = api_response.json()

        """
        chat log should look something like this:
        {
            'chat': {
                'active': True,
                'bot_id': 4,
                'bot_name': 'webhook',
                'comments': [],
                'context': {'email': 'me@example.com'},
                'created': '2017-12-20T10:18:04.558000Z',
                'first_name': None,
                'full_name': None,
                'gender': None,
                'id': '<CHAT ID>',
                'language_code': 'en',
                'last_name': None,
                'recipient_id': '<USER ID>',
                'source': 'chatbubble',
                'state': 'chatting',
                'taken_over': None,
                'updated': '2017-12-20T10:18:14.955000Z',
                'messages': [
                    {
                        'buttons': [],
                        'created': '2017-12-20T10:18:07.912000Z',
                        'exchange_id': None,
                        'exchange_type': None,
                        'from_bot': False,
                        'id': '5a3a38dfd923ba4238c70caa',
                        'message': 'create ticket',
                        'name': 'You'
                    },
                    {
                        'buttons': [],
                        'created': '2017-12-20T10:18:08.057000Z',
                        'exchange_id': '7f8601f0-b986-4acb-92f3-87b860f551d5',
                        'exchange_type': 'usersays',
                        'from_bot': True,
                        'id': '5a3a38e0d923ba4238c70cab',
                        'message': 'What is your email?',
                        'name': 'webhook'
                    },
                    {
                        'buttons': [],
                        'created': '2017-12-20T10:18:14.938000Z',
                        'exchange_id': None,
                        'exchange_type': None,
                        'from_bot': False,
                        'id': '5a3a38e6d923ba4238c70cac',
                        'message': 'me@example.com',
                        'name': 'You'
                    },
                    {
                        'buttons': [],
                        'created': '2017-12-20T10:18:14.949000Z',
                        'exchange_id': '9c7bae1f-7bb3-4bb3-9782-1a9f77e356dc',
                        'exchange_type': 'usersays',
                        'from_bot': True,
                        'id': '5a3a38e6d923ba4238c70cad',
                        'message': 'OK, creating ticket now.',
                        'name': 'webhook'
                    }
                ]
            }
        }
        """

        """
        Do what you want to do with the chatlog data
        """
        pprint.pprint(chatlog)

        """
        This example uses synchronous Python code, returning a response to the chat client at the very end.
        If the task you want to perform takes a little time, it might be wise to do the task asynchronously
        and return a response to the chat client ASAP.
        """

        return {
            # You can leave out the reply if you want, just make sure you send a 200 OK response
            'reply': "Ticket created. Check your inbox ({email}) for updates.".format(email=chatlog['chat']['context']['email']),
        }


api.add_resource(CreateTicketAPI, '/create_ticket/')

if __name__ == '__main__':
    app.run(debug=True, port=3333)

Last updated