def handle_updates(updates, client):
for update in updates.get('result', []):
try:
message = update.get('message')
if not message:
continue
code
Assistant
chat_id = message['chat']['id']
text = message.get('text')
if text:
prompt = text
result = client.predict(
inputs=prompt,
top_p=1,
temperature=1,
chat_counter=0,
chatbot=[],
api_name="/predict_1"
)
# Проверяем, что result — кортеж и первый элемент — список строк
if isinstance(result, tuple) and len(result) > 0 and isinstance(result[0], list):
responses = result[0]
else:
responses = [str(result)]
# Исправляем кодировку: предположительно, строки были закодированы в utf-8, но интерпретированы как latin1
corrected_responses = []
for res in responses:
if isinstance(res, str):
try:
# Перекодируем из latin1 обратно в bytes, затем декодируем как utf-8
corrected_text = res.encode('latin1').decode('utf-8')
corrected_responses.append(corrected_text)
except UnicodeEncodeError:
# Если перекодировка не удалась, используем оригинальный текст
corrected_responses.append(res)
else:
corrected_responses.append(str(res))
# Убираем скобочки и кавычки из ответов
response_text = "\n".join(corrected_responses).replace('(', '').replace(')', '').replace("'", "")
# Убираем вопрос пользователя из ответа
if response_text.startswith(prompt):
response_text = response_text[len(prompt):].strip()
send_message(chat_id, response_text)
else:
# Обработка сообщений без текста (например, фото, стикеры и т.д.)
send_message(chat_id, "Извините, я могу отвечать только на текстовые сообщения.")
except Exception as e:
logging.error(f"Error handling update {update}: {e}")
send_message(chat_id, "Произошла ошибка при обработке вашего запроса.")
def main():
client = Client("yuntian-deng/o1mini") # Инициализируем один раз
offset = None
while True:
updates = get_updates(offset)
if 'result' in updates and updates['result']:
offset = updates['result'][-1]['update_id'] + 1
handle_updates(updates, client)
if name == 'main':
main()
Your script sets up a Telegram bot that receives messages, processes them using a Gradio-hosted model, and sends back responses. Here's a detailed review of your code along with recommendations to enhance its functionality, security, and reliability.
1. Security Concerns
Expose of API_TOKEN
You've included your Telegram Bot API token directly in the script:
python
API_TOKEN = '7921795346:AAEbI6pfqB-FBniI7nhkaZMnF_ucQas4Vc0' # Замените на ваш новый токен
Recommendation:
Never expose your API tokens in the code, especially if it's stored in a public repository.
Use environment variables or a configuration file that's excluded from version control (e.g., using .gitignore).
Example Using Environment Variables:
python
import os
API_TOKEN = os.getenv('TELEGRAM_API_TOKEN')
if not API_TOKEN:
raise ValueError("No API token found. Please set the TELEGRAM_API_TOKEN environment variable.")
You can set the environment variable in your terminal or deployment environment:
# Исправляем кодировку: предположительно, строки были закодированы в utf-8, но интерпретированы как latin1
Recommendation:
Investigate the Root Cause: Instead of manually correcting encoding, verify why the response has encoding issues. Ensure that the Gradio model returns text in the correct encoding.
Simplify Processing: If the encoding is correct, you can remove the encoding correction logic to simplify the code.
B. Robust Error Handling
While you have basic error logging, consider enhancing it:
Retry Mechanism: Implement retries for transient errors like network issues.
Specific Exception Handling: Catch specific exceptions to handle different error types more gracefully.
Example:
python
import time
from requests.exceptions import RequestException
def send_message(chat_id, text, retries=3, delay=5):
url = BASE_URL + 'sendMessage'
payload = {
'chat_id': chat_id,
'text': text,
'parse_mode': 'Markdown'
}
for attempt in range(retries):
try:
response = requests.post(url, json=payload)
if response.status_code == 200:
return
else:
logging.error(f"Attempt {attempt + 1}: Failed to send message: {response.text}")
except RequestException as e:
logging.error(f"Attempt {attempt + 1}: Error sending message: {e}")
time.sleep(delay)
logging.error("All attempts to send message failed.")
C. Optimizing Update Handling
Your current implementation uses long polling. Depending on your use case, consider:
Webhooks: More efficient for production as Telegram pushes updates to your server.
Polling Enhancements: Implement delays or backoff strategies to handle high traffic.
D. Resource Management
Ensure that resources like the Gradio client are managed efficiently.
Initialize Once: You already initialize the Gradio client once, which is good.
Graceful Shutdown: Handle termination signals to close resources properly.
Example:
python
import signal
import sys
def signal_handler(sig, frame):
logging.info("Shutting down gracefully...")
# Add any cleanup code here
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
3. Code Refactoring for Clarity and Efficiency
A. Simplify Response Handling
If the response from client.predict is consistent, streamline the processing.
Example:
python
def handle_updates(updates, client):
for update in updates.get('result', []):
try:
message = update.get('message')
if not message:
continue
chat_id = message['chat']['id']
text = message.get('text')
if text:
prompt = text
result = client.predict(
inputs=prompt,
top_p=1,
temperature=1,
chat_counter=0,
chatbot=[],
api_name="/predict_1"
)
# Assume result is a list of responses
if isinstance(result, (tuple, list)):
responses = result[0] if isinstance(result, tuple) else result
else:
responses = [str(result)]
response_text = "\n".join(responses).strip()
# Optionally remove the prompt from the response
if response_text.startswith(prompt):
response_text = response_text[len(prompt):].strip()
send_message(chat_id, response_text)
else:
send_message(chat_id, "Извините, я могу отвечать только на текстовые сообщения.")
except Exception as e:
logging.error(f"Error handling update {update}: {e}")
send_message(chat_id, "Произошла ошибка при обработке вашего запроса.")
B. Logging Enhancements
Include more context in your logs to facilitate debugging.
Telegram imposes rate limits. Ensure your bot respects these limits to avoid being banned.
Throttle Requests: Implement rate limiting on your side if necessary.
Handle 429 Responses: If Telegram responds with a rate limit error, back off accordingly.
B. Validation and Sanitization
Ensure that the inputs and outputs are validated and sanitized to prevent potential issues.
Input Sanitization: Clean user inputs to prevent injection attacks or malformed requests.
Output Encoding: Ensure responses are properly encoded to avoid breaking Telegram's message formatting.
C. Using a Dedicated Telegram Bot Library
Consider using a dedicated Telegram bot library like python-telegram-bot which provides higher-level abstractions and handles many edge cases for you.
Example Using python-telegram-bot:
python
from telegram.ext import Updater, MessageHandler, Filters
def handle_message(update, context):
chat_id = update.effective_chat.id
text = update.message.text
# Process the text with Gradio client
result = client.predict(
inputs=text,
top_p=1,
temperature=1,
chat_counter=0,
chatbot=[],
api_name="/predict_1"
)
# Simplify response handling as shown earlier
response_text = "\n".join(result).strip()
context.bot.send_message(chat_id=chat_id, text=response_text)
def main():
updater = Updater(API_TOKEN, use_context=True)
dp = updater.dispatcher
dp.add_handler(MessageHandler(Filters.text & ~Filters.command, handle_message))
updater.start_polling()
updater.idle()
Benefits:
Simplifies handling updates.
Manages long polling or webhooks efficiently.
Provides built-in methods for common tasks like sending messages, handling different message types, etc.
5. Final Revised Code Example
Incorporating the above recommendations, here's a revised version of your script using environment variables and improved structure:
python
Key Enhancements:
Security: API token is loaded from an environment variable.
Logging: Enhanced log formatting for better readability.
Error Handling: Implemented retries with delays for sending messages.
Code Clarity: Simplified response handling.
Rate Limiting: Added handling for Telegram's rate limits.
6. Deployment Considerations
Hosting: Ensure that the environment where you deploy this bot is secure and reliable.
Monitoring: Monitor the bot's performance and logs to detect and respond to issues promptly.
Scalability: If expecting high traffic, design the bot to scale accordingly, possibly by handling updates concurrently.
7. Summary
Your script is a solid foundation for a Telegram bot that leverages a Gradio-hosted machine learning model. By addressing security concerns, enhancing error handling, and optimizing the code structure, you can create a more robust and reliable bot. Additionally, considering the use of dedicated libraries and deployment best practices will further improve the bot’s maintainability and performance.
If you have specific issues or questions about certain parts of the code, feel free to ask!