Fix the previous and next song functionality in the Discord bot.py script

I’m a fairly new developer and have always wanted to make a discord bot. So the problem is that in the next function it plays the last song from the queue not the next one which I don’t want, next is that the bot has to (remember) the next and previous song until it disconnects here is my code
ps : Thanks to those interested in helping.

queues = {}  # Song queues
repeat_mode = {}  # Repeat the song
disconnect_timers = {}  # Disconnect timers
history = {}  # Playback history
current_embeds = {}  # Embeds for current music playing
current_songs = {}  # Current songs for each guild 

# Function to play the previous song in the queue
async def previous_callback(interaction: discord.Interaction):
    await interaction.response.defer()
    guild_id = interaction.guild.id
    voice_client = interaction.guild.voice_client

    if guild_id in history and history[guild_id]:
        previous_song = history[guild_id].pop()  # Get the last song from history
        if guild_id in current_songs:
            queues[guild_id].insert(0, current_songs[guild_id])  # Re-add the current song to the front of the queue
        current_songs[guild_id] = previous_song  # Set the previous song as the current song
        await play_next(interaction, previous_song)  # Play the previous song
        await interaction.followup.send("Playing the previous song.", ephemeral=True)

    else:
        await interaction.followup.send("No previous song in the history.", ephemeral=True)



# Callback function to play the next song in the queue
async def next_callback(interaction: discord.Interaction):
    await interaction.response.defer()
    guild_id = interaction.guild.id
    voice_client = interaction.guild.voice_client

    if guild_id in queues and queues[guild_id]:
        if guild_id in current_songs:
            history[guild_id].append(current_songs[guild_id])  # Add the current song to the history
        next_song = queues[guild_id].pop(0)  # Get the next song from the queue
        current_songs[guild_id] = next_song  # Set the next song as the current song
        await play_next(interaction, next_song)  # Play the next song
        await interaction.followup.send("Playing the next song.", ephemeral=True)
    else:
        await interaction.followup.send("No next song in the queue.", ephemeral=True)





# Function to play the next song in the queue
async def play_next(interaction, is_repeat=True):
    guild_id = interaction.guild.id
    voice_client = interaction.guild.voice_client

    if guild_id not in queues or not queues[guild_id]:
        if not repeat_mode.get(guild_id, False) and not disconnect_timers.get(guild_id):
            disconnect_timers[guild_id] = asyncio.create_task(disconnect_after_delay(interaction, 7 * 60))
        return

    if repeat_mode.get(guild_id, False):
        next_song = queues[guild_id][0]
    else:
        next_song = queues[guild_id].pop(0)

    if not next_song:
        if not repeat_mode.get(guild_id, False) and not disconnect_timers.get(guild_id):
            disconnect_timers[guild_id] = asyncio.create_task(disconnect_after_delay(interaction, 7 * 60))
        return
    
    if guild_id not in history:
        history[guild_id] = []
    history[guild_id].append(next_song)


    try:
        player = await YTDLSource.from_source(next_song['data'], stream=True)
    except Exception as e:
        print(f"Error creating player for next song: {e}")
        return

    player.requester = next_song['requester']

    def after_playing(e):
        coro = play_next(interaction, False)
        fut = asyncio.run_coroutine_threadsafe(coro, bot.loop)
        try:
            fut.result()
        except Exception as e:
            print(f"Error after playing: {e}")

    if voice_client.is_connected():  # Ensure the bot is connected before playing the next song
        if voice_client.is_playing():
            voice_client.stop()
        voice_client.play(player, after=after_playing)

    if guild_id in disconnect_timers and disconnect_timers[guild_id] is not None:
        disconnect_timers[guild_id].cancel()
        disconnect_timers[guild_id] = None

    embed = await create_embed(player, next_song['requester'])

    view = discord.ui.View(timeout=None)
    view.add_item(resume_button)
    view.add_item(stop_button)
    view.add_item(previous_button)
    view.add_item(next_button)
    view.add_item(RepeatButton())

    try:
        if guild_id in current_embeds:
            message = await interaction.channel.fetch_message(current_embeds[guild_id])
            await message.edit(embed=embed, view=view)
        else:
            message = await interaction.followup.send(embed=embed, view=view)
            current_embeds[guild_id] = message.id
    except discord.NotFound:
        # Handle case where the message is not found (possibly deleted)
        pass
    except Exception as e:
        print(f"Error updating embed message: {e}")`````

I want to have an optimization code as much as I can

New contributor

Zent is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật