-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
291 lines (254 loc) · 8.2 KB
/
index.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
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
require('dotenv').config();
import {
Client,
Collection,
Guild,
GuildChannel,
Message,
MessageEmbed,
TextChannel,
} from 'discord.js';
import * as fs from 'fs';
const client = new Client();
const port = process.env.PORT || 3000; // Fallback for local development
// Heroku requires a web server respond to GET requests to keep the app running
import express, { Request, Response, raw } from 'express';
const app = express();
app.get('/', (req: Request, res: Response) => {
res.send('Discord Bot is running!');
});
app.listen(port, () => {
console.log(`Web server is listening on port ${port}`);
});
client.on('ready', () => {
console.log('Ready for action!');
//very important
});
// Create an event listener for messages
client.on('message', (message: Message) => {
// Filter messages to get an entry point
if (message.author.bot) {
return;
}
if (!message.guild) {
return;
}
if (
message.content.includes('!random_message') ||
message.content.includes('!rm')
) {
let command = message.content.includes('!random_message')
? '!random_message'
: '!rm';
// Get args
let commandArray = message.content
.substring(message.content.indexOf(command))
.split(' ');
// Break for help
if (commandArray.some((command) => command.includes('help'))) {
sendHelp(message.channel as TextChannel);
return;
}
// Break for indexing
if (commandArray.some((command) => command.includes('index'))) {
downloadHistory(message.guild);
return;
}
// Parse args
let channelName;
commandArray.forEach((command) => {
if (command.indexOf('c:') !== -1) {
channelName = command.split('c:')[1];
}
});
let channels: TextChannel[] = getChannels(
message.guild,
channelName
).array();
if (!channels || !channels.length) {
message.channel.send('`Invalid channel filter` try `!rm help`');
return;
}
let randomChannel: TextChannel =
channels[Math.floor(Math.random() * channels.length)];
console.log(`fetching rand msg from ${randomChannel.name}`);
getRandomMessage(randomChannel, message.channel as TextChannel);
}
});
const downloadChannelHistory = async (channel: GuildChannel) => {
console.log('Indexing channel: ' + channel.name);
let messageArray = await fetchAll(channel);
// Write to file
let file = fs.createWriteStream('./message_index/' + channel.name + '.txt');
file.on('error', function (err) {
console.log(err);
});
messageArray.forEach(function (message) {
// Discord.js has some really weird overwrites for toString functionality,
// that loses deep properties on the object, so we have to set them
// explicitly
let messageObj = JSON.parse(JSON.stringify(message));
messageObj.author = message.author;
messageObj.embeds = JSON.stringify(message.embeds);
messageObj.attachments = JSON.stringify(message.attachments);
messageObj.createdAt = message.createdAt;
messageObj.url = message.url;
file.write(JSON.stringify(messageObj) + '\n');
});
file.end();
console.log('done indexing: ' + channel.name);
return messageArray;
};
const downloadHistory = async (guild: Guild) => {
console.log('Start indexing');
let channels = guild.channels.cache.filter(
(channel) => channel.type === 'text'
);
channels.forEach(async (channel) => {
downloadChannelHistory(channel);
});
};
const getChannels = (
guild: Guild,
channelName: string = ''
): Collection<string, TextChannel> => {
const channels = guild.channels.cache.filter(
(channel) => channel.type === 'text' && channel.name.includes(channelName)
);
// filter out any non TextChannels
return channels as Collection<string, TextChannel>;
};
const getRandomMessage = async (
sourceChannel: TextChannel,
channelToPost: TextChannel
) => {
(channelToPost as TextChannel).startTyping();
let fileName = `./message_index/${sourceChannel.name}.txt`;
let messages: Message[];
let randomMessage;
// First choice: fetch from file
if (fs.existsSync(fileName)) {
console.log(`We have a file for ${sourceChannel.name}`);
let rawLines = fs
.readFileSync(fileName, 'utf-8')
.split('\n')
.filter((line) => line.length > 0);
let rawMessages = rawLines.map((line) => {
return JSON.parse(line);
});
// convert messages in to Message objects
messages = rawMessages.map((rawMessage) => {
rawMessage.embeds = JSON.parse(rawMessage.embeds);
let message = new Message(
sourceChannel.client,
rawMessage,
sourceChannel
);
return message;
});
} else {
// Fallback, fetch and index now
console.log('No index file found for ${sourceChannel.name}');
messages = await downloadChannelHistory(sourceChannel);
}
console.log(`Picking message at random...`);
let randomMessageIndex = Math.floor(Math.random() * messages.length);
randomMessage = messages[randomMessageIndex];
if (!randomMessage) {
console.log('No random message found');
return;
}
console.log(`sending: ${randomMessage.content} to ${channelToPost.name}`);
//Not required, but helps if there are multiple requests/message failure
channelToPost.stopTyping(true);
channelToPost.send(generateEmbed(randomMessage, sourceChannel));
};
const fetchAll = async (channel: GuildChannel) => {
let size = 100;
let messageArray: Message[] = [];
let lastID;
console.log(`starting ${channel.name} fetch, this could take a while!`);
while (size === 100) {
await (channel as TextChannel).messages
.fetch({ limit: size, before: lastID })
.then((messages) => {
console.log(`Fetching ${messages.size} messages from ${channel.name}`);
messages.each((message) => {
messageArray.push(message);
});
size = messages.size;
})
.catch(console.error);
lastID = messageArray[messageArray.length - 1].id;
}
console.log(
`Fetch complete! ${messageArray.length} messages found in ${channel.name}`
);
return messageArray;
};
const sendHelp = (channel: TextChannel) => {
const exampleEmbed = new MessageEmbed()
.setColor('#0099ff')
.setTitle('HistoryBot')
.setAuthor(
'History Bot',
'https://media.discordapp.net/attachments/358274019482664961/607715919090810987/obamer_sphere.gif',
'https://github.com/mgoudy91/discord_random_msg'
)
.setDescription("Send a random message from your server's history")
.addFields(
{ name: 'Basic Usage', value: '`!rm` or `!random_message`' },
{ name: 'Specify channel', value: '`!rm c:channel_name`', inline: true },
{ name: 'Get help', value: '`!rm help`', inline: true }
)
.setTimestamp()
.setFooter('Created with extreme malice');
channel.send(exampleEmbed);
};
function generateEmbed(message: Message, channel: TextChannel) {
let author = message.author;
console.log(author);
const embed = new MessageEmbed()
.setColor('RANDOM')
.setTitle(`#${channel.name}`)
.setURL(message.url)
.setAuthor(
author.username,
author.displayAvatarURL({ format: 'png', dynamic: true })
)
.setDescription(message.cleanContent)
.setTimestamp(message.createdAt)
.setFooter(
'Sent on',
'https://media.tenor.com/YNwyN6nZ1jcAAAAi/barack-obama-sphere.gif'
);
//Assume attachments have a higher priority
// let img;
console.log('message.embeds and message.attachments');
console.log(message.embeds);
console.log(message.attachments);
if (message.embeds && message.embeds.length > 0) {
console.log('trying to generate embed from embeds');
try {
let img = message.embeds.find(
(embed: MessageEmbed) => embed.type === 'image'
);
if (img && img.url) {
embed.setImage(img.url);
return embed;
}
} catch (e) {
console.log(e);
}
} else if (message.attachments && message.attachments.size > 0) {
console.log('trying to generate embed from attachments');
// Get first item in message.attachments that has a url field
let img = message.attachments.find((attachment) => !!attachment.url.length);
if (img && img.url) {
embed.setImage(img.url);
}
return embed;
}
return embed;
}
client.login(process.env.TOKEN);