Look, how to send alarm notification to wechat in Python?

Posted by nymall on Fri, 24 Dec 2021 02:41:51 +0100

Hello, I'm Chen Chen!

Common alarm methods include email, telephone, SMS and wechat.

SMS and phone calls are usually charged (if you don't charge, you can comment and share), while email is not so timely, so I finally chose wechat notification.

The wechat mentioned here is enterprise wechat, and I have used the license to register an individual before, so I can easily register my own enterprise wechat.

1. Create a new application

Log in to the web version of enterprise wechat( https://work.weixin.qq.com/ ), click application management - > Application - > create application

Upload the logo of the application, enter the application name, and then select the visible range to successfully create an alarm application

2. Obtain Secret

When Python is used to send alarm requests, only two interfaces are used

  • Get Token: https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid= {corpid}&corpsecret={secret}
  • Send request: https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}

As you can see, the most important are corpid and secret:

  • corpid: uniquely identify your business
  • secret: application level key. Only with it can the program know which application you want to send to the enterprise

corpid can be obtained through my enterprise - > enterprise information

It's a little more troublesome to obtain secret. Click to create an application and click to view secret

Then click send and it will be sent to your enterprise wechat

Finally, fill the following constants with corpid and secret.

import json
import datetime
import requests

CORP_ID = ""
SECRET = ""

class WeChatPub:
    s = requests.session()

    def __init__(self):
        self.token = self.get_token()

    def get_token(self):
        url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={CORP_ID}&corpsecret={SECRET}"
        rep = self.s.get(url)
        if rep.status_code != 200:
            print("request failed.")
            return
        return json.loads(rep.content)['access_token']


    def send_msg(self, content):
        url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + self.token
        header = {
            "Content-Type": "application/json"
        }
        form_data = {
            "touser": "@all",
            "toparty": " PartyID1 | PartyID2 ",
            "totag": " TagID1 | TagID2 ",
            "msgtype": "textcard",
            "agentid": 1000002,
            "textcard": {
                "title": "Service exception alarm",
                "description": content,
                "url": "URL",
                "btntxt": "more"
            },
            "safe": 0
        }
        rep = self.s.post(url, data=json.dumps(form_data).encode('utf-8'), headers=header)
        if rep.status_code != 200:
            print("request failed.")
            return
        return json.loads(rep.content)

Then you can send_msg function sent a message.

wechat = WeChatPub()
now = datetime.datetime.now()
timenow = now.strftime('%Y year%m month%d day %H:%M:%S')
wechat.send_msg(f"<div class=\"gray\">{timenow}</div> <div class=\"normal\">Alibaba cloud cookie Invalid</div><div class=\"highlight\">Please replace it with a new one as soon as possible cookie</div>")

As long as your enterprise wechat does not have the permission to close the notification, your mobile phone will pop up this alarm message immediately.

In a few simple steps, the enterprise wechat is connected to realize the real-time alarm function of the mobile phone. It is recommended to students with enterprise wechat.

Of course, there must be more and better implementation methods. I just chose one of them. If you have good ideas, you can also share them in the comment area.