【问题标题】:How to get Python Slack bot to reply within a thread?如何让 Python Slack 机器人在线程内回复?
【发布时间】:2019-11-08 21:20:23
【问题描述】:

如果我在一个线程中发布命令,我正在尝试让我的 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()

【问题讨论】:

    标签: python slack slack-api


    【解决方案1】:

    斜线命令在线程中无法正常工作。这是一个已知问题,目前尚未解决。

    另请参阅此答案:Can a Slack bot get the thread id that a slash command was sent from?

    【讨论】:

    • 这篇文章谈到了消息的“thread_ts”属性。关于如何访问消息属性的任何想法?
    • 两种主要方式是:发送chat.postMessage 或监听消息事件。您将收到可能包含该属性的消息对象
    • 查看官方线程页面了解所有详细信息:api.slack.com/docs/message-threading
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 2017-09-20
    • 2018-10-22
    • 2016-08-15
    • 2019-04-16
    • 2020-07-06
    • 1970-01-01
    相关资源
    最近更新 更多