I embarked on a project to create a discord bot using discordjs

Recently, I embarked on a project to create a Discord bot using DiscordJS. My goal was to fetch some data from the Steam API and then embed it within my bot. However, upon running the code, I encountered an issue where the embedded fields appeared empty. It seems that the problem arises because the request takes time for the data to arrive, causing the strings to remain empty when the code moves on.

The particular error message I received in the terminal is as follows:

RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values must be non-empty strings.

const gtaUrl = 'https://api.steampowered.com/ISteamUserStats/GetNumberOfCurrentPlayers/v1/?key=KEY&format=json&appid=271590';
let gtaData = '';
request(gtaUrl, function(err, res, body) {
    if (!err && res.statusCode < 400) {
        gtaData += body;
    }
});

const exampleEmbed = new MessageEmbed()
    .setColor('#0099ff')
    .setTitle('Showing concurrent player numbers for some games')
    .setDescription('the game')
    .setThumbnail('https://i.imgur.com/FNviTdG.jpeg')
    .addFields(
        { name: 'tf2 ', value: gtaData },
    )
    .addField('Inline field title', 'Some value here', true)
    .setImage('https://i.imgur.com/AfFp7pu.png')
    .setTimestamp();

message.channel.send({ embeds: [exampleEmbed] });

As I delve into this intricate world of JavaScript, I am still grappling with some concepts, especially since I am utilizing Express for the request part of my project. Despite the challenges, I am determined to troubleshoot the issue at hand and enhance my bot's functionality.

Answer №1

Simply move your code within the callback function of the request

For instance:

const gtaUrl =
  "https://api.steampowered.com/ISteamUserStats/GetNumberOfCurrentPlayers/v1/?key=KEY&format=json&appid=271590";
let gtaData = "";
request(gtaUrl, function (err, res, body) {
  if (!err && res.statusCode < 400) {
    gtaData += body;

    const exampleEmbed = new MessageEmbed()
      .setColor("#0099ff")
      .setTitle("Showing concurrent player numbers for some games")
      .setDescription("the game")
      .setThumbnail("https://i.imgur.com/FNviTdG.jpeg")
      .addFields({ name: "tf2 ", value: gtaData })
      .addField("Inline field title", "Some value here", true)
      .setImage("https://i.imgur.com/AfFp7pu.png")
      .setTimestamp();
  }
});

An alternative approach is to use Promises and Fetch, or a library like Axios

Here's an Axios example:

const gtaUrl =
    "https://api.steampowered.com/ISteamUserStats/GetNumberOfCurrentPlayers/v1/?key=KEY&format=json&appid=271590";
  
const response = await axios.get(gtaUrl);
gtaData = JSON.stringify(response.data);

const exampleEmbed = new MessageEmbed()
    .setColor("#0099ff")
    .setTitle("Showing concurrent player numbers for some games")
    .setDescription("the game")
    .setThumbnail("https://i.imgur.com/FNviTdG.jpeg")
    .addFields({ name: "tf2 ", value: gtaData })
    .addField("Inline field title", "Some value here", true)
    .setImage("https://i.imgur.com/AfFp7pu.png")
    .setTimestamp();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When clicking on the dropdown items of another button, the class of the child element in the Bootstrap button dropdown is being removed

Check out the JSFiddle for this code snippet. I'm attempting to implement Bootstrap's drop-down menu using list items instead of options. When a list item is selected, the data should be retrieved and displayed as an active selection within a bu ...

Angular refreshes a promise that already exists

I have a unique situation where my service returns a promise to the controller: // .... within the service this.RefreshData = function() { this.data = $q.all( {images: ...., tags: ....}); } RefreshData (); // .... in the controller function() OnIma ...

What is the best way to enhance the SQL query limit by activating a button?

I'm new to programming, and I want to learn how to dynamically increase the limit of an SQL query when a button is clicked. Here's what I have so far: <?php $number = 5; $db->query("SELECT * FROM results LIMIT $number"); ?> & ...

Creating a dynamic directive in AngularJS: Learn how to add or remove it from the DOM based on specific conditions

Suppose I have a customized modal directive that looks like this: return { restrict: 'E', templateUrl: 'modal.html', scope: { modalContent: "&", modalOpen: "&" } } And in the HTML: <ng-modal modal-content="co ...

