python脚本给企业微信群发送图片

转载的,精简了一下
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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值