Skip to content

Instantly share code, notes, and snippets.

@yrezgui
Last active May 19, 2017 07:16
Show Gist options
  • Save yrezgui/767f3dbe90da1a2b35cf6aa4a2b33fd9 to your computer and use it in GitHub Desktop.
Save yrezgui/767f3dbe90da1a2b35cf6aa4a2b33fd9 to your computer and use it in GitHub Desktop.
from slackeventsapi import SlackEventAdapter
from slackclient import SlackClient
from flask import request
import os
from watson_developer_cloud import ConversationV1
# We'll store the SlackClient instances for each team in a
# dictionary, so we can have multiple teams authed
CLIENTS = {}
# Our app's Slack Event Adapter for receiving actions via the Events API
SLACK_VERIFICATION_TOKEN = os.environ["SLACK_VERIFICATION_TOKEN"]
slack_events_adapter = SlackEventAdapter(SLACK_VERIFICATION_TOKEN, "/slack/events")
# Slack bot user credentials
SLACK_BOT_TOKEN = os.environ["SLACK_BOT_TOKEN"]
# Create a SlackClient for your bot to use for Web API requests
CLIENT = SlackClient(SLACK_BOT_TOKEN)
# Watson Conversation API credentials
CONVERSATION_USERNAME = os.environ["CONVERSATION_USERNAME"]
CONVERSATION_PASSWORD = os.environ["CONVERSATION_PASSWORD"]
CONVERSATION_WORKSPACE = os.environ["CONVERSATION_WORKSPACE"]
CONVERSATION_URL = os.environ["CONVERSATION_URL"]
# Create Watson Conversation API instance
conversation = ConversationV1(
username=CONVERSATION_USERNAME,
password=CONVERSATION_PASSWORD,
version='2016-09-20',
url=CONVERSATION_URL
)
conversation.CONTEXT = {
"favorite_food": "french"
}
# Example responder to greetings
@slack_events_adapter.on("message")
def handle_message(event_data):
message = event_data["event"]
# If the incoming message contains "hi", then respond with a "Hello" message
if message.get("subtype") is None:
channel = message["channel"]
# Analyse message content with Watson Conversation
response = conversation.message(
workspace_id = CONVERSATION_WORKSPACE,
message_input = { 'text': message.get('text') },
context = conversation.CONTEXT
)
conversation.CONTEXT = response["context"]
if response["output"]["text"]:
for answer in response["output"]["text"]:
CLIENT.api_call("chat.postMessage", channel=channel, text=answer)
else:
CLIENT.api_call("chat.postMessage", channel=channel, text="Sorry I didn't get that")
# Example reaction emoji echo
@slack_events_adapter.on("reaction_added")
def reaction_added(event_data):
event = event_data["event"]
emoji = event["reaction"]
channel = event["item"]["channel"]
text = ":%s:" % emoji
CLIENT.api_call("chat.postMessage", channel=channel, text=text)
# Once we have our event listeners configured, we can start the
# Flask server with the default `/events` endpoint on port 3000
slack_events_adapter.start(port=3000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment