如何让我的Discord Bot提及我提到的某人?

时间:2019-07-09 14:08:04

标签: javascript node.js discord discord.js

我刚刚开始编写Discord机器人的代码,提及某人时遇到了一个小问题。我想让我的漫游器提及某人,并说当我在任何渠道上的Discord上提及某人时,他有多酷:

Dahkris: lul howcool @Myfriend
Bot: @Myfriend is 80% cool ! 

(随机部分是有功能的)

由于我是js的新手,所以我不知道这些参数的工作原理,所以不知道应该使用@member还是“ member.displayName”等(我尝试了不同的类型)。我已经搜索过类似的代码,但通常该漫游器仅提及消息的作者。

bot.on('message', message => {
    if (message.startsWith === 'lul howcool') {
      if ( message.content === @member ) {
      message.channel.send ( @member + ' is ' + ( Math.floor(Math.random() * 100) + 1 ) + "% cool ! " )
    }
  }
  })

此代码似乎没有任何错误,但由于消息从不包含“ @member”(我认为)而无法正常工作。

5 个答案:

答案 0 :(得分:1)

邮件的mentions属性是MessageMentions,其中有两个属性可能会让您感兴趣:usersmembers。不同之处在于您要使用它做什么。 membersGuildMember的集合,而usersuser的集合。

注意:您可以使用userGuildMember访问varGuildMember.user

在这里您想提及某人。两种类型都有一个toString()方法,该方法返回一个提及用户的字符串。例如,如果变量oneUser中有某人的实例,而您进行了channel.send('Hello ' + oneUser),则输出将为Hello @TheUser

如何使用它取决于命令的工作方式(检查是否仅提及一个,是否包含多个参数,等等)。 我将以最简单的形式进行操作,即,如果消息以lul howcool开头并且是否包含用户提及。如果还有其他消息,它将仍然有效。

bot.on('message', message => {
  if (message.startsWith('lul howcool')) { // this is how you use startsWith https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
    if (message.mentions.users.length > 0) { // check if an user is mentionned
      message.mentions.users.forEach((k, v) => { // do something for each mentions
        message.channel.send( v + ' is ' + ( Math.floor(Math.random() * 100) + 1 ) + "% cool ! " );
      })
    }
  }
})

它将为消息中的每个提及(用户提及,而不是渠道或角色)发送一条消息。

免责声明:我无法测试代码,因此可能会出现错误。它背后的逻辑仍然可行。如果要在发送消息后处理可能的错误,则不使用forEach,而是使用for循环,因为forEach不能与promise see this一起使用。

答案 1 :(得分:0)

因此,我修复了代码并对其进行了测试,然后它可以工作。我选择了不同的方法,但结果是相同的。

 client.on('message', async message => {
    if (message.author.bot) return;

    let mention = message.mentions.users.first()

    if (msg.startsWith(".pfx howcool") && mention) {
        message.channel.send(`${mention} is ${Math.floor(Math.random() * 100) + 1}% cool!`)
        
    } else if (message.content === ".pfx howcool"){
        message.channel.send(`You are ${Math.floor(Math.random() * 100) + 1}% cool!`)
}});

答案 2 :(得分:0)

这是一个简单的代码片段,用于评估提及踢:

文档位于:https://discordjs.guide/creating-your-bot/commands-with-user-input.html#mentions

else if (command === 'kick') {
    // grab the "first" mentioned user from the message
    // this will return a `User` object, just like `message.author`
    const taggedUser = message.mentions.users.first();
    message.channel.send(`You wanted to kick: ${taggedUser.username}`);
}

答案 3 :(得分:0)

您可以在字符串中使用 @USER ID,例如 @766369570550186036 您也可以格式化。我使用 python 所以我的字符串格式是 {}.format() 但你应该能够使用一种格式。 (还有 @USER ID 的东西适用于所有类型的代码,因为它是一个不和谐的函数。所以如果你要输入一个包含 @USER ID 的消息(用用户 ID 替换“用户 ID”它会提到用户))

这是一个python示例:

await ctx.send("hello <@{}>".format(ctx.author.id)

答案 4 :(得分:0)

const user = message.mentions.users.first();
message.channel.send(`${user} //code`

其中 //code 是消息文本的其余部分和代码的其余部分