材料:
1、python 2.7 或者 python3.x
2、windows 可以通过 “python -m pip --version” 查看当前的pip 版本
E:\Downloads\newsInfo>python -m pip --version
pip 20.3.4 from C:\Python27\lib\site-packages\pip (python 2.7)
3、windows 系统
制作:
1、安装python
打开 WEB 浏览器访问Python Releases for Windows | Python.org
下载后,双击下载包,进入 Python 安装向导,安装非常简单,你只需要使用默认的设置一直点击"下一步"直到安装完成即可
注意:部分电脑环境可能需要配置环境变量,参考Python 环境搭建 | 菜鸟教程
2、安装 pip
下载与自己python版本对应的get-pip.py 且切换到该文件目录后执行如下命令
python get-pip.py
测试安装是否成功(注:未配置环境变量的情况,若已配置环境变量,使用pip -version)
python -m pip --version
验证:
3、安装 flask(用于简单的服务发布测试)
通过 python -m pip install flask 安装flask框架
4、程序目录结构
5、编写main.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from flask import Flask,render_template,request,jsonify
import requests
import json
import chardet
app = Flask(__name__)
@app.route('/',methods=['POST'])
def start():
data = request.get_json()
file_path = data.get('file_path')
#print("file_path",file_path)
mediaInfo = data.get('mediaInfo')
#mediaInfos = json.dumps(mediaInfo, ensure_ascii=False)
print("mediaInfo",mediaInfo)
#mediaInfo = chardet.detect(str(json.dumps(mediaInfo)).encode())
#mediaInfo = json.dumps(mediaInfo,ensure ascii-False)
#file_path = 'C:\Users\mpf\Desktop/20240819172400.png'
wxpublish(file_path,mediaInfo)
return "s"
def wxpublish(file_path,mediaInfo):
access_token = getWX_token()
print(access_token)
media_id = upload_material(access_token,file_path)
print("media_id",media_id)
mediaInfo.update({'thumb_media_id': media_id})
list_data = [mediaInfo]
media_id = save_draft(access_token,list_data)
print("save_media_id",media_id)
freepublish(access_token,media_id)
def getWX_token():
url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=(变量APPID)&secret=(变量SECRETID)'
resp = requests.get(url)
if resp.status_code == 200:
data = resp.json()
tokenjson = data.get('access_token','N/A')
return tokenjson
else:
print('Failed',resp.status_code)
def upload_material(access_token,file_path):
url = 'https://api.weixin.qq.com/cgi-bin/material/add_material'
if is_empty_string(file_path):
file_path = '/20240819172400.png'
files = {'media': open(file_path, 'rb')}
data = {
"access_token" : access_token,
"type" : "image"
}
try:
resp = requests.post(url, files=files, data=data)
resp.raise_for_status()
data = resp.json()
media_id = data.get('media_id','N/A')
return str(media_id)
except requests.exceptions.RequestException as e:
print("bpf",e)
except requests.exceptions.HTTPError as e:
print("efg",e)
except Exception as e:
print("upload_materialabcd:",e)
finally:
for key, value in files.items():
if value:
value.close()
def save_draft(access_token,media_mode):
url = 'https://api.weixin.qq.com/cgi-bin/draft/add'
data = {
"articles": media_mode
}
params = {
"access_token" : access_token
}
headers = {
"User-Agent" :'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
"Accept":'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
"Accept-Encoding":'gzip, deflate, br',
"Connection":'keep-alive',
"Content-Type":'application/json;charset=utf-8',
"Cache-Control":'max-age=0'
}
try:
data = json.dumps(data,ensure_ascii=False)
print("***",data)
resp = requests.post(url,params=params,json=data,headers=headers)
resp.raise_for_status()
data = resp.json()
media_id = data.get('media_id','N/A')
return media_id
except Exception as e:
print("save_draftabcd:",e)
finally:
print("access_token")
def freepublish(access_token,media_id):
url = 'https://api.weixin.qq.com/cgi-bin/freepublish/submit'
params = {
"access_token" : access_token
}
data = {
"media_id": media_id
}
headers = {
"User-Agent" :'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
"Accept":'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
"Accept-Encoding":'gzip, deflate, br',
"Connection":'keep-alive',
"Content-Type":'application/json;charset=utf-8',
"Cache-Control":'max-age=0'
}
try:
data = json.dumps(data,ensure_ascii=False)
resp = requests.post(url,params=params,data=data,headers=headers)
resp.raise_for_status()
data = resp.json()
print(data)
except Exception as e:
print("freepublishabcd:",e)
finally:
return
def getHtml_Of_articles():
return
def is_empty_string(text):
if text.strip() == "":
return True
else:
return False
if __name__ == '__main__':
app.run(debug=True,port=8080)
上述代码片段中有2个关键变量必须是自己的微信公众号APPID和密码 ,分别是(变量APPID)、(变量SECRETID)。
上述代码中包含了获取微信授权token、提交图片素材到微信公众号永久素材库、创建微信公众号素材草稿、发布微信公众号文章几个步骤
6、获取微信公众平台的APPID和密码及设置白名单
公众号平台:https://mp.weixin.qq.com/cgi-bin/frame?t=notification/index_frame
切换菜单到“设置与开发”-->"基础设置",如下图
注:这里的 AppSecret ID生成后需要自己记住,也就是上面代码片段中的(变量SECRETID),这里的APPID就是上面代码片段中的(变量APPID)
7、设置白名单
接第六部白名单设置,公众号开发必须设置白名单。
开发环境:由于我们研发环境基本很难有固定的IP,使用ipconfig/ifconfig都是内网IP(如:192.168.0.X),这种内网IP无法穿透。如何获得自己的临时公网IP呢?
简单:我们只需要打开百度搜索栏输入“IP”即可获得,只是这个地址不定期会变,研发使用已经足够。
8、 添加webhtml模板
在main.py 同层创建文件夹并命名templates
在templates目录下新建form.html,index.html
index.html 如下
<!DOCTYPE html>
<html>
<head>
<title>AI发文章</title>
</head>
<body>
<h1>提交<h1>
<form action="/start">
<input type = "text" name="name" >
<input type = "submit" value = "start">
</form>
</body>
</html>
form.html
<!DOCTYPE html>
<html>
<head>
<title>AI发文章</title>
</head>
<body>
<h1>成功实现<h1>
</body>
</html>
9、windows+R 打开,输入"cmd",并切换目录到 main.py 所在目录后执行 "python main.py" 即可
10、postman 请求
11、页面请求
12、微信公众号
分享
python 2.7 与python 3.x间存在编码不统一问题,可能会在提交草稿步揍出现44003异常。
乱码问题: