Creating a bot with discord.js to dynamically edit embed messages

While using discord.js version 12+, I encountered an error when trying to edit an embed sent by the bot. The error message displayed is as follows:

Uncaught Promise Error: 
DiscordAPIError: Cannot edit a message authored by another user
    at RequestHandler.execute (c:\Users\Kazzu\Desktop\ImmortusMC\node_modules\discord.js\src\rest\RequestHandler.js:170:25)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

Here is my code for ping.js:

const { MessageEmbed } = require('discord.js')
module.exports = {
    run: async(client, message, args) => {
        const msg = new MessageEmbed()
        .setTitle("Pong!")
        .setColor(0xE67E22)
        .setTimestamp()
        .setDescription(`API:\nWeb Socket:`);
        message.channel.send(msg)
        .then(m => m.edit(`API: ${m.createdTimestamp - message.createdTimestamp}ms.\nWeb Socket: ${Math.round(client.ws.ping)}ms.`))
        message.edit(msg);
        message.delete()
    },
    aliases: [],
    description: 'Test API Latency'
}

Answer №1

The reason you are encountering the error is due to the usage of message.edit(msg); when attempting to modify the message that initiated the command.

To resolve this issue, you should update the description within the embed and then adjust the sent message with the updated embed content.

const { MessageEmbed } = require('discord.js')
module.exports = {
  run: async (client, message, args) => {
    const msg = new MessageEmbed()
      .setTitle("Pong!")
      .setColor(0xE67E22)
      .setTimestamp()
      .setDescription(`API:\nWeb Socket:`);
    message.channel.send(msg)
      .then(m => {
        msg.setDescription(`API: ${m.createdTimestamp - message.createdTimestamp}ms.\nWeb Socket: ${Math.round(client.ws.ping)}ms.`)
        m.edit(msg)
      })
    message.delete()
  },
  aliases: [],
  description: 'Checking API Latency'
}

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

Encourage users to activate the physical web feature in compatible web browsers

Is it possible to use JavaScript to encourage users to activate the physical web (and thus BlueTooth), similar to how APIs like "getUserMedia()" prompt users? UPDATE: Given that this technology is still in its early stages and not extensively supported, t ...

JSONP error: "Syntax error - token not expected"

While attempting to perform a JSONP AJAX request, an error was thrown: Uncaught SyntaxError: Unexpected token I'm puzzled about what is wrong in my code. Can someone assist? $.ajax({ url: 'http://api.server32.trustklik.com/apiv1/website/ ...

use ".otherwise" or /** with the latest version of Angular2 Router to redirect non-routes using wildcards

Can anyone provide guidance on using wild cards to route in the new Router when a non functional route is specified? Similar to the .otherwise method in Angular 1.X router or /** in previous beta router. Additionally, any example or Plunker code would be ...

The onclick function is malfunctioning when attempting to use the Windows Phone app in Visual Studio 2015

web development <div class="align_center"> <div class="btn EmployeeloginBtn" **onclick="new Employee().connect()**>CONNECT</div> </div> Employee.js: var Employee = function() { var self = this; self.connect = fu ...

Creating a Hidden Button on Your PWA: A Step-by-Step Guide

After creating a React app with Create React App, I decided to use the default PWA configuration. However, I am facing some confusion regarding how to hide the "Add to Home Screen" button. Can anyone provide some guidance on this issue? Thank you. https: ...

Disabling a chosen option within a dropdown menu

`Hello there, I am just starting out with JavaScript and jQuery. Currently, I am developing a web application for ordering food and drinks. I have a dropdown menu for selecting breakfast items and the quantity. When the "add" button is clicked, a dynamic ...

What is the procedure for re-executing the request handler in a Node.js and Express application?

Currently, my setup involves node, express, and mongojs. Here is a code snippet that exemplifies my configuration: function mongoCallback(req, res) { "use strict"; return function (err, o) { if (err) { res.send(500, err.message); } else ...

Hover and focus effects of the main navigation menu in Semantic UI CSS

I seem to be having trouble styling my navbar with semantic-ui. I want to make changes to the color and background-color on hover and when focused. However, no matter what I try, the hover effect just won't work. I was only able to achieve it using jQ ...

Creating specific CSS classes for individual slides in a basic slider framework

So, I have a rather simple slider that is created using only CSS. Each slide has unique labels for navigation buttons. The main question here is: how can I dynamically add or remove classes to specific items on the slide only when that particular slide is ...

HTML Date input field not respecting locale settings and defaults to mm/dd/yyyy format

When using an html date input in an ng-repeat scenario, I noticed that it defaults to mm/dd/yyyy even though my computer's regional settings are set to dd/mm/yyyy. <script src="//unpkg.com/angular/angular.js"></script> <body ng-app&g ...

What is the best way to compare the previous and next values in React?

When working with the code snippet below to send a list of values to another component - React.createElement("ul", null, this.state.stock.map(function (value){ return (React.createElement(Price, { price: value })) }) ) the values are then sent t ...

Rendering a custom Vue 3 component as a string and then passing it to another component as a prop

Hey there coding mates! Currently diving into Vue 3 and the composition API with setup. I've been crafting a custom "Table" component to display... well, tables. It requires a prop named "data", which is an array of objects (representing rows) conta ...

Implementing an active class in a React render method

Working with UI Kit Components <ul className='uk-nav'> {languages.map(function (lang) { return ( <li style={lang === this.state.selectedLanguage ? {color: '#d0021b'} : n ...

Issues with CSS positioning

I'm facing an issue with the jQuery drop-down bar slipping behind images on a specific page that uses jQuery innerfade. You can see the problem here: <?php include('perch/runtime.php'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML ...

What methods are available to generate dynamic shapes using HTML?

Looking to create an interactive triangle where users can move vertices or sides, updating angles in real-time. I'm struggling with how to accomplish this task. My initial attempt was to manually draw the triangle using the code below. <!DOCTYPE ht ...

Confirm the session validity before invoking the web service function from an ajax function triggered by clicking a button

I am experiencing a complex issue. On a page, users input data and then click on a button to save all the parameters into a JSON object. After saving locally, they click another button which triggers an ajax method that calls a web service method on the sa ...

Error message encountered while trying to instantiate 'FormData'

My contact form was working perfectly fine until recently when it suddenly stopped allowing me to send messages. I keep encountering this error message every time I try to submit the form: Uncaught TypeError: Failed to construct 'FormData': pa ...

Tips on implementing a function within a navigation bar from a specific context

While working with a user authenticated context, I encountered an issue with the logout function. My goal is to have a link in the navigation bar that triggers the logout function and redirects me to the home page. However, I'm receiving a Typerror: l ...

How can you prevent the 'Script not responding' error when using Reverse AJAX / Comet?

My worker thread is responsible for sending requests to the server using XMLHttpRequest. The request is directed to a php file which checks the integrity of client information. If the client requires new data, it is sent. Otherwise, the server continuously ...

Encountering a 404 error while trying to refresh the page in a React App hosted on Her

After deploying a React App on Heroku, I encountered a frustrating issue: every time a page is refreshed, a 404 error appears, such as: Cannot GET /create In my search for a solution, I came across a related issue: Question about 404 with React Router ...