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
import {
10 11
  Wechaty
  , Config
12
  , log
13
} from '../'
14 15

const welcome = `
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
16 17
| __        __        _           _
| \\ \\      / /__  ___| |__   __ _| |_ _   _
18 19 20
|  \\ \\ /\\ / / _ \\/ __| '_ \\ / _\` | __| | | |
|   \\ V  V /  __/ (__| | | | (_| | |_| |_| |
|    \\_/\\_/ \\___|\\___|_| |_|\\__,_|\\__|\\__, |
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
21
|                                     |___/
22 23 24 25 26 27 28 29 30

=============== 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 (李卓桓) 已提交
31
Hope you like it, and you are very welcome to
32 33 34 35 36 37 38
upgrade me for more super powers!

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

`

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

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

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
60
    if (/^(ding|ping|bing)$/i.test(m.content()) && !m.self()) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
61 62
      m.say('dong')
      log.info('Bot', 'REPLY: dong')
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
63
    }
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
64 65 66
  } catch (e) {
    log.error('Bot', 'on(message) exception: %s' , e)
  }
67 68
})

69 70 71 72 73 74
bot.init()
.catch(e => {
  log.error('Bot', 'init() fail: %s', e)
  bot.quit()
  process.exit(-1)
})
75 76

function logToFile(data) {
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
77 78 79 80 81 82
  require('fs').appendFile('message.log', data + '\n\n#############################\n\n', err => {
    if (err) { log.error('LogToFile: %s', err) }
  })
}
if (typeof logToFile === 'fasdfsd') {
  console.log('disable linting warning')
83
}