通过python代码实现向钉钉群内自动推送消息,详细步骤及代码,超实用教学!!!

前言

我们在使用钉钉时,通常会创建或加入多个群聊,身为群聊的管理者,当我们需要及时、并按时的向这些群聊推送一些固定信息,若通过人力来解决肯定非常耗时、耗力,这时我们就可以考虑开发一个自动化脚本来实现这个功能,本篇文章我将教会大家,如何使用python开发程序,实现向钉钉群内自动发送消息。

一、创建钉钉群机器人

  • 1、登录钉钉,进入你想要发送消息的群聊。

  • 2、点击群聊右上角的“…”图标,选择“群机器人”或“智能群助手”(取决于钉钉的版本和界面更新)。

  • 3、点击“添加机器人”,选择“自定义”机器人。

  • 4、设置机器人名称,并选择安全设置(通常使用自定义关键词或加签方式)。

这里会出现三种安全设置,如:

  1. 自定义关键字词
  2. 加签
  3. 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&timestamp={}&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![图片]({image_url})" # 要发送的信息,可以使用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类型的消息,点击该链接就可以访问目标网站

微信小程序提供了日期时间选择器组件`picker`和日历组件`calendar`,但如果需要自定义样式或者功能,可以考虑封装一个日期时间组件。 以下是一个简单的日期时间组件的封装示例: 1. 在`/components`目录下创建一个`datetime-picker`文件夹,创建`datetime-picker.wxml`、`datetime-picker.wxss`、`datetime-picker.js`和`datetime-picker.json`四个文件。 2. 在`datetime-picker.json`中定义组件的属性: ```json { "component": true, "usingComponents": {}, "properties": { "startDate": { "type": String, "value": "2023-02-15", }, "endDate": { "type": String, "value": "2023-02-20", }, "startTime": { "type": String, "value": "00:00", }, "endTime": { "type": String, "value": "23:59", }, "defaultDate": { "type": String, "value": "", }, "defaultTime": { "type": String, "value": "", }, "format": { "type": String, "value": "datetime", }, "showTime": { "type": Boolean, "value": true, }, "showDate": { "type": Boolean, "value": true, }, "startPlaceholder": { "type": String, "value": "开始时间", }, "endPlaceholder": { "type": String, "value": "结束时间", }, "bind:change": { "type": Function, "value": "", } }, "options": { "styleIsolation": "apply-shared" } } ``` 上述属性中: - `startDate`和`endDate`为日期范围,用于限制可选日期的范围; - `startTime`和`endTime`为时间范围,用于限制可选时间的范围; - `defaultDate`和`defaultTime`为默认值; - `format`为显示格式,支持`datetime`、`date`和`time`三种格式; - `showTime`和`showDate`分别控制是否显示时间和日期选择器; - `startPlaceholder`和`endPlaceholder`为开始时间和结束时间的占位符; - `bind:change`为选择器值变化时的回调函数。 3. 在`datetime-picker.wxml`中定义选择器组件: ```html <view class="datetime-picker"> <view wx:if="{{showDate}}" class="datetime-picker-item"> <picker mode="date" start="{{startDate}}" end="{{endDate}}" value="{{selectedDate}}" bindchange="onDateChange"> <view class="datetime-picker-value"> <text wx:if="{{selectedDate}}">{{selectedDate}}</text> <text wx:else>{{startPlaceholder}}</text> </view> </picker> </view> <view wx:if="{{showTime}}" class="datetime-picker-item"> <picker mode="time" start="{{startTime}}" end="{{endTime}}" value="{{selectedTime}}" bindchange="onTimeChange"> <view class="datetime-picker-value"> <text wx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

盲敲代码的阿豪

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

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

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

打赏作者

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

抵扣说明:

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

余额充值