1

I have a ChatBot application running, just want to hook this application with Slack-api as it's interface.

I used Slack RTM and maintained user-session with its slack user-id.

finally solved and written a client(API) which can easily connect to any conversation engine.

Github repo link- 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.")
Manmohan
  • 31
  • 4
  • question is really broad... – vi_me Apr 01 '19 at 09:48
  • Possible duplicate of [Can Hubot Slack bot store sessions](https://stackoverflow.com/questions/50981370/can-hubot-slack-bot-store-sessions) – Erik Kalkoken Apr 01 '19 at 14:00
  • Hi @Manmohan! Thanks for your question. I took the liberty to to edit your title to better reflect your main question about user sessions with Slack. And also added the link to my general answer on the topic. Please let us know if that answer solved your problem. – Erik Kalkoken Apr 01 '19 at 14:05
  • Erik- Thanks, You got me correct. But handling user session was one among my problems. I did pull current slack user-id and maintained session with the same. – Manmohan Apr 02 '19 at 13:55

0 Answers0