aiogram.utils.exceptions.MessageTextIsEmpty: Message text is empty

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

Всем привет! Реализую чат-бота для техподдержки с помощью spaCy и aiogram.

Бот работать должен следующим образом:

1. Пользователь пишет свой вопрос

2. Бот по БД, состоящей из вопросов и ответов, ищет наиболее подходящий ответ

3. Бот отправляет пользователю ответ и спрашивает, удовлетворяет ли ответ пользователя.

4. Пользователь, с помощью кнопок отвечает "Да/Нет"

5. Если да, то бот прощается.

6. Если нет, то бот пересылает сообщение в канал с операторами, где операторы в комментариях могут общаться с пользователями.

7. Если общение завершено и пользователь узнал всё, что ему было нужно, то он может с помощью кнопки завершить диалог.

8. Бот должен запомнить вопрос и ответ на вопрос, записав его в БД.

У меня почему-то вылазит ошибка:

aiogram.utils.exceptions.MessageTextIsEmpty: Message text is empty

Код получился такой:

bot = Bot(token='TOKEN')
dp = Dispatcher(bot)


nlp = spacy.load('ru_core_news_lg')


conn = sqlite3.connect('database.db')
db = conn.cursor()



@dp.message_handler(commands=['start'])
async def start_command(message: types.Message):
    await message.reply('Привет! Я готов отвечать на вопросы.')



def find_answer(question):
    question_doc = nlp(question)

    
    best_match = None
    best_score = 0.0
    for row in db:
        answer_doc = nlp(row['answer'])
        score = question_doc.similarity(answer_doc)
        if score > best_score:
            best_match = row['answer']
            best_score = score

    return best_match


async def send_answer(chat_id, answer):
    keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
    keyboard.add(types.KeyboardButton('Да'), types.KeyboardButton('Нет'))

    await bot.send_message(chat_id, answer, reply_markup=keyboard)



@dp.channel_post_handler(content_types=[types.ContentType.TEXT])
async def handle_operator_reply(message: types.Message):
    
    if message.reply_to_message:
        user_question = message.reply_to_message.text  
        operator_reply = message.text  
        user_id = message.reply_to_message.from_user.id  

        
        await bot.send_message(user_id, operator_reply)


async def send_to_operators(question):
    channel_id = 'ID'  
    await bot.send_message(channel_id, f"Новый вопрос от пользователя:\n\n{question}")



@dp.message_handler()
async def handle_message(message: types.Message):
    question = message.text

    
    doc = nlp(question)
    processed_question = ' '.join([token.lemma_ for token in doc])

    
    answer = find_answer(processed_question)

    
    await send_answer(message.chat.id, answer)

   
    await bot.send_message(message.chat.id, "Удовлетворяет ли ответ вас?")


@dp.message_handler(content_types=types.ContentType.TEXT)
async def handle_feedback(message: types.Message):
    if message.text.lower() == 'да':
        await bot.send_message(message.chat.id, "Спасибо! Всего доброго.")
    elif message.text.lower() == 'нет':
        # Отправляем вопрос операторам
        await send_to_operators(message.text)
        await bot.send_message(message.chat.id, "Ваш вопрос передан операторам. Пожалуйста, ожидайте ответа.")
    elif message.text.lower() == 'завершить диалог':
        
        save_to_database(message.text, message.chat.id)

        await bot.send_message(message.chat.id, "Диалог завершен. Если у вас возникнут еще вопросы, не стесняйтесь обращаться.")
    else:
        await bot.send_message(message.chat.id, "Пожалуйста, используйте кнопки для ответа.")


def save_to_database(question, answer):
    db.execute("INSERT INTO question_answer (question, answer) VALUES (?, ?)", (question, answer))
    conn.commit()


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    asyncio.run(dp.start_polling())

Помогите, не совсем понимаю что не так.

Ответы

Ответов пока нет.