收藏
回答

请问一下文章推送到草稿箱没有报错,但是草稿箱中没有,是因为什么?

懂一些python但是懂得不多,一些方法是搜索的, 调用之后没报错,也请求成功了, 但是草稿箱中是不存在的


获取的media_id的函数如下, 参考的api:https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/New_temporary_materials.html

import requests
from getToken import get_wxCode_token


def upload_image_to_wechat(access_token, image_path):
    """
    Uploads an image to WeChat's temporary material library.

    Parameters:
    access_token (str): The access token for WeChat API.
    image_path (str): The local file path to the image to be uploaded.

    Returns:
    dict: The JSON response from the WeChat API.
    """
    url = f"https://api.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}&type=image"
    files = {'media': open(image_path, 'rb')}

    try:
        response = requests.post(url, files=files)
        response.raise_for_status()  # Raises an HTTPError if the HTTP request returned an unsuccessful status code
        return response.json()
    except requests.exceptions.HTTPError as errh:
        print(f"HTTP Error: {errh}")
    except requests.exceptions.ConnectionError as errc:
        print(f"Error Connecting: {errc}")
    except requests.exceptions.Timeout as errt:
        print(f"Timeout Error: {errt}")
    except requests.exceptions.RequestException as err:
        print(f"OOps: Something Else: {err}")
    finally:
        files['media'].close()

# Example usage:
# Replace 'YOUR_ACCESS_TOKEN' with your actual access token and 'path_to_image.jpg' with the path to your image file.
# response = upload_image_to_wechat('YOUR_ACCESS_TOKEN', 'path_to_image.jpg')
# print(response)

token_and_time = get_wxCode_token()
access_token = token_and_time[0]
getTokenTime = token_and_time[1]

print(upload_image_to_wechat(
    access_token,
    r"E:\图片\临时图片\4download.png"))


获取token的方法如下:

def get_wxCode_token():
    try:
        appid = "xxxxx"
        secret = "xxxx"
        textmod = {"grant_type": "client_credential",
            "appid": appid,
            "secret": secret
        }
        textmod = parse.urlencode(textmod)
        header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'}
        url = 'https://api.weixin.qq.com/cgi-bin/token'
        req = request.Request(url='%s%s%s' % (url, '?', textmod), headers=header_dict)
        res = request.urlopen(req)
        res = res.read().decode(encoding='utf-8')
        res = json.loads(res)
        access_token = res["access_token"]
        print('access_token:',(access_token,time.time()))
        return (access_token,time.time())
    except Exception as e:
        print(e)
        return False


推送到草稿箱的整体函数如下

import requests
import datetime
import time
import json
import chardet

from getToken import get_wxCode_token


# 此模块作用:将文本内容上传到公众号草稿箱,可参考https://developers.weixin.qq.com/doc/offiaccount/Draft_Box/Add_draft.html
# 全流程:
# 步骤:1.获取access_token
#      2.从天行数据拉去想要的文本数据并解析整理
#      3.调用上传草稿的接口使用post方式上传文本数据

# 步骤:
# 1.拿到token,用一个变量来记录获取token时的时间戳,每次执行时先检查时间达到2个小时的才去获取token
token = ''
getTokenTime = 0


class Caogao(object):

    def __init__(self,name,data,access_token,getTokenTime):
        self.name = name
        self.data = data
        self.access_token = access_token
        self.getTokenTime = getTokenTime

    # 先判断是否有token,如果没有,获取token,同时记录时间,获取后开始干活儿,
    # 如果有,判断是否失效,失效则重新获取,
    # 判断token是否过期
    def which_token_abate(self):
        # 获取token时间戳
        # global getTokenTime
        # 获取当前时间戳
        nowtime_stamp = time.time()
        # 用当前时间戳减去getTokenTime,大于两个小时就判定失效
        hour2 = 2 * 60 * 60 * 1000
        if nowtime_stamp - self.getTokenTime > hour2:
            return True
        return False

    # 判断是否有token
    def have_token(self):
        if self.access_token != '':
            return True
        return False

    # 发送数据,data为要发的内容
    def send_requests(self):
        # 2.导入requests包,发送post
        try:
            header_dict = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',
                'Content-Type': 'application/json; charset=utf-8'
            }
            response_psot = requests.post(
                url='https://api.weixin.qq.com/cgi-bin/draft/add?',
                params={
                    'access_token': self.access_token},
                headers=header_dict,
                data=bytes(json.dumps(self.data, ensure_ascii=False).encode('utf-8'))
                # data=self.data,
            )

            print(response_psot, "成功")
        except Exception as e:
            print(e)


def main():

    # 2.推送到公众号
    # 要传的草稿
    data = {
        "articles": [
            {
                "title": "青云RPA自动化",
                "author": "qingyun",
                "content": "dsafsfsffssfff",
                "thumb_media_id": "odDSy37Mb_kmr2ieDGwVv8TjfKNhZQqcZRzMYOWa1XdRQQSSMQfGQ2-sRvPMxILj"
            }
        ]
    }
    token_and_time = get_wxCode_token()
    access_token = token_and_time[0]
    getTokenTime = token_and_time[1]
    # 创建草稿实例
    caogao = Caogao('caogao', data, access_token, getTokenTime)
    caogao.send_requests()


if __name__ == '__main__':
    main()



回答关注问题邀请回答
收藏

1 个回答

  • Mr.Zhao
    Mr.Zhao
    10-09

    先postman调接口玩明白,再说代码,先走后跑

    10-09
    有用
    回复
登录 后发表内容