Unable to strip brackets from string lists and convert them into an integer list

43 views Asked by At

Today I was trying to expand my code a little by automating when the user goes online.

To do this, I use players.json from a FiveM server, the output looks like this:

{"endpoint":"127.0.0.1","id":32,"identifiers":["license:948704b759518d74a682144ade779ac2a1e47c89","xbl:2535411592184061","live:914798949911430","discord:757436127689965649","fivem:3055601","license2:948704b759518d74a682144ade779ac2a1e47c89"],"name":"perez_04","ping":60},

and this goes on and on for every user.

I was able to retrieve all the information I needed, like the discord id and the player name, however, I have a problem.

What I have now is that every piece of data, including numbers-only, I store them as strings (I think this is the only way to get it to work with a list) like this:

            # ----- GET INFO -----
            users = {}
            for player_data_eu1 in online_eu1:
                player_name_eu1 = player_data_eu1.get("name", "N/A")
                discord_id_eu1 = [identifier.split(":")[1] for identifier in player_data_eu1.get("identifiers", []) if "discord" in identifier]
                in_game_id_eu1 = player_data_eu1.get("id", "N/A")
                endpoint_eu1 = player_data_eu1.get("endpoint", "N/A")
                license_eu1 = [identifier.split(":")[1] for identifier in player_data_eu1.get("identifiers", []) if "license" in identifier]
                xbl_eu1 = [identifier.split(":")[1] for identifier in player_data_eu1.get("identifiers", []) if "xbl" in identifier]
                live_eu1 = [identifier.split(":")[1] for identifier in player_data_eu1.get("identifiers", []) if "live" in identifier]
                fivem_eu1 = [identifier.split(":")[1] for identifier in player_data_eu1.get("identifiers", []) if "fivem" in identifier]
                license2_eu1 = [identifier.split(":")[1] for identifier in player_data_eu1.get("identifiers", []) if "license2" in identifier]
                ping_eu1 = player_data_eu1.get("ping", "N/A")

           #----- SAVE INFO -----
                users[str(player_name_eu1)] = player_name_eu1
                users[str(discord_id_eu1)] = discord_id_eu1
                users[str(in_game_id_eu1)] = in_game_id_eu1
                users[str(endpoint_eu1)] = endpoint_eu1
                users[str(license_eu1)] = license_eu1
                users[str(xbl_eu1)] = xbl_eu1
                users[str(live_eu1)] = live_eu1
                users[str(fivem_eu1)] = fivem_eu1
                users[str(license2_eu1)] = license2_eu1
                users[str(ping_eu1)] = ping_eu1

and everything works fine however I need the discord ID as an integer and out of the squared brackets because the output of the print message:

                print("Loaded online data for:", player_name_eu1)
                print("Player Name:", player_name_eu1)
                print("Discord ID:", discord_id_eu1_i)
                print("In-Game ID:", in_game_id_eu1)
                print("\n")  # Add a newline after each user's data

gives me the discord id as for example:

Discord ID: ['633993765494033'] # Note that this is not an actual discord ID, its just to show.

I need to remove the ' ' and the [ ] from the final product, but I'm unable to do so.

This is what I have tried so far:

                if discord_id_eu1:
                    discord_id_eu1_i = [int(s.strip("[]'")) for s in discord_id_eu1]

                elif not discord_id_eu1:
                    print("No discord ID, skipping")
                    continue
                    
                else:
                    discord_id_eu1 = []
                    discord_id_eu1_i = []

but this only stripped the ' ', and not the [ ]. I tried everything!

Please not that discord_id_eu1 is a STRING list full of MULTIPLE STRINGS of Numbers, so converting it into an integer without separating each number first throws an error

An unexpected error occurred: argument of type 'int' is not iterable

Here is the full code section, for any questions, please feel free to ask. Thank you in advance!

