Can't solve a problem with the handler when writing a music tg bot

37 views Asked by At

I am writing a telebot bot that will be able to store songs from the user in the sqlite3 database and display information about the songs. Now the part with the addition of songs is ready. That is, the user can add a song. After that, all the information is added to the database. I've been stuck on the implementation of searching for a song by name for a while now.

Above is also code that calls process_song_name after entering a name. Next is a search in the database and the results of matches are displayed in buttons. Then the problems begin... When the button with the song is clicked, the callback_data, which is processed by the handler, must be referenced. And execute a function that returns everything about the song. But for some reason it does not work. I would be grateful if you could help me fix the error!

@bot.message_handler(func=lambda message: True)
def process_song_name(message):
    # Get the title
    search_name = message.text

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

    cursor.execute('SELECT * FROM songs WHERE title LIKE ?', ('%' + search_name + '%',))
    search_results = cursor.fetchall()

    conn.close()

    # Display results in buttons
    if not search_results:
        bot.send_message(message.chat.id, f"No songs found: '{search_name}'.")
    else:
        bot.send_message(message.chat.id, "Search results:")
        buttons = []  # List to store buttons
        for result in search_results:
            button_text = f"{result[3]} - {result[6]}"
            callback_data = f"song_info-{result[3]}-{result[1]}"
            markup = types.InlineKeyboardMarkup()
            markup.add(types.InlineKeyboardButton(text=button_text, callback_data=callback_data))
            buttons.append((f"Title: {result[3]}, Region: {result[6]}", markup))

        # Send all buttons together
        for text, markup in buttons:
            bot.send_message(message.chat.id, text, reply_markup=markup)


@bot.callback_query_handler(func=lambda call: call.data and call.data.startswith("song_info-"))
def handle_song_info_callback(call):
    print("Callback received:", call.data)
    song_id, song_name = call.data.split('-')[1:]

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

    cursor.execute('SELECT * FROM songs WHERE id = ?', (song_id,))
    song_info = cursor.fetchone()
    conn.close()

    if song_info:
        info_message = f"Title: {song_info[3]}\nRegion: {song_info[6]}\nAdded: {song_info[1]}\nLyrics: {song_info[5]}"
        bot.send_message(call.message.chat.id, info_message)
    else:
        bot.send_message(call.message.chat.id, "Error fetching data.")

I tried to monitor if the handler is executed via print. But seems it doesn't execute

0

There are 0 answers