wechaty.ts 31.2 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 22
import cuid    from 'cuid'
import os      from 'os'
import semver  from 'semver'
23

24
import {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
25
  // Constructor,
26
  cloneClass,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
27
  // instanceToClass,
28
}                   from 'clone-class'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
29 30 31
import {
  FileBox,
}                   from 'file-box'
32 33 34
import {
  callerResolve,
  hotImport,
35
}                   from 'hot-import'
36 37 38 39 40 41
import {
  StateSwitch,
}                   from 'state-switch'
import {
  MemoryCard,
}                   from 'memory-card'
42

43 44 45 46 47 48 49 50 51
import {
  Puppet,
  PuppetOptions,

  CHAT_EVENT_DICT,
  PUPPET_EVENT_DICT,
  PuppetEventName,
}                       from 'wechaty-puppet'

52 53 54
import {
  Accessory,
}                       from './accessory'
55
import {
56
  VERSION,
57
  config,
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
58
  log,
59
  Raven,
60
  Sayable,
61
}                       from './config'
62

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
63 64 65
import {
  Io,
}                       from './io'
M
Mukaiu 已提交
66
import {
67 68 69
  PUPPET_DICT,
  PuppetName,
}                       from './puppet-config'
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
70

71
import {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
72
  Contact,
73
  ContactSelf,
74
  Friendship,
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
75 76
  Message,
  Room,
77
}                       from './user/'
78

79 80 81 82 83 84 85 86 87 88
// 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 (李卓桓) 已提交
89

90
export const WECHATY_EVENT_DICT = {
91
  ...CHAT_EVENT_DICT,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
92
  dong      : 'tbw',
93 94 95 96
  error     : 'tbw',
  heartbeat : 'tbw',
  start     : 'tbw',
  stop      : 'tbw',
97 98 99
}

export type WechatyEventName  = keyof typeof WECHATY_EVENT_DICT
100 101

export interface WechatyOptions {
102 103 104 105
  profile?       : null | string,            // Wechaty Name
  puppet?        : PuppetName | Puppet,      // Puppet name or instance
  puppetOptions? : Partial<PuppetOptions>,   // Puppet TOKEN
  ioToken?       : string,                   // Io TOKEN
106
}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
107

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
108
/**
L
lijiarui 已提交
109
 * Main bot class.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
110
 *
L
lijiarui 已提交
111
 * [The World's Shortest ChatBot Code: 6 lines of JavaScript]{@link #wechatyinstance}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
112
 *
L
lijiarui 已提交
113 114 115
 * [Wechaty Starter Project]{@link https://github.com/lijiarui/wechaty-getting-started}
 * @example
 * import { Wechaty } from 'wechaty'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
116
 *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
117
 */
118
export class Wechaty extends Accessory implements Sayable {
119 120 121

  public readonly state  : StateSwitch

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
122
  /**
123
   * singleton globalInstance
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
124
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
125
   */
126
  private static globalInstance: Wechaty
127

128
  private readonly memory : MemoryCard
129

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
130 131
  private lifeTimer? : NodeJS.Timer
  private io?        : Io
132

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
133
  /**
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
134
   * the cuid
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
135
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
136
   */
137
  public readonly id : string
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
138

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
139 140 141
  /**
   * @private
   */
142
  // tslint:disable-next-line:variable-name
143
  public readonly Contact       : typeof Contact
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
144 145 146 147

  /**
   * @private
   */
148
  // tslint:disable-next-line:variable-name
149
  public readonly ContactSelf   : typeof ContactSelf
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
150 151 152 153

  /**
   * @private
   */
154
  // tslint:disable-next-line:variable-name
155
  public readonly Friendship    : typeof Friendship
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
156 157 158 159

  /**
   * @private
   */
160
  // tslint:disable-next-line:variable-name
161
  public readonly Message       : typeof Message
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
162 163 164 165

