wechaty.ts 38.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
  PuppetName,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
68
  puppetResolver,
69
}                       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? : 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 112 113 114 115
 * A `Bot` is a wechat client depends on which puppet you use.
 * It may equals
 * - web-wechat, when you use: [puppet-puppeteer](https://github.com/chatie/wechaty-puppet-puppeteer)/[puppet-wechat4u](https://github.com/chatie/wechaty-puppet-wechat4u)
 * - ipad-wechat, when you use: [puppet-padchat](https://github.com/lijiarui/wechaty-puppet-padchat)
 * - ios-wechat, when you use: puppet-ioscat
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
116
 *
L
lijiarui 已提交
117 118
 * See more:
 * - [What is a Puppet in Wechaty](https://github.com/Chatie/wechaty-getting-started/wiki/FAQ-EN#31-what-is-a-puppet-in-wechaty)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
119
 *
L
lijiarui 已提交
120 121 122 123 124 125 126 127 128 129
 * > If you want to know how to send message, see [Message](#Message) <br>
 * > If you want to know how to get contact, see [Contact](#Contact)
 *
 * @example <caption>The World's Shortest ChatBot Code: 6 lines of JavaScript</caption>
 * const { Wechaty } = require('wechaty')
 * const bot = new Wechaty()
 * bot.on('scan',    (qrcode, status) => console.log(['https://api.qrserver.com/v1/create-qr-code/?data=',encodeURIComponent(qrcode),'&size=220x220&margin=20',].join('')))
 * bot.on('login',   user => console.log(`User ${user} logined`))
 * bot.on('message', message => console.log(`Message: ${message}`))
 * bot.start()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
130
 */
131
export class Wechaty extends Accessory implements Sayable {
132 133 134

  public readonly state  : StateSwitch

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
135
  /**
136
   * singleton globalInstance
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
137
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
138
   */
139
  private static globalInstance: Wechaty
140

141
  private readonly memory : MemoryCard
142

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
143 144
  private lifeTimer? : NodeJS.Timer
  private io?        : Io
145

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
146
  /**
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
147
   * the cuid
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
148
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
149
   */
150
  public readonly id : string
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
151

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

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

  /**
   * @private
   */
167
  // tslint:disable-next-line:variable-name
168
  public readonly Friendship    : typeof Friendship
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
169 170 171 172

  /**
   * @private
   */
173
  // tslint:disable-next-line:variable-name
174
  public readonly Message       : typeof Message
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
175 176 177 178

  /**
   * @private
   */
179
  // tslint:disable-next-line:variable-name
180
  public readonly Room          : typeof Room
181

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
182
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
183
   * get the singleton instance of Wechaty
L
lijiarui 已提交
184
   *
L
lijiarui 已提交
185 186
   * @param {WechatyOptions} [options={}]
   *
L
lijiarui 已提交
187 188 189 190 191 192 193
   * @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}`))
L
lijiarui 已提交
194
   * .start()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
195
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
196 197 198
  public static instance(
    options?: WechatyOptions,
  ) {
199
    if (options && this.globalInstance) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
200
      throw new Error('instance can be only inited once by options!')
201
    }
202 203
    if (!this.globalInstance) {
      this.globalInstance = new Wechaty(options)
204
    }
205
    return this.globalInstance
206 207
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
208
  /**
L
lijiarui 已提交
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
   * The term [Puppet](https://github.com/Chatie/wechaty/wiki/Puppet) in Wechaty is an Abstract Class for implementing protocol plugins.
   * The plugins are the component that helps Wechaty to control the Wechat(that's the reason we call it puppet).
   * The plugins are named XXXPuppet, for example:
   * - [PuppetPuppeteer](https://github.com/Chatie/wechaty-puppet-puppeteer):
   * - [PuppetPadchat](https://github.com/lijiarui/wechaty-puppet-padchat)
   *
   * @typedef    PuppetName
   * @property   {string}  wechat4u
   * The default puppet, using the [wechat4u](https://github.com/nodeWechat/wechat4u) to control the [WeChat Web API](https://wx.qq.com/) via a chrome browser.
   * @property   {string}  padchat
   * - Using the WebSocket protocol to connect with a Protocol Server for controlling the iPad Wechat program.
   * @property   {string}  puppeteer
   * - Using the [google puppeteer](https://github.com/GoogleChrome/puppeteer) to control the [WeChat Web API](https://wx.qq.com/) via a chrome browser.
   * @property   {string}  mock
   * - Using the mock data to mock wechat operation, just for test.
   */

  /**
   * The option parameter to create a wechaty instance
   *
   * @typedef    WechatyOptions
   * @property   {string}                 profile            -Wechaty Name. </br>
   *          When you set this: </br>
   *          `new Wechaty({profile: 'wechatyName'}) ` </br>
   *          it will generate a file called `wechatyName.memory-card.json`. </br>
   *          This file stores the bot's login information. </br>
   *          If the file is valid, the bot can auto login so you don't need to scan the qrcode to login again. </br>
   *          Also, you can set the environment variable for `WECHATY_PROFILE` to set this value when you start. </br>
   *          eg:  `WECHATY_PROFILE="your-cute-bot-name" node bot.js`
   * @property   {PuppetName | Puppet}    puppet             -Puppet name or instance
   * @property   {Partial<PuppetOptions>} puppetOptions      -Puppet TOKEN
   * @property   {string}                 ioToken            -Io TOKEN
   */

  /**
   * Creates an instance of Wechaty.
   * @param {WechatyOptions} [options={}]
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
247
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
248
  constructor(
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
249
    private options: WechatyOptions = {},
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
250
  ) {
251
    super()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
252 253
    log.verbose('Wechaty', 'contructor()')

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
254
    options.profile = options.profile === null
255
                      ? null
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
256
                      : (options.profile || config.default.DEFAULT_PROFILE)
257

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
258
    this.memory = new MemoryCard(options.profile || undefined)
259 260
    this.state  = new StateSwitch('Wechaty', log)
    this.id     = cuid()
261 262

    /**
L
lijiarui 已提交
263
     * @ignore
264 265 266 267 268 269 270
     * 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 (李卓桓) 已提交
271 272
    this.Contact     = cloneClass(Contact)
    this.ContactSelf = cloneClass(ContactSelf)
273
    this.Friendship  = cloneClass(Friendship)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
274 275
    this.Message     = cloneClass(Message)
    this.Room        = cloneClass(Room)
276 277
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
278
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
279
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
280
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
281 282 283 284 285 286
  public toString() {
    if (!this.options) {
      return this.constructor.name
    }

    return [
287 288
      'Wechaty#',
      this.id,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
289
      `<${this.options && this.options.puppet || ''}>`,
290
      `(${this.memory  && this.memory.name    || ''})`,
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
291 292
    ].join('')
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
293

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
294
  public emit(event: 'dong'       , data?: string)                                                    : boolean
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
295
  public emit(event: 'error'      , error: Error)                                                     : boolean
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
296
  public emit(event: 'friendship' , friendship: Friendship)                                           : boolean
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
297 298 299 300 301 302 303 304 305 306
  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
307 308 309 310 311 312 313 314 315 316 317

  // 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 (李卓桓) 已提交
318
  public on(event: 'dong'       , listener: string | ((this: Wechaty, data?: string) => void))                                                     : this
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
319
  public on(event: 'error'      , listener: string | ((this: Wechaty, error: Error) => void))                                                     : this
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
320
  public on(event: 'friendship' , listener: string | ((this: Wechaty, friendship: Friendship) => void))                                           : this
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
321 322 323 324 325 326 327 328 329 330
  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
331

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
335
  /**
L
lijiarui 已提交
336 337 338 339 340 341 342 343 344 345 346 347
   * @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.
L
lijiarui 已提交
348 349
   * @property   {string}  scan       - A scan event will be emitted when the bot needs to show you a QR Code for scanning. </br>
   *                                    It is recommend to install qrcode-terminal(run `npm install qrcode-terminal`) in order to show qrcode in the terminal.
L
lijiarui 已提交
350 351 352 353 354 355
   */

  /**
   * @desc       Wechaty Class Event Function
   * @typedef    WechatyEventFunction
   * @property   {Function} error           -(this: Wechaty, error: Error) => void callback function
356 357
   * @property   {Function} login           -(this: Wechaty, user: ContactSelf)=> void
   * @property   {Function} logout          -(this: Wechaty, user: ContactSelf) => void
L
lijiarui 已提交
358 359 360 361 362 363 364 365 366 367 368 369
   * @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 (李卓桓) 已提交
370
   * @property   {Function} friendship      -(this: Wechaty, friendship: Friendship) => void
L
lijiarui 已提交
371 372
   * @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 (李卓桓) 已提交
373
   * @property   {Function} room-topic      -(this: Wechaty, room: Room, newTopic: string, oldTopic: string, changer: Contact) => void
L
lijiarui 已提交
374 375 376 377 378
   * @property   {Function} room-leave      -(this: Wechaty, room: Room, leaverList: Contact[]) => void
   */

  /**
   * @listens Wechaty
379
   * @param   {WechatyEventName}      event      - Emit WechatyEvent
L
lijiarui 已提交
380 381
   * @param   {WechatyEventFunction}  listener   - Depends on the WechatyEvent
   *
L
lijiarui 已提交
382 383 384 385 386
   * @return  {Wechaty}                          - this for chaining,
   * see advanced {@link https://github.com/Chatie/wechaty-getting-started/wiki/FAQ-EN#36-why-wechatyonevent-listener-return-wechaty|chaining usage}
   *
   * @desc
   * When the bot get message, it will emit the following Event.
L
lijiarui 已提交
387
   *
L
lijiarui 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400
   * You can do anything you want when in these events functions.
   * The main Event name as follows:
   * - **scan**: Emit when the bot needs to show you a QR Code for scanning. After scan the qrcode, you can login
   * - **login**: Emit when bot login full successful.
   * - **logout**: Emit when bot detected log out.
   * - **message**: Emit when there's a new message.
   *
   * see more in {@link WechatyEventName}
   *
   * @example <caption>Event:scan</caption>
   * # Scan Event will emit when the bot needs to show you a QR Code for scanning
   *
   * bot.on('scan', (url: string, code: number) => {
L
lijiarui 已提交
401 402 403 404
   *   console.log(`[${code}] Scan ${url} to login.` )
   * })
   *
   * @example <caption>Event:login </caption>
L
lijiarui 已提交
405 406
   * # Login Event will emit when bot login full successful.
   *
407
   * bot.on('login', (user: ContactSelf) => {
L
lijiarui 已提交
408 409 410 411
   *   console.log(`user ${user} login`)
   * })
   *
   * @example <caption>Event:logout </caption>
L
lijiarui 已提交
412 413
   * # Logout Event will emit when bot detected log out.
   *
414
   * bot.on('logout', (user: ContactSelf) => {
L
lijiarui 已提交
415 416 417 418
   *   console.log(`user ${user} logout`)
   * })
   *
   * @example <caption>Event:message </caption>
L
lijiarui 已提交
419 420
   * # Message Event will emit when there's a new message.
   *
L
lijiarui 已提交
421 422 423 424
   * wechaty.on('message', (message: Message) => {
   *   console.log(`message ${message} received`)
   * })
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
425
   * @example <caption>Event:friendship </caption>
L
lijiarui 已提交
426 427
   * # Friendship Event will emit when got a new friend request, or friendship is confirmed.
   *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
428 429 430 431
   * 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 已提交
432 433 434 435 436
   *       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 (李卓桓) 已提交
437
   * 	  } else if (friendship.type() === Friendship.Type.CONFIRM) { // 2. confirm friendship
L
lijiarui 已提交
438 439 440 441 442
   *       console.log(`new friendship confirmed with ${contact.name()}`)
   *    }
   *  })
   *
   * @example <caption>Event:room-join </caption>
L
lijiarui 已提交
443 444
   * # room-join Event will emit when someone join the room.
   *
L
lijiarui 已提交
445 446 447 448 449 450
   * 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>
L
lijiarui 已提交
451 452
   * # room-leave Event will emit when someone leave the room.
   *
L
lijiarui 已提交
453 454 455 456 457 458
   * 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>
L
lijiarui 已提交
459 460
   * # room-topic Event will emit when someone change the room's topic.
   *
L
lijiarui 已提交
461 462 463
   * 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()}`)
   * })
L
lijiarui 已提交
464 465 466 467 468 469 470
   *
   * @example <caption>Event:error </caption>
   * # error Event will emit when there's an error occurred.
   *
   * bot.on('error', (error) => {
   *   console.error(error)
   * })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
471
   */
472
  public on(event: WechatyEventName, listener: string | ((...args: any[]) => any)): this {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
473
    log.verbose('Wechaty', 'on(%s, %s) registered',
474 475 476 477 478 479
                            event,
                            typeof listener === 'string'
                              ? listener
                              : typeof listener,
                )

480 481
    // DEPRECATED for 'friend' event
    if (event as any === 'friend') {
482
      log.warn('Wechaty', `on('friend', contact, friendRequest) is DEPRECATED. use on('friendship', friendship) instead`)
483 484 485
      if (typeof listener === 'function') {
        const oldListener = listener
        listener = (...args: any[]) => {
486
          log.warn('Wechaty', `on('friend', contact, friendRequest) is DEPRECATED. use on('friendship', friendship) instead`)
487 488 489 490 491
          oldListener.apply(this, args)
        }
      }
    }

492
    if (typeof listener === 'function') {
493
      this.addListenerFunction(event, listener)
494
    } else {
495
      this.addListenerModuleFile(event, listener)
496
    }
497
    return this
498 499
  }

500
  private addListenerModuleFile(event: WechatyEventName, modulePath: string): void {
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
    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)
      })
  }

