首頁  >  文章  >  後端開發  >  只要三步,如何用Python發送通知到微信?

只要三步,如何用Python發送通知到微信?

WBOY
WBOY轉載
2023-05-02 22:55:052113瀏覽

                      只要三步,如何用Python發送通知到微信?一、以何種通知通知方式?

大家好,我是菜鳥哥。

常見的通知方式有:郵件,電話,短信,微信。簡訊和電話:通常是收費的,較少使用;郵件:適合帶文件類型的通知,較正式,存檔使用;微信:適合告警類型通知,較方便。這裡說的微信,是企業微信。

本文目的:透過企業微信應用程式傳送訊息給企業成員。 二、如何實現企業微信通知?

1、新應用程式

登陸網頁版企業微信(https://work.weixin.qq.com),點選應用程式管理→ 應用程式→建立應用程式

只要三步,如何用Python發送通知到微信?

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

只要三步,如何用Python發送通知到微信?

2、取得Secret

使用Python 傳送警告請求,其實只使用到兩個介面:

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

##發送請求:#https://www. php.cn/link/8123b781e08f4d9e89ea88f53e6431a9

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

corpid:唯一標識你的企業

secret:應用程式級的金鑰,有了它程式才知道你要傳送該企業的哪個應用程式

corpid 可以透過我的企業→ 企業資訊→ 企業id 取得

只要三步,如何用Python發送通知到微信?

secret 可以透過點選新建立的應用程式(債券打新) → 檢視secret → 傳送來取得

只要三步,如何用Python發送通知到微信?只要三步,如何用Python發送通知到微信?

最後將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"{timenow} 注意!今日有新债,坚持打新!")
    print('消息已发送!')


4、實作效果:

只要三步,如何用Python發送通知到微信?

只要三步,如何用Python發送通知到微信?

只要三步,如何用Python發送通知到微信?



以上是只要三步,如何用Python發送通知到微信?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:51cto.com。如有侵權,請聯絡admin@php.cn刪除