程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How to send notifications to wechat in Python?

編輯:Python
 Click on the above “ Rookie Science Python”, choice “ Star standard ” official account 

Super invincible dry goods , First time delivery !!!

Source network

One 、 What are the ways of notification ?

Common notification methods are : mail , Telephone , SMS , WeChat . SMS and phone : It's usually for a fee , Use fewer ; mail : Suitable for notifications with file types , More formal , Archive use ; WeChat : Suitable for alarm type notification , More convenient . Wechat here , It's enterprise wechat .

Purpose of this paper : Send messages to enterprise members through enterprise wechat application .

Two 、 How to realize enterprise wechat notification ?

1、 New application

Log in to the web version of enterprise wechat (https://work.weixin.qq.com), Click on Application management → application → Create an

Upload the app logo, Enter the app name ( New bonds ), Then select the visible range , Successfully create an alarm application

2、 obtain Secret

Use Python Send alarm request , In fact, only two interfaces are used :

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

Send a request :https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}

You can see , most important of all corpid and secret:

corpid: Uniquely identify your business

secret: Application level key , With it, the program will know which application you want to send to the enterprise

corpid Can pass My business → Enterprise information → Enterprises id obtain

secret Can pass Click on Newly created app ( New bonds ) → see secret → send out To get

The final will be corpid and secret Fill in the constants below .

3、 Code implementation

import json
import time
import requests
'''
This document mainly realizes sending messages to enterprise members through enterprise wechat application
'''
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",# recipient
            "toparty": "1",# Receiving department
            "totag": " TagID1 | TagID2 ",# Address book labels id
            "msgtype": "textcard",
            "agentid": 1000002,# application ID
            "textcard": {
                "title": " Bond renewal reminder ",
                "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)
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\"> Be careful !</div><div class=\"highlight\"> There are new debts today , Keep playing new !</div>")
    print(' Message sent !')

4、 Realization effect :

 Recommended reading :
introduction :  The most complete zero Foundation Python The problem of   |  Zero Basics 8 Months Python  |  Actual project  | learn Python That's the shortcut
dried food : A short comment on crawling Douban , The movie 《 The rest of us 》 | 38 year NBA Best player analysis  |    From people's expectation to public praise ! Tang Dynasty detective 3 disappointing   |  Laugh at the story of the new Yitian dragon slaying  |  Riddle answer King  | use Python Make a massive sketch of my little sister  | Mission impossible is so hot , I use machine learning to make a mini recommendation system movie
Interest : Pinball game   |  squared paper for practicing calligraphy   |  Beautiful flowers  |  Two hundred lines Python《 Cool run every day 》 game !
AI:  A robot that can write poetry  |  Color the picture  |  Forecast revenue  |  Mission impossible is so hot , I use machine learning to make a mini recommendation system movie
Gadget : Pdf turn Word, Easily handle forms and watermarks ! |  One touch html Save the page as pdf!|   bye PDF Withdrawal charges ! |  use 90 Lines of code create the strongest PDF converter ,word、PPT、excel、markdown、html One click conversion  |  Make a nail low-cost ticket reminder ! |60 Line of code to do a voice wallpaper switcher, look at my little sister every day !|

Annual hot money copy

  • 1). Oh my god !Pdf turn Word use Python Easy to handle !

  • 2). learn Python It's delicious ! I use 100 Line of code to make a website , Help people PS Travel pictures , Earn a chicken leg to eat

  • 3). Premiere billions , Hot all over the net , I analyzed 《 My sister 》, Discovered the secrets  

  • 4).80 Line code ! use Python Make a dorai A Dream separation  

  • 5). What you have to master 20 individual python Code , short , Useful  

  • 6).30 individual Python Strange sexual skills Collection  

  • 7). I summed up 80 page 《 Rookie Science Python Select dry goods .pdf》, Is dry  

  • 8). bye Python! I have to learn Go 了 !2500 Word depth analysis !

  • 9). Found a licking dog welfare ! This Python Reptile artifact is great , Automatically download sister pictures

Click to read the original , see B Stand my video !


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved