前言
我们在使用钉钉时,通常会创建或加入多个群聊,身为群聊的管理者,当我们需要及时、并按时的向这些群聊推送一些固定信息,若通过人力来解决肯定非常耗时、耗力,这时我们就可以考虑开发一个自动化脚本来实现这个功能,本篇文章我将教会大家,如何使用python开发程序,实现向钉钉群内自动发送消息。
一、创建钉钉群机器人
-
1、登录钉钉,进入你想要发送消息的群聊。
-
2、点击群聊右上角的“…”图标,选择“群机器人”或“智能群助手”(取决于钉钉的版本和界面更新)。
-
3、点击“添加机器人”,选择“自定义”机器人。
-
4、设置机器人名称,并选择安全设置(通常使用自定义关键词或加签方式)。
这里会出现三种安全设置,如:
自定义关键字词
加签
ip地址(段)
注意:
这里的IP地址(段)必须是公网地址,而不是电脑分配的局域网地址,可以在cmd命令行窗口输入:curl ifconfig.me
来查看当前网络的公网地址,或访问类似 https://whatismyipaddress.com/ 的网站来获取你的当前公网地址。我们只需要选择一种安全设置即可,下面针对不同的安全设置,我会给出不同的代码
- 5、添加机器人后,获取并复制Webhook地址,这个地址将用于发送HTTP请求。
二、以文本格式发送信息
1、若安全设置为:自定义关键字词
或 ip地址(段)
模板代码
# -*- coding: utf-8 -*-
"""
Author: @优快云盲敲代码的阿豪
Time: 2025/1/11 18:56
Project: 向钉钉自动推送消息
"""
import requests
import json
# 1、钉钉机器人Webhook地址(包含access_token)
webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=a409fb39ab926585cbd3a0be28cff95ed9e40d452c1fdc775994c374998c3312'
# 2、消息内容(这里以文本消息为例)
message = {
"msgtype": "text", # text,文本格式
"text": {
"content": "要发送的消息", # 我们将需要发送的消息,写在这里
}
}
# 3、发送HTTP POST请求
try:
response = requests.post(webhook_url, headers={'Content-Type': 'application/json'}, data=json.dumps(message))
# 检查响应状态码
if response.status_code == 200:
print(response.text)
print("消息发送成功!")
else:
print(f"消息发送失败,状态码:{response.status_code},响应内容:{response.text}")
except Exception as e:
print(f"发送消息时发生错误:{e}")
执行程序后,机器人会自动在群内发送代码中写入的固定信息
2、若安全设置为:加签
模板代码
# -*- coding: utf-8 -*-
"""
Author: @优快云盲敲代码的阿豪
Time: 2025/1/13 20:40
Project: 向钉钉自动推送消息
"""
import requests
import json
import hmac
import hashlib
import base64
import time
import urllib.parse
# 1、消息内容
message = {
"msgtype": "text", # text:文本格式
"text": {
"content": "要发送的消息内容"
},
}
# 2、如果你的机器人使用了加签方式,以下代码用于生成签名
def generate_sign(secret, timestamp):
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
return sign
# 3、参数准备
secret = 'SECb78e187beb344388613279bf117c8fd166ee0ed4aa0feb113027a05d86d3b121' # 替换为群内机器人生成的秘钥
timestamp = str(round(time.time() * 1000)) # 时间戳
sign = generate_sign(secret, timestamp) # 调用函数,得到签名
# 钉钉机器人Webhook地址(包含access_token、timestamp、sign)
webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=a409fb39ab926585cbd3a0be28cff95ed9e40d452c1fdc775994c374998c121214×tamp={}&sign={}'.format(timestamp,sign)
# 4、发送HTTP POST请求
try:
response = requests.post(webhook_url, headers={'Content-Type': 'application/json'}, data=json.dumps(message))
if response.status_code == 200:
print(response.text)
print("Message sent successfully!")
else:
print(f"Failed to send message: {response.text}")
except Exception as e:
print(f"An error occurred: {e}")
执行后,机器人会在群内自动发送消息
三、以MarkDown格式发送信息
钉钉的自定义机器人API原生并不直接支持上传和发送图片或文件作为消息内容。通常,你可以通过发送Markdown或链接类型的消息来间接展示图片,或者将文件上传到钉钉的文件系统(如钉盘),然后在消息中引用该文件的链接。
模板代码
# -*- coding: utf-8 -*-
"""
Author: @优快云盲敲代码的阿豪
Time: 2025/1/13 22:36
Project: 向钉钉自动推送消息
"""
import requests
import json
# 1、钉钉机器人Webhook地址
webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=YOUR_ACCESS_TOKEN'
# 2、图片的URL
image_url = 'https://your-image-hosting-service.com/path/to/your/image.jpg'
# 3、Markdown消息内容
markdown_message = {
"msgtype": "markdown", # 选择markdown格式
"markdown": {
"title": "Markdown消息示例", # 定义标题
"text": f"这是一条包含图片的Markdown消息!\n\n" # 要发送的信息,可以使用markdown语法编写内容
}
}
# 4、发送HTTP POST请求
try:
response = requests.post(webhook_url, headers={'Content-Type': 'application/json'}, data=json.dumps(markdown_message))
if response.status_code == 200:
print(response.text)
print("Message sent successfully!")
else:
print(f"Failed to send message: {response.text}")
except Exception as e:
print(f"An error occurred: {e}")
执行程序后,机器人会自动在群内发送markdown格式的消息,图片链接在群内也会显示为图片
四、以Link格式发送信息
模板代码
# -*- coding: utf-8 -*-
"""
Author: @优快云盲敲代码的阿豪
Time: 2025/1/13 22:36
Project: 向钉钉自动推送消息
"""
import requests
import json
# 1、钉钉机器人Webhook地址
webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=YOUR_ACCESS_TOKEN'
# 2、Link消息内容
markdown_message = {
"msgtype": "link", # link格式
"link": {
"title": "链接消息标题", # 链接标题
"text": "这是一条链接消息,点击访问:", # 链接描述
"messageUrl": "https://www.example.com", # 要访问的链接
"picUrl": "https://www.example.com/image.jpg" # 可选参数,链接消息的封面图片URL
}
}
# 3、发送HTTP POST请求
try:
response = requests.post(webhook_url, headers={'Content-Type': 'application/json'}, data=json.dumps(markdown_message))
if response.status_code == 200:
print(response.text)
print("Message sent successfully!")
else:
print(f"Failed to send message: {response.text}")
except Exception as e:
print(f"An error occurred: {e}")
执行程序后,机器人会自动向群类发送Link类型的消息,点击该链接就可以访问目标网站