wechaty.ts 22.5 KB
Newer Older
1
/**
2
 *   Wechaty - https://github.com/chatie/wechaty
3
 *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
4
 *   @copyright 2016-2018 Huan LI <zixia@zixia.net>
5
 *
6 7 8
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
9
 *
10
 *       http://www.apache.org/licenses/LICENSE-2.0
11
 *
12 13 14 15 16
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
L
lijiarui 已提交
17 18
 *
 *  @ignore
19
 */
20 21
import * as cuid    from 'cuid'
import * as os      from 'os'
22
import * as semver  from 'semver'
23

24
import {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
25
  // Constructor,
26
  cloneClass,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
27
  // instanceToClass,
28
}                   from 'clone-class'
29 30 31
import {
  callerResolve,
  hotImport,
32 33
}                   from 'hot-import'
import StateSwitch  from 'state-switch'
34

35
import {
36
  VERSION,
37
  config,
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
38
  log,
39
  Raven,
40
  Sayable,
41 42 43
}                       from './config'
import Profile          from './profile'
import PuppetAccessory  from './puppet-accessory'
M
Mukaiu 已提交
44
import {
45 46 47
  PUPPET_DICT,
  PuppetName,
}                       from './puppet-config'
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
48

49
import {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
50
  Contact,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
51 52
}                       from './contact'
import {
53
  FriendRequest,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
54 55
}                       from './friend-request'
import {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
56
  Message,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
57 58
}                       from './message'
import {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
59
  Room,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
60 61 62
}                       from './room'
import {
  Puppet,
63
}                       from './puppet/'
64 65 66 67 68 69 70 71 72 73 74

export const WECHAT_EVENT_DICT = {
  friend      : 'tbw',
  login       : 'tbw',
  logout      : 'tbw',
  message     : 'tbw',
  'room-join' : 'tbw',
  'room-leave': 'tbw',
  'room-topic': 'tbw',
  scan        : 'tbw',
}
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
75

76 77
export const WECHATY_EVENT_DICT = {
  ...WECHAT_EVENT_DICT,
78 79 80 81
  error     : 'tbw',
  heartbeat : 'tbw',
  start     : 'tbw',
  stop      : 'tbw',
82 83 84 85
}

export type WechatEventName   = keyof typeof WECHAT_EVENT_DICT
export type WechatyEventName  = keyof typeof WECHATY_EVENT_DICT
86 87

export interface WechatyOptions {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
88 89
  puppet?  : PuppetName | Puppet,
  profile? : null | string,
90
}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
91

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
92
/**
L
lijiarui 已提交
93
 * Main bot class.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
94
 *
L
lijiarui 已提交
95
 * [The World's Shortest ChatBot Code: 6 lines of JavaScript]{@link #wechatyinstance}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
96
 *
L
lijiarui 已提交
97 98 99
 * [Wechaty Starter Project]{@link https://github.com/lijiarui/wechaty-getting-started}
 * @example
 * import { Wechaty } from 'wechaty'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
100
 *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
101
 */
