forked from dempfi/ayu
-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathTypeScript.ts
60 lines (47 loc) · 1.73 KB
/
TypeScript.ts
1
2
3
4
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { Binder } from './binder'
import { Dialog } from './dialog'
import { Channel } from './channel'
import { UserMessage } from './types'
type Matcher = { match: (message: UserMessage) => boolean }
type DialogHandler<T extends Bot> = Matcher & {
handler: (dialog: Dialog<T>, bot: T) => any
}
type PerformerHandler<T> = Matcher & {
handler: (message: UserMessage, bot: T) => any
}
export abstract class Bot<BotMessage = any> extends OtherClass {
/** @internal */
_dialogHandlers: DialogHandler<this>[] = []
/** @internal */
_performerHandlers: PerformerHandler<this>[] = []
when = Binder.for(this)
_: { BotMessage: BotMessage }
private _channels = new Map<string, Channel>()
abstract listen(arg?: any): this
abstract say(channel: string, message: BotMessage): Promise<any>
/** @internal */
_channelFor(channelId: string) {
const channel = this._channels.get(channelId) || new Channel()
this._channels.set(channelId, channel)
return channel
}
dialog(channel: string, users: string[]) {
return new Dialog(this, channel, users)
}
abortDialog(channel: string, user: string) {
this._channelFor(channel).abort(user)
}
protected onMessage(message: UserMessage): any {
const performer = this._performerHandlers.find(c => c.match(message))
if (performer) return performer.handler(message, this)
const channel = this._channelFor(message.channel)
const hasActions = channel.hasFor(message.user)
if (hasActions) return channel.processMessage(`message ${message}`)
const dialog = this._dialogHandlers.find(c => c.match(message))
if (dialog) {
const obj = this.dialog(message.channel, [message.user])
obj._manager.perform(message)
dialog.handler(obj, this)
}
}
}