wechaty.ts 20.1 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

23 24 25 26
import {
  cloneClass,
  Constructor,
}                   from 'clone-class'
27 28 29
import {
  callerResolve,
  hotImport,
30 31
}                   from 'hot-import'
import StateSwitch  from 'state-switch'
32

33
import {
34
  config,
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
35
  log,
36
  PuppetName,
37
  Raven,
38
  Sayable,
39
  VERSION,
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
40
  WechatyEvent,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
41
}                     from './config'
M
Mukaiu 已提交
42
import {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
43 44
}                     from './message'
import Profile        from './profile'
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
45

46
import {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
47
  Contact,
48
  FriendRequest,
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
49 50 51 52
  Message,
  Puppet,
  PuppetAccessory,
  Room,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
53
}                     from './abstract-puppet/'
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
54

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
55 56
import PuppetWeb      from './puppet-web/'
import PuppetMock     from './puppet-mock/'
57 58

export interface WechatyOptions {
L
lijiarui 已提交
59 60
  puppet?:  PuppetName,
  profile?: string,
61
}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
62

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
63
/**
L
lijiarui 已提交
64
 * Main bot class.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
65
 *
L
lijiarui 已提交
66
 * [The World's Shortest ChatBot Code: 6 lines of JavaScript]{@link #wechatyinstance}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
67
 *
L
lijiarui 已提交
68 69 70
 * [Wechaty Starter Project]{@link https://github.com/lijiarui/wechaty-getting-started}
 * @example
 * import { Wechaty } from 'wechaty'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
71
 *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
72
 */