520
  private addListenerFunction(event: WechatyEventName, listener: Function): void {
521 522 523 524 525 526 527 528 529 530 531 532
    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 (李卓桓) 已提交
533
  private async initPuppet(): Promise<void> {
534
    log.verbose('Wechaty', 'initPuppet() %s', this.options.puppet || '')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
535

536 537 538 539 540 541 542 543 544 545 546 547
    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 (李卓桓) 已提交
548
    const puppet = await this.initPuppetResolver(this.options.puppet)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
549 550 551

    this.initPuppetVersionSatisfy(puppet)
    this.initPuppetEventBridge(puppet)
552

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
553 554
    this.initPuppetAccessory(puppet)
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
555

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
556
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
557
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
558
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
559 560
  private initPuppetVersionSatisfy(puppet: Puppet): void {
    log.verbose('Wechaty', 'initPuppetVersionSatisfy(%s)', puppet)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
561

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
562
    if (this.initPuppetSemverSatisfy(
563 564
      puppet.wechatyVersionRange(),
    )) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
565
      return
566 567
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
568 569 570 571
    throw new Error(`The Puppet Plugin(${puppet.constructor.name}) `
      + `requires a version range(${puppet.wechatyVersionRange()}) `
      + `that is not satisfying the Wechaty version: ${this.version()}.`,
    )
572 573 574
  }

  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
575 576
   * @private
   *
577 578
   * Init the Puppet
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
579
  private async initPuppetResolver(puppet?: PuppetName | Puppet): Promise<Puppet> {
580 581
    log.verbose('Wechaty', 'initPuppetResolver(%s)', puppet)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
582
    if (!puppet) {
583 584
      puppet = config.systemPuppetName()
      log.info('Wechaty', 'initPuppet() using puppet: %s', puppet)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
585 586
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
587 588 589 590 591 592
    let puppetName = puppet as string
    if (typeof puppetName !== 'string') {
      puppetName = puppet.toString()
    }
    const puppetMemory = this.memory.sub(puppetName)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
593 594
    let puppetInstance: Puppet

595
    if (typeof puppet === 'string') {
596
      // tslint:disable-next-line:variable-name
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
597
      const MyPuppet = await puppetResolver(puppet)
598 599 600 601
      if (!MyPuppet) {
        throw new Error('no such puppet: ' + puppet)
      }

602 603 604 605 606 607 608 609 610 611 612
      /**
       * We will meet the following error:
       *
       *  [ts] Cannot use 'new' with an expression whose type lacks a call or construct signature.
       *
       * When we have different puppet with different `constructor()` args.
       * For example: PuppetA allow `constructor()` but PuppetB requires `constructor(options)`
       *
       * SOLUTION: we enforce all the PuppetImplenmentation to have `options` and should not allow default parameter.
       * Issue: https://github.com/Chatie/wechaty-puppet/issues/2
       */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
613
      puppetInstance = new MyPuppet(this.options.puppetOptions)
614

615
    } else if (puppet instanceof Puppet) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
616 617
      puppetInstance = puppet

618
    } else {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
619
      throw new Error('unsupported options.puppet: ' + puppet)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
620
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
621 622 623 624

    // give puppet the memory
    puppetInstance.setMemory(puppetMemory)

625 626
    log.info('Wechaty', 'initPuppet() inited puppet: %s', puppetInstance.toString())

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
627
    return puppetInstance
628
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
629

630
  /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
631 632
   * @private
   *
633 634 635
   * Plugin Version Range Check
   */
  private initPuppetSemverSatisfy(versionRange: string) {
636
    log.verbose('Wechaty', 'initPuppetSemverSatisfy(%s)', versionRange)
637
    return semver.satisfies(
638
      this.version(true),
639 640 641
      versionRange,
    )
  }
642

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
643
  protected initPuppetEventBridge(puppet: Puppet) {
644
    const eventNameList: PuppetEventName[] = Object.keys(PUPPET_EVENT_DICT) as any
645 646 647 648
    for (const eventName of eventNameList) {
      log.verbose('Wechaty', 'initPuppetEventBridge() puppet.on(%s) registered', eventName)

      switch (eventName) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
649 650 651 652 653 654 655
        case 'dong':
          puppet.removeAllListeners('dong')
          puppet.on('dong', data => {
            this.emit('dong', data)
          })
          break

656 657 658 659 660 661 662
        case 'error':
          puppet.removeAllListeners('error')
          puppet.on('error', error => {
            this.emit('error', new Error(error))
          })
          break

663
        case 'watchdog':
664
          puppet.removeAllListeners('heartbeat')
665 666 667 668
          puppet.on('watchdog', data => {
            /**
             * Use `watchdog` event from Puppet to `heartbeat` Wechaty.
             */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
669
            // TODO: use a throttle queue to prevent beat too fast.
670 671 672 673 674 675
            this.emit('heartbeat', data)
          })
          break

        case 'start':
        case 'stop':
676 677 678
          // do not emit 'start'/'stop' again for wechaty:
          // because both puppet & wechaty should have their own
          // `start`/`stop` event seprately
679 680
          break

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
681 682 683 684 685 686 687 688 689 690 691 692 693 694
        // 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 (李卓桓) 已提交
695 696 697 698 699 700 701 702 703 704 705
        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)
706 707 708 709 710 711
          })
          break

        case 'login':
          puppet.removeAllListeners('login')
          puppet.on('login', async contactId => {
712
            const contact = this.ContactSelf.load(contactId)
713 714 715 716 717 718 719 720
            await contact.ready()
            this.emit('login', contact)
          })
          break

        case 'logout':
          puppet.removeAllListeners('logout')
          puppet.on('logout', async contactId => {
721
            const contact = this.ContactSelf.load(contactId)
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
            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)
749
            room.emit('join', inviteeList, inviter)
750 751 752 753 754
          })
          break

        case 'room-leave':
          puppet.removeAllListeners('room-leave')
755
          puppet.on('room-leave', async (roomId, leaverIdList, removerId) => {
756 757 758 759 760 761
            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()))

762 763 764 765 766 767 768
            let remover: undefined | Contact = undefined
            if (removerId) {
              remover = this.Contact.load(removerId)
              await remover.ready()
            }

            this.emit('room-leave', room, leaverList, remover)
769
            room.emit('leave', leaverList, remover)
770 771 772 773 774
          })
          break

        case 'room-topic':
          puppet.removeAllListeners('room-topic')
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
775
          puppet.on('room-topic', async (roomId, newTopic, oldTopic, changerId) => {
776 777 778 779 780 781
            const room = this.Room.load(roomId)
            await room.ready()

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

Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
782 783
            this.emit('room-topic', room, newTopic, oldTopic, changer)
            room.emit('topic', newTopic, oldTopic, changer)
784 785 786 787 788
          })
          break

        case 'scan':
          puppet.removeAllListeners('scan')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
