准備工作:
首先,到企業微信官網注冊一個企業微信,注冊過程我就不闡述了。然后登錄企業微信后台,在應用管理-應用-自建中創建應用:如下圖
創建完成之后:展示如下
獲取企業ID、agentid、secret這3個必要的參數,后面的代碼需要,自己保存好,在企業微信的通訊錄中,可以創建多個測試賬號;在手機端安裝“企業微信”APP,使用測試賬號登錄到企業微信,准備接收消息。
程序代碼:
企業微信提供API開發接口,通過HTTPS的GET、POST方法與企業微信后台進行交互,完成獲取令牌、發送數據、獲取數據的操作。
Python代碼主要使用requests庫,將企業微信API進行簡單封裝,模擬https的GET、POST操作,向指定的用戶發送企業微信消息。
import requests import json import sys import importlib importlib.reload(sys) requests.packages.urllib3.disable_warnings() class WeChat: def __init__(self): self.CORPID = '' self.CORPSECRET = '' self.AGENTID = '' self.TOUSER = "" # 接收者用戶名 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, verify=False) return req def get_access_token(self): get_req = self._get_access_token() if get_req.status_code != 200: print('連接服務器失敗') else: get_req_json = json.loads(get_req.text) if get_req_json['errcode'] != 0: print('響應結果不正確') else: access_token = get_req_json['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, verify=False) respone = respone.json() return respone["errmsg"] if __name__ == "__main__": wx = WeChat() wx.send_data("您有新的測試寶寶未處理,請登入http://www.xxx.com系統查看。")
運行展示結果如下:
參考鏈接:
python實現通過企業微信發送消息
https://www.cnblogs.com/rancher-maomao/p/10860069.html
python腳本--用企業微信實現發送信息
https://blog.csdn.net/liyyzz33/article/details/86080936
企業微信后台管理:
企業微信API文檔:
https://work.weixin.qq.com/api/doc#90000/90003/90487