首页 > 编程语言 >python调用企业微信发送消息

python调用企业微信发送消息

时间:2023-10-19 16:49:01浏览次数:31  
标签:调用 python 微信 self url json text response

# -*- coding: utf-8 -*-
import os

from requests import request
from loguru import logger
import base64
import hashlib
import re


class WechatBot:
"""
企业微信机器人
当前自定义机器人支持文本(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=[]):
"""
发送文本消息
:param content: 文本内容,最长不超过2048个字节,必须是utf8编码
:param mentioned_list: userid的列表,提醒群中的指定成员(@某个成员),@all表示提醒所有人,如果开发者获取不到userid,可以使用mentioned_mobile_list
:param mentioned_mobile_list: 手机号列表,提醒手机号对应的群成员(@某个成员),@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"通过企业微信发送文本消息成功:{response.json()}")
return True
else:
logger.error(f"通过企业微信发送文本消息失败:{response.text}")
return False

def send_markdown(self, content):
"""
发送markdown消息
目前支持的markdown语法是如下的子集:
1. 标题 (支持1至6级标题,注意#与文字中间要有空格)
2. 加粗
3. 链接
4. 行内代码段(暂不支持跨行)
5. 引用
6. 字体颜色(只支持3种内置颜色), 绿色(color="info"),灰色(color="comment"),橙红色(color="warning")
:param content: markdown内容,最长不超过4096个字节,必须是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"通过企业微信发送md消息成功:{response.json()}")
return True
else:
logger.error(f"通过企业微信发送md消息失败:{response.text}")
return False

def send_picture(self, image_path):
"""
发送图片消息
: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"), # # 将图片数据转换成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"通过企业微信发送图片消息成功:{response.json()}")
return True
else:
logger.error(f"通过企业微信发送图片失败:{response.text}")
return False

def send_text_picture(self, articles: list):
"""
发送图文消息
:param articles: 图文消息,一个图文消息支持1到8条图文, 包括如下字段
1. title: 标题,不超过128个字节,超过会自动截断
2. description: 非必填,描述,不超过512个字节,超过会自动截断
3. url: 点击后跳转的链接。
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"通过企业微信发送图文消息成功:{response.json()}")
return True
else:
logger.error(f"通过企业微信发送图文失败:{response.text}")
return False

def upload_file(self, file_path):
"""
上传文件到企业微信服务器(要求文件大小在5B~20M之间)
注意:素材上传得到media_id,该media_id仅三天内有效;media_id只能是对应上传文件的机器人可以使用
: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"上传文件失败:{response.text}")
return False

def send_file(self, media_id):
"""
发送文件
: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"通过企业微信发送文件消息成功:{response.json()}")
return True
else:
logger.error(f"通过企业微信发送文件消息失败:{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>,请相关同事注意。\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": "中秋节礼品领取",
"description": "今年中秋节公司有豪礼相送",
"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))
-----------------------------------
python 读取企业微信信息 python调用企业微信发送消息
https://blog.51cto.com/u_16213699/7487495

标签:调用,python,微信,self,url,json,text,response
From: https://www.cnblogs.com/zhaoyuanshi/p/17775054.html

相关文章

  • 在Python中range()的用法:
    在Python中,range()是一个内置函数,用于生成一个整数序列,通常用于循环遍历。以下是range()函数的一些常见用法:1.默认情况当你调用range()函数时,它会生成一个从0开始到给定数字(不包括该数字)的整数序列。foriinrange(5):print(i)#输出:0,1,2,3,42.指定开始和结......
  • 25 个超棒的 Python 脚本合集
     Python是一种功能强大且灵活的编程语言,拥有广泛的应用领域。下面是一个详细介绍25个超棒的Python脚本合集:1.网络爬虫:使用Python可以轻松编写网络爬虫,从网页中提取数据并保存为结构化的格式。2.数据清洗和预处理:Python提供了许多库和工具,用于数据清洗、去重、填充缺失值和......
  • python 类装饰器,方法装饰器
    一:装饰器介绍1.为何要用装饰器Python中的装饰器是一种语法糖,可以在运行时,动态的给函数或类添加功能。装饰器本质上是一个函数,使用@+函数名就是可实现绑定给函数的第二个功能。将一些通用的、特定函数的功能抽象成一个装饰器,可以重复利用这些功能2.什么是装饰......
  • vscode远程ubuntu,python不识别opencv的函数
    将opencv-python更新到4.8版本以上https://github.com/microsoft/pylance-release/issues/4838......
  • python数据清洗日期格式和ipv4地址格式
    清洗日期格式importrefromdatetimeimportdatetime#读取文件withopen('result.txt','r')asfile:data=file.read()#使用正则表达式查找日期时间字符串pattern=r'(\d{2}/[A-Za-z]{3}/\d{4}:\d{2}:\d{2}:\d{2}\+\d{4})'matches=re.find......
  • Python中如何将字符串变成数字?
    字符串和数字是Python中常见的数据类型,而且在撰写Python程序的时候,也经常会遇到需要将字符串转换为数字的情况,那么Python中如何将字符串变成数字?有多种方法可以使用,接下来一起来看看具体内容介绍。1、使用int()函数int()函数可以将字符串转换为整数类型。例如,将字符串......
  • python脚本中应用多线程和多进程理解
    脚本内容因为要读取mongo某个全表数据(亿级别),有个字段有索引且是一堆多的关系从其他表读取所有这个字段(十万级别),再读取大表因为数据量大所以写个测试,从中拿出几条去大表查询(每次读到十万级别数据)多线程和多进程的影响不使用多线/进程file=open('test2.csv','w')content......
  • python写爆破字典
    #coding:utf-8withopen('username.txt','wb')asf:foriinrange(00000,99999):line=str('w'+'%05d'%i)+'\n'f.write(line)f.close()    ......
  • python01
    #==============================#单行注释以警号开始#注释一般是用在有意义的代码上,helloworld大家都看得懂,没必要注释"""  多行注释内容,三个双引号或者单引号都可以  '''多行注释内容'''"""print("HelloWorld!")#==============================#......
  • 手机网页通过微信deeplink实现wap支付
    微信支付里目前已经不支持wap支付,在非微信浏览器手机网页中实现支付,可以开通H5支付。H5支付是调用微信下单接口后返回微信的一个H5链接,前端跳转到这个H5链接,这个H5链接是个支付中间页,实现了和微信app通信,拉起微信支付,并回跳商户return_url的功能,而当用户返回时,会停留在这个支付中......