789 790
          puppet.on('scan', async (qrcode, status, data) => {
            this.emit('scan', qrcode, status, data)
791 792 793
          })
          break

794
        case 'watchdog':
795
        case 'reset':
796 797
          break

798
        default:
799
          throw new Error('eventName ' + eventName + ' unsupported!')
800 801

      }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
802
    }
803
  }
804

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

808
    /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
809
     * 1. Set Wechaty
810
     */
811 812 813 814 815
    this.Contact.wechaty     = this
    this.ContactSelf.wechaty = this
    this.Friendship.wechaty  = this
    this.Message.wechaty     = this
    this.Room.wechaty        = this
816

817
    /**
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
818
     * 2. Set Puppet
819
     */
820 821 822 823 824
    this.Contact.puppet     = puppet
    this.ContactSelf.puppet = puppet
    this.Friendship.puppet  = puppet
    this.Message.puppet     = puppet
    this.Room.puppet        = puppet
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
825 826

    this.puppet               = puppet
827 828
  }

829
  /**
L
lijiarui 已提交
830 831 832
   * @desc
   * use {@link Wechaty#start} instead
   * @deprecated
833 834 835 836 837
   */
  public async init(): Promise<void> {
    log.warn('Wechaty', 'init() DEPRECATED. use start() instead.')
    return this.start()
  }
