日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python應用之如何使用Python發送通知到微信_python

作者:?shammy ? 更新時間: 2022-05-31 編程語言

一、通知方式有哪些?

常見的通知方式有:郵件,電話,短信,微信。

短信和電話:通常是收費的,較少使用;

郵件:適合帶文件類型的通知,較正式,存檔使用;

微信:適合告警類型通知,較方便。這里說的微信,是企業微信。

本文目的:通過企業微信應用給企業成員發消息。

二、如何實現企業微信通知?

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('消息已發送!')

4、實現效果:

三、參考資料

如何用 Python 發送告警通知到微信?

用python給微信公眾號發消息

總結

原文鏈接:https://blog.csdn.net/shammy_feng/article/details/123711347

欄目分類
最近更新