import requests
import base64
import hashlib
import json
# 机器人地址的key值
key="811a1652-60e8-4f51-a1d9-231783399ad2"
def path2base64(path):"""文件转换为base64:param path: 文件路径:return:"""with open(path, "rb") as f:byte_data = f.read()base64_str = base64.b64encode(byte_data).decode("ascii") # 二进制转base64return base64_str
def path2md5(path):"""文件转换为md5:param path: 文件路径:return:"""with open(path, "rb") as f:byte_data = f.read()md5_str = md5(byte_data)return md5_strdef md5(text):"""md5加密:param text::return:"""m = hashlib.md5()m.update(text)return m.hexdigest()# 上传文件
def upload_file(file_path):"""企业微信机器人上传文件,发送文件前需要现上传:param file_path: 文件路径:return:"""data = {'file': open(file_path, 'rb')}resp = requests.post(f"https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key={key}&type=file", files=data)json_res = resp.json()print(json_res)if json_res.get('errcode') == 0:print(f"企业微信机器人上传文件成功,file:{file_path}")return json_res.get('media_id')else:print(f"企业微信机器人上传文件失败,file:{file_path}")return json.loads(resp.text)class QY:def __init__(self):self.url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={key}"# 发送图片def image(self,image):data={"msgtype": "image","image": {"base64":path2base64(image),"md5":path2md5(image)}}resp=requests.post(url=self.url,json=data)print(resp.text)return json.loads(resp.text)# 发送文件def send_file(self,file):media_id=upload_file(file)data={"msgtype": "file","file":{"media_id":media_id}}resp=requests.post(url=self.url,json=data)print(resp.text)return json.loads(resp.text)# 发送文本def send_text(self,text):data={"msgtype": "text","text":{"content":text}}resp=requests.post(url=self.url,json=data)print(resp.text)return json.loads(resp.text)# 发送markdown文本def markdown(self,markdown):data={"msgtype": "markdown","markdown": {"content": '''实时新增用户反馈<font color=\"warning\">132例</font>,请相关同事注意。\n>类型:<font color=\"comment\">用户反馈</font>>普通用户反馈:<font color=\"comment\">117例</font>>VIP用户反馈:<font color=\"comment\">15例</font>'''}}resp=requests.post(url=self.url,json=data)print(resp.text)return json.loads(resp.text)# 发送图文类型def news(self,news):data={"msgtype": "news","news": {"articles" : [{"title" : "中秋节礼品领取","description" : "今年中秋节公司有豪礼相送","url" : "www.qq.com","picurl" : "http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png"}]}}resp=requests.post(url=self.url,json=data)print(resp.text)return json.loads(resp.text)if __name__ == '__main__':qy = QY()# qy.image("C:/Users/Administrator/Pictures/Saved Pictures/1.jpg")# 发送文件# qy.send_file("main.py")# 发送文本# qy.send_text("hello world")# 发送markown文本# qy.markdown("")#发送图文信息# qy.news('') 作者:浅若红尘 https://www.bilibili.com/read/cv28561312/?spm_id_from=333.999.0.0 出处:bilibili
有事情,请到哔哩哔哩