-
Notifications
You must be signed in to change notification settings - Fork 0
/
repeat_me.ts
61 lines (54 loc) · 1.68 KB
/
repeat_me.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
61
import { Message, Room } from "wechaty"
import { getMessageText } from "./utils"
const repeatGoBack = 10
const repeatMemory = 3
const textHistory: Map<string, Array<string | null>> = new Map()
const repeated: Map<string, Array<string | null>> = new Map()
const isRepeated = async (msg: Message) => {
const text = getMessageText(msg)
let room: Room | null = msg.room()
let id: string
if (room) {
id = room.id
} else {
id = msg.talker().id
}
return (
!msg.self() && // DRY: don't repeat yourself
textHistory.get(id)!.filter(el => el == text).length >= 3 && // exists three times
!repeated.get(id)!.includes(text) // hasn't been repeated recently
)
}
const updateHistory = (updated: Array<string | null>, text: string) => {
updated.shift()
updated.push(text)
}
const repeat = async (msg: Message) => {
const text = getMessageText(msg)
await msg.say(`${text} #复读机器人`)
}
const repeatMe = async (msg: Message) => {
const text = getMessageText(msg)
if (!text) return
let room: Room | null = msg.room()
let id: string
if (room) {
id = room.id
} else {
id = msg.talker().id
}
if (!textHistory.has(id)) {
textHistory.set(id, new Array(repeatGoBack).fill(null))
}
if (!repeated.has(id)) {
repeated.set(id, new Array(repeatMemory).fill(null))
}
const roomTextHistory: Array<string | null> = textHistory.get(id)!
const roomRepeated: Array<string | null> = repeated.get(id)!
updateHistory(roomTextHistory, text)
if (await isRepeated(msg)) {
updateHistory(roomRepeated, text)
await repeat(msg)
}
}
export { repeatMe }