1.登录企业微信后台
若没有可进行注册:https://work.weixin.qq.com/wework_admin/register_wx?from=myhome_mp_home
2.创建部门:通讯录--添加部门(给此部门的成员提供报警消息)--添加成员--记录部门id
3.创建应用:应用管理--自建--创建应用--填写信息(选择刚刚创建的部门)记录agent_id,secret
4.企业id:我的企业记录企业id
demo:wechat.py
import logging
import requests
logger = logging.getLogger(__name__)
class Wechat(object):
"""
微信企业号报警服务
"""
def __init__(self, appid, secret, party_id, agent_id):
self.appid = appid
self.secret = secret
# 订阅号
# self.get_token_api = "https://api.weixin.qq.com/cgi-bin/token"
# 企业微信
self.get_token_api = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
self.send_msg_api = "https://qyapi.weixin.qq.com/cgi-bin/message/send"
self.token = self.get_token()
self.party_id = party_id
self.agent_id = agent_id
def get_token(self):
"""
获取token, 调用其他接口必要的凭证
"""
params = {
"corpid": self.appid,
"corpsecret": self.secret
}
resp = requests.get(self.get_token_api, params=params)
data = resp.json()
token = data.get("access_token")
if not token:
raise UserWarning("get token error detail: %s" % data)
logger.info("get token successed")
return token
def send_msg(self, msg, party_id, agent_id):
"""
发送文本消息到用户组
@party_id: 通讯录的组id
@agent_id: 创建的应用id
@msg: 发送的文本数据
"""
params = {
"access_token": self.token,
}
body = {
"toparty": party_id,
"msgtype": "text",
"agentid": agent_id,
"text": {
"content": msg,
},
}
resp = requests.post(self.send_msg_api, params=params, json=body)
data = resp.json()
code = data.get("errcode")
if code == 0:
logger.info("send msg successed")
return
if code == 42001:
logger.warning("token expires")
self.token = self.get_token()
return self.send_msg(party_id, agent_id, msg)
else:
logger.error("send msg error detail: %s" % data)
def alarm(self, msg):
"""
发送文本报警信息
"""
self.send_msg(msg, self.party_id, agent_id)
# 企业id
appid = "ww9f17adaf3"
# 应用id
agent_id = "1000002"
# 部门id
party_id = 2
# 应用的盐值
secret = "uJW07AcQFaK7cSwk9Du0o6FTnOTtz2IiMs8h"
wechat = Wechat(appid=appid, secret=secret, party_id=party_id, agent_id=agent_id)
if __name__ == '__main__':
wechat.alarm("This is a test")
转载:https://blog.csdn.net/qq_41864652/article/details/101472964
查看评论