Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >与命令处理程序不一致的js经济命令

与命令处理程序不一致的js经济命令
EN

Stack Overflow用户
提问于 2020-03-11 03:17:26
回答 1查看 1.1K关注 0票数 0

我最近一直在研究我的第一个经济系统和我的第一个命令处理程序。我已经设法让我的'-balance‘命令与命令处理程序正确集成,但我正在努力集成其他命令,因为异步不能与命令处理程序一起工作。如果有人能帮助我将命令完全集成到命令处理程序中,我将不胜感激

经济代码:(index.js)

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Reflect.defineProperty(currency, 'add', {
    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;
    },
});

Reflect.defineProperty(currency, 'getBalance', {
    value: function getBalance(id) {
        const user = currency.get(id);
        return user ? user.balance : 0;
    },
});

client.once('ready', async () => {
    const storedBalances = await Users.findAll();
    storedBalances.forEach(b => currency.set(b.user_id, b));
    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') {
        const target = message.mentions.users.first() || message.author;
        return message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}?`);
        */

    if (command === 'buy') { //} else
        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 don't have enough currency, ${message.author}`);
        }
        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 a ${item.name}`);
    }

    if (command === 'shop') { 
        const items = await CurrencyShop.findAll();
        return message.channel.send(items.map(i => `${i.name}: ${i.cost}?`).join('\n'), { code: true });
    } else if (command === 'leaderboard') {
        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 }
        );
    }
});

命令处理程序:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
client.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const commandName = args.shift().toLowerCase();

    const command = client.commands.get(commandName)
        || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));

    if (!command) return;

    if (command.guildOnly && message.channel.type !== 'text') {
        return message.reply('I can\'t execute that command inside DMs!');
    }

    if (command.args && !args.length) {
        let reply = `You didn't provide any arguments, ${message.author}!`;

        if (command.usage) {
            reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
        }

        return message.channel.send(reply);
    }

    if (!cooldowns.has(command.name)) {
        cooldowns.set(command.name, new Discord.Collection());
    }

    const now = Date.now();
    const timestamps = cooldowns.get(command.name);
    const cooldownAmount = (command.cooldown || 3) * 1000;

    if (timestamps.has(message.author.id)) {
        const expirationTime = timestamps.get(message.author.id) + cooldownAmount;

        if (now < expirationTime) {
            const timeLeft = (expirationTime - now) / 1000;
            return message.reply(`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command.`);
        }
    }

    timestamps.set(message.author.id, now);
    setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);

    try {
        command.execute(message, args);
    } catch (error) {
        console.error(error);
        message.reply('there was an error trying to execute that command!');
    }
});
EN

回答 1

Stack Overflow用户

发布于 2020-09-28 03:44:54

我相信async确实可以使用命令处理程序,如下所示

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
async execute(message) {
// code
    },

此外,只需将货币常量导入到每个需要它的命令文件中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60628777

