Discord API对所有带有机器人令牌的查询返回401

时间:2019-10-24 21:04:37

标签: javascript node.js authorization axios discord

我正在尝试将请求发送到不和谐的Web API,但一直收到401响应代码。我几乎可以在网上找到所有答案,这些答案来自使用无记名令牌而不是机器人令牌的人,然后更改为有效的机器人令牌。我正在使用机器人令牌,但仍获得401。但是,我知道该机器人令牌是有效的,因为尝试使用无效令牌启动node bot.js会引发错误,并且无法启动机器人。我现在的代码很简单

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);

我尝试用硬编码值在邮递员中执行请求,并且得到相同的响应,因此我认为这不是语法错误,但我不能确定。预先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

从您的问题中我了解到,您从邮递员处收到了相同的回复(401未经授权),因此唯一的原因是访问令牌无效或您无权对API进行此类调用或不和谐频道。

您应该看到的另一件事是在axios中发送标头的方式,在这里我可以与您分享发送标头的正确方式: How to set header and options in axios?

还要检查“ auth.json”在您调用它时是否正确拥有令牌(auth.token)。