ding-dong-bot.js 1.7 KB
Newer Older
Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
1
const Wechaty = require('../src/wechaty')
2
const log = require('npmlog')
Huan (李卓桓)'s avatar
doc  
Huan (李卓桓) 已提交
3
//log.level = 'verbose'
4
//log.level = 'silly'
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

const welcome = `
| __        __        _           _         
| \\ \\      / /__  ___| |__   __ _| |_ _   _ 
|  \\ \\ /\\ / / _ \\/ __| '_ \\ / _\` | __| | | |
|   \\ V  V /  __/ (__| | | | (_| | |_| |_| |
|    \\_/\\_/ \\___|\\___|_| |_|\\__,_|\\__|\\__, |
|                                     |___/ 

=============== 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'!
__________________________________________________

Hope you like it, and you are very welcome to 
upgrade me for more super powers!

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

`

console.log(welcome)
const bot = new Wechaty()
31

32 33 34
bot.init()
.then(login)

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
35
bot.on('message', m => {
36
  m.ready()
Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
37 38 39
  .then (msg  => {
    log.info ('Bot', 'recv: %s'  , msg)
  })
40
  .catch(e    => log.error('Bot', 'ready: %s' , e))
41

Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
42
  if (/^(ding|ping|bing)$/i.test(m.get('content'))) {
Huan (李卓桓)'s avatar
format  
Huan (李卓桓) 已提交
43
    const r = new Wechaty.Message()
Huan (李卓桓)'s avatar
bug fix  
Huan (李卓桓) 已提交
44
    r.set('to', m.inGroup() ? m.get('group') : m.get('from'))
Huan (李卓桓)'s avatar
format  
Huan (李卓桓) 已提交
45 46
    r.set('content', 'dong')
    bot.send(r)
47
    .then(() => { log.warn('Bot', 'REPLY: dong') })
Huan (李卓桓)'s avatar
format  
Huan (李卓桓) 已提交
48
  }
49 50 51
})

function login() {
Huan (李卓桓)'s avatar
format  
Huan (李卓桓) 已提交
52
  log.info('Bot', 'Welcome to Wechaty')
53

Huan (李卓桓)'s avatar
format  
Huan (李卓桓) 已提交
54 55 56 57 58
  bot.puppet
  .getLoginQrImgUrl()
  .then(url =>
        console.log(`\n\nAction needed. Scan the belowing QRCode to login:\n\n${url}\n\nTip: You can copy/paste it to a web browser.\n`) 
       ).catch(e => log.error('Bot', 'promise rejected'))
59 60 61 62
}

bot.on('login'	, () => npm.info('Bot', 'logined'))
bot.on('logout'	, () => npm.info('Bot', 'logouted'))