javascript - Getting SyntaxError: Lexical declaration cannot appear in a single-statement context - Stack Overflow

The let part of my code is producing an error I figured out why the bot wouldn't start by moving t

The let part of my code is producing an error I figured out why the bot wouldn't start by moving the client.login to the bottom new error includes it just spamming "Invalid Zip Code. Please follow the format: _weather <#####>" even if you put in the zipcode

client.on("message", (message) => {
    if (message.content.includes("_weather") && message.author.bot === false)
        let zipCode = message.content.split(" ")[1];
    if (zipCode === undefined || zipCode.length != 5 || parseInt(zipCode) === NaN) {
        message.channel.send("`Invalid Zip Code. Please follow the format: _weather <#####>`")
            .catch(console.error);
        return;
    } else {
        fetch(`.5/weather?zip=${zipCode},us&appid=439d4b804bc8187953eb36d2a8c26a02`)
            .then(response => {
                return response.json();
            })
            .then(parsedWeather => {
                if (parsedWeather.cod === '404') {
                    message.channel.send("`This zip code does not exist or there is no information avaliable.`");
                } else {
                    message.channel.send(`

        The Current Weather
        Location: ${parsedWeather.name}, ${parsedWeather.sys.country}
        Forecast: ${parsedWeather.weather[0].main}
        Current Temperature: ${(Math.round(((parsedWeather.main.temp - 273.15) * 9 / 5 + 32)))}° F
        High Temperature: ${(Math.round(((parsedWeather.main.temp_max - 273.15) * 9 / 5 + 32)))}° F
        Low Temperature: ${(Math.round(((parsedWeather.main.temp_min - 273.15) * 9 / 5 + 32)))}° F
        `);

                }
            });
    }
});
client.login('token');

The let part of my code is producing an error I figured out why the bot wouldn't start by moving the client.login to the bottom new error includes it just spamming "Invalid Zip Code. Please follow the format: _weather <#####>" even if you put in the zipcode

client.on("message", (message) => {
    if (message.content.includes("_weather") && message.author.bot === false)
        let zipCode = message.content.split(" ")[1];
    if (zipCode === undefined || zipCode.length != 5 || parseInt(zipCode) === NaN) {
        message.channel.send("`Invalid Zip Code. Please follow the format: _weather <#####>`")
            .catch(console.error);
        return;
    } else {
        fetch(`https://openweathermap/data/2.5/weather?zip=${zipCode},us&appid=439d4b804bc8187953eb36d2a8c26a02`)
            .then(response => {
                return response.json();
            })
            .then(parsedWeather => {
                if (parsedWeather.cod === '404') {
                    message.channel.send("`This zip code does not exist or there is no information avaliable.`");
                } else {
                    message.channel.send(`

        The Current Weather
        Location: ${parsedWeather.name}, ${parsedWeather.sys.country}
        Forecast: ${parsedWeather.weather[0].main}
        Current Temperature: ${(Math.round(((parsedWeather.main.temp - 273.15) * 9 / 5 + 32)))}° F
        High Temperature: ${(Math.round(((parsedWeather.main.temp_max - 273.15) * 9 / 5 + 32)))}° F
        Low Temperature: ${(Math.round(((parsedWeather.main.temp_min - 273.15) * 9 / 5 + 32)))}° F
        `);

                }
            });
    }
});
client.login('token');
Share Improve this question edited May 5, 2020 at 1:13 Forge Mods asked May 5, 2020 at 0:09 Forge ModsForge Mods 251 silver badge9 bronze badges 3
  • 2 Would be helpful to paste the error – Syntle Commented May 5, 2020 at 0:14
  • Correct Me If I'm wrong but it looks like your bots logs in every time a message is sent? – Supesu Commented May 5, 2020 at 0:16
  • ``` let zipCode = message.content.split(" ")[1]; ^^^ SyntaxError: Lexical declaration cannot appear in a single-statement context ```is the error & regards to the logging every time it sends a message... no? it only checks for the message "_weather" – Forge Mods Commented May 5, 2020 at 0:26
Add a ment  | 

1 Answer 1

Reset to default 8

You can't use lexical declarations (const and let) after statements like if, else, for etc. without a block ({}). Use this instead:

client.on("message", (message) => {
    // declares the zipCode up here first
    let zipCode
    if (message.content.includes("_weather") && message.author.bot === false)
        zipCode = message.content.split(" ")[1];
    // rest of code
});

Edit for 2nd question

You need to check if the message was sent by a bot so that it will ignore all messages sent by them, including the 'Invalid Zip Code' message:

client.on("message", (message) => {
    if (!message.author.bot) return;
    // rest of code
});

Without that, the 'Invalid Zip Code' message would trigger the bot to send another 'Invalid Zip Code' message as 'Invalid Zip Code' is obviously not a valid zip code.


Also, change parseInt(zipCode) === NaN to Number.isNaN(parseInt(zipCode)). NaN === NaN is false for some reason in JS, so you need to use Number.isNaN. You could also just do isNaN(zipCode) because isNaN coerces its input to a number and then checks if it's NaN.

console.log(`0 === NaN: ${0 === NaN}`)
console.log(`'abc' === NaN: ${'abc' === NaN}`)
console.log(`NaN === NaN: ${NaN === NaN}`)
console.log('')
console.log(`isNaN(0): ${isNaN(0)}`)
console.log(`isNaN('abc'): ${isNaN('abc')}`)
console.log(`isNaN(NaN): ${isNaN(NaN)}`)
console.log('')
console.log(`Number.isNaN(0): ${Number.isNaN(0)}`)
console.log(`Number.isNaN('abc'): ${Number.isNaN('abc')}`)
console.log(`Number.isNaN(NaN): ${Number.isNaN(NaN)}`)


Edit 2

Try this code:

client.on("message", (message) => {
  if (message.content.includes("_weather") && !message.author.bot) {
    let zipCode = message.content.split(" ")[1];
    if (zipCode === undefined || zipCode.length != 5 || Number.isNaN(parseInt(zipCode))) {
      message.channel.send("`Invalid Zip Code. Please follow the format: _weather <#####>`")
        .catch(console.error);
      return;
    } else {
      fetch(`https://openweathermap/data/2.5/weather?zip=${zipCode},us&appid=439d4b804bc8187953eb36d2a8c26a02`)
        .then(response => {
          return response.json();
        })
        .then(parsedWeather => {
          if (parsedWeather.cod === '404') {
            message.channel.send("`This zip code does not exist or there is no information avaliable.`");
          } else {
            message.channel.send(`

        The Current Weather
        Location: ${parsedWeather.name}, ${parsedWeather.sys.country}
        Forecast: ${parsedWeather.weather[0].main}
        Current Temperature: ${(Math.round(((parsedWeather.main.temp - 273.15) * 9 / 5 + 32)))}° F
        High Temperature: ${(Math.round(((parsedWeather.main.temp_max - 273.15) * 9 / 5 + 32)))}° F
        Low Temperature: ${(Math.round(((parsedWeather.main.temp_min - 273.15) * 9 / 5 + 32)))}° F
        `);

          }
        });
    }
  }
})

Edit 3

if (message.content.startsWith("_weather") && !message.author.bot)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742271174a4412725.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信