使用python发送钉钉群消息,获取每日一次,发送不同格式信息。

python分享 (334) 2023-04-17 11:58:29
# _*_ coding:utf_8 _*_

import requests
import json
import schedule
import time
import datetime


num=['一','二','三','四','五','六','日']

def sendDing(msg):
    '''
    发送钉钉消息功能
    '''
    # 测试
    dingding_url = 'https://oapi.dingtalk.com/robot/send?access_token='
    #dingding_url = 'https://oapi.dingtalk.com/robot/send?access_token='
    headers = {'Content-Type':'application/json;charset=UTF-8'}
    send_data = json.dumps(msg).encode('utf-8')
    ret = requests.post(url=dingding_url,data=send_data,headers=headers)
    print(ret.text)

def getCiba():
    try:
        url = 'http://open.iciba.com/dsapi/'
        headers = {'Content-Type':'application/json;charset=UTF-8'}
        r = requests.get(url=url,headers=headers)
        content = r.json()['content']
        note = r.json()['note']
        img = r.json()['fenxiang_img']
        return content,note,img
    except:
        return None

def getData(msg,type='text'):
    img = ''
    content = ''
    note = ''
    ciba = getCiba()
    if ciba is not None:
        content = ciba[0]
        note = ciba[1]
        img = ciba[2]

    data = {"msgtype": "text","at":{"isAtAll":True},"text": {"content": "消息提醒:"+str(msg)}}
    if type == 'link':
        data = {
        "msgtype": "link", 
        "link": {
            "text": msg + "   " + content + "  " + note,  
            "title": "消息提醒:"+msg, 
            "picUrl": "" + img, 
            "messageUrl": "https://test.com/redmine"
            }
        }
    if type == 'markdown':
        data = {
            "msgtype": "markdown",
            "markdown": {
                "title":"消息提醒:"+msg,
                "text": "#### "+ msg+ "\n "
                +">"+  content +" \n "
                +">"+  note +" \n "
                +"> ![screenshot]("+img+")\n "
                +"> #### [readmine地址](https://test.com/redmine) \n"
                +"> ###### "+str(datetime.datetime.now())[11:19]+"发布 \n"
               
            },
            "at": {
                "atMobiles": [""],
                "atUserIds": [""],
                "isAtAll": True
            }
        }
    return data

def run():
    now = datetime.datetime.today().weekday()
    info = '今天是周{}'.format(num[now])
    print(info)
    if now < 5 :
        print("工作日开始发送信息")
        sendDing(getData('不要忘记填写readmine','markdown'))
    else:
        print('周末不发送!')
       
run()
#schedule.every().day.at('17:50').do(run)
#while True:
#    schedule.run_pending()
#    time.sleep(10)

 

THE END

发表回复