102
export class Wechaty extends PuppetAccessory implements Sayable {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
103
  /**
104
   * singleton globalInstance
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
105
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
106
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
107
  private static singletonInstance: Wechaty
108

109 110
  private profile: Profile

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
111 112
  /**
   * the state
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
113
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
114
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
115
  private state = new StateSwitch('Wechaty', log)
116

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
117
  /**
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
118
   * the cuid
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
119
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
120
   */
121
  public readonly cuid : string
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
122

123
  // tslint:disable-next-line:variable-name
124
  public readonly Contact       : typeof Contact
125
  // tslint:disable-next-line:variable-name
126
  public readonly FriendRequest : typeof FriendRequest
127
  // tslint:disable-next-line:variable-name
128
  public readonly Message       : typeof Message
129
  // tslint:disable-next-line:variable-name
130
  public readonly Room          : typeof Room
131

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
132
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
133
   * get the singleton instance of Wechaty
L
lijiarui 已提交
134 135 136 137 138 139 140 141 142
   *
   * @example <caption>The World's Shortest ChatBot Code: 6 lines of JavaScript</caption>
   * 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}`))
   * .init()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
143
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
144 145 146
  public static instance(
    options?: WechatyOptions,
  ) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
147
    if (options && this.singletonInstance) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
148
      throw new Error('instance can be only set once!')
149
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
150 151
    if (!this.singletonInstance) {
      this.singletonInstance = new Wechaty(options)
152
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
153
    return this.singletonInstance
154 155
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
156
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
157
   * @public
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
158
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
159
  constructor(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
160
    private options: WechatyOptions = {},
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
161
  ) {
162
    super()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
163 164
    log.verbose('Wechaty', 'contructor()')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
165
    options.profile = options.profile === null
166
                      ? null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
167
                      : (options.profile || config.default.DEFAULT_PROFILE)
168

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
169
    this.profile = new Profile(options.profile)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
170

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
171
    this.cuid = cuid()
172 173 174 175 176 177 178 179 180 181 182 183 184

    /**
     * Clone Classes for this bot and attach the `puppet` to the Class
     *
     *   https://stackoverflow.com/questions/36886082/abstract-constructor-type-in-typescript
     *   https://github.com/Microsoft/TypeScript/issues/5843#issuecomment-290972055
     *   https://github.com/Microsoft/TypeScript/issues/19197
     */
    // TODO: make Message & Room constructor private???
    this.Contact        = cloneClass(Contact)
    this.FriendRequest  = cloneClass(FriendRequest)
    this.Message        = cloneClass(Message)
    this.Room           = cloneClass(Room)
185 186
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
187
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
188
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
189
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
190 191 192 193 194 195 196 197 198 199 200
  public toString() {
    if (!this.options) {
      return this.constructor.name
    }

    return [
      'Wechaty',
      `<${this.options && this.options.puppet || ''}>`,
      `(${this.profile && this.profile.name   || ''})`,
    ].join('')
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
201

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
202
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
203
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
204
   */
205
  public static version(forceNpm = false): string {
206
    if (!forceNpm) {
207
      const revision = config.gitRevision()
208
      if (revision) {
209
        return `#git[${revision}]`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
210
      }
211
    }
212
    return VERSION
213
  }
214

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
215
 /**
Huan (李卓桓)'s avatar
linting  
Huan (李卓桓) 已提交
216 217 218 219 220 221 222 223 224
  * Return version of Wechaty
  *
  * @param {boolean} [forceNpm=false]  - if set to true, will only return the version in package.json.
  *                                      otherwise will return git commit hash if .git exists.
  * @returns {string}                  - the version number
  * @example
  * console.log(Wechaty.instance().version())       // return '#git[af39df]'
  * console.log(Wechaty.instance().version(true))   // return '0.7.9'
  */
