Python调用企微机器人: 发送常用格式汇总

企微接口文档

发送应用消息 - 接口文档 - 企业微信开发者中心

发送格式

应用支持推送文本、图片、视频、文件、图文等类型。

~~~以下列举常用格式 示例~~~

1.发送文本

代码如下:

复制代码
def sendtxt_robotmsg(self):
     # 正式key
     wx_key = "xx"
     wx_webhookurl = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={}'.format(wx_key)
     headers = {'Content-Type': 'application/json'}
     //发送消息时在企微自动@的人:xx值必须为同事注册企微的手机号或姓名
	 hbpeople = ["xx"]
     msg = '请关注'
     testdata = json.dumps({"msgtype": "text", "text": {"content": msg, "mentioned_list": hbpeople}})
     r = requests.post(wx_webhookurl, data=testdata, headers=headers, verify=False)
     print(r.text)
     return r

发送结果:

2.发送图片

代码如下:

图片存放在这里:

复制代码
#图片所在文件夹路径
SCRIPTS_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
GENERATECASE_DIR = os.path.join(SCRIPTS_DIR, "xx")
DATAS_DIR = os.path.join(GENERATECASE_DIR, "xx")

def sendimage_robotmsg():
    # 调试key
    wx_key = "xx"
    wx_webhookurl = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={}'.format(wx_key)
    headers = {'Content-Type': 'application/json'}
    #图片(base64编码前)最大不能超过2M,支持JPG,PNG格式
    imgPath = os.path.join(DATAS_DIR, "有福气.png")
    with open(imgPath,"rb") as f:
        fd=f.read()
        base64Content=str(base64.b64encode(fd),"utf-8")
    with open(imgPath,"rb") as f:
        fd=f.read()
        md = hashlib.md5()
        md.update(fd)
        md5Content = md.hexdigest()
    testdata = {"msgtype": "image","image": {"base64": base64Content,"md5": md5Content}}
    r = requests.post(wx_webhookurl, headers=headers, json=testdata)
    print(r.text)
    return r

发送结果:

3.发送文件

文件路径:

代码如下:

复制代码
SCRIPTS_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
GENERATECASE_DIR = os.path.join(SCRIPTS_DIR, "xx")
DATAS_DIR = os.path.join(GENERATECASE_DIR, "xx")


def upload_weixin(key=None, filename=None):
    """
    上传附件到企业微信,获得media_id.然后发送消息通知,可查看文件
    """
    if not key:
        print("key不能为空")
        raise
    # 请求地址
    url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key={}&type=file".format(key)
    # 请求头
    headers = {"Content-Type": "multipart/form-data"}
    # 请求数据,是rb读取文件流
    data = {"file": open(filename, "rb")}
    # 发送请求
    res = requests.post(url, files=data, headers=headers).json()
    return res.get("media_id")

def sendfile_robotmsg():
    #key
    wx_key = "xx"
    wx_webhookurl = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={}'.format(wx_key)
    headers = {'Content-Type': 'application/json'}
    filename = os.path.join(DATAS_DIR, "xx.html")
    print(filename)
    medid= upload_weixin(wx_key,filename)
    data = {
        "msgtype": "file",
        "file": {
            "media_id": medid
        }
    }
    print(medid)
    r = requests.post(url=wx_webhookurl,headers=headers, json=data)

    print(r.text)
    return r

发送结果:

4.发送图文

文件路径:

代码如下:

复制代码
SCRIPTS_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
GENERATECASE_DIR = os.path.join(SCRIPTS_DIR, "xx")
DATAS_DIR = os.path.join(GENERATECASE_DIR, "xx")


def sendimagetext_robotmsg():
    # 正式key
    wx_key = "xx"
    wx_webhookurl = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={}'.format(wx_key)
    headers = {'Content-Type': 'application/json'}
    imgPath = os.path.join(DATAS_DIR, "有福气.png")

    testdata = {
   "msgtype" : "news",
   "agentid" : 1,
   "news" : {
       "articles" : [
           {
               "title" : "测试一下",
               "description" : "测试",
               "url" : "URL",
               "picurl":"",
        	   "pagepath": imgPath
           }
        ]
   },
   "enable_id_trans": 0,
   "enable_duplicate_check": 0,
   "duplicate_check_interval": 1800
}
    r = requests.post(wx_webhookurl, headers=headers, json=testdata)
    print(r.text)
    return r

发送结果:

相关推荐
starzy199012 小时前
深入理解Scala隐式类:扩展方法机制
开发语言·人工智能·scala
M--Y12 小时前
LangGraph 工作流模式
开发语言·javascript·python·langchain·大模型·llm·langgraph
岁月宁静13 小时前
DeepSeek Harness 实战与架构解析:让 Agent 从“会聊”到“能交付”
人工智能·python·agent
LiaoWL12313 小时前
NumPy 入门实战(二):向量化与余弦相似度——从 ndarray 到 Embedding
python·numpy·embedding
forest_0913 小时前
多 Agent 协作第二课:交叉验证≠独立验证
人工智能·python·算法·机器学习·prompt·agi
吴可可12313 小时前
WScript Shell操作注册表详解
开发语言
纪念 22914 小时前
C++ 算法基础 (差分)
开发语言·c++·算法
databook16 小时前
时间序列数据,先拆规律还是先查异常
python·数据挖掘·数据分析
师夷长技以自愈17 小时前
手搓 AI Agent 第 8 篇:从手写循环到画流程图——LangGraph 封装
人工智能·python
aifannihao18 小时前
Rust 1.100 的 DropGuard:用 Python 实测失败回滚与吞异常
python·rust·异常处理·标准库·contextlib