Search code examples
pythondiscordnextcord

How call a function in a callback function with nextcord python


@bot.slash_command(guild_ids=[1061756784567656448])
async def oui(ctx):
    button = Button(label="A + 1", style=ButtonStyle.blurple)
    myview = View(timeout=180)
    myview.add_item(button)
    
    
    async def aurevoir(ctx):
        await ctx.send_message("aurevoir")
        
    
    async def bonjour(interaction: discord.Interaction):
        await interaction.response.send_message("bonjour")
        await aurevoir(ctx)
        
    button = Button(label="A + 1", style=ButtonStyle.blurple)
    myview = View(timeout=180)
    myview.add_item(button)
        
    
    button.callback = bonjour
    await ctx.send(f"hello",view= myview)

The function "aurevoir" never sends the message, and I got a lot of errors like 'Context' object has no attribute 'send_message'. I don't know how to fix it.


Solution

  • The issue is that you were passing the ctx object through - it'd be better to use the interaction object that bonjour gets when you press the button and using the followup property on the interaction to send the message.

    async def oui(ctx: discord.ApplicationContext):
        await ctx.defer()
        button = Button(label="A + 1", style=ButtonStyle.blurple)
        myview = View(timeout=180)
        myview.add_item(button)
        
        async def aurevoir(interaction: discord.Interaction):
            await interaction.followup.send("aurevoir")
            
        async def bonjour(interaction: discord.Interaction):
            await interaction.response.send_message("bonjour")
            await aurevoir(interaction)
            
        button = Button(label="A + 1", style=ButtonStyle.blurple)
        myview = View(timeout=180)
        myview.add_item(button)
            
        button.callback = bonjour
        await ctx.followup.send("hello", view=myview)
    

    I also added a ctx.defer and a ctx.followup.send.