钉钉-自定义机器人接入

  • 适用场景

  在平常工作中,项目中的通知文案、代码中的异常捕获,一些不需要交互(机器人无法应答)的通知,可以通过钉钉机器人发送到指定群内。

  • 群内创建机器人

    • 选择群 -> 【群设置】-> 【智能群助手】

                 

    • 【机器人管理】-> 【添加机器人】-> 自定义

           

                 

    • 设置

         

    • 安全设置 参考官网: https://open.dingtalk.com/document/robots/customize-robot-security-settings
      • 自定义关键词: 发送消息时,通知内容要包换关键字其中之一,否则看不到提醒;
      • 加签: 加密数据
      • IP地址段: 来自对应IP范围内的数据才能处理
    • 保存webhook 

       

  • 代码测试

    • 错误的简单的文本信息

import requests


def send_msg(webkook, content):
    response = requests.post(
        webkook,
        json=dict(
            msgtype="text",
            text={"content": content}
        )
    )
    print(response.text)


if __name__ == '__main__':
    webkook = "https://oapi.dingtalk.com/robot/send?access_token=xxx"
    send_msg(webkook, "这是条文本")

# ==============
# 返回信息: 未找到自定义关键词,需要上文中的自定义关键词
{"errcode":310000,"errmsg":"keywords not in content, more: [https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq]"}
    • 简单的文本信息

import requests


def send_msg(webkook, content):
    response = requests.post(
        webkook,
        json=dict(
            msgtype="text",  # 表示文本格式
            text={"content": content}
        )
    )
    print(response.text)


if __name__ == '__main__':
    webkook = "https://oapi.dingtalk.com/robot/send?access_token=xxxx"
    send_msg(webkook, "这是条测试数据")
#
# 返回信息: {"errcode":0,"errmsg":"ok"} 表示发送成功,群内也有对应信息
    • markdown类型

import requests


def send_msg_by_md(webkook, content):
    response = requests.post(
        webkook,
        json=dict(
            msgtype="markdown",  # 格式
            markdown=dict(
                title="玩在一起(测试)",  # 对话框显示的信息
                text=content
            )
        )
    )
    print(response.text)


if __name__ == '__main__':
    webkook = "https://oapi.dingtalk.com/robot/send?access_token=xxx"
    content = """### 这是*玩ba*的**标题** \n\n
> ![图片](https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F0144685cc00565a801208f8bbbd26c.jpg%401280w_1l_2o_100sh.jpg&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1657783778&t=dc7eaf99bed1f485c855c5af1ec09b00)\n\n
> [一起玩吧](http://www.moqipobing.com/)
"""
    send_msg_by_md(webkook, content)
  • 注意

  1分钟内只能发送20条dingding 消息(解决条数限制后期会更新)

 

posted @ 2022-06-14 15:46  Simba辛巴  阅读(369)  评论(0)    收藏  举报