Discord.py机器人无响应求助:启动仅输出READY,命令无反应无日志
Discord机器人无响应及日志空白问题排查
问题代码中的核心错误
模块拼写错误:
代码中bot = commmands.Bot(command_prefix="*")一行里,commmands多打了一个m,正确应为commands.Bot。这个错误会导致机器人实例未正确初始化,所有命令监听逻辑直接失效。文件写入未持久化:
- 打开日志文件时使用
mode="w",每次启动会清空原有日志内容,建议改为mode="a"实现追加写入。 log函数中调用f.write()后未执行f.flush()或f.close(),写入内容会停留在内存缓冲区,不会实时写入文件。
- 打开日志文件时使用
未定义token变量:
最后一行bot.run(token)中的token未赋值,虽然你提到机器人能启动,推测实际代码中有定义,但需确保token正确且机器人在Discord开发者平台的权限配置无误。
修正后的代码示例
import discord from discord.ext import commands # 修正拼写错误 bot = commands.Bot(command_prefix="*") # 改为追加模式打开,避免清空日志 f = open("log.txt", mode="a") def log(command_used, user): log_content = f"{user} -> {command_used}\n" print(f"{user} used the {command_used} command") f.write(log_content) # 刷新缓冲区,确保内容写入文件 f.flush() @bot.event async def on_ready(): print("READY") @bot.command() async def test(ctx): print("a") log("test", str(ctx.author)) # 替换为你的机器人token bot.run("YOUR_BOT_TOKEN_HERE")
额外建议
- 建议使用
with语句管理文件,自动处理关闭操作,避免资源泄漏:def log(command_used, user): log_content = f"{user} -> {command_used}\n" print(f"{user} used the {command_used} command") with open("log.txt", mode="a") as f: f.write(log_content) - 若使用Discord.py v2.x版本,需确保在Discord开发者平台中开启
Message Content Intent权限,否则机器人无法接收命令内容。
内容的提问来源于stack exchange,提问作者univers
相关产品推荐
相关产品推荐

