- Wechaty
Main bot class.
A
Botis 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- Room
All wechat rooms(groups) will be encapsulated as a Room.
- Contact
All wechat contacts(friend) will be encapsulated as a Contact.
- Friendship
Send, receive friend request, and friend confirmation events.
- send request
- receive request(in friend event)
- confirmation friendship(friend event)
- Message
All wechat messages will be encapsulated as a Message.
- 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 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 .init()- .start() ⇒
Promise.<void> - .stop() ⇒
Promise.<void> - .logout() ⇒
Promise.<void> - .logonoff() ⇒
boolean .self()- .userSelf() ⇒
ContactSelf - .say(textOrContactOrFile) ⇒
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: string, code: number) => {
console.log(`[${code}] Scan ${url} to login.` )
})Example (Event:login )
# Login Event will emit when bot login full successful.
bot.on('login', (user: ContactSelf) => {
console.log(`user ${user} login`)
})Example (Event:logout )
# Logout Event will emit when bot detected log out.
bot.on('logout', (user: ContactSelf) => {
console.log(`user ${user} logout`)
})Example (Event:message )
# Message Event will emit when there's a new message.
wechaty.on('message', (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: 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: Room, inviteeList: Contact[], inviter: Contact) => {
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: Room, leaverList: Contact[]) => {
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: Room, topic: string, oldTopic: string, changer: Contact) => {
console.log(`Room ${room.topic()} topic changed from ${oldTopic} to ${topic} by ${changer.name()}`)
})Example (Event:error )
# error Event will emit when there's an error occurred.
bot.on('error', (error) => {
console.error(error)
})Deprecated
use start instead
Kind: instance method of Wechaty
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 hereStop 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')
}Deprecated
Should use userSelf instead
Kind: instance method of Wechaty
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.
Kind: instance method of Wechaty
| Param | Type | Description |
|---|---|---|
| textOrContactOrFile | string | Contact | FileBox |
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 = 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://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.fromLocal('/tmp/text.jpg')
await bot.say(fileBox)get the singleton 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() // Singleton
.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()All wechat rooms(groups) will be encapsulated as a Room.
Kind: global class
- Room
- instance
- .say(textOrContactOrFile, [mention]) ⇒
Promise.<void> - .on(event, listener) ⇒
this - .add(contact) ⇒
Promise.<void> - .del(contact) ⇒
Promise.<void> - .quit() ⇒
Promise.<void> - .topic([newTopic]) ⇒
Promise.<(string|void)> - .announce([text]) ⇒
Promise.<(void|string)> - .qrcode() ⇒
Promise.<string> - .alias(contact) ⇒
Promise.<(string|null)> - .roomAlias(contact) ⇒
Promise.<(string|null)> - .has(contact) ⇒
Promise.<boolean> - .memberAll(query) ⇒
Promise.<Array.<Contact>> - .member(queryArg) ⇒
Promise.<(null|Contact)> - .memberList() ⇒
Promise.<Array.<Contact>> - .sync() ⇒
Promise.<void> - .owner() ⇒
Contact|null
- .say(textOrContactOrFile, [mention]) ⇒
- static
- .create(contactList, [topic]) ⇒
Promise.<Room> - .findAll([query]) ⇒
Promise.<Array.<Room>> - .find(query) ⇒
Promise.<(Room|null)> - .load(id) ⇒
Room
- .create(contactList, [topic]) ⇒
- instance
Send message inside Room, if set [replyTo], wechaty will mention the contact as well.
Kind: instance method of Room
| Param | Type | Description |
|---|---|---|
| textOrContactOrFile | string | Contact | FileBox |
Send text or media file inside Room. You can use FileBox to send file |
| [mention] | Contact | Array.<Contact> |
Optional parameter, send content inside Room, and mention @replyTo contact or contactList. |
Example
const bot = new Wechaty()
await bot.start()
// after logged in...
const room = await bot.Room.find({topic: 'wechaty'})
# 1. Send text inside Room
await room.say('Hello world!')
# 2. Send media file inside Room
import { FileBox } from 'file-box'
const fileBox1 = FileBox.fromUrl('https://chatie.io/wechaty/images/bot-qr-code.png')
const fileBox2 = FileBox.fromLocal('/tmp/text.txt')
await room.say(fileBox1)
await room.say(fileBox2)
# 3. Send Contact Card in a room
const contactCard = await bot.Contact.find({name: 'lijiarui'}) // change 'lijiarui' to any of the room member
await room.say(contactCard)
# 4. Send text inside room and mention @mention contact
const contact = await bot.Contact.find({name: 'lijiarui'}) // change 'lijiarui' to any of the room member
await room.say('Hello world!', contact)Kind: instance method of Room
Returns: this - - this for chain
| Param | Type | Description |
|---|---|---|
| event | RoomEventName |
Emit WechatyEvent |
| listener | RoomEventFunction |
Depends on the WechatyEvent |
Example (Event:join )
const bot = new Wechaty()
await bot.start()
// after logged in...
const room = await bot.Room.find({topic: 'topic of your room'}) // change `event-room` to any room topic in your wechat
if (room) {
room.on('join', (room: Room, inviteeList: Contact[], inviter: Contact) => {
const nameList = inviteeList.map(c => c.name()).join(',')
console.log(`Room got new member ${nameList}, invited by ${inviter}`)
})
}Example (Event:leave )
const bot = new Wechaty()
await bot.start()
// after logged in...
const room = await bot.Room.find({topic: 'topic of your room'}) // change `event-room` to any room topic in your wechat
if (room) {
room.on('leave', (room: Room, leaverList: Contact[]) => {
const nameList = leaverList.map(c => c.name()).join(',')
console.log(`Room lost member ${nameList}`)
})
}Example (Event:topic )
const bot = new Wechaty()
await bot.start()
// after logged in...
const room = await bot.Room.find({topic: 'topic of your room'}) // change `event-room` to any room topic in your wechat
if (room) {
room.on('topic', (room: Room, topic: string, oldTopic: string, changer: Contact) => {
console.log(`Room topic changed from ${oldTopic} to ${topic} by ${changer.name()}`)
})
}Add contact in a room
Kind: instance method of Room
| Param | Type |
|---|---|
| contact | Contact |
Example
const bot = new Wechaty()
await bot.start()
// after logged in...
const contact = await bot.Contact.find({name: 'lijiarui'}) // change 'lijiarui' to any contact in your wechat
const room = await bot.Room.find({topic: 'wechat'}) // change 'wechat' to any room topic in your wechat
if (room) {
try {
await room.add(contact)
} catch(e) {
console.error(e)
}
}Delete a contact from the room It works only when the bot is the owner of the room
Kind: instance method of Room
| Param | Type |
|---|---|
| contact | Contact |
Example
const bot = new Wechaty()
await bot.start()
// after logged in...
const room = await bot.Room.find({topic: 'wechat'}) // change 'wechat' to any room topic in your wechat
const contact = await bot.Contact.find({name: 'lijiarui'}) // change 'lijiarui' to any room member in the room you just set
if (room) {
try {
await room.del(contact)
} catch(e) {
console.error(e)
}
}Bot quit the room itself
Kind: instance method of Room
Example
await room.quit()SET/GET topic from the room
Kind: instance method of Room
| Param | Type | Description |
|---|---|---|
| [newTopic] | string |
If set this para, it will change room topic. |
Example (When you say anything in a room, it will get room topic. )
const bot = new Wechaty()
bot
.on('message', async m => {
const room = m.room()
if (room) {
const topic = await room.topic()
console.log(`room topic is : ${topic}`)
}
})
.start()Example (When you say anything in a room, it will change room topic. )
const bot = new Wechaty()
bot
.on('message', async m => {
const room = m.room()
if (room) {
const oldTopic = await room.topic()
await room.topic('change topic to wechaty!')
console.log(`room topic change from ${oldTopic} to ${room.topic()}`)
}
})
.start()SET/GET announce from the room
Tips: It only works when bot is the owner of the room.
Kind: instance method of Room
| Param | Type | Description |
|---|---|---|
| [text] | string |
If set this para, it will change room announce. |
Example (When you say anything in a room, it will get room announce. )
const bot = new Wechaty()
await bot.start()
// after logged in...
const room = await bot.Room.find({topic: 'your room'})
const announce = await room.announce()
console.log(`room announce is : ${announce}`)Example (When you say anything in a room, it will change room announce. )
const bot = new Wechaty()
await bot.start()
// after logged in...
const room = await bot.Room.find({topic: 'your room'})
const oldAnnounce = await room.announce()
await room.announce('change announce to wechaty!')
console.log(`room announce change from ${oldAnnounce} to ${room.announce()}`)Get QR Code of the Room from the room, which can be used as scan and join the room.
Kind: instance method of Room
Return contact's roomAlias in the room, the same as roomAlias
Kind: instance method of Room
Returns: Promise.<(string|null)> - - If a contact has an alias in room, return string, otherwise return null
| Param | Type |
|---|---|
| contact | Contact |
Example
const bot = new Wechaty()
bot
.on('message', async m => {
const room = m.room()
const contact = m.from()
if (room) {
const alias = await room.alias(contact)
console.log(`${contact.name()} alias is ${alias}`)
}
})
.start()Same as function alias
Kind: instance method of Room
| Param | Type |
|---|---|
| contact | Contact |
Check if the room has member contact, the return is a Promise and must be await-ed
Kind: instance method of Room
Returns: Promise.<boolean> - Return true if has contact, else return false.
| Param | Type |
|---|---|
| contact | Contact |
Example (Check whether 'lijiarui' is in the room 'wechaty')
const bot = new Wechaty()
await bot.start()
// after logged in...
const contact = await bot.Contact.find({name: 'lijiarui'}) // change 'lijiarui' to any of contact in your wechat
const room = await bot.Room.find({topic: 'wechaty'}) // change 'wechaty' to any of the room in your wechat
if (contact && room) {
if (await room.has(contact)) {
console.log(`${contact.name()} is in the room wechaty!`)
} else {
console.log(`${contact.name()} is not in the room wechaty!`)
}
}Find all contacts in a room
namethe name-string set by user-self, should be called name, equal toContact.name()roomAliasthe name-string set by user-self in the room, should be called roomAliascontactAliasthe name-string set by bot for others, should be called alias, equal toContact.alias()
Kind: instance method of Room
| Param | Type | Description |
|---|---|---|
| query | RoomMemberQueryFilter | string |
When use memberAll(name:string), return all matched members, including name, roomAlias, contactAlias |
Find all contacts in a room, if get many, return the first one.
Kind: instance method of Room
| Param | Type | Description |
|---|---|---|
| queryArg | RoomMemberQueryFilter | string |
When use member(name:string), return all matched members, including name, roomAlias, contactAlias |
Example (Find member by name)
const bot = new Wechaty()
await bot.start()
// after logged in...
const room = await bot.Room.find({topic: 'wechaty'}) // change 'wechaty' to any room name in your wechat
if (room) {
const member = await room.member('lijiarui') // change 'lijiarui' to any room member in your wechat
if (member) {
console.log(`wechaty room got the member: ${member.name()}`)
} else {
console.log(`cannot get member in wechaty room!`)
}
}Example (Find member by MemberQueryFilter)
const bot = new Wechaty()
await bot.start()
// after logged in...
const room = await bot.Room.find({topic: 'wechaty'}) // change 'wechaty' to any room name in your wechat
if (room) {
const member = await room.member({name: 'lijiarui'}) // change 'lijiarui' to any room member in your wechat
if (member) {
console.log(`wechaty room got the member: ${member.name()}`)
} else {
console.log(`cannot get member in wechaty room!`)
}
}Get all room member from the room
Kind: instance method of Room
Example
await room.memberList()Force reload data for Room, Sync data for Room
Kind: instance method of Room
Example
await room.sync()room.owner() ⇒ Contact | null
Get room's owner from the room.
Kind: instance method of Room
Example
const owner = room.owner()Room.create(contactList, [topic]) ⇒ Promise.<Room>
Create a new room.
Kind: static method of Room
| Param | Type |
|---|---|
| contactList | Array.<Contact> |
| [topic] | string |
Example (Creat a room with 'lijiarui' and 'juxiaomi', the room topic is 'ding - created')
const helperContactA = await Contact.find({ name: 'lijiarui' }) // change 'lijiarui' to any contact in your wechat
const helperContactB = await Contact.find({ name: 'juxiaomi' }) // change 'juxiaomi' to any contact in your wechat
const contactList = [helperContactA, helperContactB]
console.log('Bot', 'contactList: %s', contactList.join(','))
const room = await Room.create(contactList, 'ding')
console.log('Bot', 'createDingRoom() new ding room created: %s', room)
await room.topic('ding - created')
await room.say('ding - created')Find room by by filter: {topic: string | RegExp}, return all the matched room
Kind: static method of Room
| Param | Type |
|---|---|
| [query] | RoomQueryFilter |
Example
const bot = new Wechaty()
await bot.start()
// after logged in
const roomList = await bot.Room.findAll() // get the room list of the bot
const roomList = await bot.Room.findAll({topic: 'wechaty'}) // find all of the rooms with name 'wechaty'Try to find a room by filter: {topic: string | RegExp}. If get many, return the first one.
Kind: static method of Room
Returns: Promise.<(Room|null)> - If can find the room, return Room, or return null
| Param | Type |
|---|---|
| query | RoomQueryFilter |
Example
const bot = new Wechaty()
await bot.start()
// after logged in...
const roomList = await bot.Room.find()
const roomList = await bot.Room.find({topic: 'wechaty'})Room.load(id) ⇒ Room
Load room by topic.
Tips: For Web solution, it cannot get the unique topic id, but for other solutions besides web, we can get unique and permanent topic id.
Kind: static method of Room
| Param | Type |
|---|---|
| id | string |
Example
const bot = new Wechaty()
await bot.start()
// after logged in...
const room = bot.Room.load('roomId')All wechat contacts(friend) will be encapsulated as a Contact.
Kind: global class
- Contact
- instance
- .say(textOrContactOrFile) ⇒
Promise.<void> - .name() ⇒
string - .alias(newAlias) ⇒
string|null|Promise.<boolean> .stranger()- .friend() ⇒
boolean|null .official().personal()- .type() ⇒
ContactType.Unknown|ContactType.Personal|ContactType.Official - .gender() ⇒
ContactGender.Unknown|ContactGender.Male|ContactGender.Female - .province() ⇒
string|null - .city() ⇒
string|null - .avatar() ⇒
Promise.<FileBox> .refresh()- .sync() ⇒
Promise.<this> - .self() ⇒
boolean
- .say(textOrContactOrFile) ⇒
- static
- .load(id) ⇒
Contact - .find(query) ⇒
Promise.<(Contact|null)> - .findAll([queryArg]) ⇒
Promise.<Array.<Contact>>
- .load(id) ⇒
- instance
Kind: instance method of Contact
| Param | Type | Description |
|---|---|---|
| textOrContactOrFile | string | Contact | FileBox |
send text, Contact, or file to contact. You can use FileBox to send file |
Example
const bot = new Wechaty()
await bot.start()
const contact = await bot.Contact.find({name: 'lijiarui'}) // change 'lijiarui' to any of your contact name in wechat
# 1. send text to contact
await contact.say('welcome to wechaty!')
# 2. send media file to contact
import { FileBox } from 'file-box'
const fileBox1 = FileBox.fromUrl('https://chatie.io/wechaty/images/bot-qr-code.png')
const fileBox2 = FileBox.fromLocal('/tmp/text.txt')
await contact.say(fileBox1)
await contact.say(fileBox2)
# 3. send contact card to contact
const contactCard = bot.Contact.load('contactId')
await contact.say(contactCard)Get the name from a contact
Kind: instance method of Contact
Example
const name = contact.name()GET / SET / DELETE the alias for a contact
Tests show it will failed if set alias too frequently(60 times in one minute).
Kind: instance method of Contact
| Param | Type |
|---|---|
| newAlias | none | string | null |
Example ( GET the alias for a contact, return {(string | null)})
const alias = contact.alias()
if (alias === null) {
console.log('You have not yet set any alias for contact ' + contact.name())
} else {
console.log('You have already set an alias for contact ' + contact.name() + ':' + alias)
}Example (SET the alias for a contact)
try {
await contact.alias('lijiarui')
console.log(`change ${contact.name()}'s alias successfully!`)
} catch (e) {
console.log(`failed to change ${contact.name()} alias!`)
}Example (DELETE the alias for a contact)
try {
const oldAlias = await contact.alias(null)
console.log(`delete ${contact.name()}'s alias successfully!`)
console.log('old alias is ${oldAlias}`)
} catch (e) {
console.log(`failed to delete ${contact.name()}'s alias!`)
}Deprecated
Should use friend instead
Kind: instance method of Contact
Check if contact is friend
Kind: instance method of Contact
Returns: boolean | null -
True for friend of the bot
False for not friend of the bot, null for unknown.
Example
const isFriend = contact.friend()Deprecated
Check if it's a offical account, should use type instead
Kind: instance method of Contact
Deprecated
Check if it's a personal account, should use type instead
Kind: instance method of Contact
Return the type of the Contact
Tips: ContactType is enum here.
Kind: instance method of Contact
Example
const bot = new Wechaty()
await bot.start()
const isOfficial = contact.type() === bot.Contact.Type.OfficialContact gender
Tips: ContactGender is enum here.
Kind: instance method of Contact
Example
const gender = contact.gender() === bot.Contact.Gender.MaleGet the region 'province' from a contact
Kind: instance method of Contact
Example
const province = contact.province()Get the region 'city' from a contact
Kind: instance method of Contact
Example
const city = contact.city()Get avatar picture file stream
Kind: instance method of Contact
Example
# Save avatar to local file like `1-name.jpg`
const file = await contact.avatar()
const name = file.name
await file.toFile(name, true)
console.log(`Contact: ${contact.name()} with avatar file: ${name}`)Deprecated
Force reload(re-ready()) data for Contact, use sync instead
Kind: instance method of Contact
Force reload(re-ready()) data for Contact,
Kind: instance method of Contact
Example
await contact.sync()Check if contact is self
Kind: instance method of Contact
Returns: boolean - True for contact is self, False for contact is others
Example
const isSelf = contact.self()Contact.load(id) ⇒ Contact
Get Contact by id
Kind: static method of Contact
| Param | Type |
|---|---|
| id | string |
Example
const bot = new Wechaty()
await bot.start()
const contact = bot.Contact.load('contactId')Try to find a contact by filter: {name: string | RegExp} / {alias: string | RegExp}
Find contact by name or alias, if the result more than one, return the first one.
Kind: static method of Contact
Returns: Promise.<(Contact|null)> - If can find the contact, return Contact, or return null
| Param | Type |
|---|---|
| query | ContactQueryFilter |
Example
const bot = new Wechaty()
await bot.start()
const contactFindByName = await bot.Contact.find({ name:"ruirui"} )
const contactFindByAlias = await bot.Contact.find({ alias:"lijiarui"} )Find contact by name or alias
If use Contact.findAll() get the contact list of the bot.
namethe name-string set by user-self, should be called namealiasthe name-string set by bot for others, should be called alias
Kind: static method of Contact
| Param | Type |
|---|---|
| [queryArg] | ContactQueryFilter |
Example
const bot = new Wechaty()
await bot.start()
const contactList = await bot.Contact.findAll() // get the contact list of the bot
const contactList = await bot.Contact.findAll({name: 'ruirui'}) // find allof the contacts whose name is 'ruirui'
const contactList = await bot.Contact.findAll({alias: 'lijiarui'}) // find all of the contacts whose alias is 'lijiarui'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()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()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!')
}All wechat messages will be encapsulated as a Message.
Kind: global class
- Message
- .from() ⇒
Contact - .to() ⇒
Contact|null - .room() ⇒
Room|null .content()- .text() ⇒
string - .say(textOrContactOrFile, [mention]) ⇒
Promise.<void> - .type() ⇒
MessageType - .self() ⇒
boolean - .mention() ⇒
Promise.<Array.<Contact>> .mentioned()- .forward(to) ⇒
Promise.<void> - .age() ⇒
number .file()- .toFileBox() ⇒
Promise.<FileBox> - .toContact() ⇒
Promise.<Contact>
- .from() ⇒
message.from() ⇒ Contact
Get the sender from a message.
Kind: instance method of Message
Example
const bot = new Wechaty()
bot
.on('message', async m => {
const contact = msg.from()
const text = msg.text()
const room = msg.room()
if (room) {
const topic = await room.topic()
console.log(`Room: ${topic} Contact: ${contact.name()} Text: ${text}`)
} else {
console.log(`Contact: ${contact.name()} Text: ${text}`)
}
})
.start()message.to() ⇒ Contact | null
Get the destination of the message Message.to() will return null if a message is in a room, use Message.room() to get the room.
Kind: instance method of Message
message.room() ⇒ Room | null
Get the room from the message.
If the message is not in a room, then will return null
Kind: instance method of Message
Example
const bot = new Wechaty()
bot
.on('message', async m => {
const contact = msg.from()
const text = msg.text()
const room = msg.room()
if (room) {
const topic = await room.topic()
console.log(`Room: ${topic} Contact: ${contact.name()} Text: ${text}`)
} else {
console.log(`Contact: ${contact.name()} Text: ${text}`)
}
})
.start()Deprecated
use text instead
Kind: instance method of Message
Get the text content of the message
Kind: instance method of Message
Example
const bot = new Wechaty()
bot
.on('message', async m => {
const contact = msg.from()
const text = msg.text()
const room = msg.room()
if (room) {
const topic = await room.topic()
console.log(`Room: ${topic} Contact: ${contact.name()} Text: ${text}`)
} else {
console.log(`Contact: ${contact.name()} Text: ${text}`)
}
})
.start()Reply a Text or Media File message to the sender.
Kind: instance method of Message
See: Examples/ding-dong-bot
| Param | Type | Description |
|---|---|---|
| textOrContactOrFile | string | Contact | FileBox |
send text, Contact, or file to bot. You can use FileBox to send file |
| [mention] | Contact | Array.<Contact> |
If this is a room message, when you set mention param, you can @ Contact in the room. |
Example
import { FileBox } from 'file-box'
const bot = new Wechaty()
bot
.on('message', async m => {
# 1. send Image
if (/^ding$/i.test(m.text())) {
const fileBox = FileBox.fromUrl('https://chatie.io/wechaty/images/bot-qr-code.png')
await msg.say(fileBox)
}
# 2. send Text
if (/^dong$/i.test(m.text())) {
await msg.say('dingdingding')
}
# 3. send Contact
if (/^lijiarui$/i.test(m.text())) {
const contactCard = await bot.Contact.find({name: 'lijiarui'})
if (!contactCard) {
console.log('not found')
return
}
await msg.say(contactCard)
}
})
.start()Get the type from the message.
Tips: MessageType is Enum here.
- MessageType.Unknown
- MessageType.Attachment
- MessageType.Audio
- MessageType.Contact
- MessageType.Emoticon
- MessageType.Image
- MessageType.Text
- MessageType.Video
Kind: instance method of Message
Example
const bot = new Wechaty()
if (message.type() === bot.Message.Type.Text) {
console.log('This is a text message')
}Check if a message is sent by self.
Kind: instance method of Message
Returns: boolean - - Return true for send from self, false for send from others.
Example
if (message.self()) {
console.log('this message is sent by myself!')
}Get message mentioned contactList.
Message event table as follows
| Web | Mac PC Client | iOS Mobile | android Mobile | |
|---|---|---|---|---|
| [You were mentioned] tip ([有人@我]的提示) | ✘ | √ | √ | √ |
| Identify magic code (8197) by copy & paste in mobile | ✘ | √ | √ | ✘ |
| Identify magic code (8197) by programming | ✘ | ✘ | ✘ | ✘ |
| Identify two contacts with the same roomAlias by [You were mentioned] tip | ✘ | ✘ | √ | √ |
Kind: instance method of Message
Returns: Promise.<Array.<Contact>> - - Return message mentioned contactList
Example
const contactList = await message.mention()
console.log(contactList)Deprecated
should use mention instead
Kind: instance method of Message
Forward the received message.
Kind: instance method of Message
| Param | Type | Description |
|---|---|---|
| to | Sayable | Array.<Sayable> |
Room or Contact The recipient of the message, the room, or the contact |
Example
const bot = new Wechaty()
bot
.on('message', async m => {
const room = await bot.Room.find({topic: 'wechaty'})
if (room) {
await m.forward(room)
console.log('forward this message to wechaty room!')
}
})
.start()Returns the message age in seconds.
For example, the message is sent at time 8:43:01,
and when we received it in Wechaty, the time is 8:43:15,
then the age() will return 8:43:15 - 8:43:01 = 14 (seconds)
Kind: instance method of Message
Deprecated
use toFileBox instead
Kind: instance method of Message
Extract the Media File from the Message, and put it into the FileBox.
Kind: instance method of Message
message.toContact() ⇒ Promise.<Contact>
Get Share Card of the Message Extract the Contact Card from the Message, and encapsulate it into Contact class
Kind: instance method of Message
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 |
|---|---|---|
| wechat4u | string |
The default puppet, using the wechat4u to control the WeChat Web API via a chrome browser. |
| padchat | string |
- Using the WebSocket protocol to connect with a Protocol Server for controlling the iPad Wechat program. |
| puppeteer | string |
- Using the google puppeteer to control the WeChat Web API via a chrome browser. |
| 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 |
|---|---|---|
| profile | string |
Wechaty 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 |
| puppet | PuppetName | 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. |
| friend | string |
When someone sends you a friend request, there will be a Wechaty friend event fired. |
| message | string |
Emit when there's a new message. |
| 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. |
| 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 |
| 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 |
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 |