ding-dong-bot.ts 2.1 KB
Newer Older
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
1 2 3 4 5 6 7 8
/**
 *
 * Wechaty - Wechat for Bot
 *
 * Connecting ChatBots
 * https://github.com/wechaty/wechaty
 *
 */
9 10

/* tslint:disable:variable-name */
11
const QrcodeTerminal  = require('qrcode-terminal')
12
const finis           = require('finis')
13

14
import {
15 16
  Wechaty
  , Config
17
  , log
18
} from '../'
19 20

const welcome = `
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
21 22
| __        __        _           _
| \\ \\      / /__  ___| |__   __ _| |_ _   _
23 24 25
|  \\ \\ /\\ / / _ \\/ __| '_ \\ / _\` | __| | | |
|   \\ V  V /  __/ (__| | | | (_| | |_| |_| |
|    \\_/\\_/ \\___|\\___|_| |_|\\__,_|\\__|\\__, |
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
26
|                                     |___/
27 28 29 30 31 32 33 34 35

=============== Powered by Wechaty ===============
-------- https://github.com/zixia/wechaty --------

I'm a bot, my super power is talk in Wechat.

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
36
Hope you like it, and you are very welcome to
37 38 39 40 41 42 43
upgrade me for more super powers!

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

`

console.log(welcome)
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
44
const bot = Wechaty.instance({ profile: Config.DEFAULT_PROFILE })
45

46
bot
47 48 49 50
.on('login'	  , user => {
  log.info('Bot', `${user.name()} logined`)
  bot.say('Wechaty login')
})
51
.on('logout'	, user => log.info('Bot', `${user.name()} logouted`))
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
52
.on('error'   , e => log.info('Bot', 'error: %s', e))
53
.on('scan', (url, code) => {
54
  if (!/201|200/.test(String(code))) {
55
    let loginUrl = url.replace(/\/qrcode\//, '/l/')
56
    QrcodeTerminal.generate(loginUrl)
57
  }
58
  console.log(`${url}\n[${code}] Scan QR Code in above url to login: `)
59
})
60
.on('message', m => {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
61
  try {
62 63
    const room = m.room()
    console.log((room ? '[' + room.topic() + ']' : '')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
64
                + '<' + m.from().name() + '>'
65 66 67
                + ':' + m.toStringDigest()
    )

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
68
    if (/^(ding|ping|bing)$/i.test(m.content()) && !m.self()) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
69 70
      m.say('dong')
      log.info('Bot', 'REPLY: dong')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
71
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
72 73 74
  } catch (e) {
    log.error('Bot', 'on(message) exception: %s' , e)
  }
75 76
})

77 78 79 80 81 82
bot.init()
.catch(e => {
  log.error('Bot', 'init() fail: %s', e)
  bot.quit()
  process.exit(-1)
})
83

84
finis((code, reason) => {
85 86 87
  const exitMsg = `Wechaty exit ${code} because of ${reason} `
  console.log(exitMsg)
  bot.say(exitMsg)
88
})