wechaty.ts 19.7 KB
Newer Older
1
/**
2
 *   Wechaty - https://github.com/chatie/wechaty
3
 *
4
 *   @copyright 2016-2017 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
import { EventEmitter } from 'events'
21 22
import * as os          from 'os'

23 24 25 26 27
import StateSwitch      from 'state-switch'
import {
  callerResolve,
  hotImport,
}                       from 'hot-import'
28

29
import {
30
  config,
31
  PuppetName,
32
  Raven,
33 34
  Sayable,
  log,
35
}                     from './config'
36

37 38
import Contact        from './contact'
import FriendRequest  from './friend-request'
M
Mukaiu 已提交
39 40 41
import {
  Message,
  MediaMessage,
42 43
}                     from './message'
import Profile        from './profile'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
44
import Puppet         from './puppet'
45 46 47 48 49
import PuppetWeb      from './puppet-web/'
import Room           from './room'
import Misc           from './misc'

export interface WechatyOptions {
L
lijiarui 已提交
50 51
  puppet?:  PuppetName,
  profile?: string,
52
}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
53

54 55 56 57 58 59 60 61 62 63 64
export type WechatEvent = 'friend'
                        | 'login'
                        | 'logout'
                        | 'message'
                        | 'room-join'
                        | 'room-leave'
                        | 'room-topic'
                        | 'scan'

export type WechatyEvent = WechatEvent
                        | 'error'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
65
                        | 'heartbeat'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
66 67
                        | 'start'
                        | 'stop'
68

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
86 87
  /**
   * the puppet
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
88
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
89
   */
90
  public puppet: Puppet | null
91

92 93
  private profile: Profile

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
94 95
  /**
   * the state
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
96
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
97
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
98
  private state = new StateSwitch('Wechaty', log)
99

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
100 101
  /**
   * the uuid
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
102
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
103
   */
104
  public uuid:        string
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
105

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

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

139
    options.puppet  = options.puppet  || config.puppet
140

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

143
    this.uuid = Misc.guid()
144 145
  }

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
151 152
  /**
   * Return version of Wechaty
Huan (李卓桓)'s avatar
doc  
Huan (李卓桓) 已提交
153
   *
Huan (李卓桓)'s avatar
dodc  
Huan (李卓桓) 已提交
154 155
   * @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.
Huan (李卓桓)'s avatar
doc  
Huan (李卓桓) 已提交
156
   * @returns {string}                  - the version number
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
157
   * @example
L
lijiarui 已提交
158 159
   * console.log(Wechaty.instance().version())       // return '#git[af39df]'
   * console.log(Wechaty.instance().version(true))   // return '0.7.9'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
160
   */
161
  public static version(forceNpm = false): string {
162
    if (!forceNpm) {
163 164
      const revision = config.gitVersion()
      if (revision) {
165
        return `#git[${revision}]`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
166
      }
167
    }
168 169
    return config.npmVersion()
  }
170

H
hcz 已提交
171
  /**
L
lijiarui 已提交
172
   * @private
H
hcz 已提交
173
   */
