获取MS Teams用户状态及最后上线时间的方法
获取Microsoft Teams用户在线状态及离线时长的方法
核心实现思路
你可以通过Microsoft Graph的Presence API结合时间计算来实现需求,具体步骤如下:
调用Presence API获取基础数据
- 单个用户查询:调用接口
GET /users/{userId}/presence - 批量用户查询:调用接口
GET /communications/presences/getPresencesByUserIds(适合团队成员批量查询) - 接口返回的关键字段:
availability:用户当前状态(如Available在线、Away离开等)lastActiveDateTime:用户最后活跃的UTC时间戳
- 单个用户查询:调用接口
计算离开状态时长
- 当
availability为Away时,用当前UTC时间减去lastActiveDateTime的时间戳,得到的时间差就是用户处于离开状态的时长。 - 示例逻辑(伪代码):
from datetime import datetime, timezone # 假设接口返回的lastActiveDateTime为字符串格式 last_active = datetime.fromisoformat(last_active_str.replace('Z', '+00:00')).astimezone(timezone.utc) current_time = datetime.now(timezone.utc) duration = current_time - last_active if duration.total_seconds() >= 900: # 900秒=15分钟 print(f"用户状态:离开,已离开时长:{duration.total_seconds()//60}分钟")
- 当
注意事项
- 时区处理:
lastActiveDateTime是UTC时间,计算时务必统一使用UTC时间,避免时区偏差导致时长计算错误。 - 权限配置:需要在Azure AD中为应用配置
Presence.Read.All(批量查询)或Presence.Read(单个用户)权限,授权类型支持应用权限或委派权限。 - 接口限制:注意Graph API的调用频率限制,批量查询时合理控制请求规模。
内容的提问来源于stack exchange,提问作者Sigar Dave
相关产品推荐
相关产品推荐

