python通过钉钉小程序发送服务器项目日志文件

# -*- coding: utf-8 -*-
import requests,json,datetime,os

def getAccess_token():
    appkey = 'xxx' # 管理员账号登录开发者平台,应用开发-创建应用-查看详情-appkey
    appsecret = 'xxx' # 应用里的appsecret
    url = 'https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s' % (appkey, appsecret)
    headers = {
        'Content-Type': "application/x-www-form-urlencoded"
    }
    data = {'appkey': appkey,
            'appsecret': appsecret}
    r = requests.request('GET',url,data=data,headers=headers)
    access_token = r.json()["access_token"]
    return access_token

def getMedia_id(i):
    access_token = getAccess_token()  # 拿到接口凭证
    log_time=(datetime.datetime.now()+datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
    profile = "error-"+log_time+"."+str(i)+".log"
    path = '/data/logs/app/exchange-app-api/'+profile  # 文件路径
    
    if  os.path.exists(path):
        url = 'https://oapi.dingtalk.com/media/upload?access_token=' + access_token + '&type=file'
        files = {'media': open(path, 'rb')}
        data = {'access_token': access_token,'type': 'file'}
        response = requests.post(url, files=files, data=data)
        json = response.json()
        return json["media_id"]
    return ""


def SendFile():
    access_token = getAccess_token()
    for i in range(0,20):
        media_id = getMedia_id(i)
        if(media_id != ""):
            chatid = 'xxx'  # 通过jsapi工具获取的群聊id
            url = 'https://oapi.dingtalk.com/chat/send?access_token=' + access_token
            header = {
                'Content-Type': 'application/json'
            }
            data = {'access_token': access_token,
                    'chatid': chatid,
                    'msg': {
                        'msgtype': 'file',
                        'file': {'media_id': media_id}
                    }}
            r = requests.request('POST', url, data=json.dumps(data), headers=header)
if __name__ == '__main__':
	SendFile()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值