一、打开钉钉群,添加自定义机器人,记住创建机器人的webhook即可。
二、发送消息到钉钉群:
import json
import requests
# 步骤一的webhook
webhook = ""
header = {
"Content-Type": "application/json",
"Charset": "UTF-8"
}
message = {
"msgtype": "link",
"link": {
"title": 标题,
"text": 文本内容,
"picUrl": 图片链接,
"messageUrl": 文章链接
},
"at": {
"isAtAll": True
}
}
message_json = json.dumps(message)
info = requests.post(url=webhook, data=message_json,headers=header)
# 消息是否发送成功查看
print(json.loads(info.text))
发送的消息类型参见钉钉文档:
https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
三、定时发送消息到钉钉群
from apscheduler.schedulers.background import BlockingScheduler
import requests
import json
webhook = ""
header = {
"Content-Type": "application/json",
"Charset": "UTF-8"
}
def sendInfo():
message = {
"msgtype": "text",
"text": {
# 消息内容一定要包含钉钉群添加机器人时候的关键词,否则无法发送
"content": "发送一条消息"
},
"at": {
"isAtAll": True
}
}
message_json = json.dumps(message, ensure_ascii=False)
info = requests.post(url=webhook, data=message_json, headers=header)
print('-'*20)
print(info.text)
if __name__ == "__main__":
scheduler = BlockingScheduler()
"""
sendInfo:发送消息函数
cron:定时发送
hour:发送时间
id:定时任务ID
"""
scheduler.add_job(sendInfo, 'cron', hour=10, id='operate')
scheduler.start()