个人微信机器人不仅要能“听”,更要能“说”。在回复用户时,单纯的文本往往不够生动,有时候还需要发送图片、图文链接或 PDF 文件。通过 E云管家 API,我们可以轻松实现多元化的消息发送。  
腾讯轻联 - Tencent
以下是封装好的消息发送工具类(Python 版本),包含了常见的消息类型兼容:

import requests

class WeChatSender:
    def __init__(self, base_url, token, instance_id):
        self.base_url = base_url
        self.headers = {"Authorization": f"Bearer {token}"}
        self.instance_id = instance_id

    def send_text(self, to_wxid, text_content):
        """通过 E云管家 api 发送纯文本消息"""
        url = f"{self.base_url}/message/send_text"
        payload = {
            "instance_id": self.instance_id,
            "to_wxid": to_wxid,
            "content": text_content
        }
        res = requests.post(url, json=payload, headers=self.headers)
        return res.json()

    def send_image(self, to_wxid, image_url):
        """通过 E云管家 api 发送网络图片消息"""
        url = f"{self.base_url}/message/send_image"
        payload = {
            "instance_id": self.instance_id,
            "to_wxid": to_wxid,
            "image_url": image_url
        }
        res = requests.post(url, json=payload, headers=self.headers)
        return res.json()

    def send_file(self, to_wxid, file_url, file_name):
        """通过 E云管家 api 发送文件(如PDF, Word)"""
        url = f"{self.base_url}/message/send_file"
        payload = {
            "instance_id": self.instance_id,
            "to_wxid": to_wxid,
            "file_url": file_url,
            "file_name": file_name
        }
        res = requests.post(url, json=payload, headers=self.headers)
        return res.json()

# 调用示例
if __name__ == "__main__":
    sender = WeChatSender("http://api.e-yun-guanjia.com/v1", "my_token", "ins_12345")
    # 给好友发送问候
    sender.send_text("wxid_xxxxxx", "你好!这是一条来自机器人的智能回复 🤖")
    # 发送一张图
    sender.send_image("wxid_xxxxxx", "https://example.com/welcome.jpg")

避坑指南: 使用 E云管家 api 发送媒体文件时,请确保所填写的 image_urlfile_url 能够被公网直接访问,且下载速度较快。如果是大文件,建议预先压缩。另外,高频发信容易触发微信风控,建议在多条发送任务之间引入 1-3 秒的随机延迟(Random Delay)。

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