You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新版Slack应用能否使用presence_query?Python实现咨询

新版Slack应用(Python)查询用户在线状态的方法

核心结论

新版Slack应用无法使用presence_query——该方法依赖已废弃的RTM API,而RTM仅支持旧版经典应用,新版应用无法获取对应的bot权限。

替代方案:使用Slack Web API与Events API

新版应用需通过Web API查询状态,或通过Events API监听实时状态变化,以下是具体实现:

1. 单次/批量查询用户在线状态

使用users.getPresence Web API方法,支持单个用户查询,批量查询需循环调用(注意API调用频率限制):

import time
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

# 初始化Web客户端
client = WebClient(token="xoxb-YOUR-BOT-TOKEN")

# 示例:批量查询用户状态
target_user_ids = ["U12345678", "U87654321", "U11223344"]

for user_id in target_user_ids:
    try:
        # 调用API获取用户状态
        response = client.users_getPresence(user=user_id)
        print(f"用户 {user_id} 状态: {response['presence']}")
        print(f"是否自动离开: {response['auto_away']}")
        time.sleep(1)  # 避免触发Slack的请求频率限制
    except SlackApiError as e:
        print(f"查询用户 {user_id} 失败: {e.response['error']}")

2. 实时监听用户状态变化

通过Events API的presence_change事件,实时接收用户状态更新:

from slack_sdk import App
from slack_sdk.errors import SlackApiError

# 初始化App客户端
app = App(token="xoxb-YOUR-BOT-TOKEN")

# 监听状态变化事件
@app.event("presence_change")
def handle_presence_update(event):
    user_id = event["user"]
    new_status = event["presence"]
    print(f"用户 {user_id} 的状态更新为: {new_status}")

if __name__ == "__main__":
    # 启动本地服务(默认端口3000),需在Slack应用后台配置事件订阅的请求URL
    app.start(port=3000)

必要权限配置

在Slack应用后台的OAuth & Permissions页面,需添加以下权限并重新安装应用到工作区:

  • users:read
  • users:read.presence

内容的提问来源于stack exchange,提问作者Or Yair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 00:45:35