为什么randomstring对于相同的常数给出不同的值?

时间:2020-07-25 05:55:21

标签: javascript discord.js

我认为我没有将值重新分配给常量,验证码,也可能未基于验证码重新分配。

如果用户使用不带args的命令,则该代码应将图像中带有验证码的DM发送给用户;如果用户成功输入了最新生成的验证码,则该代码应给用户一个角色,并以成功消息进行答复。但是,即使从图像中看到输入验证码,该漫游器仍会回答该验证码是错误的。我尝试添加checkmymoney,但现在也无法正常工作。

这是我的代码:

很抱歉,如果答案很明显,我想不出解决方案,而且我对编程没什么看法。

const { prefix } = require('../config.json');

module.exports = {
    name: 'verify',
    description: 'This command allows you to verify yourself',
    aliases: ['verification'],
    usage: 'without arguments to get verification code and with verification code to verify',
    cooldown: 5,
    execute(message, args) {
        const data = [];
        const Discord = require('discord.js');
        const { commands } = message.client;

        const member = message.author;
        
        const randomString =  require('random-string')
        const verificationcode = randomString({
            length: 6,
            numeric: true,
            letters: false,
            special: false,
        });
 

        const verificationimg = `https://flamingtext.com/net-fu/proxy_form.cgi?imageoutput=true&script=supermarket-logo&text=${verificationcode}&doScale=true&scaleWidth=240&scaleHeight=120&backgroundRadio=2&backgroundPattern=Purple+Glow`

        if (!args.length) {

            const verificationEmbed = new Discord.MessageEmbed()
                .setColor("#0000FF")
                .setAuthor(message.author.tag, message.author.displayAvatarURL({ dynamic: true}))
                .setTitle("Verification Image")
                .setDescription(`Please do \`verify (code shown in image)\` in the server to verify yourself and gain access to rest of server. If the image is not loading, use this link: \`${verificationimg}\``)
                .setTimestamp()
                .setImage(verificationimg)
                .setFooter("MikuBot verification");

            
            return message.author.send(verificationEmbed)
                .then(() => {
                    if (message.channel.type === 'dm') return;
                        message.reply('Check your DMs for the verification code');
                        console.log(`User ${message.author.tag} requested for verification code.`);
                    })
    
                    .catch(error => {
                        console.error(`Could not send verification DM to ${message.author.tag}.\n`, error);
                        message.reply(`The DM couldn't get through. Please ensure that 1) You have DMs enabled for this server 2) You allow me to send DMs to you. If error persists, contact a @Helper for assistance.`);
                });
        }
        
        

        else if (args.length) {
           let role = message.guild.roles.cache.find(r => r.name === 'test');
           const userMessage = args
           if (verificationcode === undefined) {
               return message.channel.send (`Please use \`!verify\` without arguments first to generate your verification code.`)
           }
           else if (userMessage === "checkmycode") {
                return message.channel.send(verificationcode)
            }
           else if (verificationcode != userMessage) {
               return message.channel.send (`Verification code is wrong! Please try again`)
           }
           else if (verificationcode === userMessage) {
                if(role) message.member.roles.add(role);
                message.channel.type === 'dm'
                return message.channel.send(`You have been successfully verified in **OwO Server**`)
           }
        
    }
}}

2 个答案:

答案 0 :(得分:0)

当用户第一次调用您的函数时,您会生成一个代码,但不会存储该代码,因此,当用户第二次使用arg调用该函数时,您会生成第二个与第一个代码不同的代码。

答案 1 :(得分:0)

我已经通过删除未使用的变量,删除无用的语句,移动代码块,修复缩进和修复验证功能对您的代码进行了很多修改。

我通过在文件开头使用const codes = new Discord.Collection();创建一个新集合并添加与用户ID关联的验证码来解决验证码问题。由于变量是在函数外部声明的,因此它保持其值,因此不会产生与旧代码不匹配的新代码的问题。

const Discord = require('discord.js');
const randomString =  require('random-string');

const codes = new Discord.Collection();

module.exports = {
  name: 'verify',
  description: 'This command allows you to verify yourself',
  aliases: ['verification'],
  usage: 'without arguments to get verification code and with verification code to verify',
  cooldown: 5,
  execute(message, args) {
    if (message.author.bot) return;
    
    if (!args.length) {
      codes.set(message.user.id, randomString({
        length: 6,
        numeric: true,
        letters: false,
        special: false
      }));

      const img = 'https://flamingtext.com/net-fu/proxy_form.cgi?imageoutput=true&script=supermarket-logo&text='
      + verificationcode
      + '&doScale=true&scaleWidth=240&scaleHeight=120&backgroundRadio=2&backgroundPattern=Purple+Glow';

      const embed = new Discord.MessageEmbed()
        .setColor('#0000FF')
        .setAuthor(message.author.tag, message.author.displayAvatarURL({ dynamic: true }))
        .setTitle('Verification Code')
        .setDescription('Please type `!verify <code in image>` to verify yourself and access the rest of the server.'
          + 'If the image is not loading, use this link instead: `' + img + '`.')
        .setTimestamp()
        .setImage(img)
        .setFooter('MikuBot verification');
      
      return message.author.send(embed)
        .then(() => {
          message.reply('Please check your DMs for the verification code');
          console.log('User ' + message.author.tag + ' requested a verification code.');
        }).catch(err => {
          message.reply('An error occurred when sending a DM. Please ensure that '
            + '1) You have DMs enabled for this server '
            + '2) You allow me to send DMs to you.'
            + 'If the error persists, please contact a @Helper for assistance.');
          console.error('Could not send a verification DM to ' + message.author.tag + ': ' + err);
        });
    } else {
      const role = message.guild.roles.cache.find(r => r.name === 'test');

      const subcommand = args[0];

      if (codes.has(message.user.id)) {
        if (subcommand === 'checkmycode') {
          return message.reply(codes.get(message.user.id));
        } else if (subcommand === codes.get(message.user.id)) {
          if (role) message.member.roles.add(role);

          codes.delete(message.user.id);

          return message.reply('You have successfully been verified in **OwO Server**.');
        }
      } else {
        return message.reply('Please use `!verify` without arguments first to generate your verification code.');
      }
    }
  }
};