【问题标题】:What is the right organization for this Currency bot - code wise?这个货币机器人的正确组织是什么 - 代码明智?
【发布时间】:2023-04-09 09:33:02
【问题描述】:

我收到一条错误消息,“await 仅在异步函数中有效”,这让我认为我没有为代码添加任何内容,或者我放错了位置。或者也许我需要制作另一个主文件,因为这个文件有点大而且杂乱?但我不知道出了什么问题……感谢您的帮助。

const Discord = require("discord.js");

const Sequelize = require('sequelize');

这当然是强制性的,正确的^^^

const fs = require("fs");
const client = new Discord.Client();
const { Users, CurrencyShop } = require('./dbObjects');
const { Op } = require('sequelize');
const currency = new Discord.Collection();
const prefix = "&";

这部分很乱,是它可能无法正常工作的原因吗?^^^ 下面是我可能搞砸的信息?

client.once('ready', async () => {
    // [beta]
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', async message => {
    if (message.author.bot) return;
    currency.add(message.author.id, 1);

if (!message.content.startsWith(PREFIX)) return;
const input = message.content.slice(PREFIX.length).trim();
if (!input.length) return;
const [, command, commandArgs] = input.match(/(\w+)\s*([\s\S]*)/);

下面写的一些命令可能最好忽略。

if (command === 'balance') {
    // [gamma]
} else if (command === 'inventory') {
    // [delta]
} else if (command === 'transfer') {
    // [epsilon]
} else if (command === 'buy') {
    // [zeta]
} else if (command === 'shop') {
    // [theta]
} else if (command === 'leaderboard') {
    // [lambda]
}

});

Reflect.defineProperty(currency, 'add', {
    /* eslint-disable-next-line func-name-matching */
    value: async function add(id, amount) {
        const user = currency.get(id);
        if (user) {
            user.balance += Number(amount);
            return user.save();
        }
        const newUser = await Users.create({ user_id: id, balance: amount });
        currency.set(id, newUser);
        return newUser;
    },
});

const storedBalances = await Users.findAll();
storedBalances.forEach(b => currency.set(b.user_id, b));

const target = message.mentions.users.first() || message.author;
return message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}????`);

const target = message.mentions.users.first() || message.author;
const user = await Users.findOne({ where: { user_id: target.id } });
const items = await user.getItems();

if (!items.length) return message.channel.send(`${target.tag} has nothing!`);
return message.channel.send(`${target.tag} currently has ${items.map(i => `${i.amount} ${i.item.name}`).join(', ')}`);

const currentAmount = currency.getBalance(message.author.id);
const transferAmount = commandArgs.split(/ +/g).find(arg => !/<@!?\d+>/g.test(arg));
const transferTarget = message.mentions.users.first();

if (!transferAmount || isNaN(transferAmount)) return message.channel.send(`Sorry ${message.author}, that's an invalid amount.`);
if (transferAmount > currentAmount) return message.channel.send(`Sorry ${message.author}, you only have ${currentAmount}.`);
if (transferAmount <= 0) return message.channel.send(`Please enter an amount greater than zero, ${message.author}.`);

currency.add(message.author.id, -transferAmount);
currency.add(transferTarget.id, transferAmount);

return message.channel.send(`Successfully transferred ${transferAmount}???? to ${transferTarget.tag}. Your current balance is ${currency.getBalance(message.author.id)}????`);

const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: commandArgs } } });
if (!item) return message.channel.send(`That item doesn't exist.`);
if (item.cost > currency.getBalance(message.author.id)) {
    return message.channel.send(`You currently have ${currency.getBalance(message.author.id)}, but the ${item.name} costs ${item.cost}!`);
}

const user = await Users.findOne({ where: { user_id: message.author.id } });
currency.add(message.author.id, -item.cost);
await user.addItem(item);

message.channel.send(`You've bought: ${item.name}.`);

const items = await CurrencyShop.findAll();
return message.channel.send(items.map(item => `${item.name}: ${item.cost}????`).join('\n'), { code: true });

return message.channel.send(
    currency.sort((a, b) => b.balance - a.balance)
        .filter(user => client.users.cache.has(user.user_id))
        .first(10)
        .map((user, position) => `(${position + 1}) ${(client.users.cache.get(user.user_id).tag)}: ${user.balance}????`)
        .join('\n'),
    { code: true }
);


Reflect.defineProperty(currency, 'getBalance', {
    /* eslint-disable-next-line func-name-matching */
    value: function getBalance(id) {
        const user = currency.get(id);
        return user ? user.balance : 0;
    },
});

client.commands = new Discord.Collection();

const commandFiles = fs
  .readdirSync("./battle_game/")
  .filter((file) => file.endsWith(".js"));

for (const file of commandFiles) {
  const command = require(`./battle_game/${file}`);

  client.commands.set(command.name, command);
}

client.once("ready", () => {
  console.log("Rosy Bree is online!");
});

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

  const [commandName, ...args] = message.content
    .slice(prefix.length)
    .split(/ +/);

  const command = client.commands.get(commandName.toLowerCase());

  if (!command) {
    return;
  }

  command.execute(message, args);
});

client.login('token');

【问题讨论】:

    标签: node.js async-await discord.js


    【解决方案1】:

    您需要将带有等待参数的每一行放入异步函数中。 例如:

    async function yourFunction() {
        const storedBalances = await Users.findAll();
        storedBalances.forEach(b => currency.set(b.user_id, b));
    }
    

    然后对其中包含 await 的所有其他行执行此操作。

    【讨论】:

    • 谢谢!但我现在有另一个错误,我不知道它是否相关,但它在 cmd 提示符上显示“未处理的承诺拒绝警告”
    • @RUEBee 你的新代码是什么,它在哪里给你未处理的承诺警告?
    • pastebin.com/C5aTGVQW = 错误信息 + 位置 pastebin.com/uMn1WELw = 新代码
    • SQLITE_ERROR: no such table: users 你没有users 表,你需要先创建它,然后再读/写它。我发现这个帖子可以帮助你:link
    猜你喜欢
    • 1970-01-01
    • 2020-11-27
    • 2014-01-17
    • 2023-04-04
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 2014-08-05
    相关资源
    最近更新 更多