我想创建一个自动功能,用于检查用户名是否包含数字和字母以外的其他内容。我已经尝试过这样做,但是还没有一个可以工作的。
我已经使用了它,甚至试图捕获错误,但是它不起作用,但是不会产生错误。我真的不知道问题是什么。我对JS和Discord机器人的创作还很陌生,所以我对此不太满意。
bot.on("guildMemberAdd", k => {
if (!message.guild.me.hasPermission(["MANAGE_NICKNAMES", "ADMINISTRATOR"])) return message.channel.send("I do not meet the permission criteria!")
let user = bot.users.cache
if (user.user.username != /[^a-zA-Z0-9]/g, '_') {
try {
let i = 1
user.user.setNickname('Pingable Name #' + i + 1)
} catch (e) {
return console.log(e);
}
}
})
答案 0 :(得分:0)
if (user.user.username != /[^a-zA-Z0-9]/g.test(user.user.username));
尝试这样的事情。
答案 1 :(得分:0)
我看到您的代码存在多个问题:
message
变量,因为您的处理程序正在接收新的行会成员(您将其命名为k
),而不是消息。查看文档中的guildMemberAdd
事件以获取更多信息。user
定义为bot.users.cache
(因此是一个用户集合),但是随后就好像它是公会成员一样使用它:这是错误的,但是您也不会因为您已经有行会成员作为函数的参数,所以需要这样做。user.user.username != /[^a-zA-Z0-9]/g, '_'
检查用户名是否与此正则表达式匹配,但这是无效的语法。让我们看看如何解决它们:
bot.on('guildMemberAdd', newMember => {
// You can avoid checking for the admin permission, since if it's present it will work by default
if (!newMember.guild.me.hasPermission("MANAGE_NICKNAMES")) {
// Using message.channel.send is impossible, since message is not defined.
// return message.channel.send("I do not meet the permission criteria!")
// You can try sending a message to the owner:
return newMember.guild.owner.send('Can\'t change nickname: missing permissions')
}
// You can get the user from the guild member
let user = newMember.user
// Use the Regex.test() method
let regex = /[^a-zA-Z0-9_]/g // I've added the _ inside the regex
if (regex.test(user.username)) {
try {
// I'm removing the i variable since it's not being changed and it's not in global scope,
// you would need to store it somewhere in order for it to work
// let i = 1
// The setNickname method exists only inside the GuildMember class
newMember.setNickname('Pingable Name')
} catch (e) {
return console.log(e);
}
}
})