Piotr Moroń
Piotr Moroń

Reputation: 41

How to get Avatar from discord API?

I am asking how can I get an avatar of a user who has authorized with oAuth2.

https://cdn.discordapp.com/avatars/781264468998488095/ XXXXXXXXXXXXXXXXXXX ?size=128

The first one is client ID, could someone explain what could be behind "/"?

Or how can I download from api Text Text

Upvotes: 3

Views: 17645

Answers (2)

Spoot
Spoot

Reputation: 101

The information that is provided to you by the Discord OAuth2 response includes an avatar id:

{id: '537355342313422849', username: 'Spectacle', avatar: '1ee4375beb131ae43a4e4b81e267a265', discriminator: '1738', public_flags: 64, …}

That's what goes in the URL after the client ID.

Example:

https://cdn.discordapp.com/avatars/537355342313422849/1ee4375beb131ae43a4e4b81e267a265

And of course, you can add specifications for the size.

Upvotes: 6

Piotr Moroń
Piotr Moroń

Reputation: 41

const { get, post } = require("snekfetch");
const express = require("express");
const btoa = require("btoa");
const app = express();

const cfg = {
    id: "****",
    secret: "*****",
};

app.get("/", (req, res) => {
    console.log(req.query.code);
    res.status(200).json({ status: "ok" });
    get(`https://discord.com/users/{id}`)
        .then((response) => {
            console.log(response);
            res.send(response);
        })
        .catch(console.error);
});

app.get("/dc", (req, res) => {
    res.redirect(
        [
            "https://discordapp.com/oauth2/authorize",
            `?client_id=${cfg.id}`,
            "&scope=identify+guilds",
            "&response_type=code",
            `&callback_uri=http://localhost:8080/authorize`,
        ].join("")
    );
});

app.get("/authorize", (req, res) => {
    const code = req.query.code;
    const cred = btoa(`${cfg.id}:${cfg.secret}`);
    post(
        `https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}`
    )
        .set("Authorization", `Basic ${cred}`)
        .then((response) =>
            res.redirect(`/guilds?token=${response.body.access_token}`)
        )
        .catch(console.error);
});

app.get("/guilds", (req, res) => {
    get("https://discordapp.com/api/v6/users/@me/guilds")
        .set("Authorization", `Bearer ${req.query.token}`)
        .then((response) => res.json(response.body))
        .catch(console.error);
});

app.listen(8080, () => console.log("Ready"));

Upvotes: 0

Related Questions