73
export class Wechaty extends PuppetAccessory implements Sayable {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
74 75
  /**
   * singleton _instance
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
76
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
77
   */
78
  private static _instance: Wechaty
79

80 81
  private profile: Profile

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
82 83
  /**
   * the state
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
84
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
85
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
86
  private state = new StateSwitch('Wechaty', log)
87

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
88
  /**
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
89
   * the cuid
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
90
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
91
   */
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
92
  public cuid:        string
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
93

94
  // tslint:disable-next-line:variable-name
95
  public Contact        : typeof Contact        & Constructor<{}>
96
  // tslint:disable-next-line:variable-name
97
  public FriendRequest  : typeof FriendRequest  & Constructor<{}>
98
  // tslint:disable-next-line:variable-name
99
  public Message        : typeof Message        & Constructor<{}>
100
  // tslint:disable-next-line:variable-name
101
  public Room           : typeof Room           & Constructor<{}>
102

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
103
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
104
   * get the singleton instance of Wechaty
L
lijiarui 已提交
105 106 107 108 109 110 111 112 113
   *
   * @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 (李卓桓) 已提交
114
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
115 116 117
  public static instance(
    options?: WechatyOptions,
  ) {
118
    if (options && this._instance) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
119
      throw new Error('there has already a instance. no params will be allowed any more')
120 121
    }
    if (!this._instance) {
122
      this._instance = new Wechaty(options)
123 124 125 126
    }
    return this._instance
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
127
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
128
   * @public
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
129
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
130
  constructor(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
131 132
    private options: WechatyOptions = {},
  ) {
133
    super()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
134 135
    log.verbose('Wechaty', 'contructor()')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
136
    options.puppet  = options.puppet || config.puppet
137

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

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
140
    this.cuid = cuid()
141 142
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
143
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
144
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
145
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
146
  public toString() { return `Wechaty<${this.options.puppet}, ${this.profile.name}>`}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
147

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
148
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
149
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
150
   */
151
  public static version(forceNpm = false): string {
152
    if (!forceNpm) {
153
      const revision = config.gitRevision()
154
      if (revision) {
155
        return `#git[${revision}]`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
156
      }
157
    }
158
    return VERSION
159
  }
160

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
161
 /**
Huan (李卓桓)'s avatar
linting  
Huan (李卓桓) 已提交
162 163 164 165 166 167 168 169 170
  * 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'
  */
171 172
  public version(forceNpm?) {
    return Wechaty.version(forceNpm)
173
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
174

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
175 176 177 178 179 180 181 182 183 184 185 186
  public on(event: 'error'      , listener: string | ((this: Wechaty, error: Error) => void))                                                  : this
  public on(event: 'friend'     , listener: string | ((this: Wechaty, friend: Contact, request?: FriendRequest) => void))                      : this
  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[]) => 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
187 188
  // guard for the above event: make sure it includes all the possible values
  public on(event: never,         listener: any): this
L
lijiarui 已提交
189

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
190
  /**
L
lijiarui 已提交
191 192 193 194 195 196 197 198 199 200 201 202
   * @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 (李卓桓) 已提交
203
   * @property   {string}  scan       - A scan event will be emitted when the bot needs to show you a QR Code for scanning.
L
lijiarui 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
   */

  /**
   * @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
   * @property   {Function} friend          -(this: Wechaty, friend: Contact, request?: FriendRequest) => void
   * @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
233
   * @param   {WechatyEvent}      event      - Emit WechatyEvent
L
lijiarui 已提交
234 235 236
   * @param   {WechatyEventFunction}  listener   - Depends on the WechatyEvent
   * @return  {Wechaty}                          - this for chain
   *
237
   * More Example Gist: [Examples/Friend-Bot]{@link https://github.com/wechaty/wechaty/blob/master/examples/friend-bot.ts}
L
lijiarui 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
   *
   * @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>
   * bot.on('friend', (contact: Contact, request: FriendRequest) => {
   *   if(request){ // 1. request to be friend from new contact
   *     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!`)
   *       }
   * 	  } else { // 2. confirm friend ship
   *       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 (李卓桓) 已提交
289
   */
290
  public on(event: WechatyEvent, listener: string | ((...args: any[]) => any)): this {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
291
    log.verbose('Wechaty', 'on(%s, %s) registered',
292 293 294 295 296 297
                            event,
                            typeof listener === 'string'
                              ? listener
                              : typeof listener,
                )

298 299 300 301
    if (typeof listener === 'function') {
      this.onFunction(event, listener)
    } else {
      this.onModulePath(event, listener)
302
    }
303
    return this
304 305
  }

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
  private onModulePath(event: WechatyEvent, modulePath: string): void {
    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)
      })
  }

  private onFunction(event: WechatyEvent, listener: Function): void {
    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 (李卓桓) 已提交
339
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
340
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
341
   */
342
  public initPuppet(): Puppet {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
343
    log.verbose('Wechaty', 'initPuppet()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
344
    let puppet: Puppet
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
345

346
    switch (this.options.puppet) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
347
      case 'web':
348
        puppet = new PuppetWeb({
349
          profile:  this.profile,
350
          wechaty:  this,
351
        })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
352
        break
353

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
354 355 356 357 358 359 360
      case 'mock':
        puppet = new PuppetMock({
          profile:  this.profile,
          wechaty:  this,
        })
        break

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
361
      default:
362
        throw new Error('Puppet unsupport(yet?): ' + this.options.puppet)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
363
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
364

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
365
    const eventList: WechatyEvent[] = [
L
lijiarui 已提交
366 367 368 369 370 371 372 373 374 375
      'error',
      'friend',
      'heartbeat',
      'login',
      'logout',
      'message',
      'room-join',
      'room-leave',
      'room-topic',
      'scan',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
376 377
    ]

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
378 379 380 381 382
    for (const event of eventList) {
      log.verbose('Wechaty', 'initPuppet() puppet.on(%s) registered', event)
      /// e as any ??? Maybe this is a bug of TypeScript v2.5.3
      puppet.on(event as any, (...args: any[]) => {
        this.emit(event, ...args)
383
      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
384
    }
385

386 387 388 389 390 391 392 393 394 395 396 397 398
    /**
     * Clone Classes for this bot
     *
     * Fixme:
     *   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
     */
    this.Contact        = cloneClass(puppet.Contact       as any)
    this.FriendRequest  = cloneClass(puppet.FriendRequest as any)
    this.Message        = cloneClass(puppet.Message       as any)
    this.Room           = cloneClass(puppet.Room          as any)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
399
    return puppet
400 401
  }

402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
  /**
   * 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 {
      this.profile.load()
      this.puppet = this.initPuppet()

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

      if (this === Wechaty._instance) {
        /**
         * Here means `this` is the global instance of Wechaty (`Wechaty.instance()`)
         * so we can keep using `Contact.find()` and `Room.find()`
         *
         * This workaround should be removed after v0.18
         *
         * See: fix the breaking changes for #518
         * https://github.com/Chatie/wechaty/issues/518
         */
        Contact.puppet       = this.puppet
        FriendRequest.puppet = this.puppet
        Message.puppet       = this.puppet
        Room.puppet          = this.puppet
      }

      this.Contact.puppet       = this.puppet
      this.FriendRequest.puppet = this.puppet
      this.Message.puppet       = this.puppet
      this.Room.puppet          = this.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 (李卓桓) 已提交
469 470 471 472 473 474 475 476
  /**
   * Stop the bot
   *
   * @returns {Promise<void>}
   * @example
   * await bot.stop()
   */
  public async stop(): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
477
    log.verbose('Wechaty', 'stop()')
478

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
479
    if (this.state.off()) {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
480 481 482
      log.silly('Wechaty', 'stop() on an stopping/stopped instance')
      await this.state.ready('off')
      log.silly('Wechaty', 'stop() state.ready(off) resolved')
483
      return
484
    }
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
485

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

488 489 490 491
    let puppet: Puppet
    try {
      puppet = this.puppet
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
492
      log.warn('Wechaty', 'stop() without this.puppet')
493
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
494 495
    }

496
    // this.puppet = null
497 498 499 500 501
    // config.puppetInstance(null)
    // this.Contact.puppet       = undefined
    // this.FriendRequest.puppet = undefined
    // this.Message.puppet       = undefined
    // this.Room.puppet          = undefined
502

503
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
504
      await puppet.stop()
505
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
506
      log.error('Wechaty', 'stop() exception: %s', e.message)
507 508
      Raven.captureException(e)
      throw e
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
509
    } finally {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
510
      this.state.off(true)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
511
      this.emit('stop')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
512

513 514
      // 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 (李卓桓) 已提交
515
      setImmediate(() => puppet.removeAllListeners())
516
    }
517
    return
518
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
519

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
520
  /**
L
lijiarui 已提交
521 522 523 524 525
   * Logout the bot
   *
   * @returns {Promise<void>}
   * @example
   * await bot.logout()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
526
   */
527
  public async logout(): Promise<void>  {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
528 529
    log.verbose('Wechaty', 'logout()')

530 531 532 533 534 535 536
    try {
      await this.puppet.logout()
    } catch (e) {
      log.error('Wechaty', 'logout() exception: %s', e.message)
      Raven.captureException(e)
      throw e
    }
537
    return
538
  }
539

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
540 541 542 543 544
  /**
   * Get the logon / logoff state
   *
   * @returns {boolean}
   * @example
545
   * if (bot.logonoff()) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
546 547 548 549 550
   *   console.log('Bot logined')
   * } else {
   *   console.log('Bot not logined')
   * }
   */
551
  public logonoff(): Boolean {
552 553 554
    try {
      return this.puppet.logonoff()
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
555 556 557 558
      return false
    }
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
559
  /**
L
lijiarui 已提交
560 561 562 563 564 565
   * Get current user
   *
   * @returns {Contact}
   * @example
   * const contact = bot.self()
   * console.log(`Bot is ${contact.name()}`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
566
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
567 568
  public self(): Contact {
    return this.puppet.self()
569
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
570

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
571
  /**
L
lijiarui 已提交
572
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
573
   */
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
574
  public async send(message: Message): Promise<void> {
575
    try {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
576
      await this.puppet.send(message)
577 578 579 580 581
    } catch (e) {
      log.error('Wechaty', 'send() exception: %s', e.message)
      Raven.captureException(e)
      throw e
    }
582
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
583

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
584
  /**
L
lijiarui 已提交
585 586
   * Send message to filehelper
   *
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
587
   * @param {string} text
L
lijiarui 已提交
588
   * @returns {Promise<boolean>}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
589
   */
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
590 591 592
  public async say(text: string): Promise<void> {
    log.verbose('Wechaty', 'say(%s)', text)
    await this.puppet.say(text)
593 594
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
595
  /**
L
lijiarui 已提交
596
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
597
   */
598
  public static async sleep(millisecond: number): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
599
    await new Promise(resolve => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
600 601 602 603
      setTimeout(resolve, millisecond)
    })
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
604
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
605
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
606
   */
607 608 609 610 611 612 613 614
  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 (李卓桓) 已提交
615
  }
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630

  /**
   * @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 (李卓桓) 已提交
631 632 633 634 635 636

  /**
   * @private
   */
  public async reset(reason?: string): Promise<void> {
    log.verbose('Wechaty', 'reset() because %s', reason)
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
637 638
    await this.puppet.stop()
    await this.puppet.start()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
639 640 641
    return
  }

642
}
643 644

export default Wechaty