Skip to main content

Wechaty

Main bot class, A Bot is a wechat client depends on which puppet you use.

Classes

Wechaty

Main bot class.

A Bot is a wechat client depends on which puppet you use. It may equals

See more:

If you want to know how to send message, see Message
If you want to know how to get contact, see Contact

Typedefs

PuppetName

The term Puppet in Wechaty is an Abstract Class for implementing protocol plugins. The plugins are the component that helps Wechaty to control the Wechat(that's the reason we call it puppet). The plugins are named PuppetXXX, for example:

WechatyOptions

The option parameter to create a wechaty instance WechatyEventName

Wechaty Class Event Type WechatyEventFunction

Wechaty Class Event Function

Wechaty

Main bot class.

A Bot is a wechat client depends on which puppet you use. It may equals

See more:

If you want to know how to send message, see Message
If you want to know how to get contact, see Contact

Kind: global class

new Wechaty([options])

Creates an instance of Wechaty.

ParamTypeDefault
[options]WechatyOptions{}

Example (The World's Shortest ChatBot Code: 6 lines of JavaScript)

import { Wechaty }  from 'wechaty'
const bot = new Wechaty()
bot.on('scan', (qrcode, status) => console.log(['https://api.qrserver.com/v1/create-qr-code/?data=',encodeURIComponent(qrcode),'&size=220x220&margin=20',].join('')))
bot.on('login', user => console.log(`User ${user} logined`))
bot.on('message', message => console.log(`Message: ${message}`))
bot.start()

wechaty.on(event, listener)Wechaty

When the bot get message, it will emit the following Event.

You can do anything you want when in these events functions. The main Event name as follows:

  • scan: Emit when the bot needs to show you a QR Code for scanning. After scan the qrcode, you can login
  • login: Emit when bot login full successful.
  • logout: Emit when bot detected log out.
  • message: Emit when there's a new message.

see more in WechatyEventName

Kind: instance method of Wechaty
Returns: Wechaty - - this for chaining, see advanced chaining usage

ParamTypeDescription
eventWechatyEventNameEmit WechatyEvent
listenerWechatyEventFunctionDepends on the WechatyEvent

Example (Event:scan)

// Scan Event will emit when the bot needs to show you a QR Code for scanning

bot.on('scan', (url, code) => {
console.log(`[${code}] Scan ${url} to login.` )
})

Example (Event:login )

// Login Event will emit when bot login full successful.

bot.on('login', (user) => {
console.log(`user ${user} login`)
})

Example (Event:logout )

// Logout Event will emit when bot detected log out.

bot.on('logout', (user) => {
console.log(`user ${user} logout`)
})

Example (Event:message )

// Message Event will emit when there's a new message.

wechaty.on('message', (message) => {
console.log(`message ${message} received`)
})

Example (Event:friendship )

// Friendship Event will emit when got a new friend request, or friendship is confirmed.

bot.on('friendship', async (friendship) => {
const contact = friendship.contact()
if (friendship.type() === bot.Friendship.Type.Receive) { // 1. receive new friendship request from new contact
let result = await friendship.accept()
if (result) {
console.log(`Request from ${contact.name()} is accept succesfully!`)
} else {
console.log(`Request from ${contact.name()} failed to accept!`)
}
} else if (friendship.type() === bot.Friendship.Type.Confirm) { // 2. confirm friendship
console.log(`New friendship confirmed with ${contact.name()}`)
}
})

Example (Event:room-join )

// room-join Event will emit when someone join the room.

bot.on('room-join', async (room, inviteeList, inviter) => {
const nameList = inviteeList.map(c => c.name()).join(',')
console.log(`Room ${await room.topic()} got new member ${nameList}, invited by ${inviter}`)
})

Example (Event:room-leave )

// room-leave Event will emit when someone leave the room.

bot.on('room-leave', async (room, leaverList, remover) => {
const nameList = leaverList.map(c => c.name()).join(',')
console.log(`Room ${await room.topic()} lost member ${nameList}, the remover is: ${remover}`)
})

Example (Event:room-topic )

// room-topic Event will emit when someone change the room's topic.

bot.on('room-topic', async (room, topic, oldTopic, changer) => {
console.log(`Room ${await room.topic()} topic changed from ${oldTopic} to ${topic} by ${changer.name()}`)
})

Example (Event:room-invite, RoomInvitation has been encapsulated as a RoomInvitation Class. )

// room-invite Event will emit when there's an room invitation.

bot.on('room-invite', async roomInvitation => {
try {
console.log(`received room-invite event.`)
await roomInvitation.accept()
} catch (e) {
console.error(e)
}
}

Example (Event:error )

// error Event will emit when there's an error occurred.

bot.on('error', (error) => {
console.error(error)
})

wechaty.start()Promise <void>

When you start the bot, bot will begin to login, need you wechat scan qrcode to login

Tips: All the bot operation needs to be triggered after start() is done

Kind: instance method of Wechaty

Example

await bot.start()
// do other stuff with bot here

wechaty.stop()Promise <void>

Stop the bot

Kind: instance method of Wechaty

Example

await bot.stop()

wechaty.logout()Promise <void>

Logout the bot

Kind: instance method of Wechaty

Example

await bot.logout()

wechaty.logonoff()boolean

Get the logon / logoff state

Kind: instance method of Wechaty

Example

if (bot.logonoff()) {
console.log('Bot logined')
} else {
console.log('Bot not logined')
}

wechaty.userSelf()ContactSelf

Get current user

Kind: instance method of Wechaty

Example

const contact = bot.userSelf()
console.log(`Bot is ${contact.name()}`)

wechaty.say(textOrContactOrFileOrUrl)Promise <void>

Send message to userSelf, in other words, bot send message to itself.

Tips: This function is depending on the Puppet Implementation, see puppet-compatible-table

Kind: instance method of Wechaty

ParamTypeDescription
textOrContactOrFileOrUrlstring | Contact | FileBox | UrlLinksend text, Contact, file or Link to bot. </br> You can use FileBox to send file

Example

const bot = new Wechaty()
await bot.start()
// after logged in

// 1. send text to bot itself
await bot.say('hello!')

// 2. send Contact to bot itself
const contact = bot.Contact.load('contactId')
await bot.say(contact)

// 3. send Image to bot itself from remote url
import { FileBox } from 'file-box'
const fileBox = FileBox.fromUrl('https://wechaty.github.io/wechaty/images/bot-qr-code.png')
await bot.say(fileBox)

// 4. send Image to bot itself from local file
import { FileBox } from 'file-box'
const fileBox = FileBox.fromFile('/tmp/text.jpg')
await bot.say(fileBox)

// 5. send Link to bot itself
const linkPayload = new UrlLink({
description : 'WeChat Bot SDK for Individual Account, Powered by TypeScript, Docker, and Love',
thumbnailUrl: 'https://avatars0.githubusercontent.com/u/25162437?s=200&v=4',
title : 'Welcome to Wechaty',
url : 'https://github.com/wechaty/wechaty',
})
await bot.say(linkPayload)

Wechaty.instance([options])

Get the global instance of Wechaty

Kind: static method of Wechaty

ParamTypeDefault
[options]WechatyOptions{}

Example (The World's Shortest ChatBot Code: 6 lines of JavaScript)

import { Wechaty }  from 'wechaty'

Wechaty.instance() // Global instance
.on('scan', (url, code) => console.log(`Scan QR Code to login: ${code}\n${url}`))
.on('login', user => console.log(`User ${user} logined`))
.on('message', message => console.log(`Message: ${message}`))
.start()

PuppetName

The term Puppet in Wechaty is an Abstract Class for implementing protocol plugins. The plugins are the component that helps Wechaty to control the Wechat(that's the reason we call it puppet). The plugins are named PuppetXXX, for example:

Kind: global typedef
Properties

NameTypeDescription
wechat4ustringThe default puppet, using the wechat4u to control the WeChat Web API via a chrome browser.
padchatstring- Using the WebSocket protocol to connect with a Protocol Server for controlling the iPad Wechat program.
puppeteerstring- Using the google puppeteer to control the WeChat Web API via a chrome browser.
mockstring- Using the mock data to mock wechat operation, just for test.

WechatyOptions

The option parameter to create a wechaty instance

Kind: global typedef
Properties

NameTypeDescription
profilestringWechaty Name. When you set this: new Wechaty({profile: 'wechatyName'}) it will generate a file called wechatyName.memory-card.json. This file stores the bot's login information. If the file is valid, the bot can auto login so you don't need to scan the qrcode to login again. Also, you can set the environment variable for WECHATY_PROFILE to set this value when you start. eg: WECHATY_PROFILE="your-cute-bot-name" node bot.js. This field is deprecated, please use name instead. see more
puppetPuppetModuleName | PuppetPuppet name or instance
puppetOptionsPartial.Puppet TOKEN
ioTokenstringIo TOKEN

WechatyEventName

Wechaty Class Event Type

Kind: global typedef
Properties

NameTypeDescription
errorstringWhen the bot get error, there will be a Wechaty error event fired.
loginstringAfter the bot login full successful, the event login will be emitted, with a Contact of current logined user.
logoutstringLogout will be emitted when bot detected log out, with a Contact of the current login user.
heartbeatstringGet bot's heartbeat.
friendshipstringWhen someone sends you a friend request, there will be a Wechaty friendship event fired.
messagestringEmit when there's a new message.
readystringEmit when all data has load completed, in wechaty-puppet-padchat, it means it has sync Contact and Room completed
room-joinstringEmit when anyone join any room.
room-topicstringGet topic event, emitted when someone change room topic.
room-leavestringEmit when anyone leave the room.
room-invitestringEmit when there is a room invitation, see more in RoomInvitation If someone leaves the room by themselves, wechat will not notice other people in the room, so the bot will never get the "leave" event.
scanstringA scan event will be emitted when the bot needs to show you a QR Code for scanning. </br> It is recommend to install qrcode-terminal(run npm install qrcode-terminal) in order to show qrcode in the terminal.

WechatyEventFunction

Wechaty Class Event Function

Kind: global typedef
Properties

NameTypeDescription
errorfunction(this: Wechaty, error: Error) => void callback function
loginfunction(this: Wechaty, user: ContactSelf)=> void
logoutfunction(this: Wechaty, user: ContactSelf) => void
scanfunction(this: Wechaty, url: string, code: number) => void
heartbeatfunction(this: Wechaty, data: any) => void
friendshipfunction(this: Wechaty, friendship: Friendship) => void
messagefunction(this: Wechaty, message: Message) => void
readyfunction(this: Wechaty) => void
room-joinfunction(this: Wechaty, room: Room, inviteeList: Contact[], inviter: Contact) => void
room-topicfunction(this: Wechaty, room: Room, newTopic: string, oldTopic: string, changer: Contact) => void
room-leavefunction(this: Wechaty, room: Room, leaverList: Contact[]) => void
room-invitefunction(this: Wechaty, room: Room, leaverList: Contact[]) => void see more in RoomInvitation