Skip to content

Latest commit

 

History

History
339 lines (256 loc) · 10.1 KB

wechaty.md

File metadata and controls

339 lines (256 loc) · 10.1 KB

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)

Return the type of: 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)
})

wechaty.init()

Deprecated

use start instead

Kind: instance method of Wechaty

wechaty.start()

Return the type of: 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()

Return the type of: Promise.<void>

Stop the bot

Kind: instance method of Wechaty
Example

await bot.stop()

wechaty.logout()

Return the type of: Promise.<void>

Logout the bot

Kind: instance method of Wechaty
Example

await bot.logout()

wechaty.logonoff()

Return the type of: 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.self()

Deprecated

Should use userSelf instead

Kind: instance method of Wechaty

wechaty.userSelf()

Return the type of: ContactSelf

Get current user

Kind: instance method of Wechaty
Example

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

wechaty.say(textOrContactOrFile)

Return the type of: Promise.<void>

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)

wechaty.version([forceNpm])

Return the type of: string

Return version of Wechaty

Kind: instance method of Wechaty
Returns: string - - the version number

Param Type Default Description
[forceNpm] boolean false If set to true, will only return the version in package.json.
Otherwise will return git commit hash if .git exists.

Example

console.log(Wechaty.instance().version())       // return '#git[af39df]'
console.log(Wechaty.instance().version(true))   // return '0.7.9'

Wechaty.instance([options])

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()