笔记:使用python对飞书用户活跃度统计的一个尝试
说明
一个python练习
代码
import json
import time
import openpyxl
from openpyxl import load_workbook
from datetime import datetime, timedelta
import lark_oapi as lark
from lark_oapi.api.admin.v1 import *
def data_r(start_date, end_date):
r_data = []
client = lark.Client.builder() \
.app_id("app-id") \
.app_secret("app-secret") \
.build()
num = 1
more = True
token = ''
while more:
if num == 1:
request: ListAdminUserStatRequest = ListAdminUserStatRequest.builder() \
.user_id_type("user_id") \
.department_id_type("department_id") \
.start_date(start_date) \
.end_date(end_date) \
.department_id("id——num") \
.page_size(60) \
.build()
num = num + 1
else:
request: ListAdminUserStatRequest = ListAdminUserStatRequest.builder() \
.user_id_type("user_id") \
.department_id_type("department_id") \
.start_date(start_date) \
.end_date(end_date) \
.department_id("id——num") \
.page_size(60) \
.page_token(token) \
.build()
num = num + 1
response: ListAdminUserStatResponse = client.admin.v1.admin_user_stat.list(request)
# 处理失败返回
if not response.success():
lark.logger.error(
f"client.admin.v1.admin_user_stat.list failed, code: {response.code}, msg: {response.msg}, log_id: {response.get_log_id()}, resp: \n{json.dumps(json.loads(response.raw.content), indent=4, ensure_ascii=False)}")
return
more = response.data.has_more
token = response.data.page_token
items_j = lark.JSON.marshal(response.data, indent=4)
items = json.loads(items_j)
for item in items['items']:
o_data = [item['date'], item['user_name'], item['user_id'], item['department_path'], item['suite_active_flag'], item['last_active_time']]
r_data.append(o_data)
return r_data
def p2excel(wbname, wsname, l_value):
wb = load_workbook(wbname)
ws = wb[wsname]
for a in l_value:
ws.append(a)
wb.save(wbname)
def main():
start_date_s = '2024-07-01'
end_date_s = '2024-12-31'
format_str = '%Y-%m-%d'
start_date = datetime.strptime(start_date_s, format_str)
end_date = datetime.strptime(end_date_s, format_str)
# 数据表表头
wb_header = [['时间', '用户名', '用户id', '部门路径', '活跃状态', '最近活跃时间']]
nowdt = time.strftime("%Y-%m-%d-%H%M%S", time.localtime())
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), ":创建文件")
# 文件名
wbname = '飞书活跃用户数据_' + nowdt + '.xlsx'
# sheet 名
wsname = '活跃用户数据'
# 创建表格
log_wb = openpyxl.Workbook()
log_ws = log_wb.create_sheet(wsname, 0)
log_wb.save(wbname)
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), ":加入表头")
# 加入表头
p2excel(wbname, wsname, wb_header)
# 数据插入
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), ":开始数据插入:")
while start_date <= end_date:
result = []
next_date = start_date + timedelta(days=31)
if next_date > end_date:
next_date = end_date
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), ":", start_date.strftime(format_str), "-", next_date.strftime(format_str))
print('获取数据')
result = data_r(start_date.strftime(format_str), next_date.strftime(format_str))
print('插入数据')
p2excel(wbname, wsname, result)
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), ":", start_date.strftime(format_str), "-",
next_date.strftime(format_str), ' 完成')
start_date = next_date + timedelta(days=1)
if __name__ == "__main__":
main()