-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtribesBot.V2-old
More file actions
301 lines (286 loc) · 9.81 KB
/
tribesBot.V2-old
File metadata and controls
301 lines (286 loc) · 9.81 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits, MessageFlags} = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers] });
// Not sure what this is; it probably came with my example?
var logger = require('winston');
const { ExceptionHandler, child } = require('winston');
// Not sure what this is; it probably came with my example?
const { ConsoleTransportOptions } = require('winston/lib/winston/transports');
// Not sure what this is; it probably came with my example?
const { spawn } = require('child_process');
const savelib = require("./libs/save.js");
const pop = require("./libs/population.js")
client.commands = new Collection();
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);
var allGames = {}
var alertChannel = {};
for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
console.log("setting command "+filePath)
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
client.once(Events.ClientReady, () => {
console.log('Tribes Ready!');
var d = new Date();
var n = d.toISOString();
alertChannel = client.channels.cache.find(channel => channel.name === 'server-restarted')
alertChannel.send('TribesBot is alive again. '+n)
});
client.once('reconnecting', () => {
console.log('Reconnecting Tribes!');
});
client.once('disconnect', () => {
console.log('Disconnect Tribes!');
});
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
let channel = await client.channels.fetch(interaction.channelId);
console.log("command "+interaction.commandName+ " by "+interaction.member.displayName+" of "+channel.name);
if (channel.name.endsWith('tribe')){
gameState = allGames[channel.name];
if (!gameState ){
gameState = savelib.loadTribe(channel.name);
}
if (!gameState){
gameState = savelib.initGame(channel.name);
}
if ( gameState.ended && interaction.commandName == "join"){
console.log("Join on an ended game; starting fresh game");
gameState = savelib.initGame(channel.name);
}
allGames[channel.name] = gameState;
} else {
const response = "Tribes commands need to be in a tribe channel";
try {
if (interaction && ! interaction.replied ){
interaction.reply({ content: response, flags: MessageFlags.Ephemeral });
return
}
} catch (error){
console.log("Error handling non-tribe-channel command: "+error);
}
channel.send("Tribes commands need to be in a tribe channel");
return;
}
nickName = interaction.member.displayName;
// if no errors, and we are sure we have a gameState
try {
interaction.nickName = nickName?nickName:interaction.user.displayName;
command.execute(interaction, gameState, client);
// send responses to the messages
sendMessages(client, gameState, interaction);
var d = new Date();
var saveTime = d.toISOString();
saveTime = saveTime.replace(/\//g, "-");
console.log("Command completed: "+saveTime);
if (gameState.saveRequired){
savelib.saveTribe(gameState);
gameState.saveRequired = false;
}
if (gameState.archiveRequired){
savelib.archiveTribe(gameState);
gameState.archiveRequired = false;
}
} catch (error) {
console.log("there was an error in that command:");
console.error(error);
channel.send("TribesBot had a problem with the last command.")
}
});
async function sendMessages(bot, gameState, interaction){
const messagesDict = gameState['messages'];
const channel = bot.channels.cache.find(channel => channel.name === gameState.name);
if (! messagesDict){
console.log("sendMessages on empty");
return;
}
var actorName = "Unknown"
var needsReply = false;
if (interaction){
actorName = interaction.nickName;
needsReply = interaction.isRepliable();
console.log("Had an interaction needs reply = "+needsReply )
}
var chunks = []
MAX_LENGTH = 1900; //docs say 2000 is max; better safe than sorry
// regext [\S\s] is any chacter that is either a space or not a space; eg, any character
if ("tribe" in messagesDict ){
//console.log("in send messages tribe >>"+messagesDict["tribe"]+"<<");
var message = messagesDict["tribe"];
chunksSent = 0;
var chunks = []
if (message){
chunks = message.match(/[\S\s]{1,1900}/g);
if (needsReply ){
interaction.reply({ content: chunks[0] });
chunksSent = 1;
} else {
channel.send({content: chunks[chunksSent++] });
}
needsReply = false;
}
while (chunks && chunksSent < chunks.length){
//console.log("sending bonus chunks to tribe");
channel.send({content: chunks[chunksSent++] });
}
delete messagesDict["tribe"];
}
if (actorName in messagesDict && needsReply){
//console.log("Actor "+actorName+" in the dictionary and needsReply");
// only reply here if reply is still needed; otherwise handle with other messages below
const message = messagesDict[actorName];
if (!message){
console.log('skipping empty message for '+actorName);
} else {
var chunks = []
if (message.length < 1){
console.log("Weird empty message (length zero) for "+actorName);
} else {
chunks = message.match(/[\S\s]{1,1900}/g);
}
if (!chunks || chunks.length == 0){
console.log("Weird empty message (no chunks) for "+actorName);
} else {
chunks = message.match(/[\S\s]{1,1900}/g);
//console.log("message needs reply, with this many chunks:"+chunks.length);
if (message && interaction.isRepliable() ){
needsReply = false;
user = interaction.user;
response = chunks[0];
chunksSent = 0;
if (chunks.length > 1){
response += " \n(message truncated. Check DMs for more info)"
}
//console.log("reply to "+actorName+" : "+response);
interaction.reply({ content: response, flags: MessageFlags.Ephemeral })
// double tap user so they have a DM of content as well. TODO: confirm this is correct?
if (chunks[0]){
user.send(chunks[0]);
}
chunksSent++;
if (chunksSent < chunks.length){
sendRemainingMessageChunksToUser(user, chunks, chunksSent);
}
delete messagesDict[actorName];
} else {
console.log("null message for "+actorName+ " seasonCounter:"+gameState.seasonCounter)
}
}
}
} else {
console.log(actorName+" was not in the messagesDictionary");
}
for (const [address, message] of Object.entries(messagesDict)){
member = pop.memberByName(address, gameState);
if (!message){
console.log('empty message for '+address);
continue;
}
const chunks = message.match(/[\S\s]{1,1900}/g);
if (!chunks || chunks.length == 0){
console.log("Weird empty message (no chunks) for "+address);
continue;
}
console.log(chunks.length+" chunks addressed to "+address);
if (!member){
console.log("No member for name "+address);
continue;
}
if (!message){
console.log("Not sending empty message to "+address);
continue;
}
userHandle = member["handle"]
if (userHandle){
var userId = "";
// different clients call it different things
if ("id" in userHandle){
userId = userHandle["id"];
} else if ( "userId" in userHandle){
userId = userHandle["userId"];
} else {
console.log("Could not get an ID for "+address);
continue;
}
var user = await bot.users.cache.get(userId);
if (!user){
try {
user = await getUser(userId);
//console.log("Got user "+user+" "+user.displayName);
} catch( error){
console.log("error with emergency get user:"+error);
}
}
if (! user){
console.log("not finding user for "+address+" userId="+userId)
console.log("Dropping "+chunks.length+" message chunks, including:"+chunks[0])
} else {
chunksSent = 0;
sendRemainingMessageChunksToUser(user, chunks, chunksSent);
}
//console.log("messages complete for "+address);
} else {
console.log("no handle for "+address);
}
delete messagesDict[address]
}
if (needsReply){
console.log(" no reply made that command");
}
return 0;
}
async function getUser(userId) {
console.log("In emergency get user for "+userId);
try {
console.log("UserId:"+userId);
const user = await client.users.fetch(userId);
console.log(`Found user: ${user.tag}`);
return user;
} catch (error) {
console.error(`Failed to fetch user with ID ${userId}:`, error);
return null;
}
}
function sendRemainingMessageChunksToUser(user, messageArray, chunksSent){
if (! user || !messageArray || (chunksSent > messageArray.length)){
console.error("bad call to send remaining messages ");
return;
}
while (chunksSent < messageArray.length){
//console.log(messageArray.length+ " chunks bound for "+user.displayName);
if (messageArray[chunksSent]){
try {
user.send({content: messageArray[chunksSent++] });
} catch ( error){
console.log("Error sending message: "+messageArray[chunksSent]);
console.log("To user:"+user);
console.log(error);
}
} else {
console.log("empty chunk? chunkSent:"+chunksSent);
chunksSent++; //increment to avoid infinite loops
}
if (chunksSent > 10){
console.log("Spamming user with too many chunks. Aborting messages");
break;
}
}
//console.log(chunksSent+ " chunks sent to "+user.displayName);
return;
}
////////////////////////////////////////////////
client.login(token);