Having problems using weather-js - node.js

Some monthes ago I followed a tutorial to code a bot that shows weather forecast depending on a stated location. This bot is using weather-js package, but since recently, no matter if I host my bot or launch it through the console, it's working when it wants to, and not working for some locations.
Here is what contains my index.js :
const fs = require('fs');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
\\client.on("ready")....
.....
client.on('messageCreate', async message => {
if (!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).split(" ");
let command = args.shift().toLowerCase()
if (command === "weather") {
client.commands.get("weather").execute(message, args, Discord, weather)
}
});
and what my weather.js contains:
var weather = require('weather-js');
const Discord = require('discord.js');
module.exports = {
name: 'weather',
description: "Used to get the weather of a place",
execute(message, args, Discord, weather) {
const city = args[0]
weather.find({search: args.join(" "), degreeType: "C"}, function(error, result){
if (error) return message.channel.send(error)
if (!city) return message.channel.send("You must specify a location please!")
if (result === undefined || result.length === 0) return message.channel.send("**Invalid location**")
let current = result[0].current
let location = result[0].location
const embed = new Discord.MessageEmbed()
.setTitle(`Weather forecast for ${current.observationpoint}`)
.setDescription(current.skytext)
.setThumbnail(current.imageUrl)
.setColor("RANDOM")
.setTimestamp()
.addField("Temperature: ", current.temperature + "°C", true)
.addField("Wind Speed: ", current.winddisplay, true)
.addField("Humidity: ", `${current.humidity}%`, true)
.addField("Timezone: ", `UTC${location.timezone}`, true)
message.channel.send({ embeds: [embed]});
})
}
}
I always got that same error when it doesn't work:
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async TextChannel.send (/home/container/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:175:15) {
There's even some locations that were working before, but that suddenly stopped working for any reason!
Has someone had the same problems with weather-js, or is it coming from the code?
Thank you by advance!

One of your line on embed should be a null. That's why its throwing an error. To prevent this. You can use an OR operator.
const embed = new Discord.MessageEmbed()
.setTitle(`Weather forecast for ${current.observationpoint || "NO DATA"}`)
.setDescription(`${current.skytext || "NO DATA"}`) //Using a direct call can cause an error.
.setThumbnail(current.imageUrl) //If this part is the culprit let me know
.setColor("RANDOM")
.setTimestamp()
.addField("Temperature: ", `${current.temperature || "NO DATA"} °C`, true)
.addField("Wind Speed: ", `${current.winddisplay || "NO DATA"}`, true)
.addField("Humidity: ", `${current.humidity || "NO DATA"}%`, true)
.addField("Timezone: ", `UTC${location.timezone || "NO DATA"}`, true)
message.channel.send({ embeds: [embed]});
The || symbols is a OR operator.

Related

Discord.js - TypeError: Cannot read properties of undefined (reading 'commands')

I'm coding a Discord Bot in JavaScript, but I have this error when I launch the bot !
I don't find because I check the "application.commands" box!
Here's the full error message:
I don't know how I can resolve the problem :(
I try to invite my bot another time, but it doesn't work :(
The error message who makes problems :
node:events:491
throw er; // Unhandled 'error' event
^
TypeError: Cannot read properties of undefined (reading 'commands')
at Client.<anonymous> (/home/container/index.js:72:51)
at Client.emit (node:events:513:28)
at WebSocketManager.triggerClientReady (/home/container/node_modules/discord.js/src/client/websocket/WebSocketManager.js:385:17)
at WebSocketManager.checkShardsReady (/home/container/node_modules/discord.js/src/client/websocket/WebSocketManager.js:368:10)
at WebSocketShard.<anonymous> (/home/container/node_modules/discord.js/src/client/websocket/WebSocketManager.js:194:14)
at WebSocketShard.emit (node:events:513:28)
at WebSocketShard.checkReady (/home/container/node_modules/discord.js/src/client/websocket/WebSocketShard.js:511:12)
at WebSocketShard.onPacket (/home/container/node_modules/discord.js/src/client/websocket/WebSocketShard.js:483:16)
at WebSocketShard.onMessage (/home/container/node_modules/discord.js/src/client/websocket/WebSocketShard.js:320:10)
at WebSocket.onMessage (/home/container/node_modules/ws/lib/event-target.js:199:18)
Emitted 'error' event on Client instance at:
at emitUnhandledRejectionOrErr (node:events:394:10)
at process.processTicksAndRejections (node:internal/process/task_queues:84:21)
Node.js v18.12.0
The default code :
const { Client, GatewayIntentBits, Message, version, MessageFlags } = require("discord.js");
const { SlashCommandBuilder} = require("#discordjs/builders");
const { EmbedBuilder } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages
]
})
//const { REST, Routes } = require('discord.js');
const {clientId, skorflexID, guildId, token, hostRole, multiplayerAnnouncementRole, fortniteLogo, rebootLogo, basicFortniteImage, sept, un, quatre, trois, modoID } = require('./config.json');
const announce = new SlashCommandBuilder()
.setName("announce")
.setDescription("This command will send a embed message to announce your hosting !")
.addStringOption(option => option
.setName("version")
.setDescription("Put the version of Fortnite you want to host")
.setRequired(true))
.addStringOption(option => option
.setName("radmin_ip")
.setDescription("Put your Radmin IP here (without the 'open')")
.setRequired(true));
const clear = new SlashCommandBuilder()
.setName("clear")
.setDescription("This command will delete a number of messages in one second !")
.addIntegerOption(option => option
.setName("number")
.setDescription("Put the number of messages who will be deleted !")
.setRequired(true))
const say = new SlashCommandBuilder()
.setName("say")
.setDescription("The bot will say your message")
.addStringOption(option => option
.setName("message")
.setDescription("Type your message !")
.setRequired(true))
const thumbnail = new SlashCommandBuilder()
.setName("thumbnail")
.setDescription("The bot send you the thumbnail of a YouTube video")
.addStringOption(option => option
.setName("id")
.setDescription("You can find the ID in the link after the << watch?v= >>")
.setRequired(true))
client.on("ready", async () => {
client.guilds.cache.get("1027595307187441664").commands.create(thumbnail);
client.guilds.cache.get(guildId).commands.fetch();
client.guilds.cache.get(guildId).commands.cache.map(command => {
command.delete();
});
console.log("Le bot est lancé et prêt à l'utilisation !");
});
client.on("interactionCreate", interaction => {
if(interaction.isCommand()){
// announce ou announcement
if(interaction.commandName === "announce" || interaction.commandName === "announcement"){
let version1 = interaction.options.getString("version")
let radmin_ip1 = interaction.options.getString("radmin_ip")
let image = basicFortniteImage;
if( version1 != undefined && radmin_ip1 != undefined ){
if(version1 ==="7.30" || version1 ==="7.3" || version1 ==="7.2"|| version1 ==="7.1"|| version1 ==="7"){
image = sept;
}else if(version1 == "1.7.2"){
image = un;
}else if(version1 =="3.5"){
image = trois;
}else if(version1 =="4.5"){
image = quatre;
}
const exampleEmbed = new EmbedBuilder()
.setColor(0xFFA3F8)
.setTitle("**Multiplayer Announcement**")
.setDescription("<#"+interaction.user.id+"> is hosting rn in **"+ version1 + "**\n\n - To join, write this in the fortnite console : \n\n> `open "+ radmin_ip1 +"`\n\n To open the fortnite console you need to press the ² button or if it's doesn't work press ` ")
.setImage(image)
.setFooter({ text: 'Hosted with Reboot Launcher', iconURL: rebootLogo})
.setThumbnail(fortniteLogo)
.setTimestamp()
.setFields({name: "To join", value: 'you need to be connected on **RADMIN VPN**'})
if(interaction.member.roles.cache.some(e => e.id == hostRole)){
interaction.channel.send("<#&"+multiplayerAnnouncementRole+">")
interaction.reply({embeds: [exampleEmbed]});
}else{
interaction.reply({ content: "You don't have the Host role !", ephemeral: true });
}
}
}
if(interaction.commandName === "clear"){
var number = interaction.options.getInteger("number")
if(interaction.member.roles.cache.some(e => e.id == modoID)){
if(number >= 1 && number <= 100){
interaction.channel.bulkDelete(number);
interaction.reply({content: number + " messages has been deleted correctly !", ephemeral: true});
}else{
interaction.reply({content: "To use the clear command, your number will be over 1 and under 100 ! Please retry", ephemeral: true});
}
}
}
if(interaction.commandName === "say"){
let message2 = interaction.options.getString("message");
if(interaction.member.roles.cache.some(e => e.id == modoID)){
interaction.reply({content: "."})
interaction.deleteReply();
interaction.channel.send({content: message2})
}else if(interaction.member.roles.cache.some(i => i.id != modoID)){
interaction.reply({content: "You are not a moderator !", ephemeral: true})
}
}
if(interaction.commandName === "thumbnail"){
var ytID = interaction.options.getString("id");
interaction.reply({content: "."})
interaction.deleteReply();
interaction.channel.send({content: "https://img.youtube.com/vi/"+ ytID +"/maxresdefault.jpg"})
}
}
})
client.login(token);
it's referring to this line here:
client.guilds.cache.get("1027595307187441664").commands.create(thumbnail);
Basically client.guilds.cache.get("1027595307187441664") is undefined and did not return a result.

