### Set Up Virtual Environment and Install Dependencies Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/README.md Create a Python virtual environment and activate it. Then, install all necessary project dependencies using pip. ```bash python -m venv .venv source .venv/bin/activate # Linux/macOS # or .venv\Scripts\activate # Windows pip install -r requirements.txt ``` -------------------------------- ### Install and Login to Vercel CLI Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/README.md Install the Vercel CLI globally and log in to your Vercel account. This is the first step for deploying the project on Vercel. ```bash npm i -g vercel vercel login ``` -------------------------------- ### Supabase MCP Configuration Example Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/MCP_DATABASE_ACCESS.md An example JSON configuration for setting up a Supabase MCP server connection, specifying the type and URL. ```json { "mcpServers": { "supabase-everest-dev": { "type": "http", "url": "https://mcp.supabase.com/mcp?project_ref=&read_only=true&features=database,docs" } } } ``` -------------------------------- ### Run Cloudflared Tunnel Locally Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/README.md Start the cloudflared tunnel using the locally installed cloudflared binary. This is an alternative to using Docker. ```bash cloudflared tunnel --no-autoupdate run --token "$CLOUDFLARED_TUNNEL_TOKEN" ``` -------------------------------- ### Install python-telegram-bot Source: https://context7.com/artemfilin1990/telegramdadatabot/llms.txt Install the base package or with optional dependencies for extended functionality. ```bash pip install python-telegram-bot --upgrade ``` ```bash pip install "python-telegram-bot[ext]" ``` ```bash pip install "python-telegram-bot[all]" ``` ```bash pip install "python-telegram-bot[job-queue]" # APScheduler для таймеров ``` ```bash pip install "python-telegram-bot[webhooks]" # Tornado для webhook ``` ```bash pip install "python-telegram-bot[callback-data]" # произвольные данные кнопок ``` ```bash pip install "python-telegram-bot[rate-limiter]" # ограничитель частоты запросов ``` ```bash pip install "python-telegram-bot[http2]" # поддержка HTTP/2 ``` ```bash pip install "python-telegram-bot[socks]" # SOCKS5 прокси ``` ```bash pip install "python-telegram-bot[passport]" # Telegram Passport ``` -------------------------------- ### JobQueue for Scheduled Tasks Example Source: https://context7.com/artemfilin1990/telegramdadatabot/llms.txt This example shows how to schedule delayed and repeating tasks using `JobQueue`. It requires `python-telegram-bot[job-queue]` to be installed. Functions like `run_once`, `run_repeating`, `run_daily`, and `run_monthly` are supported. ```python import logging from telegram import Update from telegram.ext import Application, CommandHandler, ContextTypes logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO) async def alarm(context: ContextTypes.DEFAULT_TYPE) -> None: """Отправляет уведомление по истечении таймера.""" job = context.job await context.bot.send_message( job.chat_id, text=f"Таймер истёк! Прошло {job.data} секунд." ) def remove_job_if_exists(name: str, context: ContextTypes.DEFAULT_TYPE) -> bool: """Удаляет существующее задание по имени. Возвращает True, если задание было удалено.""" current_jobs = context.job_queue.get_jobs_by_name(name) if not current_jobs: return False for job in current_jobs: job.schedule_removal() return True async def set_timer(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Создаёт таймер на указанное количество секунд.""" chat_id = update.effective_message.chat_id try: due = float(context.args[0]) if due < 0: await update.effective_message.reply_text("Нельзя установить таймер на прошлое!") return # Удаляем предыдущий таймер для этого чата (если есть) job_removed = remove_job_if_exists(str(chat_id), context) # Создаём новое одноразовое задание context.job_queue.run_once( alarm, due, chat_id=chat_id, name=str(chat_id), data=due ) text = "Таймер установлен!" if job_removed: text += " Предыдущий таймер удалён." await update.effective_message.reply_text(text) except (IndexError, ValueError): await update.effective_message.reply_text("Использование: /set <секунды>") async def unset(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Отменяет активный таймер.""" chat_id = update.message.chat_id job_removed = remove_job_if_exists(str(chat_id), context) text = "Таймер отменён!" if job_removed else "У вас нет активного таймера." await update.message.reply_text(text) def main() -> None: # job-queue активируется автоматически при наличии APScheduler application = Application.builder().token("TOKEN").build() application.add_handler(CommandHandler(["start", "help"], lambda u, c: u.message.reply_text("Используйте /set <секунды>"))) application.add_handler(CommandHandler("set", set_timer)) application.add_handler(CommandHandler("unset", unset)) application.run_polling(allowed_updates=Update.ALL_TYPES) if __name__ == "__main__": main() ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/README.md Copy the example environment file and edit it to include your Telegram bot token and DaData API credentials. These are essential for the bot's operation. ```bash cp .env.example .env ``` ```env TELEGRAM_TOKEN=your_telegram_bot_token_here DADATA_API_KEY=your_dadata_api_key_here DADATA_SECRET_KEY=your_dadata_secret_key_here ``` -------------------------------- ### Run Telegram Bot with Webhooks Source: https://context7.com/artemfilin1990/telegramdadatabot/llms.txt Use this snippet to start your Telegram bot using webhooks. Ensure you have installed `python-telegram-bot[webhooks]` and have SSL certificates and a private key configured. ```python from telegram.ext import Application def main() -> None: application = Application.builder().token("TOKEN").build() # Настройка и запуск webhook application.run_webhook( listen="0.0.0.0", # Адрес для прослушивания port=8443, # Порт (443, 80, 88, 8443) secret_token="MY_SECRET", # Секретный токен для верификации запросов от Telegram key="private.key", # Путь к приватному ключу SSL cert="cert.pem", # Путь к сертификату SSL webhook_url="https://your-domain.com/TOKEN", # Публичный URL вашего сервера ) if __name__ == "__main__": main() ``` -------------------------------- ### Run FastAPI Application Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/README.md Start the FastAPI application for local development or testing. The `--reload` flag enables hot-reloading for development. ```bash uvicorn api.main:app --host 0.0.0.0 --port 8000 --reload ``` -------------------------------- ### Telegram Bot Main Application Setup Source: https://context7.com/artemfilin1990/telegramdadatabot/llms.txt Sets up the Telegram bot application, registers command handlers for `/poll` and `/quiz`, and adds handlers for `PollAnswerHandler` and `PollHandler`. The bot polls for updates continuously. ```Python def main() -> None: application = Application.builder().token("TOKEN").build() application.add_handler(CommandHandler("poll", poll)) application.add_handler(CommandHandler("quiz", quiz)) application.add_handler(PollAnswerHandler(receive_poll_answer)) application.add_handler(PollHandler(lambda u, c: None)) # Обработчик обновлений опроса application.run_polling(allowed_updates=Update.ALL_TYPES) if __name__ == "__main__": main() ``` -------------------------------- ### InlineKeyboardMarkup and CallbackQueryHandler Example Source: https://context7.com/artemfilin1990/telegramdadatabot/llms.txt This snippet demonstrates creating messages with inline buttons and handling user interactions via CallbackQueryHandler. Ensure CallbackQuery is acknowledged with `query.answer()`. ```python import logging from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update from telegram.ext import Application, CallbackQueryHandler, CommandHandler, ContextTypes logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO) async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Отправляет сообщение с тремя inline-кнопками.""" keyboard = [ [ InlineKeyboardButton("Вариант 1", callback_data="1"), InlineKeyboardButton("Вариант 2", callback_data="2"), ], [InlineKeyboardButton("Вариант 3", callback_data="3")], ] reply_markup = InlineKeyboardMarkup(keyboard) await update.message.reply_text("Выберите вариант:", reply_markup=reply_markup) async def button(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Обрабатывает нажатие кнопки и обновляет текст сообщения.""" query = update.callback_query # Обязательно подтверждаем получение callback query await query.answer() # Редактируем исходное сообщение await query.edit_message_text(text=f"Выбран вариант: {query.data}") def main() -> None: application = Application.builder().token("TOKEN").build() application.add_handler(CommandHandler("start", start)) # CallbackQueryHandler без паттерна — перехватывает все callback application.add_handler(CallbackQueryHandler(button)) application.run_polling(allowed_updates=Update.ALL_TYPES) if __name__ == "__main__": main() ``` -------------------------------- ### Run Cloudflared Tunnel with Docker Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/README.md Start the cloudflared tunnel using Docker. This command ensures the connector runs in an isolated environment. ```bash docker run --rm cloudflare/cloudflared:latest tunnel --no-autoupdate run --token "$CLOUDFLARED_TUNNEL_TOKEN" ``` -------------------------------- ### Local DB MCP Configuration Copy Command Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/MCP_DATABASE_ACCESS.md Command to copy the example MCP configuration file to a local configuration file for modification. Sensitive access details should not be committed. ```bash cp mcp/db-mcp.config.example.json mcp/db-mcp.config.local.json ``` -------------------------------- ### Run the Telegram Bot Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/README.md Execute the main Python script to start the Telegram bot. The bot will run in polling mode to receive updates from Telegram. ```bash python bot/main.py ``` -------------------------------- ### Cursor/Claude Code MCP Configuration for db-mcp-server Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/MCP_DATABASE_ACCESS.md Example `.cursor/mcp.json` configuration for connecting to a local db-mcp-server instance using the STDIO transport mode. Adjust paths as necessary. ```json { "mcpServers": { "everest-db": { "command": "/path/to/db-mcp-server/server", "args": [ "-t", "stdio", "-c", "/path/to/TelegramDadataBot/mcp/db-mcp.config.local.json" ] } } } ``` -------------------------------- ### Getting Updates Methods Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/source/inclusions/bot_methods.rst Methods for retrieving and managing updates, including long polling and webhooks. ```APIDOC ## get_updates ### Description Used for getting updates using long polling. ### Method GET ### Endpoint /getUpdates ## get_webhook_info ### Description Used for getting current webhook status. ### Method GET ### Endpoint /getWebhookInfo ## set_webhook ### Description Used for setting a webhook to receive updates. ### Method POST ### Endpoint /setWebhook ## delete_webhook ### Description Used for removing webhook integration. ### Method POST ### Endpoint /deleteWebhook ``` -------------------------------- ### Telegram Bot with PicklePersistence Source: https://context7.com/artemfilin1990/telegramdadatabot/llms.txt This example shows a complete Telegram bot using PicklePersistence to save conversation state and user data. It requires a Telegram Bot Token and saves data to 'my_bot_data'. ```python import logging from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update from telegram.ext import ( Application, CommandHandler, ContextTypes, ConversationHandler, MessageHandler, PicklePersistence, filters, ) logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO) CHOOSING, TYPING_REPLY = range(2) reply_keyboard = [["Возраст", "Цвет"], ["Готово"]] markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: """Начало диалога с восстановлением сохранённых данных.""" if context.user_data: # Данные сохранились между перезапусками! saved_keys = ", ".join(context.user_data.keys()) reply_text = f"С возвращением! Я помню: {saved_keys}. Что добавить?" else: reply_text = "Привет! Расскажите о себе." await update.message.reply_text(reply_text, reply_markup=markup) return CHOOSING async def received_information(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: """Сохраняет введённую информацию в user_data.""" topic = context.user_data.get("choice", "что-то") context.user_data[topic] = update.message.text await update.message.reply_text( f"Записал! Ваш {topic}: {update.message.text}", reply_markup=markup ) return CHOOSING async def done(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: """Завершает диалог, показывает итог.""" if context.user_data: facts = "\n".join(f"{k}: {v}" for k, v in context.user_data.items() if k != "choice") await update.message.reply_text(f"Итого:\n{facts}", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def main() -> None: # Данные сохраняются в файл my_bot_data persistence = PicklePersistence(filepath="my_bot_data") application = ( Application.builder() .token("TOKEN") .persistence(persistence) # Подключаем persistence .build() ) conv_handler = ConversationHandler( entry_points=[CommandHandler("start", start)], states={ CHOOSING: [ MessageHandler(filters.Regex("^(Возраст|Цвет)$$"), lambda u, c: (c.user_data.update({"choice": u.message.text}) or True) and u.message.reply_text(f"Ваш {u.message.text}?") or TYPING_REPLY), ], TYPING_REPLY: [MessageHandler(filters.TEXT & ~filters.COMMAND, received_information)], }, fallbacks=[MessageHandler(filters.Regex("^Готово$"), done)], # persist=True сохраняет состояние разговора между перезапусками persistent=True, name="my_conversation", ) application.add_handler(conv_handler) application.run_polling(allowed_updates=Update.ALL_TYPES) if __name__ == "__main__": main() ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/README.md Clone the project repository and navigate into the project directory. This is the initial step for setting up the bot locally. ```bash git clone cd TelegramDadataBot ``` -------------------------------- ### Deploy Project on Vercel Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/README.md Deploy the project to Vercel from the project root. This command initiates the deployment process. ```bash vercel ``` -------------------------------- ### Runtime vs. MCP Data Access Chains Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/MCP_DATABASE_ACCESS.md Illustrates the distinct data access paths for production applications (FastAPI/asyncpg) versus development/agent access via MCP. ```text FastAPI / Telegram → service layer → asyncpg → PostgreSQL ``` ```text Agent / Codex / Claude Code → MCP server → PostgreSQL / Supabase ``` -------------------------------- ### Project Directory Structure Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/AGENTS.md Outlines the recommended directory structure for the project, separating concerns like bot logic, API, legal processing, configuration, and utilities. ```text bot/ Telegram bot: handlers, keyboards, formatter, DaData client api/ FastAPI app: routes, schemas, deps, services bot/legal/ legal ingestion, RAG, storage, template generation config/ settings from environment utils/ validators and helpers templates/ DOCX templates ``` -------------------------------- ### MCP Recommendation for PostgreSQL/Amvera Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/MCP_DATABASE_ACCESS.md Recommends using FreePeak/db-mcp-server for projects with PostgreSQL or Amvera databases. ```text использовать FreePeak/db-mcp-server ``` -------------------------------- ### Production Deployment on Vercel Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/README.md Perform a production deployment of the project using the Vercel CLI. Ensure all production environment variables are set correctly. ```bash vercel --prod ``` -------------------------------- ### Basic Telegram Bot Application Source: https://context7.com/artemfilin1990/telegramdadatabot/llms.txt Sets up a Telegram bot using Application, CommandHandler, and MessageHandler. Requires Python 3.10+ and the python-telegram-bot library. ```python import logging from telegram import ForceReply, Update from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO ) logging.getLogger("httpx").setLevel(logging.WARNING) async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Обработчик команды /start — приветствует пользователя.""" user = update.effective_user await update.message.reply_html( rf"Привет, {user.mention_html()}!", reply_markup=ForceReply(selective=True), ) async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Повторяет входящее сообщение обратно пользователю.""" await update.message.reply_text(update.message.text) def main() -> None: # Создание приложения через Builder application = Application.builder().token("TOKEN").build() # Регистрация обработчиков команд application.add_handler(CommandHandler("start", start)) # Обработчик текстовых сообщений (не команды) application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo)) # Запуск бота в режиме polling — блокирует выполнение до Ctrl-C application.run_polling(allowed_updates=Update.ALL_TYPES) if __name__ == "__main__": main() ``` -------------------------------- ### Bot Settings Methods Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/source/inclusions/bot_methods.rst Methods for configuring bot commands, descriptions, names, and menu buttons. ```APIDOC ## set_my_commands ### Description Used for setting the list of commands. ### Method `set_my_commands` ## delete_my_commands ### Description Used for deleting the list of commands. ### Method `delete_my_commands` ## get_my_commands ### Description Used for obtaining the list of commands. ### Method `get_my_commands` ## get_my_default_administrator_rights ### Description Used for obtaining the default administrator rights for the bot. ### Method `get_my_default_administrator_rights` ## set_my_default_administrator_rights ### Description Used for setting the default administrator rights for the bot. ### Method `set_my_default_administrator_rights` ## get_chat_menu_button ### Description Used for obtaining the menu button of a private chat or the default menu button. ### Method `get_chat_menu_button` ## set_chat_menu_button ### Description Used for setting the menu button of a private chat or the default menu button. ### Method `set_chat_menu_button` ## set_my_description ### Description Used for setting the description of the bot. ### Method `set_my_description` ## get_my_description ### Description Used for obtaining the description of the bot. ### Method `get_my_description` ## set_my_short_description ### Description Used for setting the short description of the bot. ### Method `set_my_short_description` ## get_my_short_description ### Description Used for obtaining the short description of the bot. ### Method `get_my_short_description` ## set_my_name ### Description Used for setting the name of the bot. ### Method `set_my_name` ## get_my_name ### Description Used for obtaining the name of the bot. ### Method `get_my_name` ``` -------------------------------- ### Supabase MCP Recommended Mode Configuration Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/MCP_DATABASE_ACCESS.md Use these parameters for restricted access to Supabase projects via MCP. Ensure `project_ref` is always specified to limit visibility. ```text project_ref= read_only=true features=database,docs ``` ```text https://mcp.supabase.com/mcp?project_ref=&read_only=true&features=database,docs ``` -------------------------------- ### Production Code Recommendation Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/MCP_DATABASE_ACCESS.md Advises against using MCP for production code, recommending direct use of asyncpg and application services instead. ```text не использовать MCP, работать через asyncpg и сервисы приложения ``` -------------------------------- ### FreePeak/db-mcp-server Local STDIO Mode Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/MCP_DATABASE_ACCESS.md Command to run the FreePeak/db-mcp-server in local STDIO mode for development and diagnostics. Ensure the config file path is correct. ```bash ./bin/server -t stdio -c mcp/db-mcp.config.local.json ``` -------------------------------- ### MCP Recommendation for Supabase Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/MCP_DATABASE_ACCESS.md Recommends using Supabase MCP with specific parameters for projects hosted on Supabase. ```text использовать Supabase MCP с read_only=true + project_ref + features=database,docs ``` -------------------------------- ### Miscellaneous Methods Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/source/inclusions/bot_methods.rst Utility methods for bot management and information retrieval. ```APIDOC ## close ### Description Used for closing server instance when switching to another local server. ### Method close ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## log_out ### Description Used for logging out from cloud Bot API server. ### Method log_out ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## get_file ### Description Used for getting basic info about a file. ### Method get_file ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## get_available_gifts ### Description Used for getting information about gifts available for sending. ### Method get_available_gifts ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## get_chat_gifts ### Description Used for getting information about gifts owned and hosted by a chat. ### Method get_chat_gifts ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## get_me ### Description Used for getting basic information about the bot. ### Method get_me ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## get_user_gifts ### Description Used for getting information about gifts owned and hosted by a user. ### Method get_user_gifts ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## save_prepared_inline_message ### Description Used for storing a message to be sent by a user of a Mini App. ### Method save_prepared_inline_message ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` -------------------------------- ### DOCX Template Placeholders Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/AGENTS.md Illustrates the format of placeholders used within DOCX templates for dynamic content insertion. ```text [[НОМЕР_ДОГОВОРА]] [[ИНН_ПОКУПАТЕЛЯ]] [[РАСЧЕТНЫЙ_СЧЕТ_ПОКУПАТЕЛЯ]] ``` -------------------------------- ### Unfilled Placeholder Options Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/AGENTS.md Presents the options offered to the user when placeholders remain unfilled after template generation. ```text [✍️ Заполнить] [📤 Выгрузить как есть] [❌ Отмена] ``` -------------------------------- ### Multi-step Dialogs with ConversationHandler Source: https://context7.com/artemfilin1990/telegramdadatabot/llms.txt Manage stateful, multi-step conversations using `ConversationHandler`. It tracks user states and transitions between them based on defined handlers. ```python import logging from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update from telegram.ext import ( Application, CommandHandler, ContextTypes, ConversationHandler, MessageHandler, filters, ) logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO) # Определение состояний диалога GENDER, PHOTO, LOCATION, BIO = range(4) async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: """Начало диалога — запрашивает пол.""" reply_keyboard = [["Мужской", "Женский", "Другой"]] await update.message.reply_text( "Привет! Я буду задавать вам вопросы.\nОтправьте /cancel для отмены.\n\nВаш пол?", reply_markup=ReplyKeyboardMarkup( reply_keyboard, one_time_keyboard=True, input_field_placeholder="Выберите пол" ), ) return GENDER # Переход в состояние GENDER async def gender(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: """Сохраняет пол и запрашивает фото.""" user = update.message.from_user logging.info("Пол пользователя %s: %s", user.first_name, update.message.text) await update.message.reply_text( "Хорошо! Пришлите ваше фото или /skip.", reply_markup=ReplyKeyboardRemove(), ) return PHOTO # Переход в состояние PHOTO async def photo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: """Сохраняет фото и запрашивает местоположение.""" photo_file = await update.message.photo[-1].get_file() await photo_file.download_to_drive("user_photo.jpg") await update.message.reply_text("Отлично! Теперь пришлите вашу геолокацию или /skip.") return LOCATION async def skip_photo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: """Пропускает фото.""" await update.message.reply_text("Пришлите вашу геолокацию или /skip.") return LOCATION async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: """Отменяет диалог.""" await update.message.reply_text("Диалог завершён.", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END # Завершение диалога def main() -> None: application = Application.builder().token("TOKEN").build() conv_handler = ConversationHandler( entry_points=[CommandHandler("start", start)], states={ GENDER: [MessageHandler(filters.Regex("^(Мужской|Женский|Другой)$"), gender)], PHOTO: [ MessageHandler(filters.PHOTO, photo), CommandHandler("skip", skip_photo), ], LOCATION: [CommandHandler("skip", cancel)], }, fallbacks=[CommandHandler("cancel", cancel)], ) application.add_handler(conv_handler) application.run_polling(allowed_updates=Update.ALL_TYPES) if __name__ == "__main__": main() ``` -------------------------------- ### FreePeak/db-mcp-server Docker SSE Mode Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/MCP_DATABASE_ACCESS.md Command to run db-mcp-server using Docker in SSE (Server-Sent Events) mode. Mounts a local config file and exposes the SSE endpoint on port 9092. ```bash docker pull freepeak/db-mcp-server:latest docker run --rm -p 9092:9092 \ -v $(pwd)/mcp/db-mcp.config.local.json:/app/my-config.json \ -e TRANSPORT_MODE=sse \ -e CONFIG_PATH=/app/my-config.json \ freepeak/db-mcp-server ``` -------------------------------- ### SQL: Create Documents Table Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/README.md SQL statement to create the 'documents' table in the PostgreSQL database. This table stores metadata for uploaded documents. ```sql CREATE TABLE documents ( id BIGSERIAL PRIMARY KEY, title TEXT NOT NULL, original_filename TEXT NOT NULL, mime_type TEXT NOT NULL, size_bytes BIGINT NOT NULL, source_type TEXT NOT NULL, source_id TEXT, uploaded_by TEXT, processing_status TEXT NOT NULL, processing_error TEXT, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); ``` -------------------------------- ### Enable Telegram Polling Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/README.md Run the bot's main script with Telegram polling enabled. This is only active if the `ENABLE_TELEGRAM_POLLING` environment variable is set to `true`. ```bash ENABLE_TELEGRAM_POLLING=true python bot/main.py ``` -------------------------------- ### Sticker Management Methods Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/source/inclusions/bot_methods.rst Methods for creating, deleting, and managing sticker sets and individual stickers. ```APIDOC ## create_sticker_set ### Description Used for creating a new sticker set. ### Method POST ### Endpoint /createStickerSet ## delete_sticker_set ### Description Used for deleting a sticker set made by a bot. ### Method POST ### Endpoint /deleteStickerSet ## set_chat_sticker_set ### Description Used for setting a sticker set of a chat. ### Method POST ### Endpoint /setChatStickerSet ## delete_chat_sticker_set ### Description Used for deleting the set sticker set of a chat. ### Method POST ### Endpoint /deleteChatStickerSet ## replace_sticker_in_set ### Description Used for replacing a sticker in a set. ### Method POST ### Endpoint /replaceStickerInSet ## set_sticker_position_in_set ### Description Used for moving a sticker's position in the set. ### Method POST ### Endpoint /setStickerPositionInSet ## set_sticker_set_title ### Description Used for setting the title of a sticker set. ### Method POST ### Endpoint /setStickerSetTitle ## set_sticker_emoji_list ### Description Used for setting the emoji list of a sticker. ### Method POST ### Endpoint /setStickerEmojiList ## set_sticker_keywords ### Description Used for setting the keywords of a sticker. ### Method POST ### Endpoint /setStickerKeywords ## set_sticker_mask_position ### Description Used for setting the mask position of a mask sticker. ### Method POST ### Endpoint /setStickerMaskPosition ## set_sticker_set_thumbnail ### Description Used for setting the thumbnail of a sticker set. ### Method POST ### Endpoint /setStickerSetThumbnail ## set_custom_emoji_sticker_set_thumbnail ### Description Used for setting the thumbnail of a custom emoji sticker set. ### Method POST ### Endpoint /setCustomEmojiStickerSetThumbnail ## get_sticker_set ### Description Used for getting a sticker set. ### Method GET ### Endpoint /getStickerSet ## upload_sticker_file ### Description Used for uploading a sticker file. ### Method POST ### Endpoint /uploadStickerFile ## get_custom_emoji_stickers ### Description Used for getting custom emoji files based on their IDs. ### Method GET ### Endpoint /getCustomEmojiStickers ``` -------------------------------- ### Forum Topic Management Methods Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/source/inclusions/bot_methods.rst Methods for managing forum topics within a chat. ```APIDOC ## close_forum_topic ### Description Used for closing a forum topic. ### Method POST ### Endpoint /closeForumTopic ## close_general_forum_topic ### Description Used for closing the general forum topic. ### Method POST ### Endpoint /closeGeneralForumTopic ## create_forum_topic ### Description Used to create a topic. ### Method POST ### Endpoint /createForumTopic ## delete_forum_topic ### Description Used for deleting a forum topic. ### Method POST ### Endpoint /deleteForumTopic ## edit_forum_topic ### Description Used to edit a topic. ### Method POST ### Endpoint /editForumTopic ## edit_general_forum_topic ### Description Used to edit the general topic. ### Method POST ### Endpoint /editGeneralForumTopic ## get_forum_topic_icon_stickers ### Description Used to get custom emojis to use as topic icons. ### Method GET ### Endpoint /getForumTopicIconStickers ## hide_general_forum_topic ### Description Used to hide the general topic. ### Method POST ### Endpoint /hideGeneralForumTopic ## unhide_general_forum_topic ### Description Used to unhide the general topic. ### Method POST ### Endpoint /unhideGeneralForumTopic ## reopen_forum_topic ### Description Used to reopen a topic. ### Method POST ### Endpoint /reopenForumTopic ## reopen_general_forum_topic ### Description Used to reopen the general topic. ### Method POST ### Endpoint /reopenGeneralForumTopic ## unpin_all_forum_topic_messages ### Description Used to unpin all messages in a forum topic. ### Method POST ### Endpoint /unpinAllForumTopicMessages ## unpin_all_general_forum_topic_messages ### Description Used to unpin all messages in the general forum topic. ### Method POST ### Endpoint /unpinAllGeneralForumTopicMessages ``` -------------------------------- ### Sticker Set Management Methods Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/source/inclusions/bot_methods.rst Methods for managing stickers within sticker sets. ```APIDOC ## add_sticker_to_set ### Description Used for adding a sticker to a set. ### Method `add_sticker_to_set` ## delete_sticker_from_set ### Description Used for deleting a sticker from a set. ### Method `delete_sticker_from_set` ## create_new_sticker_set ### Description Used for creating a new sticker set. ### Method `create_new_sticker_set` ``` -------------------------------- ### Handle Inline Queries in Python Source: https://context7.com/artemfilin1990/telegramdadatabot/llms.txt This snippet demonstrates how to handle inline queries in a Telegram bot. It processes user input and returns a list of articles with different text formatting options. Ensure Inline Mode is enabled via @BotFather. ```python import logging from html import escape from uuid import uuid4 from telegram import InlineQueryResultArticle, InputTextMessageContent, Update from telegram.constants import ParseMode from telegram.ext import Application, CommandHandler, ContextTypes, InlineQueryHandler logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO) async def inline_query(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Обрабатывает инлайн-запросы. Вызывается при @botname <текст>. """ query = update.inline_query.query if not query: return # Пустой запрос игнорируется results = [ # Результат 1: текст в верхнем регистре InlineQueryResultArticle( id=str(uuid4()), title="ЗАГЛАВНЫЕ", input_message_content=InputTextMessageContent(query.upper()), ), # Результат 2: жирный текст (HTML) InlineQueryResultArticle( id=str(uuid4()), title="Жирный", input_message_content=InputTextMessageContent( f"{escape(query)}", parse_mode=ParseMode.HTML, ), ), # Результат 3: курсив (HTML) InlineQueryResultArticle( id=str(uuid4()), title="Курсив", input_message_content=InputTextMessageContent( f"{escape(query)}", parse_mode=ParseMode.HTML, ), ), ] # Отправляем список результатов пользователю await update.inline_query.answer(results) def main() -> None: application = Application.builder().token("TOKEN").build() application.add_handler(InlineQueryHandler(inline_query)) application.run_polling(allowed_updates=Update.ALL_TYPES) if __name__ == "__main__": main() ``` -------------------------------- ### Placeholder Regex Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/AGENTS.md Provides the regular expression used to find placeholders in DOCX templates. ```regex \[\[[^\\\]]+\]\] ``` -------------------------------- ### Game Methods Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/source/inclusions/bot_methods.rst Methods for interacting with game high scores and setting game scores. ```APIDOC ## get_game_high_scores ### Description Used for getting the game high scores. ### Method GET ### Endpoint /getGameHighScores ## set_game_score ### Description Used for setting the game score. ### Method POST ### Endpoint /setGameScore ``` -------------------------------- ### SQL: Create Document Chunks Table Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/README.md SQL statement to create the 'document_chunks' table. This table stores processed chunks of documents for Retrieval-Augmented Generation (RAG). ```sql CREATE TABLE document_chunks ( id BIGSERIAL PRIMARY KEY, document_id BIGINT REFERENCES documents(id) ON DELETE CASCADE, chunk_index INT NOT NULL, content TEXT NOT NULL, content_hash TEXT NOT NULL, token_count INT NOT NULL, metadata JSONB DEFAULT '{}'::jsonb, created_at TIMESTAMPTZ DEFAULT NOW() ); ``` -------------------------------- ### Business Account Methods Source: https://github.com/artemfilin1990/telegramdadatabot/blob/autogen-code/docs/source/inclusions/bot_methods.rst Methods related to managing business accounts, including profile settings, messages, and stories. ```APIDOC ## get_business_account_gifts ### Description Used for getting gifts owned by the business account. ### Method get_business_account_gifts ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## get_business_account_star_balance ### Description Used for getting the amount of Stars owned by the business account. ### Method get_business_account_star_balance ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## read_business_message ### Description Used for marking a message as read. ### Method read_business_message ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## delete_story ### Description Used for deleting business stories posted by the bot. ### Method delete_story ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## delete_business_messages ### Description Used for deleting business messages. ### Method delete_business_messages ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## remove_business_account_profile_photo ### Description Used for removing the business accounts profile photo. ### Method remove_business_account_profile_photo ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## set_business_account_name ### Description Used for setting the business account name. ### Method set_business_account_name ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## set_business_account_username ### Description Used for setting the business account username. ### Method set_business_account_username ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## set_business_account_bio ### Description Used for setting the business account bio. ### Method set_business_account_bio ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## set_business_account_gift_settings ### Description Used for setting the business account gift settings. ### Method set_business_account_gift_settings ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## set_business_account_profile_photo ### Description Used for setting the business accounts profile photo. ### Method set_business_account_profile_photo ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## post_story ### Description Used for posting a story on behalf of business account. ### Method post_story ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## repost_story ### Description Used for reposting an existing story on behalf of business account. ### Method repost_story ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## edit_story ### Description Used for editing business stories posted by the bot. ### Method edit_story ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## convert_gift_to_stars ### Description Used for converting owned regular gifts to stars. ### Method convert_gift_to_stars ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## upgrade_gift ### Description Used for upgrading owned regular gifts to unique ones. ### Method upgrade_gift ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## transfer_gift ### Description Used for transferring owned unique gifts to another user. ### Method transfer_gift ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## transfer_business_account_stars ### Description Used for transferring Stars from the business account balance to the bot's balance. ### Method transfer_business_account_stars ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## send_checklist ### Description Used for sending a checklist on behalf of the business account. ### Method send_checklist ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` ```APIDOC ## edit_message_checklist ### Description Used for editing a checklist on behalf of the business account. ### Method edit_message_checklist ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example N/A ### Response N/A ``` -------------------------------- ### Direct Telegram Bot API Access with Bot Class Source: https://context7.com/artemfilin1990/telegramdadatabot/llms.txt Use the `Bot` class as an async context manager for direct, asynchronous access to Telegram Bot API methods. It handles HTTP connection management. ```python import asyncio import contextlib import datetime as dtm import logging from telegram import Bot, Update from telegram.error import Forbidden, NetworkError logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO ) logging.getLogger("httpx").setLevel(logging.WARNING) async def echo(bot: Bot, update_id: int) -> int: """Получает обновления и эхо-отвечает на текстовые сообщения.""" updates = await bot.get_updates( offset=update_id, timeout=dtm.timedelta(seconds=10), allowed_updates=Update.ALL_TYPES, ) for update in updates: next_update_id = update.update_id + 1 if update.message and update.message.text: logging.info("Получено сообщение: %s", update.message.text) await update.message.reply_text(update.message.text) return next_update_id return update_id async def main() -> None: # Использование Bot как async context manager async with Bot("TOKEN") as bot: try: update_id = (await bot.get_updates())[0].update_id except IndexError: update_id = None logging.info("Ожидание новых сообщений...") while True: try: update_id = await echo(bot, update_id) except NetworkError: await asyncio.sleep(1) except Forbidden: # Пользователь заблокировал бота update_id += 1 if __name__ == "__main__": with contextlib.suppress(KeyboardInterrupt): asyncio.run(main()) ```