python利用企业微信api来进行发送自定义报警的类实现

http://blog.51cto.com/7706173/1955976

python利用企业微信api来进行发送自定义报警的类实现

  1. 企业微信注册

    打开http://work.weixin.qq.com/企业微信主页;

    wKioL1mQWsHgzC_4AAUT2UUM0Nw651.png-wh_50a

    点击企业注册;

wKioL1mQWyHz_PniAAB76ksmaao280.png-wh_50

填写相关信息,营业执照和注册号可以不用填,直接下一步,按照提示操作即可;

注册完成后,登陆,就显示如下界面:

wKiom1mQXEbTXR84AAD2Y4eqMnc163.png-wh_50

点击我的企业标签:

wKioL1mQXMuzIM8CAACK0TjYlnM839.png-wh_50

看到如上界面,复制CorpID对应的值;

点击企业应用

wKiom1mQXWfilkKhAAB28XmBUZI997.png-wh_50

点击 创建应用

wKioL1mQXciBgtotAABo__DcRVg329.png-wh_50

填写对应内容,点击创建应用即可;

然后再点击企业应用,就可以在自建应用里看到自己创建的应用;

点击应用图标,看到如下图

wKioL1mQXjKDZtrIAACidJ1quzE226.png-wh_50

复制AgentId、Secret

至此我们需要的三个值就都有(AgentId、Secret、CorpID

2.程序实现

接下来我们用python的类来实现

git clone https://github.com/yxxhero/weixinalarm.git

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env python
# encoding: utf-8
# -*- coding: utf8 -*-
import  urllib
import  urllib2
import  json
import  sys
import  time
import  os
import  logging
reload (sys)
sys.setdefaultencoding( 'utf8' )
#日志模式初始化
logging.basicConfig(level = "DEBUG" ,
                 format = '%(asctime)s  %(levelname)s %(message)s' ,
                 datefmt = '%Y-%m-%d %H:%M:%S' ,
                 filename = './log/dark_status.log' ,
                 filemode = 'a' )
class  weixinalarm( object ):
     def  __init__( self ,corpid,secrect,agentid):  #构造函数,获取关键变量
         self .corpid = corpid
         self .secrect = secrect
         self .agentid = agentid
     def  get_access_token( self ):  #获取token
         access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + self .corpid + "&corpsecret=" + self .secrect
         try :
             res_data  =  urllib2.urlopen(access_token_url,timeout = 3 )
             access_token = json.loads(res_data.read())[ "access_token" ]
         except  Exception,e:
             logging.info( str (e))
             logging.info( "access_token获取超时" )
             return  None 
         else :
             return  access_token
     def  check_token( self ):  #检查token的缓存文件是否存在或者超时,如果不存在或者超时重新获取。
         if  os.path.exists( "/tmp/weixinalarm" ):
             with  open ( "/tmp/weixinalarm" , "r+" ) as fd:
             result_info = fd.read().split( "^" )
                 timestamp = result_info[ 1 ]
                 if  time.time() - int (timestamp) < 7200 :
                     access_token = result_info[ 0 ]
             return  access_token
                 else :
                     access_token = self .get_access_token()
                     timestamp = time.time()
                     tokentime = access_token + "^" + str (timestamp).split( "." )[ 0 ]
                     with  open ( "/tmp/weixinalarm" , "w" ) as fd:
                         fd.write(tokentime)
             return  access_token
         else :
             access_token = self .get_access_token()
             timestamp = time.time()
             tokentime = access_token + "^" + str (timestamp).split( "." )[ 0 ]
             with  open ( "/tmp/weixinalarm" , "w" ) as fd:
                 fd.write(tokentime)
         return  access_token
     def  sendmsg( self ,title,description):  #利用api发送消息,具体的api格式可以参考官方文档
         try :
         access_token = self .check_token()
             if  access_token:
                 send_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token
                 send_info = {
                 "touser"  "@all" ,
                 "msgtype"  "text" ,
                 "agentid"  self .agentid,
                 "text" :{
                     "content" : str (title) + ":" + str (description)
                     }
                 }
                 logging.info(send_info)
                 send_info_urlencode  =  json.dumps(send_info)
                 #send_info_urlencode = json.dumps(send_info,ensure_ascii=False)
                 req = urllib2.Request(url  =  send_url,data  = send_info_urlencode)
                 response = urllib2.urlopen(req,timeout = 3 )
                 res_info = response.read()
             else :
                 logging.error( "no access_token" )
         except  Exception,e:
             logging.error( str (e))
         else :
             alarm_result = json.loads(res_info)
             if  int (alarm_result[ "errcode" ]) = = 0 :
                 logging.info( "报警正常" )
             else :
                 logging.info(alarm_result[ "errmsg" ])
         finally :
             if  response:
                 response.close()

代码很简单,有想和我交流的可以加我微信18333610114

基本使用:

1
2
3
4
5
6
7
from  weixinalarm  import  weixinalarm
sender = weixinalarm(corpid = Secret,secrect = Secret,agentid = AgentId)
发送消息:
sender.sendmsg(title = "自定义" ,description = "自定义" )
即可
日志放在log下,log目录需自行创建,和weixinalarm.py同

### 如何在企业微信中开通并配置 Webhook #### ### 一、什么是企业微信 Webhook? 企业微信中的 Webhook 是一种轻量级的消息推送接口,允许开发者通过 HTTP POST 请求向指定 URL 发送 JSON 数据,从而实现消息通知功能。它常用于自动化流程的通知场景,比如任务完成提醒、报警信息发送等。 #### ### 二、开通与配置步骤 1. **创建应用** 登录企业微信管理后台,在“应用管理”页面点击“创建应用”。填写应用名称、Logo 和可见范围等内容后保存[^3]。 2. **获取 Webhook 地址** 在已创建的应用详情页中找到“接收消息”的设置项,启用入群机器人或自定义 Webhook 功能即可获得唯一的 Webhook URL[^4]。 3. **测试连接有效性** 使用 curl 命令或者 Postman 工具模拟发送一条简单的文本消息至上述地址验证其可用性: ```bash curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=your_webhook_key' \ -H 'Content-Type: application/json' \ -d '{"msgtype": "text", "text": {"content":"Hello, this is a test message!"}}' ``` 4. **编写业务逻辑代码** 根据实际需求设计程序调用此 API 的方式。例如利用 Python 脚本定期查询数据库状态并向相关人员汇报异常情况: ```python import requests webhook_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=your_webhook_key" def send_message(content): payload = { "msgtype": "text", "text": { "content": content } } response = requests.post(webhook_url, json=payload) return response.json() result = send_message("Database connection failed!") print(result) ``` 5. **集成高级特性** 如果希望进一步增强通知效果,则可以考虑引入卡片形式展示更多细节;或是结合 PowerJob 等分布式任务调度框架完成复杂作业流管控时的状态更新提示。 6. **安全加固措施** 对于敏感操作建议实施 IP 白名单限制访问来源以防恶意攻击者滥用接口资源造成不必要的损失[^5]。 --- #### ### 总结 以上即为企业微信 Webhook 的基本使用方法介绍及其应用场景举例说明。合理运用该技术手段能够显著提升团队协作效率降低沟通成本。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值