  /**
   * @private
   */
166
  // tslint:disable-next-line:variable-name
167
  public readonly Room          : typeof Room
168

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
169
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
170
   * get the singleton instance of Wechaty
L
lijiarui 已提交
171 172 173 174 175 176 177 178 179
   *
   * @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 (李卓桓) 已提交
180
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
181 182 183
  public static instance(
    options?: WechatyOptions,
  ) {
184
    if (options && this.globalInstance) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
185
      throw new Error('instance can be only inited once by options!')
186
    }
187 188
    if (!this.globalInstance) {
      this.globalInstance = new Wechaty(options)
189
    }
190
    return this.globalInstance
191 192
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
193
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
194
   * @public
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
195
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
196
  constructor(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
197
    private options: WechatyOptions = {},
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
198
  ) {
199
    super()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
200 201
    log.verbose('Wechaty', 'contructor()')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
202
    options.profile = options.profile === null
203
                      ? null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
204
                      : (options.profile || config.default.DEFAULT_PROFILE)
205

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
206
    this.memory = new MemoryCard(options.profile || undefined)
207 208
    this.state  = new StateSwitch('Wechaty', log)
    this.id     = cuid()
209 210 211 212 213 214 215 216 217

    /**
     * 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???
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
218 219
    this.Contact     = cloneClass(Contact)
    this.ContactSelf = cloneClass(ContactSelf)
220
    this.Friendship  = cloneClass(Friendship)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
221 222
    this.Message     = cloneClass(Message)
    this.Room        = cloneClass(Room)
223 224
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
225
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
226
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
227
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
228 229 230 231 232 233
  public toString() {
    if (!this.options) {
      return this.constructor.name
    }

    return [
234 235
      'Wechaty#',
      this.id,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
236
      `<${this.options && this.options.puppet || ''}>`,
237
      `(${this.memory  && this.memory.name    || ''})`,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
238 239
    ].join('')
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
240

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
241
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
242
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
243
   */
244
  public static version(forceNpm = false): string {
245
    if (!forceNpm) {
246
      const revision = config.gitRevision()
247
      if (revision) {
248
        return `#git[${revision}]`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
249
      }
250
    }
251
    return VERSION
252
  }
253

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
254
 /**
Huan (李卓桓)'s avatar
linting  
Huan (李卓桓) 已提交
255 256 257 258 259 260 261 262 263
  * 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'
  */
264
  public version(forceNpm = false): string {
265
    return Wechaty.version(forceNpm)
266
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
267

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
268
  public emit(event: 'dong'       , data?: string)                                                    : boolean
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
269
  public emit(event: 'error'      , error: Error)                                                     : boolean
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
270
  public emit(event: 'friendship' , friendship: Friendship)                                           : boolean
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
271 272 273 274 275 276 277 278 279 280
  public emit(event: 'heartbeat'  , data: any)                                                        : boolean
  public emit(event: 'logout'     , user: ContactSelf)                                                : boolean
  public emit(event: 'login'      , user: ContactSelf)                                                : boolean
  public emit(event: 'message'    , message: Message)                                                 : boolean
  public emit(event: 'room-join'  , room: Room, inviteeList : Contact[], inviter  : Contact)          : boolean
  public emit(event: 'room-leave' , room: Room, leaverList  : Contact[], remover? : Contact)          : boolean
  public emit(event: 'room-topic' , room: Room, newTopic: string, oldTopic: string, changer: Contact) : boolean
  public emit(event: 'scan'       , qrcode: string, status: number, data?: string)                    : boolean
  public emit(event: 'start')                                                                         : boolean
  public emit(event: 'stop')                                                                          : boolean
281 282 283 284 285 286 287 288 289 290 291

  // guard for the above event: make sure it includes all the possible values
  public emit(event: never, listener: never): never

  public emit(
    event:   WechatyEventName,
    ...args: any[]
  ): boolean {
    return super.emit(event, ...args)
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
292
  public on(event: 'dong'       , listener: string | ((this: Wechaty, data?: string) => void))                                                     : this
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
293
  public on(event: 'error'      , listener: string | ((this: Wechaty, error: Error) => void))                                                     : this
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
294
  public on(event: 'friendship' , listener: string | ((this: Wechaty, friendship: Friendship) => void))                                           : this
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
295 296 297 298 299 300 301 302 303 304
  public on(event: 'heartbeat'  , listener: string | ((this: Wechaty, data: any) => void))                                                        : this
  public on(event: 'logout'     , listener: string | ((this: Wechaty, user: ContactSelf) => void))                                                : this
  public on(event: 'login'      , listener: string | ((this: Wechaty, user: ContactSelf) => 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, newTopic: string, oldTopic: string, changer: Contact) => void)) : this
  public on(event: 'scan'       , listener: string | ((this: Wechaty, qrcode: string, status: number, data?: string) => void))                    : this
  public on(event: 'start'      , listener: string | ((this: Wechaty) => void))                                                                   : this
  public on(event: 'stop'       , listener: string | ((this: Wechaty) => void))                                                                   : this
305

306
  // guard for the above event: make sure it includes all the possible values
307
  public on(event: never, listener: never): never
L
lijiarui 已提交
308

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
309
  /**
L
lijiarui 已提交
310 311 312 313 314 315 316 317 318 319 320 321
   * @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 (李卓桓) 已提交
322
   * @property   {string}  scan       - A scan event will be emitted when the bot needs to show you a QR Code for scanning.
L
lijiarui 已提交
323 324 325 326 327 328
   */

  /**
   * @desc       Wechaty Class Event Function
   * @typedef    WechatyEventFunction
   * @property   {Function} error           -(this: Wechaty, error: Error) => void callback function
329 330
   * @property   {Function} login           -(this: Wechaty, user: ContactSelf)=> void
   * @property   {Function} logout          -(this: Wechaty, user: ContactSelf) => void
L
lijiarui 已提交
331 332 333 334 335 336 337 338 339 340 341 342
   * @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
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
343
   * @property   {Function} friendship      -(this: Wechaty, friendship: Friendship) => void
L
lijiarui 已提交
344 345
   * @property   {Function} message         -(this: Wechaty, message: Message) => void
   * @property   {Function} room-join       -(this: Wechaty, room: Room, inviteeList: Contact[],  inviter: Contact) => void
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
346
   * @property   {Function} room-topic      -(this: Wechaty, room: Room, newTopic: string, oldTopic: string, changer: Contact) => void
L
lijiarui 已提交
347 348 349 350 351
   * @property   {Function} room-leave      -(this: Wechaty, room: Room, leaverList: Contact[]) => void
   */

  /**
   * @listens Wechaty
352
   * @param   {WechatyEventName}      event      - Emit WechatyEvent
L
lijiarui 已提交
353 354 355
   * @param   {WechatyEventFunction}  listener   - Depends on the WechatyEvent
   * @return  {Wechaty}                          - this for chain
   *
356
   * More Example Gist: [Examples/Friend-Bot]{@link https://github.com/Chatie/wechaty/blob/master/examples/friend-bot.ts}
L
lijiarui 已提交
357 358 359 360 361 362 363
   *
   * @example <caption>Event:scan </caption>
   * wechaty.on('scan', (url: string, code: number) => {
   *   console.log(`[${code}] Scan ${url} to login.` )
   * })
   *
   * @example <caption>Event:login </caption>
364
   * bot.on('login', (user: ContactSelf) => {
L
lijiarui 已提交
365 366 367 368
   *   console.log(`user ${user} login`)
   * })
   *
   * @example <caption>Event:logout </caption>
369
   * bot.on('logout', (user: ContactSelf) => {
L
lijiarui 已提交
370 371 372 373 374 375 376 377
   *   console.log(`user ${user} logout`)
   * })
   *
   * @example <caption>Event:message </caption>
   * wechaty.on('message', (message: Message) => {
   *   console.log(`message ${message} received`)
   * })
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
378 379 380 381 382
   * @example <caption>Event:friendship </caption>
   * 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()
L
lijiarui 已提交
383 384 385 386 387
   *       if(result){
   *         console.log(`Request from ${contact.name()} is accept succesfully!`)
   *       } else{
   *         console.log(`Request from ${contact.name()} failed to accept!`)
   *       }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
388
   * 	  } else if (friendship.type() === Friendship.Type.CONFIRM) { // 2. confirm friendship
L
lijiarui 已提交
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
   *       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 (李卓桓) 已提交
409
   */
410
  public on(event: WechatyEventName, listener: string | ((...args: any[]) => any)): this {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
411
    log.verbose('Wechaty', 'on(%s, %s) registered',
412 413 414 415 416 417
                            event,
                            typeof listener === 'string'
                              ? listener
                              : typeof listener,
                )

418 419
    // DEPRECATED for 'friend' event
    if (event as any === 'friend') {
420
      log.warn('Wechaty', `on('friend', contact, friendRequest) is DEPRECATED. use on('friendship', friendship) instead`)
421 422 423
      if (typeof listener === 'function') {
        const oldListener = listener
        listener = (...args: any[]) => {
424
          log.warn('Wechaty', `on('friend', contact, friendRequest) is DEPRECATED. use on('friendship', friendship) instead`)
425 426 427 428 429
          oldListener.apply(this, args)
        }
      }
    }

430
    if (typeof listener === 'function') {
431
      this.addListenerFunction(event, listener)
432
    } else {
433
      this.addListenerModuleFile(event, listener)
434
    }
435
    return this
436 437
  }

438
  private addListenerModuleFile(event: WechatyEventName, modulePath: string): void {
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    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)
      })
  }

