ForcePilot/backend/package/yuxi/channel/extensions/line/delivery.py

46 lines
1.3 KiB
Python
Raw Normal View History

from __future__ import annotations
import logging
from yuxi.channel.extensions.line.bot import LineBotClient
logger = logging.getLogger(__name__)
MAX_REPLY_MESSAGES = 5
MAX_PUSH_MESSAGES_PER_BATCH = 5
class LineDeliveryManager:
async def deliver_messages(
self,
to: str,
messages: list[dict],
reply_token: str | None,
token: str,
) -> bool:
bot = LineBotClient(channel_access_token=token)
if reply_token:
try:
reply_batch = messages[:MAX_REPLY_MESSAGES]
ok = await bot.reply_message(reply_token, reply_batch)
if ok:
remaining = messages[MAX_REPLY_MESSAGES:]
if remaining:
for batch in _batch_list(remaining, MAX_PUSH_MESSAGES_PER_BATCH):
await bot.push_message(to, batch)
return True
except Exception:
logger.exception("LINE reply_message failed, falling back to push")
for batch in _batch_list(messages, MAX_PUSH_MESSAGES_PER_BATCH):
ok = await bot.push_message(to, batch)
if not ok:
return False
return True
def _batch_list(items: list, batch_size: int) -> list[list]:
return [items[i: i + batch_size] for i in range(0, len(items), batch_size)]