我正在尝试将请求发送到不一致的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);
我尝试用硬编码值在邮递员中执行请求,并且得到相同的响应,因此我不认为这是语法错误,但我不能确定。预先感谢您的帮助。
据我从您的问题中了解到,您从邮递员处获得了相同的响应(未经授权的401),因此唯一的原因是访问令牌无效,或者您无权对API或不和谐频道。
您应该看到的另一件事是在axios中发送标头的方式,在这里我可以与您分享发送标头的正确方法:How to set header and options in axios?
还要检查“ auth.json”在您调用它时是否正确拥有令牌(auth.token)。