首页 > 解决方案 > 如何让 Python Slack 机器人在线程内回复?

问题描述

如果我将命令发布在一个线程中,我正在尝试让我的 Python Slack 机器人自动在一个线程中回复。但是,无论我在哪里发布我的命令 - 在线程中或其他地方,它仍然作为一般消息回复。

我希望让它在一个线程中回复。到目前为止,这是我的代码(为简洁起见,我截断了大部分初始化和启动代码):

import os, time, re, inspect, functools
from slackclient import SlackClient

class Bot(object):
    def __init__(self, token): 
        ...

    def startup(self):
        ...

    def parse_bot_commands(self, 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.
        """
        for event in slack_events:
            if event["type"] == "message" and not "subtype" in event:
                user_id, message = self.parse_direct_mention(event["text"])
                if user_id == self.starterbot_id:
                    return message, event["channel"]
        return None, None

    def parse_direct_mention(self, 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(self.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(self, 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(self.EXAMPLE_COMMAND)

        # Finds and executes the given command, filling in response
        response = None

        # NOTE: This is where you start to implement more commands!
        if command.lower().startswith("roll"):
            response = 'Rock and Roll!"

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

'''START THE BOT!'''
#Initialize the token (when installing the app)
bot = Bot('xxx-xxx')
bot.startup()

标签: pythonslackslack-api

解决方案


斜线命令在线程中无法正常工作。它是一个已知问题,迄今为止尚未解决。

另请参阅此答案:Slack 机器人可以获取发送斜杠命令的线程 id 吗?


推荐阅读