python脚本实现向钉钉群组发送消息

时间:2022-04-13 19:20:27

一、json格式

import json
import requests def sendmessage(message):
url = 'https://oapi.dingtalk.com/robot/send?access_token=fksdjfksjXXXXXX' #钉钉机器人的webhook地址
HEADERS = {
"Content-Type": "application/json ;charset=utf-8 "
}
message = message
String_textMsg = {
"msgtype": "text",
"text": {"content": message},
"at": {
"atMobiles": [
"130xxxxxxxx" #如果需要@某人,这里写他的手机号
],
"isAtAll": #如果需要@所有人,这些写1
}
}
String_textMsg = json.dumps(String_textMsg)
res = requests.post(url, data=String_textMsg, headers=HEADERS)
print(res.text) if '__name__' == '__main__':
sendmessage('test')

二、消息模式:

#!/usr/bin/python
# -*- coding: utf- -*-
import dingtalkchatbot.chatbot as cb
webhook = 'https://oapi.dingtalk.com/robot/send?access_token=fasdjlfkjasXXXXXXXXX'
ding = cb.DingtalkChatbot(webhook)
ding.send_text(msg='test python script!',is_at_all=True) // is_at_all=True表示@all ,如果不加这个参数,钉钉群组收到消息不会@任何人。

其中一定要确保系统中安装了模块 “dingtalkchatbot ” ,

如果没有安装,使用命令 " pip install DingtalkChatbot " 来安装模块 dingtalkchatbot