Skip to content

Commit

Permalink
script output translations added
Browse files Browse the repository at this point in the history
v1.1.0
* You can now add translations for the script output.
* Possibility to change the ouput type (all/error/none)
  • Loading branch information
Jisagi committed Sep 1, 2018
1 parent 591c9b8 commit 78f07bd
Show file tree
Hide file tree
Showing 14 changed files with 323 additions and 102 deletions.
4 changes: 2 additions & 2 deletions README.fr.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ Jisagi de vérifier les nouveaux commits pour les changements qui pourraient cas
## Problèmes
La plupart des problèmes courants sont affichés dans la console lors de l'exécution du script. Si vous rencontrez des pannes ou tout autre comportement étrange non répertorié [ici](https://github.com/Jisagi/Discord-guild-copy#common-behaviour), n'hésitez pas à créer un [problème] (https: // github. com / Jisagi / Discord-guild-copy / issues / new). Le script crée des journaux dans le dossier 'logs'. N'hésitez pas à les télécharger sur quelque chose comme [pastebin](https://pastebin.com/) et ajoutez-les au problème créé pour m'aider à trouver le problème.

### Puis-je suggérer de nouvelles fonctionnalités (ou me plaindre du code laide)
Bien sûr, il suffit de créer un [numéro](https://github.com/Jisagi/Discord-guild-copy/issues/new) ou une [demande de traction](https://github.com/Jisagi/Discord-guild -copy / compare).
## Puis-je suggérer de nouvelles fonctionnalités (ou me plaindre du code laide)
Bien sûr, il suffit de créer un [numéro](https://github.com/Jisagi/Discord-guild-copy/issues/new) ou une [demande de traction](https://github.com/Jisagi/Discord-guild-copy/compare).

## Licence
Ce logiciel est sous licence GPLv3. Pour plus de détails, voir [LICENCE](https://github.com/Jisagi/Discord-guild-copy/blob/master/LICENSE).
Expand Down
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ To get the id of a guild open your client settings -> Appearance and then enable
| newGuildAdminRoleId | The id of a role with administrator permissions. The bot needs to have this role on the new guild! You can manually create a new role called 'guildcopy' and the script will automatically use it. If you do so, just leave this field empty. |
| copyEmojis | default: false - set to true to copy emojis (see also [Common Behaviour](https://github.com/Jisagi/Discord-guild-copy#common-behaviour)) |
| copyBans | default: false - set to true to copy banned users The bot needs to have the BAN_MEMBERS permission on the original guild if you enable this! |
| language | default: en - set this to any supported language from the `translations` folder |
| output | default: all - Possible values: `all` for everything, `error` for errors only, `none` for no output at all |
| debug | default: false - set to true for a more detailed general and error output e.g. when creating an issue |
| token | Your account token. The bot does not need any permissions on the original guild (only exception: copyBans=true). |

Expand All @@ -71,9 +73,12 @@ I try to check new commits for changes which might break something but if I miss
## Issues
Most of the common issues are displayed in the console while running the script. If you encounter crashes or any other weird behaviour not listed [here](https://github.com/Jisagi/Discord-guild-copy#common-behaviour) feel free to create an [issue](https://github.com/Jisagi/Discord-guild-copy/issues/new). The script creates logs in the 'logs' folder. Feel free to upload those to something like [pastebin](https://pastebin.com/) and add them to the created issue to help me find the problem.

### Can I suggest new features (or complain about ugly code)
## Can I suggest new features (or complain about ugly code)
Of course, just create an [issue](https://github.com/Jisagi/Discord-guild-copy/issues/new) or a [pull request](https://github.com/Jisagi/Discord-guild-copy/compare).

## Translation Guide
If you want to help translate the script, feel free do so so. Just create a copy of the `en.json` in the `translation` folder and create a pull request with the new transation. All `[@@X@@]` statements are dynamic parts of a sentence and need to be in the correct spot for each language numbered with 1,2,3,... Please test your translation at least once before submitting it and don't forget to change the langcode/language/author at the top of the file.

## License
This software is licensed under the terms of the GPLv3. For more details see [LICENSE](https://github.com/Jisagi/Discord-guild-copy/blob/master/LICENSE).

Expand Down
58 changes: 34 additions & 24 deletions copy.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,33 @@ const Serializer = require('./objects/serializer');
const Cleaner = require('./objects/cleaner');
const Creator = require('./objects/creator');
const Logger = require('./objects/logger');
const Translator = require('./objects/translator');
const settings = require('./settings.json');
const client = new Discord.Client();

let isBackup = false;
let isRestore = false;
let isClone = false;
let backupFile = 'guildData.json';

client.on('ready', async () => {
await Translator.loadTranslations().catch(langError => {
console.error(langError);
return process.exit(1);
});

if (!['all', 'error', 'none'].includes(settings.output)) {
console.error(Translator.disp('errorOutputParameter'));
return process.exit(1);
}

let lang = Translator.getLanguage();
Logger.logMessage(Translator.disp('messageLanguageAuthor', [lang['language'], lang['author']]));

if (!client.user.bot) {
Logger.logError('Specified user token is not a bot user token.');
Logger.logError(Translator.disp('errorUserToken'));
return process.exit(1);
}
Logger.logMessage(`Successfully logged in as ${client.user.tag}. Starting script.`);
Logger.logMessage(Translator.disp('messsageLogin', [client.user.tag]));

let originalGuildId = settings.originalGuildId;
let newGuildId = settings.newGuildId;
Expand All @@ -30,67 +43,65 @@ client.on('ready', async () => {
try {
// Check discord.js version
let djsVersion = require('./node_modules/discord.js/package.json').version;
if (djsVersion !== '12.0.0-dev') throw new Error('Please don\'t install discord.js with \'npm install discord.js\'! Installation instructions are in the README.');
if (djsVersion !== '12.0.0-dev') throw new Error(Translator.disp('errorNPM'));

// Check script version
let { version } = require('./package.json');
let result = await VersionControl.checkVersion().catch(err => {
return { error: err || new Error('failed') };
let result = await VersionControl.checkVersion(Translator).catch(err => {
return { error: err || new Error(Translator.disp('errorUnspecified')) };
});
if (result.error) console.log(`${result.error}\nScript execution will resume.`)
else if (version !== result.version) throw new Error(`You are not using the latest script version. Please redownload the repository.`
+ `\nYour version: ${version}\nLatest version: ${result.version}`);
if (!result.error) console.log('Latest script version installed');
if (result.error) Logger.logMessage(Translator.disp('errorVersionCheckOther', [result.error]))
else if (version !== result.version) throw new Error(Translator.disp('errorVersionCheckOutdated', [version, result.version]));
if (!result.error) Logger.logMessage(Translator.disp('messageVersionCheckSuccess'));

// Settings Validation only on restore or clone
let data = { changed: false };
if (!isBackup) data = Validator.validateSettings(client, originalGuildId, newGuildId, newGuildAdminRoleId);
if (!isBackup) data = Validator.validateSettings(client, originalGuildId, newGuildId, newGuildAdminRoleId, Translator);
if (data.changed) newGuildAdminRoleId = data.newGuildAdminRoleId;

// Load/Create serialized guildData
if (fs.existsSync(backupFile) && isRestore) {
guildData = require(`./${backupFile}`);
guildData.step = 1;
Logger.logMessage(`${guildData.step++}. Serialized data was found and will be used.`);
Logger.logMessage(Translator.disp('messageSerialized', [guildData.step++]));
} else if (isRestore) {
throw new Error(`Specified restore but guild backup '${backupFile}' doesn't exist.`);
throw new Error(Translator.disp('errorRestoreNotExistent', [backupFile]));
} else {
if (!client.guilds.has(originalGuildId)) {
throw new Error('Original guild to copy does not exist. Please check if the id in the ' +
'settings is correct and if the bot is also member of this guild.');
throw new Error(Translator.disp('errorSerializationOriginalNotExistent'));
}
let banCollection = new Discord.Collection();
try {
if (settings.copyBans) banCollection = await client.guilds.get(originalGuildId).fetchBans();
} catch (banError) {
throw new Error('You tried to copy bans without giving the bot the BAN_MEMBERS permissions on the original guild.');
throw new Error(Translator.disp('errorSerializationNoBanPermissions'));
}
guildData = Serializer.serializeOldGuild(client, originalGuildId, banCollection, guildData, backupFile);
guildData = Serializer.serializeOldGuild(client, originalGuildId, banCollection, guildData, backupFile, Translator);
}

// Stop on backup only
if (isBackup) {
Logger.logMessage(`${guildData.step}. Program execution finished because backup was specified.`);
Logger.logMessage(Translator.disp('messageBackupDone', [guildData.step]));
await client.destroy();
return process.exit();
return process.exit(0);
}

// Cleanup new guild
guildData = await Cleaner.cleanNewGuild(client, newGuildId, newGuildAdminRoleId, guildData);
guildData = await Cleaner.cleanNewGuild(client, newGuildId, newGuildAdminRoleId, guildData, Translator);

// Create new guild
await Creator.setData(client, guildData, newGuildId, newGuildAdminRoleId);
await Creator.setData(client, guildData, newGuildId, newGuildAdminRoleId, Translator);
} catch (err) {
Logger.logError(err);
}

await client.destroy();
return process.exit();
return process.exit(0);
});

client.on('rateLimit', rateLimitObj => {
if (settings.debug) {
Logger.logMessage(`Rate limit reached!\nTimeout: ${rateLimitObj.timeout}\nLimit: ${rateLimitObj.limit}\n` +
Logger.logError(`Rate limit reached!\nTimeout: ${rateLimitObj.timeout}\nLimit: ${rateLimitObj.limit}\n` +
`TimeDiff: ${rateLimitObj.timeDifference}\nMethod: ${rateLimitObj.method}\nPath: ${rateLimitObj.path}\n` +
`Route: ${rateLimitObj.route}`);
}
Expand Down Expand Up @@ -119,7 +130,6 @@ function main() {
}
isBackup = args[0] === 'backup';
isRestore = args[0] === 'restore';
isClone = args[0] === 'clone';
client.login(settings.token);
}

Expand Down
15 changes: 8 additions & 7 deletions objects/cleaner.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,28 @@ class Cleaner {
* @param {string} newGuildId New guild id
* @param {string} newGuildAdminRoleId New guild Administrator role id
* @param {Object} guildData Serialized guild data
* @param {Object} translator Translator object
* @returns {Object} guildData
*/
static cleanNewGuild(client, newGuildId, newGuildAdminRoleId, guildData) {
static cleanNewGuild(client, newGuildId, newGuildAdminRoleId, guildData, translator) {
return new Promise(async (resolve, reject) => {
try {
let newGuild = client.guilds.get(newGuildId);

// Delete channel
Logger.logMessage(`${guildData.step++}. Deleting channels`);
Logger.logMessage(translator.disp('messageCleanerChannels', [guildData.step++]));
let promises = [];
newGuild.channels.forEach(channel => {
promises.push(channel.delete());
});
await Promise.all(promises);
promises = [];


// Delete roles
let filter = role => role.id !== newGuildAdminRoleId && role.id !== newGuild.defaultRole.id;
let rolesToDelete = newGuild.roles.filter(filter);
Logger.logMessage(`${guildData.step++}. Deleting roles`);
Logger.logMessage(translator.disp('messageCleanerRoles', [guildData.step++]));
rolesToDelete.forEach(role => {
promises.push(role.delete());
});
Expand All @@ -41,7 +42,7 @@ class Cleaner {

// Delete emojis
if (copyEmojis) {
Logger.logMessage(`${guildData.step++}. Deleting emojis`);
Logger.logMessage(translator.disp('messageCleanerEmojis', [guildData.step++]));
newGuild.emojis.forEach(emoji => {
promises.push(emoji.delete());
});
Expand All @@ -51,14 +52,14 @@ class Cleaner {

// Delete Bans
if (copyBans) {
Logger.logMessage(`${guildData.step++}. Lifting bans`);
Logger.logMessage(translator.disp('messageCleanerBans', [guildData.step++]));
let bans = await newGuild.fetchBans();
let unbans = [];
bans.forEach(ban => unbans.push(newGuild.members.unban(ban.user.id)));
await Promise.all(unbans);
}

Logger.logMessage(`${guildData.step++}. New guild cleanup finished`);
Logger.logMessage(translator.disp('messageCleanerFinished', [guildData.step++]));
return resolve(guildData);
} catch (err) {
return reject(err);
Expand Down
Loading

0 comments on commit 78f07bd

Please sign in to comment.