Cannot read property 'toDateString' of undefined

Im trying to make a discord bot that can show when a certain member joins the server, and the date of when they joined Discord. I have tried using toDateString to show thw number of days from the joining of the server and the current date. Here's the full code:
const Discord = require("discord.js");
const { MessageEmbed } = require("discord.js");
const { Color } = require("../../config.js");
module.exports = {
name: "userinfo",
aliases: ["memberinfo", "whois"],
description: "Show User Information!",
usage: "Userinfo | <Mention User>",
run: async (client, message, args) => {
//Start
let member = message.mentions.users.first() || message.author;
const statuses = {
online: "Online",
dnd: "Do Not Disturb",
idle: "Idle",
offline: "Offline/Invisible"
};
const embed = new MessageEmbed()
.setTitle(member.username + " Information!")
.setColor(Color)
.setThumbnail(member.displayAvatarURL())
.addField("Full Name", member.tag, true)
.addField("ID", `${member.id}`, true)
.addField("Status", statuses[member.presence.status], true)
.addField(
`Roles Count`,
message.guild.members.cache.get(member.id).roles.cache.size ||
"No Roles!",
true
)
.addField(`Avatar Url`, `[Link](${member.displayAvatarURL()})`, true)
.addField("Joined Server At", member.joinedAt.toDateString())
.addField("Joined Discord At", member.createdAt.toDateString())
.setFooter(`Requested by ${message.author.username}`)
.setTimestamp();
message.channel.send(embed);
//End
}
};
Instances of GuildMember do not have a createdAt property (see here). You want to access the user property of the guild member to get User.createdAt
addField("Joined Discord At", member.user.createdAt.toDateString())
member.createdAt is undefined
Must make it member.user.createdAt
.addField("Joined Discord At", member.createdAt.toDateString())
And change member var to #GuildMember
let member = message.mentions.members.first() || message.member;

