python-slackclient
Go to GitHub

Real Time Messaging (RTM)

The Real Time Messaging (RTM) API is a WebSocket-based API that allows you to receive events from Slack in real time and send messages as users.

If you prefer events to be pushed to your app, we recommend using the HTTP-based Events API instead. The Events API contains some events that aren’t supported in the RTM API (like the app_home_opened event), and it supports most of the event types in the RTM API. If you’d like to use the Events API, you can use the Python Slack Events Adaptor.

The RTMClient allows apps to communicate with the Slack Platform’s RTM API.

The event-driven architecture of this client allows you to simply link callbacks to their corresponding events. When an event occurs this client executes your callback while passing along any information it receives. We also give you the ability to call our web client from inside your callbacks.

In our example below, we watch for a message event that contains “Hello” and if its recieved, we call the say_hello() function. We then issue a call to the web client to post back to the channel saying “Hi” to the user.

Connecting to the RTM API

import os
from slack import RTMClient

@RTMClient.run_on(event="message")
def say_hello(**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
    )

slack_token = os.environ["SLACK_API_TOKEN"]
rtm_client = RTMClient(token=slack_token)
rtm_client.start()

rtm.start vs rtm.connect

By default, the RTM client uses rtm.connect to establish a WebSocket connection with Slack. The response contains basic information about the team and WebSocket url. If you’d rather use rtm.start to establish the connection, which provides more information about the conversations and users on the team, you can set the connect_method option to rtm.start when instantiating the RTM Client. Note that on larger teams, use of rtm.start can be slow and unreliable.

import os
from slack import RTMClient

@RTMClient.run_on(event="message")
def say_hello(**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
    )

slack_token = os.environ["SLACK_API_TOKEN"]
rtm_client = RTMClient(
  token=slack_token,
  connect_method='rtm.start'
)
rtm_client.start()

Read the rtm.connect docs and the rtm.start docs for more details.

RTM Events

{
  'type': 'message',
  'ts': '1358878749.000002',
  'user': 'U023BECGF',
  'text': 'Hello'
}

See RTM Events for a complete list of events.