javascript - 从之前的命令获取数据

标签 javascript github heroku discord.js

我一直在尝试为我的 Discord Bot 获取 Bio,以保存用户使用 setBio 命令设置的 Bio,因为每次我重置机器人时 Bios 也会重置。然而,我想出了一些我不完全确定该怎么做的事情(如果我能做到的话)。

在机器人重置并且有人首次尝试使用 setBio 命令后,机器人会查看消息历史记录并找到该人上次使用该命令的时间。然后,它使用 args.slice(1) 来仅读取用于设置该 Bio 的参数。然后机器人会说:

I found a previous Bio that was set earlier. Type yes if you want to set your Bio to this:

Example bio

之后,如果用户输入yes,则将使用该 Bio。为了让它不那么烦人,只有在重置后第一次有人更改 Bio 时才会这样做。

我只有这个,我不知道如何将其放入代码中。 要使用什么才能实现这一点?

以下是与此问题相关的一些代码:

     case 'setBio':
        let newArr = args.slice(1)
        bio[message.author.id] = newArr
        message.channel.send('Your bio has been changed!')
            .then(msg => msg.delete(3000)); 
        break;
     case 'profile':
        if(!bio[message.author.id]) {
        return message.channel.send('Sorry, please set a bio with `!setBio` to view your profile!')
        } else {
        const embed = new Discord.RichEmbed()
            .setTitle('__' + message.author.username + '\'s Profile__')
            .addField('Bio:', bio[message.author.id].join(" "))
            .setColor(message.member.colorRole.color)
            .setThumbnail(message.author.avatarURL)
            message.channel.send(embed);
        }
        break;

最佳答案

这是可能的,但还有更实用的方法来解决您的整体问题。

回答您原来的问题:

  1. 获取 channel 中的所有消息。

    TextChannel#messages是包含 channel 中所有消息的属性。

  2. 仅过滤掉调用该命令的用户发出的消息。

    Collection#filter(fn, thisArg)是一种可以根据任何 bool 返回函数 fn 过滤掉集合中的值的方法.

  3. 仅过滤掉 setBio 的使用命令。

    我们将再次使用Collection#filter .

  4. 从用户发出的消息集合中获取第一个值。

    Collection#last()是获取集合中最后一个值的方法。

  5. 发送提示,询问用户是否要使用最后的生物集。
  6. 等待用户响应。

    有很多方法可以做到这一点,但其中一种方法可以通过创建另一个消息事件,然后等待用户回复"is"或“否”的消息来完成。

所以,你可以使用这段代码:

case "setBio":
    let messages = message.channel.messages;
    let authorMessages = messages.filter(m => m.author.id === message.author.id);
    let setBioCommands = authorMessages.filter(m => m.content.startsWith(/*insert setBio command
                                                                           with prefix here*/);
    let firstBio = setBioCommands.last();
    // say user prompt, then wait for user to say yes.

但是,解决此问题的更好方法是将所有用户数据存储在单独的文件中,就像 @Snel23 所说的那样。

这样,即使机器人关闭,所有用户数据也将保留。

关于javascript - 从之前的命令获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58476720/

相关文章:

javascript - 更改属性或将事件应用于 jQuery 中的多个对象

github - 在 GitHub 操作中缓存 node_modules

security - 如何安全地允许 Github Actions 检查 PR 并在评论中发布结果

swift - 使用 Swift 4.1 将 Vapor 3 beta 应用程序部署到 Heroku 时出现问题

javascript - 使用 javascript 获取 SELECT 元素的值

javascript - 从 1..N 项数组中查找丢失的项

javascript - XMLHttpRequest() 设置间隔

email - Github API 无法设置用户电子邮件

python - Heroku 上的基本 Django 静态文件部署

node.js - 未找到 Heroku 应用程序