Wechaty

一个Wechaty 代表着一个微信的客户端,他取决于你具体使用哪一个Puppet

简介

根据你选择的Puppet的不同,Bot 可能等于下面中的一个客户端,不同的Puppet 代表的我们对微信协议的不同实现方式, Puppet的英文意思是傀儡, 很形象的描述了我们希望Puppet做的事情:帮助 Wechaty 来控制微信的操作。

了解更多:

如果你希望先了解如何发送消息,点击下面

如果你希望先了解如何操作微信联系人,点击下面

如果你希望先了解如何操作微信群,点击下面

Wechaty

Kind: global class

new Wechaty([options])

创建一个 Wechaty 的实例,默认使用Web 的方式,切换到iPad 的方式,参数设置请查看示例代码

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

注意,new Wechaty() 是可以传参数的

使用网页版本的场景

  • 这里name 是用来存储登录信息的,和Wechaty.instance({name: 'XX'}) 的作用是一样的。 查看详情.

const bot = new Wechaty({ name: 'your-bot-name' })

使用iPad 版本的场景

  • 当不使用web 版本的时候,需要定义你需要用什么样的方式接入,通过定义puppet名字的方式确定接入方式,这里是wechaty-puppet-padchat

  • puppetOptions 在这里是用来传递token的,按照下面代码示例传入即可。

const WECHATY_PUPPET_PADCHAT_TOKEN = 'your-token-here'

const puppet = 'wechaty-puppet-padchat' // 使用ipad 的方式接入。

const puppetOptions = {
  token: WECHATY_PUPPET_PADCHAT_TOKEN,
}

const bot = new Wechaty({
  name: 'your-bot-name'
  puppet,
  puppetOptions,
})
  • 上述的puppet 和 token 也可以不写进代码里面,通过环境变量来传递,如在命令行中运行:

WECHATY_PUPPET_PADCHAT_TOKEN=你的token WECHATY_PUPPET=padchat node bot.js

wechaty.on(event, listener) ⇒ Wechaty

当机器人收到消息,会触发一个事件,一些简单的事件介绍如下:

  • scan: 当机器人需要扫码登录的时候,会触发这个事件,当手机扫码登录后,机器人就可以登录进去了。

  • login: 当机器人登陆成功后,会触发这个事件。

  • logout: 当机器人退出登陆的时候,会触发到这个事件。

  • message: 当有新消息的时候会触发这个事件。

初次之外,wechaty还有一些群相关的事件,了解更多:WechatyEventName

你可以在这些时间的方法中自定义你希望的所有逻辑。​

Kind: instance method of Wechaty

Returns: Wechaty - - this for chaining, see advanced chaining usage

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', (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.

启动机器人

机器人所有的操作必须在这个函数执行完成之后。

Kind: instance method of Wechaty Example

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

wechaty.stop() ⇒ Promise.

停止机器人

Kind: instance method of Wechaty Example

await bot.stop()

wechaty.logout() ⇒ Promise.

登出机器人

Kind: instance method of Wechaty Example

await bot.logout()

wechaty.logonoff() ⇒ boolean

获取机器人logon/logoff 的状态

Kind: instance method of Wechaty Example

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

wechaty.userSelf() ⇒ ContactSelf

获取当前机器人的所有信息

Kind: instance method of Wechaty Example

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

wechaty.say(textOrContactOrFileOrUrl) ⇒ Promise.

机器人自己给自己发消息。

这个函数是否能成功调用,取决于你使用了哪一种Puppet 的实现,了解更多:Puppet 兼容性列表

Kind: instance method of Wechaty

// 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.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\]\)

获取全局的Wechaty 实例。

**Kind**: static method of [`Wechaty`](wechaty.md#wechaty)​

| Param | Type | Default |
| :--- | :--- | :--- |
| \[options\] | ​[`WechatyOptions`](wechaty.md#wechatyoptions)​ | `{}` |

**Example**

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

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

类型定义

PuppetModuleName

Kind: global typedef Properties PuppetModuleName 参数在这里代表着Puppet 的名称,类型是 string, 可能的取值为:

WechatyOptions

创建wechaty 实例的可选参数类型。

Kind: global typedef Properties

WechatyEventName

Wechaty 事件的类型 Kind: global typedef Properties

Last updated