You need to enable JavaScript to run this app. Discord机器人天气命令报TypeError: args.join is not a function如何修复
优惠活动
大模型
产品
解决方案
定价
更多

Discord机器人天气命令报TypeError: args.join is not a function如何修复

Discord机器人天气命令报错修复方案

错误根因

TypeError: args.join is not a function 报错的核心原因是传入run函数的args参数不是数组类型,只有数组才支持join方法,你尝试调用args[0].join的逻辑也是错误的,args[0]是数组的第一个元素,更不可能具备数组方法。

修复步骤

  1. 校验命令处理器的传参顺序
    绝大多数Discord.js命令框架的run函数传参顺序为(client, message, args),你当前代码写的参数顺序是(message, args, client),如果和你主文件的命令调用逻辑不匹配,会导致拿到的args实际是message对象,自然不是数组。你可以先在run函数第一行加一行打印确认参数:
console.log('args类型:', typeof args, 'args值:', args)

如果打印出来是对象而非数组,就把参数顺序调整为和调用逻辑一致即可。

  1. 检查主文件的参数拆分逻辑
    确认你主文件处理消息的代码里,有正确将消息内容拆分为参数数组,正确的拆分示例如下:
// 假设prefix是你设置的命令前缀
const args = message.content.slice(prefix.length).trim().split(/ +/)
const command = args.shift().toLowerCase()

如果没有这段拆分逻辑,你传入命令的args就不会是数组。

  1. 修复代码中其他潜在问题
  • 你使用了MessageEmbed但没有正确导入,需要改为new discord.MessageEmbed(),否则会抛出未定义错误。
  • 你当前degreeType设置为F(华氏度),但嵌入消息里写的温度单位是Celcius(摄氏度),单位会不匹配,按需调整其中一处即可。
  • 建议先判断weather.find回调的err参数和result数组是否为空,避免无效查询直接进入catch抛出通用报错。

修正后的完整代码

const weather = require('weather-js');
const discord = require('discord.js')

module.exports = {
  name: "weather",
  description: "Get the weather of anywhere",
  category: "info",
  usage: "weather [地区名称]",
  // 先确认你这里的参数顺序和主文件调用逻辑一致,如果你主文件传参是(client, message, args),就保留当前顺序即可
  run: (client, message, args) => {
    // 先判断有没有传入地区参数
    if (!args.length) return message.channel.send("请指定要查询的地区")
    weather.find({search: args.join(" "), degreeType: 'C'}, function(err, result) {
      // 先处理接口报错或无返回结果的情况
      if (err || !result || !result.length) return message.channel.send("无法获取指定地区的天气数据")
      try {
        const embed = new discord.MessageEmbed()
        .setTitle(`天气 - ${result[0].location.name}`)
        .setColor("#ff2050")
        .setDescription("温度单位可能存在一定偏差")
        .addField("温度", `${result[0].current.temperature} 摄氏度`, true)
        .addField("天气状况", result[0].current.skytext, true)
        .addField("湿度", result[0].current.humidity, true)
        .addField("风速", result[0].current.windspeed, true)
        .addField("观测时间", result[0].current.observationtime, true)
        .addField("风向信息", result[0].current.winddisplay, true)
        .setThumbnail(result[0].current.imageUrl);
        message.channel.send(embed)
      } catch(err) {
        return message.channel.send("无法获取指定地区的天气数据")
      }
    });   
  }
}

内容的提问来源于stack exchange,提问作者RektVFX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 20:24:04