0

I Have a code that reads a file and randomly chooses a line from that file and sends it through DMs as a discord bot. However, I want it to read a certain section of the txt file by which character the section starts and ends with. Ex: , Hi ,

This is the code I'm using that reads a random line and sends it through DM:

emailFile = open("C:/Users/jacob/Downloads/Spotify_premiums.txt", "r")
emails = []
for email in emailFile:
    emails.append(email)

@bot.command(pass_context = True)
@commands.cooldown(1, 30, commands.BucketType.user)
@commands.has_any_role("| Premium |")
async def spotifypremium(ctx):
    msg = emails
    await bot.send_message(ctx.message.author, random.choice(msg))
    await bot.send_message(ctx.message.channel, "Alt Has Been Seen To Your DMs")
    await bot.purge_from(ctx.message.channel, limit=2)
    await bot.send_message(ctx.message.author, "Please Wait 30 Seconds Before Using This Command Again. If you do not wait the full time then you won't be sent an alt.")
  • So are you just trying to read the section from a given start and end point? or are you trying to just choose from lines that match a given start and end? – Sam Rockett Oct 04 '17 at 21:05
  • also remember to close your files by either using `with open(...) as emailFile` or with `emailFile.close()` – Sam Rockett Oct 04 '17 at 21:06
  • @squaswin ok so say there is a comma at the start and a comma at the end of a message in the txt file... I want for it to use the message in between the commas – Kaitlyn Wathen Oct 04 '17 at 21:09
  • Would this link help? https://stackoverflow.com/questions/7559397/python-read-file-from-and-to-specific-lines-of-text – Amiga500 Oct 04 '17 at 21:10
  • @Amiga500 do you know if that would work with multiple “start end” statements in the file like to choose a random one from the file – Kaitlyn Wathen Oct 04 '17 at 21:17
  • Hmmm. If the commas are both start and end delimiters, then there is a really easy solution with `re`. – Sam Rockett Oct 04 '17 at 21:20
  • @squaswin that is exactly what I want... if you could make an answer for that I would be very appreciative – Kaitlyn Wathen Oct 04 '17 at 21:21

1 Answers1

0

As you've explained, you use comma (,) as a delimeter, so you can use str.split() to split the file into sections on the comma.

def load_file(fp):
    with open(fp) as file:
        content = file.read()
    lines = content.split(",")
    # Given ", hi ,", this will return ["", " hi ", ""]

    # To clean the whitespace:
    lines = [x.strip() for x in lines]
    # To remove the empty start and end
    lines = lines[1:-1]

    # If your file is ", email 1 , email 2 , email 3 ,
    # then you can return here, otherwise youll need to remove 
    # intermediate entries
    lines = [l for i, l in enumerate(lines) if i % 2 == 0]

    return lines

That last list comprehension spins off every line with an index number and keeps only the even ones.

Sam Rockett
  • 3,145
  • 2
  • 19
  • 33
  • Not to sound like an idiot but where would I put this in reference to my program – Kaitlyn Wathen Oct 04 '17 at 21:35
  • as long as you understand what its doing, you should just be able to drop it in as its own function and then you can either call it in the global scope `emails = load_file(emailFile)` or put it in the command function `msg = load_file(emailFile)`. The latter would mean that the file is reread every time the command is called, and therefore will update in real time – Sam Rockett Oct 04 '17 at 21:41
  • discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'emailFile' is not defined ... But as you can see from my code it is. – Kaitlyn Wathen Oct 04 '17 at 23:32
  • Oh whoops, I didn't realise that `emailFile` was a file object while that function asks for a string filepath. Maybe there are some scoping issues going on in your command method. Try defining the filepath inside the command body instead of on the global scope. – Sam Rockett Oct 04 '17 at 23:37
  • i defined it in the command and i get this error: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper – Kaitlyn Wathen Oct 04 '17 at 23:51
  • I think this explains why its giving me the error, but i dont know how to change the return at the end for your code https://stackoverflow.com/questions/43490993/python-write-then-read-file – Kaitlyn Wathen Oct 05 '17 at 02:28