wechaty

WeChat Bot SDK for Individual Account, Powered by TypeScript, Docker, and πŸ’–

View the Project on GitHub Chatie/wechaty

Wechaty v0.27.39 Documentation

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

ContactSelf

Bot itself will be encapsulated as a ContactSelf.

Tips: this class is extends Contact

Friendship

Send, receive friend request, and friend confirmation events.

  1. send request
  2. receive request(in friend event)
  3. confirmation friendship(friend event)

Examples/Friend-Bot

Typedefs

PuppetModuleName

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 XXXPuppet, for example:

WechatyOptions

The option parameter to create a wechaty instance

WechatyEventName

Wechaty Class Event Type

WechatyEventFunction

Wechaty Class Event Function

RoomQueryFilter

The filter to find the room: {topic: string | RegExp}

RoomEventName

Room Class Event Type

RoomEventFunction

Room Class Event Function

RoomMemberQueryFilter

The way to search member by Room.member()

ContactQueryFilter

The way to search Contact

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.

Param Type Default
[options] WechatyOptions {}

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

const { Wechaty } = require('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:

see more in WechatyEventName

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

Param Type Description
event WechatyEventName Emit WechatyEvent
listener WechatyEventFunction Depends 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, status) => {
  console.log(`[${status}] 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', (friendship) => {
  if(friendship.type() === Friendship.Type.Receive){ // 1. receive new friendship request from new contact
    const contact = friendship.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() === 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', (room, inviteeList, inviter) => {
  const nameList = inviteeList.map(c => c.name()).join(',')
  console.log(`Room ${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', (room, leaverList) => {
  const nameList = leaverList.map(c => c.name()).join(',')
  console.log(`Room ${room.topic()} lost member ${nameList}`)
})

Example (Event:room-topic )

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

bot.on('room-topic', (room, topic, oldTopic, changer) => {
  console.log(`Room ${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

Param Type Description
textOrContactOrFileOrUrl string | Contact | FileBox | UrlLink send text, Contact, or file 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 = await bot.Contact.find()
await bot.say(contact)

// 3. send Image to bot itself from remote url
import { FileBox }  from 'file-box'
const fileBox = FileBox.fromUrl('https://chatie.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/chatie/wechaty',
})
await bot.say(linkPayload)

Wechaty.instance([options])

Get the global instance of Wechaty

Kind: static method of Wechaty

Param Type Default
[options] WechatyOptions {}

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

const { Wechaty } = require('wechaty')

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

ContactSelf

Bot itself will be encapsulated as a ContactSelf.

Tips: this class is extends Contact

Kind: global class

contactSelf.avatar([file]) β‡’ Promise.<(void\|FileBox)>

GET / SET bot avatar

Kind: instance method of ContactSelf

Param Type
[file] FileBox

Example ( GET the avatar for bot, return {Promise<FileBox>})

// Save avatar to local file like `1-name.jpg`

bot.on('login', (user: ContactSelf) => {
  console.log(`user ${user} login`)
  const file = await user.avatar()
  const name = file.name
  await file.toFile(name, true)
  console.log(`Save bot avatar: ${contact.name()} with avatar file: ${name}`)
})

Example (SET the avatar for a bot)

import { FileBox }  from 'file-box'
bot.on('login', (user: ContactSelf) => {
  console.log(`user ${user} login`)
  const fileBox = FileBox.fromUrl('https://chatie.io/wechaty/images/bot-qr-code.png')
  await user.avatar(fileBox)
  console.log(`Change bot avatar successfully!`)
})

contactSelf.qrcode() β‡’ Promise.<string>

Get bot qrcode

Kind: instance method of ContactSelf
Example

import { generate } from 'qrcode-terminal'
bot.on('login', (user: ContactSelf) => {
  console.log(`user ${user} login`)
  const qrcode = await user.qrcode()
  console.log(`Following is the bot qrcode!`)
  generate(qrcode, { small: true })
})

contactSelf.signature(signature)

Change bot signature

Kind: instance method of ContactSelf

Param Description
signature The new signature that the bot will change to

Example

bot.on('login', async user => {
  console.log(`user ${user} login`)
  try {
    await user.signature(`Signature changed by wechaty on ${new Date()}`)
  } catch (e) {
    console.error('change signature failed', e)
  }
})

Friendship

Send, receive friend request, and friend confirmation events.

  1. send request
  2. receive request(in friend event)
  3. confirmation friendship(friend event)

Examples/Friend-Bot

Kind: global class

friendship.accept() β‡’ Promise.<void>

Accept Friend Request

Kind: instance method of Friendship
Example

const bot = new Wechaty()
bot.on('friendship', async friendship => {
  try {
    console.log(`received friend event.`)
    switch (friendship.type()) {

    // 1. New Friend Request

    case Friendship.Type.Receive:
      await friendship.accept()
      break

    // 2. Friend Ship Confirmed

    case Friendship.Type.Confirm:
      console.log(`friend ship confirmed`)
      break
    }
  } catch (e) {
    console.error(e)
  }
}
.start()

friendship.hello() β‡’ string

Get verify message from

Kind: instance method of Friendship
Example (If request content is `ding`, then accept the friendship)

const bot = new Wechaty()
bot.on('friendship', async friendship => {
  try {
    console.log(`received friend event from ${friendship.contact().name()}`)
    if (friendship.type() === Friendship.Type.Receive && friendship.hello() === 'ding') {
      await friendship.accept()
    }
  } catch (e) {
    console.error(e)
  }
}
.start()

friendship.contact() β‡’ Contact

Get the contact from friendship

Kind: instance method of Friendship
Example

const bot = new Wechaty()
bot.on('friendship', async friendship => {
  const contact = friendship.contact()
  const name = contact.name()
  console.log(`received friend event from ${name}`)
}
.start()

friendship.type() β‡’ FriendshipType

Return the Friendship Type

Tips: FriendshipType is enum here. </br>

  • FriendshipType.Unknown </br>
  • FriendshipType.Confirm </br>
  • FriendshipType.Receive </br>
  • FriendshipType.Verify </br>

Kind: instance method of Friendship
Example (If request content is `ding`, then accept the friendship)

const bot = new Wechaty()
bot.on('friendship', async friendship => {
  try {
    if (friendship.type() === Friendship.Type.Receive && friendship.hello() === 'ding') {
      await friendship.accept()
    }
  } catch (e) {
    console.error(e)
  }
}
.start()

Friendship.send()

Deprecated

use Friendship#add instead

Kind: static method of Friendship

Friendship.add(contact, hello) β‡’ Promise.<void>

Send a Friend Request to a contact with message hello.

The best practice is to send friend request once per minute. Remeber not to do this too frequently, or your account may be blocked.

Kind: static method of Friendship

Param Type Description
contact Contact Send friend request to contact
hello string The friend request content

Example

const memberList = await room.memberList()
for (let i = 0; i < memberList.length; i++) {
  await bot.Friendship.add(member, 'Nice to meet you! I am wechaty bot!')
}

PuppetModuleName

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 XXXPuppet, for example:

Kind: global typedef
Properties

Name Type Description
PUPPET_DEFAULT string The default puppet.
wechaty-puppet-wechat4u string The default puppet, using the wechat4u to control the WeChat Web API via a chrome browser.
wechaty-puppet-padchat string - Using the WebSocket protocol to connect with a Protocol Server for controlling the iPad Wechat program.
wechaty-puppet-puppeteer string - Using the google puppeteer to control the WeChat Web API via a chrome browser.
wechaty-puppet-mock string - Using the mock data to mock wechat operation, just for test.

WechatyOptions

The option parameter to create a wechaty instance

Kind: global typedef
Properties

Name Type Description
name string Wechaty Name. </br> When you set this: </br> new Wechaty({name: 'wechaty-name'}) </br> it will generate a file called wechaty-name.memory-card.json. </br> This file stores the bot’s login information. </br> If the file is valid, the bot can auto login so you don’t need to scan the qrcode to login again. </br> Also, you can set the environment variable for WECHATY_NAME to set this value when you start. </br> eg: WECHATY_NAME="your-cute-bot-name" node bot.js
puppet PuppetModuleName | Puppet Puppet name or instance
puppetOptions Partial.<PuppetOptions> Puppet TOKEN
ioToken string Io TOKEN

WechatyEventName

Wechaty Class Event Type

Kind: global typedef
Properties

Name Type Description
error string When the bot get error, there will be a Wechaty error event fired.
login string After the bot login full successful, the event login will be emitted, with a Contact of current logined user.
logout string Logout will be emitted when bot detected log out, with a Contact of the current login user.
heartbeat string Get bot’s heartbeat.
friendship string When someone sends you a friend request, there will be a Wechaty friendship event fired.
message string Emit when there’s a new message.
ready string Emit when all data has load completed, in wechaty-puppet-padchat, it means it has sync Contact and Room completed
room-join string Emit when anyone join any room.
room-topic string Get topic event, emitted when someone change room topic.
room-leave string Emit when anyone leave the room.
- 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.
room-invite string Emit when there is a room invitation, see more in RoomInvitation
scan string A 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

Name Type Description
error function (this: Wechaty, error: Error) => void callback function
login function (this: Wechaty, user: ContactSelf)=> void
logout function (this: Wechaty, user: ContactSelf) => void
scan function (this: Wechaty, url: string, code: number) => void
<ol> <li>URL: {String} the QR code image URL</li> <li>code: {Number} the scan status code. some known status of the code list here is:</li> </ol> <ul> <li>0 initial_</li> <li>200 login confirmed</li> <li>201 scaned, wait for confirm</li> <li>408 waits for scan</li> </ul>
heartbeat function (this: Wechaty, data: any) => void
friendship function (this: Wechaty, friendship: Friendship) => void
message function (this: Wechaty, message: Message) => void
ready function (this: Wechaty) => void
room-join function (this: Wechaty, room: Room, inviteeList: Contact[], inviter: Contact) => void
room-topic function (this: Wechaty, room: Room, newTopic: string, oldTopic: string, changer: Contact) => void
room-leave function (this: Wechaty, room: Room, leaverList: Contact[]) => void
room-invite function (this: Wechaty, room: Room, leaverList: Contact[]) => void
see more in RoomInvitation

RoomQueryFilter

The filter to find the room: {topic: string | RegExp}

Kind: global typedef
Properties

Name Type
topic string

RoomEventName

Room Class Event Type

Kind: global typedef
Properties

Name Type Description
join string Emit when anyone join any room.
topic string Get topic event, emitted when someone change room topic.
leave string Emit when anyone leave the room.
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.

RoomEventFunction

Room Class Event Function

Kind: global typedef
Properties

Name Type Description
room-join function (this: Room, inviteeList: Contact[] , inviter: Contact) => void
room-topic function (this: Room, topic: string, oldTopic: string, changer: Contact) => void
room-leave function (this: Room, leaver: Contact) => void

RoomMemberQueryFilter

The way to search member by Room.member()

Kind: global typedef
Properties

Name Type Description
name string Find the contact by wechat name in a room, equal to Contact.name().
roomAlias string Find the contact by alias set by the bot for others in a room.
contactAlias string Find the contact by alias set by the contact out of a room, equal to Contact.alias(). More Detail

ContactQueryFilter

The way to search Contact

Kind: global typedef
Properties

Name Type Description
name string The name-string set by user-self, should be called name
alias string The name-string set by bot for others, should be called alias More Detail