wechaty.ts 16.9 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
 */
L
lijiarui 已提交
20

21
import { EventEmitter } from 'events'
22

23 24
import { StateSwitch }  from 'state-switch'

25
import {
26
  config,
27 28
  HeadName,
  PuppetName,
29
  Raven,
30 31 32
  Sayable,
  log,
}                         from './config'
33

34 35
import { Contact }        from './contact'
import { FriendRequest }  from './friend-request'
M
Mukaiu 已提交
36 37 38 39
import {
  Message,
  MediaMessage,
}                         from './message'
40 41 42 43
import { Puppet }         from './puppet'
import { PuppetWeb }      from './puppet-web/'
import { Room }           from './room'
import { UtilLib }        from './util-lib'
44

45
export interface PuppetSetting {
L
lijiarui 已提交
46 47 48
  head?:    HeadName,
  puppet?:  PuppetName,
  profile?: string,
49
}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
50

51 52 53 54 55 56 57 58 59 60
export type WechatyEventName = 'error'
                              | 'friend'
                              | 'heartbeat'
                              | 'login'
                              | 'logout'
                              | 'message'
                              | 'room-join'
                              | 'room-leave'
                              | 'room-topic'
                              | 'scan'
61

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
79 80
  /**
   * the puppet
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
81
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
82
   */
83
  public puppet: Puppet | null
84

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
85 86
  /**
   * the state
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
87
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
88
   */
89
  private state = new StateSwitch<'standby', 'ready'>('Wechaty', 'standby', log)
90

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
91 92
  /**
   * the uuid
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
93
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
94
   */
