@The_King_Midas

Телеграм-бот не обрабатывает сообщения, что не так (pytelegrambotapi)?

Собственно код:
spoiler
import telebot
from telebot import types
import sqlite3
import urllib
import os.path
token = 'ТОКЕН'
bot = telebot.TeleBot(token)
@bot.message_handler(commands=["start"])
def start (message):
    user_name = message.from_user.first_name
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    btn1 = types.KeyboardButton('Добавить купюру')
    btn2 = types.KeyboardButton('Поиск купюры')
    btn3 = types.KeyboardButton('Мой профиль')
    btn4 = types.KeyboardButton('О проекте')
    markup.add(btn1, btn2, btn3, btn4)
    bot.send_message(message.chat.id,'Привет! '+ user_name +'!', reply_markup=markup)	
@bot.message_handler(content_types=['text'])
def menu (message):
    user_name = message.from_user.first_name
    user_id = message.from_user.id
    flag = True
    if message.text == 'Добавить купюру' :  
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        btn1 = types.KeyboardButton('↪️Меню↪️')
        markup.add(btn1)
        bot.send_message(message.chat.id,'Отправь серийный номер купюры', reply_markup=markup)
        @bot.message_handler(content_types=['text'])
        def handle_docs_photo(message):
            bill_num = message.text.lower()
            check_file = os.path.exists('C:\\Users\\User\\Desktop\\' + bill_num + '.jpg')
            if check_file == True:
                markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
                btn1 = types.KeyboardButton('Да хорошо!', request_location=True)
                btn2 = types.KeyboardButton('↪️Меню↪️')
                markup.add(btn1, btn2)
                bot.send_message(message.chat.id,'Эту купюру уже загрузил кто то другой, отправь геолокацию для построения маршрута этой купюры', reply_markup=markup)
                @bot.message_handler(content_types=['text'])
                def geo (message):
                    if message.text == 'Да хорошо!':
                        bot.send_message(message.chat.id,'Спасибо! Геолокация сохранена!', reply_markup=markup)
            elif check_file == False:
                if len(bill_num) == 9 or len(bill_num) == 11:
                    chat_id = message.chat.id
                    file_info = bot.get_file(message.document.file_id)
                    downloaded_file = bot.download_file(file_info.file_path)
                    src = 'C:\\Users\\User\\Desktop\\' + bill_num.lower() + '.jpg'
                    with open(src, 'wb') as new_file:
                        new_file.write(downloaded_file)
                    bot.send_message(message.chat.id,'Загрузи фото купюры как документ (без сжатия)')
                    @bot.message_handler(content_types=['document', 'photo'] )
                    def photo (message):
                        if message.content_type == 'photo':
                            bot.send_message(message.chat.id,('Загрузи фото купюры без зжатия во избежание потери качества'))
                        elif message.content_type == 'document':
                            chat_id = message.chat.id
                            file_info = bot.get_file(message.document.file_id)
                            downloaded_file = bot.download_file(file_info.file_path)
                            src = 'C:\\Users\\User\\Desktop\\' + bill_num.lower() + '.jpg'
                            with open(src, 'wb') as new_file:
                                new_file.write(downloaded_file)         
                else:
                    bot.reply_to(message,'Что то не так с серийным номером попробуй ещё раз')    

    if message.text == 'Поиск купюры' :
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        btn1 = types.KeyboardButton('↪️Меню↪️')
        markup.add(btn1)
        bot.send_message(message.chat.id,'Пришли номер купюры которую хочешь найти:', reply_markup=markup)
        @bot.message_handler(content_types=['text'])
        def find (message):
            num = message.text.lower()
            try:
                if len(num) == 9 or len(num) == 11:
                    check_file = os.path.exists('C:\\Users\\User\\Desktop\\' + num + '.jpg')
                    if check_file == True:
                        bot.send_photo(message.chat.id, open('C:\\Users\\User\\Desktop\\' + num + '.jpg', 'rb', num))
                    elif check_file == False:
                        bot.send_message(message.chat.id,'Такой купюры не найдено, добавь её нажав соответствующею кнопку')
                        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
                        btn1 = types.KeyboardButton('Добавить купюру')
                        btn2 = types.KeyboardButton('Поиск купюры')
                        btn3 = types.KeyboardButton('Мой профиль')
                        btn4 = types.KeyboardButton('О проекте')
                        markup.add(btn1, btn2, btn3, btn4)
                        bot.send_message(message.chat.id,'Такой купюры не найдено, добавь её нажав соответствующею кнопку', reply_markup=markup)
                else:
                    bot.send_message(message.chat.id,('Что то не так с серийным номером попробуй ещё раз'))	
            except:
                bot.send_message(message.chat.id,('Что то не так с серийным номером попробуй ещё раз'))
    if message.text == 'Мой профиль' :
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        btn1 = types.KeyboardButton('↪️Меню↪️')
        markup.add(btn1)
        bot.send_message(message.chat.id," *Профиль*\n \n1️⃣Имя: " + user_name + "\n \n2️⃣ID: " + str(user_id) + "\n \n3️⃣Добалено купюр: 0\n \n4️⃣Редактировано купюр: 0", parse_mode="markdown", reply_markup=markup)
    if message.text == 'О проекте' :
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        btn1 = types.KeyboardButton('↪️Меню↪️')
        markup.add(btn1)
        markup = types.InlineKeyboardMarkup()
        button1 = types.InlineKeyboardButton("GitHab", url='https://github.com/Midasik')
        markup.add(button1)
        bot.send_message(message.chat.id,'*Collektor of Money*\n\n*Версия: *Pre-Alpha\n\n*Автор: *The King Midas', parse_mode="markdown", reply_markup=markup)
    if message.text == '↪️Меню↪️' :
            markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
            btn1 = types.KeyboardButton('Добавить купюру')
            btn2 = types.KeyboardButton('Поиск купюры')
            btn3 = types.KeyboardButton('Мой профиль')
            btn4 = types.KeyboardButton('О проекте')
            markup.add(btn1, btn2, btn3, btn4)
            bot.send_message(message.chat.id,('*Меню*'), parse_mode="markdown", reply_markup=markup)	
bot.polling(none_stop=True)



Суть в том что бот собирает присланные купюры и переименовывает файл так чтобы потом можно было найти её по номеру, в бедующем добавлю ещё сохранение геолокации. После нажатия на кнопки 'Добавить купюру' и 'Поиск купюры' не реагирует на дальнейшие сообщения. Пробовал вариант не с @bot.message_handler(content_types=['text']), а с bot.register_next_step_handler(), но не помогло
  • Вопрос задан
  • 119 просмотров
Решения вопроса 1
shurshur
@shurshur
Сисадмин, просто сисадмин...
Так, как написано сейчас, работать не будет. Потому что регистрируется несколько обработчиков с одинаковым условием content_types=text, и применяется только первый. Надо как раз использовать bot.register_next_step_handler (или городить свой велосипед на замену). Смысл обработчиков именно в том, что они получают сообщение, обрабатывают его и завершаются. Ждать следующего сообщения не нужно.

И зачем вообще внутри одной функции описывать другую? Так иногда делают, но в данном случае это не имеет смысла.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

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

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