feat: 新增打卡明细接口支持,优化加班校验逻辑
1. 新增打卡明细接口封装,支持单页查询与自动分页获取员工真实打卡记录 2. 重构加班校验逻辑,使用打卡明细接口替代原考勤逐日接口的打卡字段,解决跨天打卡归属错误问题 3. 移除过时的打卡时间解析与单条打卡修正逻辑,简化代码维护 4. 优化OA登录脚本,新增requests依赖并完善会话校验逻辑 5. 新增钉钉群机器人推送通用模块,支持多场景通知推送
This commit is contained in:
@@ -0,0 +1,496 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: dingtalk_robot.py
|
||||
@Description: 钉钉群机器人推送自定义指令(影刀编码版 Python 模块源码,单一真源)。
|
||||
作为「37du钉钉群机器人推送」影刀自定义指令的模块源码,
|
||||
供所有需要往钉钉群发通知的影刀脚本/流程复用(周考勤、请假审批、加班审批、人事变动等),
|
||||
避免每个脚本各自内联 Webhook 加签与 Markdown 排版逻辑。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 dingtalk_robot,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 params(字典类型,dict),或分别增加 msgtype/title/content/status 等参数;
|
||||
4. 保存并「发版」;在需要钉钉群推送的应用中「获取指令」并安装;
|
||||
5. 在流程中拖入该指令,把业务脚本输出的参数传入(两种方式任选):
|
||||
方式A(推荐):流程中先拼一个字典变量(如 {"title": "任务执行失败", "content": "..."}),
|
||||
作为 params 整体传入;
|
||||
方式B:分别传 msgtype、title、content 等变量,指令内部自动拼成字典;
|
||||
指令返回 JSON:{"success": bool, "message": str},可在后续流程中判断是否重试。
|
||||
|
||||
推送原理(HTTP Webhook 方式,与 app/utils/dingtalk_robot.py 一致):
|
||||
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
|
||||
向机器人 Webhook 推送 JSON 消息,无需登录钉钉桌面端。
|
||||
失败自动重试 3 次,成功/失败均有日志。
|
||||
|
||||
依赖:
|
||||
仅使用 Python 标准库(urllib/hashlib/hmac/base64),零第三方依赖,无需 pip 安装。
|
||||
|
||||
约定(与项目 app 版一致,见 app/utils/dingtalk_robot.py):
|
||||
- 配置:影刀运行环境无 .env 文件读取,故推送地址/加签密钥/页脚署名
|
||||
直接内联在下方「默认参数」区(单一真源),改推送目标时改常量即可;
|
||||
也可在调用 main(args) 时通过 webhook/secret/server_name 参数覆盖;
|
||||
- 页脚署名默认 "小芒 任务调度平台":
|
||||
注意:钉钉机器人若配置了"自定义关键词"安全校验,
|
||||
页脚署名需包含该关键词(如 小芒)才会被接受。
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口
|
||||
args = {
|
||||
"msgtype": "notification|text|markdown|actionCard(可选,默认 notification)",
|
||||
"title": "消息标题(notification/markdown/actionCard 使用)",
|
||||
"content": "消息正文,多行自动转引用块(notification 使用)",
|
||||
"text": "文本内容(msgtype=text 使用)",
|
||||
"status": "info|success|warning|error(可选,默认 info,决定标题颜色)",
|
||||
"at_mobiles": "需 @ 的手机号列表(可选;兼容逗号分隔字符串)",
|
||||
"at_user_ids":"需 @ 的用户 userid 列表(可选)",
|
||||
"is_at_all": "是否 @所有人(可选,默认 false)",
|
||||
"webhook": "机器人 webhook(可选,缺省用内联默认值)",
|
||||
"secret": "加签密钥(可选,缺省用内联默认值)",
|
||||
"server_name":"页脚署名(可选,缺省用内联默认值)",
|
||||
"single_title":"按钮文字(msgtype=actionCard 使用)",
|
||||
"single_url": "按钮跳转链接(msgtype=actionCard 使用)",
|
||||
}
|
||||
通过流程参数传入(支持整字典 params 或分别传各字段)
|
||||
返回 JSON 安全 dict:{"success": bool, "message": str}
|
||||
|
||||
python dingtalk_robot.py 消息内容 [--title 标题] [--status info] [--webhook ...] [--secret ...]
|
||||
独立运行(等价于 main({"title": ..., "content": ..., ...}))
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
# ==================== 日志(print) ====================
|
||||
class _PrintLogger:
|
||||
"""影刀版无 logging 依赖,直接用 print 输出,行为与项目 logger 对齐。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
# ==================== 默认参数 ====================
|
||||
# 影刀运行环境无 .env 文件读取,故 webhook/secret/署名直接内联在此(单一真源),
|
||||
# 需要调整推送目标时改这里即可;也可在调用 main(args) 时通过 webhook/secret/server_name 覆盖。
|
||||
DEFAULT_WEBHOOK = (
|
||||
'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
|
||||
)
|
||||
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
|
||||
DEFAULT_SERVER_NAME = '37du 任务调度平台'
|
||||
DEFAULT_TIMEOUT = 10 # HTTP 请求超时秒数
|
||||
DEFAULT_RETRY_TIMES = 3 # 失败重试次数(含首次)
|
||||
DINGTALK_ROBOT_ENDPOINT = 'https://oapi.dingtalk.com/robot/send'
|
||||
|
||||
# 通知状态 → 标题颜色(与 app 版 dingtalk_robot.py 色板一致)
|
||||
_STATUS_COLORS = {
|
||||
'info': '#0077ff', # 蓝色
|
||||
'success': '#00b300', # 绿色
|
||||
'warning': '#ff9900', # 橙色
|
||||
'error': '#ff0000', # 红色
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
|
||||
).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=''):
|
||||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = '&' if '?' in webhook else '?'
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
def _at_payload(at_mobiles=None, at_user_ids=None, is_at_all=False):
|
||||
"""构造 @ 参数。三种 @ 方式可组合,都不指定时返回空 dict。"""
|
||||
at = {}
|
||||
if at_mobiles:
|
||||
at['atMobiles'] = list(at_mobiles)
|
||||
if at_user_ids:
|
||||
at['atUserIds'] = list(at_user_ids)
|
||||
if is_at_all:
|
||||
at['isAtAll'] = True
|
||||
return at
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""
|
||||
钉钉群机器人推送器。
|
||||
|
||||
Args:
|
||||
webhook: 机器人 webhook 地址;缺省用内联默认值 DEFAULT_WEBHOOK
|
||||
secret: 加签密钥;缺省用内联默认值 DEFAULT_SECRET
|
||||
server_name: 页脚平台署名;缺省用内联默认值 DEFAULT_SERVER_NAME,
|
||||
默认 "小芒 任务调度平台"(含关键词"小芒",可满足机器人自定义关键词校验)
|
||||
timeout: HTTP 请求超时秒数
|
||||
|
||||
Raises:
|
||||
ValueError: webhook 为空
|
||||
"""
|
||||
|
||||
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
|
||||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||||
self.timeout = timeout
|
||||
if not self.webhook:
|
||||
raise ValueError(
|
||||
'webhook 不能为空,请通过参数传入或修改模块内 DEFAULT_WEBHOOK 内联常量'
|
||||
)
|
||||
|
||||
def _post(self, payload):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(DEFAULT_RETRY_TIMES):
|
||||
try:
|
||||
url = _build_url(self.webhook, self.secret)
|
||||
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
body = resp.read().decode('utf-8')
|
||||
resp_data = json.loads(body)
|
||||
if resp_data.get('errcode') != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
|
||||
f"errmsg={resp_data.get('errmsg')}"
|
||||
)
|
||||
logger.debug('钉钉机器人推送成功,响应: %s', resp_data)
|
||||
return
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
logger.warning('推送失败(第 %d/%d 次):%s', attempt + 1, DEFAULT_RETRY_TIMES, e)
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||||
|
||||
def _build_footer(self, server_name=''):
|
||||
"""构建页脚:###### {署名} | {当前时间}。署名缺省取实例的 server_name。"""
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
return f"###### {display_name} | {current_time}"
|
||||
|
||||
def send_text(self, content, at_mobiles=None, at_user_ids=None, is_at_all=False):
|
||||
"""发送文本消息。"""
|
||||
if not content or not content.strip():
|
||||
raise ValueError('content 不能为空')
|
||||
|
||||
payload = {'msgtype': 'text', 'text': {'content': content}}
|
||||
at = _at_payload(at_mobiles, at_user_ids, is_at_all)
|
||||
if at:
|
||||
payload['at'] = at
|
||||
|
||||
logger.info('钉钉机器人推送文本: %s', content[:50] + ('...' if len(content) > 50 else ''))
|
||||
self._post(payload)
|
||||
return True
|
||||
|
||||
def send_markdown(self, title, text, at_mobiles=None, at_user_ids=None, is_at_all=False):
|
||||
"""发送 Markdown 消息(底层通用方法,内容完全由调用方控制)。"""
|
||||
if not title or not title.strip():
|
||||
raise ValueError('title 不能为空')
|
||||
if not text or not text.strip():
|
||||
raise ValueError('text 不能为空')
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
at = _at_payload(at_mobiles, at_user_ids, is_at_all)
|
||||
if at:
|
||||
payload['at'] = at
|
||||
|
||||
logger.info('钉钉机器人推送 Markdown: %s', title)
|
||||
self._post(payload)
|
||||
return True
|
||||
|
||||
def send_notification(
|
||||
self, title, content, status='info',
|
||||
at_mobiles=None, at_user_ids=None, is_at_all=False,
|
||||
server_name='', append_footer=True,
|
||||
):
|
||||
"""
|
||||
统一通知方法(推荐业务方使用),样式与 app 版 dingtalk_robot.py 一致:
|
||||
|
||||
**<font color='#ff0000'>任务执行失败</font>** ← 标题按 status 着色
|
||||
|
||||
内容详情:
|
||||
> 订单同步失败 ← 内容多行自动转引用块
|
||||
> 错误原因:接口超时
|
||||
|
||||
---
|
||||
|
||||
###### 小芒 任务调度平台 | 2026-08-14 14:30:00 ← 页脚:署名 + 当前时间
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 消息主体内容,支持多行(自动按行转引用块)
|
||||
status: 状态类型,决定标题颜色: info(蓝) | success(绿) | warning(橙) | error(红)
|
||||
at_mobiles: 需要 @ 的手机号列表
|
||||
at_user_ids: 需要 @ 的用户 userid 列表
|
||||
is_at_all: 是否 @所有人
|
||||
server_name: 页脚署名,缺省用实例的 server_name
|
||||
append_footer: 是否自动追加页脚(署名 + 时间),默认 True
|
||||
|
||||
Returns:
|
||||
是否推送成功
|
||||
|
||||
Raises:
|
||||
ValueError: title 或 content 为空
|
||||
"""
|
||||
if not title or not title.strip():
|
||||
raise ValueError('title 不能为空')
|
||||
if not content or not content.strip():
|
||||
raise ValueError('content 不能为空')
|
||||
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += '内容详情:\n'
|
||||
for line in content.strip().splitlines():
|
||||
line = line.strip()
|
||||
if line:
|
||||
# 行尾两个空格 + 换行:钉钉 markdown 单个 \n 不换行,必须用硬换行才分行显示
|
||||
text += f"> {line} \n"
|
||||
if append_footer:
|
||||
text += f"\n\n---\n\n{self._build_footer(server_name)}"
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
at = _at_payload(at_mobiles, at_user_ids, is_at_all)
|
||||
if at:
|
||||
payload['at'] = at
|
||||
|
||||
logger.info('钉钉机器人推送通知 [%s]: %s', status, title)
|
||||
self._post(payload)
|
||||
return True
|
||||
|
||||
def send_action_card(
|
||||
self, title, content, single_title, single_url,
|
||||
at_mobiles=None, at_user_ids=None, is_at_all=False,
|
||||
server_name='',
|
||||
):
|
||||
"""发送 ActionCard 消息(底部带按钮,如"点击下载报表")。"""
|
||||
if not title or not title.strip():
|
||||
raise ValueError('title 不能为空')
|
||||
if not content or not content.strip():
|
||||
raise ValueError('content 不能为空')
|
||||
if not single_title or not single_title.strip():
|
||||
raise ValueError('single_title 不能为空')
|
||||
if not single_url or not single_url.strip():
|
||||
raise ValueError('single_url 不能为空')
|
||||
|
||||
text = f"**{title}**\n\n{content}\n\n---\n\n{self._build_footer(server_name)}"
|
||||
payload = {
|
||||
'msgtype': 'actionCard',
|
||||
'actionCard': {
|
||||
'title': title,
|
||||
'text': text,
|
||||
'singleTitle': single_title,
|
||||
'singleURL': single_url,
|
||||
},
|
||||
}
|
||||
at = _at_payload(at_mobiles, at_user_ids, is_at_all)
|
||||
if at:
|
||||
payload['at'] = at
|
||||
|
||||
logger.info('钉钉机器人推送 ActionCard: %s -> %s', title, single_url)
|
||||
self._post(payload)
|
||||
return True
|
||||
|
||||
|
||||
# ==================== 一次性便捷函数 ====================
|
||||
def send_robot_text(content, webhook='', secret='', at_mobiles=None, at_user_ids=None, is_at_all=False):
|
||||
"""一键发送文本到群机器人(webhook 缺省用内联默认值 DEFAULT_WEBHOOK)。"""
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret)
|
||||
return robot.send_text(content, at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all)
|
||||
|
||||
|
||||
def send_robot_notification(
|
||||
title, content, status='info',
|
||||
webhook='', secret='',
|
||||
at_mobiles=None, at_user_ids=None, is_at_all=False,
|
||||
server_name='',
|
||||
):
|
||||
"""一键发送统一通知(样式与 send_notification 一致)。"""
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret)
|
||||
return robot.send_notification(
|
||||
title, content, status=status,
|
||||
at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all,
|
||||
server_name=server_name,
|
||||
)
|
||||
|
||||
|
||||
# ==================== 影刀自定义指令入口 ====================
|
||||
def _to_list(value):
|
||||
"""把 at_mobiles / at_user_ids 参数归一为 list:列表原样返回,字符串按逗号拆。"""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, (list, tuple)):
|
||||
return [str(v).strip() for v in value if str(v).strip()]
|
||||
if isinstance(value, str):
|
||||
return [v.strip() for v in value.replace(',', ',').split(',') if v.strip()]
|
||||
return [str(value)]
|
||||
|
||||
|
||||
def _send_one(args):
|
||||
"""按 args 字典发送一条消息,返回 {success: bool, message: str}。"""
|
||||
try:
|
||||
msgtype = str(args.get('msgtype', '') or 'notification').strip().lower() or 'notification'
|
||||
webhook = str(args.get('webhook', '') or '').strip()
|
||||
secret = str(args.get('secret', '') or '').strip()
|
||||
server_name = str(args.get('server_name', '') or '').strip()
|
||||
at_mobiles = _to_list(args.get('at_mobiles'))
|
||||
at_user_ids = _to_list(args.get('at_user_ids'))
|
||||
is_at_all = bool(args.get('is_at_all', False))
|
||||
title = str(args.get('title', '') or '').strip()
|
||||
content = str(args.get('content', '') or '')
|
||||
text = str(args.get('text', '') or '').strip()
|
||||
status = str(args.get('status', '') or 'info').strip().lower() or 'info'
|
||||
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
|
||||
|
||||
if msgtype == 'text':
|
||||
if not text:
|
||||
return {'success': False, 'message': 'msgtype=text 时参数 text 不能为空'}
|
||||
robot.send_text(text, at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all)
|
||||
return {'success': True, 'message': f"已发送文本消息({len(text)} 字)"}
|
||||
|
||||
if msgtype == 'markdown':
|
||||
if not title or not text:
|
||||
return {'success': False, 'message': 'msgtype=markdown 时参数 title/text 不能为空'}
|
||||
robot.send_markdown(
|
||||
title, text, at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all
|
||||
)
|
||||
return {'success': True, 'message': f'已发送 Markdown 消息:{title}'}
|
||||
|
||||
if msgtype == 'actioncard':
|
||||
single_title = str(args.get('single_title', '') or '').strip()
|
||||
single_url = str(args.get('single_url', '') or '').strip()
|
||||
if not title or not content or not single_title or not single_url:
|
||||
return {
|
||||
'success': False,
|
||||
'message': 'msgtype=actionCard 时参数 title/content/single_title/single_url 不能为空',
|
||||
}
|
||||
robot.send_action_card(
|
||||
title, content, single_title, single_url,
|
||||
at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all,
|
||||
server_name=server_name,
|
||||
)
|
||||
return {'success': True, 'message': f'已发送 ActionCard:{title}'}
|
||||
|
||||
# 默认 notification
|
||||
if not title or not content.strip():
|
||||
return {'success': False, 'message': '参数 title/content 不能为空'}
|
||||
robot.send_notification(
|
||||
title, content, status=status,
|
||||
at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all,
|
||||
server_name=server_name,
|
||||
)
|
||||
return {'success': True, 'message': f"已发送通知 [{status}]:{title}"}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': str(e)}
|
||||
|
||||
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37du钉钉群机器人推送」调用入口。
|
||||
args: dict,通过流程变量传入(影刀变量支持传字典/列表):
|
||||
方式A(批量,推荐):args = {"messages": [{msgtype?, title?, content?, ...}, ...]}
|
||||
messages 为「字典列表」,逐条推送并返回汇总结果;
|
||||
方式B(单条):args = {"params": {...}} 或直接 {"msgtype":..., "title":..., "content":...};
|
||||
返回: dict
|
||||
单条: {success: bool, message: str}
|
||||
批量: {success: bool, message: str, sent: int, failed: int, results: [...]}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
# 兼容「整个字典作为 params 传入」的用法
|
||||
if isinstance(args.get('params'), dict):
|
||||
merged = dict(args)
|
||||
merged.update(args['params'])
|
||||
args = merged
|
||||
|
||||
# 批量:messages 为字典列表,逐条推送
|
||||
if isinstance(args.get('messages'), list):
|
||||
results = [_send_one(m) for m in args['messages']]
|
||||
ok = sum(1 for r in results if r.get('success'))
|
||||
return {
|
||||
'success': ok == len(results),
|
||||
'message': f'共 {len(results)} 条,成功 {ok},失败 {len(results) - ok}',
|
||||
'sent': ok,
|
||||
'failed': len(results) - ok,
|
||||
'results': results,
|
||||
}
|
||||
|
||||
# 单条推送
|
||||
return _send_one(args)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# 仅本地自测连通性。影刀中会直接调用 main(args) 并通过流程变量传参,不会走这里。
|
||||
# 批量测试:流程变量 messages = 字典列表,每条含 title/content,main 逐条推送并汇总。
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description='钉钉群机器人消息推送工具(影刀指令源码独立运行)')
|
||||
parser.add_argument('content', nargs='?', default='', help='消息正文/文本(多行可用换行分隔)')
|
||||
parser.add_argument('-t', '--title', default='消息通知', help='消息标题')
|
||||
parser.add_argument('--status', default='info',
|
||||
choices=['info', 'success', 'warning', 'error'], help='通知状态(决定标题颜色)')
|
||||
parser.add_argument('--msgtype', default='notification',
|
||||
choices=['notification', 'text', 'markdown', 'actionCard'], help='消息类型')
|
||||
parser.add_argument('-w', '--webhook', default='', help='机器人 webhook,缺省用内联默认值')
|
||||
parser.add_argument('-s', '--secret', default='', help='加签密钥,缺省用内联默认值')
|
||||
parser.add_argument('--name', default='', help='页脚平台署名,缺省用内联默认值')
|
||||
parser.add_argument('--all', action='store_true', help='@所有人')
|
||||
parser.add_argument('--text', default='', help='msgtype=text/markdown 时的文本内容')
|
||||
parser.add_argument('--single-title', default='点击查看', help='actionCard 按钮文字')
|
||||
parser.add_argument('--single-url', default='https://www.37du.co', help='actionCard 按钮链接')
|
||||
_cli = parser.parse_args()
|
||||
|
||||
_params = {
|
||||
'msgtype': _cli.msgtype,
|
||||
'title': _cli.title,
|
||||
'content': _cli.content,
|
||||
'text': _cli.text,
|
||||
'status': _cli.status,
|
||||
'webhook': _cli.webhook,
|
||||
'secret': _cli.secret,
|
||||
'server_name': _cli.name,
|
||||
'is_at_all': _cli.all,
|
||||
'single_title': _cli.single_title,
|
||||
'single_url': _cli.single_url,
|
||||
}
|
||||
result = main(_params)
|
||||
print('最终结果:', result)
|
||||
@@ -23,10 +23,13 @@
|
||||
oa_target_url_keyword=OA 登录成功后 URL 关键字
|
||||
oa_login_username=用户名
|
||||
oa_login_password=密码
|
||||
oa_validate_url=(可选)轻量会话校验接口 URL;不配置则仅以 cookies 存在作为复用依据
|
||||
oa_validate_url=(可选)轻量会话校验接口 URL;默认使用 sumTodoCount 待办统计接口
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage python-dotenv
|
||||
pip install DrissionPage requests python-dotenv
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||||
@@ -36,8 +39,9 @@ import os
|
||||
import json
|
||||
import time
|
||||
|
||||
from DrissionPage import ChromiumPage, SessionPage
|
||||
from DrissionPage import ChromiumPage
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
@@ -55,13 +59,37 @@ def _load_shared_env():
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ================== 配置 ==================
|
||||
# 注意:必须在读取环境变量前先加载 .env,否则 import 时这些值会被捕获为 None
|
||||
_load_shared_env()
|
||||
LOGIN_URL = os.getenv('oa_login_url')
|
||||
SUCCESS_KEYWORD = os.getenv('oa_target_url_keyword')
|
||||
USERNAME = os.getenv('oa_login_username')
|
||||
PASSWORD = os.getenv('oa_login_password')
|
||||
|
||||
# OA 会话校验接口:cookies 有效时返回 JSON,失效时被重定向到登录页返回 HTML
|
||||
TODO_COUNT_URL = "https://oa.37du.co/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
|
||||
USERNAME_INPUT = 'tag:input@name=j_username'
|
||||
PASSWORD_INPUT = 'tag:input@name=j_password'
|
||||
LOGIN_BTN = '.lui_login_button_div_c'
|
||||
|
||||
TIMEOUT = 10
|
||||
WAIT_AFTER_LOAD = 2
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化 ==================
|
||||
def save_browser_cookies(page):
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
os.makedirs(_SESSIONS_DIR, exist_ok=True)
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
@@ -75,60 +103,69 @@ def load_cookies():
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(无需打开浏览器) ==================
|
||||
def _is_oa_session_valid():
|
||||
"""轻量校验 OA 会话:请求 oa_validate_url,返回 JSON 视为有效。未配置则默认有效。"""
|
||||
validate_url = os.getenv('oa_validate_url', '').strip()
|
||||
if not validate_url:
|
||||
return True
|
||||
"""API 轻量校验 OA cookies:请求 oa_validate_url(默认 sumTodoCount 待办统计接口),
|
||||
返回 JSON 视为 cookies 有效;被重定向到登录页返回 HTML 即视为失效。
|
||||
|
||||
与业务脚本(overtime_approval/leave_approval/social_change 等)使用同一套接口与校验逻辑:
|
||||
requests.Session + Chrome UA + 仅注入 37du.co 域 cookies,GET method=sumTodoCount。
|
||||
"""
|
||||
validate_url = os.getenv('oa_validate_url', '').strip() or TODO_COUNT_URL
|
||||
try:
|
||||
session = SessionPage()
|
||||
cookies = load_cookies()
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
session.set.timeout(10)
|
||||
session.get(validate_url)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.get(validate_url, params={"method": "sumTodoCount"}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _do_login(username=None, password=None, timeout=10, wait_after_load=2):
|
||||
def _do_login(timeout=TIMEOUT, wait_after_load=WAIT_AFTER_LOAD):
|
||||
"""打开浏览器完成 OA 账号密码登录,成功保存 cookies。"""
|
||||
login_url = os.getenv('oa_login_url')
|
||||
if not login_url:
|
||||
raise RuntimeError("环境变量 oa_login_url 未设置")
|
||||
target_url_keyword = os.getenv('oa_target_url_keyword')
|
||||
if not target_url_keyword:
|
||||
raise RuntimeError("环境变量 oa_target_url_keyword 未设置")
|
||||
|
||||
final_username = username or os.getenv('oa_login_username')
|
||||
final_password = password or os.getenv('oa_login_password')
|
||||
if not final_username or not final_password:
|
||||
raise RuntimeError("用户名或密码未提供,请设置环境变量或传入参数")
|
||||
|
||||
page = ChromiumPage()
|
||||
try:
|
||||
page.get(login_url)
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(wait_after_load)
|
||||
|
||||
username_input = page.ele('tag:input@name=j_username')
|
||||
username_input = page.ele(USERNAME_INPUT)
|
||||
if not username_input:
|
||||
raise RuntimeError("未找到用户名输入框")
|
||||
username_input.input(final_username)
|
||||
username_input.input(USERNAME)
|
||||
page.wait(0.5)
|
||||
|
||||
password_input = page.ele('tag:input@name=j_password')
|
||||
password_input = page.ele(PASSWORD_INPUT)
|
||||
if not password_input:
|
||||
raise RuntimeError("未找到密码输入框")
|
||||
password_input.input(final_password)
|
||||
password_input.input(PASSWORD)
|
||||
page.wait(0.5)
|
||||
|
||||
login_button = page.ele('.lui_login_button_div_c')
|
||||
login_button = page.ele(LOGIN_BTN)
|
||||
if not login_button:
|
||||
raise RuntimeError("未找到登录按钮")
|
||||
login_button.click()
|
||||
@@ -136,7 +173,7 @@ def _do_login(username=None, password=None, timeout=10, wait_after_load=2):
|
||||
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
if target_url_keyword in page.url:
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print(f"登录成功!当前 URL: {page.url}")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
@@ -153,29 +190,35 @@ def _do_login(username=None, password=None, timeout=10, wait_after_load=2):
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(force=False, username=None, password=None):
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 OA 登录态并缓存 cookies。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
# 默认未登录;登录成功或复用有效 cookies 后再置 True
|
||||
_set_login_state(False)
|
||||
|
||||
if not os.getenv('oa_login_url'):
|
||||
if not (LOGIN_URL and SUCCESS_KEYWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "未配置 oa_login_url 环境变量", "relogin": False}
|
||||
"message": "未配置 oa_login_url / oa_target_url_keyword 环境变量", "relogin": False}
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "未配置 oa_login_username / oa_login_password 环境变量", "relogin": False}
|
||||
|
||||
if not force:
|
||||
if load_cookies() and _is_oa_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 OA 登录态")
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需打开浏览器)
|
||||
if not force and _is_oa_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 OA 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
try:
|
||||
_do_login(username=username, password=password)
|
||||
ok = _do_login()
|
||||
if ok:
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录失败:{e}", "relogin": False}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
@@ -188,7 +231,11 @@ def main(args):
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
return ensure_login(force=force)
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user