python发送文件到企业微信

python发送文件到企业微信

用途

发送文件到企业微信,可用于发送定时报告等内容。

python脚本

文件名称:wechat_send_file.py

#!/usr/bin/python3
#--coding: utf-8--
import os
import json
import urllib3
import sys

file_path   = sys.argv[1] # 文件路径

class WinxinApi(object):

    def __init__(self,corpid,secret,agentid,touser):
        self.secret = secret    # 企业微信应用凭证
        self.corpid = corpid    # 企业微信id
        self.agentid = agentid  # 应用Agentid
        self.touser = touser    # 接收消息的userid
        self.http = urllib3.PoolManager()


    def __get_token(self):
        '''token获取'''
        url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={}".format(self.corpid,self.secret)
        r = self.http.request('GET', url)
        req = r.data.decode("utf-8")
        data = json.loads(req)
        if data["errcode"] == 0:
            return data['access_token']
        else:
            raise data["errmsg"]

    def __upload_file(self,file_path,type='file'):
        '''上传临时文件'''
        if not os.path.exists(file_path):
            raise ValueError("{},文件不存在".format(file_path))
        file_name = file_path.split("\\")[-1]
        token = self.__get_token()
        with open(file_path,'rb') as f:
            file_content = f.read()
        files = {'filefield': (file_name, file_content, 'text/plain')}
        url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={}&type={}".format(token,type)
        r = self.http.request('POST', url,fields=files)
        req = r.data.decode("utf-8")
        data = json.loads(req)
        if data["errcode"] == 0:
            return data['media_id']
        else:
            raise data["errmsg"]


    def send_file_message(self,file_path):
        token = self.__get_token()
        media_id = self.__upload_file(file_path)
        body = {
               "agentid" : self.agentid,        # agentid
               "touser"  : self.touser,
               "msgtype" : "file",              # 消息类型,此时固定为:file
               "file" : {"media_id" : media_id},# 文件id,可以调用上传临时素材接口获取
               "safe":0                         # 表示是否是保密消息,0表示否,1表示是
            }
        url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}".format(token)
        bodyjson = json.dumps(body)
        r = self.http.request('POST', url, body=bodyjson)
        req = r.data.decode("utf-8")
        data = json.loads(req)
        if data["errcode"] == 0:
            print("发送文件到企业微信成功")
        else:
            raise data["errmsg"]

wechat = WinxinApi("***corpid***","***secret***","***agentid***","***touser***")
wechat.send_file_message(file_path)

调用方式

./wechat_send_file.py myfile.txt

异常处理

# 如果执行时提示缺少urllib3:
  File "./wechat_send_file.py", line 5, in <module>
    import urllib3
ModuleNotFoundError: No module named 'urllib3'

# 解决办法:
yum install -y python3-pip
pip3 install urllib3

— 结束 —

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值