174 175
  public version(forceNpm?) {
    return Wechaty.version(forceNpm)
176
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
177

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
178
  /**
L
lijiarui 已提交
179 180
   * Initialize the bot, return Promise.
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
181
   * @deprecated
L
lijiarui 已提交
182 183 184 185
   * @returns {Promise<void>}
   * @example
   * await bot.init()
   * // do other stuff with bot here
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
186
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
187
  public async init(): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201
    log.warn('Wechaty', 'init() DEPRECATED and will be removed after Jun 2018. Use start() instead.')
    await this.start()
  }

  /**
   * 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())
202 203
    log.verbose('Wechaty', 'puppet: %s'       , this.options.puppet)
    log.verbose('Wechaty', 'profile: %s'      , this.options.profile)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
204
    log.verbose('Wechaty', 'uuid: %s'         , this.uuid)
205

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
206
    if (this.state.on() === true) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
207
      log.error('Wechaty', 'start() already started. return and do nothing.')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
208
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
209 210 211
    } else if (this.state.on() === 'pending') {
      log.error('Wechaty', 'start() another task is starting. return and do nothing.')
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
212 213
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
214
    this.state.on('pending')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
215

216
    try {
217
      this.profile.load()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
218 219
      this.puppet = await this.initPuppet()

220
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
221
      log.error('Wechaty', 'start() exception: %s', e && e.message)
222
      Raven.captureException(e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
223
      throw e
224
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
225

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
228
    this.state.on(true)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
229 230
    this.emit('start')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
231
    return
232
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
233

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
234 235 236 237 238 239 240 241 242 243 244 245
  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
246 247
  // guard for the above event: make sure it includes all the possible values
  public on(event: never,         listener: any): this
L
lijiarui 已提交
248

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
249
  /**
L
lijiarui 已提交
250 251 252 253 254 255 256 257 258 259 260 261
   * @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 (李卓桓) 已提交
262
   * @property   {string}  scan       - A scan event will be emitted when the bot needs to show you a QR Code for scanning.
L
lijiarui 已提交
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 289 290 291
   */

  /**
   * @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
292
   * @param   {WechatyEvent}      event      - Emit WechatyEvent
L
lijiarui 已提交
293 294 295 296 297 298 299 300 301 302 303 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 339 340 341 342 343 344 345 346 347
   * @param   {WechatyEventFunction}  listener   - Depends on the WechatyEvent
   * @return  {Wechaty}                          - this for chain
   *
   * More Example Gist: [Example/Friend-Bot]{@link https://github.com/wechaty/wechaty/blob/master/example/friend-bot.ts}
   *
   * @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 (李卓桓) 已提交
348
   */
349
  public on(event: WechatyEvent, listener: string | ((...args: any[]) => any)): this {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
350
    log.verbose('Wechaty', 'on(%s, %s) registered',
351 352 353 354 355 356
                            event,
                            typeof listener === 'string'
                              ? listener
                              : typeof listener,
                )

357 358 359 360
    if (typeof listener === 'function') {
      this.onFunction(event, listener)
    } else {
      this.onModulePath(event, listener)
361
    }
362
    return this
363 364
  }

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
  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 (李卓桓) 已提交
398
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
399
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
400
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
401
  public async initPuppet(): Promise<Puppet> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
402
    log.verbose('Wechaty', 'initPuppet()')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
403
    let puppet: Puppet
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
404

405
    switch (this.options.puppet) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
406
      case 'web':
407
        puppet = new PuppetWeb({
408
          profile:  this.profile,
409
        })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
410
        break
411

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
412
      default:
413
        throw new Error('Puppet unsupport(yet?): ' + this.options.puppet)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
414
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
415

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
416
    const eventList: WechatyEvent[] = [
L
lijiarui 已提交
417 418 419 420 421 422 423 424 425 426
      'error',
      'friend',
      'heartbeat',
      'login',
      'logout',
      'message',
      'room-join',
      'room-leave',
      'room-topic',
      'scan',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
427 428
    ]

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
429 430 431 432 433
    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)
434
      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
435
    }
436

437
    // set puppet instance to Wechaty Static variable, for using by Contact/Room/Message/FriendRequest etc.
438
    config.puppetInstance(puppet)
439
    await puppet.init()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
440

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
441
    return puppet
442 443
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
444
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
445
   * Quit the bot
L
lijiarui 已提交
446
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
447
   * @deprecated
L
lijiarui 已提交
448 449 450
   * @returns {Promise<void>}
   * @example
   * await bot.quit()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
451
   */
452
  public async quit(): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
453 454 455 456 457 458 459 460 461 462 463 464
    log.warn('Wechaty', 'quit() DEPRECATED and will be removed after Jun 2018. Use stop() instead.')
    await this.stop()
  }

  /**
   * Stop the bot
   *
   * @returns {Promise<void>}
   * @example
   * await bot.stop()
   */
  public async stop(): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
465
    log.verbose('Wechaty', 'stop()')