复制
相关文章
log4js日志
该文章介绍了如何利用log4j2的配置文件对日志进行切割和归档,并给出了具体的例子。
用户1141560
2017/12/26
2.3K0
log4js的配置
log4js是一个日志记录模块,可以单独使用,也可以,结合服务框架使用,这里结合express配置来使用。
挥刀北上
2023/05/25
9020
log4js的配置
Log4js 2.9.0 日志管理插件
Node端的日志插件Log4js,以后版本更新了继续跟进 安装&&版本 npm install log4js 或者 yarn add log4js "express": "4.16.2", "log4js": "2.9.0", 最简单的写法 var log4js = require('log4js'); var logger = log4js.getLogger(); logger.level = 'debug'; logger.debug("Some debug messages"); 稍
CloudCat
2022/06/15
4320
基于 log4js 做全链路日志
提到监控或应用观测,经常出现三个词:「链路(Tracing)」、「指标(Metric)」和「日志(Logging)」。
joefu
2022/01/20
2.5K1
MySQL kill会话不起作用?
在一次日常测试中发现,kill 一个会话后,SQL语句依然在运行并没终止;被kill的会话重新连接并继续执行原来的SQL语句。
老叶茶馆
2023/09/01
2520
MySQL kill会话不起作用?
nodejs总结之日志模块log4js
1 /** 2 * npm install log4js 3 * 源码及文档地址:https://github.com/nomiddlename/log4js-node 4 */ 5 var log4js = require('log4js'); 6 7 /** 8 * 第一种: 9 * configure方法为配置log4js对象,内部有levels、appenders、categories三个属性 10 * levels: 11 *
晓晨
2018/06/22
2.9K0
nodejs使用log4js做日志系统
在一个项目当中,日志系统在项目中重要性在这里就不再累述,log4js是nodejs中的一个日志模块,通过设置其优先级别,可以打印出不同级别的日志,便于后续的系统分析。下面来介绍一下log4js的具体使用,这里介绍的版本为2.8.0。
OECOM
2020/07/01
5K0
MySQL kill会话不起作用?
在一次日常测试中发现,kill 一个会话后,SQL语句依然在运行并没终止;被kill的会话重新连接并继续执行原来的SQL语句。
GreatSQL社区
2023/08/10
3980
MySQL kill会话不起作用?
RecyclerView.Adapter notifyDataSetChanged 不起作用
如果应用启动,不在聊天界面,接收到消息后就弹出通知栏消息通知用户,点击进入聊天界面。
张拭心 shixinzhang
2022/05/06
3K0
关于.gitignore不起作用「建议收藏」
由于公司和家里的as版本不同,倒腾了好久,但是代码到本地后build.gradle等文件做了修改,为了不影响公司版本,故家里的需要忽略这些文件的修改,想到的就是加gitignore配置,直接添加不起效果,找到如下办法:
全栈程序员站长
2022/11/01
2K0
setOnItemClickListener不起作用解决方法
setOnItemClickListener不起作用解决方法 问题 原因 源码解析 解决方法 问题 使用ListView时通常会和Adapter一起使用,在使用setOnItemClickListener方法监听节点时不起作用 原因 原因是因为在你自己定义的Item中存在诸如ImageButton,Button,CheckBox等子控件,此时这些子控件会获取到焦点,所以常常当点击item时变化的是子控件,item本身的点击没有响应,此时就该用到descendantFocusability属性了,下面让我
是阿超
2022/05/05
2K0
setOnItemClickListener不起作用解决方法
Nginx配置缺失导致CSS不起作用
启动nginx,打开网页,发现样式并没有如期加载,看chrome的console,显示如下:
血狼debugeeker
2021/03/02
3.9K0
解决CSS属性position:fixed不起作用
若父元素设置了transform属性,无论transform设置任何属性值,都会导致position:fixed属性失效!
赵彤刚
2022/12/13
3.3K0
解决CSS属性position:fixed不起作用
textarea 的 placeholder="" 不起作用
textarea 的 placeholder="请输入解决方案(极简化、不超过500字)" 不起作用
一个会写诗的程序员
2018/08/17
2K0
FeignClient 设置 fallback不起作用
StringCloud FeignClient 设置 fallback不起作用 今天在配置feign中是用hystrix的时候,FeignClient 中的 fallback不起任何作用,本来以为是 不支持这个属性了,打开源码一看,还提供这个fallback属性,后来翻阅各中资料,才发现是没有打开feign对hustrix的支持。下面是解决方案: 在application.yml中加入如下配置就可以了 feign: hystrix: enabled: true
码农笔录
2018/06/29
3.5K0
网站就必须用响应式布局吗?MVC视图展现模式之移动布局
本文先引入给读者一个自己研究的机会,下次深入说明一下: 废话不多说,直接上图 新建一个mvc的项目 在视图里面添加一个移动端视图 正常访问一下 Bootstrap自带的响应式的方式(页面代码并没有改变
逸鹏
2018/04/10
1.1K0
网站就必须用响应式布局吗?MVC视图展现模式之移动布局
【约束布局】使用 Design 模式编辑 ConstraintLayout 约束布局 ( 添加 Guideline 引导线 | 添加 FragmentContainerView )
向约束布局 ConstraintLayout 中添加两个 Fragment , 垂直方向各占 50 % , 一个在屏幕上半部分 , 一个占据屏幕下半部分 ;
韩曙亮
2023/03/30
1.1K0
【约束布局】使用 Design 模式编辑 ConstraintLayout 约束布局 ( 添加 Guideline 引导线 | 添加 FragmentContainerView )
【3/25】使用组合模式(Composite Pattern)实现布局容器
组合模式(Composite)是将对象组合成树形结构,以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性。接下来我们考虑在当前项目中应用组合模式。
LIYI
2021/02/23
6900
【3/25】使用组合模式(Composite Pattern)实现布局容器
MVC视图展现模式之移动布局解析-续集
网站就必须用响应式布局吗?MVC视图展现模式之移动布局:http://www.cnblogs.com/dunitian/p/5213787.html 有人会疑问,为什么他能识别.mobile的后缀却不
逸鹏
2018/04/10
7970
MVC视图展现模式之移动布局解析-续集
点击加载更多

相似问题

node log4js maxlogsize不起作用

149

log4js npm错误,log4js配置

10

转义花括号在LOG4Js -替换{模式}{regex}{替换}

12

布局-土地概念在景观模式下不起作用

12

Log4js配置错误

119
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文