banner
虫子游戈

虫子游戈

一个写故事的人类
mastodon
email

Typora uploads article images to the WeChat public account material library

I referred to this article “Using WeChat Official Account's Image Upload Interface to Create Your Own Image Hosting Function!”, but it has two issues:

  1. The images are not uploaded to the material library, but to another image library (although it cannot be managed in the material library, it can be used to send graphic messages, which is generally sufficient);
  2. The uploaded image names include the full path name, resulting in file names like: C:\\\\Users\\\\username\\\\AppData\\\\Local\\\\Temp\\\\Typora\\\\typora-icon.png. Long and cumbersome.

With the help of ChatGPT, issue 1 was easily resolved, but issue 2 was quite difficult. Later, I tried uploading to the material library using Python and found that the image file names could be successfully retained. So I had a sudden idea to have ChatGPT rewrite the above Go program into a Python version, and issue 2 was thus resolved. The reason, well, I’m not sure.

Here I share the Python version I obtained:

import requests

import json

import sys

  

# Constant definitions

APP_ID = "Your_APP_ID"

APP_SECRET = "Your_APP_SECRET"

  

ACCESS_TOKEN_URL = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APP_ID}&secret={APP_SECRET}"

UPLOAD_PERMANENT_IMAGE_URL = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token="

  

# Get access_token

response = requests.get(ACCESS_TOKEN_URL)

if response.status_code == 200:

    res = response.json()

    access_token = res.get("access_token")

else:

    print(f"Failed to get access token: {response.text}")

    sys.exit(1)

  

# Ensure access_token exists

if access_token:

    urls = []

    # Get command line arguments and upload images

    for v in sys.argv[1:]:

        files = {

            'media': open(v, 'rb'),

        }

        data = {

            'type': 'image',

        }

  

        # Send image upload request

        upload_response = requests.post(f"{UPLOAD_PERMANENT_IMAGE_URL}{access_token}&type=image", files=files, data=data)

  

        if upload_response.status_code == 200:

            res_url = upload_response.json()

            url = res_url.get("url")

            if url:

                urls.append(url)

        else:

            print(f"Failed to upload image {v}: {upload_response.text}")

  

    # Output the URLs of successfully uploaded images

    if urls:

        print("Upload Success:")

        for url in urls:

            print(url)

else:

    print(f"Failed to retrieve access token: {response.text}")  

 
Other steps are similar to the original text, just that corresponding Python operations are needed.

Once set up, you can automatically upload images to the WeChat Official Account's material library while writing in Typora.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.