466

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
467
    if (this.state.off() === 'pending') { // current() !== 'on' || !this.state.stable()) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
468
      const err = new Error(`stop() must run on a inited instance.`)
469
      log.error('Wechaty', err.message)
470 471
      this.emit('error', err)
      return
472
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
473
    this.state.off('pending')
474

475
    if (!this.puppet) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
476
      log.warn('Wechaty', 'stop() without this.puppet')
477
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
478 479
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
480 481
    const puppet = this.puppet

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
482
    this.puppet = null
483
    config.puppetInstance(null)
484

485
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
486
      await puppet.quit()
487
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
488
      log.error('Wechaty', 'stop() exception: %s', e.message)
489 490
      Raven.captureException(e)
      throw e
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
491
    } finally {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
492
      this.state.off(true)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
493
      this.emit('stop')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
494

495 496
      // 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 (李卓桓) 已提交
497
      setImmediate(() => puppet.removeAllListeners())
498
    }
499
    return
500
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
501

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
502
  /**
L
lijiarui 已提交
503 504 505 506 507
   * Logout the bot
   *
   * @returns {Promise<void>}
   * @example
   * await bot.logout()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
508
   */
509
  public async logout(): Promise<void>  {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
510 511
    log.verbose('Wechaty', 'logout()')

512 513 514
    if (!this.puppet) {
      throw new Error('no puppet')
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
515

516 517 518 519 520 521 522
    try {
      await this.puppet.logout()
    } catch (e) {
      log.error('Wechaty', 'logout() exception: %s', e.message)
      Raven.captureException(e)
      throw e
    }
523
    return
524
  }
525

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
  /**
   * Get the logon / logoff state
   *
   * @returns {boolean}
   * @example
   * if (bot.logonoff()) {
   *   console.log('Bot logined')
   * } else {
   *   console.log('Bot not logined')
   * }
   */
  public logonoff(): Boolean {
    if (!this.puppet) {
      return false
    }
    return this.puppet.logonoff()
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
544
  /**
L
lijiarui 已提交
545 546 547 548 549 550
   * Get current user
   *
   * @returns {Contact}
   * @example
   * const contact = bot.self()
   * console.log(`Bot is ${contact.name()}`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
551
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
552
  public self(): Contact {
553
    if (!this.puppet) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
554
      throw new Error('Wechaty.self() no puppet')
555
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
556
    return this.puppet.self()
557
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
558

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
559
  /**
L
lijiarui 已提交
560
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
561
   */
562
  public async send(message: Message | MediaMessage): Promise<boolean> {
563 564 565
    if (!this.puppet) {
      throw new Error('no puppet')
    }
566 567 568 569 570 571 572
    try {
      return await this.puppet.send(message)
    } catch (e) {
      log.error('Wechaty', 'send() exception: %s', e.message)
      Raven.captureException(e)
      throw e
    }
573
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
574

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
575
  /**
L
lijiarui 已提交
576 577 578 579
   * Send message to filehelper
   *
   * @param {string} content
   * @returns {Promise<boolean>}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
580
   */
581
  public async say(content: string): Promise<boolean> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
582 583
    log.verbose('Wechaty', 'say(%s)', content)

584 585 586
    if (!this.puppet) {
      throw new Error('no puppet')
    }
587
    return await this.puppet.say(content)
588 589
  }

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
599
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
600
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
601
   */
602
  public async ding(): Promise<string> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
603 604 605 606
    if (!this.puppet) {
      return Promise.reject(new Error('wechaty cant ding coz no puppet'))
    }

607 608 609 610 611 612 613
    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 (李卓桓) 已提交
614
  }
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629

  /**
   * @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 (李卓桓) 已提交
630 631 632 633 634 635 636 637 638 639 640 641 642

  /**
   * @private
   */
  public async reset(reason?: string): Promise<void> {
    log.verbose('Wechaty', 'reset() because %s', reason)
    if (!this.puppet) {
      throw new Error('no puppet')
    }
    await this.puppet.reset(reason)
    return
  }

643
}
644 645

export default Wechaty