im new to making discord bots with node.js, i am having trouble with an error, it says that message is not defined in line 14 and 18

const Discord = require('discord.js');
const client = new Discord.Client()
const prefix = '+';
client.once('ready' , () => {
console.log('MemeStrifer is online')
});
client.on('message', message => {
if(message.content.startsWith(prefix) ||message.author.bot) return;
const args = message.content.slice(prefix.lenght).split(/+/);
const command = args.shift().toLowerCase();
if(command === 'blackhumour'){
message.channel.send('What is the difference between a kid and a bowling ball? when you put your fingers in one it doesnt scream');
} else if (command === 'sex') {
message.channel.send('no you f***ing pervert');
}
});
client.login('***');
Sorry if I am making any stupid errors, I just started yesterday by a YouTube video.
here,try this:
client.on('message', message =>{
if(message.content.startsWith(prefix) ||message.author.bot) return;
const args = message.content.slice(prefix.lenght).split(/+/);
const command = args.shift().toLowerCase();
if(command === 'blackhumour'){
message.channel.send('What is the difference between a kid and a bowling ball? when you put your fingers in one it doesnt scream');
} else if(command === 'sex'){
message.channel.send('no you fucking pervert');
}
});

My bot says it doesnt have permissions to kick/ban

I am making a Discord bot in js. Yesterday i finished some work on the bot's ban command and it worked normally. Today I wake up, don't modify anything and when I try it again, it says that it does not have permission. Nothing was changed and noone changed the permissions of the bot, it still has administrator. The error message:
(node:2490) UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
at RequestHandler.execute (/home/runner/AUN/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async RequestHandler.push (/home/runner/AUN/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
My code is (a bit long):
const Discord = require("discord.js");
const dp = require('discord-prefix');
const lang = require('../language_manager');
const settings = require('discord-server-settings');
module.exports = (message, client) => {
if (!message.member.permissions.has("BAN_MEMBERS")) return message.reply("You do not have the permission to ban users");
if (!message.guild.me.hasPermission("BAN_MEMBERS")) return message.reply("I do not have permission to ban users");
let prefix = dp.getPrefix();
if(dp.getPrefix(message.guild.id)){
prefix = dp.getPrefix(message.guild.id);
}
var langchar = settings.getSetting('lang', message.guild.id)
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
var noerror = true;
const member = getUserFromMention(args[0]);
const reason = args[1] || lang.get('ban_no_reason', langchar);
const embed1 = new Discord.MessageEmbed()
.setAuthor('AUN', 'https://drive.google.com/uc?export=view&id=129_JKrVi3IJ6spDDciA5Y5sm4pjUF7eI')
.setTitle(lang.get('ban_title', langchar))
.setColor('#ed3f2c')
.setDescription(lang.get('ban_noone_banned', langchar))
.setTimestamp()
.setFooter('Ping: ' + client.ws.ping + ' | '+prefix+command);
const embed = new Discord.MessageEmbed()
.setTitle(lang.get('ban_you_title', langchar))
.setAuthor("AUN", "https://drive.google.com/uc?export=view&id=129_JKrVi3IJ6spDDciA5Y5sm4pjUF7eI")
.setColor(0x00AE86)
.setDescription(lang.get('ban_you_part1', langchar)+message.guild.name+lang.get('ban_you_part2', langchar)+message.member.name+lang.get('ban_you_part3', langchar)+reason)
.setFooter("Ping: "+client.ws.ping+" | AUN discord bot")
.setTimestamp();
if (!member) {
embed1.setTitle(lang.get('ban_error', langchar))
.setDescription(lang.get('ban_no_mention', langchar))
.setColor('#bd1300');
noerror = false;
}
if(noerror){
embed1.setDescription(lang.get('ban_banned_part1', langchar)+member.tag+lang.get('ban_banned_part2', langchar));
member.send(embed);
}
message.channel.send(embed1);
try{
return message.guild.member(member).ban();
}catch (e){
return;
}
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('<#') && mention.endsWith('>')) {
mention = mention.slice(2, -1);
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
return client.users.cache.get(mention);
}
}
}
Please if you have any idea what is going on, tell me
You should check if you can actually ban the member.
You can check this with
GuildMember#manageable

