Search code examples
pythonoauth-2.0discord

Read Discord Channel Historical messages from Discord


I'm trying to build a very simple program to read all the message from a Discord Channel.

Step 1: Create an AUTH Token -> Working

Step 2: Test the token for read my own Info -> Working

Step 3: Get messages from channel is not working , I'm getting 401 error.

What is missing in step-1 , I tried few possible scopes yet no luck ... https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes

Please advise. Even if there are any other alternate methods apart from OAuth please advise. The Authorization token extracted from browser will work temporarily, so I cannot use that. if there is a way in DiscordPy please advise as well

Step 1: Generate Auth token working

API_ENDPOINT = 'https://discord.com/api/v10'
CLIENT_ID = 'XXXXXXXX'
CLIENT_SECRET = 'XXXXXXX'

def get_token():
    data = {
        'grant_type': 'client_credentials',
        'scope': 'identify connections'
    }
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    r = requests.post('%s/oauth2/token' % API_ENDPOINT, data=data, headers=headers, auth=(CLIENT_ID, CLIENT_SECRET))
    r.raise_for_status()
    return r.json()

result = get_token()
print(result)

===============

{'access_token': 'XXXXXXXXXXXX', 'expires_in': 604800, 'scope': 'identify connections', 'token_type': 'Bearer'}

===========

Step 2: Read about myself, working

 curl --location --request \
 GET 'https://discord.com/api/users/@me' \
--header 'Authorization: Bearer XXXXXXXXXX'
===============
{"id": "XXXXXXXXXX", "username": "XXXXXXXXXX", "avatar": null, "avatar_decoration": null, "discriminator": "XXXXXXXXXX", "public_flags": 0, "flags": 0, "banner": null, "banner_color": null, "accent_color": null, "locale": "en-US", "mfa_enabled": false}
===============

Step 3: Reading channel data is not working

curl --location --request GET 'https://discord.com/api/channels/00000000000000/messages' \
--header 'Authorization: Bearer XXXXXXXXX' 
===============
{"message": "401: Unauthorized", "code": 0}
===============


Solution

  • You aren't able to do that with Oauth. The only thing message related you can authorize with Oauth is reading the messages sent in channels/guilds your app creates. You can find the info here. https://discord.com/developers/docs/topics/oauth2 I honeslty advise you to just create an actual bot if you are wanting to get messages from channels and such.