利用服務器和釘釘API給釘釘賬號發消息,在很多實際的場景中會有作用,比如應用程序的報警通知,或者數據報表的通知等等。微信目前的開放程度沒有釘釘強,使用釘釘API可以很方便的做到,這里就簡單總結一下步驟。
有幾個關鍵步驟需要完成。
注冊一個釘釘賬號
這個比較簡單,自行下載釘釘客戶端注冊,或者在網站上注冊即可。
在釘釘開發者平台上注冊一個團隊
通過釘釘開發者平台https://ding-doc.dingtalk.com/注冊團隊,用前面注冊釘釘賬號的手機來注冊團隊,這樣可以讓團隊管理綁定釘釘賬號。這一步比較重要,因為后續團隊涉及到認證問題,只有認證才能獲取到調用API所需要的token。綁定釘釘賬號,這些過程就變得簡單。
創建H5微應用
注冊團隊完成后,就可以跳轉登陸https://open-dev.dingtalk.com/,也就是釘釘開放平台。在開放平台中創建H5微應用。
之后就可以拿到三個重要的信息,AgentID、APPkey、APPSecret。
利用工作通知發送消息
幾個需要注意的地方。
-
使用API需要access_token,這個需要利用API做一次交互獲取;
-
發送消息是基於userid,這個userid跟釘釘賬號還不一樣,是釘釘開發者平台的userid。可以通過釘釘賬號的信息來獲取,這里使用的是get_userid用手機號獲取方式;
-
利用工作通知發送是一個取巧的方式。因為其它方式,需要創建或者獲取對話,相對麻煩,而工作通知可以直接發送消息;
-
重復的消息內容會被去重;
-
消息的格式可以參考https://ding-doc.dingtalk.com/doc#/serverapi2/pgoxpy;
#! /bin/env python # -*- coding: UTF-8 -*- import sys import json if sys.version_info.major <= 2: print("not support python2") sys.exit(0) import urllib.request as request import urllib.parse APP_KEY = "你的APPKey" APP_SECRET = "你的APPSecret" AGENT_ID = "你的AgentID" def get_access_token(): req = request.urlopen('https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s' % (APP_KEY, APP_SECRET)) res = req.read().decode('utf-8') data = json.loads(res) if data["errcode"] == 0: return data["access_token"] else: return None def get_userid(access_token, mobile): req = request.urlopen('https://oapi.dingtalk.com/user/get_by_mobile?access_token=%s&mobile=%s' % (access_token, mobile)) res = req.read().decode('utf-8') data = json.loads(res) if data["errcode"] == 0: return data["userid"] else: return None def post_message(userid, access_token): msg = {} msg["userid_list"] = userid msg["agent_id"] = AGENT_ID msg["msg"] = {} msg["msg"]["msgtype"] = "text" msg["msg"]["text"] = {} msg["msg"]["text"]["content"] = "This is a test message2!" postData = urllib.parse.urlencode(msg) postData = postData.encode('utf-8') res = request.urlopen('https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=%s' % access_token, postData) result = res.read() print(result) if __name__ == '__main__': access_token = get_access_token() userid = get_userid(access_token, "接收賬號對應的手機號") post_message(userid, access_token) sys.exit(0)
注意事項:
使用api時需要開啟接口權限管理
還要開啟api調用白名單IP