求discord.js机器人查询比特币澳元/美元价格的命令实现代码
Discord.js BTC 实时价格查询命令实现(适配v14版本)
前置准备
- 安装所需依赖:
npm install discord.js@14 axios
如果你使用的是discord.js v13及以下版本,需要调整斜杠命令的声明方式和交互处理逻辑,接口请求部分代码可通用。
功能逻辑说明
通过公开加密货币价格接口获取实时报价,支持返回BTC对美元(USD)、澳元(AUD)的最新成交价,默认使用斜杠命令触发,也可根据需求修改为前缀命令。
完整代码示例
1. 斜杠命令逻辑代码
const { SlashCommandBuilder } = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('btc-price') .setDescription('获取比特币实时兑USD、AUD价格'), async execute(interaction) { const axios = require('axios'); await interaction.deferReply(); // 避免交互超时 try { // 请求公开价格接口获取数据 const res = await axios.get('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd,aud'); const btcUsd = res.data.bitcoin.usd; const btcAud = res.data.bitcoin.aud; return interaction.editReply(` **比特币实时价格** 💵 兑美元(USD):\`$${btcUsd.toLocaleString()}\` 🇦🇺 兑澳元(AUD):\`A$${btcAud.toLocaleString()}\` 数据更新时间:<t:${Math.floor(Date.now() / 1000)}:R> `); } catch (err) { return interaction.editReply('⚠️ 当前价格接口请求失败,请稍后重试。'); } }, };
2. 主文件命令加载逻辑补充
如果还没有配置斜杠命令加载逻辑,需要在bot主文件(比如index.js)中添加以下代码段,确保命令能正常识别触发:
const fs = require('node:fs'); const path = require('node:path'); const { Client, Collection, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [GatewayIntentBits.Guilds] }); client.commands = new Collection(); const commandsPath = path.join(__dirname, 'commands'); const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); for (const file of commandFiles) { const filePath = path.join(commandsPath, file); const command = require(filePath); client.commands.set(command.data.name, command); } client.on('interactionCreate', async interaction => { if (!interaction.isChatInputCommand()) return; const command = client.commands.get(interaction.commandName); if (!command) return; try { await command.execute(interaction); } catch (error) { console.error(error); await interaction.reply({ content: '执行命令时出现错误', ephemeral: true }); } }); client.login('你的Bot Token');
使用说明
- 将上面的命令代码保存为
btc-price.js放在你项目的commands文件夹下 - 部署启动bot后,在服务器内输入
/btc-price即可触发查询 - 可根据需求自行修改返回内容的格式、添加更多币种查询逻辑,也可添加本地缓存减少接口请求频率,降低被限流的概率
内容的提问来源于stack exchange,提问作者Fish Exploits
相关产品推荐
相关产品推荐

