Skip to content

Instantly share code, notes, and snippets.

@edonosotti
Last active December 15, 2020 10:22
Show Gist options
  • Save edonosotti/6cad23aaccea4e1b415fe6f1d18c1030 to your computer and use it in GitHub Desktop.
Save edonosotti/6cad23aaccea4e1b415fe6f1d18c1030 to your computer and use it in GitHub Desktop.
How to integrate Chatbase in a Python project.
# Integrating Chatbase in your chatbot - Python version
#
# The purpose of this code is to show how to integrate the Chatbase service in any chatbot.
#
# See my article on Chatbots Magazine for details:
# https://chatbotsmagazine.com/advanced-chatbot-analytics-and-sentiment-analysis-part-1-17a8e674d7e1
#
# License: MIT (https://opensource.org/licenses/MIT) (C) Edoardo Nosotti, 2017
from chatbase import Message, MessageSet, MessageTypes, InvalidMessageTypeError
api_key = 'APIKEY' # Chatbase API key
platform = 'facebook-or-whatever' # Chat platform name
message_user = 'Do you know the time, please?' # User message
message_bot = 'It's 12 o'clock!' # Bot response message
intent = 'ASK-CURRENT-TIME' # This should be actually decoded from the user message!
version = '1' # Bot version, useful if you want to mark them for A/B testing or compare results across versions
user_id = 'facebook-user-XYZ' # User ID on the chat platform, or custom ID
time_stamp = int(round(time.time() * 1e3)) # Mandatory
# Create an instance of MessageSet to collect all the messages
message_set = MessageSet(api_key=api_key, platform=platform,
version=version, user_id=user_id)
# Create an instance of Message for the user message and set values in the constructor
msg1 = Message(api_key=api_key, platform=platform, message=message,
intent=intent, version=version, user_id=user_id,
type=MessageTypes.USER, not_handled=True,
time_stamp=time_stamp)
# Set the message as "handled" because the NLP was able to successfully decode the intent
msg1.set_as_feedback()
# Create an instance of Message for the bot response message and set values in the constructor
msg2 = Message(api_key=api_key, platform=platform, message=message,
version=version, user_id=user_id,
type=MessageTypes.AGENT)
message_set = MessageSet(api_key=api_key, platform=platform,
version=version, user_id=user_id)
# Push messages into the collection (MessageSet)
message_set.append_message(msg1)
message_set.append_message(msg2)
# Send the messages
response = message_set.send()
# response.status_code will be 200 if sending worked
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment