SlackClient Python RTM不捕获消息

2024-09-28 22:20:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我向bot授予了所有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已启动并运行”消息,但是在空闲通道上,到Bot的连接似乎处于脱机状态,而且我无法在终端中获得任何响应,无法获得直接消息,甚至在邀请Bot到给定通道后也无法获得通道消息


Tags: 代码clienttoken消息databot机器人slack
1条回答
网友
1楼 · 发布于 2024-09-28 22:20:16

对不起,我不能让这件事过去。。我找到了答案,以下是步骤:

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

Add the bot features

  1. 单击“添加遗留Bot用户”按钮(这将添加您需要的“rtm.stream”范围,但无法手动添加)

Legacy bot user

  1. 从“基本信息”页面,在工作区中安装应用程序
  2. 来自OAuth&;权限页,复制“Bot用户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.

相关问题 更多 >