官方文檔地址:https://developer.work.weixin.qq.com/document/path/91770#%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%E7%BE%A4%E6%9C%BA%E5%99%A8%E4%BA%BA文章來源:http://www.zghlxwxcb.cn/news/detail-700577.html
一、獲取自定義機器人webhook
可以通過如下步驟設(shè)置企業(yè)微信機器人:文章來源地址http://www.zghlxwxcb.cn/news/detail-700577.html
- 首先建立或者進入某個群聊
- 進入群聊設(shè)置頁面, 點擊“群機器人>添加”可添加一個機器人成功
- 添加成功后,復(fù)制并保留其webhook地址。
二、python封裝腳本
# -*- coding: utf-8 -*-
# @Time : 2023/5/11 15:01
# @Author : chenyinhua
# @File : webchat_handle.py
# @Software: PyCharm
# @Desc: 企業(yè)微信機器人
import os
from requests import request
from loguru import logger
import base64
import hashlib
import re
class WechatBot:
"""
企業(yè)微信機器人
當(dāng)前自定義機器人支持文本(text)、markdown(markdown)、圖片(image)、圖文(news), 文件(file)五種消息類型。
機器人的text/markdown類型消息支持在content中使用<@userid>擴展語法來@群成員
"""
def __init__(self, webhook_url):
"""
:param webhook_url: 機器人的WebHook_url
"""
self.webhook_url = webhook_url
self.headers = {
"Content-Type": "application/json",
"Charset": "UTF-8"
}
def send_text(self, content, mentioned_list=[], mentioned_mobile_list=[]):
"""
發(fā)送文本消息
:param content: 文本內(nèi)容,最長不超過2048個字節(jié),必須是utf8編碼
:param mentioned_list: userid的列表,提醒群中的指定成員(@某個成員),@all表示提醒所有人,如果開發(fā)者獲取不到userid,可以使用mentioned_mobile_list
:param mentioned_mobile_list: 手機號列表,提醒手機號對應(yīng)的群成員(@某個成員),@all表示提醒所有人
"""
payload = {
"msgtype": "text",
"text": {
"content": content,
"mentioned_list": mentioned_list,
"mentioned_mobile_list": mentioned_mobile_list
}
}
response = request(url=self.webhook_url, method="POST", json=payload, headers=self.headers)
if response.json().get("errcode") == 0:
logger.debug(f"通過企業(yè)微信發(fā)送文本消息成功:{response.json()}")
return True
else:
logger.error(f"通過企業(yè)微信發(fā)送文本消息失敗:{response.text}")
return False
def send_markdown(self, content):
"""
發(fā)送markdown消息
目前支持的markdown語法是如下的子集:
1. 標題 (支持1至6級標題,注意#與文字中間要有空格)
2. 加粗
3. 鏈接
4. 行內(nèi)代碼段(暫不支持跨行)
5. 引用
6. 字體顏色(只支持3種內(nèi)置顏色), 綠色(color="info"),灰色(color="comment"),橙紅色(color="warning")
:param content: markdown內(nèi)容,最長不超過4096個字節(jié),必須是utf8編碼
"""
payload = {
"msgtype": "markdown",
"markdown": {
"content": content
}
}
response = request(url=self.webhook_url, method="POST", json=payload, headers=self.headers)
if response.json().get("errcode") == 0:
logger.debug(f"通過企業(yè)微信發(fā)送md消息成功:{response.json()}")
return True
else:
logger.error(f"通過企業(yè)微信發(fā)送md消息失?。?/span>{response.text}")
return False
def send_picture(self, image_path):
"""
發(fā)送圖片消息
:param image_path: 圖片的絕對路徑
"""
with open(image_path, "rb") as f:
image_data = f.read()
payload = {
"msgtype": "image",
"image": {
"base64": base64.b64encode(image_data).decode("utf-8"), # # 將圖片數(shù)據(jù)轉(zhuǎn)換成Base64編碼格式
"md5": hashlib.md5(image_data).hexdigest() # # 計算圖片的MD5值
}
}
response = request(url=self.webhook_url, method="POST", json=payload, headers=self.headers)
if response.json().get("errcode") == 0:
logger.debug(f"通過企業(yè)微信發(fā)送圖片消息成功:{response.json()}")
return True
else:
logger.error(f"通過企業(yè)微信發(fā)送圖片失敗:{response.text}")
return False
def send_text_picture(self, articles: list):
"""
發(fā)送圖文消息
:param articles: 圖文消息,一個圖文消息支持1到8條圖文, 包括如下字段
1. title: 標題,不超過128個字節(jié),超過會自動截斷
2. description: 非必填,描述,不超過512個字節(jié),超過會自動截斷
3. url: 點擊后跳轉(zhuǎn)的鏈接。
4. picurl: 非必填,圖文消息的圖片鏈接,支持JPG、PNG格式,較好的效果為大圖 1068*455,小圖150*150。
"""
payload = {
"msgtype": "news",
"news": {
"articles": [
]
}
}
for article in articles:
payload["news"]["articles"].append(
{
"title": article.get("title"),
"description": article.get("description", ""),
"url": article.get("url"),
"picurl": article.get("picurl", "")
}
)
response = request(url=self.webhook_url, method="POST", json=payload, headers=self.headers)
if response.json().get("errcode") == 0:
logger.debug(f"通過企業(yè)微信發(fā)送圖文消息成功:{response.json()}")
return True
else:
logger.error(f"通過企業(yè)微信發(fā)送圖文失敗:{response.text}")
return False
def upload_file(self, file_path):
"""
上傳文件到企業(yè)微信服務(wù)器(要求文件大小在5B~20M之間)
注意:素材上傳得到media_id,該media_id僅三天內(nèi)有效;media_id只能是對應(yīng)上傳文件的機器人可以使用
:param file_path: 文件絕對路徑
"""
token_regex = r"key=([\w-]+)"
match = re.search(token_regex, self.webhook_url)
token = match.group(1)
url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key={token}&type=file"
headers = {
"Content-Type": "multipart/form-data;"
}
with open(file_path, "rb") as f:
files = {"media": (os.path.basename(file_path), f.read())}
response = request(url=url, method="POST", files=files, headers=headers)
if response.json().get("errcode") == 0:
media_id = response.json().get("media_id")
logger.debug(f"上傳文件成功,media_id= {media_id}")
return media_id
else:
logger.error(f"上傳文件失?。?/span>{response.text}")
return False
def send_file(self, media_id):
"""
發(fā)送文件
:param media_id: 文件id,通過下文的文件上傳接口獲取
"""
payload = {
"msgtype": "file",
"file": {
"media_id": media_id,
}
}
response = request(url=self.webhook_url, method="POST", json=payload, headers=self.headers)
if response.json().get("errcode") == 0:
logger.debug(f"通過企業(yè)微信發(fā)送文件消息成功:{response.json()}")
return True
else:
logger.error(f"通過企業(yè)微信發(fā)送文件消息失?。?/span>{response.text}")
return False
if __name__ == '__main__':
webhook_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=***********"
bot = WechatBot(webhook_url)
bot.send_text(content="hello1", mentioned_list=["@all"])
bot.send_text(content="hello2", mentioned_list=["@all"], mentioned_mobile_list=["18774970063"])
md = "實時新增用戶反饋<font color=\"warning\">132例</font>,請相關(guān)同事注意。\n>類型:<font color=\"comment\">用戶反饋</font>>普通用戶反饋:<font color=\"comment\">117例</font>>VIP用戶反饋:<font color=\"comment\">15例</font>"
bot.send_markdown(content=md)
bot.send_picture(image_path=r"xxxxxx.png")
articles = [
{
"title": "中秋節(jié)禮品領(lǐng)取",
"description": "今年中秋節(jié)公司有豪禮相送",
"url": "www.qq.com",
"picurl": "http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png"
}
]
bot.send_text_picture(articles=articles)
filepath = r"xxxxxxx\apiautotest-report-2023-05-11 14_57_18.html"
bot.send_file(media_id=bot.upload_file(filepath))
到了這里,關(guān)于封裝Python腳本:使用企業(yè)微信機器人發(fā)送消息至企業(yè)微信的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!