简体   繁体   English

响应 discord.js 中的消息

[英]Responding to a message in discord.js

I would like to send a message "E" to the channel where someone sent a message starting with s#.我想向有人发送以 s# 开头的消息的频道发送消息“E”。 I have got 2 problems:我有两个问题:

  1. I have got a function:我有一个功能:
function read(msg)
{
  if(msg[0] === "s" && msg[1] === "#") console.log("E");
}

and I don't know how to call this function with a message that someone sent as 'msg'.而且我不知道如何使用某人作为“msg”发送的消息来调用此函数。

  1. And when I figure out how to do this, I would like to add a channel.send("E");当我弄清楚如何做到这一点时,我想添加一个channel.send("E"); , but I don't know how to get the id of the channel that the message was sent to. ,但我不知道如何获取消息发送到的频道的 id。
client.on('message', message => {
    if(message.content.startsWith('s#')) console.log('s#');//check if the message starts with s#
});
message.channel.send('this is a reply to the message sent in this channel');

see docs: https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=e-message见文档: https : //discord.js.org/#/docs/main/stable/class/Client? scrollTo = e- message

Edit (the whole code with the read function):编辑(带有读取功能的整个代码):

const Discord = require('discord.js');
const client = new Discord.Client();

client.on('message', message => {
    read(message);
});

function read(message){
   if(message.content.startsWith('s#')) console.log('s#');
}

client.login('your-token-here');

If you want to use the read function there two ways如果你想使用 read 函数有两种方法

As @SickBoy Said,正如@SickBoy 所说,

function read(msg){
if(msg.content.startsWith('s#'){
return true;
}
else{
return false;
}
}

or else,要不然,

function read(msg){
const data = msg.content.split('')
if(data[0] === 's' && data[1] === '#'){
return true;
}
else{
return false;
}
}

To call this function simply add a event of message.要调用此函数,只需添加一个消息事件。

client.on('message' , message=> {
const res = read(message)
if(res){
//The message starts with s#
}
else{
//It doesn't start with s#
}
})

There is an event called message which gets emitted whenever someone sends a message in the server.每当有人在服务器中发送message ,就会发出一个名为message的事件。 This event returns a message object which contains all the information about that message like content, author, channel, member, etc. So to send something back as a reply you can do this:此事件返回一个message对象,其中包含有关该消息的所有信息,如内容、作者、频道、成员等。因此,要将某些内容作为回复发回,您可以执行以下操作:

client.on('message', message => {
    if (message.content.startsWith('s#')) {
        message.channel.send('E');
    }
}

Also, I saw you're doing this in your ready function: msg[0] .另外,我看到您在ready函数中执行此操作: msg[0] This is not how you access the content of a message object.这不是您访问message对象内容的方式。 It's not an array.它不是一个数组。 You can get the content of a message using let text = message.content .您可以使用let text = message.content获取消息的内容。 This text is of string type and stores the message text.此文本为字符串类型并存储消息文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM