javascript - Discord API 为所有带有机器人令牌的查询返回 401
问题描述
我正在尝试向 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);
我试过用硬编码值在邮递员中发出请求,我得到了相同的响应,所以我不认为这是一个语法错误,但我不能确定。提前感谢您的帮助。
解决方案
正如我从您的问题中了解到的那样,您从邮递员那里得到了相同的响应(401 Unauthorized),因此唯一的原因是访问令牌无效或者您无权对 API 或通道进行此类调用不和谐。
另一个你应该看到的是你在 axios 中发送 headers 的方式,这里我可以和你分享发送 headers 的正确方法: 如何在 axios 中设置 header 和选项?
还要检查“auth.json”是否具有正确的令牌,因为您正在调用它(auth.token)。
推荐阅读
- elasticsearch - 在管道聚合中显示选定的值
- ignite - javax.cache.CacheException:找不到类型为 XXXXXX 的 SQL 表
- java - java.lang.ClassCastException 的任何建议解决方案:oracle.xdb.XMLType 与 oracle.sql.OPAQUE 不兼容
- data-warehouse - 如何获取传入事实记录的精确代理键
- regex - 如何根据两列是否包含其他列中存在的值来返回值
- python-3.x - 如何将 xmi:version="2.0" 属性添加到元素
- php - CSV 错误编码
- javascript - NodeJS、ReactJS:Axios 帖子没有及时更新
- javascript - 将操作从 localhost 上托管的 Javascript/PHP 发送到 WPF 应用程序
- python - 将集合的 defaultdict 替换为具有 setdefault 的普通 dict