- Blog - https://blog.chatie.io
- Docs - https://docs.chatie.io
- Wechaty
Main bot class.
A
Bot
is a wechat client depends on which puppet you use. It may equals- web-wechat, when you use: puppet-puppeteer/puppet-wechat4u
- ipad-wechat, when you use: puppet-padchat
- ios-wechat, when you use: puppet-ioscat
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.
- send request
- receive request(in friend event)
- confirmation friendship(friend event)
- 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
Main bot class.
A Bot
is a wechat client depends on which puppet you use.
It may equals
- web-wechat, when you use: puppet-puppeteer/puppet-wechat4u
- ipad-wechat, when you use: puppet-padchat
- ios-wechat, when you use: puppet-ioscat
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
- Wechaty
- new Wechaty([options])
- instance
- .on(event, listener) ⇒
Wechaty
- .start() ⇒
Promise.<void>
- .stop() ⇒
Promise.<void>
- .logout() ⇒
Promise.<void>
- .logonoff() ⇒
boolean
- .userSelf() ⇒
ContactSelf
- .say(textOrContactOrFileOrUrlOrMini) ⇒
Promise.<void>
- .on(event, listener) ⇒
- static
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:
- 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
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)
})
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
Stop the bot
Kind: instance method of Wechaty
Example
await bot.stop()
Logout the bot
Kind: instance method of Wechaty
Example
await bot.logout()
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()}`)
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 |
---|---|---|
textOrContactOrFileOrUrlOrMini | string | Contact | FileBox | UrlLink | MiniProgram |
send text, Contact, or file to bot. 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)
// 6. send MiniProgram to bot itself
const miniProgramPayload = new MiniProgram ({
username : 'gh_xxxxxxx', //get from mp.weixin.qq.com
appid : '', //optional, get from mp.weixin.qq.com
title : '', //optional
pagepath : '', //optional
description : '', //optional
thumbnailurl : '', //optional
})
await bot.say(miniProgramPayload)
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()
Bot itself will be encapsulated as a ContactSelf.
Tips: this class is extends Contact
Kind: global class
- ContactSelf
- .avatar([file]) ⇒
Promise.<(void|FileBox)>
- .qrcode() ⇒
Promise.<string>
- .signature(signature)
- .avatar([file]) ⇒
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!`)
})
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 })
})
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)
}
})
Send, receive friend request, and friend confirmation events.
- send request
- receive request(in friend event)
- confirmation friendship(friend event)
Kind: global class
- Friendship
- instance
- .accept() ⇒
Promise.<void>
- .hello() ⇒
string
- .contact() ⇒
Contact
- .type() ⇒
FriendshipType
- .accept() ⇒
- static
.send()- .add(contact, hello) ⇒
Promise.<void>
- instance
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()
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()
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()
Return the Friendship Type
Tips: FriendshipType is enum here.
- FriendshipType.Unknown
- FriendshipType.Confirm
- FriendshipType.Receive
- FriendshipType.Verify
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()
Deprecated
use Friendship#add instead
Kind: static method of Friendship
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!')
}
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. |
The option parameter to create a wechaty instance
Kind: global typedef
Properties
Name | Type | Description |
---|---|---|
name | string |
Wechaty Name. When you set this: new Wechaty({name: 'wechaty-name'}) it will generate a file called wechaty-name.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_NAME to set this value when you start. 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 |
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. It is recommend to install qrcode-terminal(run npm install qrcode-terminal ) in order to show qrcode in the terminal. |
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
|
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 |
The filter to find the room: {topic: string | RegExp}
Kind: global typedef
Properties
Name | Type |
---|---|
topic | string |
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. |
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 |
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 |
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 |