"""
OA工作沟通自动化发送脚本
支持:多接收人、多附件、HTML内容
依赖:requests, xml.etree.ElementTree
"""
import requests
import hashlib
import os
import base64
import time
import xml.etree.ElementTree as ET
from typing import List, Union, Optional
# ============================================================
# 配置区域(请根据实际情况修改)
# ============================================================
OA_BASE_URL = "https://oa.37du.co" # OA系统根地址
# 登录方式1:已有Cookie(从浏览器导出)
COOKIE_STRING = "" # 如 "JSESSIONID=xxx; Route=xxx"
# 登录方式2:账号密码(需要自行实现登录逻辑)
USERNAME = "" # 工号
PASSWORD = "" # 密码
# 当前操作人的ID(可通过搜索自己的工号获取)
CREATOR_ID = "37b1d9a5c5834a98bc4274143ab53d10" # 替换为实际值
# ============================================================
# 工具函数
# ============================================================
def get_session() -> requests.Session:
"""获取已登录的Session"""
session = requests.Session()
# 方式1:设置已有Cookie
if COOKIE_STRING:
for cookie in COOKIE_STRING.split("; "):
if "=" in cookie:
key, value = cookie.split("=", 1)
session.cookies.set(key, value)
print("✅ 使用已有Cookie登录")
return session
# 方式2:账号密码登录(这里需要根据实际登录接口实现)
if USERNAME and PASSWORD:
# TODO: 实现具体登录逻辑
# login_url = f"{OA_BASE_URL}/login.do"
# session.post(login_url, data={"username": USERNAME, "password": PASSWORD})
print("⚠️ 请实现登录逻辑,或使用COOKIE_STRING方式")
return session
print("⚠️ 未配置登录信息,请设置 COOKIE_STRING 或 USERNAME/PASSWORD")
return session
def search_person(session: requests.Session, keyword: str) -> Optional[tuple]:
"""
根据工号或姓名搜索人员
:return: (person_id, person_name) 或 None
"""
url = f"{OA_BASE_URL}/sys/common/dataxml.jsp"
params = {
"s_bean": "organizationDialogSearch",
"orgType": "15",
"deptLimit": "",
"isExternal": "",
"key": keyword,
"s_ajax": "true"
}
try:
resp = session.get(url, params=params)
if resp.status_code != 200:
print(f"❌ 搜索人员失败: HTTP {resp.status_code}")
return None
# 解析XML
root = ET.fromstring(resp.text)
data = root.find(".//data")
if data is None:
print(f"❌ 未找到人员: {keyword}")
return None
person_id = data.get("id")
person_name = data.get("name")
print(f"✅ 搜索到人员: {person_name} (ID: {person_id})")
return person_id, person_name
except Exception as e:
print(f"❌ 搜索人员异常: {e}")
return None
def upload_attachment(session: requests.Session, file_path: str) -> Optional[str]:
"""
上传单个附件,返回 attid(最终附件ID)
完整模拟了OA的5步上传流程
"""
file_name = os.path.basename(file_path)
file_size = str(os.path.getsize(file_path))
# 计算MD5
with open(file_path, 'rb') as f:
md5_hash = hashlib.md5(f.read()).hexdigest()
# 文件修改时间
last_modified = time.strftime("%a %b %d %Y %H:%M:%S GMT+0800", time.localtime(os.path.getmtime(file_path)))
# fdSign = Base64(文件名)
fd_sign = base64.b64encode(file_name.encode()).decode()
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Referer": f"{OA_BASE_URL}/",
"X-Requested-With": "XMLHttpRequest"
}
session.headers.update(headers)
base_att_url = f"{OA_BASE_URL}/sys/attachment/sys_att_main/sysAttMain.do"
# ---- 步骤1:获取 userkey ----
params1 = {
"method": "handleAttUpload",
"gettype": "getuserkey",
"format": "json",
"filesize": file_size,
"md5": "",
"fileName": file_name,
"isSupportDirect": "false",
"s_ajax": "true"
}
try:
resp1 = session.get(base_att_url, params=params1)
userkey = resp1.json().get("token", {}).get("header", {}).get("userkey")
if not userkey:
print(f"❌ 获取userkey失败: {resp1.text}")
return None
print(f" ✅ 1. 获取userkey成功")
except Exception as e:
print(f"❌ 步骤1异常: {e}")
return None
# ---- 步骤2:MD5秒传校验 ----
params2 = {
"method": "handleAttUpload",
"gettype": "checkMd5",
"format": "json",
"filesize": file_size,
"md5": md5_hash,
"fileName": file_name,
"isSupportDirect": "false",
"s_ajax": "true"
}
try:
resp2 = session.get(base_att_url, params=params2)
result2 = resp2.json()
md5_exists = result2.get("md5Exists", False)
print(f" ✅ 2. MD5校验: {'已存在(秒传)' if md5_exists else '需上传'}")
except Exception as e:
print(f"❌ 步骤2异常: {e}")
return None
# ---- 步骤3:上传二进制(仅当文件不存在时) ----
if not md5_exists:
uploader_url = f"{OA_BASE_URL}/sys/attachment/uploaderServlet?gettype=upload&format=json"
files = {
'file': (file_name, open(file_path, 'rb'), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
}
data3 = {
'id': 'WU_FILE_0',
'name': file_name,
'type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'lastModifiedDate': last_modified,
'size': file_size
}
try:
resp3 = session.post(uploader_url, files=files, data=data3)
filekey = resp3.json().get("filekey")
if not filekey:
print(f"❌ 上传二进制失败: {resp3.text}")
return None
print(f" ✅ 3. 二进制上传成功, filekey: {filekey[:16]}...")
except Exception as e:
print(f"❌ 步骤3异常: {e}")
return None
else:
# 秒传成功,需要获取已存在文件的filekey
# 这里需要额外接口,部分OA支持直接用md5做submit
# 简化处理:调用一个获取文件信息的接口(如果有)
filekey = md5_hash # 尝试用md5作为filekey(不保证成功)
print(f" ⚠️ 3. 秒传模式,使用md5作为filekey: {filekey[:16]}...")
# ---- 步骤4:提交绑定附件(获取最终attid) ----
params4 = {
"method": "handleAttUpload",
"gettype": "submit",
"format": "json",
"filekey": filekey,
"filename": file_name,
"fdKey": "attachment",
"fdModelName": "com.landray.kmss.km.collaborate.model.KmCollaborateMain",
"fdAttType": "byte",
"width": "null",
"height": "null",
"proportion": "true",
"fdSign": fd_sign,
"s_ajax": "true"
}
try:
resp4 = session.get(base_att_url, params=params4)
result4 = resp4.json()
attid = result4.get("attid")
if result4.get("status") != "1" or not attid:
print(f"❌ 提交绑定失败: {resp4.text}")
return None
print(f" ✅ 4. 提交绑定成功, attid: {attid}")
return attid
except Exception as e:
print(f"❌ 步骤4异常: {e}")
return None
def send_work_communication(
session: requests.Session,
receiver_ids: Union[str, List[str]],
receiver_names: Union[str, List[str]],
subject: str,
content: str,
attachment_ids: Union[str, List[str]] = None,
creator_id: str = None
) -> Optional[str]:
"""
发送工作沟通(新建)
:param session: 已登录的Session
:param receiver_ids: 接收人ID,单个字符串或列表
:param receiver_names: 接收人姓名,单个字符串或列表(顺序需与ID一致)
:param subject: 标题
:param content: 内容(支持HTML)
:param attachment_ids: 附件ID,单个字符串或列表
:param creator_id: 创建人ID,默认使用全局CREATOR_ID
:return: 沟通ID(成功时返回数字字符串)
"""
# 类型转换
if isinstance(receiver_ids, list):
receiver_ids_str = ",".join(receiver_ids)
else:
receiver_ids_str = receiver_ids
if isinstance(receiver_names, list):
receiver_names_str = ",".join(receiver_names)
else:
receiver_names_str = receiver_names
if isinstance(attachment_ids, list):
attachment_ids_str = ",".join(attachment_ids)
else:
attachment_ids_str = attachment_ids or ""
if creator_id is None:
creator_id = CREATOR_ID
# 构造参数
data = {
"fdId": "", # 新建传空
"participantIds": receiver_ids_str,
"participantNames": receiver_names_str,
"docSubject": subject,
"fdContent": content,
"docCreatorId": creator_id,
"attachmentForms.attachment.attachmentIds": attachment_ids_str,
"attachmentForms.attachment.fdModelName": "com.landray.kmss.km.collaborate.model.KmCollaborateMain",
"attachmentForms.attachment.fdKey": "attachment",
"fdNotifyType": "todo",
"fdRemindersDay": "2",
"fdIsOnlyView": "false",
"fdIsReminders": "false",
"fdPartnerOperating": "true",
"_fdPartnerOperating": "true",
"fdCategoryId": "",
}
# 防重复提交参数(取第一个附件ID做标记)
if attachment_ids_str:
first_att = attachment_ids_str.split(",")[0]
data[f"__notify_type_{first_att}"] = "todo"
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Referer": f"{OA_BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do",
"X-Requested-With": "XMLHttpRequest"
}
url = f"{OA_BASE_URL}/sys/ui/resources/user.jsp?s_ajax=true"
try:
resp = session.post(url, data=data, headers=headers)
if resp.status_code != 200:
print(f"❌ 发送沟通失败: HTTP {resp.status_code}")
print(f" 返回: {resp.text[:200]}")
return None
# 成功时返回数字ID(如 "37036361")
if resp.text.strip().isdigit():
print(f"✅ 发送沟通成功! 沟通ID: {resp.text}")
return resp.text.strip()
else:
print(f"❌ 发送沟通失败: {resp.text[:200]}")
return None
except Exception as e:
print(f"❌ 发送沟通异常: {e}")
return None
# ============================================================
# 主流程测试
# ============================================================
def main():
"""主流程:登录 → 搜索人员 → 上传附件 → 发送沟通"""
print("=" * 50)
print("开始执行OA工作沟通自动化发送")
print("=" * 50)
# 1. 获取登录Session
session = get_session()
# 2. 搜索接收人(示例:通过工号搜索)
print("\n--- 搜索接收人 ---")
person_id, person_name = search_person(session, "37036801") # 替换为实际工号
if not person_id:
print("❌ 未找到接收人,退出")
return
# 3. 上传附件(示例:上传一个文件)
print("\n--- 上传附件 ---")
# attid = upload_attachment(session, "data.xlsx") # 替换为实际文件路径
# 4. 发送沟通
print("\n--- 发送沟通 ---")
result = send_work_communication(
session=session,
receiver_ids=person_id,
receiver_names=person_name,
subject="【RPA测试】工作沟通",
content="<p>这是通过RPA接口自动发送的测试内容。</p><p>如有疑问请联系IT支持。</p>",
attachment_ids=None, # 或传入 ["attid1", "attid2"]
creator_id=CREATOR_ID
)
if result:
print(f"\n🎉 全部流程完成! 沟通ID: {result}")
else:
print("\n❌ 流程执行失败,请检查日志")
if __name__ == "__main__":
main()