python telebot. Бесконечно отправляются сообщения
Изучаю Python не так давно. Решил сделать небольшого бота, для себя. Хочу добавить функцию добавления текста на фото, но что-то не работает. При последнем шаге где нужно отправить текст бот начинает бесконечно слать "Это не текст. Введите ТЕКСТ". Вроде register_next_step_handler должно ждать ответа, а не сразу переходить или я чего-то не понимаю? Помогите исправить.
Вот код
from telebot import types
import telebot
import configure
from PIL import Image, ImageDraw, ImageFont
import random
bot = telebot.TeleBot(configure.telegram_bot["token"])
@bot.message_handler(commands = ["start"])
def start(message):
keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
keyboard.add(types.KeyboardButton("✅ Понял, Начать ?"))
msg = bot.send_message(message.chat.id, f"Вас приветствует бот по имени {configure.telegram_bot['name']} " \
"Жмите на все конопочки " \
"и прочие орудия пыток ",
reply_markup=keyboard
)
bot.register_next_step_handler(msg, menu)
def menu(message):
keyboard = types.ReplyKeyboardMarkup()
keyboard.add(
types.KeyboardButton("текст на картинку"),
types.KeyboardButton("нечего"),
types.KeyboardButton("Comming sonn"),
types.KeyboardButton("сдесь что-то будет"),
types.KeyboardButton("потом добавлю"),
types.KeyboardButton("пусто"),
)
msg = bot.send_message(message.chat.id, f"Вот вам орудя " \
"чем хотите воспользоватся? ",
reply_markup=keyboard
)
bot.register_next_step_handler(msg, executor)
def executor(message):
if (message.text == "текст на картинку"):
msg = bot.send_message(message.chat.id, "Пришлите картинку на которой хотите написать текст")
bot.register_next_step_handler(msg, text_on_image_part1)
else:
keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
keyboard.add(
types.KeyboardButton("Вернутся в меню")
)
msg = bot.send_message(message.chat.id, "Такой команды не существует", reply_markup=keyboard)
bot.register_next_step_handler(msg, menu)
def text_on_image_part1(message):
if (message.content_type == "photo"):
file_info = bot.get_file(message.photo[len(message.photo) - 1].file_id)
downloaded_file = bot.download_file(file_info.file_path)
src = 'files/' + file_info.file_path
with open(src, 'wb') as new_file:
new_file.write(downloaded_file)
msg = bot.send_message(message.chat.id, "Введите ваш текст")
photo = Image.open(src)
bot.register_next_step_handler(msg, text_on_image_part2(message, photo))
else:
msg = bot.send_message(message.chat.id, "ОТПРАВЬТЕ ОДНО ФОТО!!!")
bot.register_next_step_handler(msg, text_on_image_part1)
def text_on_image_part2(message, photo):
if message.content_type == "text":
draw_photo = ImageDraw.Draw(photo)
headline = ImageFont.truetype("arial.ttf", size=12 )
draw_photo.text((random.randint(0, 20),random.randint(0, 20)), message.text, headline)
bot.send_photo(message.chat.id, draw_photo)
else:
msg = bot.send_message(message.chat.id, "Это не текст. Введите ТЕКСТ")
bot.register_next_step_handler(msg, text_on_image_part2(message, photo))
bot.enable_save_next_step_handlers(delay=2)
bot.load_next_step_handlers()
bot.polling()
в файле configure.py рядом со скриптом записано
telegram_bot = {
"name" : "тут имя бота",
"token" : "тут токен"
}
Ответы (1 шт):
Автор решения: GrAnd
→ Ссылка
Так вы же сразу вызываете вторую функцию text_on_image_part2(message, photo) при задании обработчика. :
def text_on_image_part1(message):
if (message.content_type == "photo"):
...
bot.register_next_step_handler(msg, text_on_image_part2(message, photo))
И во второй функции тоже:
def text_on_image_part2(message, photo):
...
else:
bot.register_next_step_handler(msg, text_on_image_part2(message, photo))
Вот он и входит в рекурсию.
Возможно там надо что-то типа:
bot.register_next_step_handler(msg, lambda mesg: text_on_image_part2(mesg, photo))
(извините, в ботах не особо шарю)