Receive Message client
The next step is to finally receive the message.
The atmosphere is becoming more and more like a bot!
WARNING
Note, however, that to receive the group's message, the decrypt key in FileStorage or so on, as described in Start 2.
First, let's create a bot that only receives “!ping” and returns “pong!”.
Chat
To receive messages, do the following.
client.on("message", (message) => {
...
});This is all that is needed to receive the message.
Easy, isn't it?
So first, let's retrieve the messages sent.
client.on("message", (message) => {
const text = message.text;
console.log(text);
});
client.listen();Your console should now show the message that was sent to you!
Hello EdamAmex
I love you! :DNext, let's check if the message is “!ping”.
client.on("message", (message) => {
const text = message.text;
if (text === "!ping") {
...
}
});This is perfect. Next time I need to reply.
To reply, you can call a method that sends a messageId with a relatedMessageId, but there is a more convenient way.
client.on("message", (message) => {
const text = message.text;
if (text === "!ping") {
message.reply("pong!");
}
});What a beautiful code! It's too easy. However, in this case, it is more beautiful to enclose it in an asynchronous function.
client.on("message", async (message) => {
const text = message.text;
if (text === "!ping") {
await message.reply("pong!");
}
});That's all!
There are also send, reaction, etc.
Let me explain all the methods in other chapters.
Edited messages
When a message is edited, LINE does not send it again through message. Listen to message:edit instead.
client.on("message:edit", (message) => {
console.log(message.raw.id, "was edited to:", message.text);
});The edited message keeps the id of the original message, so you can replace your cached copy by id. message.isEdited is true and message.updatedTime holds the time of the edit.
The event fires both when someone else edits a message and when you edit one from another device.
WARNING
Only receiving edits is supported. Editing a message from linejs is not implemented.
Square
So what should we do with Square (OpenChat)? Basically the same thing.
client.on("square:message", async (message) => {
const text = message.text;
if (text === "!ping") {
await message.reply("pong!");
}
});With this alone you can create a basic bot.
There are many more features!
Stay tuned for our next journey.
If you encounter problems, please refer to Question,
not only here.