ForcePilot/backend/package/yuxi/channels/adapters/telegram/poll.py

87 lines
2.2 KiB
Python
Raw Normal View History

from __future__ import annotations
from typing import Any
from telegram import Bot
from telegram.error import TelegramError
from yuxi.utils.logging_config import logger
async def create_poll(
bot: Bot,
chat_id: str,
question: str,
options: list[str],
is_anonymous: bool = True,
allows_multiple_answers: bool = False,
poll_type: str = "regular",
open_period: int | None = None,
close_date: int | None = None,
visibility: str = "public",
**kwargs,
) -> Any:
try:
poll_kwargs = {
"chat_id": chat_id,
"question": question,
"options": options,
"is_anonymous": is_anonymous,
"allows_multiple_answers": allows_multiple_answers,
"type": poll_type,
"open_period": open_period,
"close_date": close_date,
**kwargs,
}
if visibility == "quiz" and poll_type == "quiz":
poll_kwargs["type"] = "quiz"
return await bot.send_poll(**poll_kwargs)
except TelegramError as e:
logger.error(f"[Telegram] Failed to create poll: {e}")
raise
async def stop_poll(
bot: Bot,
chat_id: str,
message_id: int,
) -> Any:
try:
return await bot.stop_poll(
chat_id=chat_id,
message_id=message_id,
)
except TelegramError as e:
logger.error(f"[Telegram] Failed to stop poll: {e}")
raise
async def create_quiz(
bot: Bot,
chat_id: str,
question: str,
options: list[str],
correct_option_id: int = 0,
explanation: str | None = None,
is_anonymous: bool = True,
open_period: int | None = None,
close_date: int | None = None,
**kwargs,
) -> Any:
try:
return await bot.send_poll(
chat_id=chat_id,
question=question,
options=options,
type="quiz",
correct_option_id=correct_option_id,
explanation=explanation or "",
is_anonymous=is_anonymous,
open_period=open_period,
close_date=close_date,
**kwargs,
)
except TelegramError as e:
logger.error(f"[Telegram] Failed to create quiz: {e}")
raise