步驟是這樣:先申請公衆號,找到接口文件。看了之後發現主要是通過corpid(企業祕鑰)和corpsecret(應用祕鑰)獲得登錄token,通過這個token進入各個url操作。
我這個用的是企業微信,所以有部門。其他公衆號也類似。結果如下:
# -*- coding:utf-8 -*-
import requests
import json
import time
url0 = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
def get_group_id(): #查看部門與成員
values_address = {'corpid': '你的corpid',
'corpsecret': 通訊錄corpsecret',
}
req = requests.post(url0, params=values_address)
data = json.loads(req.text)
token = data["access_token"]
url_department="https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token="+token #部門
r_department=requests.get(url_department)
result_department=r_department.json()
result_department_no=result_department['department']
print("***已獲取部門信息如下:")
for item in result_department_no:
print("[部門]:",item['id']," [部門名稱]:",item[ 'name']," [父部門]:",item['parentid']," [序號]:",item['order'])
print("***已獲取成員信息如下:")
for i in range(len(result_department_no)):
i=i+1
url_member = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=%s&department_id=%s&fetch_child=FETCH_CHILD" % (token, i) # 成員
r_member = requests.get(url_member)
result_member = r_member.json()
result_member_no = result_member['userlist']
for item in result_member_no:
print("[成員id]:", item['userid'], " [成員名稱]:", item['name'], " [所屬部門]:", item['department'])
return result_department_no,result_member_no
def upload_img():
values_address = {'corpid': '你的corpsecret',
'corpsecret': '應用corpsecret',
}
req = requests.post(url0, params=values_address)
data = json.loads(req.text)
token = data["access_token"]
print("***已獲取token.")
url_upimg="https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s"%(token,"image")
files = {'filename': ('xn.JPG', open("D:\DOCS\DAY\郵件/DRjpg.JPG", 'rb'))
} # 顯式的設置文件名
values_upimg={
"Content - Type": 'multipart/form-data; boundary="----WebKitFormBoundaryn5UouHKhfu8g2XNp";',
"Content - Length": '331698; boundary="----WebKitFormBoundaryn5UouHKhfu8g2XNp";',
"Content - Disposition":'form-data; name="image"; boundary=----WebKitFormBoundaryn5UouHKhfu8g2XNp;',
"content - type": "application/octet-stream; boundary=----WebKitFormBoundaryn5UouHKhfu8g2XNp;"
}
req_upimg = requests.post(url_upimg,files=files, data=values_upimg)
data = json.loads(req_upimg.text)
media_id=data['media_id']
print("***已獲取素材所需id.")
return token,media_id
def send_msg(token,media_id): #發送圖片
url="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+token
values = {
"touser": "@all",
"toparty" : "2", #***************部門******************
"msgtype" : "image",
"agentid" : 1000003,
"image" : {
"media_id" : media_id
},
"safe":0
}
data = json.dumps(values)
req = requests.post(url, data)
print("返回結果:", req.text)
return req
#打印返回信息
while True:
current_time = time.localtime(time.time())
if ((current_time.tm_hour == 8) and (current_time.tm_min == 13) and (current_time.tm_sec == 50)):
(result_department_no, result_member_no) = get_group_id()
(token, media_id) = upload_img()
send_msg(token,media_id)
time.sleep(1)
效果是這樣: