Как преобразовать мои многие операторы if в операторы switch? Раздор. js - PullRequest
0 голосов
/ 04 августа 2020

Я новичок в JavaScript, поэтому прошу прощения, если это нелепый вопрос.

Вот мой код:

client.on('message', message => {
    if (message.content === '!rule1') {
        message.channel.send('Rule 1: **Don\'t be annoying.**');
    }
    if (message.content === '!rule2') {
        message.channel.send('Rule 2: **Leaving the server during your crypt sentence will result in a permanent ban. 3 strikes and you\'re out.**');
    }
    if (message.content === '!rule3') {
        message.channel.send('Rule 3: **Watch your language.**');
    }
    if (message.content === '!rule4') {
        message.channel.send('Rule 4: **No NSFW content of any kind.**');
    }
    if (message.content === '!rule5') {
        message.channel.send('Rule 5: **No racism, homophobia, or other hate speech is allowed whatsoever.**');
    }
    if (message.content === '!rule6') {
        message.channel.send('Rule 6: **Moderators\' discretion.**');
    }
    if (message.content === '!rule7') {
        message.channel.send('Rule 7: **Don\'t randomly ping roles or people for no reason.**');
    }
    if (message.content === '!rule8') {
        message.channel.send('Rule 8: **No spam allowed whatsoever.** Spam will result in a delete and warn, and a crypt sentence if continued.');
    }
    if (message.content === '!rule9') {
        message.channel.send('Rule 9: Please speak English at all times! Non-English messages are subject to deletion.');
    }
    if (message.content === '!rule10') {
        message.channel.send('Rule 10: **Please avoid talking about triggering topics.**');
    }
    if (message.content === '!rule11') {
        message.channel.send('Rule 11: **Please censor all personally identifiable info from images and text.**');
    }
    if (message.content === '!rule12') {
        message.channel.send('Rule 12: **Please keep bot commands in <#620789282226962464>**.');
    }
    if (message.content === '!rule13') {
        message.channel.send('Rule 13: **Posting gore is an instant deletion of your message(s) and permanent ban.**');
    }
    if (message.content === '!rule14') {
        message.channel.send('Rule 14: **YOU MUST BE 13 YEARS OF AGE OR OLDER TO USE THIS SERVER.**');
    }
    if (message.content === '!rule15') {
        message.channel.send('Rule 15: **Politics are strictly banned from the server.**');
    }
    if (message.content === '!rule16') {
        message.channel.send('Rule 16: **Don\'t name yourself stupid things.**');
    }
    if (message.content === '!rule17') {
        message.channel.send('Rule 17: **No bright flashing media of any kind, including emotes.**');
    }
    if (message.content === '!rule18') {
        message.channel.send('Rule 18: **No Gacha edits.**');
    }
    if (message.content === '!rule19') {
        message.channel.send('Rule 19: **Keep conversation civil and appropriate.**');
    }
    if (message.content === '!rule20') {
        message.channel.send('Rule 20: **No edgy, dark or offensive jokes or memes.**');
    }
    if (message.content === '!rule21') {
        message.channel.send('Rule 21: **No threats or considerations of ||self-harm|| or ||suicide|| in the server.**');
    }
    if (message.content === '!rule22') {
        message.channel.send('Rule 22: **Anything that violates Discord TOS will get you immediately banned.**');
    }
    if (message.content === '!rule23') {
        message.channel.send('Rule 23: **Do not sexualize/ship any of the moderators, or any members of the server for that matter.**');
    }
    if (message.content === '!strikeappeal') {
        message.channel.send('If you would like to appeal a strike, you can DM <@738765589748645908>. Simply explain why you got that strike, why you think it should be removed, and apologize.');
    }
});

Думаю, вы согласитесь со мной, когда я говорят, что этот код выглядит очень длинным и беспорядочным. Есть ли способ сократить этот код? Я не могу понять, как преобразовать его во что-то вроде операторов switch. Заранее спасибо

Ответы [ 4 ]

