import re import logging from telegram import Update, ForceReply from telegram.ext…
- User
import re import logging from telegram import Update, ForceReply from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, MessageHandler, filters from gradio_client import Client
TOKEN = "6361706021:AAHgvmXqcqTsyMwReW1fco2E5fP07V561bU"
Включение логирования
logger = logging.getLogger(name)
Инициализация клиента Gradio
try: logger.info("Initializing Gradio client...") client = Client("yuntian-deng/o1") logger.info("Gradio client initialized successfully") except Exception as e: logger.error(f"Failed to initialize Gradio client: {e}", exc_info=True)
Словарь для хранения истории чатов для каждого пользователя
chat_histories = {}
разрешённые ID даша стёпа дениз
ALLOWED_USER_IDS = [5197267693, 1956293525, 424323538]
def markdown_to_telegram_html(text): # Заголовки text = re.sub(r'^# (.+)', r'<b>\1</b>', text, flags=re.MULTILINE) text = re.sub(r'^## (.+)', r'\1', text, flags=re.MULTILINE) text = re.sub(r'^### (.+)$', r'\1', text, flags=re.MULTILINE)
# Жирный курсивный текст text = re.sub(r'\*\*\*(.*?)\*\*\*', r'<b><i>\1</i></b>', text) # Жирный текст text = re.sub(r'\*\*(.*?)\*\*', r'<b>\1</b>', text) # Курсивный текст text = re.sub(r'\*(.*?)\*', r'<i>\1</i>', text) # Зачёркнутый текст text = re.sub(r'(.*?)', r'<s>\1</s>', text) # Горизонтальная линия (заменяем на символы, поддерживаемые Telegram) text = re.sub(r'^---$', r'――――――――――', text, flags=re.MULTILINE) # Ссылки text = re.sub(r'\[(.*?)\]\((.*?)\)', r'<a href="\2">\1</a>', text) # Блоки кода (многострочные) text = re.sub(r'(?:\w+\n)?([\s\S]+?)', r'<pre>\1</pre>', text) # Однострочный код text = re.sub(r'(.*?)', r'<code>\1</code>', text) # Списки (упрощенно) text = re.sub(r'^-\s(.+)$', r'• \1', text, flags=re.MULTILINE) text = re.sub(r'^\d+\.\s(.+)$', r' \1', text, flags=re.MULTILINE) # Удаление неподдерживаемых элементов #text = re.sub(r'!\[.*?\]\(.*?\)', '', text) # Изображения #text = re.sub(r'^\|.*\|.*$', '', text, flags=re.MULTILINE) # Таблицы #text = re.sub(r':[a-z_+-]+:', '', text) # Эмодзи #text = re.sub(r'[\^~](.+?)[\^~]', r'\1', text) # Подстрочный и надстрочный текст #text = re.sub(r'\$\$.*?\$\$', '', text, flags=re.DOTALL) # Формулы TeX #text = re.sub(r'\[\d+\]:\s*http.*$', '', text, flags=re.MULTILINE) # Сноски #text = re.sub(r'^> (.+)$', r'\1', text, flags=re.MULTILINE) # Цитаты # Удаление неподдерживаемых HTML-тегов def remove_unsupported_html_tags(text): allowed_tags = ['a', 'b', 'strong', 'i', 'em', 'u', 'ins', 's', 'strike', 'del', 'code', 'pre'] # Исправленное регулярное выражение pattern = r'</?(?!(?:' + '|'.join(allowed_tags) + r')\b)([a-zA-Z]+)(?:\s[^>]*)?>' text = re.sub(pattern, '', text) return text text = remove_unsupported_html_tags(text) return text.strip()Команда /start
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: user = update.effective_user
# Проверка, разрешен ли доступ пользователю if user.id not in ALLOWED_USER_IDS: await update.message.reply_text("Извините, у вас нет доступа к этому боту.") return await update.message.reply_html( rf"Привет, {user.mention_html()}! Как я могу вам помочь?", reply_markup=ForceReply(selective=True), )Обработка текстовых сообщений
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: user_id = update.effective_user.id
# Проверка, разрешен ли доступ пользователю if user_id not in ALLOWED_USER_IDS: await update.message.reply_text("Извините, у вас нет доступа к этому боту.") return user_message = update.message.text # Получение истории чата пользователя или инициализация новой history = chat_histories.get(user_id, []) - Assistant
It looks like you're working on a Telegram bot that interfaces with a Gradio client. I'd be happy to help you troubleshoot or improve your code. Here are some observations and suggestions based on the code you've provided:
-
Incomplete
handle_messageFunction:- The
handle_messagefunction ends abruptly after retrieving the user's chat history:
There is no further code to process the user's message or interact with the Gradio client. You'll need to implement the logic to send the user's message to the Gradio client and handle the response.history = chat_histories.get(user_id, [])
- The
-
Undefined Variable
namein Logger Configuration:- In the logger setup, you're using
name, but it isn't defined in your code:logger = logging.getLogger(name)- Solution: Replace
namewith__name__to use the current module's name:logger = logging.getLogger(__name__) - Additionally, you might want to configure the logging level and format:
logging.basicConfig(level=logging.INFO)
- Solution: Replace
- In the logger setup, you're using
-
Handling the Bot Token Securely:
- Storing the bot token directly in your code is not secure. If this code is ever shared or pushed to a repository, your bot token could be compromised.
- Solution: Use environment variables to store sensitive information. For example:
import os TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") - Then, set the
TELEGRAM_BOT_TOKENenvironment variable in your deployment environment.
- Solution: Use environment variables to store sensitive information. For example:
- Storing the bot token directly in your code is not secure. If this code is ever shared or pushed to a repository, your bot token could be compromised.
-
Completing the
handle_messageFunction:- To make the bot functional, you need to implement the message handling logic. Here's a basic outline of how you might proceed:
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: user_id = update.effective_user.id # Check if the user is allowed if user_id not in ALLOWED_USER_IDS: await update.message.reply_text("Извините, у вас нет доступа к этому боту.") return user_message = update.message.text # Get or initialize the user's chat history history = chat_histories.get(user_id, []) # Add the user's message to the history history.append({"role": "user", "content": user_message}) try: # Send the message to the Gradio client and get the response result = client.predict( user_message, api_name="/chat" # Adjust this based on your Gradio app's API endpoint ) # Process the result (if needed) bot_response = result # Assuming 'result' is the bot's reply # Convert Markdown to Telegram-compatible HTML bot_response = markdown_to_telegram_html(bot_response) # Add the bot's response to the history history.append({"role": "assistant", "content": bot_response}) # Save the updated history chat_histories[user_id] = history # Send the response to the user await update.message.reply_html(bot_response) except Exception as e: logger.error(f"Error processing message: {e}", exc_info=True) await update.message.reply_text("Произошла ошибка при обработке вашего сообщения.")- Adjust the
client.predictcall according to the actual API of your Gradio client. - Make sure to handle exceptions to prevent the bot from crashing on unexpected errors.
- Adjust the
- To make the bot functional, you need to implement the message handling logic. Here's a basic outline of how you might proceed:
-
Adjusting the
markdown_to_telegram_htmlFunction:- The regular expressions in your
markdown_to_telegram_htmlfunction might need adjustments to correctly convert Markdown to Telegram's HTML format. - Also, ensure that you're properly escaping any HTML-sensitive characters to prevent formatting issues.
- The regular expressions in your
-
Setting Up the Bot Application:
- Ensure that you have the bot application set up and running. Here's an example of how to put it all together:
if __name__ == "__main__": # Create the application instance application = ApplicationBuilder().token(TOKEN).build() # Add handlers application.add_handler(CommandHandler("start", start)) application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) # Run the bot application.run_polling()- This will start the bot and begin polling for updates.
- Ensure that you have the bot application set up and running. Here's an example of how to put it all together:
-
Ensuring Gradio Client Compatibility:
- Verify that the Gradio client is correctly configured and that you're using the correct API endpoints.
- The
api_namein thepredictfunction should match the API endpoint defined in your Gradio app. - Ensure that the Gradio server is running and accessible from where your bot is deployed.
-
Debugging and Logging:
- Use logging statements liberally to trace the execution flow and catch any issues.
- Example:
logger.info(f"Received message from user {user_id}: {user_message}") logger.info(f"Sending message to Gradio client: {user_message}")
-
Environment Setup:
- Make sure all necessary packages are installed and up to date:
pip install python-telegram-bot gradio_client
- Make sure all necessary packages are installed and up to date:
-
Sample Complete Code:
- Here’s how the complete script might look after incorporating all the suggestions:
import os import re import logging from telegram import Update, ForceReply from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, MessageHandler, filters from gradio_client import Client # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Get the bot token from an environment variable TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") # Initialize the Gradio client try: logger.info("Initializing Gradio client...") client = Client("yuntian-deng/o1") logger.info("Gradio client initialized successfully") except Exception as e: logger.error(f"Failed to initialize Gradio client: {e}", exc_info=True) # Dictionary to store chat histories chat_histories = {} # Allowed user IDs ALLOWED_USER_IDS = [5197267693, 1956293525, 424323538] def markdown_to_telegram_html(text): # Your regex transformations here... # (Ensure that the function correctly transforms Markdown to Telegram HTML) return text.strip() async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: user = update.effective_user # Check if the user is allowed if user.id not in ALLOWED_USER_IDS: await update.message.reply_text("Извините, у вас нет доступа к этому боту.") return await update.message.reply_html( rf"Привет, {user.mention_html()}! Как я могу вам помочь?", reply_markup=ForceReply(selective=True), ) async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: user_id = update.effective_user.id # Check if the user is allowed if user_id not in ALLOWED_USER_IDS: await update.message.reply_text("Извините, у вас нет доступа к этому боту.") return user_message = update.message.text logger.info(f"Received message from user {user_id}: {user_message}") # Get or initialize the user's chat history history = chat_histories.get(user_id, []) # Add the user's message to the history history.append({"role": "user", "content": user_message}) try: # Send the message to the Gradio client and get the response result = client.predict( user_message, api_name="/chat" # Adjust based on your Gradio app ) bot_response = result logger.info(f"Received response from Gradio client: {bot_response}") # Convert Markdown to Telegram HTML bot_response = markdown_to_telegram_html(bot_response) # Add the bot's response to the history history.append({"role": "assistant", "content": bot_response}) # Save the updated history chat_histories[user_id] = history # Send the response to the user await update.message.reply_html(bot_response) except Exception as e: logger.error(f"Error processing message: {e}", exc_info=True) await update.message.reply_text("Произошла ошибка при обработке вашего сообщения.") if __name__ == "__main__": # Create the application instance application = ApplicationBuilder().token(TOKEN).build() # Add handlers application.add_handler(CommandHandler("start", start)) application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) # Run the bot application.run_polling()
Next Steps:
- Test the Bot Locally: Run the bot locally and test its functionality.
- Check Gradio Integration: Ensure that the communication with the Gradio client works as expected.
- Error Handling: Enhance error handling as needed, possibly adding retries or more detailed user messages.
- Security Review: Review the code for any potential security issues, especially if you plan to deploy it to a production environment.
Questions for You:
- Are you encountering any specific errors when running the bot?
- Do you need assistance with setting up the Gradio client or defining its API endpoints?
- Is there any specific functionality you'd like to add to the bot?
Feel free to share any error messages or additional requirements, and I'll be happy to help further!
-