wechaty.js 2.0 KB
Newer Older
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1 2 3 4 5 6 7 8
/**
 *
 * wechaty: Wechat for Bot. and for human who talk to bot/robot
 *
 * Licenst: ISC
 * https://github.com/zixia/wechaty
 *
 */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
9
const EventEmitter = require('events')
10

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
11 12 13 14 15 16
const Puppet      = require('./puppet')
const PuppetWeb   = require('./puppet-web')

const Message     = require('./message')
const Contact     = require('./contact')
const Group       = require('./group')
17 18

class Wechaty extends EventEmitter {
Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
19
  constructor(options) {
20
    super()
21 22 23 24 25 26 27 28 29 30 31
    this.options = options || {}
    this.options.puppet = this.options.puppet || 'web'
  }
  toString() { return 'Class Wechaty(' + this.puppet + ')'}
  init() {
    this.initPuppet()
    this.initEventHook()
    return this.puppet.init()
  }
  initPuppet() {
    switch (this.options.puppet) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
32
      case 'web':
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
33
        this.puppet = new Puppet.Web({
34 35
          head:   this.options.head
          , port: this.options.port
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
36
        })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
37 38
        break
      default:
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
39
        throw new Error('Puppet unsupport(yet): ' + puppet)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
40 41
        break
    }
42 43 44 45 46 47 48
    return Promise.resolve(this.puppet)
  }
  initEventHook() {
    // scan qrCode
    this.puppet.on('scan', (e) => {
      this.emit('scan', e)
    })
49 50 51 52 53 54 55 56 57
    this.puppet.on('message', (e) => {
      this.emit('message', e)
    })
    this.puppet.on('login', (e) => {
      this.emit('login', e)
    })
    this.puppet.on('logout', (e) => {
      this.emit('logout', e)
    })
58
    return Promise.resolve()
59 60
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
61
  currentUser()   { return this.puppet.currentUser() }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
62
  quit()          { return this.puppet.quit() }
63 64
  send(message)   { return this.puppet.say(message) }
  reply(message, reply) { return this.puppet.reply(message, reply) }
65

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
66 67 68 69
  ding()          {
    // TODO: test through the server & browser
    return 'dong'
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
70

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
71 72 73 74
  /**
   * @deprecated
   * use on('scan', ({code, url}) => {}) instead.
   */
Huan (李卓桓)'s avatar
fix  
Huan (李卓桓) 已提交
75
  getLoginQrImgUrl() { return this.puppet.getLoginQrImgUrl() }
76 77
}

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
78
Puppet.Web = PuppetWeb
79

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
80 81 82 83 84 85
Object.assign(Wechaty, {
  Puppet:     Puppet
  , Message:  Message
  , Contact:  Contact
  , Group:    Group
})
86 87

module.exports = Wechaty