1. 程式人生 > >python調用企業微信API

python調用企業微信API

python api wechat

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 2017-07-25 編寫

import json
import sys
import urllib, urllib2

"""
CorpID 企業ID
Secret 應用密鑰
"""
CorpID  = ‘‘
Secret  = ‘‘
touser  = ‘@all‘
content = ‘‘

#獲取access_token
def getToken(CorpID, Secret):
    url          = ‘https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s‘ % (CorpID, Secret)
    req          = urllib2.Request(url)
    result       = urllib2.urlopen(req)
    access_token = json.loads(result.read())
    return access_token[‘access_token‘]

#發送消息
def tonews(access_token, content):
    url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token
    """
    touser  成員 @all 就是所有
    toparty 部門ID @all 就是所有
    msgtype 文本類型
    agentid 企業應用ID
    content 內容
    safe 是否保密 0是不保密
    """
    values = {
               "touser"  : touser,
               "toparty" : ‘2‘,
               "msgtype" : "text",
               "agentid" : 1,
               "text"    : {
                            "content" : content
                           },
     "safe"    :"0"
    }
    send_data    = json.dumps(values)
    send_request = urllib2.Request(url, send_data)
    response     = json.loads(urllib2.urlopen(send_request).read())
    if response[‘errcode‘] == 0:
        print ‘發送消息成功‘

if __name__ == ‘__main__‘:
   access_token = getToken(CorpID, Secret)
   print "獲取token成功"
   content = ‘\n‘.join(sys.argv[1:])
   if not content:
       content = "測試成功"
   tonews(access_token, content)

[[email protected] /]# python wechat.py 456 678 //需要傳遞的數據

本文出自 “小卡” 博客,請務必保留此出處http://xiaocuik.blog.51cto.com/12090846/1968648

python調用企業微信API