Assigning roles to Discord users with Python and API endpoints

I’m working on a project to add roles to users in my Discord server. I’ve been trying to use the Discord API and Python’s requests library, but I’m running into some issues.

Here’s the code I’m using:

def assign_role(server_id, member_id, role_id):
    endpoint = f'https://discord.com/api/servers/{server_id}/members/{member_id}/roles/{role_id}'
    
    payload = {
        'action': 'add',
        'data': {}
    }
    result = requests.put(endpoint, json=payload)
    print(result)

When I run this, I get a 401 error instead of the 204 status code I’m expecting. The role isn’t being added to the user either.

Am I missing something in my API call? Maybe there’s an issue with authentication? Any help would be appreciated!

hey mate, i think ur missing the headers in ur request. u need to add the bot token for auth. try somethin like this:

headers = {‘Authorization’: ‘Bot ur_token_here’}
result = requests.put(endpoint, headers=headers, json=payload)

should fix that 401 error for ya. good luck!

I’ve dealt with Discord API integrations before, and there are a few things to consider. First, ensure you’re using the correct API version in your endpoint URL. The current version is v10, so your endpoint should look like this:

https://discord.com/api/v10/guilds/{server_id}/members/{member_id}/roles/{role_id}

Also, as others mentioned, you need to include the bot token in your headers. Here’s an updated version of your function that should work:

import requests

def assign_role(server_id, member_id, role_id, bot_token):
endpoint = f’https://discord.com/api/v10/guilds/{server_id}/members/{member_id}/roles/{role_id}
headers = {‘Authorization’: f’Bot {bot_token}'}

result = requests.put(endpoint, headers=headers)
return result.status_code

Remember to replace bot_token with your actual bot token when calling the function. This should resolve your authentication issues and allow you to assign roles successfully.

I’ve encountered similar issues when integrating with Discord’s API. In my experience, a 401 error is typically a sign that the authentication details are not being passed correctly. It is important to use a bot token and to include it in the request headers. For example, you might try:

headers = {
    'Authorization': f'Bot {YOUR_BOT_TOKEN}'
}
result = requests.put(endpoint, headers=headers, json=payload)

Additionally, check that your bot has the required permissions and that the API endpoint is current, such as using the v9 endpoint. This adjustment resolved similar issues for me.