python調用釘釘API發送消息

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 2017-8-20 釘釘API發送消息

import urllib, urllib2
import requests
import json
import os
import sys

'''
釘釘管理後臺 : http://open-dev.dingtalk.com
CorpId       : 企業應用ID
secrect      : corpSecret管理列表下面 企業應用的憑證密鑰
'''
corpid = ''
secrect = ''

#獲取access_token
def getToken():
    url          = 'https://oapi.dingtalk.com/gettoken?corpid=%s&corpsecret=%s' % (corpid, secrect)
    req          = urllib2.Request(url)
    result       = urllib2.urlopen(req)
    access_token = json.loads(result.read())
    return access_token['access_token']

#默認情況下第一次創建羣組 並獲取羣組id chatid並寫入文件裏
def getChatid(access_token):
    file_name = "/tmp/.chatid" 
    #判斷羣組id文件是否存在
    if not os.path.exists(file_name):
        url = 'https://oapi.dingtalk.com/chat/create?access_token=%s' % access_token
        '''
        name : 羣組名字
        owner: 羣主userid
        useridlist: 羣成員userId列表 也可以寫羣主userid
        '''
        data = {
                "name": "test1",
                "owner": "manager302",
                "useridlist": ["manager302"]
        }
        data   = json.dumps(data)
        req    = requests.post(url, data)
        chatid = json.loads(req.text)['chatid']
        with open(file_name,'w') as fd:
            fd.write(chatid)
    else:
        with open(file_name) as fd:
            chatid = fd.read()
    return chatid

#access_token 訪問令牌 chatid 羣組id content 發送的內容
def tonews(access_token, chatid, content):
    '''
    chatid  : 羣組id
    msgtype : 類型
    content : 內容
    '''
    url    = "https://oapi.dingtalk.com/chat/send?access_token=%s" % access_token
    msgtype = 'text'
    values  = {
               "chatid": chatid,
               "msgtype": msgtype,
               msgtype: {
                   "content": content
               }
    }
    values = json.dumps(values)
    data   = requests.post(url, values)
    errmsg = json.loads(data.text)['errmsg']
    if errmsg == 'ok':
        return "ok"
    return "fail: %s" % data.text

if __name__ == '__main__':
    access_token = getToken()
    chatid = getChatid(access_token)
    content = '\\\\\\\\n'.join(sys.argv[1:])
    if not content:
        content = '測試'
    print tonews(access_token, chatid, content)

[root@tieba ~]# python dingding.py 123 測試測試 測試測試



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章