如何使Discord.js机器人在特定频道中说出自定义消息并在消息中标记用户

时间:2020-10-19 19:02:23

标签: javascript discord.js bots

因此,我想为我的朋友和我创建自己的不和谐服务器,并且我希望它具有一些机器人功能...于是我开始编码..长话短说,我把它弄乱了,并且经过数小时的尝试找到我放弃的解决方案。

第一个是单词过滤器,可以很好地工作,我只是不能标记任何人。它应该删除说出的消息并发出一条消息,就像“ @example,不要这么说!” < / p>

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

    var array = ['example1, 'example2'];

    if(!msg.member.hasPermission('MANAGE_MESSAGES')){
        if(array.some(w => ` ${msg.content.toLowerCase()} `.includes(` ${w}`))){
            msg.delete();
            msg.channel.send(`${client.user.tag}`)
            return;
        }
    }
        
});

我的第二个问题: 我尝试创建一个命令,每次您在Discord上输入(prefix)say + "text"时,该漫游器都会显示该消息。最好的办法是,如果您可以在一个文本通道中键入所有命令,并且能够选择我希望机器人也要在哪个通道中键入该消息。这个简单的变体对我来说也很好。这是我的代码:

const isValidCommand = (message, cmdName) => message.content.toLowerCase().startsWith(prefix + cmdName);

require('dotenv').config();

client.on('message', function(message) {
    if(message.author.bot) return;

    else if(isValidCommand(message, "say")) {
        let marketing = message.content.substring(5);
        let marketingchannel = client.channels.cache.get('766732225185054740');
        let logsChannel = client.channels.cache.find(channel => channel.name.toLowerCase() === 'logs');
        if(logsChannel)
            logsChannel.send(marketing);
    }
});

我真的希望我能开始工作。

谢谢!

1 个答案:

答案 0 :(得分:0)

第一个问题

User.tag实际上并未提及用户。用户的标签由其usernamediscriminator组合而成。

'Lioness100'; // my username
'4566'; // my discriminator

'Lioness100#4566'; // my tag

有几种在消息中提及某人的方法。第一个是内置的Message.reply()函数,它将发送给定消息,并以<mention of author>,

开头

screenshot

第二种方法是将User / GuildMember对象转换为字符串。不和谐会自动将其解析为提及内容。

screenshot

第三种也是最通用的方法是使用提及语法。对于用户,它是<@id>

screenshot


您的第二个问题

我不太确定您的代码是否有问题,或者您的要求到底是什么,但是我认为您希望针对每条消息动态选择通道。您可以通过创建一个args变量来做到这一点。

// new usage:
// {prefix}say channelName message

client.on('message', function(message) {
 if (message.author.bot) return;

 // split string by every space => returns an array
 const args = message.content.slice(prefix.length).split(/ +/);

 // removes the first element (the command name) and stores it in this variable => returns a string
 const command = args.shift().toLowerCase();

 // now it's much easier to check the command
 if (command === 'say') {
  // the first element of `args` is the first word after the command, which can be the channel name
  // we can then find a channel by that name => returns a Channel or undefined
  const channel = message.guild.channels.cache.find(
   (c) => c.name === args[0]
  );

  if (!channel)
   return message.channel.send(`There is no channel with the name ${args[0]}`);

  // join all args besides the first by a space and send it => returns a string
  channel.send(args.slice(1).join(' '));
 }
});