因此,我决定开始制作一个非常简单的Discord机器人,如果其他成员具有相同的角色,则该机器人应该为该成员赋予角色,
例如;
人员1:我被感染了
人员2:我没有受感染的角色。
人2:@ Person1等等等等
现在,第2个人应该获得受感染的角色,但那不会发生,而且我也找不到解决它的方法。
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
console.log("rerararararrederasd")
var infectionStarted = true; client.on("message", message => {
if (infectionStarted) {
try{ let role = message.guild.roles.cache.find(r => r.name === 'infected');
client.users.cache.get(message.mentions.members.first().id).roles.add(role);}catch(e){console.log(e)};
}
});
client.login('my discord bots token ofc goes here i just removed for stackoverflow');
但是在控制台中,我收到此问题报告:
at Client.emit (events.js:196:13)
at MessageCreateAction.handle (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/discord.js/12.3.1/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/discord.js/12.3.1/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/discord.js/12.3.1/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/discord.js/12.3.1/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/discord.js/12.3.1/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/ws/7.3.1/node_modules/ws/lib/event-target.js:125:16)
at WebSocket.emit (events.js:196:13)
at Receiver.receiverOnMessage (/rbd/pnpm-volume/ec7e49f1-7b76-4ef8-9653-1982138496c7/node_modules/.registry.npmjs.org/ws/7.3.1/node_modules/ws/lib/websocket.js:797:20)
TypeError: Cannot read property 'add' of undefined
这可能非常明显,但是我不知道该如何解决,如果您能帮助我,我将非常感谢,谢谢!
答案 0 :(得分:0)
编辑:
我建议对代码进行结构化以及对变量进行结构化。
问题在于,client.users.fetch()
返回的user
与member
毫无作用。因此,为什么返回undefined
client.on("message", message => {
const infectionStarted = true
const role = message.guild.roles.cache.find(r => r.name === 'infected')
// have 'member' = the mentioned member
const member = message.mentions.members.first()
// If there was a mention, add the role to the mentioned
if (member) {
// Instead of fetching the user through Discord, I add the role directly to the member object like this
member.roles.cache.add(role)
}
}