Wechaty
NewsBlogDevelopersDocs
中文版
中文版
  • 介绍
  • 快速开始
  • API 文档
    • Wechaty
    • Message
    • Contact
    • ContactSelf
    • Room
    • RoomInvitation
    • Friendship
  • 示例代码
  • Puppet
  • 常见问题
  • 最佳实践
  • 参与贡献
  • 了解更多
    • 视频教程
    • 进阶
    • 测试
    • 目录结构
    • ReleaseLog
    • ChangeLog
    • Awesome Wechaty
    • Contributors
    • 关于token的所有问题
Powered by GitBook
On this page
  • 简介
  • Wechaty
  • new Wechaty([options])
  • wechaty.on(event, listener) ⇒ Wechaty​
  • wechaty.start() ⇒ Promise.
  • wechaty.stop() ⇒ Promise.
  • wechaty.logout() ⇒ Promise.
  • wechaty.logonoff() ⇒ boolean
  • wechaty.userSelf() ⇒ ContactSelf
  • wechaty.say(textOrContactOrFileOrUrl) ⇒ Promise.
  • 类型定义
  • PuppetModuleName
  • WechatyOptions
  • WechatyEventName

Was this helpful?

  1. API 文档

Wechaty

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

PreviousAPI 文档NextMessage

Last updated 5 years ago

Was this helpful?

简介

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

  • 网页微信客户端, 当你选择: /​

  • iPad 微信客户端, 当你选择: ​

了解更多:

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

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

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

Wechaty

Kind: global class

  • ​​

    • ​​

    • instance

      • ​ ⇒ ​

      • ​ ⇒ Promise.

      • ​ ⇒ Promise.

      • ​ ⇒ Promise.

      • ​ ⇒ boolean

      • ​ ⇒ ContactSelf

      • ​ ⇒ Promise.

    • static

      • ​​

new Wechaty([options])

Param

Type

Default

[options]

{}

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() 是可以传参数的

使用网页版本的场景

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

使用iPad 版本的场景

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

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

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

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

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

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

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

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

Param

Type

Description

event

Emit WechatyEvent

listener

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

启动机器人

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

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

wechaty.stop() ⇒ Promise.

停止机器人

await bot.stop()

wechaty.logout() ⇒ Promise.

登出机器人

await bot.logout()

wechaty.logonoff() ⇒ boolean

获取机器人logon/logoff 的状态

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

wechaty.userSelf() ⇒ ContactSelf

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

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

wechaty.say(textOrContactOrFileOrUrl) ⇒ Promise.

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

Param

Type

Description

textOrContactOrFileOrUrl

string | Contact | FileBox | UrlLink

发送文本、联系人名片或者文件给机器人自己。

// 2. send Contact to bot itself const contact = bot.Contact.load('contactId') await bot.say(contact)​

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

### 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, 可能的取值为:

Name

Type

Description

PUPPET_DEFAULT

string

默认的puppet, 默认会使用 wechaty-puppet-puppeteer

wechaty-puppet-wechat4u

string

wechaty-puppet-padchat

string

使用WebSocket 协议链接一个协议服务器,来控制iPad 微信。

wechaty-puppet-puppeteer

string

wechaty-puppet-mock

string

为单元测试提供模拟调用的Puppet

WechatyOptions

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

Kind: global typedef Properties

名称

类型

描述

name

string

Wechaty 机器人的名称. 当你按照下面的方式设置的时候: new Wechaty({name: 'wechatyName'}) 他会自动生成一个叫做wechatyName.memory-card.json的文件 。这个文件会存储机器人的登陆信息。如果这个文件有效,启动wechaty 的时候,你不需要扫码登陆就能自动登陆机器人(只对wechaty-puppet-padchat有效)。 这个名字在启动机器人的时候,是可以通过环境变量WECHATY_NAME 设置的,如:WECHATY_NAME="wechatyName" node bot.js

puppet

puppetOptions

PuppetOptions

指定puppet信息 endpoint: 指定puppet的底层服务器地址; timeout:指定watchDog的超时时间 token: 指定puppet的token

WechatyEventName

Wechaty 事件的类型 Kind: global typedef Properties

名称

类型

描述

error

string

当机器人内部出错的时候会触发error 事件。

login

string

当机器人成功登陆后,会触发login 事件,并会在事件中传递当前登陆机器人的信息。

logout

string

当机器人检测到登出的时候,会触发logout 事件,并会在事件中传递机器人的信息。

heartbeat

string

获取机器人的心跳。

friendship

string

当有人给机器人发好友请求的时候会触发这个事件。

message

string

当机器人收到消息的时候会触发这个事件。

ready

string

当所有数据加载完成后,会触发这个事件。在wechaty-puppet-padchat 中,它意味着已经加载完成Contact 和Room 的信息。

room-join

string

当有人进入微信群的时候会触发这个事件。机器人主动进入某个微信群,t那个样会触发这个事件。

room-topic

string

当有人修改群名称的时候会触发这个事件。

room-leave

string

当机器人把群里某个用户移出群聊的时候会触发这个时间。用户主动退群是无法检测到的。

room-invite

string

scan

string

当机器人需要扫码登陆的时候会触发这个事件。 建议你安装 qrcode-terminal(运行 npm install qrcode-terminal) 这个包,这样你可以在命令行中直接看到二维码。

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

​​

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

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

wechaty.on(event, listener) ⇒ ​

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

Kind: instance method of

Returns: - - this for chaining, see advanced ​

​​

​​

Kind: instance method of Example

Kind: instance method of Example

Kind: instance method of Example

Kind: instance method of Example

Kind: instance method of Example

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

Kind: instance method of ​

你可以使用 来发送文件

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

默认的puppet,使用 来控制

通过chrome(谷歌)浏览器使用 来控制

| Puppet

使用puppet名称指定相关puppet或者直接传入puppet实例作为Wechaty底层插件, 了解更多信息

当收到群邀请的时候,会触发这个事件。具体请

示例代码
token
https://chatie.io/wechaty/images/bot-qr-code.png
https://avatars0.githubusercontent.com/u/25162437?s=200&v=4
https://github.com/chatie/wechaty
Wechaty
WechatyEventName
Wechaty
chaining usage
Wechaty
Wechaty
Wechaty
Wechaty
Wechaty
Wechaty
Wechaty
PuppetModuleName
WechatyOptions
WechatyEventName
WechatyEventFunction
FileBox
wechat4u
网页微信 API
google puppeteer
网页微信 API
puppet
RoomInvitation
WechatyOptions
WechatyEventName
WechatyEventFunction
PuppetModuleName
puppet-puppeteer
puppet-wechat4u
puppet-padchat
Message
Contact
Room
.on(event, listener)
Wechaty
new Wechaty([options])
Wechaty
.start()
.stop()
.logout()
.logonoff()
.userSelf()
.say(textOrContactOrFileOrUrl)
.instance([options])
Puppet
Puppet
Wechaty 中的Puppet 是什么意思
Puppet 兼容性列表
查看详情