LoginSignup
2
2

More than 1 year has passed since last update.

PythonでDiscordのOAuth2をやってみる

Last updated at Posted at 2021-04-14

PythonでDiscordのOAuth2を行う方法をまとめておきます。
Flaskとrequestsを利用します

ネットを調べてみましたが、出てきたライブラリ等が正常に動かなかったので自前で実装
githubにも公開しています
https://github.com/CubeZeero/Discord-OAuth2-Example.py

準備

Flaskとrequestsをインストール

pip install flask requests

次にDiscordのDeveloperPortalからアプリケーションを作成
https://discord.com/developers/applications

右上にあるNew Applicationから新しいアプリケーションを作成
image.png

アプリケーションの名前を決め、Create
image.png

左のメニューからOAuth2を選択し、ClientIDとClientSecretをメモっておく
RedirectsにCallbackURLを指定しておきます。今回はhttp://localhost:5000/callback/でテスト
image.png

実装

先程メモしたClientIDとClientSecretを変数に入れ、portが5000になっていることを確認
githubからstaticフォルダとtemplateフォルダを落としてpythonプログラムと同じディレクトリにおいてください
https://github.com/CubeZeero/Discord-OAuth2-Example.py

以下コード

DiscordOAuth2.py
from flask import Flask, request, render_template
import webbrowser
import requests
import json

app = Flask(__name__)

port = 5000
client_id = 'YOUR CLIENT_ID HERE'
client_secret = 'YOUR CLIENT_SECRET HERE'
callback_url = 'http://localhost:'+ str(port) +'/callback/'

login_url = 'https://discord.com/api/oauth2/authorize?response_type=code&client_id='+ client_id +'&scope=identify&redirect_uri='+ callback_url + '&prompt=consent'

webbrowser.open(login_url)

@app.route('/callback/')
def callback():
    authorization_code = request.args.get("code")

    request_postdata = {'client_id': client_id, 'client_secret': client_secret, 'grant_type': 'authorization_code', 'code': authorization_code, 'redirect_uri': callback_url}
    accesstoken_request = requests.post('https://discord.com/api/oauth2/token', data=request_postdata)

    responce_json = accesstoken_request.json()

    access_token = responce_json['access_token']
    token_type = responce_json['token_type']
    expires_in = responce_json['expires_in']
    refresh_token = responce_json['refresh_token']
    scope = responce_json['scope']

    responce_txt = open('responce.txt', 'w')
    responce_txt.write('access_token: '+ access_token +'\ntoken_type: '+ token_type +'\nexpires_in: '+ str(expires_in) +'\nrefresh_token: '+ refresh_token +'\nscope: '+ scope)
    responce_txt.close()

    return render_template('complete_window.html', title='Complete')

if __name__ == "__main__":
    app.run(port=port)

流れとしては

  1. ClientIDやscopeなどを指定してログインURLを作成

  2. 作成したログインURLを webbrowser.open() で開く

  3. 認証完了後 /callback にコードが返ってくるので request.args.get("code") でコードのみ取得

  4. requestsを使用し、必要な情報をPOSTしてトークンと交換

  5. トークンなどの情報をresponce.txtとしてまとめて保存

  6. 完了したことを示すhtmlを表示

こんな感じです

終わり

基本的なOAuth2の流れなので他のサービスでも利用できるはずです
以上

:hugging:

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2