838 839 840 841
  /**
   * Start the bot, return Promise.
   *
   * @returns {Promise<void>}
L
lijiarui 已提交
842 843 844
   * @description
   * When you start the bot, bot will begin to login, need you wechat scan qrcode to login
   * > Tips: All the bot operation needs to be triggered after start() is done
845 846 847 848 849
   * @example
   * await bot.start()
   * // do other stuff with bot here
   */
  public async start(): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
850 851 852 853
    log.info('Wechaty', '<%s> start() v%s is starting...' ,
                        this.options.puppet || config.systemPuppetName(),
                        this.version(),
            )
854 855
    log.verbose('Wechaty', 'puppet: %s'   , this.options.puppet)
    log.verbose('Wechaty', 'profile: %s'  , this.options.profile)
856
    log.verbose('Wechaty', 'id: %s'       , this.id)
857 858 859

    if (this.state.on()) {
      log.silly('Wechaty', 'start() on a starting/started instance')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
860
      await this.state.ready('on')
861 862 863 864
      log.silly('Wechaty', 'start() state.ready() resolved')
      return
    }

865 866 867 868
    if (this.lifeTimer) {
      throw new Error('start() lifeTimer exist')
    }

869 870 871
    this.state.on('pending')

    try {
872
      await this.memory.load()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
873

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
874
      await this.initPuppet()
875 876
      await this.puppet.start()

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
877 878 879 880 881 882 883 884
      if (this.options.ioToken) {
        this.io = new Io({
          token   : this.options.ioToken,
          wechaty : this,
        })
        await this.io.start()
      }

885
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
886
      console.error(e)
887 888
      log.error('Wechaty', 'start() exception: %s', e && e.message)
      Raven.captureException(e)
889 890 891 892 893 894 895 896 897 898 899
      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
      }
