ding-dong-bot.ts 5.5 KB
Newer Older
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1
/**
2
 *   Wechaty - https://github.com/chatie/wechaty
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
3
 *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
4
 *   @copyright 2016-2018 Huan LI <zixia@zixia.net>
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
5
 *
6 7 8 9 10 11 12 13 14 15 16
 *   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
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   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.
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
17 18
 *
 */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
19
import * as path      from 'path'
20 21

/* tslint:disable:variable-name */
22 23
import * as QrcodeTerminal  from 'qrcode-terminal'
import finis                from 'finis'
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
24
import { FileBox }          from 'file-box'
25

26 27 28 29 30
/**
 * Change `import { ... } from '../'`
 * to     `import { ... } from 'wechaty'`
 * when you are runing with Docker or NPM instead of Git Source.
 */
31
import {
Huan (李卓桓)'s avatar
clean  
Huan (李卓桓) 已提交
32 33
  Wechaty,
  log,
34
}               from '../src/'
35

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
36 37 38 39 40
const BOT_QR_CODE_IMAGE_FILE = path.join(
  __dirname,
  '../docs/images/bot-qr-code.png',
)

41
const welcome = `
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
42 43
| __        __        _           _
| \\ \\      / /__  ___| |__   __ _| |_ _   _
44 45 46
|  \\ \\ /\\ / / _ \\/ __| '_ \\ / _\` | __| | | |
|   \\ V  V /  __/ (__| | | | (_| | |_| |_| |
|    \\_/\\_/ \\___|\\___|_| |_|\\__,_|\\__|\\__, |
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
47
|                                     |___/
48 49

=============== Powered by Wechaty ===============
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
50
-------- https://github.com/chatie/wechaty --------
51

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
52
I'm a bot, my superpower is talk in Wechat.
53 54 55 56

If you send me a 'ding', I will reply you a 'dong'!
__________________________________________________

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
57
Hope you like it, and you are very welcome to
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
58
upgrade me to more superpowers!
59 60 61 62 63 64

Please wait... I'm trying to login in...

`

console.log(welcome)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
65
const bot = Wechaty.instance()
66

67
bot
Huan (李卓桓)'s avatar
clean  
Huan (李卓桓) 已提交
68
.on('logout'	, user => log.info('Bot', `${user.name()} logouted`))
69
.on('login'	  , user => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
70
  log.info('Bot', `${user.name()} login`)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
71
  bot.say('Wechaty login').catch(console.error)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
72
})
73
.on('scan', (url, code) => {
74
  if (!/201|200/.test(String(code))) {
75
    const loginUrl = url.replace(/\/qrcode\//, '/l/')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
76 77 78 79 80
    QrcodeTerminal.generate(loginUrl, { small: true }, (qrcode: string) => {
      console.log(qrcode)
      console.log(url)
      console.log(`[${code}] Scan QR Code above url to log in: `)
    })
81
  }
82
})
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
83
.on('message', async msg => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
84
  try {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
85
    console.log(msg.toString())
86

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
87
    if (/^(ding|ping|bing|code)$/i.test(msg.text()) && !msg.self()) {
88 89 90
      /**
       * 1. reply 'dong'
       */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
91
      log.info('Bot', 'REPLY: dong')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
92
      msg.say('dong')
93

94 95 96 97
      const joinWechaty =  `Join Wechaty Developers' Community\n\n` +
                            `Wechaty is used in many ChatBot projects by hundreds of developers.\n\n` +
                            `If you want to talk with other developers, just scan the following QR Code in WeChat with secret code: wechaty,\n\n` +
                            `you can join our Wechaty Developers' Home at once`
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
98
      await msg.say(joinWechaty)
99 100 101 102

      /**
       * 2. reply qrcode image
       */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
103 104 105
      const fileBox = FileBox.fromLocal(BOT_QR_CODE_IMAGE_FILE)

      log.info('Bot', 'REPLY: %s', fileBox)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
106
      await msg.say(fileBox)
107 108 109 110

      /**
       * 3. reply 'scan now!'
       */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
111
      await msg.say('Scan now, because other Wechaty developers want to talk with you too!\n\n(secret code: wechaty)')
112

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
113
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
114 115
  } catch (e) {
    log.error('Bot', 'on(message) exception: %s' , e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
116
    console.error(e)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
117
  }
118 119
})

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
120 121
bot.on('error', async e => {
  log.error('Bot', 'error: %s', e)
122
  if (bot.logonoff()) {
123 124
    await bot.say('Wechaty error: ' + e.message).catch(console.error)
  }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
125
  // await bot.stop()
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
126 127
})

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
let killChrome: NodeJS.SignalsListener

bot.start()
.then(() => {
  const listenerList = process.listeners('SIGINT')
  for (const listener of listenerList) {
    if (listener.name === 'killChrome') {
      process.removeListener('SIGINT', listener)
      killChrome = listener
    }
  }
})
.catch(e => {
  log.error('Bot', 'start() fail: %s', e)
  bot.stop()
  process.exit(-1)
})

146
let quiting = false
147 148 149 150 151 152 153 154
finis((code, signal) => {
  log.info('Bot', 'finis(%s, %s)', code, signal)

  if (!bot.logonoff()) {
    log.info('Bot', 'finis() bot had been already stopped')
    doExit(code)
  }

155
  if (quiting) {
156
    log.warn('Bot', 'finis() already quiting... return and wait...')
157 158
    return
  }
159

160
  quiting = true
161 162 163
  let done = false
  // let checkNum = 0

164
  const exitMsg = `Wechaty will exit ${code} because of ${signal} `
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181

  log.info('Bot', 'finis() broadcast quiting message for bot')
  bot.say(exitMsg)
      // .then(() => bot.stop())
      .catch(e => log.error('Bot', 'finis() catch rejection: %s', e))
      .then(() => done = true)

  setImmediate(checkForExit)

  function checkForExit() {
    // if (checkNum++ % 100 === 0) {
    log.info('Bot', 'finis() checkForExit() checking done: %s', done)
    // }
    if (done) {
      log.info('Bot', 'finis() checkForExit() done!')
      setTimeout(() => doExit(code), 1000)  // delay 1 second
      return
182
    }
183 184 185 186 187
    // death loop to wait for `done`
    // process.nextTick(checkForExit)
    // setImmediate(checkForExit)
    setTimeout(checkForExit, 100)
  }
188
})
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204

function doExit(code: number): void {
  log.info('Bot', 'doExit(%d)', code)
  if (killChrome) {
    killChrome('SIGINT')
  }
  process.exit(code)
}

// process.on('SIGINT', function() {
//   console.log('Nice SIGINT-handler')
//   const listeners = process.listeners('SIGINT')
//   for (let i = 0; i < listeners.length; i++) {
//       console.log(listeners[i].toString())
//   }
// })