95
  public uuid:        string
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
96

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
119
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
120
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
121
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
122
  private constructor(private setting: PuppetSetting = {}) {
123
    super()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
124 125
    log.verbose('Wechaty', 'contructor()')

126 127 128
    setting.head    = setting.head    || config.head
    setting.puppet  = setting.puppet  || config.puppet
    setting.profile = setting.profile || config.profile
129

130
    // setting.port    = setting.port    || Config.port
131

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
132 133
    if (setting.profile) {
      setting.profile  = /\.wechaty\.json$/i.test(setting.profile)
134 135
                        ? setting.profile
                        : setting.profile + '.wechaty.json'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
136
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
137

138
    this.uuid = UtilLib.guid()
139 140
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
141
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
142
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
143
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
144
  public toString() { return 'Class Wechaty(' + this.setting.puppet + ')'}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
145

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

H
hcz 已提交
166
  /**
L
lijiarui 已提交
167
   * @private
H
hcz 已提交
168
   */
169 170
  public version(forceNpm?) {
    return Wechaty.version(forceNpm)
171
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
172

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
173
  /**
L
lijiarui 已提交
174
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
175
   */
Huan (李卓桓)'s avatar
fix #54  
Huan (李卓桓) 已提交
176
  public user(): Contact {
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
177 178
    log.warn('Wechaty', 'user() DEPRECATED. use self() instead.')

Huan (李卓桓)'s avatar
fix #54  
Huan (李卓桓) 已提交
179 180 181 182 183
    if (!this.puppet || !this.puppet.user) {
      throw new Error('no user')
    }
    return this.puppet.user
  }
184

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
185
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
186
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
187
   */
188
  public async reset(reason?: string): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
189
    log.verbose('Wechaty', 'reset() because %s', reason)
190 191 192
    if (!this.puppet) {
      throw new Error('no puppet')
    }
193 194
    await this.puppet.reset(reason)
    return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
195
  }
196

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
197
  /**
L
lijiarui 已提交
198 199 200 201 202 203
   * Initialize the bot, return Promise.
   *
   * @returns {Promise<void>}
   * @example
   * await bot.init()
   * // do other stuff with bot here
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
204
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
205
  public async init(): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
206
    log.info('Wechaty', 'v%s initializing...' , this.version())
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
207
    log.verbose('Wechaty', 'puppet: %s'       , this.setting.puppet)
208 209
    log.verbose('Wechaty', 'head: %s'         , this.setting.head)
    log.verbose('Wechaty', 'profile: %s'      , this.setting.profile)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
210
    log.verbose('Wechaty', 'uuid: %s'         , this.uuid)
211

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
212
    if (this.state.current() === 'ready') {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
213
      log.error('Wechaty', 'init() already inited. return and do nothing.')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
214
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
215 216
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
217
    this.state.target('ready')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
218 219
    this.state.current('ready', false)

220 221 222
    try {
      await this.initPuppet()
    } catch (e) {
Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
223
      log.error('Wechaty', 'init() exception: %s', e && e.message)
224
      Raven.captureException(e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
225
      throw e
226
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
227 228

    this.state.current('ready')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
229
    return
230
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
231

232 233 234 235 236 237 238 239
  public on(event: 'error'      , listener: (this: Wechaty, error: Error) => void):                                                  this
  public on(event: 'friend'     , listener: (this: Wechaty, friend: Contact, request?: FriendRequest) => void):                      this
  public on(event: 'heartbeat'  , listener: (this: Wechaty, data: any) => void):                                                     this
  public on(event: 'logout'     , listener: (this: Wechaty, user: Contact) => void):                                                 this
  public on(event: 'login'      , listener: (this: Wechaty, user: Contact) => void):                                                 this
  public on(event: 'message'    , listener: (this: Wechaty, message: Message) => void):                                              this
  public on(event: 'room-join'  , listener: (this: Wechaty, room: Room, inviteeList: Contact[],  inviter: Contact) => void):         this
  public on(event: 'room-leave' , listener: (this: Wechaty, room: Room, leaverList: Contact[]) => void):                             this
240
  public on(event: 'room-topic' , listener: (this: Wechaty, room: Room, topic: string, oldTopic: string, changer: Contact) => void): this
241
  public on(event: 'scan'       , listener: (this: Wechaty, url: string, code: number) => void):                                     this
L
lijiarui 已提交
242

243 244
  // guard for the above event: make sure it includes all the possible values
  public on(event: never,         listener: any): this
L
lijiarui 已提交
245

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
246
  /**
L
lijiarui 已提交
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 289 290 291 292 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
   * @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}  scan       - A scan event will be emitted when the bot needs to show you a QR Code for scanning.
   * @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.
   */

  /**
   * @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
   * @param   {WechatyEventName}      event      - Emit WechatyEvent
   * @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 (李卓桓) 已提交
345
   */
346
  public on(event: WechatyEventName, listener: (...args: any[]) => any): this {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
347
    log.verbose('Wechaty', 'addListener(%s, %s)', event, typeof listener)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
348
    super.on(event, listener) // `this: Wechaty` is Sayable
349
    return this
350 351
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
352
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
353
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
354
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
355
  public async initPuppet(): Promise<Puppet> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
356
    let puppet: Puppet
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
357 358 359 360 361

    if (!this.setting.head) {
      throw new Error('no head')
    }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
362
    switch (this.setting.puppet) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
363
      case 'web':
364
        puppet = new PuppetWeb({
L
lijiarui 已提交
365 366
          head:     this.setting.head,
          profile:  this.setting.profile,
367
        })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
368
        break
369

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
370
      default:
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
371
        throw new Error('Puppet unsupport(yet?): ' + this.setting.puppet)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
372
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
373

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
374
    const eventList: WechatyEventName[] = [
L
lijiarui 已提交
375 376 377 378 379 380 381 382 383 384
      'error',
      'friend',
      'heartbeat',
      'login',
      'logout',
      'message',
      'room-join',
      'room-leave',
      'room-topic',
      'scan',
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
385 386 387
    ]

    eventList.map(e => {
388 389
      // https://strongloop.com/strongblog/an-introduction-to-javascript-es6-arrow-functions/
      // We’ve lost () around the argument list when there’s just one argument (rest arguments are an exception, eg (...args) => ...)
390
      puppet.on(e, (...args: any[]) => {
391 392
        // this.emit(e, data)
        this.emit.apply(this, [e, ...args])
393
      })
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
394
    })
395

396
    // set puppet before init, because we need this.puppet if we quit() before init() finish
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
397
    this.puppet = <Puppet>puppet // force to use base class Puppet interface for better encapsolation
398 399

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

402
    await puppet.init()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
403
    return puppet
404 405
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
406
  /**
L
lijiarui 已提交
407 408 409 410 411
   * Quit the bot
   *
   * @returns {Promise<void>}
   * @example
   * await bot.quit()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
412
   */
413
  public async quit(): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
414
    log.verbose('Wechaty', 'quit()')
415 416 417 418 419 420 421

    if (this.state.current() !== 'ready' || this.state.inprocess()) {
      const err = new Error('quit() must run on a inited instance.')
      log.error('Wechaty', err.message)
      throw err
    }
    this.state.target('standby')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
422
    this.state.current('standby', false)
423

424 425
    if (!this.puppet) {
      log.warn('Wechaty', 'quit() without this.puppet')
426
      return
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
427 428
    }

429
    const puppetBeforeDie = this.puppet
430
    this.puppet     = null
431
    config.puppetInstance(null)
432

433 434 435 436 437 438 439
    try {
      await puppetBeforeDie.quit()
    } catch (e) {
      log.error('Wechaty', 'quit() exception: %s', e.message)
      Raven.captureException(e)
      throw e
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
440
    this.state.current('standby')
441
    return
442
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
443

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
444
  /**
L
lijiarui 已提交
445 446 447 448 449
   * Logout the bot
   *
   * @returns {Promise<void>}
   * @example
   * await bot.logout()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
450
   */
451
  public async logout(): Promise<void>  {
452 453 454
    if (!this.puppet) {
      throw new Error('no puppet')
    }
455 456 457 458 459 460 461
    try {
      await this.puppet.logout()
    } catch (e) {
      log.error('Wechaty', 'logout() exception: %s', e.message)
      Raven.captureException(e)
      throw e
    }
462
    return
463
  }
464

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
465
  /**
L
lijiarui 已提交
466 467 468 469 470 471
   * Get current user
   *
   * @returns {Contact}
   * @example
   * const contact = bot.self()
   * console.log(`Bot is ${contact.name()}`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
472
   */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
473
  public self(): Contact {
474
    if (!this.puppet) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
475
      throw new Error('Wechaty.self() no puppet')
476
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
477
    return this.puppet.self()
478
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
479

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
480
  /**
L
lijiarui 已提交
481
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
482
   */
483
  public async send(message: Message | MediaMessage): Promise<boolean> {
484 485 486
    if (!this.puppet) {
      throw new Error('no puppet')
    }
487 488 489 490 491 492 493
    try {
      return await this.puppet.send(message)
    } catch (e) {
      log.error('Wechaty', 'send() exception: %s', e.message)
      Raven.captureException(e)
      throw e
    }
494
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
495

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
496
  /**
L
lijiarui 已提交
497 498 499 500
   * Send message to filehelper
   *
   * @param {string} content
   * @returns {Promise<boolean>}
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
501
   */
502
  public async say(content: string): Promise<boolean> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
503 504
    log.verbose('Wechaty', 'say(%s)', content)

505 506 507
    if (!this.puppet) {
      throw new Error('no puppet')
    }
508
    return await this.puppet.say(content)
509 510
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
511
  /**
L
lijiarui 已提交
512
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
513
   */
514
  public static async sleep(millisecond: number): Promise<void> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
515
    await new Promise(resolve => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
516 517 518 519
      setTimeout(resolve, millisecond)
    })
  }

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
520
  /**
Huan (李卓桓)'s avatar
jsdoc  
Huan (李卓桓) 已提交
521
   * @private
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
522
   */
523
  public async ding(): Promise<string> {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
524 525 526 527
    if (!this.puppet) {
      return Promise.reject(new Error('wechaty cant ding coz no puppet'))
    }

528 529 530 531 532 533 534
    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 (李卓桓) 已提交
535
  }
536
}
537 538

export default Wechaty