Discord Bot Implementation with Python 3

I’ve created a function in lib.py to retrieve a player’s ID based on their username:

def fetchPlayerID(username):
    parameters = {"action": "autocompleteList",
                  "iso": iso,
                  "server": server}
    response = requests.post(url_base, parameters)
    json_data = response.json()
    users = json_data["player"]

    for user in users:
        if username in user["pseudo"]:
            return user["id"]
    return 0

And in bot.py, I have the following code:

import discord
from discord.ext import commands
from lib import *

@bot.command(pass_context=True)
async def locate(ctx, *args):
    ...
    player_id = fetchPlayerID('JD')  # always returns 0 despite the user existing
    ...

My issue is that when I use fetchPlayerID within my bot command, it consistently returns 0, even though it works correctly in lib.py. I can’t identify the problem in my implementation since no errors are reported. Any insights would be greatly appreciated.

One aspect that might cause this behavior is related to how external requests are made within an asynchronous context in Discord bots. Since your fetchPlayerID is making a synchronous request using requests.post, it can lead to unexpected behavior. Consider using an asynchronous HTTP library like aiohttp instead, which is more suitable for non-blocking operations in an asynchronous environment. Replacing the requests.post with aiohttp’s client session and handling it with await may solve the issue while ensuring proper handling of the event loop.

Another thing to check is if the API’s ‘player’ key actually contains data or is returning an empty list when your bot function calls it. Try printing out json_data right after the response to debug. Might be different when calls are made via bot if server settings differ.