Stephen Burns
Stephen Burns

Reputation: 172

Discord API returning 401 for all queries with bot token

I'm trying to send requests to the discord web API but keep getting a 401 response code. Almost all of the answers I can find online are from people who were using a bearer token instead of the bot token, and changing to the bot token worked. I'm using the bot token and still getting a 401. However, I know that this bot token is valid because trying to launch node bot.js with an invalid token throws an error and doesn't launch the bot. My code right now is simply

const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
const axios = require('axios');
const headers = {
    'Authorization': `Bot ${auth.token}`
};

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', msg => {

    /* If the author is a bot, do nothing */
    if (msg.author.bot) {
        return;
    }

    /* Only perform an action if the first character is ? */
    if (msg.content.substring(0, 1) == '?' && msg.content.length > 1) {
        var message = msg.content.substring(1).toLowerCase();

        //console.log(message);
        //console.log(msg);
        //console.log(msg.channel.name);

        switch (message) {
            case 'gos':

                axios.get(`https://discordapp.com/api/channels/${msg.channel.id}/messages`, headers)
                .then(response => {
                    console.log(response);
                }).catch(err => {
                    console.log(err);
                });


                break;
            case 'dolphin':
                msg.reply('dolphin', {files: [
                    "https://www.dolphinproject.com/wp-content/uploads/2019/07/Maya-870x580.jpg"
                ]});
                break;
        }

    }
});

client.login(auth.token);

I've tried doing the request in postman with hardcoded values and I get the same response, so I do not think it is a syntactical error, but I cannot be sure. Thanks in advance for any help.

Upvotes: 0

Views: 2897

Answers (1)

Estuardo Estrada
Estuardo Estrada

Reputation: 86

As I understood from your question, you are getting the same response from postman (401 Unauthorized), so the only reason for that is that the access token is not valid or you do not have permission to do such call to the API or channel from discord.

Another thing you should see is the way you are sending your headers in axios, here I can share with you the correct way to send headers: How to set header and options in axios?

Also check that "auth.json" has the token correctly as your are calling it (auth.token).

Upvotes: 2

Related Questions