|
| 1 | +import asyncio |
| 2 | +from typing import List, Union |
| 3 | +from telegram import Bot |
| 4 | +from telegram.ext import ApplicationBuilder |
| 5 | + |
| 6 | + |
| 7 | +def _run_async(coro): |
| 8 | + """ |
| 9 | + Runs an async function safely. |
| 10 | + - If an event loop is running, it schedules the coroutine with `asyncio.create_task()`. |
| 11 | + - Otherwise, it starts a new event loop with `asyncio.run()`. |
| 12 | + """ |
| 13 | + try: |
| 14 | + loop = asyncio.get_running_loop() |
| 15 | + return asyncio.create_task(coro) |
| 16 | + except RuntimeError: |
| 17 | + return asyncio.run(coro) |
| 18 | + |
| 19 | + |
| 20 | +class TelegramPlugin: |
| 21 | + """ |
| 22 | + A Telegram Bot SDK Plugin that integrates message handling and function-based execution. |
| 23 | +
|
| 24 | + Features: |
| 25 | + - Handles user interactions in Telegram. |
| 26 | + - Supports function-based execution (e.g., sending messages, polls). |
| 27 | + - Manages active user sessions. |
| 28 | +
|
| 29 | + Attributes: |
| 30 | + bot_token (str): The Telegram bot token, loaded from environment. |
| 31 | + application (Application): The Telegram application instance. |
| 32 | + bot (Bot): The Telegram bot instance. |
| 33 | +
|
| 34 | + Example: |
| 35 | + ```python |
| 36 | + tgBot = TelegramPlugin(bot_token=os.getenv("TELEGRAM_BOT_TOKEN")) |
| 37 | + tgBot.start_polling() |
| 38 | + ``` |
| 39 | + """ |
| 40 | + |
| 41 | + def __init__(self, bot_token: str): |
| 42 | + self.bot_token = bot_token |
| 43 | + self.application = ApplicationBuilder().token(self.bot_token).build() |
| 44 | + self.bot = self.application.bot |
| 45 | + |
| 46 | + def send_message(self, chat_id: Union[int, str], text: str): |
| 47 | + """Send a message to a chat safely while polling is running.""" |
| 48 | + if not chat_id or not text: |
| 49 | + raise Exception("Error: chat_id and text are required.") |
| 50 | + |
| 51 | + return _run_async(self.bot.send_message(chat_id=chat_id, text=text)) |
| 52 | + |
| 53 | + def send_media( |
| 54 | + self, chat_id: Union[int, str], media_type: str, media: str, caption: str = None |
| 55 | + ): |
| 56 | + """Send a media message (photo, document, video, audio) with an optional caption.""" |
| 57 | + if not chat_id or not media_type or not media: |
| 58 | + raise Exception("Error: chat_id, media_type, and media are required.") |
| 59 | + |
| 60 | + if media_type == "photo": |
| 61 | + return _run_async(self.bot.send_photo(chat_id=chat_id, photo=media, caption=caption)) |
| 62 | + elif media_type == "document": |
| 63 | + return _run_async(self.bot.send_document(chat_id=chat_id, document=media, caption=caption)) |
| 64 | + elif media_type == "video": |
| 65 | + return _run_async(self.bot.send_video(chat_id=chat_id, video=media, caption=caption)) |
| 66 | + elif media_type == "audio": |
| 67 | + return _run_async(self.bot.send_audio(chat_id=chat_id, audio=media, caption=caption)) |
| 68 | + else: |
| 69 | + raise Exception("Error: Invalid media_type. Use 'photo', 'document', 'video', or 'audio'.") |
| 70 | + |
| 71 | + def create_poll( |
| 72 | + self, chat_id: Union[int, str], question: str, options: List[str], is_anonymous: bool = True, |
| 73 | + allows_multiple_answers: bool = False |
| 74 | + ): |
| 75 | + """Create a poll in a chat safely while polling is running.""" |
| 76 | + if not chat_id or not question or not options: |
| 77 | + raise Exception("Error: chat_id, question, and options are required.") |
| 78 | + if not (2 <= len(options) <= 10): |
| 79 | + raise Exception("Poll must have between 2 and 10 options.") |
| 80 | + |
| 81 | + return _run_async( |
| 82 | + self.bot.send_poll( |
| 83 | + chat_id=chat_id, |
| 84 | + question=question, |
| 85 | + options=options, |
| 86 | + is_anonymous=is_anonymous, |
| 87 | + allows_multiple_answers=allows_multiple_answers |
| 88 | + ) |
| 89 | + ) |
| 90 | + |
| 91 | + def pin_message(self, chat_id: Union[int, str], message_id: int): |
| 92 | + """Pin a message in the chat.""" |
| 93 | + if chat_id is None or message_id is None: |
| 94 | + raise Exception("Error: chat_id and message_id are required to pin a message.") |
| 95 | + |
| 96 | + return _run_async(self.bot.pin_chat_message(chat_id=chat_id, message_id=message_id)) |
| 97 | + |
| 98 | + def unpin_message(self, chat_id: Union[int, str], message_id: int): |
| 99 | + """Unpin a specific message in the chat.""" |
| 100 | + if chat_id is None or message_id is None: |
| 101 | + raise Exception("Error: chat_id and message_id are required to unpin a message.") |
| 102 | + |
| 103 | + return _run_async(self.bot.unpin_chat_message(chat_id=chat_id, message_id=message_id)) |
| 104 | + |
| 105 | + def delete_message(self, chat_id: Union[int, str], message_id: int): |
| 106 | + """Delete a message from the chat.""" |
| 107 | + if chat_id is None or message_id is None: |
| 108 | + raise Exception("Error: chat_id and message_id are required to delete a message.") |
| 109 | + |
| 110 | + return _run_async(self.bot.delete_message(chat_id=chat_id, message_id=message_id)) |
| 111 | + |
| 112 | + def start_polling(self): |
| 113 | + """Start polling asynchronously in the main thread.""" |
| 114 | + self.application.run_polling() |
| 115 | + |
| 116 | + def add_handler(self, handler): |
| 117 | + """Register a message handler for text messages.""" |
| 118 | + self.application.add_handler(handler) |
0 commit comments