Hello everyone, can someone tell me what my joke is in the code, in short, I have a bot. which should answer users' questions by question category, but there is a joke, for some reason it gives a crooked translation (used the google trans library), what's the joke? I scored the gpt chat, he just put comments on me and said everything correctly, and I don't understand why it works that way, but here's an example of a piece of message where the translation is stupid and crooked. I don't understand what the joke is, please tell me. If anything, I'll thank you with a coin for the new year
Where does he write the "ВОПРЕС" and "OTVET" from???
RU:
Всем привет, может ли кто-то подсказать, в чем у меня прикол в коде, короче, у меня есть бот. который долежн отвечать на вопросы юзеров по категориям вопросов, но есть прикол, он почему-то выдает кривой перевод (использовал библиотеку google trans), в чем прикол? Забивал чату гпт, он мне только комментарии расставил и сказал все корректно и я хз почему тогда это так работает, но вот пример куска сообщения, где тупой и кривой перевод. не понимаю в чем прикол, подскажите пожалуйста. Если что отблагодарю монеткой на новый год
ОТкуда он пишет Вопрес Otwet???
Код: Выделить всё
# -----------------------------------------------------------------------------------------
# 3) Detect language and translating:
# -----------------------------------------------------------------------------------------
translator = Translator()
def is_cyrillic(text: str) -> bool:
cyr_count = sum(1 for ch in text if 'а' 1:
nav_buttons.append(types.InlineKeyboardButton(text="⬅️ Previous", callback_data=f"chats_page_{page-1}"))
if page < total_pages:
nav_buttons.append(types.InlineKeyboardButton(text="Next ➡️", callback_data=f"chats_page_{page+1}"))
if nav_buttons:
markup.row(*nav_buttons)
# Добавляем кнопку выхода в общий список диалогов
markup.row(
types.InlineKeyboardButton(text="🔙 Back to Main Menu", callback_data="back_to_main_menu")
)
# Формируем текст сообщения
text = f"📄 User Chats List (Page {page} of {total_pages}):"
bot.send_message(user_id, text, reply_markup=markup)
# Обработка нажатий кнопок для /chats, FAQ и GPT
@bot.callback_query_handler(func=lambda call: True)
def handle_callback_queries(call):
if call.data.startswith('chats_page_'):
# Обработка пагинации в /chats
try:
page_num = int(call.data.split('_')[-1])
except ValueError:
logging.error(f"Invalid page number in callback data: {call.data}")
bot.answer_callback_query(call.id, "❌ Invalid page number.")
return
business_connections = load_business_connections()
users = []
for bc_id, data in business_connections.items():
username = data.get('username', 'Unknown')
user_chat_id = data.get('user_chat_id')
if username != 'Unknown':
business_connection_id = f"user_{user_chat_id}"
chat_history = get_chat_history(user_chat_id, business_connection_id)
if chat_history:
users.append({'id': user_chat_id, 'username': username})
if not users:
bot.answer_callback_query(call.id, "📄 No available chats.")
return
# Сортируем пользователей по username
users = sorted(users, key=lambda x: x['username'])
per_page = 10
total_pages = (len(users) + per_page - 1) // per_page
current_users = []
if 1 1:
markup.row(
types.InlineKeyboardButton(text="Next ➡️", callback_data=f"chat_page_{user_id}_2")
)
# Добавляем кнопку возврата в главное меню
markup.row(
types.InlineKeyboardButton(text="🔙 Back to Main Menu", callback_data="back_to_main_menu")
)
# Формируем текст сообщения
text = f"💬 Chat with @{bc.get('username', 'Unknown')}\n\n{page_text}"
bot.send_message(call.message.chat.id, text, reply_markup=markup)
elif call.data.startswith('chat_page_'):
# Обработка пагинации внутри чата
parts = call.data.split('_')
if len(parts) != 4:
logging.error(f"Invalid callback data format for chat_page: {call.data}")
bot.answer_callback_query(call.id, "❌ Invalid data format.")
return
try:
user_id = int(parts[2])
page_num = int(parts[3])
except ValueError:
logging.error(f"Invalid user ID or page number in callback data: {call.data}")
bot.answer_callback_query(call.id, "❌ Invalid user ID or page number.")
return
business_connection_id = f"user_{user_id}"
bc = get_business_connection(business_connection_id)
if not bc:
bot.answer_callback_query(call.id, "❌ Chat history not found.")
return
chat_history = get_chat_history(user_id, business_connection_id)
if not chat_history:
# Нет истории диалога
bot.answer_callback_query(call.id, "❌ This user has no chat history.")
return
# Формирование сообщений
messages = []
for role, content in chat_history:
if role == 'assistant':
messages.append(f"🤖 Bot: {content}")
elif role == 'user':
username = bc.get('username', 'Unknown')
messages.append(f"👤 @{username}: {content}")
full_text = "\n".join(messages)
# Разделение на страницы
per_page_chars = 3500 # Установлено меньше максимума для безопасности
pages = split_text_into_pages(full_text, per_page_chars=per_page_chars)
total_pages = len(pages)
if page_num < 1 or page_num > len(pages):
bot.answer_callback_query(call.id, "❌ Invalid page number.")
return
page_text = pages[page_num - 1]
markup = types.InlineKeyboardMarkup()
nav_buttons = []
if page_num > 1:
nav_buttons.append(types.InlineKeyboardButton(text="⬅️ Previous", callback_data=f"chat_page_{user_id}_{page_num-1}"))
if page_num < len(pages):
nav_buttons.append(types.InlineKeyboardButton(text="Next ➡️", callback_data=f"chat_page_{user_id}_{page_num+1}"))
if nav_buttons:
markup.row(*nav_buttons)
# Добавляем кнопку возврата в главное меню
markup.row(
types.InlineKeyboardButton(text="🔙 Back to Main Menu", callback_data="back_to_main_menu")
)
# Формируем текст сообщения
text = f"💬 Chat with @{bc.get('username', 'Unknown')}\n\n{page_text}"
bot.edit_message_text(
text,
chat_id=call.message.chat.id,
message_id=call.message.message_id,
reply_markup=markup
)
elif call.data.startswith('faq_page_'):
# Обработка пагинации в FAQ сообщениях
try:
parts = call.data.split('_')
bc_id = parts[2]
page_num = int(parts[3])
except (IndexError, ValueError):
logging.error(f"Invalid callback data format for faq_page: {call.data}")
bot.answer_callback_query(call.id, "❌ Invalid data format.")
return
business_connection_id = bc_id
bc = get_business_connection(business_connection_id)
if not bc:
bot.answer_callback_query(call.id, "❌ FAQ not found.")
return
# Получение faq_pages
faq_pages = bc.get('faq_pages', [])
if not faq_pages:
bot.answer_callback_query(call.id, "❌ FAQ pages not found.")
return
if page_num < 1 or page_num > len(faq_pages):
bot.answer_callback_query(call.id, "❌ Invalid page number.")
return
page_text = faq_pages[page_num - 1]
# Создание новой разметки
markup = types.InlineKeyboardMarkup()
nav_buttons = []
if page_num > 1:
nav_buttons.append(types.InlineKeyboardButton(text="⬅️ Previous", callback_data=f"faq_page_{bc_id}_{page_num-1}"))
if page_num < len(faq_pages):
nav_buttons.append(types.InlineKeyboardButton(text="Next ➡️", callback_data=f"faq_page_{bc_id}_{page_num+1}"))
if nav_buttons:
markup.row(*nav_buttons)
# Добавляем кнопку возврата в главное меню
markup.row(
types.InlineKeyboardButton(text="🔙 Back to Main Menu", callback_data="back_to_main_menu")
)
# Формируем текст сообщения
text = f"📄 FAQ (Page {page_num} of {len(faq_pages)}):\n\n{page_text}"
bot.edit_message_text(
text,
chat_id=call.message.chat.id,
message_id=call.message.message_id,
reply_markup=markup
)
else:
# Необработанные данные callback
bot.answer_callback_query(call.id, "❌ Invalid action.")
return
# Команда /start
@bot.message_handler(commands=['start'])
def handle_start(message):
user_id = message.chat.id
username = message.from_user.username if message.from_user.username else "Unknown"
bc_id = f"user_{user_id}"
if message.content_type == 'text':
user_text = message.text.strip()
else:
user_text = ""
# Определяем язык на основе команды /start
user_lang = detect_user_language_robust(message.text)
logging.debug(f"[handle_start] user_lang={user_lang}")
update_or_create_business_connection(bc_id, user_chat_id=user_id, date=message.date, username=username, language=user_lang)
reset_failed_attempts(bc_id)
# Получаем приветственное сообщение на всех трёх языках
greeting_message = get_greeting_message_all_languages()
# Добавляем эмодзи в начало сообщения
greeting_message = f"👋 {greeting_message}"
bot.send_message(user_id, greeting_message)
# Обработка сообщений от пользователей
@bot.message_handler(content_types=['text', 'photo', 'video'])
def handle_user_message(message):
user_id = message.chat.id
username = message.from_user.username if message.from_user.username else "Unknown"
bc_id = f"user_{user_id}"
if message.content_type == 'text':
user_text = message.text.strip()
else:
user_text = f"User sent {message.content_type}"
# Определяем язык
user_lang = detect_user_language_robust(user_text)
logging.debug(f"[handle_user_message] user_lang={user_lang}")
# Обновляем информацию о пользователе, включая язык
update_or_create_business_connection(bc_id, user_chat_id=user_id, date=message.date, username=username, language=user_lang)
# Сохраняем сообщение пользователя
save_message(user_id, bc_id, 'user', user_text)
connection = get_business_connection(bc_id)
if not (connection and connection.get('is_enabled') and connection.get('can_reply')):
# Добавляем эмодзи перед сообщением
answer = "🤖 Sorry, I can't respond right now."
bot.send_message(user_id, answer)
return
if need_welcome(bc_id):
# Повторное приветствие (спустя 24 часа)
greet_text = get_greeting_message_all_languages()
# Добавляем эмодзи в начало сообщения
greet_text = f"👋 {greet_text}"
bot.send_message(user_id, greet_text)
attempts = get_failed_attempts(bc_id)
text_lower = user_text.lower()
# 1) Проверяем GPT ключевые слова
if user_wants_gpt(text_lower):
if attempts < 3:
block_txt = (
"You can only use GPT after 3 unsuccessful attempts at finding the ready answers.\n"
"Try rephrasing your question with a specific category first."
)
block_tr = google_translate_response(block_txt, user_lang)
support_msg = get_support_message(user_lang)
answer = f"🤖 {block_tr}\n\n{support_msg}"
save_message(user_id, bc_id, 'assistant', answer)
bot.send_message(user_id, answer)
return
else:
trig = get_gpt_trigger_phrase(text_lower)
if trig:
try:
actual_q = message.text.split(trig, 1)[1].strip()
except IndexError:
actual_q = ""
if not actual_q:
block_txt = (
"Please specify your question after the GPT keyword.\n"
"For example: `gpt: How to contact bot support?`"
)
block_tr = google_translate_response(block_txt, user_lang)
support_msg = get_support_message(user_lang)
answer = f"🤖 {block_tr}\n\n{support_msg}"
save_message(user_id, bc_id, 'assistant', answer)
bot.send_message(user_id, answer)
return
else:
actual_q = user_text
gpt_answer = get_gpt_response_simple(actual_q)
reset_failed_attempts(bc_id)
suffix = "If you haven't found the answer, manager @solomon_bog will contact you soon!"
full_ans = gpt_answer + "\n\n" + suffix
final_ans = google_translate_response(full_ans, user_lang)
support_msg = get_support_message(user_lang)
combined_ans = final_ans + "\n\n" + support_msg
# Разделяем сообщение на страницы
pages = split_text_into_pages(combined_ans, per_page_chars=3500)
total_pages = len(pages)
if total_pages == 1:
# Одно сообщение
answer = f"🤖 {pages[0]}"
save_message(user_id, bc_id, 'assistant', answer)
bot.send_message(user_id, answer)
else:
# Несколько отдельных сообщений без кнопок навигации
for page in pages:
answer = f"🤖 {page}"
save_message(user_id, bc_id, 'assistant', answer)
bot.send_message(user_id, answer)
return
# 2) Ищем категорию (FAQ)
cats = load_categories("categories.json")
found_cat, faq_list = find_category_fuzzy(user_text, cats, threshold=60)
if not found_cat:
increment_failed_attempts(bc_id)
attempts_new = get_failed_attempts(bc_id)
msg_no_cat = (
"I can't determine the category of your question. "
"Please specify, for example: 'How to set up a Facebook account?'."
)
if attempts_new >= 4:
msg_no_cat += (
"\n\nIt seems we can't find an answer. Now you can use GPT keywords like: "
"`gpt`, `chat gpt`, `open ai`, `find in gpt`, etc."
)
tr_msg = google_translate_response(msg_no_cat, user_lang)
support_msg = get_support_message(user_lang)
answer = f"🤖 {tr_msg}\n\n{support_msg}"
save_message(user_id, bc_id, 'assistant', answer)
bot.send_message(user_id, answer)
return
# Если категория найдена, сбрасываем счетчик
reset_failed_attempts(bc_id)
# Формируем список FAQ с локализованными метками
faq_text = build_faq_full_list(found_cat, faq_list, user_lang)
# Переводим на user_lang
translated_faq = google_translate_response(faq_text, user_lang)
# Разделяем на страницы
pages = split_text_into_pages(translated_faq, per_page_chars=3500)
total_pages = len(pages)
if total_pages == 1:
# Одно сообщение
answer = f"🤖 {pages[0]}"
save_message(user_id, bc_id, 'assistant', answer)
bot.send_message(user_id, answer)
else:
# Несколько отдельных сообщений без кнопок навигации
for page in pages:
answer = f"🤖 {page}"
save_message(user_id, bc_id, 'assistant', answer)
bot.send_message(user_id, answer)
# Функция для получения сообщения поддержки на нужном языке
def get_support_message(lang):
support_messages = {
'en': "For support, please contact our manager on Telegram: @solomon_bog.",
'ru': "Для связи с поддержкой (реальным менеджером) перейдите в телеграм: @solomon_bog.",
'zh': "要联系支持(真实的经理),请转到 Telegram:@solomon_bog。"
}
return support_messages.get(lang, support_messages['en'])
# -----------------------------------------------------------------------------------------
# 8) Точка входа
# -----------------------------------------------------------------------------------------
if __name__ == "__main__":
create_table()
logging.info("Deleting webhook (if exists) to enable long polling...")
bot.delete_webhook()
logging.info("Starting the bot...")
bot.infinity_polling()
Подробнее здесь: https://stackoverflow.com/questions/793 ... ate-on-oth
Мобильная версия