报错1
wechatpy.exceptions.WeChatClientException: Error code: 45015, message: response out of time limit or subscription is canceled rid: 644a55b8-4177bff4-706e065f
解决方案:在用户端向公众号发送任意消息
报错2
ModuleNotFoundError: No module named 'wechatpy'
解决方案:使用python3指令运行程序
内容:
测试号与用户信息
app_id = "xxxx"
app_secret = "xxxxx"
# 模板,需要修改,模板ID在模板开头
template_id = "xxxxxx"
# 推送目标用户ID,需要关注测试号获取
user_id = "xxxxxx"
client = WeChatClient(app_id, app_secret)
向用户发送模板消息(模板内容为时间)
wm = WeChatMessage(client)
dfacetim = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
data = {"dfacetim":{"value":dfacetim,"color":"#FF0000"}}
res = wm.send_template(user_id, template_id, data)
print("send successfully:",res)
向用户发送消息
user = client.user.get(user_id)
menu = client.menu.get()
client.message.send_text(user_id, '消息内容')
向用户发送图片
def get_access_token(app_id, app_secret):
url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={app_id}&secret={app_secret}"
response = requests.get(url)
response_json = response.json()
return response_json['access_token']
def send_image_to_wechat_test_account(image_path, user_id,access_token):
# 上传图片获取media_id
upload_url = f"https://api.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}&type=image"
with open(image_path, "rb") as image_file:
files = {"media": image_file}
response = requests.post(upload_url, files=files)
response_json = response.json()
media_id = response_json["media_id"]
# 发送图片到微信测试号
send_url = f"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={access_token}"
payload = {
"touser": user_id,
"msgtype": "image",
"image": {
"media_id": media_id
}
}
headers = {"Content-Type": "application/json"}
response = requests.post(send_url, json=payload, headers=headers)
return response.json()
image_path = "st.jpg" # 将此替换为图片文件的实际路径
access_token = get_access_token(app_id, app_secret)
response = send_image_to_wechat_test_account(image_path, user_id,access_token)
print("send text successfully:",response["errmsg"])