cubbot/src/modules/Chat.ts

59 lines
1.6 KiB
TypeScript

import { vsprintf } from 'sprintf-js'
import Module from '../utils/Module'
import { IDict } from '../utils/types'
import Connection from './Connection'
/** Message packet payload */
export interface IMessage { text?: string, extra?: Array<{text: string}>, translate?: string, with?: IMessage[] }
/** Handle chat display and replies */
export default class Chat extends Module<{ reply?: string, bye?: string }> {
/** Convert payload to string */
public static parse(msg: IMessage, language: IDict) {
let text = ''
if (msg.text) {
text += msg.text
}
if (msg.translate && msg.translate in language) {
text += vsprintf(language[msg.translate], (msg.with || [])
.map(w => typeof w === 'string' ? w : Chat.parse(w, language)))
}
if (msg.extra) {
text += msg.extra.map(({text: t}) => t).join()
}
return text
}
private connection!: Connection
public parse(msg: IMessage) {
return Chat.parse(msg, this.connection.oldData.language)
}
public write(message: string) {
this.client.write('chat', { message })
}
public umount() {
if (this.connection.connected && this.conf.bye) {
this.write(this.conf.bye)
}
}
protected mount() {
this.connection = this.load<Connection>(Connection)
this.client.on('chat', packet => {
const message = JSON.parse(packet.message)
this.logger.info(this.parse(message))
})
}
//TODO: reply
protected getConf() {
return { }
}
}