225
  public version(forceNpm = false): string {
226
    return Wechaty.version(forceNpm)
227
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
228

229
  public on(event: 'error'      , listener: string | ((this: Wechaty, error: Error) => void))                                                 : this
230
  public on(event: 'friend'     , listener: string | ((this: Wechaty, request: FriendRequest) => void))                     : this
231 232 233 234 235 236 237 238 239 240
  public on(event: 'heartbeat'  , listener: string | ((this: Wechaty, data: any) => void))                                                    : this
  public on(event: 'logout'     , listener: string | ((this: Wechaty, user: Contact) => void))                                                : this
  public on(event: 'login'      , listener: string | ((this: Wechaty, user: Contact) => void))                                                : this
  public on(event: 'message'    , listener: string | ((this: Wechaty, message: Message) => void))                                             : this
  public on(event: 'room-join'  , listener: string | ((this: Wechaty, room: Room, inviteeList: Contact[],  inviter: Contact) => void))        : this
  public on(event: 'room-leave' , listener: string | ((this: Wechaty, room: Room, leaverList: Contact[], remover?: Contact) => void))         : this
  public on(event: 'room-topic' , listener: string | ((this: Wechaty, room: Room, topic: string, oldTopic: string, changer: Contact) => void)): this
  public on(event: 'scan'       , listener: string | ((this: Wechaty, url: string,  code: number) => void))                                   : this
  public on(event: 'start'      , listener: string | ((this: Wechaty) => void))                                                               : this
  public on(event: 'stop'       , listener: string | ((this: Wechaty) => void))                                                               : this
241
  // guard for the above event: make sure it includes all the possible values
242
  public on(event: never,         listener: never): never
L
lijiarui 已提交
243

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
244
  /**
L
lijiarui 已提交
245 246 247 248 249 250 251 252 253 254 255 256
   * @desc       Wechaty Class Event Type
   * @typedef    WechatyEventName
   * @property   {string}  error      - When the bot get error, there will be a Wechaty error event fired.
   * @property   {string}  login      - After the bot login full successful, the event login will be emitted, with a Contact of current logined user.
   * @property   {string}  logout     - Logout will be emitted when bot detected log out, with a Contact of the current login user.
   * @property   {string}  heartbeat  - Get bot's heartbeat.
   * @property   {string}  friend     - When someone sends you a friend request, there will be a Wechaty friend event fired.
   * @property   {string}  message    - Emit when there's a new message.
   * @property   {string}  room-join  - Emit when anyone join any room.
   * @property   {string}  room-topic - Get topic event, emitted when someone change room topic.
   * @property   {string}  room-leave - Emit when anyone leave the room.<br>
   *                                    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.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
257
   * @property   {string}  scan       - A scan event will be emitted when the bot needs to show you a QR Code for scanning.
L
lijiarui 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
   */

  /**
   * @desc       Wechaty Class Event Function
   * @typedef    WechatyEventFunction
   * @property   {Function} error           -(this: Wechaty, error: Error) => void callback function
   * @property   {Function} login           -(this: Wechaty, user: Contact)=> void
   * @property   {Function} logout          -(this: Wechaty, user: Contact) => void
   * @property   {Function} scan            -(this: Wechaty, url: string, code: number) => void <br>
   * <ol>
   * <li>URL: {String} the QR code image URL</li>
   * <li>code: {Number} the scan status code. some known status of the code list here is:</li>
   * </ol>
   * <ul>
   * <li>0 initial_</li>
   * <li>200 login confirmed</li>
   * <li>201 scaned, wait for confirm</li>
   * <li>408 waits for scan</li>
   * </ul>
   * @property   {Function} heartbeat       -(this: Wechaty, data: any) => void
278
   * @property   {Function} friend          -(this: Wechaty, request?: FriendRequest) => void
L
lijiarui 已提交
279 280 281 282 283 284 285 286
   * @property   {Function} message         -(this: Wechaty, message: Message) => void
   * @property   {Function} room-join       -(this: Wechaty, room: Room, inviteeList: Contact[],  inviter: Contact) => void
   * @property   {Function} room-topic      -(this: Wechaty, room: Room, topic: string, oldTopic: string, changer: Contact) => void
   * @property   {Function} room-leave      -(this: Wechaty, room: Room, leaverList: Contact[]) => void
   */

  /**
   * @listens Wechaty
287
   * @param   {WechatyEventName}      event      - Emit WechatyEvent
L
lijiarui 已提交
288 289 290
   * @param   {WechatyEventFunction}  listener   - Depends on the WechatyEvent
   * @return  {Wechaty}                          - this for chain
   *
291
   * More Example Gist: [Examples/Friend-Bot]{@link https://github.com/Chatie/wechaty/blob/master/examples/friend-bot.ts}
L
lijiarui 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
   *
   * @example <caption>Event:scan </caption>
   * wechaty.on('scan', (url: string, code: number) => {
   *   console.log(`[${code}] Scan ${url} to login.` )
   * })
   *
   * @example <caption>Event:login </caption>
   * bot.on('login', (user: Contact) => {
   *   console.log(`user ${user} login`)
   * })
   *
   * @example <caption>Event:logout </caption>
   * bot.on('logout', (user: Contact) => {
   *   console.log(`user ${user} logout`)
   * })
   *
   * @example <caption>Event:message </caption>
   * wechaty.on('message', (message: Message) => {
   *   console.log(`message ${message} received`)
   * })
   *
   * @example <caption>Event:friend </caption>
314 315 316
   * bot.on('friend', (request: FriendRequest) => {
   *   if(request.type === FriendRequest.Type.RECEIVE){ // 1. receive new friend request from new contact
   *     const contact = request.contact()
L
lijiarui 已提交
317 318 319 320 321 322
   *     let result = await request.accept()
   *       if(result){
   *         console.log(`Request from ${contact.name()} is accept succesfully!`)
   *       } else{
   *         console.log(`Request from ${contact.name()} failed to accept!`)
   *       }
323
   * 	  } else if (request.type === FriendRequest.Type.CONFIRM) { // 2. confirm friend ship
L
lijiarui 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
   *       console.log(`new friendship confirmed with ${contact.name()}`)
   *    }
   *  })
   *
   * @example <caption>Event:room-join </caption>
   * 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 <caption>Event:room-leave </caption>
   * 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 <caption>Event:room-topic </caption>
   * 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()}`)
   * })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
344
   */
345
  public on(event: WechatyEventName, listener: string | ((...args: any[]) => any)): this {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
346
    log.verbose('Wechaty', 'on(%s, %s) registered',
347 348 349 350 351 352
                            event,
                            typeof listener === 'string'
                              ? listener
                              : typeof listener,
                )

353 354 355 356
    if (typeof listener === 'function') {
      this.onFunction(event, listener)
    } else {
      this.onModulePath(event, listener)
357
    }
358
    return this
359 360
  }

361
  private onModulePath(event: WechatyEventName, modulePath: string): void {
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    const absoluteFilename = callerResolve(modulePath, __filename)
    log.verbose('Wechaty', 'onModulePath() hotImpor(%s)', absoluteFilename)
    hotImport(absoluteFilename)
      .then((func: Function) => super.on(event, (...args: any[]) => {
        try {
          func.apply(this, args)
        } catch (e) {
          log.error('Wechaty', 'onModulePath(%s, %s) listener exception: %s',
                                event, modulePath, e)
          this.emit('error', e)
        }
      }))
      .catch(e => {
        log.error('Wechaty', 'onModulePath(%s, %s) hotImport() exception: %s',
                              event, modulePath, e)
        this.emit('error', e)
      })
  }

381
  private onFunction(event: WechatyEventName, listener: Function): void {
382 383 384 385 386 387 388 389 390 391 392 393
    log.verbose('Wechaty', 'onFunction(%s)', event)

    super.on(event, (...args: any[]) => {
      try {
        listener.apply(this, args)
      } catch (e) {
        log.error('Wechaty', 'onFunction(%s) listener exception: %s', event, e)
        this.emit('error', e)
      }
    })
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
  /**
   * Will be called from the Puppet.
   */
  public attach(puppet: Puppet) {
    log.verbose('Wechaty', 'attach(%s) this.options.puppet="%s"',
                            puppet,
                            this.options.puppet && this.options.puppet.toString(),
                )

    if (this.options.puppet instanceof Puppet) {
      if (this.options.puppet === puppet) {
        log.silly('Wechaty', 'attach(%s) called again', puppet)
        return
      } else {
        throw new Error('puppet can only be attached once!')
      }
    }

    this.options.puppet = puppet
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
415
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
416
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
417
   */
418
  private initPuppet(): void {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
419
    log.verbose('Wechaty', 'initPuppet()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
420

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
421
    if (!this.options.puppet) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
422 423
      log.warn('Wechaty', 'initPuppet() using default puppet: %s', config.puppet)
      this.options.puppet  = config.puppet
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
424 425
    }

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
    const puppet = this.initPuppetResolver(this.options.puppet)

    if (!this.initPuppetSemverSatisfy(
      puppet.wechatyVersionRange(),
    )) {
      throw new Error(`The Puppet Plugin(${puppet.constructor.name}) `
          + `requires a version range(${puppet.wechatyVersionRange()}) `
          + `that is not satisfying the Wechaty version: ${this.version()}.`,
        )
    }

    this.initPuppetEventBridge(puppet)
    this.initPuppetAccessory(puppet)
  }

  /**
   * Init the Puppet
   */
  private initPuppetResolver(puppet: PuppetName | Puppet): Puppet {
    log.verbose('Wechaty', 'initPuppetResolver(%s)', puppet)

    if (typeof puppet === 'string') {
448
      // tslint:disable-next-line:variable-name
449 450 451 452 453
      const MyPuppet = PUPPET_DICT[puppet]
      if (!MyPuppet) {
        throw new Error('no such puppet: ' + puppet)
      }

454
      const options = {
455 456
        profile:  this.profile,
        wechaty:  this,
457 458
      }

459
      return new MyPuppet(options)
460

461 462
    } else if (puppet instanceof Puppet) {
      return puppet
463 464
    } else {
      throw new Error('unsupported options.puppet!')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
465
    }
466
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
467

468 469 470 471 472 473
  /**
   * Plugin Version Range Check
   */
  private initPuppetSemverSatisfy(versionRange: string) {
    log.verbose('Wechaty', 'initPuppet(%s)', versionRange)
    return semver.satisfies(
474
      this.version(true),
475 476 477
      versionRange,
    )
  }
478

479
  private initPuppetEventBridge(puppet: Puppet) {
480
    for (const event of Object.keys(WECHATY_EVENT_DICT)) {
481
      log.verbose('Wechaty', 'initPuppetEventBridge() puppet.on(%s) registered', event)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
482 483 484
      /// e as any ??? Maybe this is a bug of TypeScript v2.5.3
      puppet.on(event as any, (...args: any[]) => {
        this.emit(event, ...args)
485
      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
486
    }
487
  }
488

489 490
  private initPuppetAccessory(puppet: Puppet) {
    log.verbose('Wechaty', 'initPuppetAccessory(%s)', puppet)
491

492 493 494 495 496 497
    this.Contact.puppet       = puppet
    this.FriendRequest.puppet = puppet
    this.Message.puppet       = puppet
    this.Room.puppet          = puppet

    this.puppet = puppet
498 499
  }

500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
  /**
   * Start the bot, return Promise.
   *
   * @returns {Promise<void>}
   * @example
   * await bot.start()
   * // do other stuff with bot here
   */
  public async start(): Promise<void> {
    log.info('Wechaty', 'v%s starting...' , this.version())
    log.verbose('Wechaty', 'puppet: %s'   , this.options.puppet)
    log.verbose('Wechaty', 'profile: %s'  , this.options.profile)
    log.verbose('Wechaty', 'cuid: %s'     , this.cuid)

    if (this.state.on()) {
      log.silly('Wechaty', 'start() on a starting/started instance')
      await this.state.ready()
      log.silly('Wechaty', 'start() state.ready() resolved')
      return
    }

    this.state.on('pending')

    try {
524 525
      await this.profile.load()
      await this.initPuppet()
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545

      // set puppet instance to Wechaty Static variable, for using by Contact/Room/Message/FriendRequest etc.
      // config.puppetInstance(puppet)

      await this.puppet.start()

    } catch (e) {
      log.error('Wechaty', 'start() exception: %s', e && e.message)
      Raven.captureException(e)
      throw e
    }

    this.on('heartbeat', () => this.memoryCheck())

    this.state.on(true)
    this.emit('start')

    return
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
546 547 548 549 550 551 552 553
  /**
   * Stop the bot
   *
   * @returns {Promise<void>}
   * @example
   * await bot.stop()
   */
  public async stop(): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
554
    log.verbose('Wechaty', 'stop()')
555

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
556
    if (this.state.off()) {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
557 558 559
      log.silly('Wechaty', 'stop() on an stopping/stopped instance')
      await this.state.ready('off')
      log.silly('Wechaty', 'stop() state.ready(off) resolved')
560
      return
561
    }
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
562

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
563
    this.state.off('pending')
564

565 566 567 568
    let puppet: Puppet
    try {
      puppet = this.puppet
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
569
      log.warn('Wechaty', 'stop() without this.puppet')
570
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
571 572
    }

573
    // this.puppet = null
574 575 576 577 578
    // config.puppetInstance(null)
    // this.Contact.puppet       = undefined
    // this.FriendRequest.puppet = undefined
    // this.Message.puppet       = undefined
    // this.Room.puppet          = undefined
579

580
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
581
      await puppet.stop()
582
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
583
      log.error('Wechaty', 'stop() exception: %s', e.message)
584 585
      Raven.captureException(e)
      throw e
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
586
    } finally {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
587
      this.state.off(true)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
588
      this.emit('stop')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
589

590 591
      // MUST use setImmediate at here(the end of this function),
      // because we need to run the micro task registered by the `emit` method
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
592
      setImmediate(() => puppet.removeAllListeners())
593
    }
594
    return
595
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
596

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
597
  /**
L
lijiarui 已提交
598 599 600 601 602
   * Logout the bot
   *
   * @returns {Promise<void>}
   * @example
   * await bot.logout()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
603
   */
604
  public async logout(): Promise<void>  {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
605 606
    log.verbose('Wechaty', 'logout()')

607 608 609 610 611 612 613
    try {
      await this.puppet.logout()
    } catch (e) {
      log.error('Wechaty', 'logout() exception: %s', e.message)
      Raven.captureException(e)
      throw e
    }
614
    return
615
  }
616

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
617 618 619 620 621
  /**
   * Get the logon / logoff state
   *
   * @returns {boolean}
   * @example
622
   * if (bot.logonoff()) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
623 624 625 626 627
   *   console.log('Bot logined')
   * } else {
   *   console.log('Bot not logined')
   * }
   */
628
  public logonoff(): Boolean {
629
    return this.puppet.logonoff()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
630 631
  }

632 633 634 635
  /**
   * @deprecated
   */
  public self(): Contact {
636
    log.warn('Wechaty', 'self() DEPRECATED. use userSelf() instead.')
637 638 639
    return this.userSelf()
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
640
  /**
L
lijiarui 已提交
641 642 643 644
   * Get current user
   *
   * @returns {Contact}
   * @example
645
   * const contact = bot.userSelf()
L
lijiarui 已提交
646
   * console.log(`Bot is ${contact.name()}`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
647
   */
648
  public userSelf(): Contact {
649
    return this.puppet.userSelf()
650
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
651

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
652
  /**
L
lijiarui 已提交
653
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
654
   */
655 656 657 658 659 660 661 662 663
  // public async send(message: Message): Promise<void> {
  //   try {
  //     await this.puppet.messageSend(message)
  //   } catch (e) {
  //     log.error('Wechaty', 'send() exception: %s', e.message)
  //     Raven.captureException(e)
  //     throw e
  //   }
  // }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
664

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
665
  /**
L
lijiarui 已提交
666 667
   * Send message to filehelper
   *
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
668
   * @param {string} text
L
lijiarui 已提交
669
   * @returns {Promise<boolean>}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
670
   */
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
671 672 673
  public async say(text: string): Promise<void> {
    log.verbose('Wechaty', 'say(%s)', text)
    await this.puppet.say(text)
674 675
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
676
  /**
L
lijiarui 已提交
677
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
678
   */
679
  public static async sleep(millisecond: number): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
680
    await new Promise(resolve => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
681 682 683 684
      setTimeout(resolve, millisecond)
    })
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
685
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
686
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
687
   */
688 689 690 691 692 693 694 695
  public async ding(): Promise<string> {
    try {
      return await this.puppet.ding() // should return 'dong'
    } catch (e) {
      log.error('Wechaty', 'ding() exception: %s', e.message)
      Raven.captureException(e)
      throw e
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
696
  }
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711

  /**
   * @private
   */
  private memoryCheck(minMegabyte = 4): void {
    const freeMegabyte = Math.floor(os.freemem() / 1024 / 1024)
    log.silly('Wechaty', 'memoryCheck() free: %d MB, require: %d MB',
                          freeMegabyte, minMegabyte)

    if (freeMegabyte < minMegabyte) {
      const e = new Error(`memory not enough: free ${freeMegabyte} < require ${minMegabyte} MB`)
      log.warn('Wechaty', 'memoryCheck() %s', e.message)
      this.emit('error', e)
    }
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
712 713 714 715 716

  /**
   * @private
   */
  public async reset(reason?: string): Promise<void> {
717
    log.verbose('Wechaty', 'reset() because %s', reason || 'no reason')
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
718 719
    await this.puppet.stop()
    await this.puppet.start()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
720 721 722
    return
  }

723 724 725
  public unref(): void {
    log.warn('Wechaty', 'unref() To Be Implemented. See: https://github.com/Chatie/wechaty/issues/1197')
  }
726
}
727 728

export default Wechaty