【发布时间】:2021-10-28 20:10:46
【问题描述】:
我拥有一个 discord.py 机器人。我做了一些命令,可以创建一个带有一些简单功能的文件。我有一个命令让我读取文件,但是,我想改进它。我希望机器人读取文件的特定行。就像我说+file read test txt 9 一样,机器人会在第 9 行读取文件 test.txt。
我在 cog (cogs/owner.py) 中使用命令组。名为“file”的命令组具有 False invoke_without_command() (@commmands.group(invoke_without_command=False))
我首先尝试将“line”变量放入await ctx.send(f.read(line)),但没有成功。
这是代码的 MRE(最小可重现示例):
cogs/owner.py
from discord.ext import commands
import discord
class Owner(commands.Cog):
# the init function
@commands.group(invoke_without_command=False)
async def file(self, ctx):
print=" "
@file.command()
async def read(self, ctx, filename, extension, line=None):
if line == None:
f = open(f"{filename}.{extension}", "r")
await ctx.send(f.read())
else:
f = open(f"{filename}.{extension}", "r")
await ctx.send(f.read(line))
"""
also tried this:
await ctx.send(f.read(type(Line)))
""""
#setup function
【问题讨论】:
-
请注意,Discord.py API 即将停用 gist.github.com/Rapptz/4a2f62751b9600a31a0d3c78100287f1
-
如果不读取之前的所有字符,就无法知道文件中特定行的位置。您可以读取整个文件,或逐行读取,但“跳过”行没有任何优化
标签: python discord discord.py bots