0

I'm trying to make something that goes through a file called "tokens.txt" and removes all of the invalid discord user tokens. However, instead of deleting them, it keeps writing the same invalid tokens in the file and messing it up. I don't know why it is not properly deleting the tokens. Please let me know how to fix this. The code is below.

import requests
    
with open("tokens.txt","r+") as f:
    for line in f:
        token=line.strip("\n")
        headers = {'Content-Type': 'application/json', 'authorization': token}
        url = "https://discordapp.com/api/v6/users/@me/library"
        r=requests.get(url,headers=headers)
        if r.status_code == 200:
            print(token+" is valid")
        else:
            print("invalid token found "+token)
            tokenlines=f.readlines()
            for usertoken in tokenlines:
                if usertoken.strip("\n") != token:
                    f.write(usertoken)
                    print("invalid token automatically deleted")
  • maybe check if token is in upper or lower letters – Jon Nezbit Aug 09 '20 at 20:14
  • they are all randomly upper or lower case if that is what you are talking about. What does that mean? – Supergamer5465 Aug 09 '20 at 20:22
  • 1
    You're trying to iterate a file while already iterating it. Simplify your algorithm: iterate the input file, checking each token. If it is good, write it to the output file, if not, then simply dont write it to the output file. – Jonathon Reinhart Aug 09 '20 at 20:46
  • 1
    @Supergamer5465 that means that if you try to match for example uppercase "A" with lowercase "a" you will not get match if I recall correctly. Use upper() or lower() functions to match case – Jon Nezbit Aug 09 '20 at 21:40

1 Answers1

1

You can either, find all the valid tokens, collect them into a list and then completely rewrite the file with the valid tokens.

import requests

valid_tokens = []
with open("tokens.txt","r+") as f:
    for line in f:
        token=line.strip("\n")
        url = "https://discordapp.com/api/v6/users/@me/library"
        r = requests.get(url, headers=headers)
        if r.status_code == 200:
            print(token + " is valid")
            valid_tokens.append(token)
        else:
            print("invalid token found "+token)
            # Could collect the invalid tokens here

with open("tokens.txt","w+") as f:
    for i in valid_tokens:
        f.write(i+"\n")

Otherwise, if you would rather replace the lines within the file, I would recommend looking at this post: Replace and overwrite instead of appending.

mihuo999o
  • 96
  • 2