1、python操作企业微信群机器人发送群消息(日常使用企业微信)
import requests
创建企业微信群并创建群机器人
1、先在企业微信群
2、在企业微信群中创建机器人,
3、获取webhook地址中的key信息
https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=*************************
特别特别要注意:一定要保护好机器人的webhook地址,避免泄漏!不要分享到github、博客等可被公开查阅的地方,否则坏人就可以用你的机器人来发垃圾消息了。
python操作机器人
发送文字
#自定义函数
def wx_post(text,wx_key):
wx_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s'%wx_key # 发送消息接口地址
data2 = {
"msgtype": "text",
"text": {
"content": "如下为截止到昨天的中端车数据,请查收", #信息内容
"mentioned_list":["wx_userid","@all"], #需要@的人的userid(需要企业管理人员才能看到,可用手机号@)
#"mentioned_mobile_list":["12345678910","@all"] #需要@的人的手机号,或@all
}
}
r1= requests.post(url=wx_url, json=data2) #发送信息
return
发送文件(不大于20M的文件)
def wx_post(filename,wx_key):
#文件上传获取media_id
id_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=%s&type=file'%wx_key # 上传文件接口地址
data = {'file': open(filename, 'rb')} # post jason
response = requests.post(url=id_url, files=data) # post 请求上传文件
json_res = response.json() # 返回转为json
media_id = json_res['media_id'] # 提取返回ID
#发送文件
wx_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s'%wx_key # 发送消息接口地址
data = {"msgtype": "file", "file": {"media_id": media_id}}
r= requests.post(url=wx_url, json=data) #发送信息
return
发送图片
发送图片需要base64和hashlib两个包(图片需要转成base64格式,并转为MD5值)
import requests
import base64
import hashlib
def wx_post(filename,wx_key)
with open(image, 'rb') as file: #转换图片成base64格式
data = file.read()
encodestr = base64.b64encode(data)
image_data = str(encodestr, 'utf-8')
with open(image, 'rb') as file: #图片的MD5值
md = hashlib.md5()
md.update(file.read())
image_md5 = md.hexdigest()
wx_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s'%wx_key
data = {
"msgtype": "image",
"image": {
"base64": image_data,
"md5": image_md5
}
}
r= requests.post(url=wx_url, json=data) #发送信息
return
其他还可以发送markdown等,可参考企业微信中的相关资料