@tasks.loop(seconds=20)
async def check_activities():
    for guild in bot.guilds:
        for member in guild.members:
            if member.bot:
                continue

            # Check if member has Trainee, Cadet, or SWAT role
            allowed_role_ids = [1033432392758722682, 962226985222959145, 958274314036195359]
            has_allowed_role = any(role.id in allowed_role_ids for role in member.roles)
            
            if not has_allowed_role:
                continue  # Skip members without the specified roles
              
            try:
              # ---- EU1 ----
                request_online_eu1 = requests.get(api_url_online_eu1)
                request_online_eu1.raise_for_status()  # Raise an HTTPError for bad responses
                online_eu1 = request_online_eu1.json()
                time.sleep(1)
        
                if request_online_eu1.status_code == 200:
                    print("Status Code: 200 (OK)")
                    online_eu1 = request_online_eu1.json()
                    
                else:
                    print("Status code not 200, locked program")
                    
                users = {}
                for player_data_eu1 in online_eu1:
                    player_name_eu1 = player_data_eu1.get("name", "N/A")
                    discord_id_eu1 = [identifier.split(":")[1] for identifier in player_data_eu1.get("identifiers", []) if "discord" in identifier]
                    in_game_id_eu1 = player_data_eu1.get("id", "N/A")
                    endpoint_eu1 = player_data_eu1.get("endpoint", "N/A")
                    license_eu1 = [identifier.split(":")[1] for identifier in player_data_eu1.get("identifiers", []) if "license" in identifier]
                    xbl_eu1 = [identifier.split(":")[1] for identifier in player_data_eu1.get("identifiers", []) if "xbl" in identifier]
                    live_eu1 = [identifier.split(":")[1] for identifier in player_data_eu1.get("identifiers", []) if "live" in identifier]
                    fivem_eu1 = [identifier.split(":")[1] for identifier in player_data_eu1.get("identifiers", []) if "fivem" in identifier]
                    license2_eu1 = [identifier.split(":")[1] for identifier in player_data_eu1.get("identifiers", []) if "license2" in identifier]
                    ping_eu1 = player_data_eu1.get("ping", "N/A")
                    
                    users[str(player_name_eu1)] = player_name_eu1
                    users[str(discord_id_eu1)] = discord_id_eu1
                    users[str(in_game_id_eu1)] = in_game_id_eu1
                    users[str(endpoint_eu1)] = endpoint_eu1
                    users[str(license_eu1)] = license_eu1
                    users[str(xbl_eu1)] = xbl_eu1
                    users[str(live_eu1)] = live_eu1
                    users[str(fivem_eu1)] = fivem_eu1
                    users[str(license2_eu1)] = license2_eu1
                    users[str(ping_eu1)] = ping_eu1
                   
                    
                    if discord_id_eu1:
                        discord_id_eu1_i = [int(s.strip("[]'")) for s in discord_id_eu1]

                        
                    elif not discord_id_eu1:
                        print("No discord ID, skipping")
                        continue
                        
                    else:
                        discord_id_eu1 = []
                        discord_id_eu1_i = []
                        

                    
                    print("Loaded online data for:", player_name_eu1)
                    print("Player Name:", player_name_eu1)
                    print("Discord ID:", discord_id_eu1_i)
                    print("In-Game ID:", in_game_id_eu1)
                    print("\n")  # Add a newline after each user's data
              
              # ------ LOGIC ------
              # ---- EU1 ----
                    if member.id in discord_id_eu1_i:
                        print(f"Success!, ID: {in_game_id_eu1}, NAME: {player_name_eu1}, DISCORD: {discord_id_eu1_i}")
   
             # ---- EXCEPTIONS ----
            except requests.exceptions.HTTPError as e:
                print(f'HTTPError: {e}')
            except requests.exceptions.ConnectionError as e:
                print(f'ConnectionError: {e}')
            except requests.exceptions.RequestException as e:
                print(f'RequestException: {e}')
            except Exception as e:
                print(f'An unexpected error occurred: {e}')
2

There are 2 answers

0
Pfinnn On BEST ANSWER

The response you get from the server is in JSON Format. Treat it as such. Right now you are working with strings, which complicates everything.

Try this instead:

import json

# The provided JSON string
json_string = '{"endpoint":"127.0.0.1","id":32,"identifiers":["license:948704b759518d74a682144ade779ac2a1e47c89","xbl:2535411592184061","live:914798949911430","discord:757436127689965649","fivem:3055601","license2:948704b759518d74a682144ade779ac2a1e47c89"],"name":"perez_04","ping":60}'

# Deserialize the JSON string into a Python dictionary
data = json.loads(json_string)

# Access the data
print("Endpoint:", data["endpoint"])
print("ID:", data["id"])
print("Identifiers:", data["identifiers"])
print("Name:", data["name"])
print("Ping:", data["ping"])
0
sicco14 On

What is the type of the "discord_id_eu1_i" variable? If it is a list you can just use "discord_id_eu1_i[0]" to access the first list element, which is the ID that you want.

If it is a string you could just filter for Numbers in your string. For example by using

filtered_ID = ''.join(filter(str.isdigit, discord_id_eu1_i))

keep in mind that its still a string afterwards. If you want to use it in discord.py context you need to convert it into an integer. For example by:

int(filtered_ID)