用python向钉钉群发送消息

具体的设置参见这个

https://blog.csdn.net/zy215215/article/details/145724045

过程讲的非常清楚了。

官方的文档在这里:

https://open.dingtalk.com/document/robots/custom-robot-access

示例代码下载:

https://open.dingtalk.com/document/orgapp/custom-bot-to-send-group-chat-messages?spm=ding_open_doc.document.0.0.1d1c5e59Rev7fa

官方的代码

我进行了一点小修改。

比较简单。

复制代码
# !/usr/bin/env python3

import argparse
import logging
import time
import hmac
import hashlib
import base64
import urllib.parse
import requests

def setup_logger():
    logger = logging.getLogger()
    handler = logging.StreamHandler()
    handler.setFormatter(
        logging.Formatter('%(asctime)s %(name)-8s %(levelname)-8s %(message)s [%(filename)s:%(lineno)d]'))
    logger.addHandler(handler)
    logger.setLevel(logging.INFO)
    return logger


def define_options():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--access_token', dest='access_token',# required=True,
        help='机器人webhook的access_token from https://open.dingtalk.com/document/orgapp/obtain-the-webhook-address-of-a-custom-robot '
    )
    parser.add_argument(
        '--secret', dest='secret', #required=True,
        help='secret from https://open.dingtalk.com/document/orgapp/customize-robot-security-settings#title-7fs-kgs-36x'
    )
    parser.add_argument(
        '--userid', dest='userid',
        help='待 @ 的钉钉用户ID,多个用逗号分隔 from https://open.dingtalk.com/document/orgapp/basic-concepts-beta#title-o8w-yj2-t8x '
    )
    parser.add_argument(
        '--at_mobiles', dest='at_mobiles',
        help='待 @ 的手机号,多个用逗号分隔'
    )
    parser.add_argument(
        '--is_at_all', dest='is_at_all', action='store_true',
        help='是否@所有人,指定则为True,不指定为False'
    )
    parser.add_argument(
        '--msg', dest='msg', default='钉钉,让进步发生',
        help='要发送的消息内容'
    )
    return parser.parse_args()


def send_custom_robot_group_message(access_token, secret, msg, at_user_ids=None, at_mobiles=None, is_at_all=False):
    """
    发送钉钉自定义机器人群消息
    :param access_token: 机器人webhook的access_token
    :param secret: 机器人安全设置的加签secret
    :param msg: 消息内容
    :param at_user_ids: @的用户ID列表
    :param at_mobiles: @的手机号列表
    :param is_at_all: 是否@所有人
    :return: 钉钉API响应
    """
    timestamp = str(round(time.time() * 1000))
    string_to_sign = f'{timestamp}\n{secret}'
    hmac_code = hmac.new(secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

    url = f'https://oapi.dingtalk.com/robot/send?access_token={access_token}&timestamp={timestamp}&sign={sign}'

    body = {
        "at": {
            "isAtAll": str(is_at_all).lower(),
            "atUserIds": at_user_ids or [],
            "atMobiles": at_mobiles or []
        },
        "text": {
            "content": msg
        },
        "msgtype": "text"
    }
    headers = {'Content-Type': 'application/json'}
    resp = requests.post(url, json=body, headers=headers)
    logging.info("钉钉自定义机器人群消息响应:%s", resp.text)
    
    print("resp: ", resp.text)
    return resp.json()




# --msg abcdefg
#
def main():
    options = define_options()
    
    options.secret='SEC8************3d'
    options.access_token='a8*********************68'
    
    
    #options.msg="hello world"
    options.is_at_all=True
    
    # 处理 @用户ID
    at_user_ids = []
    if options.userid:
        at_user_ids = [u.strip() for u in options.userid.split(',') if u.strip()]
    # 处理 @手机号
    at_mobiles = []
    if options.at_mobiles:
        at_mobiles = [m.strip() for m in options.at_mobiles.split(',') if m.strip()]
    
    print("send.")
    send_custom_robot_group_message(
        options.access_token,
        options.secret,
        options.msg,
        at_user_ids=at_user_ids,
        at_mobiles=at_mobiles,
        is_at_all=options.is_at_all
    )





if __name__ == '__main__':
    main()
相关推荐
一念一花一世界18 小时前
PostIn零基础学习 - 集成钉钉,使用钉钉扫码登录PostIn
钉钉·postin·接口管理工具
一念一花一世界21 小时前
sourcefare零基础学习 - 集成钉钉,使用钉钉扫码登录sourcefare
钉钉·sourcefare·代码扫描工具
一念一花一世界21 小时前
Arbess零基础学习 - 集成钉钉,使用钉钉扫码登录Arbess
ci/cd·钉钉·arbess
一念一花一世界2 天前
Arbess V2.1.9版本发布,支持Arm64位系统的安装部署,支持自定义消息模版,支持钉钉消息通知
ci/cd·钉钉·arm·arbess
一念一花一世界2 天前
Arbess零基础学习 - 发布流水线提交评审,通过钉钉通知评审人
ci/cd·钉钉·arbess
青靴9 天前
轻量级 CI/CD 实战(四):本地开发钉钉告警 → 自动部署云服务器 Kafka 消费者容器
ci/cd·docker·钉钉
是孑然呀19 天前
【钉钉表单(周/日报)】每天定时发送,实现收集每天信息
钉钉
ζั͡山 ั͡有扶苏 ั͡✾20 天前
完善EKF可观测性体系:基于ElastAlert2构建k8s智能钉钉日志告警系统
容器·kubernetes·钉钉·kibana·filebeat·日志监控
cui_win21 天前
Prometheus实战教程 05 - 告警通知实现 - 邮件 + 钉钉 + 自定义告警模板
钉钉·prometheus·邮件通知
CHN悠远25 天前
debian13 安装钉钉后,钉钉无法运行问题的解决办法
linux·运维·服务器·钉钉·debian13