181 lines
5.3 KiB
Python
181 lines
5.3 KiB
Python
"""Notion API 客户端 - 用于保存注册账号信息到 Notion 数据库"""
|
||
|
||
import os
|
||
import requests
|
||
from typing import Dict, Optional
|
||
from config import DEBUG
|
||
|
||
|
||
class NotionClient:
|
||
"""Notion 数据库客户端"""
|
||
|
||
def __init__(self, token: Optional[str] = None, database_id: Optional[str] = None):
|
||
"""
|
||
初始化 Notion 客户端
|
||
|
||
Args:
|
||
token: Notion Integration Token(或从环境变量 NOTION_TOKEN 读取)
|
||
database_id: Notion 数据库 ID(或从环境变量 DATA_SOURCE_ID 读取)
|
||
"""
|
||
self.token = token or os.environ.get('NOTION_TOKEN')
|
||
self.database_id = database_id or os.environ.get('DATA_SOURCE_ID')
|
||
|
||
if not self.token:
|
||
raise ValueError("NOTION_TOKEN not found in environment or parameters")
|
||
|
||
if not self.database_id:
|
||
raise ValueError("DATA_SOURCE_ID not found in environment or parameters")
|
||
|
||
self.api_url = "https://api.notion.com/v1/pages"
|
||
self.api_version = "2025-09-03"
|
||
|
||
if DEBUG:
|
||
print(f"✅ NotionClient initialized")
|
||
print(f" Token: {self.token[:20]}...")
|
||
print(f" Database ID: {self.database_id}")
|
||
|
||
def add_account(
|
||
self,
|
||
email: str,
|
||
password: str,
|
||
billing_url: Optional[str] = None,
|
||
person: Optional[str] = None,
|
||
status: str = "未开始",
|
||
done_status: str = "done",
|
||
auto_status: str = "fail"
|
||
) -> Dict:
|
||
"""
|
||
添加账号信息到 Notion 数据库
|
||
|
||
Args:
|
||
email: 邮箱地址
|
||
password: 密码
|
||
billing_url: 账单链接(可选)
|
||
person: 人员(可选)
|
||
status: 车状态(默认 "未开始")
|
||
done_status: Done 状态(默认 "done")
|
||
auto_status: 自动检测支付状态("success" 或 "fail",默认 "fail")
|
||
|
||
Returns:
|
||
API 响应结果
|
||
"""
|
||
|
||
# 构建 properties
|
||
properties = {
|
||
"email": {
|
||
"title": [{"text": {"content": email}}]
|
||
},
|
||
"密码": {
|
||
"rich_text": [{"text": {"content": password}}]
|
||
},
|
||
"车状态": {
|
||
"status": {"name": status}
|
||
},
|
||
"done": {
|
||
"status": {"name": done_status}
|
||
},
|
||
"autoStatus": {
|
||
"rich_text": [{"text": {"content": auto_status}}]
|
||
}
|
||
}
|
||
|
||
# 可选字段:账单链接
|
||
if billing_url:
|
||
properties["账单链接"] = {"url": billing_url}
|
||
|
||
# 可选字段:人员
|
||
if person:
|
||
properties["人员"] = {"select": {"name": person}}
|
||
|
||
# 构建请求体
|
||
payload = {
|
||
"parent": {
|
||
"type": "data_source_id",
|
||
"data_source_id": self.database_id
|
||
},
|
||
"properties": properties
|
||
}
|
||
|
||
# 准备 headers
|
||
headers = {
|
||
"Authorization": f"Bearer {self.token}",
|
||
"Notion-Version": self.api_version,
|
||
"Content-Type": "application/json"
|
||
}
|
||
|
||
# 发送请求
|
||
try:
|
||
resp = requests.post(
|
||
self.api_url,
|
||
headers=headers,
|
||
json=payload,
|
||
timeout=30
|
||
)
|
||
|
||
if resp.status_code == 200:
|
||
if DEBUG:
|
||
print(f"✅ Account added to Notion: {email}")
|
||
return {
|
||
'success': True,
|
||
'data': resp.json()
|
||
}
|
||
else:
|
||
error_msg = f"Failed to add account: {resp.status_code} {resp.text}"
|
||
if DEBUG:
|
||
print(f"❌ {error_msg}")
|
||
return {
|
||
'success': False,
|
||
'error': error_msg,
|
||
'status_code': resp.status_code,
|
||
'response': resp.text
|
||
}
|
||
|
||
except Exception as e:
|
||
error_msg = f"Exception during Notion API call: {e}"
|
||
if DEBUG:
|
||
print(f"❌ {error_msg}")
|
||
return {
|
||
'success': False,
|
||
'error': error_msg
|
||
}
|
||
|
||
def add_registered_account(
|
||
self,
|
||
registration_result: Dict,
|
||
password: str,
|
||
billing_url: Optional[str] = None
|
||
) -> Dict:
|
||
"""
|
||
从注册结果中提取信息并添加到 Notion
|
||
|
||
Args:
|
||
registration_result: OpenAIRegistrar.register() 或 register_with_auto_email() 的返回结果
|
||
password: 账号密码
|
||
billing_url: 账单链接(可选)
|
||
|
||
Returns:
|
||
API 响应结果
|
||
"""
|
||
|
||
if not registration_result.get('success'):
|
||
return {
|
||
'success': False,
|
||
'error': 'Registration failed, cannot add to Notion'
|
||
}
|
||
|
||
email = registration_result.get('email')
|
||
|
||
if not email:
|
||
return {
|
||
'success': False,
|
||
'error': 'No email found in registration result'
|
||
}
|
||
|
||
return self.add_account(
|
||
email=email,
|
||
password=password,
|
||
billing_url=billing_url,
|
||
status="未开始",
|
||
done_status="未开始"
|
||
)
|