py 通過企業微信發送消息

 

1、新建應用

登錄網頁版企業微信 (https://work.weixin.qq.com),點擊 應用管理 → 應用 → 創建應用

上傳應用的 logo,輸入應用名稱(債券打新),再選擇可見範圍,成功創建一個告警應用

2、獲取Secret

使用 Python 發送告警請求,其實就只使用到兩個接口:

獲取 Token :https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={secret}

發送請求:https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}

可以看到,最重要的是 corpid 和 secret:

corpid:唯一標識你的企業

secret:應用級的密鑰,有了它程序才知道你要發送該企業的哪個應用

corpid 可以通過 我的企業 → 企業信息 → 企業id 獲取

secret 可以通過 點擊 新創建的應用(債券打新) → 查看 secret → 發送 來獲取

最後將 corpid 和 secret 填入下面的常量中。

3、代碼實現

import json
import time
import requests


CORP_ID = "xxxx"
SECRET = "xxxx"

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": "FengXianMei",#接收人
            "toparty": "1",#接收部門
            "totag": " TagID1 | TagID2 ",#通訊錄標籤id
            "msgtype": "textcard",
            "agentid": 1000002,#應用ID
            "textcard": {
                "title": "債券打新提醒",
                "description": content,
                "url": "URL",
                "btntxt": "更多"
            },
            "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)

if __name__ == "__main__":
    wechat = WeChatPub()
    timenow = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    wechat.send_msg(f"<div class=\"gray\">{timenow}</div> <div class=\"normal\">注意!</div><div class=\"highlight\">今日有新債,堅持打新!</div>")
    print('消息已發送!')

轉自:https://mp.weixin.qq.com/s/44Ondl9eYqFtnaQFzOl-DQ

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章