Discord.js Per Server Prefix Error "TypeError: Cannot read property 'ID' of null"

Hi i was making a per server prefix thing for my discord.js v12 bot using quick.db everything was going well but when using a command it throws this error
C:\Users\Aoshey\Desktop\Taco Bot V2\tacobot.js:50
let prefix = db.get(`prefix_${message.guild.ID}`);
^
TypeError: Cannot read property 'ID' of null
i don't quite understand since i'm new to coding so sorry if it was something stupid
the main bot file's code:
client.on('message', message => {
let prefix = db.get(`prefix_${message.guild.ID}`);
if(prefix === null) prefix = default_prefix;
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().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 === 'dm') {
return message.reply('I can\'t execute that command inside DMs!');
}
if (command.args && !args.length) {
let reply = `${message.author}, wrong usage`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command! Please tell Aro#1221 about this.');
}
});
i noticed that the error only occurs when its used on only 1 command meanwhile other commands work well (also yes i'm using the command in a guild)
the code for the command which causes the error i think?
const fsn = require("fs-nextra");
const colors = require("colors");
module.exports = {
name: 'deleteorder',
description: 'deleting/denying an order.',
args: 'true',
usage: '<order id> <reason>',
aliases: ['od', 'delorder', 'do'],
execute(message, args) {
if (message.member.roles.cache.find(r => r.id === '745410836901789749')) {
let ticketID = args[0];
let reason = args[1];
fsn.readJSON("./orders.json").then((orderDB) => {
const order = orderDB[ticketID];
if(order === undefined) {
message.reply(`Couldn't find order \`${args[0]}\` Try again.`);
return;
}
if(reason === "") {
reason = "None Provided";
}
delete orderDB[ticketID];
fsn.writeJSON("./orders.json", orderDB, {
replacer: null,
spaces: 4
});
message.reply(`You deleted order \`${args[0]}\` with reason \`${args[1]}\``)
// Sends a message to the customer.
let customer = message.guild.members.cache.find(m => m.id === order.userID)
//message.users.cache.get(order.userID).send(`Sorry, but your order was cancelled by **${message.author.username}** due to the following reason: \`${reason}\`.`);
customer.send(`Sorry, but your order was cancelled by **${message.author.username}** due to the following reason: \`${reason}\`.`)
// Logs in console.
console.log(colors.red(`${message.author.username} deleted order ${order.orderID}.`));
});
} else {
message.reply("You aren't an employee.");
console.log(colors.red(`${message.author.username} did not have access to the delorder command.`));
}
}
}
Its just id in lowercase letters. ID in uppercase letters doesn't exist.
let prefix = db.get(`prefix_${message.guild.id}`);

Resources