1

I own a discord.py bot. I made a few commands that can create a file with a few simple functions. I have a command who let me read the file, but, I want to improve it. I want that the bot read a specific line of the file. Like if i say +file read test txt 9, the bot will read the file test.txt at line 9.

I use a command group in a cog (cogs/owner.py). The command group called "file" who has a False invoke_without_command() (@commmands.group(invoke_without_command=False))

I tried first to just put the "line" variable in the await ctx.send(f.read(line)), but it didn’t worked.

This is the MRE (minimum reproducible example) of the code:

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
Morhexa
  • 11
  • 3
  • 1
    Just as a heads up, the Discord.py API will be discontinued soon https://gist.github.com/Rapptz/4a2f62751b9600a31a0d3c78100287f1 – Josi Whitlock Aug 30 '21 at 00:34
  • 1
    There's no way to know where a specific line in a file is without reading all of the characters before it. You can read the entire file, or read line by line, but there's no optimization to be had by "skipping" lines – Garr Godfrey Aug 30 '21 at 00:39

1 Answers1

1

The read function doesn't understand line numbers. You want something like this:

await ctx.send(f.readlines()[line-1])

... the - 1 is because Python arrays like the array of lines returned by readlines start counting from 0, but text file line numbers usually start at 1.

Though that will blow up with an exception if the file doesn't have that many lines, so you may want to add an except clause to handle that case.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175