458
  private addListenerFunction(event: WechatyEventName, listener: Function): void {
459 460 461 462 463 464 465 466 467 468 469 470
    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 (李卓桓) 已提交
471 472 473
  private initPuppet(): void {
    log.verbose('Wechaty', 'initPuppet(%s)', this.options.puppet)

474 475 476 477 478 479 480 481 482 483 484 485
    let inited = false
    try {
      inited = !!this.puppet
    } catch (e) {
      inited = false
    }

    if (inited) {
      log.verbose('Wechaty', 'initPuppet(%s) had already been inited, no need to init twice', this.options.puppet)
      return
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
486 487 488 489
    const puppet = this.initPuppetResolver(this.options.puppet)

    this.initPuppetVersionSatisfy(puppet)
    this.initPuppetEventBridge(puppet)
490

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
491 492
    this.initPuppetAccessory(puppet)
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
493

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
494
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
495
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
496
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
497 498
  private initPuppetVersionSatisfy(puppet: Puppet): void {
    log.verbose('Wechaty', 'initPuppetVersionSatisfy(%s)', puppet)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
499

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
500
    if (this.initPuppetSemverSatisfy(
501 502
      puppet.wechatyVersionRange(),
    )) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
503
      return
504 505
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
506 507 508 509
    throw new Error(`The Puppet Plugin(${puppet.constructor.name}) `
      + `requires a version range(${puppet.wechatyVersionRange()}) `
      + `that is not satisfying the Wechaty version: ${this.version()}.`,
    )
510 511 512
  }

  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
513 514
   * @private
   *
515 516
   * Init the Puppet
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
517
  private initPuppetResolver(puppet?: PuppetName | Puppet): Puppet {
518 519
    log.verbose('Wechaty', 'initPuppetResolver(%s)', puppet)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
520
    if (!puppet) {
521
      log.info('Wechaty', 'initPuppet() using puppet: %s', config.puppet)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
522 523 524
      puppet  = config.puppet
    }

525
    if (typeof puppet === 'string') {
526
      // tslint:disable-next-line:variable-name
527 528 529 530 531
      const MyPuppet = PUPPET_DICT[puppet]
      if (!MyPuppet) {
        throw new Error('no such puppet: ' + puppet)
      }

532
      const options: PuppetOptions = {
533
        memory : this.memory,
534
        ...this.options.puppetOptions,
535 536
      }

537
      return new MyPuppet(options)
538

539 540
    } else if (puppet instanceof Puppet) {
      return puppet
541
    } else {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
542
      throw new Error('unsupported options.puppet: ' + puppet)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
543
    }
544
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
545

546
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
547 548
   * @private
   *
549 550 551
   * Plugin Version Range Check
   */
  private initPuppetSemverSatisfy(versionRange: string) {
552
    log.verbose('Wechaty', 'initPuppetSemverSatisfy(%s)', versionRange)
553
    return semver.satisfies(
554
      this.version(true),
555 556 557
      versionRange,
    )
  }
558

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
559
  protected initPuppetEventBridge(puppet: Puppet) {
560
    const eventNameList: PuppetEventName[] = Object.keys(PUPPET_EVENT_DICT) as any
561 562 563 564
    for (const eventName of eventNameList) {
      log.verbose('Wechaty', 'initPuppetEventBridge() puppet.on(%s) registered', eventName)

      switch (eventName) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
565 566 567 568 569 570 571
        case 'dong':
          puppet.removeAllListeners('dong')
          puppet.on('dong', data => {
            this.emit('dong', data)
          })
          break

572 573 574 575 576 577 578
        case 'error':
          puppet.removeAllListeners('error')
          puppet.on('error', error => {
            this.emit('error', new Error(error))
          })
          break

579
        case 'watchdog':
580
          puppet.removeAllListeners('heartbeat')
581 582 583 584
          puppet.on('watchdog', data => {
            /**
             * Use `watchdog` event from Puppet to `heartbeat` Wechaty.
             */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
585
            // TODO: use a throttle queue to prevent beat too fast.
586 587 588 589 590 591
            this.emit('heartbeat', data)
          })
          break

        case 'start':
        case 'stop':
592 593 594
          // do not emit 'start'/'stop' again for wechaty:
          // because both puppet & wechaty should have their own
          // `start`/`stop` event seprately
595 596
          break

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
597 598 599 600 601 602 603 604 605 606 607 608 609 610
        // case 'start':
        //   puppet.removeAllListeners('start')
        //   puppet.on('start', () => {
        //     this.emit('start')
        //   } )
        //   break

        // case 'stop':
        //   puppet.removeAllListeners('stop')
        //   puppet.on('stop', () => {
        //     this.emit('stop')
        //   } )
        //   break

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
611 612 613 614 615 616 617 618 619 620 621
        case 'friendship':
          puppet.removeAllListeners('friendship')
          puppet.on('friendship', async friendshipId => {
            const friendship = this.Friendship.load(friendshipId)
            await friendship.ready()
            this.emit('friendship', friendship)
            friendship.contact().emit('friendship', friendship)

            // support deprecated event name: friend.
            // Huan LI 201806
            this.emit('friend' as any, friendship as any)
622 623 624 625 626 627
          })
          break

        case 'login':
          puppet.removeAllListeners('login')
          puppet.on('login', async contactId => {
628
            const contact = this.ContactSelf.load(contactId)
629 630 631 632 633 634 635 636
            await contact.ready()
            this.emit('login', contact)
          })
          break

        case 'logout':
          puppet.removeAllListeners('logout')
          puppet.on('logout', async contactId => {
637
            const contact = this.ContactSelf.load(contactId)
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
            await contact.ready()
            this.emit('logout', contact)
          })
          break

        case 'message':
          puppet.removeAllListeners('message')
          puppet.on('message', async messageId => {
            const msg = this.Message.create(messageId)
            await msg.ready()
            this.emit('message', msg)
          })
          break

        case 'room-join':
          puppet.removeAllListeners('room-join')
          puppet.on('room-join', async (roomId, inviteeIdList, inviterId) => {
            const room = this.Room.load(roomId)
            await room.ready()

            const inviteeList = inviteeIdList.map(id => this.Contact.load(id))
            await Promise.all(inviteeList.map(c => c.ready()))

            const inviter = this.Contact.load(inviterId)
            await inviter.ready()

            this.emit('room-join', room, inviteeList, inviter)
665
            room.emit('join', inviteeList, inviter)
666 667 668 669 670
          })
          break

        case 'room-leave':
          puppet.removeAllListeners('room-leave')
671
          puppet.on('room-leave', async (roomId, leaverIdList, removerId) => {
672 673 674 675 676 677
            const room = this.Room.load(roomId)
            await room.ready()

            const leaverList = leaverIdList.map(id => this.Contact.load(id))
            await Promise.all(leaverList.map(c => c.ready()))

678 679 680 681 682 683 684
            let remover: undefined | Contact = undefined
            if (removerId) {
              remover = this.Contact.load(removerId)
              await remover.ready()
            }

            this.emit('room-leave', room, leaverList, remover)
685
            room.emit('leave', leaverList, remover)
686 687 688 689 690
          })
          break

        case 'room-topic':
          puppet.removeAllListeners('room-topic')
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
691
          puppet.on('room-topic', async (roomId, newTopic, oldTopic, changerId) => {
692 693 694 695 696 697
            const room = this.Room.load(roomId)
            await room.ready()

            const changer = this.Contact.load(changerId)
            await changer.ready()

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
698 699
            this.emit('room-topic', room, newTopic, oldTopic, changer)
            room.emit('topic', newTopic, oldTopic, changer)
700 701 702 703 704
          })
          break

        case 'scan':
          puppet.removeAllListeners('scan')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
705 706
          puppet.on('scan', async (qrcode, status, data) => {
            this.emit('scan', qrcode, status, data)
707 708 709
          })
          break

710 711 712
        case 'watchdog':
          break

713 714 715 716
        default:
          throw new Error('eventName ' + eventName + 'unsupported!')

      }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
717
    }
718
  }
719

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
720
  protected initPuppetAccessory(puppet: Puppet) {
721
    log.verbose('Wechaty', 'initAccessory(%s)', puppet)
722

723
    /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
724
     * 1. Set Wechaty
725
     */
726 727 728 729 730
    this.Contact.wechaty     = this
    this.ContactSelf.wechaty = this
    this.Friendship.wechaty  = this
    this.Message.wechaty     = this
    this.Room.wechaty        = this
731

732
    /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
733
     * 2. Set Puppet
734
     */
735 736 737 738 739
    this.Contact.puppet     = puppet
    this.ContactSelf.puppet = puppet
    this.Friendship.puppet  = puppet
    this.Message.puppet     = puppet
    this.Room.puppet        = puppet
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
740 741

    this.puppet               = puppet
742 743
  }

744
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
745
   * @private
746 747 748 749 750 751
   * @deprecated use start() instead
   */
  public async init(): Promise<void> {
    log.warn('Wechaty', 'init() DEPRECATED. use start() instead.')
    return this.start()
  }
752 753 754 755 756 757 758 759 760
  /**
   * Start the bot, return Promise.
   *
   * @returns {Promise<void>}
   * @example
   * await bot.start()
   * // do other stuff with bot here
   */
  public async start(): Promise<void> {
761
    log.info('Wechaty', 'start() v%s is starting...' , this.version())
762 763
    log.verbose('Wechaty', 'puppet: %s'   , this.options.puppet)
    log.verbose('Wechaty', 'profile: %s'  , this.options.profile)
764
    log.verbose('Wechaty', 'id: %s'       , this.id)
765 766 767

    if (this.state.on()) {
      log.silly('Wechaty', 'start() on a starting/started instance')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
768
      await this.state.ready('on')
769 770 771 772
      log.silly('Wechaty', 'start() state.ready() resolved')
      return
    }

773 774 775 776
    if (this.lifeTimer) {
      throw new Error('start() lifeTimer exist')
    }

777 778 779
    this.state.on('pending')

    try {
780
      await this.memory.load()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
781 782

      this.initPuppet()
783 784
      await this.puppet.start()

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
785 786 787 788 789 790 791 792
      if (this.options.ioToken) {
        this.io = new Io({
          token   : this.options.ioToken,
          wechaty : this,
        })
        await this.io.start()
      }

793
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
794
      console.error(e)
795 796
      log.error('Wechaty', 'start() exception: %s', e && e.message)
      Raven.captureException(e)
797 798 799 800 801 802 803 804 805 806 807
      this.emit('error', e)

      try {
        await this.stop()
      } catch (e) {
        log.error('Wechaty', 'start() stop() exception: %s', e && e.message)
        Raven.captureException(e)
        this.emit('error', e)
      } finally {
        return
      }
808 809 810 811
    }

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

812 813 814 815
    this.lifeTimer = setInterval(() => {
      log.silly('Wechaty', 'start() setInterval() this timer is to keep Wechaty running...')
    }, 1000 * 60 * 60)

816 817 818 819 820 821
    this.state.on(true)
    this.emit('start')

    return
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
822 823 824 825 826 827 828 829
  /**
   * Stop the bot
   *
   * @returns {Promise<void>}
   * @example
   * await bot.stop()
   */
  public async stop(): Promise<void> {
830
    log.info('Wechaty', 'stop() v%s is stoping ...' , this.version())
831

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
832
    if (this.state.off()) {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
833 834 835
      log.silly('Wechaty', 'stop() on an stopping/stopped instance')
      await this.state.ready('off')
      log.silly('Wechaty', 'stop() state.ready(off) resolved')
836
      return
837
    }
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
838

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
839
    this.state.off('pending')
840
    await this.memory.save()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
841

842 843 844 845 846
    if (this.lifeTimer) {
      clearInterval(this.lifeTimer)
      this.lifeTimer = undefined
    }

847
    try {
848
      await this.puppet.stop()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
849 850 851 852 853 854

      if (this.io) {
        await this.io.stop()
        this.io = undefined
      }

855
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
856
      log.error('Wechaty', 'stop() exception: %s', e.message)
857
      Raven.captureException(e)
858
      this.emit('error', e)
859
    }
860 861 862 863 864 865 866 867 868 869

    this.state.off(true)
    this.emit('stop')

    /**
     * MUST use setImmediate at here(the end of this function),
     * because we need to run the micro task registered by the `emit` method
     */
    setImmediate(() => this.puppet.removeAllListeners())

870
    return
871
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
872

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
873
  /**
L
lijiarui 已提交
874 875 876 877 878
   * Logout the bot
   *
   * @returns {Promise<void>}
   * @example
   * await bot.logout()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
879
   */
880
  public async logout(): Promise<void>  {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
881 882
    log.verbose('Wechaty', 'logout()')

883 884 885 886 887 888 889
    try {
      await this.puppet.logout()
    } catch (e) {
      log.error('Wechaty', 'logout() exception: %s', e.message)
      Raven.captureException(e)
      throw e
    }
890
    return
891
  }
892

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
893 894 895 896 897
  /**
   * Get the logon / logoff state
   *
   * @returns {boolean}
   * @example
898
   * if (bot.logonoff()) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
899 900 901 902 903
   *   console.log('Bot logined')
   * } else {
   *   console.log('Bot not logined')
   * }
   */
904
  public logonoff(): Boolean {
905
    return this.puppet.logonoff()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
906 907
  }

908 909 910 911
  /**
   * @deprecated
   */
  public self(): Contact {
912
    log.warn('Wechaty', 'self() DEPRECATED. use userSelf() instead.')
913 914 915
    return this.userSelf()
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
916
  /**
L
lijiarui 已提交
917 918 919 920
   * Get current user
   *
   * @returns {Contact}
   * @example
921
   * const contact = bot.userSelf()
L
lijiarui 已提交
922
   * console.log(`Bot is ${contact.name()}`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
923
   */
924
  public userSelf(): Contact {
925
    const userId = this.puppet.selfId()
926
    const user = this.ContactSelf.load(userId)
927
    return user
928
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
929

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
930
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
931
   * Send message to userSelf
L
lijiarui 已提交
932
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
933
   * @param {string} textOrContactOrFile
L
lijiarui 已提交
934
   * @returns {Promise<boolean>}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
935
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
936 937 938 939 940 941 942 943 944 945 946 947 948
  public async say(textOrContactOrFile: string | Contact | FileBox): Promise<void> {
    log.verbose('Wechaty', 'say(%s)', textOrContactOrFile)

    // Make Typescript Happy:
    if (typeof textOrContactOrFile === 'string') {
      await this.userSelf().say(textOrContactOrFile)
    } else if (textOrContactOrFile instanceof Contact) {
      await this.userSelf().say(textOrContactOrFile)
    } else if (textOrContactOrFile instanceof FileBox) {
      await this.userSelf().say(textOrContactOrFile)
    } else {
      throw new Error('unsupported')
    }
949 950
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
951
  /**
L
lijiarui 已提交
952
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
953
   */
954
  public static async sleep(millisecond: number): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
955
    await new Promise(resolve => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
956 957 958 959
      setTimeout(resolve, millisecond)
    })
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
960
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
961
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
962
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
963 964 965
  public ding(data?: string): void {
    log.silly('Wechaty', 'ding(%s)', data || '')

966
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
967
      this.puppet.ding(data)
968 969 970
    } catch (e) {
      log.error('Wechaty', 'ding() exception: %s', e.message)
      Raven.captureException(e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
971
      throw e
972
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
973
  }
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988

  /**
   * @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 (李卓桓) 已提交
989 990 991 992 993

  /**
   * @private
   */
  public async reset(reason?: string): Promise<void> {
994
    log.verbose('Wechaty', 'reset() because %s', reason || 'no reason')
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
995 996
    await this.puppet.stop()
    await this.puppet.start()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
997 998 999
    return
  }

1000 1001 1002
  public unref(): void {
    log.warn('Wechaty', 'unref() To Be Implemented. See: https://github.com/Chatie/wechaty/issues/1197')
  }
1003
}
1004 1005

export default Wechaty