Stoat.py Bot 能运行但不上线、不响应命令怎么排查
数据小陈
最可能的原因是 ChaosBot.setup_hook() 在加载 ./gears 时抛出了异常,登录流程因此中断,但事件循环没有退出,所以程序看起来一直在运行,却不响应。你的文件结构里没有 gears 目录,listdir("./gears") 会直接抛 FileNotFoundError,而这个异常没有被内层 try 捕获。
先修 gears 加载
把加载逻辑改成先判断目录是否存在:
from os.path import isdir, listdir
async def setup_hook(self):
await super().setup_hook()
# ...
gear_dir = "./gears"
if not isdir(gear_dir):
print(gear_dir + " 不存在,跳过扩展加载")
else:
for filename in listdir(gear_dir):
if filename.endswith(".py"):
try:
if self.get_gear(filename[:-3]):
await self.reload_extension(f"gears.{filename[:-3]}")
else:
await self.load_extension(f"gears.{filename[:-3]}")
except Exception as e:
print(f"Gear Error: {e}")
改完后看启动日志。如果能打印 We have set up as ...,并且 bot 上线,就说明问题出在这里。
同时修正 __init__ 的参数传递
ChaosBot.__init__ 没有把 self_bot、owner_ids 等参数继续传给父类:
class ChaosBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(
command_prefix="/",
)
这样 self_bot=True 会被丢弃。self_bot=True 在示例注释里的意思是“只监听你自己”,如果你希望 bot 响应其他人,应去掉该参数;如果你确实只用自己账号测试,则要确认是用同一个账号发命令。更稳妥的写法是:
class ChaosBot(commands.Bot):
def __init__(self, *args, **kwargs):
kwargs.setdefault("command_prefix", "/")
super().__init__(*args, **kwargs)
排查顺序
- 看启动日志里有没有
We have set up as ...;没有就重点查setup_hook异常。 - 确认
.env里的STOAT_TOKEN是 bot token,不是用户 token;示例能跑通只说明 token 有效,不说明两种模式完全等价。 - 确认命令前缀:
ChaosBot里写的是"/",发命令时要用一致的前缀。 @bot.listen()的on_member_remove事件名在 Stoat.py 中不一定叫这个名字;事件不触发不会导致不上线,但会影响成员清理逻辑。atexit里直接bot.loop.stop()/close()在 loop 已关闭时可能报错,建议只做资源清理,不要强行停 loop。
注意事项
- 不要混用用户 token 和 bot token;
self_bot=True的行为依赖库和平台策略。 bot.run(token=bot_token)只调用一次,并确保它在所有初始化之后执行。- 如果
setup_hook里还有数据库连接、ClientSession创建等逻辑,也要一起检查是否抛异常。
备注:内容仅供参考。
