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

Python Twitchio:同时使用命令与event_message失效问题求助

TwitchIO同时实现命令响应与消息录制的解决方案

问题根源

  • 继承commands.Bot时,若重写event_message但未调用父类的同名方法,会覆盖命令系统的消息处理逻辑,导致命令无法触发。
  • 直接创建Bot实例时,若未正确将消息传递给命令处理模块,或事件函数参数/注册方式错误,会出现消息无输出或命令失效的问题。

正确实现代码示例

方案1:继承commands.Bot(推荐)

这种方式最简洁,只需在自定义的event_message中先执行录制逻辑,再调用父类方法保留命令处理:

from twitchio.ext import commands

class TwitchBot(commands.Bot):
    def __init__(self):
        # 替换为你的令牌、命令前缀、目标频道
        super().__init__(
            token='YOUR_TWITCH_TOKEN',
            prefix='!',
            initial_channels=['YOUR_CHANNEL_NAME']
        )

    async def event_message(self, message):
        # 跳过机器人自身发送的消息,避免重复录制
        if message.echo:
            return
        
        # 消息录制逻辑:打印作者和内容,也可写入文件等
        print(f"[{message.author.name}]: {message.content}")
        
        # 必须调用父类方法,否则命令系统无法处理消息
        await super().event_message(message)

    # 示例命令:!ping
    @commands.command(name='ping')
    async def ping_cmd(self, ctx):
        await ctx.send('Pong!')

if __name__ == "__main__":
    bot = TwitchBot()
    bot.run()

方案2:直接创建Bot实例

若需直接使用Bot,需手动将消息传递给命令处理模块:

import twitchio
from twitchio.ext.commands import Client

# 初始化Bot
bot = twitchio.Bot(
    token='YOUR_TWITCH_TOKEN',
    initial_channels=['YOUR_CHANNEL_NAME']
)

# 初始化命令客户端,指定前缀
cmd_client = Client(bot=bot, prefix='!')

# 注册消息录制事件
@bot.event()
async def event_message(message):
    if message.echo:
        return
    
    print(f"[{message.author.name}]: {message.content}")
    # 将消息传递给命令客户端处理
    await cmd_client.handle_message(message)

# 示例命令:!ping
@cmd_client.command(name='ping')
async def ping_cmd(ctx):
    await ctx.send('Pong!')

if __name__ == "__main__":
    bot.run()

关键注意点

  • 无论哪种方式,都要跳过message.echo(机器人自身的消息),避免循环处理。
  • 使用commands.Bot时,父类的event_message是命令系统处理消息的入口,必须调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:39:28