Python 对接企业微信 API:发送应用消息与部门管理示例

顾言
顾言
发布时间:2026-12-06| 842人浏览过
原创

使用 Python 的 requests 库,先通过企业微信 API 获取 access_token ,再调用消息发送接口或部门管理接口即可完成对接。

Python 对接企业微信 API:发送应用消息与部门管理示例

应用凭证与 Token 获取机制

企业微信所有 API 调用都需要 access_token,它由 corp_id 和 corp_secret 换取。Token 有效期为 7200 秒,建议缓存复用,避免频繁请求触发频率限制。

Python 对接企业微信 API:发送应用消息与部门管理示例

Token 获取接口返回 JSON 包含 errcode、errmsg 和 access_token。若 errcode 不为 0,需检查 corp_id 和 corp_secret 是否正确,或应用是否已授权。实际开发中应封装一个 get_token 函数,并在 token 过期前自动刷新。

发送应用消息与部门列表查询实现

将完整程序保存为 wechat_work.py,运行 python wechat_work.py 即可看到发送消息和获取部门列表的结果。程序默认使用测试用的 CorpID 和 Secret,实际使用时请替换为真实值。

Python 对接企业微信 API:发送应用消息与部门管理示例

import requests

def get_access_token(corp_id, corp_secret):
    url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={corp_secret}"
    response = requests.get(url)
    data = response.json()
    if data.get('errcode') != 0:
        raise Exception(f"Failed to get token: {data.get('errmsg')}")
    return data['access_token']

def send_app_message(token, msg_type, content, agentid, touser="@all", toparty=None, totag=None):
    url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}"
    data = {
        "touser": touser,
        "msgtype": msg_type,
        "agentid": agentid,
        msg_type: content
    }
    if toparty:
        data["toparty"] = toparty
    if totag:
        data["totag"] = totag
    
    response = requests.post(url, json=data)
    result = response.json()
    print(f"Send message result: {result}")
    return result

def get_department_list(token, dept_id=1):
    url = f"https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={token}&id={dept_id}"
    response = requests.get(url)
    data = response.json()
    if data.get('errcode') != 0:
        print(f"Failed to get department list: {data.get('errmsg')}")
        return []
    return data.get('department', [])

if __name__ == "__main__":
    # 请替换为真实的 CorpID 和 Secret
    CORP_ID = "your_corp_id"
    CORP_SECRET = "your_corp_secret"
    AGENT_ID = 1000001  # 请替换为真实的应用 AgentId

    try:
        token = get_access_token(CORP_ID, CORP_SECRET)
        
        # 发送文本消息给所有成员
        text_content = {"content": "Hello from Python!"}
        send_app_message(token, "text", text_content, AGENT_ID, touser="@all")
        
        # 获取部门列表
        depts = get_department_list(token, 1)
        print(f"Departments: {depts}")
        
    except Exception as e:
        print(f"Error: {e}")

程序输出应显示消息发送成功(errcode=0)及部门列表数据。若发送失败,检查 touser 是否为有效用户或部门,以及 agentid 是否正确。部门 ID 传入 1 通常返回根部门及其子部门。

程序演示了如何构造消息体并发送,以及如何查询指定部门的子部门列表。注意消息发送需要指定 agentid,且接收人可以是 userid、departmentid 或 touser(多个用户用 | 分隔)。

touser 参数在部门 ID 场景下的行为差异

当接收人参数设置为部门 ID 时,API 会向该部门下所有成员发送消息,但前提是这些成员必须关注了该企业微信应用。若未关注,则不会收到消息。

在实际使用中,常遇到“消息发送成功但无人收到”的情况。这通常是因为目标部门成员未安装或未关注企业微信应用。排查时应先确认成员状态,而非仅检查 API 返回值。部门 ID 必须是数字类型,且在 JSON 中作为字符串传递时需确保格式正确。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Python

Python

3.15.0 · Windows

Python 官方解释器与标准库,适合 Python 学习和应用开发。

Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。