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

discord.py无消息上下文时如何调用Bot命令?

解决方法

因为你的play命令不需要依赖上下文,最直接的方式是直接调用命令的核心逻辑,而非通过上下文invoke触发。具体可以按以下两种方式处理:

  • 重构代码(推荐):把play命令里的实际执行逻辑抽成独立的异步函数,让命令和监听器都调用这个函数,代码更清晰易维护:

    # 抽离核心播放逻辑
    async def play_music(arg):
        # 原来play命令里的业务代码,比如连接语音频道、加载音频、播放等
        pass
    
    # 原play命令调用抽离后的函数
    @bot.command()
    async def play(ctx, arg):
        await play_music(arg)
    
    # 语音频道加入事件监听器
    @bot.event
    async def on_voice_state_update(member, before, after):
        # 判断用户是否加入目标频道
        target_channel_id = 1234567890  # 替换成你的目标频道ID
        if after.channel and after.channel.id == target_channel_id:
            await play_music("要传入的参数")
    
  • 直接调用命令函数:如果不想重构代码,因为命令不依赖上下文,直接忽略ctx参数调用即可:

    @bot.event
    async def on_voice_state_update(member, before, after):
        target_channel_id = 1234567890
        if after.channel and after.channel.id == target_channel_id:
            await play(None, "要传入的参数")
    

如果后续你的命令需要依赖上下文,再考虑手动构造Context对象,但目前这种场景完全没必要。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:54:26