Как передать переменную чтобы выводилось имя, а не сам текст Telegram Bot Aiogram

Рейтинг: 0Ответов: 1Опубликовано: 29.01.2023

Есть телеграм бот. Я начал его переводить на три языка и создал новый файл со списком сообщений. Сообщение будто-бы выводится без f-строки. Как сделать чтобы выводилось нормально:

  • 👋 Hello Ivan Ivanov. 🎉 Welcome to our bot 🎉

А не как с переменной:

  • 👋 Hello {message.from_user.first_name} {message.from_user.last_name}. 🎉 Welcome to our bot 🎉

Если дописать f к строке в списке сообщений:

'hello_with_all_name_en': f'👋 Hello <b><u>{message.from_user.first_name} {message.from_user.last_name}</u></b>. 🎉 Welcome to our bot 🎉'

То выводится ошибка:NameError: name 'message' is not defined, так что, думаю это не вариант

Вот строчка кода:

await bot.send_message(message.from_user.id, locales.hello_user[f'hello_with_all_name_{BotDB.user_language(message.from_user.id)}'], parse_mode='html', reply_markup=kb.markup_start)

А вот список сообщений с файла locales.py:

hello_user = {
   'hello_with_all_name_uk': '👋 Привіт, <b><u>{message.from_user.first_name} {message.from_user.last_name}</u></b>. 🎉 Вітаємо у нашому боті 🎉',
   'hello_with_all_name_ru': '👋 Привет, <b><u>{message.from_user.first_name} {message.from_user.last_name}</u></b>. 🎉 Поздравляем в нашем сапоге 🎉',
   'hello_with_all_name_en': '👋 Hello <b><u>{message.from_user.first_name} {message.from_user.last_name}</u></b>. 🎉 Welcome to our bot 🎉'
}

Ответы

▲ 1Принят

Вы можете попробывать реализовать это в формате функции:

def hello(message):
    hello_user = {
       'hello_with_all_name_uk': '👋 Привіт, <b><u>{message.from_user.first_name} {message.from_user.last_name}</u></b>. 🎉 Вітаємо у нашому боті 🎉',
       'hello_with_all_name_ru': '👋 Привет, <b><u>{message.from_user.first_name} {message.from_user.last_name}</u></b>. 🎉 Поздравляем в нашем сапоге 🎉',
       'hello_with_all_name_en': '👋 Hello <b><u>{message.from_user.first_name} {message.from_user.last_name}</u></b>. 🎉 Welcome to our bot 🎉'
    }
    
    return hello_user["hello_with_all_name_uk"]

В эту функцию вы просто передаёте само сообщение в обрабработчике при отправке. Вот пример:

@dp.message_handler(commands=['start'])
async def send_welcome(message: types.Message):
    await message.reply(hello(message))

P.S. - Не забудьте изменить данные в [] в return в функции hello, на свои с БД!!!

И также не большая правочка насчёт Вашего словаря, правильние украинский язык назвать hello_with_all_name_ua, потомучто uk - это United Kingdom(Великобритания) ;)

Вы можеет попробывать использывать .format для выполнения Вашей задачи. Пример использования:

@dp.message_handler(commands=['start'])
async def send_welcome(message: types.Message):
    hello_user = {
       'hello_with_all_name_uk': '👋 Привіт, <b><u>{} {}</u></b>. 🎉 Вітаємо у нашому боті 🎉',
       'hello_with_all_name_ru': '👋 Привет, <b><u>{} {}</u></b>. 🎉 Поздравляем в нашем сапоге 🎉',
       'hello_with_all_name_en': '👋 Hello <b><u>{} {}</u></b>. 🎉 Welcome to our bot 🎉'
    }
    await bot.send_message(message.from_user.id, hello_user["hellow_with_all_name_uk"].format(message.from_user.first_name, message.from_user.last_name))

Если этот пример Вам больше по душе и будет коректно работать в Вашей ситуации, то не забудьте изменить словарь hello_user на поданый в этом примере и использовать для дальнейшей локализации в подобном формате!