-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbotlog.ts
95 lines (82 loc) · 2.95 KB
/
botlog.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { Message, MessageEmbed, TextChannel } from "discord.js";
import { client } from "./client";
import * as util from 'util';
const TARGET_CHANNEL_NAME = 'bot-log';
export async function botlog(message:string):Promise<void> {
message = '```\n'+message+'\n```';
const list = await client.guilds.fetch();
const promises = list.map(guildAuth=>(async()=>{
const guild = await guildAuth.fetch();
const channels = await guild.channels.fetch();
const botChannel = channels.find(channel=>channel.name === TARGET_CHANNEL_NAME);
if (botChannel instanceof TextChannel) {
await botChannel.send(message);
}
})());
await Promise.all(promises);
}
export class BotConsole {
private message = '```\n';
private msgs:Message[]|null = null;
private updated = false;
private updating:Promise<void>|null = null;
private skipTimeout:(()=>void)|null = null;
private async _update():Promise<void> {
if (this.updating !== null) {
this.updated = true;
return;
}
let updatingResolver:(()=>void)|null = null;
this.updating = new Promise(resolve=>{
updatingResolver = resolve;
});
for (;;) {
const out = this.message+'```';
if (this.msgs === null) {
const list = await client.guilds.fetch();
const proms = list.map(guildAuth=>(async()=>{
const guild = await guildAuth.fetch();
const channels = await guild.channels.fetch();
const botChannel = channels.find(channel=>channel.name === TARGET_CHANNEL_NAME);
if (botChannel instanceof TextChannel) {
return await botChannel.send(out);
}
return null;
})());
this.msgs = (await Promise.all(proms)).filter(msg=>msg !== null) as Message[];
} else {
this.msgs = await Promise.all(this.msgs.map(item=>item.edit(out)));
}
await new Promise<void>(resolve=>{
setTimeout(resolve, 1000);
this.skipTimeout = resolve;
});
this.skipTimeout = null;
if (!this.updated) break;
else this.updated = false;
}
this.updating = null;
updatingResolver!();
}
write(message:string):void {
this.message += message;
this._update();
}
log(...message:unknown[]):void {
for (const msg of message) {
if (typeof msg === 'string') {
this.message += msg;
} else {
this.message += util.inspect(msg);
}
this.message += '\n';
this._update();
}
}
flush():Promise<void> {
if (this.skipTimeout !== null) {
this.skipTimeout();
}
return this.updating ?? Promise.resolve();
}
}