Adjusting Renderer Size in ThreeJS for Fullscreen Display

After creating a ThreeJS application designed for a 4:3 layout with multiple buttons and features, I decided to enable Fullscreen mode using THREEx.Fullscreen.js. Although the Fullscreen mode is functioning properly, a new issue arose - the renderer size(x ...

When I download the image/file, I am receiving encoded data

I have successfully implemented a proxy in my NestJs Application to work around the CORS restrictions. The service endpoint is - https://api.niftyuat.com/cors?cd=https://google.com By using this endpoint, I am able to retrieve the content of the Google ...

Limiting the number of input tags to a maximum of 5

I am using a jquery tags plugin and need help to restrict the number of tags to a maximum of 5 words separated by spaces. Can someone assist me with this? Below is the original code for the plugin: (function($) { var delimiter = new Array(); jQuery. ...

Identification for checkbox within an HTML container

I am looking to create a feature where clicking on the label text will toggle the checkbox on the box.html page. Within index.html, I have added an iframe that displays box.html. Index.html <html> <body> <iframe src="box.html" ...

Having difficulty with Angular's ng-options feature in a Select element

I'm currently tackling an issue with using ng-options to iterate through an array of objects and display specific properties in a select element. Upon querying the api/admin endpoint, I receive JSON data containing details of all users holding the ad ...

When trying to extend classes, an error is thrown indicating that the property 'prototype' is undefined

Encountering an issue with extending items, resulting in: Uncaught TypeError: Cannot read property 'prototype' of undefined After researching, it seems that items must be defined in a specific order. I have organized them accordingly but stil ...

Develop a new ASP.NET Core RESTful API utilizing JavaScript that handles DateTime conversion to UTC time, rather than

I am facing an issue with sending data from my React application using new Date() function in JavaScript, where the date is Sat Oct 30 2021 00:00:00 GMT+0800 (Singapore Standard Time). However, when I receive this data in my ASP.NET Core Rest Web API app ...

What is the method for determining the dimensions of the rectangle that the camera can capture at a specific location?

In my latest project, I developed a small three.js application that showcases the movement of multiple circles from the bottom to the top of the canvas: let renderer, scene, light, circles, camera; initialize(); animate(); function initialize() { re ...

Ensure that all input fields are validated simultaneously using the required attribute

I have been designing a form with various fields including text, number, and textarea. My goal is: I want to create a validation system for the form that checks all input fields with the required attribute in one single condition. For example, if the inp ...

Are tabs best displayed as an overlay?

I've been searching high and low for a tutorial on how to create an overlay with tabs similar to the Google Chrome webstore. If anyone knows of a tutorial or a combination of tutorials that can help me achieve this, please let me know! Link Any guida ...

Manage the dimensions of elements using Javascript on the client side

Here is a form I created: <form action="#" enctype="multipart/form-data" method="post" name="..." id="formPhoto" class="fmp"> <input type="file" name="pho" id="photo" class="inph" accept="image/*"> <button type="submit" id=" ...

How can ExpressJS be used to direct users to individual standalone React applications?

I've spent a lot of time scouring the internet for a solution to my problem, but it seems like maybe I'm not asking in the right way. My project involves creating a Node-Express website where ReactJS is only needed on specific pages, while the r ...

Guide to verify the user selection within a select form

Here is a form with a select field: <form method="post" name="posting_txt" onSubmit="return blank_post_check();" id="post_txt"> <select style="background: transparent; border-bottom:5px;" name="subname" class="required"> ...

Please identify the path of chromedriver for selenium-standalone

I've encountered an issue when trying to initialize the selenium-standalone server (https://www.npmjs.com/package/selenium-standalone). The error message I receive is as follows: 14:19:09 /usr/local/lib/node_modules/selenium-standalone/bin/selenium-s ...

What is the best way to transfer the userId from the browser to protractor?

Using *ngFor in my angular2 component to render users has been successful. <ul> <li *ng-for="let user of users"> <input [(ng-model)]="user.name"> <button (click)="remove(user._id)">Remove</button> ...

Switch out the Select feature for Checkboxes

Hey there! I'm currently trying to enhance the style and functionality of the Select checkboxes on my blog. However, when I change them to checkboxes, they lose their original function of searching for selected tags in each Select option. This issue i ...