提交 63486af0 编写于 作者: Huan (李卓桓)'s avatar Huan (李卓桓)

clean ding-dong code

上级 bf638c12
......@@ -16,31 +16,25 @@
* limitations under the License.
*
*/
import * as fs from 'fs'
import * as path from 'path'
import {
Contact,
Message,
Wechaty,
} from '../' // from 'wechaty'
// import { PuppetPuppeteer } from 'wechaty-puppet-puppeteer'
/* tslint:disable:variable-name */
import { generate } from 'qrcode-terminal'
import { finis } from 'finis'
import { FileBox } from 'file-box'
import { generate } from 'qrcode-terminal'
/**
* Change `import { ... } from '../'`
* to `import { ... } from 'wechaty'`
* when you are runing with Docker or NPM instead of Git Source.
*
* 0. Declare your bot!
*
*/
import {
Wechaty,
log,
qrcodeValueToImageUrl,
} from '../src/'
const BOT_QR_CODE_IMAGE_FILE = path.resolve(
__dirname,
'../docs/images/bot-qr-code.png',
)
const bot = Wechaty.instance()
const bot = new Wechaty({
profile : 'padchat-demo',
// puppet : new PuppetPupeteer(),
})
const welcome = `
| __ __ _ _
......@@ -68,144 +62,110 @@ Please wait... I'm trying to login in...
console.log(welcome)
bot
.on('logout' , user => log.info('Bot', `${user.name()} logouted`))
.on('login' , user => {
log.info('Bot', `${user.name()} login`)
bot.say('Wechaty login').catch(console.error)
})
.on('scan', (qrcode, status, data) => {
/**
*
* 1. Define Event Handler Functions for:
* `scan`, `login`, `logout`, `error`, and `message`
*
*/
function onScan (qrcode: string, status: number) {
generate(qrcode, { small: true })
if (data) {
console.log(data)
}
console.log(qrcodeValueToImageUrl(qrcode))
console.log('^^^ Online QR Code Image URL ^^^ ')
console.log(`[${status}] ${qrcode} Scan QR Code above url to log in: `)
})
.on('message', async msg => {
try {
console.log(msg.toString())
if (/^(ding|ping|bing|code)$/i.test(msg.text()) /*&& !msg.self()*/) {
/**
* 1. reply 'dong'
*/
log.info('Bot', 'REPLY: dong')
await msg.say('dong')
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`
await msg.say(joinWechaty)
/**
* 2. reply qrcode image
*/
// const fileBox = FileBox.packLocal(BOT_QR_CODE_IMAGE_FILE)
const fileBox = FileBox.fromStream(
fs.createReadStream(BOT_QR_CODE_IMAGE_FILE),
BOT_QR_CODE_IMAGE_FILE,
)
log.info('Bot', 'REPLY: %s', fileBox.toString())
await msg.say(fileBox)
/**
* 3. reply 'scan now!'
*/
await msg.say('Scan now, because other Wechaty developers want to talk with you too!\n\n(secret code: wechaty)')
}
} catch (e) {
log.error('Bot', 'on(message) exception: %s' , e)
console.error(e)
}
})
bot.on('error', async e => {
log.error('Bot', 'error: %s', e)
if (bot.logonoff()) {
await bot.say('Wechaty error: ' + e.message).catch(console.error)
}
// await bot.stop()
})
const qrcodeImageUrl = [
'https://api.qrserver.com/v1/create-qr-code/?data=',
encodeURIComponent(qrcode),
'&size=220x220&margin=0',
].join('')
let killChrome: NodeJS.SignalsListener
console.log(`[${status}] ${qrcodeImageUrl}\nScan QR Code above to log in: `)
}
bot.start()
.then(() => {
const listenerList = process.listeners('SIGINT')
for (const listener of listenerList) {
if (listener.name === 'killChrome') {
process.removeListener('SIGINT', listener)
killChrome = listener
}
}
})
.catch(async e => {
log.error('Bot', 'start() fail: %s', e)
await bot.stop()
process.exit(-1)
})
function onLogin (user: Contact) {
console.log(`${user.name()} login`)
bot.say('Wechaty login').catch(console.error)
}
let quiting = false
finis(async (code, signal) => {
log.info('Bot', 'finis(%s, %s)', code, signal)
function onLogout (user: Contact) {
console.log(`${user.name()} logouted`)
}
if (!bot.logonoff()) {
log.info('Bot', 'finis() bot had been already stopped')
doExit(code)
function onError (e: Error) {
console.error('Bot error:', e)
if (bot.logonoff()) {
bot.say('Wechaty error: ' + e.message).catch(console.error)
}
}
if (quiting) {
log.warn('Bot', 'finis() already quiting... return and wait...')
/**
*
* 2. The most important handler is for:
* dealing with Messages.
*
*/
async function onMessage (msg: Message) {
console.log(msg.toString())
if (msg.age() > 60) {
console.log('Message TOO OLD(than 1 minute), discarded.')
return
}
quiting = true
let done = false
// let checkNum = 0
const exitMsg = `Wechaty will exit ${code} because of ${signal} `
log.info('Bot', 'finis() broadcast quiting message for bot')
await 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
}
// death loop to wait for `done`
// process.nextTick(checkForExit)
// setImmediate(checkForExit)
setTimeout(checkForExit, 100)
if (!/^(ding|ping|bing|code)$/i.test(msg.text()) /*&& !msg.self()*/) {
console.log('Message NOT MATCH, discarded.')
return
}
})
function doExit(code: number): void {
log.info('Bot', 'doExit(%d)', code)
if (killChrome) {
killChrome('SIGINT')
}
process.exit(code)
/**
* 1. reply 'dong'
*/
await msg.say('dong')
console.log('REPLY: dong')
/**
* 2. reply image(qrcode image)
*/
const fileBox = FileBox.fromUrl('https://chatie.io/wechaty/images/bot-qr-code.png')
await msg.say(fileBox)
console.log('REPLY: %s', fileBox.toString())
/**
* 3. reply 'scan now!'
*/
await msg.say([
'Join Wechaty Developers Community\n\n',
'Scan now, because other Wechaty developers want to talk with you too!\n\n',
'(secret code: wechaty)',
].join(''))
}
// 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())
// }
// })
/**
*
* 3. Register all event handlers
* that we had previous defined.
*
*/
bot
.on('logout', onLogout)
.on('login', onLogin)
.on('scan', onScan)
.on('error', onError)
.on('message', onMessage)
/**
*
* 4. Start the bot!
*
*/
bot.start()
.catch(async e => {
console.error('Bot start() fail:', e)
await bot.stop()
process.exit(-1)
})
/**
*
* 5. You are all set. ;-]
*
*/
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册