@belugasinister

Как оптимизировать моего телеграм-бота, написанного на Python?

Я написал довольно простого бота, который предоставляет информацию или дополнительный выбор в зависимости от запроса пользователя. Он работает хорошо и выполняет свою работу, однако мне было интересно, как я могу оптимизировать свой код и лучше использовать телебота? В настоящее время основное действие происходит в callback query handler, и что-то мне подсказывает, что мне не хватает эффективности (например, когда я попытаюсь создать больше разветвлений выбора юзера). Ниже приведен код, упрощенный для демонстрационных целей:

import telebot
from telebot import types

token = bottoken

bot = telebot.TeleBot(token)

@bot.message_handler(commands=['start'])
def welcome(message):

	# here i give the main choice that is always visible to the user

	markup = types.ReplyKeyboardMarkup(resize_keyboard=False)
	item1 = types.KeyboardButton("Button1")
	item2 = types.KeyboardButton("Button2")

	markup.add(item1, item2)

	bot.send_message(message.chat.id, "Welcome message".format(message.from_user, bot.get_me()),
		parse_mode='html', reply_markup=markup)


@bot.message_handler(content_types=['text'])
def main_choice(message):

	# here i develop each of the main choices and redirect to the callback handler

	if message.text == 'Button1':

		# Forward to callback handler

			markup = types.InlineKeyboardMarkup()
			item1 = types.InlineKeyboardButton("Yes", callback_data = 'demo_yes')
			item2 = types.InlineKeyboardButton("No", callback_data = 'demo_no')

			markup.add(item1, item2)

			bot.send_message(message.chat.id, 'Some text', reply_markup=markup)


	elif message.text == 'Button2':

		# some logic

	else :
		bot.send_message(message.chat.id, 'Sorry, i dont understand. You can use /help to check how i work')


@bot.callback_query_handler(func=lambda call: True)
def tempo(call):

	# here a handle the queries launched both by main buttons and the inline keyboard 


	if call.data == "demo_yes":

		keyboard = types.InlineKeyboardMarkup()
		item1 = types.InlineKeyboardButton("Text1", callback_data = 'call1')
		item2 = types.InlineKeyboardButton("Text2", callback_data = 'call2')
		keyboard.add(item1,item2)

		bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard)

	elif call.data == "demo_no":

		kkeyboard = types.InlineKeyboardMarkup()
		item1 = types.InlineKeyboardButton("Text3", callback_data = 'call3')
		item2 = types.InlineKeyboardButton("Text4", callback_data = 'call4')
		keyboard.add(item1,item2)

		bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard)

	if call.data == "call1":

		keyboard = types.InlineKeyboardMarkup()
		item1 = types.InlineKeyboardButton("Text5", callback_data = 'another_call1')
		item2 = types.InlineKeyboardButton("Text6", callback_data = 'another_call2')
		keyboard.add(item1,item2)

		bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard)

	elif call.data == "call2":

		kkeyboard = types.InlineKeyboardMarkup()
		item1 = types.InlineKeyboardButton("Text7", callback_data = 'another_call3')
		item2 = types.InlineKeyboardButton("Text8", callback_data = 'another_call4')
		keyboard.add(item1,item2)

		bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard)
  • Вопрос задан
  • 881 просмотр
Пригласить эксперта
Ответы на вопрос 1
@Alexa2007
Ну на первый взгляд можно просто раскидать минимум на три файла:
1.py
import telebot
from telebot import types
token = bottoken
bot = telebot.TeleBot(token)
bot.polling()


2.py
#Все хендлеры

@bot.message_handler(commands=['start'])
def welcome(message):


2.py
#Все коллбеки без elif а нормально читаемые

@bot.callback_query_handler(func=lambda call: call.data == '7')
def seven(call):
    bot.send_message(call.message.chat.id,text = 'seven')

@bot.callback_query_handler(func=lambda call: call.data == '1')
def one(call):
    bot.send_message(call.message.chat.id,text = 'one')
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы