Last active
September 2, 2023 14:03
-
-
Save nitori/a582203fe153da27e3c6a4c1c5c8c103 to your computer and use it in GitHub Desktop.
Get access token from discord api via oauth2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from multiprocessing import Process, Queue | |
| from urllib.parse import urlencode | |
| import os | |
| from dotenv import load_dotenv | |
| load_dotenv() | |
| def run_local_app(q: Queue, state: str): | |
| from flask import Flask, request | |
| app = Flask(__name__) | |
| @app.route('/discord/auth') | |
| def auth(): | |
| code = request.args.get('code') | |
| verify_state = request.args.get('state') | |
| if verify_state != state: | |
| return 'Invalid state!' | |
| q.put(code) | |
| return 'You can close this window now.' | |
| app.run() | |
| def main(): | |
| import secrets | |
| import time | |
| state = secrets.token_hex(32) | |
| params = { | |
| 'client_id': os.environ['DISCORD_CLIENT_ID'], | |
| 'redirect_uri': os.environ['DISCORD_REDIRECT_URI'], | |
| 'response_type': 'code', | |
| 'scope': 'guilds.join', | |
| 'state': state, | |
| } | |
| url = 'https://discord.com/api/oauth2/authorize?' + urlencode(params) | |
| print('*' * 80) | |
| print('Please visit the following URL to authorize the bot:') | |
| print(url) | |
| print('*' * 80) | |
| print('Starting local server to wait for response...') | |
| q = Queue() | |
| proc = Process(target=run_local_app, args=(q, state)) | |
| proc.start() | |
| code = q.get() | |
| time.sleep(1) # give the server some time to respond | |
| proc.terminate() | |
| proc.join() | |
| # do the actual request to get the access token | |
| import requests | |
| r = requests.post('https://discord.com/api/oauth2/token', data={ | |
| 'client_id': os.environ['DISCORD_CLIENT_ID'], | |
| 'client_secret': os.environ['DISCORD_CLIENT_SECRET'], | |
| 'redirect_uri': os.environ['DISCORD_REDIRECT_URI'], | |
| 'grant_type': 'authorization_code', | |
| 'code': code, | |
| 'scope': 'guilds.join', | |
| }) | |
| # { | |
| # 'token_type': 'Bearer', | |
| # 'access_token': 'xxx', | |
| # 'expires_in': 604800, | |
| # 'refresh_token': 'yyy', | |
| # 'scope': 'guilds.join' | |
| # } | |
| data = r.json() | |
| # now you can do requests to the API with the access token, on behalf of the user | |
| print(data) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment