discord.py - Oauth2 - join user to guild

29 Views Asked by At

I am currently trying to make a Discord Bot with Python which when authenticated with a user is able to join the user onto a server. This is the guide I followed: https://dev.to/dandev95/add-a-user-to-a-guild-with-discord-oauth2-in-python-using-requests-595f Sadly, it did not work. Therefore I changed the code a bit and got this:

import discord
from discord import app_commands
import requests

with open("token.txt") as file:
    token = file.read().strip()

API_ENDPOINT = 'https://discord.com/api/v10'
CLIENT_ID = '123456789'
CLIENT_SECRET = '123456789abcdefg'
REDIRECT_URI = "https://google.com"

class aclient(discord.Client):
    def __init__(self):
        super().__init__(intents = discord.Intents.all())
        self.synced = False

    async def on_ready(self):
        await self.wait_until_ready()
        await tree.sync(guild = discord.Object(id=1209872153269243904))
        print(f"Logged in as {self.user}.")

client = aclient()
tree = app_commands.CommandTree(client)

def exchange_code(code):
  data = {
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET,
    'grant_type': 'authorization_code',
    'code': code,
    'redirect_uri': REDIRECT_URI
  }
  headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
  r = requests.post('%s/oauth2/token' % API_ENDPOINT, data=data, headers=headers)
  r.raise_for_status()
  return r.json()

def add_to_guild(access_token, userID, guildID):
    url = f"{API_ENDPOINT}/guilds/{guildID}/members/{userID}"
    botToken = token
    data = {
    "access_token" : access_token,
    }
    headers = {
    "Authorization" : f"Bot {botToken}",
    'Content-Type': 'application/json'
    }
    response = requests.put(url=url, headers=headers, json=data)
    print(response.text)

@client.event
async def on_ready():
    print(f"Logged in as {client.user}")

code = exchange_code('abcdefghijklmnopqrstuvwxyz')['access_token']
print(code)
add_to_guild(code, '716235295032344596', '622176715183226910')

client.run(token)

When the Bot is run this is printed in the console: OgGVKANijnj3yyAec0OuP0D4dY63qK {"message": "Missing Permissions", "code": 50013} It says "Missing Permissions" but as seen here it should:

I tried searching in the Docs here but I also did not find any solution to my problem there.

0

There are 0 best solutions below