服务器向微信测试号发送卡片、文字消息、图片(部分代码来自GPT-4)

报错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"])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值