钉钉机器人简单使用示例

我们在进行定时任务的时候,很多时候都想要及时的知道程序的运行情况。我们可用钉钉来提示我们,任务开始了,任务结束了,任务报错了等

一、 创建钉钉机器人

基于下图路径在群中添加机器人

群设置
智能群助手
添加机器人
自定义
机器人名
自定义关键词
完成, 复制Webhook

二、通过钉钉机器人发送消息

发送的整个流程如下

构建发送的消息的dict
转换成json
通过request向webhook中发送信息
钉钉收到消息

在钉钉的gitHub上可以看到,总共有5种消息方式。

  • DingTalkNotificationText
  • DingTalkNotificationLink
  • DingTalkNotificationMarkdown
  • DingTalkNotificationActionCard
  • DingTalkNotificationButton

这里仅仅以DingTalkNotificationText的结构进行消息发送,对markdwon比较热衷的小伙伴可以试试用markdown进行消息

import json
import requests
def dingding_msg(msg, key_word='success'):
    """通过钉钉机器人发送消息
    构建发送的消息的dict -> 转换成json -> 通过request向webhook中发送信息 -> 钉钉收到消息
    数据结构参考源码:
    https://github.com/timonwong/prometheus-webhook-dingtalk/blob/main/pkg/models/dingtalk.go
    """
    headers = {'Content-Type': 'application/json; charset=utf-8'}
    data = {
        "msgtype": "text",
        "text" : {"content": f'{key_word} | {msg}'},
        "at" : {"atMobiles": ["mobile-phone"], "isAtAll": False}
    }
    post_data = json.dumps(data)
    webhook = "https://oapi.dingtalk.com/robot/send?access_token=*****"
    return requests.post(webhook, headers=headers, data=post_data)

dingding_msg('haha')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Scc_hy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值