轻松将chatbot与slack-app集成

时间:2019-04-01 09:36:21

标签: python-3.x slack-api

我有一个ChatBot应用程序正在运行,只是想用Slack-api作为它的界面来挂接该应用程序。

我使用了Slack RTM并通过其松弛用户ID维护了用户会话。

最终解决并编写了一个可以轻松连接到任何对话引擎的客户端(API)。

Github回购链接- https://github.com/csemanmohan/Slack_api_client

import time
import re
from slackclient import SlackClient
import requests

# 'url', chatbot endpoint and 'slack_token' is slack application user-access-token
url = "http://127.0.0.1:****/*******/v2/api"
slack_token = "xoxb-**********-***********-*************lipO8hoI"

# instantiate Slack client
slack_client = SlackClient(slack_token)

# starterbot's user ID in Slack: value is assigned after the bot starts up
starterbot_id = None

# constants
RTM_READ_DELAY = 1  # 1 second delay between reading from RTM
EXAMPLE_COMMAND = "do"
MENTION_REGEX = "^<@(|[WU].+?)>(.*)"


def parse_bot_commands(slack_events):
    """
        Parses a list of events coming from the Slack RTM API to find bot commands.
        If a bot command is found, this function returns a tuple of command and channel.
        If its not found, then this function returns None, None.
    """
    # below var msg and channel_var will be used/
    # when no trigger(@app-name) passed from application
    msg = ""
    channel_def = ""
    for event in slack_events:
        if event["type"] == "message" and not "subtype" in event:
            msg = event["text"]
            channel_def = event["channel"]
            user_id, message = parse_direct_mention(event["text"])
            print("there is an event here...", user_id, message)
            if user_id == starterbot_id:
                return message, event["channel"]
    channel_def = channel_def
    return msg, channel_def


def parse_direct_mention(message_text):
    """
        Finds a direct mention (a mention that is at the beginning) in message text
        and returns the user ID which was mentioned. If there is no direct mention, returns None
    """
    matches = re.search(MENTION_REGEX, message_text)
    # the first group contains the username, the second group contains the remaining message
    return (matches.group(1), matches.group(2).strip()) if matches else (None, None)


def handle_command(command, channel):
    """
        Executes bot command if the command is known
    """
    # Default response is help text for the user
    default_response = "Not sure what you mean. Try *{}*.".format(EXAMPLE_COMMAND)

    # Implemented below code-snippet for making API call to ChatBot
    input_text = command
    payload = {"text": input_text, "email": "manmohan@m******.com"}
    headers = {'content-type': "application/json"}
    resp = requests.request("POST", url, json=payload, headers=headers)
    result = eval(resp.json())
    print("result is: ", result)
    response = result['text']

    # Sends the response back to the channel
    slack_client.api_call(
        "chat.postMessage",
        channel=channel,
        text=response or default_response
    )


if __name__ == "__main__":
    if slack_client.rtm_connect(with_team_state=False):
        print("Starter Bot connected and running!")
        # Read bot's user ID by calling Web API method `auth.test`
        starterbot_id = slack_client.api_call("auth.test")["user_id"]
        while True:
            command, channel = parse_bot_commands(slack_client.rtm_read())
            if command:
                handle_command(command, channel)
            time.sleep(RTM_READ_DELAY)
    else:
        print("Connection failed. Exception traceback printed above.")

0 个答案:

没有答案