Как оптимизировать и переиспользовать код на Python?
Я только начала ботов писать. можно ли как-то повторяющиеся кусочки кода записать в отдельный файл? просто из-за них код выйдет на более 3000 строк
import telebot
from telebot import types
bot = telebot.TeleBot('....')
@bot.message_handler(commands=['start'])
def start(message):
bot.send_message(message.chat.id, 'Введите /train, чтобы начать тренироваться \nВведите /start для перезапуска')
@bot.message_handler(commands=['train'])
def train(message):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
word1 = types.KeyboardButton('аэропОрты')
word2 = types.KeyboardButton('аэропортЫ')
markup.add(word1, word2)
bot.send_message(message.chat.id, 'Выберите слово с правильным ударением:', reply_markup=markup)
@bot.message_handler(content_types=['text'])
def text(message):
if message.chat.type == 'private':
# начинаем отслеживать 1 вопрос
if message.text == 'аэропОрты':
bot.send_message(message.chat.id, 'Верно ✅')
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
word1 = types.KeyboardButton('бАнты')
word2 = types.KeyboardButton('бантЫ')
markup.add(word1, word2)
bot.send_message(message.chat.id, 'Выберите слово с правильным ударением:', reply_markup=markup)
elif message.text == 'аэропортЫ':
a = telebot.types.ReplyKeyboardRemove()
bot.send_message(message.chat.id,"Неверно ❌ \nПравильный ответ: аэропОрты \nНажмите /train, чтобы начать заново.", reply_markup=a)
Источник: Stack Overflow на русском