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

使用Nextcord开发Discord机器人时,关闭工单功能的await表达式触发TypeError错误

Nextcord开发Discord机器人时,关闭工单功能的await表达式触发TypeError错误

嘿,这个问题其实是个很常见的小疏忽!你看报错信息里说“object method can't be used in 'await' expression”,根源就在你调用flatten的方式上——你漏加了括号,把它当成了一个属性而不是异步方法来用。await只能作用于异步可等待对象(比如协程、任务),而.flatten只是引用了这个方法本身,不是执行它返回的协程,所以Python才会报错。

另外我还注意到你代码里有个拼写错误:fianl = final + msg里的fianl应该是final,这个小错误会导致你的transcript内容无法正确拼接,甚至触发变量未定义的错误,得一起改掉。

下面是修正后的完整代码,我标出来了关键修改点:

@nextcord.ui.button(
    label="Close Ticket", style=nextcord.ButtonStyle.red, custom_id="ticket_settings:red"
)
async def close_ticket(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
    # 关键修改1:给flatten加上括号,调用异步方法
    messages = await interaction.channel.history(limit=None, oldest_first=True).flatten()
    
    contents = [message.content for message in messages]
    final = ""
    for msg in contents:
        msg = msg + "\n"
        # 关键修改2:修正拼写错误 fianl → final
        final = final + msg
    
    # 额外小优化:可以用join替代循环拼接,更简洁高效
    # final = '\n'.join(contents) + '\n'
    
    with open('transcript.txt', 'w') as f:
        f.write(final)
    
    await interaction.response.send_message("Ticket is being closed.")
    await interaction.channel.delete()
    await interaction.user.send(
        f"Ticket closed in {interaction.channel.mention}. Here is the transcript.", 
        file=nextcord.File(r'transcript.txt')
    )
    os.remove("transcript.txt")

简单解释下:

  • 加上flatten()之后,这个方法会返回一个协程对象,await就可以正确处理它,获取到频道的消息列表了。
  • 修正拼写错误后,transcript的内容才能正常累加写入文件。
  • 另外我加了个可选的优化方案,用'\n'.join(contents)代替循环拼接字符串,Python里字符串拼接用join效率更高,代码也更简洁,你可以根据习惯选择用哪个。

备注:内容来源于stack exchange,提问作者maxxdev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 10:39:29