转载的,精简了一下
1,先在企微种添加一个机器人,然后复制他的webhook结尾的一串key(识别码),创建就有,然后替换到下面代码中,创建机器人参考链接:https://qinglian.tencent.com/docs/applications/wwx-robot/
2.看代码,替换url的机器人的key和pic_full_name (图片地址),直接运行即可发送
import requests
import hashlib
import os
import base64
# 获取文件的Base64编码
def get_file_base64(filepath):
if not os.path.isfile(filepath):
return
with open(filepath, "rb") as f:
image = f.read()
image_base64 = str(base64.b64encode(image), encoding='utf-8') # 这里要说明编码,否则不成功
return image_base64
# 获取文件md5函数
def get_file_md5(filepath):
# 获取文件的md5
if not os.path.isfile(filepath):
return
myhash = hashlib.md5()
f = open(filepath, "rb")
while True:
b = f.read(8096)
if not b:
break
myhash.update(b)
f.close
# print(myhash.hexdigest())
return myhash.hexdigest()
# 发送消息函数, msgtype定义:text 发送字符串消息,markdown 发送图片消息,image 发送图片消息, news 发送图文消息
def postmsg(url, post_data, msgtype):
# sss = "这是一条用python发送的测试信息,请忽略!"
post_data = '{"msgtype" : "%s", "%s" : %s}' % (msgtype, msgtype, post_data)
if url == '':
print('URL地址为空!')
else:
r = requests.post(url, data=post_data.encode())
rstr = r.json()
if r.status_code == 200 and 'error' not in rstr:
result = '发送成功'
return result
else:
return 'Error'
if __name__ == '__main__':
url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxxx-xxxxxxx-xxxxx-xxxxxxxxx" # 群机器人地址
# 取当前时间为文件名
# pic_full_name = './' + time.strftime("%Y%m%d%H%M%S", time.localtime()) + '.jpg'
pic_full_name = 'D:\桌面\下载.png'
pic_md5 = get_file_md5(pic_full_name)
pic_base64s = get_file_base64(pic_full_name)
out_pic_msg = '{"base64":"%s", "md5":"%s"}' % (pic_base64s, pic_md5)
result = postmsg(url, out_pic_msg, "image")
print(result)
3.遇到问题:
Max retries exceeded with url
我这边直接给request更新一下就解决了
$ pip install --upgrade requests
4.可以的话点个赞!!!原地址链接:https://zhuanlan.zhihu.com/p/138583880