Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

node.js - What is the right organization for this Currency bot - code wise?

i get an error saying, "await is only valid in an async function" which makes me think I didn't put something in for the code or I misplaced it. Or maybe I needed to make another main file as this one is a bit big and cluttered? But I have no idea what's wrong...and help is appreciated.

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

const Sequelize = require('sequelize');

This of course is mandatory and correct^^^

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 = "&";

This part is messy and is the reason why it might not be working?^^^ Below is information which might be where I messed up on?

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*([sS]*)/);

Some commands written below which would probably be best ignored.

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('
'), { 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('
'),
    { 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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to put every line with an await parameter in an async function. For example:

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

And do that with every other line that has an await in it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...