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

clean(code): add await and move comments

上级 3336053a
......@@ -84,14 +84,14 @@ bot
fileHelper.say(logMsg)
console.log(logMsg)
/**
*
* 1. New Friend Request
*
* when request is set, we can get verify message from `request.hello`,
* and accept this request by `request.accept()`
*/
if (request) {
/**
*
* 1. New Friend Request
*
* when request is set, we can get verify message from `request.hello`,
* and accept this request by `request.accept()`
*/
if (request.hello === 'ding') {
logMsg = 'accepted because verify messsage is "ding"'
request.accept()
......@@ -99,12 +99,12 @@ bot
} else {
logMsg = 'not auto accepted, because verify message is: ' + request.hello
}
/**
*
* 2. Friend Ship Confirmed
*
*/
} else {
/**
*
* 2. Friend Ship Confirmed
*
*/
logMsg = 'friend ship confirmed with ' + contact.get('name')
}
} catch (e) {
......
......@@ -26,7 +26,7 @@ import {
Contact,
FriendRequest,
Room,
} from '../../'
} from '../../'
export async function onFriend(contact: Contact, request?: FriendRequest): Promise<void> {
try {
......@@ -42,8 +42,8 @@ export async function onFriend(contact: Contact, request?: FriendRequest): Promi
await request.accept()
setTimeout(
_ => {
contact.say('thank you for adding me')
async _ => {
await contact.say('thank you for adding me')
},
3000,
)
......@@ -52,9 +52,9 @@ export async function onFriend(contact: Contact, request?: FriendRequest): Promi
const myRoom = await Room.find({ topic: 'ding' })
if (!myRoom) return
setTimeout(
_ => {
myRoom.add(contact)
myRoom.say('welcome ' + contact.name())
async _ => {
await myRoom.add(contact)
await myRoom.say('welcome ' + contact.name())
},
3000,
)
......
......@@ -50,22 +50,22 @@ export async function onMessage(message: Message): Promise<void> {
*/
if (content === 'ding') {
message.say('thanks for ding me')
await message.say('thanks for ding me')
const myRoom = await Room.find({ topic: 'ding' })
if (!myRoom) return
if (myRoom.has(sender)) {
sender.say('no need to ding again, because you are already in ding room')
await sender.say('no need to ding again, because you are already in ding room')
return
}
sender.say('ok, I will put you in ding room!')
myRoom.add(sender)
await sender.say('ok, I will put you in ding room!')
await myRoom.add(sender)
return
} else if (content === 'dong') {
sender.say('ok, dong me is welcome, too.')
await sender.say('ok, dong me is welcome, too.')
return
}
......@@ -76,6 +76,6 @@ export async function onMessage(message: Message): Promise<void> {
*/
/*********************************************/
} catch (e) {
console.log(e)
console.error(e)
}
}
......@@ -26,7 +26,7 @@ import {
Contact,
Room,
Sayable,
} from '../../'
} from '../../'
export async function onRoomJoin(
this: Sayable,
......@@ -43,22 +43,22 @@ export async function onRoomJoin(
*/
if (room.topic() !== 'ding') {
this.say('Room ' + room.topic()
+ ' got new memeber ' + inviteeName
+ ' invited by ' + inviter.name(),
)
await this.say('Room ' + room.topic()
+ ' got new memeber ' + inviteeName
+ ' invited by ' + inviter.name(),
)
return
}
const inviterIsMyself = inviter.self()
if (inviterIsMyself) {
room.say('Welcome to my room: ' + inviteeName)
await room.say('Welcome to my room: ' + inviteeName)
return
}
room.say('请勿私自拉人。需要拉人请加我', inviter)
room.say('请先加我好友,然后我来拉你入群。先把你移出啦。', inviteeList)
await room.say('请勿私自拉人。需要拉人请加我', inviter)
await room.say('请先加我好友,然后我来拉你入群。先把你移出啦。', inviteeList)
inviteeList.forEach(c => {
room.del(c)
......
......@@ -17,11 +17,14 @@
*
*/
/* tslint:disable:variable-name */
const QrcodeTerminal = require('qrcode-terminal')
// import { inspect } from 'util'
import { createWriteStream, writeFileSync } from 'fs'
import {
createWriteStream,
// writeFileSync,
} from 'fs'
/* tslint:disable:variable-name */
import * as qrcodeTerminal from 'qrcode-terminal'
/**
* Change `import { ... } from '../'`
......@@ -40,7 +43,7 @@ bot
.on('scan', (url, code) => {
if (!/201|200/.test(String(code))) {
const loginUrl = url.replace(/\/qrcode\//, '/l/')
QrcodeTerminal.generate(loginUrl)
qrcodeTerminal.generate(loginUrl)
}
console.log(`${url}\n[${code}] Scan QR Code in above url to login: `)
})
......@@ -49,7 +52,7 @@ bot
console.log(`RECV: ${m}`)
// console.log(inspect(m))
saveRawObj(m.rawObj)
// saveRawObj(m.rawObj)
if ( m.type() === MsgType.IMAGE
|| m.type() === MsgType.EMOTICON
......@@ -65,23 +68,23 @@ bot
.init()
.catch(e => console.error('bot.init() error: ' + e))
function saveMediaFile(message: Message) {
async function saveMediaFile(message: Message) {
const filename = message.filename()
console.log('IMAGE local filename: ' + filename)
const fileStream = createWriteStream(filename)
console.log('start to readyStream()')
message.readyStream()
.then(stream => {
stream.pipe(fileStream)
.on('close', () => {
console.log('finish readyStream()')
})
})
.catch(e => console.log('stream error:' + e))
try {
const netStream = await message.readyStream()
netStream
.pipe(fileStream)
.on('close', _ => console.log('finish readyStream()'))
} catch (e) {
console.error('stream error:', e)
}
}
function saveRawObj(o) {
writeFileSync('rawObj.log', JSON.stringify(o, null, ' ') + '\n\n\n', { flag: 'a' })
}
// function saveRawObj(o) {
// writeFileSync('rawObj.log', JSON.stringify(o, null, ' ') + '\n\n\n', { flag: 'a' })
// }
......@@ -18,7 +18,7 @@
*/
/* tslint:disable:variable-name */
const QrcodeTerminal = require('qrcode-terminal')
const qrcodeTerminal = require('qrcode-terminal')
/**
* Change `import { ... } from '../'`
......@@ -33,13 +33,15 @@ bot
.on('scan', (url, code) => {
if (!/201|200/.test(String(code))) {
const loginUrl = url.replace(/\/qrcode\//, '/l/')
QrcodeTerminal.generate(loginUrl)
qrcodeTerminal.generate(loginUrl)
}
console.log(`${url}\n[${code}] Scan QR Code in above url to login: `)
})
.on('message', m => {
if (m.self()) { return }
m.say('roger') // 1. reply others' msg
.on('message', async m => {
if (m.self()) {
return // skip self
}
await m.say('roger') // 1. reply others' msg
console.log(`RECV: ${m}, REPLY: "roger"`) // 2. log message
})
.init()
......
......@@ -45,7 +45,7 @@ const HELPER_CONTACT_NAME = 'Bruce LEE'
*/
/* tslint:disable:variable-name */
const QrcodeTerminal = require('qrcode-terminal')
const qrcodeTerminal = require('qrcode-terminal')
/**
* Change `import { ... } from '../'`
......@@ -92,7 +92,7 @@ bot
.on('scan', (url, code) => {
if (!/201|200/.test(String(code))) {
const loginUrl = url.replace(/\/qrcode\//, '/l/')
QrcodeTerminal.generate(loginUrl)
qrcodeTerminal.generate(loginUrl)
}
console.log(`${url}\n[${code}] Scan QR Code in above url to login: `)
})
......@@ -105,15 +105,15 @@ bot
* do initialization inside this event.
* (better to set a timeout, for browser need time to download other data)
*/
.on('login', function(this, user) {
.on('login', async function(this, user) {
let msg = `${user.name()} logined`
log.info('Bot', msg)
this.say(msg)
await this.say(msg)
msg = `setting to manageDingRoom() after 3 seconds ... `
log.info('Bot', msg)
this.say(msg)
await this.say(msg)
setTimeout(manageDingRoom.bind(this), 3000)
})
......@@ -157,7 +157,7 @@ bot
/**
* Global Event: message
*/
.on('message', function (this, message) {
.on('message', async function(this, message) {
const room = message.room()
const sender = message.from()
const content = message.content()
......@@ -168,7 +168,7 @@ bot
)
if (message.self()) {
return
return // skip self
}
/**
* `ding` will be the magic(toggle) word:
......@@ -196,69 +196,65 @@ bot
/**
* find room name start with "ding"
*/
Room.find({ topic: /^ding/i })
.then(dingRoom => {
try {
const dingRoom = await Room.find({ topic: /^ding/i })
if (dingRoom) {
/**
* room found
*/
log.info('Bot', 'onMessage: got dingRoom: %s', dingRoom.topic())
if (dingRoom.has(sender)) {
/**
* room found
* speaker is already in room
*/
if (dingRoom) {
log.info('Bot', 'onMessage: got dingRoom: %s', dingRoom.topic())
/**
* speaker is already in room
*/
if (dingRoom.has(sender)) {
log.info('Bot', 'onMessage: sender has already in dingRoom')
sender.say('no need to ding again, because you are already in ding room')
// sendMessage({
// content: 'no need to ding again, because you are already in ding room'
// , to: sender
// })
/**
* put speaker into room
*/
} else {
log.info('Bot', 'onMessage: add sender(%s) to dingRoom(%s)', sender.name(), dingRoom.topic())
sender.say('ok, I will put you in ding room!')
putInRoom(sender, dingRoom)
}
log.info('Bot', 'onMessage: sender has already in dingRoom')
sender.say('no need to ding again, because you are already in ding room')
// sendMessage({
// content: 'no need to ding again, because you are already in ding room'
// , to: sender
// })
} else {
/**
* room not found
* put speaker into room
*/
} else {
log.info('Bot', 'onMessage: dingRoom not found, try to create one')
/**
* create the ding room
*/
createDingRoom(sender)
.then(_ => {
/**
* listen events from ding room
*/
manageDingRoom()
})
}
})
.catch(e => {
log.error(e)
})
log.info('Bot', 'onMessage: add sender(%s) to dingRoom(%s)', sender.name(), dingRoom.topic())
sender.say('ok, I will put you in ding room!')
putInRoom(sender, dingRoom)
}
} else {
/**
* room not found
*/
log.info('Bot', 'onMessage: dingRoom not found, try to create one')
/**
* create the ding room
*/
await createDingRoom(sender)
/**
* listen events from ding room
*/
manageDingRoom()
}
} catch (e) {
log.error(e)
}
}
}
})
.init()
.catch(e => console.error(e))
function manageDingRoom() {
async function manageDingRoom() {
log.info('Bot', 'manageDingRoom()')
/**
* Find Room
*/
Room.find({ topic: /^ding/i })
.then(room => {
try {
const room = await Room.find({ topic: /^ding/i })
if (!room) {
log.warn('Bot', 'there is no room topic ding(yet)')
return
......@@ -293,13 +289,12 @@ function manageDingRoom() {
changer.name(),
)
})
})
.catch(e => {
} catch (e) {
log.warn('Bot', 'Room.find rejected: %s', e.stack)
})
}
}
function checkRoomJoin(room: Room, inviteeList: Contact[], inviter: Contact) {
async function checkRoomJoin(room: Room, inviteeList: Contact[], inviter: Contact) {
log.info('Bot', 'checkRoomJoin(%s, %s, %s)',
room.topic(),
inviteeList.map(c => c.name()).join(','),
......@@ -314,28 +309,26 @@ function checkRoomJoin(room: Room, inviteeList: Contact[], inviter: Contact) {
}
if (inviter.id !== user.id) {
room.say('RULE1: Invitation is limited to me, the owner only. Please do not invit people without notify me.',
inviter,
)
room.say('Please contact me: by send "ding" to me, I will re-send you a invitation. Now I will remove you out, sorry.',
inviteeList,
)
await room.say('RULE1: Invitation is limited to me, the owner only. Please do not invit people without notify me.',
inviter,
)
await room.say('Please contact me: by send "ding" to me, I will re-send you a invitation. Now I will remove you out, sorry.',
inviteeList,
)
room.topic('ding - warn ' + inviter.name())
setTimeout(
_ => {
inviteeList.forEach(c => room.del(c))
},
10000,
_ => inviteeList.forEach(c => room.del(c)),
10 * 1000,
)
} else {
room.say('Welcome to my room! :)')
await room.say('Welcome to my room! :)')
let welcomeTopic
welcomeTopic = inviteeList.map(c => c.name()).join(', ')
room.topic('ding - welcome ' + welcomeTopic)
await room.topic('ding - welcome ' + welcomeTopic)
}
} catch (e) {
......@@ -344,26 +337,26 @@ function checkRoomJoin(room: Room, inviteeList: Contact[], inviter: Contact) {
}
function putInRoom(contact, room) {
async function putInRoom(contact, room) {
log.info('Bot', 'putInRoom(%s, %s)', contact.name(), room.topic())
try {
room.add(contact)
.catch(e => {
log.error('Bot', 'room.add() exception: %s', e.stack)
})
setTimeout(_ => room.say('Welcome ', contact), 1000)
await room.add(contact)
setTimeout(
_ => room.say('Welcome ', contact),
10 * 1000,
)
} catch (e) {
log.error('Bot', 'putInRoom() exception: ' + e.stack)
}
}
function getOutRoom(contact: Contact, room: Room) {
async function getOutRoom(contact: Contact, room: Room) {
log.info('Bot', 'getOutRoom(%s, %s)', contact, room)
try {
room.say('You said "ding" in my room, I will remove you out.')
room.del(contact)
await room.say('You said "ding" in my room, I will remove you out.')
await room.del(contact)
} catch (e) {
log.error('Bot', 'getOutRoom() exception: ' + e.stack)
}
......@@ -395,9 +388,8 @@ async function createDingRoom(contact): Promise<any> {
const room = await Room.create(contactList, 'ding')
log.info('Bot', 'createDingRoom() new ding room created: %s', room)
room.topic('ding - created')
room.say('ding - created')
await room.topic('ding - created')
await room.say('ding - created')
return room
......
......@@ -25,7 +25,7 @@ import Ffmpeg = require('fluent-ffmpeg')
import querystring = require('querystring')
/* tslint:disable:variable-name */
const QrcodeTerminal = require('qrcode-terminal')
const qrcodeTerminal = require('qrcode-terminal')
/**
* Change `import { ... } from '../'`
......@@ -45,7 +45,7 @@ bot
.on('scan', (url, code) => {
if (!/201|200/.test(String(code))) {
const loginUrl = url.replace(/\/qrcode\//, '/l/')
QrcodeTerminal.generate(loginUrl)
qrcodeTerminal.generate(loginUrl)
}
console.log(`${url}\n[${code}] Scan QR Code in above url to login: `)
})
......@@ -142,7 +142,7 @@ function mp3ToWav(mp3Stream: NodeJS.ReadableStream): NodeJS.ReadableStream {
* http://blog.csdn.net/dlangu0393/article/details/7214728
* http://elric2011.github.io/a/using_speech_recognize_service.html
*/
async function wavToText(readableStream: NodeJS.ReadableStream): Promise<string> {
async function wavToText(wavStream: NodeJS.ReadableStream): Promise<string> {
const params = {
'cuid': 'wechaty',
'lan': 'zh',
......@@ -159,7 +159,7 @@ async function wavToText(readableStream: NodeJS.ReadableStream): Promise<string>
}
return new Promise<string>((resolve, reject) => {
readableStream.pipe(request.post(apiUrl, options, (err, httpResponse, body) => {
wavStream.pipe(request.post(apiUrl, options, (err, httpResponse, body) => {
// "err_msg":"success.","err_no":0,"result":["这是一个测试测试语音转文字,"]
if (err) {
return reject(err)
......
......@@ -27,7 +27,7 @@
*/
/* tslint:disable:no-var-requires */
/* tslint:disable:variable-name */
const QrcodeTerminal = require('qrcode-terminal')
const qrcodeTerminal = require('qrcode-terminal')
const Tuling123 = require('tuling123-client')
/**
......@@ -71,7 +71,7 @@ bot
.on('scan', (url, code) => {
if (!/201|200/.test(String(code))) {
const loginUrl = url.replace(/\/qrcode\//, '/l/')
QrcodeTerminal.generate(loginUrl)
qrcodeTerminal.generate(loginUrl)
}
console.log(`${url}\n[${code}] Scan QR Code in above url to login: `)
})
......@@ -81,14 +81,16 @@ bot
log.info('Bot', 'talk: %s' , msg)
tuling.ask(msg.content(), {userid: msg.from()})
.then(({text}) => {
log.info('Tuling123', 'Talker reply:"%s" for "%s" ', text, msg.content())
msg.say(text)
})
.catch(err => {
log.error('Bot', 'on message rejected: %s' , err)
})
try {
const reply = tuling.ask(msg.content(), {userid: msg.from()})
log.info('Tuling123', 'Talker reply:"%s" for "%s" ',
reply,
msg.content(),
)
msg.say(reply)
} catch (e) {
log.error('Bot', 'on message tuling.ask() exception: %s' , e && e.message || e)
}
})
bot.init()
......
......@@ -352,12 +352,13 @@ export class Room extends EventEmitter implements Sayable {
if (newTopic) {
log.verbose('Room', 'topic(%s)', newTopic)
Config.puppetInstance().roomTopic(this, newTopic)
.catch(e => {
log.warn('Room', 'topic(newTopic=%s) exception: %s',
newTopic, e && e.message || e,
)
})
Config.puppetInstance()
.roomTopic(this, newTopic)
.catch(e => {
log.warn('Room', 'topic(newTopic=%s) exception: %s',
newTopic, e && e.message || e,
)
})
if (!this.obj) {
this.obj = <RoomObj>{}
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册