向微信公众号用户发送语音消息的步骤和代码实现如下:
步骤:
1. 获取access_token:向微信服务器发送获取access_token的请求,获得access_token。access_token是调用微信接口的必备参数。
2. 上传语音文件:将本地的语音文件上传到微信服务器,获得media_id。
3. 发送语音消息:通过微信公众号的客服接口,向指定用户发送语音消息,将media_id作为语音消息的参数。
代码实现:
import requests import json # 获取access_token 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}' resp = requests.get(url) access_token = json.loads(resp.text)['access_token'] return access_token # 上传语音文件 def upload_voice(access_token, file_path): url = f'https://api.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}&type=voice' with open(file_path, 'rb') as f: files = {'media': f} resp = requests.post(url, files=files) media_id = json.loads(resp.text)['media_id'] return media_id # 发送语音消息 def send_voice(access_token, openid, media_id): url = f'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={access_token}' data = { 'touser': openid, 'msgtype': 'voice', 'voice': { 'media_id': media_id } } resp = requests.post(url, data=json.dumps(data)) return resp.text if __name__ == '__main__': app_id = 'your_app_id' app_secret = 'your_app_secret' access_token = get_access_token(app_id, app_secret) file_path = 'your_file_path' media_id = upload_voice(access_token, file_path) openid = 'your_openid' resp = send_voice(access_token, openid, media_id) print(resp)
其中,app_id和app_secret是微信公众号的应用ID和应用密钥,file_path是本地语音文件的路径,openid是要发送语音消息的用户的openid。