Skip to content

Instantly share code, notes, and snippets.

@izy521
Last active November 11, 2016 12:15
Show Gist options
  • Save izy521/1bcc08278b8e1ab5644dc29ac6406299 to your computer and use it in GitHub Desktop.
Save izy521/1bcc08278b8e1ab5644dc29ac6406299 to your computer and use it in GitHub Desktop.
For use with >= 2.0
var Discord = require('discord.io');
var fs = require('fs');
var client = new Discord.Client({
token: "",
autorun: true
});
var channelToArchive = "",
channelToPost = ""
client.on('ready', function() {
archive(client, channelToArchive, channelToPost);
});
//Would be more easier on RAM to use an IOStream, but at what cost, really?
function archive(client, cta, ctp) {
var ctaData, ctpData, offset, mData;
if (!client.channels[cta] || !client.channels[ctp]) return;
ctaData = client.channels[cta];
ctpData = client.channels[ctp];
console.log("Starting archiver for: #%s", ctaData.name);
console.log("Posting to: #%s", ctpData.name);
try {
mData = require('./' + ctaData.name + '.json');
offset = mData[0].id;
} catch(e) { mData = []; }
return getMessages(client, ctaData, ctpData, offset, mData);
}
function getMessages(client, archiveChannel, postChannel, offset, heldMessages) {
var opts = {
channelID: archiveChannel.id,
limit: 100
};
if (offset) opts.before = offset;
client.getMessages(opts, function(err, messageArray) {
if (err) return setTimeout( getMessages, 5000, client, archiveChannel, postChannel, offset, heldMessages, console.log("Receiving again in 5 seconds...") );
if (!messageArray[0]) return uploadAndExit(postChannel.id, archiveChannel.name);
console.log("Adding %d more messages", messageArray.length);
appendAndSave(heldMessages, messageArray, archiveChannel.name);
return setTimeout( getMessages, 500, client, archiveChannel, postChannel, messageArray[messageArray.length - 1].id, heldMessages);
});
}
function appendAndSave(heldMessages, newMessages, channelName) {
for (var i=0; i<newMessages.length; i++) {
heldMessages.unshift( newMessages[i] );
}
return fs.writeFileSync('./' + channelName + '.json', JSON.stringify(heldMessages, null, '\t'));
}
function uploadAndExit(channelID, channelName) {
var m = codeify(
[
["Name: " + channelName],
["Archived: " + new Date().toUTCString()]
].join("\n"),
'xl'
);
client.uploadFile({
to: channelID,
file: './' + channelName + '.json',
message: m
}, function(err) {
if (err) return setTimeout( uploadAndExit, 5000, channelID, channelName, console.log(err), console.log("Uploading again in 5 seconds...") );
process.exit(0);
});
}
function codeify(m, as) {
return "\`\`\`" + (as||"") + "\n" + m +"\n\`\`\`";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment