TypeError: Cannot read property 'current' of undefined
I just made a weather command for discord.js, it works fine but if I run p!weather 'not a city'
it'll give me an error, I can't find any mistakes in my code, does anyone knows how to fix it. I am using slappy/discord.js. This is my code:
const Discord = require("discord.js");
const weather = require("weather-js");
module.exports = class WeatherCommand extends BaseCommand {
constructor() {
super('weather', 'fun', []);
}
async run(client, message, args) {
if (!message.guild) return message.channel.send(`Try again if you are in a server channel!`);
const city = message.content.split(" ").slice(1).join(" ")
if (!city) return message.channel.send("I need a city to check :wink:")
weather.find({search: city, degreeType: 'C'}, function(err, result) {
if (err) {
message.channel.send("**${arg}** Isnt inside my query, please check again")
console.log(err.stack)
return;
}
let url;
if (result[0].current.skytext === "Mostly Sunny") url = "https://openclipart.org/image/2400px/svg_to_png/3367/ivak-Decorative-Sun.png"
else if (result[0].current.skytext === "Mostly Cloudy" || result[0].current.skytext === "Cloudy") url = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Weather-heavy-overcast.svg/200px-Weather-heavy-overcast.svg.png"
else if (result[0].current.skytext === "Partly Cloudy") url = "";
var embed = new Discord.MessageEmbed()
.setTitle(`Forecast for ${result[0].location.name}`, message.author.displayAvatarURL)
.addField("Temperature", `**${result[0].current.temperature}ºC**`, true)
.addField("Humidity", `**${result[0].current.humidity}%**`, true)
.addField("Wind Speed", `**${result[0].current.windspeed.replace("mph", "ms/h")}**`, true)
.addField("Feels Like", `**${result[0].current.feelslike}ºC**`, true)
.addField("Status", `**${result[0].current.skytext}**`, true)
.setTimestamp()
.setThumbnail(result[0].current.imageUrl)
.setColor('YELLOW')
.setFooter(`Requested by: ${message.author.tag}`)
message.channel.send({ embed: embed })
})};
}
thanks
1 answer
-
answered 2021-02-24 09:30
Exstare
The bot can't read the property of
current
. You usedcurrent
afterresults[0]
, which means that that's undefined. I suggest loggingresults
to see what's in it to know how to get your desired data.
See also questions close to this topic
-
How to create an order from a cart in Mongoose and delete cart
I am trying to: a) Create an order from my current cart b) Populate the response of the order with the selected object attributes in the "select" c) Finally, I would like to delete the cart.
I have tried the below but here are my problems:
- the result response does not come back populated even if the
prevProductsQuantity
constant is indeed populated - I created the function cartClear to receive the cart id and delete the document from the model but it is not working.
- I am able to create many "same" orders so I think i need to manage with a conditiona but not sure where.
The response I am looking for:
{ "success": true, "data": { "_id": "607ed5c425ae063f7469a807", "userId": "6071aed0ed7ec9344cf9616c", "productsQuantity": [ { "_id": "607f2507994d5e4bf4d91879", "productId": { "productRef": "463b8bb7-6cf6-4a97-a665-ab5730b69ba2", "productName": "table", "brand": "boehm llc", "price": 713, "__v": 0, "createdAt": "2021-04-09T18:31:43.430Z", "updatedAt": "2021-04-09T18:31:43.430Z" }, "quantity": 2, "updatedAt": "2021-04-21T15:12:51.894Z", "createdAt": "2021-04-21T15:12:51.894Z" } ], "__v": 0 }
++ THE DELETION OF THE CART ++
The current response I am getting:
{ "success": true, "data": { "state": "pending-payment", "_id": "6080507a0c758608d0dc585c", "userId": "6071aed0ed7ec9344cf9616c", "totalPrice": 1426, "productsQuantity": [ { "_id": "607f2507994d5e4bf4d91879", "productId": "60709d8f24a9615d9cff2b69", "quantity": 2, "updatedAt": "2021-04-21T15:12:51.894Z", "createdAt": "2021-04-21T15:12:51.894Z" } ], "createdAt": "2021-04-21T16:19:06.056Z", "updatedAt": "2021-04-21T16:19:06.056Z", "__v": 0 }
** AND THE CART IS NOT DELETING **
this is the code I typed for these purposes.
Any guidance is super appreciated
router.post('/', [isAuthenticated], async (req, res, next) => { try { const cart = await CartModel.findOne({ userId: req.user }).populate({ path: 'productsQuantity.productId', select: { price: 1, brand: 1, productName: 1, productRef: 1, pictures: 1 } }); const prevProductsQuantity = cart .get('productsQuantity') .map((el) => el.toObject()); const totalPriceByProduct = prevProductsQuantity.map( (product) => product.productId.price * product.quantity ); const totalPrice = totalPriceByProduct.reduce(function (a, b) { return a + b; }); const result = await OrderModel.create({ userId: req.user, totalPrice: totalPrice, state: 'pending-payment', productsQuantity: prevProductsQuantity }); const cartClear = (id) => CartModel.deleteOne({ _id: id._id }); res.status(200).json({ success: true, data: result }); cartClear(`${cart._id.toString()}`); } catch (error) { next(error); } });
- the result response does not come back populated even if the
-
How to fetch SQL data using api and use that data in react-native-svg charts? I am having an API that I want to use to fetch data and display
I am fetching some data using an api. Inside that api there are SQL queries that are executed. I have api that will be used to fetch data or execute these queries. I want to know how can I replace my chart's static data with dynamic data that will be fetched from api.
Here is my
TabDashboardDetail.js
where I am fetching title for all charts based on api data:import React from 'react'; import DefaultScrollView from '../components/default/DefaultScrollView'; import ChartView from '../components/default/ChartView'; import CogniAreaChart from '../components/CogniAreaChart'; import { areaChartData } from '../chartData'; const TabDashboardDetail = ({ navigation, route }) => { const tabsConfig = route.params.tabsConfig; return ( <DefaultScrollView> {tabsConfig.components.map((comp, index) => { return ( <ChartView key={index} title={comp.name}> <CogniAreaChart areaChartData={areaChartData} height={200} /> </ChartView> ); })} </DefaultScrollView> ); }; export default TabDashboardDetail;
Here is my
CogniAreaChart.js
which is chart file that is currently being rendered:/* eslint-disable react-native/no-inline-styles */ import React from 'react'; import { View } from 'react-native'; import { AreaChart, YAxis, XAxis } from 'react-native-svg-charts'; import * as shape from 'd3-shape'; const CogniAreaChart = ({ areaChartData, visibility, ...props }) => { const xAxis = areaChartData.message.map((item) => item[Object.keys(item)[0]]); const areaChartY1 = areaChartData.message.map( (item) => item[Object.keys(item)[1]], ); return ( <View style={{ height: props.height, flexDirection: 'row', }}> <YAxis data={areaChartY1} contentInset={{ marginBottom: 20 }} svg={{ fill: 'grey', fontSize: 12, }} /> <View style={{ flex: 1 }}> <AreaChart style={{ flex: 1 }} data={areaChartY1} contentInset={{ top: 20, bottom: 20 }} curve={shape.curveNatural} svg={{ fill: 'rgba(134, 65, 244, 0.8)' }} /> <XAxis style={{ height: 20 }} data={areaChartY1} formatLabel={(value, index) => xAxis[index]} contentInset={{ left: 30, right: 30 }} svg={{ fill: 'grey', fontSize: 12, rotation: 35, originY: 5, y: 15, }} /> </View> </View> ); }; export default CogniAreaChart;
Here is areachartData that is currently being used in
CogniAreaChart.js
:export const areaChartData = { message: [ { year: '2018', quantity: 241.01956823922, sales: 74834.12976954, }, { year: '2019', quantity: 288.57247706422, sales: 80022.3050176429, }, ], status: 'success', };
I have the API that I will replace with the example if anyone suggests.
-
Sort,Filter,search in Javascript array
Given values for acctData and balances below, write a function that returns only an array of account numbers, and accepts the following optional parameters:
- user - sortBy (accepts "acctNum" or "balance") - sortDirection (accepts "asc" or "desc"; default to asc)
Execute your function and output the results as an array in console log for the following scenarios:
a) filtered by Bob b) filtered by Charlie c) sorted by acctNum d) filtered by Alice; sorted by balance ascending
acctData = [ { "acctNum": "AAA - 1234", "user": "Alice" }, { "acctNum": "AAA - 5231", "user": "Bob" }, { "acctNum": "AAA - 9921", "user": "Alice" }, { "acctNum": "AAA - 8191", "user": "Alice" } ]; balance = { "AAA - 1234": 4593.22, "AAA - 9921": 0, "AAA - 5231": 232142.5, "AAA - 8191": 4344 };
-
Permission error with PHP 8 and Session Handler
Dears, I`m refracting old php code 4 to php 8, but I'm having some errors on Session Control. I implementing a SessionHandlerInterface, but I still having error when execute session write
Warning: file_put_contents(../sessions/sess_fc6a0b26f218654ca0f45493861fdf58): failed to open stream: Arquivo ou diretório inexistente in /home/pedro/htdocs/ypanel/session.controller.php on line 36
Warning: session_write_close(): Failed to write session data using user defined save handler. (session.save_path: ../sessions) in Unknown on line 0I'm using Lampp with Mysql on Debian.
Here my class
<?php header('Content-Type: application/json'); //========================================================================================= ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session')); //========================================================================================= session_save_path("../sessions"); //========================================================================================= error_reporting(2); //========================================================================================= class MySessionHandler implements SessionHandlerInterface { private $savePath; public function open($savePath, $sessionName) { // printf(file_exists($savePath)); // printf(is_dir($this->savePath).' dir'); $this->savePath = $savePath; if (!is_dir($this->savePath)) { chmod($this->savePath,0777); mkdir($this->savePath, 0777,true); } else printf('diretorio ja existe'); return true; } public function close() { return true; } public function read($id) { return (string)@file_get_contents("$this->savePath/sess_$id"); } public function write($id, $data) { return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true; } public function destroy($id) { $file = "$this->savePath/sess_$id"; if (file_exists($file)) { unlink($file); } return true; } public function gc($maxlifetime) { foreach (glob("$this->savePath/sess_*") as $file) { if (filemtime($file) + $maxlifetime < time() && file_exists($file)) { unlink($file); } } return true; } } $handler = new MySessionHandler(); session_set_save_handler($handler, true); session_start(); ?>
-
How to use EC2 Instance Profile in Nodejs application to access AWS Services?
I have a Nodejs application which runs on an EC2.
The EC2 has an instance profile attached to it.
How can I use the instance profile inside my Nodejs code so that my Nodejs code can access AWS Services like S3 bucket etc without using AWS Access Keys?
I found this link that's close to this topic but could not see any sample code provided there:
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-node-credentials-iam.html
-
How do I store an array in a PSQL, where it is passed as a parameter $1 to the db query
I am passing a one-dimensional array of three strings to the function, it looks like this going in:
[ '#masprofundo', '#massensual', '#eclectic' ]
The data column is declared thus:
tags TEXT []
This is my function:
const query = `INSERT INTO posts (posted_at, message, link, tags) VALUES (TO_TIMESTAMP($1, 'DD/MM/YYYY HH24:MI'), $2, $3, ARRAY [$4]) RETURNING tags;`; const params = [timestamp, message, link, tags];
Now, postgres believes I want to insert an array containing one item, which is a string of all the values in my tags array. It looks like this:
{ tags: [ '{"#masprofundo","#massensual","#eclectic"}' ] }
What I want to know is, how do I prevent this behaviour, where postGres adds an unnecessary extra layer of quotation marks and parentheses? For further clarification; this is what the row looks like in my terminal.
{"{\"#masprofundo\",\"#massensual\",\"#eclectic\"}"}
I have looked at the docs, and tried a dozen variations on ARRAY[$4]. From what I can see, the docs do not elaborate on inserting arrays as variables. Is there some destructuring that needs to happen? The arrays I pass will be of varying size, and sometimes empty.
Any help is much appreciated.
-
Do something according to the emoji you reacted with Discord.js
I'm trying to create a calendar and depending on the emoji which one we react something happens but I don't find the good function . I try to find in another post but nothing helped me.
Thanks for your help.
This is the code :
if (message.content.startsWith('!agenda')){ var embed = new Discord.MessageEmbed() .setColor('YELLOW') .setTitle('Matter') .addFields( {name : 'Math :', value: '📏'}, ) var Msg = await message.channel.send(embed); Msg.react("📏"); var emoji = await Msg.awaitReactions; if (emoji === '📏'){ message.channel.send('test') } } })
-
discord.py check every ID's last message date from a JSON file and print ID if older than a week
How can I check every last message's date with belongs their IDs from the JSON file and if the last message date is older than a week then print the ID?
So I don't want to print every user ID just if their last message date is older than a week.
with open("users.json") as file: data = json.load(file) user_ids = list(data.keys()) last_message_dates = [uid["lmessage"] for uid in data.values()] #credit: @Jacob Lee print(user_ids + last_message_dates) #output: ['531590632706020132', '834243753941240705', '2021-04-21 16:59:10','2021-04-21 16:43:32'] date_minusweek = datetime.now(timezone('CET')) - timedelta(days=7) minusweek = date_minusweek.strftime("%Y-%m-%d %H:%M:%S") print(minusweek) #output: 2021-04-14 17:18:10 #Here I want to do a check for every user ID's and their own last message date's and if some of the ID's last message date is older than a week, then print the ID"
-
Getting the ID of the channel a user is currently in with discord.py
I'm struggling to get the ID (or name) of the voice channel a user is currently in on discord. I want to be able to move the user to a specific channel, but then move the user back to the channel it was in after a time interval.
So basically a "time out" method.
The code I have, but the channelID line doesn't work.
from discord.ext import commands import discord import os import time bot = commands.Bot(command_prefix = '$') @bot.command(pass_context=True) async def goout(ctx, member: discord.Member): channelID = member.voice_channel.id channel = discord.utils.get(ctx.guild.voice_channels, name='Go out') channel2 = discord.utils.get(ctx.guild.voice_channels, id=channelID) while True: await member.edit(voice_channel=channel) time.sleep(3) await member.edit(voice_channel=channel2) return False
-
How to use test input file in Xcode C++ by using command line arguments?
I am trying to use sample.in.txt as a test input in Xcode C++. Thus, I go to edit schema and add arguments like this.
However, when I run the project, it is still getting the input from the user and do nothing about the input file I typed on the arguments. I print the argv, then it all prints correctly.
This is my main function
int main(int argc, char** argv) { int T; cin >> T; for(int i = 0; i < T; i++){ int size, shift; cin >> size >> shift; Array test(size); for(int j = 0; j < size; j++){ int x; cin >> x; test.add(j, x); } test.shift(shift); } return 0; }
-
why do i have ping command eror in discord.py?
so i have problem with discord.py commands , i want to make ping command which will response with bot ping, i have code like this but it doesn't work, can someone help my?
@bot.command() async def ping(ctx): await ctx.send(f"Pong :ping_pong:! Bot latency: **{round(bot.latency * 1000)}ms**"
i tryed to write code like this:
@client.command() async def ping(ctx): await ctx.send(f"Pong :ping_pong:! Bot latency: **{round(bot.latency * 1000)}ms**"
but it still don't works
-
Discord.py AFK Command Rewrite
Here is my afk command:
@client.event async def on_message(message): if message.mentions results = collection.find({"member": message.author.id}) for result in results: collection.delete_one(result) if message.content == result: await message.channel.send(f"This person is currently AFK. \nFor: {reason}") await client.process_commands(message)
Error:
File "main.py", line 124 if message.mentions ^ SyntaxError: invalid syntax
I was a little confused on why. any ideas?
-
random number generator not working properly
I am developing a discord bot, this is a random number generator command and when i use it it returns: random number from 5 to 10: 35 after a couple fo tries it returns fully rounded random numbers ignoring the parameters.
module.exports = { name: 'random', description: 'returns an aleatory number', execute(message){ let arguments = message.content.split(' ') let from = arguments[1] let to = arguments[2] let result = Math.floor(Math.random() * (to - from + 1) ) + from; message.channel.send(`random number from ${from} to ${to}:\n${result}`) } }
-
My discord bot doesn't always trigger on reaction event
I got a problem with my ticket bot. I have a ticket bot that gives you 5 options, but the bot doesn't really work. Sometimes it does make a ticket on reaction sometimes it just adds the reaction but doesn't make a ticket. I have 2 bots with this issue now so I'm guess I'm just doing it wrong.
Also I'm getting no errors in my console, and I never have the issue my self but other people sometimes do!
bot.on('messageReactionAdd', (reaction, user) => { if (user.bot) { return; } reaction.users.remove(user.id) bot.users.fetch(user.id).then((user) => { let channelId = ""; let query = `SELECT * FROM ticketMessage`; db.get(query, (err, row) => { let ticketMessage = row.MessageId; if (reaction.emoji.name == "🦖") { const startTicket = async (name) => { reaction.message.channel.guild.channels.create(user.username + name, { type: 'text' }) .then(channel => { let category = ""; category = reaction.message.channel.guild.channels.cache.find(c => c.id == settings["Categories"].ticketcategory && c.type == "category"); if (!category) { user.send("Couldn't Process your ticket since there is no category setup for it!") } else { channel.setParent(category.id).then(() => { channelId = channel.id sendQuestions() }) } }).catch(console.error); } startTicket(" Dino Lines"); const sendQuestions = async () => { ticketChannel = bot.channels.cache.get(channelId) await ticketChannel.updateOverwrite(user, { VIEW_CHANNEL: true }); const filter = m => m.author.id === user.id && m.channel === ticketChannel; embed2 = new Discord.MessageEmbed(); embed2 .setDescription("What are the names of the dino's you would like to buy, Example => (T-rex, Bronto)?") .setFooter(settings["Embeds"].displayname, settings["Embeds"].image) .setColor(settings["Embeds"].color) .setTimestamp() ticketChannel.send(embed2); ticketChannel.awaitMessages(filter, { max: 1, time: 120000 }) .then(collected => { let dinoName = collected.first().content embed3 = new Discord.MessageEmbed(); embed3 .setDescription("How many dino's would you like to buy, Example => (Dino1: 5, Dino2: 3)?") .setFooter(settings["Embeds"].displayname, settings["Embeds"].image) .setColor(settings["Embeds"].color) .setTimestamp() ticketChannel.send(embed3); ticketChannel.awaitMessages(filter, { max: 1, time: 120000 }) .then(collected => { let ammount = collected.first().content embed4 = new Discord.MessageEmbed(); embed4 .setDescription("What kind of currency would you like to use, Example => (Money, Items)?") .setFooter(settings["Embeds"].displayname, settings["Embeds"].image) .setColor(settings["Embeds"].color) .setTimestamp() ticketChannel.send(embed4); ticketChannel.awaitMessages(filter, { max: 1, time: 120000 }) .then(collected => { let currencyKind = collected.first().content embed5 = new Discord.MessageEmbed(); embed5 .setDescription("Do you want to submit this ticket? => (Yes, No)") .setFooter(settings["Embeds"].displayname, settings["Embeds"].image) .setColor(settings["Embeds"].color) .setTimestamp() ticketChannel.send(embed5); ticketChannel.awaitMessages(filter, { max: 1, time: 120000 }) .then(collected => { let yn = collected.first().content if (yn.toLowerCase() == "yes") { embed1 = new Discord.MessageEmbed ticketChannel.bulkDelete(8, true) embed1 .setTitle(user.username + "'s Ticket") .addFields({ name: "Buying Dino Lines", value: "\u200b \n **Dino Names:** " + dinoName + "\n **Dino Count:** " + ammount + "\n **Payment Methode:** " + currencyKind, inline: true }, ) .setFooter(settings["Embeds"].displayname, settings["Embeds"].image) .setColor(settings["Embeds"].color) .setTimestamp() ticketChannel.send(embed1) } else { ticketChannel.send("Okay ticket canceled!"); } }) }) }) }) }