Discord Bot读取.log文件含IMPORTANT:内容报错,求代码修正
问题
我在Windows 10 + Python 3.10.11环境下,用@client.command装饰器开发Discord机器人,目标是让它从持续更新的.log文件中提取包含IMPORTANT:的内容并发送到Discord频道。但运行?run命令时触发错误,找不到直接读取.log文件输出到Discord的相关资料,刚接触Python,需要基础的语法和代码结构修正指导。
预期效果:机器人输出.log文件中含IMPORTANT:的行
实际情况:执行?run命令后仅返回错误
错误信息
Traceback (most recent call last): File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped ret = await coro(*args, **kwargs) File "C:\Users\*USER\OneDrive\Desktop\DiscordBot\main.py", line 18, in follow for line in loglines: TypeError: 'coroutine' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\**USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1366, in invoke await ctx.command.invoke(ctx) File "C:\Users|\*USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke await injected(*ctx.args, **ctx.kwargs) # type: ignore File "C:\Users\*USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'coroutine' object is not iterable C:\Users\*USER\AppData\Local\Programs\Python\Python310\lib\asyncio\events.py:80: RuntimeWarning: coroutine 'Command.__call__' was never awaited self._context.run(self._callback, *self._args) RuntimeWarning: Enable tracemalloc to get the object allocation traceback
原始代码
import discord import time, os from discord.ext import commands @client.event async def coroutine(ctx, *args): print("Bot Is Ready") @client.command() async def run(thefile): if __name__ == "__main__": logfile = open(os.getenv("APPDATA")+"/.directory/logs/announcement.log", "r") loglines = follow(logfile) for line in loglines: if "IMPORTANT:" in line: await print (line) client.run("token is here")
解决方案
问题分析
- 未初始化Bot实例:代码直接使用
client但未创建commands.Bot对象,导致事件和命令无法绑定 - 错误的事件函数:
@client.event装饰的函数应为Discord预设事件(如on_ready),而非自定义的coroutine - 缺失
follow函数实现:调用了follow(logfile)但未定义该函数,且即使有定义,异步处理逻辑也存在问题 await print错误:print是同步函数,不需要用await修饰,且Discord机器人需用ctx.send发送内容到频道- 无用参数与路径拼接问题:
run命令定义的thefile参数未实际使用,且手动拼接路径易出现Windows系统分隔符兼容问题 - 日志监听逻辑缺失:未实现持续读取日志新增内容的逻辑,无法跟踪实时更新的.log文件
修正后的代码
import discord import os import time from discord.ext import commands # 初始化Bot,设置命令前缀与必要权限 client = commands.Bot(command_prefix="?", intents=discord.Intents.default()) # 机器人就绪事件 @client.event async def on_ready(): print("Bot Is Ready") # 实现持续读取日志新增内容的函数 def follow(logfile): logfile.seek(0, os.SEEK_END) # 定位到文件末尾 while True: line = logfile.readline() if not line: time.sleep(1) # 无新内容时等待1秒 continue yield line @client.command() async def run(ctx): # 用os.path.join拼接路径,适配Windows系统 log_path = os.path.join(os.getenv("APPDATA"), ".directory", "logs", "announcement.log") try: with open(log_path, "r", encoding="utf-8") as logfile: # 先读取文件现有内容中的目标行 for line in logfile: cleaned_line = line.strip() if "IMPORTANT:" in cleaned_line: await ctx.send(cleaned_line) # 持续监听新增内容 for line in follow(logfile): cleaned_line = line.strip() if "IMPORTANT:" in cleaned_line: await ctx.send(cleaned_line) except FileNotFoundError: await ctx.send("日志文件不存在,请检查路径!") except Exception as e: await ctx.send(f"发生错误:{str(e)}") # 运行机器人,替换为你的Token client.run("你的机器人Token")
关键修正说明
- 新增
commands.Bot实例初始化,指定命令前缀和默认权限(Intents) - 替换错误事件函数为标准的
on_ready,确保机器人就绪时触发提示 - 实现
follow函数,通过定位文件末尾+循环读取,实现实时日志监听 - 用
ctx.send替代await print,将内容发送到Discord频道 - 用
os.path.join拼接路径,解决Windows系统路径分隔符问题 - 添加异常处理,避免文件不存在或其他错误导致机器人崩溃
内容的提问来源于stack exchange,提问作者Comet Caster
相关产品推荐
相关产品推荐