900 901 902 903
    }

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

904 905 906 907
    this.lifeTimer = setInterval(() => {
      log.silly('Wechaty', 'start() setInterval() this timer is to keep Wechaty running...')
    }, 1000 * 60 * 60)

908 909 910 911 912 913
    this.state.on(true)
    this.emit('start')

    return
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
914 915 916 917 918 919 920 921
  /**
   * Stop the bot
   *
   * @returns {Promise<void>}
   * @example
   * await bot.stop()
   */
  public async stop(): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
922 923 924 925
    log.info('Wechaty', '<%s> stop() v%s is stoping ...' ,
                        this.options.puppet || config.systemPuppetName(),
                        this.version(),
            )
926

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
927
    if (this.state.off()) {
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
928 929 930
      log.silly('Wechaty', 'stop() on an stopping/stopped instance')
      await this.state.ready('off')
      log.silly('Wechaty', 'stop() state.ready(off) resolved')
931
      return
932
    }
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
933

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
934
    this.state.off('pending')
935
    await this.memory.save()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
936

937 938 939 940 941
    if (this.lifeTimer) {
      clearInterval(this.lifeTimer)
      this.lifeTimer = undefined
    }

942
    try {
943
      await this.puppet.stop()
944 945 946
    } catch (e) {
      log.warn('Wechaty', 'stop() puppet.stop() exception: %s', e.message)
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
947

948
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
949 950 951 952 953
      if (this.io) {
        await this.io.stop()
        this.io = undefined
      }

954
    } catch (e) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
