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()会直接阻塞整个事件循环,导致后续的消息发送请求无法被框架正确调度执行。
修复方案是将所有同步睡眠替换为异步睡眠,具体步骤:
- 导入
asyncio模块 - 将所有
sleep(randint(a,b))替换为await asyncio.sleep(randint(a,b)) - 类方法中建议使用
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
相关产品推荐
相关产品推荐

