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

Discord.py机器人无响应求助:启动仅输出READY,命令无反应无日志

Discord机器人无响应及日志空白问题排查

问题代码中的核心错误

  1. 模块拼写错误:
    代码中bot = commmands.Bot(command_prefix="*")一行里,commmands多打了一个m,正确应为commands.Bot。这个错误会导致机器人实例未正确初始化,所有命令监听逻辑直接失效。

  2. 文件写入未持久化:

    • 打开日志文件时使用mode="w",每次启动会清空原有日志内容,建议改为mode="a"实现追加写入。
    • log函数中调用f.write()后未执行f.flush()或f.close(),写入内容会停留在内存缓冲区,不会实时写入文件。
  3. 未定义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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:35:19