钉钉开发结合Python实现批量推送信息

基于钉钉开放平台,创建应用,授权成员信息读权限,调用企业API基础权限,通过py调用api接口实现企业内部批量推送信息。新建Excel文件,A,B列标题分别为 userid,消息内容。第二行你开始填写需要被推送用户的钉钉ID,及要推送的文本。将脚本和Excel文件放在同一目录执行脚本,即可实现批量推送。

以下是代码示例:

import requests
from openpyxl import load_workbook

# 钉钉配置(替换为你自己的值)
APP_KEY = "AppKey"          # 开放平台应用的AppKey
APP_SECRET = "AppSecret"   # 开放平台应用的AppSecret
AGENT_ID = "AgentId"           # 应用详情页中的AgentId

def get_access_token():
    url = f"https://oapi.dingtalk.com/gettoken?appkey={APP_KEY}&appsecret={APP_SECRET}"
    response = requests.get(url)
    return response.json().get("access_token")
def send_dingtalk_message(userid, content, token):
    url = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2"
    headers = {"Content-Type": "application/json"}
    data = {
        "agent_id": AGENT_ID,
        "userid_list": userid,
        "msg": {
            "msgtype": "text",
            "text": {"content": content}
        }
    }
    response = requests.post(
        url,
        json=data,
        params={"access_token": token},
        headers=headers
    )
    return response.json()
def push_from_excel(file_path):
    wb = load_workbook(file_path)
    ws = wb.active
    token = get_access_token()
    for row in ws.iter_rows(min_row=2, values_only=True):
        userid = str(row[0]).strip()
        content = str(row[1]) if row[1] else "(空内容)"
        print(f"准备推送 -> UserID: '{userid}' (类型: {type(userid)}, 长度: {len(userid)}), 内容: '{content}'")
        result = send_dingtalk_message(userid, content, token)
        print(f"推送结果: {result}\n")
if __name__ == "__main__":
    excel_file = "人员消息列表.xlsx"  # 替换为你的Excel文件路径
    print(f"开始处理Excel文件: {excel_file}")
    push_from_excel(excel_file)
    print("处理完成!")
Language
中文(简体) 中文(繁體) 日本語 한국어 русский English français Deutsch español italiano বাংলা (ভারত) العربية ไทย Tiếng Việt Bahasa Melayu Filipino ελληνικά magyar dansk norsk íslenska Gaeilge