在下面的代码中,每当用户对特定消息做出“ A”表情符号反应时,我都会尝试为该用户添加角色。但是,当我对消息做出反应时,我只看到控制台日志Role Added1
,这意味着线程被卡在试图为用户分配角色的行中。在以下导致错误的代码中我做了什么错误的事情?
bot.on("raw", event => {
const eventName = event.t;
if(eventName == "MESSAGE_REACTION_ADD"){
var roles = JSON.parse(fs.readFileSync("roles.json"));
var info = JSON.parse(fs.readFileSync("info.json"))
if(event.d.message_id == info["Class Message"]){//class selection
switch(event.d.emoji.name){
case "?":
console.log("Role Added1");
event.d.member.roles.add(bot.guilds.cache.get("721695624613068830")
.roles.cache.get(roles["myrole"]));
console.log("Role Added2");
break;
}
}
}
}
答案 0 :(得分:1)
您没有从GuildMember
事件中收到raw
类实例。这是一个简单的json对象,与discordjs无关。这是可行的:
bot.on("raw", async event => {
const eventName = event.t;
if(eventName == "MESSAGE_REACTION_ADD"){
var roles = JSON.parse(fs.readFileSync("roles.json"));
var info = JSON.parse(fs.readFileSync("info.json"))
if(event.d.message_id == info["Class Message"]){//class selection
switch(event.d.emoji.name){
case "?":
console.log("Role Added1");
const guild = bot.guilds.cache.get("721695624613068830");
const memberID = event.d.user_id;
const member = await guild.members.fetch(memberID);
member.roles.add(roles["myrole"]);
console.log("Role Added2");
break;
}
}
}
}
您还可以使用以下命令使事件函数同步:
bot.on("raw", event => {
const eventName = event.t;
if(eventName == "MESSAGE_REACTION_ADD"){
var roles = JSON.parse(fs.readFileSync("roles.json"));
var info = JSON.parse(fs.readFileSync("info.json"))
if(event.d.message_id == info["Class Message"]){//class selection
switch(event.d.emoji.name){
case "?":
console.log("Role Added1");
const guild = bot.guilds.cache.get("721695624613068830");
const memberID = event.d.user_id;
guild.members.fetch(memberID).then((member) => {
member.roles.add(roles["myrole"]);
console.log("Role Added2");
});
break;
}
}
}
}