跳到主要内容

Dealing with message

Messages

Automation of messages can be done easily with wechaty onMessage function. This guide will give you a step by step overview of how to respond to self messages or messages in a room.

Prerequisites

  • Your system must have Node.js installed (version >= 16).
  • Your system must have Wechaty (version >= 0.40).
  • You need to be familiar with the basics of Wechaty platform. If not, follow our tutorials section.
  • You need to have at least a minimal application ready to work, follow one of our Example/Ding-dong-bot.

If you don't know where to start from

See Running our first ding-dong bot.

There are various message type such as MessageType.Text, MessageType.Image, MessageType.Video, MessageType.Url, MessageType.Emotions, MessageType.Attachment. Some of the function are mentioned below and require a basic script that can help run the bot. The basic script starts by importing the code from Github/Ding-dong-bot.Integrate the below code, for this action to work.

Mention

Use this Mention feature to send a (@ mention) to others in the room.This function works if the message received by the onMessage function belongs to a room.

import { Message } from 'wechaty'

async function onMessage(message: Message): Promise<void> {
if (await message.mentionSelf()) {
const room = message.room()
if (!room) {
throw new Error('Should never reach here: a mention message must in a room')
}

console.info(message.text())
// "@bot Hello"
console.info(await message.mentionList())
// [bot]
console.info(await message.mentionText())
// "Hello"

const talker = room.talker()
await room.say`Thanks for mention me! ${talker}`
}
}

bot.on('message', onMessage)

The expected output of the JavaScript code is: Message

Self message

Use this Self message feature to reply to the bot.This function works if the message received by the onMessage function has been sent by the bot to itself.

import { Message } from 'wechaty'

async function onMessage(message: Message): Promise<void> {
if (message.self()) {
const talker = message.talker()
const bot = message.wechaty.userSelf()
assert(talker === bot, 'Message is sent from bot')
console.info('Message is sent from bot')
}
}

bot.on('message', onMessage)

The expected output of the JavaScript code is: Message