Created
April 25, 2017 13:11
-
-
Save yrezgui/b31730e658e2ab79d432350eeef207d3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
conversation = ConversationV1( | |
username=os.environ["CONVERSATION_USERNAME"], | |
password=os.environ["CONVERSATION_PASSWORD"], | |
version='2016-09-20') | |
# 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"] | |
# message = "Hello <@%s>! :tada:" % message["user"] | |
WORKSPACE_ID = os.environ["CONVERSATION_WORKSPACE"] | |
response = conversation.message(workspace_id=WORKSPACE_ID, message_input={ | |
'text': message.get('text')}) | |
# if response["intents"][0]["intent"] == "book-flight": | |
# if len(response["entities"]) > 0 and response["entities"][0]["entity"] == "Airports": | |
# message = "Do you want to fly to " + response["entities"][0]["value"] | |
# else: | |
# message = "Where do you want to fly?" | |
# else: | |
# message = "Hi " + message["user"] | |
# formatted_resp = "```" + response + "```" | |
if len(response["output"]["text"]) > 0: | |
message = response["output"]["text"][0] | |
else: | |
message = "Hi " + message["user"] | |
CLIENT.api_call("chat.postMessage", channel=channel, text=message) | |
# 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