完成Help Scout渠道的完整功能实现,包含API客户端、webhook处理、轮询同步、自动回复、工单标签分配、客户资料管理等核心能力,附带完整的配置Schema与插件元信息
66 lines
2.0 KiB
Python
66 lines
2.0 KiB
Python
from __future__ import annotations
|
|
|
|
import logging
|
|
from datetime import UTC, datetime, timedelta
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class HelpScoutPoller:
|
|
def __init__(self, client, mailbox_id: int, poll_interval: int = 30):
|
|
self._client = client
|
|
self._mailbox_id = mailbox_id
|
|
self._poll_interval = poll_interval
|
|
self._last_modification_time: datetime | None = None
|
|
self._running = False
|
|
|
|
async def start(self):
|
|
self._running = True
|
|
self._last_modification_time = datetime.now(UTC) - timedelta(minutes=5)
|
|
logger.info(
|
|
"Help Scout poller started: mailbox=%d interval=%ds",
|
|
self._mailbox_id,
|
|
self._poll_interval,
|
|
)
|
|
|
|
async def stop(self):
|
|
self._running = False
|
|
|
|
async def poll(self) -> list[dict]:
|
|
if not self._running:
|
|
return []
|
|
|
|
modified_since = self._last_modification_time.strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
try:
|
|
result = await self._client.list_conversations(
|
|
mailbox=self._mailbox_id,
|
|
status="active",
|
|
modified_since=modified_since,
|
|
embed="threads",
|
|
)
|
|
except Exception:
|
|
logger.exception("Help Scout poller: API call failed")
|
|
return []
|
|
|
|
conversations = result.get("_embedded", {}).get("conversations", [])
|
|
messages = []
|
|
|
|
for conv in conversations:
|
|
threads = conv.get("_embedded", {}).get("threads", [])
|
|
for thread in threads:
|
|
if thread.get("type") == "customer" and thread.get("status") != "draft":
|
|
messages.append(
|
|
{
|
|
"conversation": conv,
|
|
"thread": thread,
|
|
}
|
|
)
|
|
|
|
self._last_modification_time = datetime.now(UTC) - timedelta(seconds=30)
|
|
|
|
if messages:
|
|
logger.debug("Help Scout poller: %d new customer messages found", len(messages))
|
|
|
|
return messages
|