You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nextcord Python:回调函数内调用函数报错,无法发送消息

问题修复方案

核心错误原因

  1. API方法误用:discord.py的Context对象没有send_message方法,发送消息的正确方法是ctx.send()。
  2. 变量名冲突:内部定义的aurevoir函数参数名ctx和外部命令的上下文ctx重名,导致调用时变量被覆盖,无法正确访问命令上下文。
  3. 冗余代码:原代码重复创建了按钮和视图,完全没必要,只会增加冗余。

修正后的完整代码

@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)
    
    # 直接使用外部的命令上下文,无需重复定义ctx参数
    async def aurevoir():
        await ctx.send("aurevoir")
        
    async def bonjour(interaction: discord.Interaction):
        await interaction.response.send_message("bonjour")
        # 调用内部函数无需传参,直接使用外部ctx
        await aurevoir()
        
    button.callback = bonjour
    await ctx.send(f"hello", view=myview)

可选优化:基于交互上下文发送后续消息

如果希望在按钮交互的上下文里发送后续消息(而不是命令的初始上下文),可以改用交互的followup.send方法,适合需要在同一交互会话中发送多条消息的场景:

@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(interaction):
        # 交互响应后发送后续消息需用followup.send
        await interaction.followup.send("aurevoir")
        
    async def bonjour(interaction: discord.Interaction):
        await interaction.response.send_message("bonjour")
        # 传递交互对象给aurevoir
        await aurevoir(interaction)
        
    button.callback = bonjour
    await ctx.send(f"hello", view=myview)

内容的提问来源于stack exchange,提问作者Natounet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 02:10:51