Slack API: rtm.start works but rtm.connect doesn't in slack_sdk.rtm_v2

514 views Asked by At

TL;DR: Trying to make a Slack bot in Python using slack_sdk.rtm_v2. rtm.start works but rtm.connect doesn't, even though they are presented as doing pretty much the same thing except for the amount of info returned. Why?


I'm trying to make a Slack bot in Python that listens to a channel and answers different things when it recognizes a message as a command. I must say I'm a bit confused by their online documentation. It's very disorganized and scattered across several websites (slack.dev, api.slack.com, ...). Examples using premade methods are provided, but the documentation talks mostly about the JSON strings sent and received by these methods, not how to use the methods themselves. (If someone from Slack reads this, I think there is room for improvement.)

From what I gathered, there is the old slackclient API and the newer slack_sdk, which itself contains the rtm and the rtm_v2 APIs. (Pretty annoying because the answers you're looking for on forums have about 2/3 chances of being for an API you're not using!) It says at different places that building bots with slack_sdk.rtm_v2 works, but still requires a classic Slack app instead of a newer app.

I tried the first example on this page, which works for me:

import os
from slack_sdk.rtm_v2 import RTMClient

rtm = RTMClient(token=os.environ["SLACK_BOT_TOKEN"])

@rtm.on("message")
def handle(client: RTMClient, event: dict):
    if 'Hello' in event['text']:
        channel_id = event['channel']
        thread_ts = event['ts']
        user = event['user'] # This is not username but user ID (the format is either U*** or W***)

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

rtm.start()

On other pages (for example this one, this one, and this one), rtm.start and rtm.connect are presented as accomplishing pretty much the same thing, except that rtm.start returns more information and therefore yields more traffic. For this reason, they recommend rtm.connect.

Here's my problem, when I replacertm.start with rtm.connect in the above example, my script stops after a second, without any message or error. What's going on?

0

There are 0 answers