使用Python發送企業微信消息

準備工做:html

    到企業微信官網,註冊一個企業;登陸企業微信後臺,建立一個「自建」應用, 獲取企業ID、agentid、secret這3個必要的參數;在企業微信的通信錄中,建立多個測試帳號;在手機端安裝「企業微信」APP,使用測試帳號登陸到企業微信,準備接收消息。python

 

程序代碼json

    企業微信提供API開發接口,經過HTTPS的GET、POST方法與企業微信後臺進行交互,完成獲取令牌、發送數據、獲取數據的操做。c#

    Python代碼主要使用requests庫,將企業微信API進行簡單封裝,模擬https的GET、POST操做,向指定的用戶發送企業微信消息。api

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import requests
import json


class WeChat:
    def __init__(self):
        self.CORPID = 'ww2e1234567895498f5498f'  #企業ID,在管理後臺獲取
        self.CORPSECRET = 'xy11234567898hk_ecJ123456789DhKy4_1y12345OI'#自建應用的Secret,每一個自建應用裏都有單獨的secret
        self.AGENTID = '1000002'  #應用ID,在後臺應用中獲取
        self.TOUSER = "maomao|dingding"  # 接收者用戶名,多個用戶用|分割

    def _get_access_token(self):
        url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
        values = {'corpid': self.CORPID,
                  'corpsecret': self.CORPSECRET,
                  }
        req = requests.post(url, params=values)
        data = json.loads(req.text)
        return data["access_token"]

    def get_access_token(self):
        try:
            with open('./tmp/access_token.conf', 'r') as f:
                t, access_token = f.read().split()
        except:
            with open('./tmp/access_token.conf', 'w') as f:
                access_token = self._get_access_token()
                cur_time = time.time()
                f.write('\t'.join([str(cur_time), access_token]))
                return access_token
        else:
            cur_time = time.time()
            if 0 < cur_time - float(t) < 7260:
                return access_token
            else:
                with open('./tmp/access_token.conf', 'w') as f:
                    access_token = self._get_access_token()
                    f.write('\t'.join([str(cur_time), access_token]))
                    return access_token

    def send_data(self, message):
        send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token()
        send_values = {
            "touser": self.TOUSER,
            "msgtype": "text",
            "agentid": self.AGENTID,
            "text": {
                "content": message
                },
            "safe": "0"
            }
        send_msges=(bytes(json.dumps(send_values), 'utf-8'))
        respone = requests.post(send_url, send_msges)
        respone = respone.json()   #當返回的數據是json串的時候直接用.json便可將respone轉換成字典
        return respone["errmsg"]


if __name__ == '__main__':
    wx = WeChat()
    wx.send_data("這是程序發送的第1條消息!\n Python程序調用企業微信API,從自建應用「告警測試應用」發送給管理員的消息!")
    wx.send_data("這是程序發送的第2條消息!")

 

運行截圖:微信

  

 

  

 

參考連接:post

python實現經過企業微信發送消息測試

http://www.javashuo.com/article/p-qewqrvyn-cp.htmlurl

 

python腳本--用企業微信實現發送信息spa

http://www.javashuo.com/article/p-unaouiyh-kx.html

 

企業微信後臺管理:

https://work.weixin.qq.com/

 

企業微信API文檔:

https://work.weixin.qq.com/api/doc#90000/90003/90487

相關文章
相關標籤/搜索