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

Python Twitch机器人仅发送首条消息问题求助

Twitch机器人仅发送第一条消息的问题排查与修复

问题描述

需要Python脚本将所有命令以随机顺序发送至Twitch聊天窗口,指定时间段后无限循环运行。但实际运行时,命令行日志显示所有消息发送成功,Twitch聊天却仅收到第一条消息。本人非程序员,已花一整天研究相关内容,可理解专业技术解答。

复现代码

#!/usr/bin/env python

from time import sleep
from random import randint, shuffle
from sys import argv
from twitchio.ext import commands

import logging
logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO)

class Bot(commands.Bot):

    def __init__(self):
        super().__init__(
                        token=argv[1],
                        prefix='',
                        initial_channels=['#channel_name']
                )

    async def event_ready(self):
        lst = ['command_1', 'command_2', 'command_3']

        while True:
            shuffle(lst)
            for x in lst:
                logging.info(f'{self.nick} is sending: {x}')
                await bot.connected_channels[0].send(x)
                sleep(randint(210,270))
            logging.info('Sent all msgs, sleeping...')
            sleep(randint(270,300))
            logging.info(f'Slept!\n')

bot = Bot()
bot.run()

现象说明

  • 命令行日志显示三条消息均已发送
  • Twitch聊天窗口仅收到第一条消息

问题原因与修复

问题核心在于使用了同步的sleep()函数:TwitchIO基于异步IO(asyncio)框架,同步sleep()会直接阻塞整个事件循环,导致后续的消息发送请求无法被框架正确调度执行。

修复方案是将所有同步睡眠替换为异步睡眠,具体步骤:

  1. 导入asyncio模块
  2. 将所有sleep(randint(a,b))替换为await asyncio.sleep(randint(a,b))
  3. 类方法中建议使用self.connected_channels[0]替代全局bot变量,避免潜在的引用问题

修复后的完整代码:

#!/usr/bin/env python

import asyncio
from random import randint, shuffle
from sys import argv
from twitchio.ext import commands

import logging
logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO)

class Bot(commands.Bot):

    def __init__(self):
        super().__init__(
                        token=argv[1],
                        prefix='',
                        initial_channels=['#channel_name']
                )

    async def event_ready(self):
        lst = ['command_1', 'command_2', 'command_3']

        while True:
            shuffle(lst)
            for x in lst:
                logging.info(f'{self.nick} is sending: {x}')
                await self.connected_channels[0].send(x)
                await asyncio.sleep(randint(210,270))
            logging.info('Sent all msgs, sleeping...')
            await asyncio.sleep(randint(270,300))
            logging.info(f'Slept!\n')

bot = Bot()
bot.run()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:43:28