企业微信发送音频视频文件
企业微信发送文件 import requests import json import io class WeChatBot: def __init__(self, api_key): self.api_key = api_key self.base_url = f'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={self.api_key}' self.headers = {'Content-Type': 'application/json'} self.upload_url = f'https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key={self.api_key}&type=file' def send_message(self, data): return self._post_request(self.base_url, data) def upload_media(self, content, file_name, content_type): files = {'media': (file_name, content, content_type)} return self._post_request(self.upload_url, files=files, is_json=False) def upload_text_as_media(self, text_content, file_name): file_stream = io.BytesIO(text_content.encode('utf-8')) return self.upload_media(file_stream, file_name, 'application/octet-stream') def upload_audio_as_media(self, audio_file_path): return self._upload_file(audio_file_path, 'audio/mpeg') def upload_video_as_media(self, video_file_path): return self._upload_file(video_file_path, 'video/mp4') def send_media(self, response): if response.get("media_id"): data = { "msgtype": "file", "file": {"media_id": response["media_id"]} } return self.send_message(data) return response def _post_request(self, url, data=None, files=None, is_json=True): try: if is_json: response = requests.post(url, headers=self.headers, data=json.dumps(data)) else: response = requests.post(url, files=files) response.raise_for_status() return response.json() except requests.RequestException as e: print(f"请求时出错: {e}")……