SlackClient Python RTM 未捕获消息

SlackClient Python RTM not capturing messages

我想编写一个简单的 slack 机器人,它可以响应给定的字符串来提及@,但是我无法使官方文档代码正常工作。

我已将所有 OAuth 权限授予机器人并具有以下代码:

from slack import RTMClient

@RTMClient.run_on(event="message")
def gravity_bot(**payload):
    data = payload['data']
    print(data.get('text'))

try:
    rtm_client = RTMClient(
        token="my_token_auth_code",
        connect_method='rtm.start'
    )
    print("Bot is up and running!")
    rtm_client.start()
except Exception as err:
    print(err)

我认为连接已建立,因为“Bot 已启动并且 运行”消息出现,但是在 slack channel 上,bot 似乎处于离线状态,而且我无法在终端,不适用于直接消息,即使在邀请机器人加入给定频道后也不适用于频道消息。

抱歉不能放过这个。我想通了,步骤如下:

  1. 在 Slack 中创建一个“经典”应用程序(这是获得适当范围的唯一方法),只需单击此 link:https://api.slack.com/apps?new_classic_app=1
  2. 在“添加特性和功能”选项卡中点击“机器人”:

  1. 单击“添加旧版机器人用户”按钮(这将添加您需要但无法手动添加的“rtm.stream”范围)

  1. 从基本信息页面,在工作区中安装您的应用程序
  2. 从 OAuth 和权限页面,复制“机器人用户 OAuth 访问令牌”(底部的那个)
  3. 运行 以下代码(文档中代码的略微修改版本)
from slack_sdk.rtm import RTMClient

# This event runs when the connection is established and shows some connection info
@RTMClient.run_on(event="open")
def show_start(**payload):
    print(payload)

@RTMClient.run_on(event="message")
def say_hello(**payload):
    print(payload)
    data = payload['data']
    web_client = payload['web_client']
    if 'Hello' in data['text']:
        channel_id = data['channel']
        thread_ts = data['ts']
        user = data['user']

        web_client.chat_postMessage(
            channel=channel_id,
            text=f"Hi <@{user}>!",
            thread_ts=thread_ts
        )

if __name__ == "__main__":
    slack_token = "<YOUR TOKEN HERE>"
    rtm_client = RTMClient(token=slack_token)
    rtm_client.start()

上一个回答:

Hmm, this is tricky one... According to the docs this only works for "classic" Slack apps, so that might be the first pointer. It explicitly says that you should not upgrade your app. Furthermore, you'll need to set the right permissions (god knows which ones) by selecting the "bot" scope.

Honestly, I haven't been able to get this running. Looks like Slack is getting rid of this connection method, so you might have more luck looking into the "Events API". I know it's not the ideal solution because its not as real-time, but it looks better documented and it will stay around for a while. Another approach could be polling. Its not sexy but it works...

My guess is that your problem is that there is not a valid connection, but there is no proper error handling in the Slack library. The message is printed before you actually connect, so that doesn't indicate anything.