Python 调用企业微信群机器人发送消息及文件

Python 操作企业微信群机器人。

企业微信群创建机器人 :


安装 requests json :

shell 复制代码
pip install requests
pip install json

发送消息(markdown)

python 复制代码
import requests
import json

# 企业微信机器人发送文字
def send_markdown (message, wx_url):
    # wx_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxx'
    data = {"msgtype": "markdown", "markdown": {"content": message}}

    r = requests.post(url=wx_url,
                      data=json.dumps(data))  # url中的xxx是你的机器人webhook对应片段,不要轻易泄露出去否则任何人都可以控制你的机器人
    print(r.text)
    print(r.status_code)


send_message(wx_url='xxx',message='xxxx')

发送文件及消息

python 复制代码
import requests
import json

#发送文件
def post_file(file, wx_url, id_url):
    # wx_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxx'
    data = {'file': open(file, 'rb')}
    # 请求id_url(将文件上传微信临时平台),返回media_id
    #  id_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=xxxxxx&type=file'
    response = requests.post(url=id_url, files=data) 
    print(response.text)
    json_res = response.json()
    media_id = json_res['media_id']
    data = {"msgtype": "file",
            "file": {"media_id": media_id}
            }
    # 发送文件
    result = requests.post(url=wx_url, json=data)
    return (result)


# 发送文字
def send_message(message, person_list, wx_url):
    # wx_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxx&type'
    data = {
        "msgtype": "text",
        "text": {
            "content": message,
            "mentioned_list": person_list  # 需@人的姓名

        }
    }
    r = requests.post(url=wx_url,
                      json=data)  # url中的xxx是你的机器人webhook对应片段,不要轻易泄露出去否则任何人都可以控制你的机器人



#发送文件 发送 send?   上传文件 upload_media?  type=file
wx_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxx'
id_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=xxxxxxx&type=file'
post_file('/zscript/serverpi/zserverpireport/xxx.html',wx_url=wx_url,id_url=id_url)


#发送文字
wx_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx&type'
send_message(message='今日巡检报告已生成,请注意查收',person_list='@all',wx_url=wx_url)

企业微信机器人

当前自定义机器人支持文本(text)、markdown(markdown)、图片(image)、图文(news)四种消息类型。

机器人的text/markdown类型消息支持在content中使用<@userid>扩展语法来@群成员

更多内容可参照企业微信官方帮助文档 https://open.work.weixin.qq.com/help2/pc/14931

也可单机群机器人webhook地址查看详细配置说明

相关推荐
该用户已不存在1 天前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
资源开发与学习1 天前
机器人运动规划源码解析
机器人
站大爷IP1 天前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780511 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
c8i1 天前
python中类的基本结构、特殊属性于MRO理解
python
liwulin05061 天前
【ESP32-CAM】HELLO WORLD
python
Doris_20231 天前
Python条件判断语句 if、elif 、else
前端·后端·python
Doris_20231 天前
Python 模式匹配match case
前端·后端·python
这里有鱼汤1 天前
Python量化实盘踩坑指南:分钟K线没处理好,小心直接亏钱!
后端·python·程序员
大模型真好玩1 天前
深入浅出LangGraph AI Agent智能体开发教程(五)—LangGraph 数据分析助手智能体项目实战
人工智能·python·mcp