955
      log.error('Wechaty', 'stop() exception: %s', e.message)
956
      Raven.captureException(e)
957
      this.emit('error', e)
958
    }
959 960 961 962 963 964 965 966 967 968

    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())

969
    return
970
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
971

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
972
  /**
L
lijiarui 已提交
973 974 975 976 977
   * Logout the bot
   *
   * @returns {Promise<void>}
   * @example
   * await bot.logout()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
978
   */
979
  public async logout(): Promise<void>  {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
980 981
    log.verbose('Wechaty', 'logout()')

982 983 984 985 986 987 988
    try {
      await this.puppet.logout()
    } catch (e) {
      log.error('Wechaty', 'logout() exception: %s', e.message)
      Raven.captureException(e)
      throw e
    }
989
    return
990
  }
991

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
992 993 994 995 996
  /**
   * Get the logon / logoff state
   *
   * @returns {boolean}
   * @example
997
   * if (bot.logonoff()) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
998 999 1000 1001 1002
   *   console.log('Bot logined')
   * } else {
   *   console.log('Bot not logined')
   * }
   */
1003
  public logonoff(): Boolean {
1004
    return this.puppet.logonoff()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1005 1006
  }

1007
  /**
L
lijiarui 已提交
1008 1009
   * @description
   * Should use {@link Wechaty#userSelf} instead
1010 1011 1012
   * @deprecated
   */
  public self(): Contact {
1013
    log.warn('Wechaty', 'self() DEPRECATED. use userSelf() instead.')
1014 1015 1016
    return this.userSelf()
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1017
  /**
L
lijiarui 已提交
1018 1019
   * Get current user
   *
1020
   * @returns {ContactSelf}
L
lijiarui 已提交
1021
   * @example
1022
   * const contact = bot.userSelf()
L
lijiarui 已提交
1023
   * console.log(`Bot is ${contact.name()}`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1024
   */
1025
  public userSelf(): ContactSelf {
1026
    const userId = this.puppet.selfId()
1027
    const user = this.ContactSelf.load(userId)
1028
    return user
1029
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1030

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1031
  /**
L
lijiarui 已提交
1032 1033 1034 1035 1036
   * Send message to userSelf, in other words, bot send message to itself.
   * @param {(string | Contact | FileBox)} textOrContactOrFile
   * send text, Contact, or file to bot. </br>
   * You can use {@link https://www.npmjs.com/package/file-box|FileBox} to send file
   * @returns {Promise<void>}
L
lijiarui 已提交
1037
   *
L
lijiarui 已提交
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
   * @example
   * const bot = new Wechaty()
   * await bot.start()
   * // after logged in
   *
   * # 1. send text to bot itself
   * await bot.say('hello!')
   *
   * # 2. send Contact to bot itself
   * const contact = bot.Contact.load('contactId')
   * await bot.say(contact)
   *
   * # 3. send Image to bot itself from remote url
   * import { FileBox }  from 'file-box'
   * const fileBox = FileBox.fromUrl('https://chatie.io/wechaty/images/bot-qr-code.png')
   * await bot.say(fileBox)
   *
   * # 4. send Image to bot itself from local file
   * import { FileBox }  from 'file-box'
   * const fileBox = FileBox.fromLocal('/tmp/text.jpg')
   * await bot.say(fileBox)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1059
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
  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')
    }
1073 1074
  }

L
lijiarui 已提交
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
  /**
   * @private
   */
  public static version(forceNpm = false): string {
    if (!forceNpm) {
      const revision = config.gitRevision()
      if (revision) {
        return `#git[${revision}]`
      }
    }
    return VERSION
  }

 /**
  * Return version of Wechaty
  *
  * @param {boolean} [forceNpm=false]  - If set to true, will only return the version in package.json. </br>
  *                                      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'
  */
  public version(forceNpm = false): string {
    return Wechaty.version(forceNpm)
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1102
  /**
L
lijiarui 已提交
1103
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1104
   */
1105
  public static async sleep(millisecond: number): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1106
    await new Promise(resolve => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1107 1108 1109 1110
      setTimeout(resolve, millisecond)
    })
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1111
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
1112
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1113
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1114 1115 1116
  public ding(data?: string): void {
    log.silly('Wechaty', 'ding(%s)', data || '')

1117
    try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1118
      this.puppet.ding(data)
1119 1120 1121
    } catch (e) {
      log.error('Wechaty', 'ding() exception: %s', e.message)
      Raven.captureException(e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1122
      throw e
1123
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1124
  }
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139

  /**
   * @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 (李卓桓) 已提交
1140 1141 1142 1143 1144

  /**
   * @private
   */
  public async reset(reason?: string): Promise<void> {
1145
    log.verbose('Wechaty', 'reset() because %s', reason || 'no reason')
Huan (李卓桓)'s avatar
wip...  
Huan (李卓桓) 已提交
1146 1147
    await this.puppet.stop()
    await this.puppet.start()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1148 1149 1150
    return
  }

1151 1152 1153
  public unref(): void {
    log.warn('Wechaty', 'unref() To Be Implemented. See: https://github.com/Chatie/wechaty/issues/1197')
  }
1154
}
1155 1156

export default Wechaty