2 голосов
/ 04 августа 2020
client.on('message', message => {
    switch (message.content) {
      case '!rule1': 
          message.channel.send('Rule 1: **Don\'t be annoying.**');
          break;
      case '!rule2':
          message.channel.send('Rule 2: **Leaving the server during your crypt sentence will result in a permanent ban. 3 strikes and you\'re out.**');
          break;
      case '!rule3':
            message.channel.send('Rule 3: **Watch your language.**');
        break;
      case '!strikeappeal':
          message.channel.send('If you would like to appeal a strike, you can DM <@738765589748645908>. Simply explain why you got that strike, why you think it should be removed, and apologize.');
          break;
        
      ...
      
      default:
            message.channel.send('Default message');
   }
});

Примечание: Не забывайте разрыв в конце case, потому что в противном случае будет выполнен и следующий case.

1 голос
/ 04 августа 2020

Как предложил @Andreas, поместите свои правила в объект, а затем создайте код общего назначения для извлечения соответствующего правила.

const rules = {
  '!rule1': 'Rule 1: **Don\'t be annoying.**',
  '!rule2': 'Rule 2: **Leaving the server during your crypt sentence will result in a permanent ban. 3 strikes and you\'re out.**'
};
// etc

client.on('message', message => {
  const ruleText = rules[message.content];
  if (ruleText) {
    message.channel.send(ruleText);
  } else {
    // normal message
  }
});
0 голосов
/ 04 августа 2020

Я изменил ваш код, чтобы уменьшить количество повторяющихся частей и упростить создание новых команд и добавление новых правил. Однако вместо того, чтобы набирать что-то вроде !rule3, вам нужно набрать !rule 3.

Для получения дополнительной информации о том, как расширить возможности вашего бота, прочитайте Discord. js руководство .

const prefix = '!';

const rules = [
    "**Don\'t be annoying.**",
    "**Leaving the server during your crypt sentence will result in a permanent ban. 3 strikes and you\'re out.**",
    "**Watch your language.**",
    "**No NSFW content of any kind.**",
    "**No racism, homophobia, or other hate speech is allowed whatsoever.**",
    "**Moderators\' discretion.**",
    "**Don\'t randomly ping roles or people for no reason.**",
    "**No spam allowed whatsoever.** Spam will result in a delete and warn, and a crypt sentence if continued.",
    "**Please speak English at all times! Non-English messages are subject to deletion.**",
    "**Please avoid talking about triggering topics.**",
    "**Please censor all personally identifiable info from images and text.**",
    "**Please keep bot commands in <#620789282226962464>.**",
    "**Posting gore is an instant deletion of your message(s) and permanent ban.**",
    "**YOU MUST BE 13 YEARS OF AGE OR OLDER TO USE THIS SERVER.**",
    "**Politics are strictly banned from the server.**",
    "**Don\'t name yourself stupid things.**",
    "**No bright flashing media of any kind, including emotes.**",
    "**No Gacha edits.**",
    "**Keep conversation civil and appropriate.**",
    "**No edgy, dark or offensive jokes or memes.**",
    "**No threats or considerations of ||self-harm|| or ||suicide|| in the server.**",
    "**Anything that violates Discord TOS will get you immediately banned.**",
    "**Do not sexualize/ship any of the moderators, or any members of the server for that matter.**"
];

client.on('message', message => {
    if (message.author.bot || !message.content.startsWith(prefix)) return;

    const args = message.content.slice(prefix.length).trim().split(/\s+/g);
    const command = args.shift().toLowercase();

    switch (command) {
        case 'rule':
            if (!args[0]) return message.reply('**usage:** `!rule <rule number>`.');

            args[0] = Number(args[0]);
            if (!(args[0] > 0 && args[0] <= rules.length)) return message.reply(`please enter a number between 1 and ${rules.length}.`);

            message.channel.send(`Rule ${args[0]}: ${rules[args[0] - 1]}`);
            break;
        case 'strikeappeal':
            message.channel.send('If you would like to appeal a strike, you can DM <@738765589748645908>. Simply explain why you got that strike, why you think it should be removed, and apologize.');
            break;
        default:
            message.reply(`the command \`${command}\` was not recognized.`);
});
0 голосов
/ 04 августа 2020

2 варианта:

  1. заменить все операторы if (кроме первого) на else if Это почти то же самое, что и switch, и требует минимальных настроек
  2. прочтите, как работает оператор switch здесь
...