Struggling to Create a Survey with Included Message: Error - Unable to Initialize MessageEmbed

I'm attempting to create a poll feature for my discord bot that displays both the poll question and results as an embedded message. While I've managed to get the poll information in plain text format, I'm encountering an error when trying to generate embeds.

TypeError: MessageEmbed is not a constructor

The following is the code snippet I'm currently working with:

const { SlashCommandBuilder } = require('discord.js');
const { MessageEmbed } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('poll')
    .setDescription('Create a poll')
    .addStringOption(option =>
      option
        .setName('question')
        .setDescription('The poll question')
        .setRequired(true)
    )
    .addStringOption(option =>
      option
        .setName('options')
        .setDescription('The poll options, separated by commas')
        .setRequired(true)
    )
    .addIntegerOption(option =>
      option
        .setName('duration')
        .setDescription('The duration of the poll in seconds')
        .setRequired(true)
    ),
  run: async ({ interaction, client }) => {
    const question = interaction.options.getString('question');
    const options = interaction.options.getString('options').split(',');
    const duration = interaction.options.getInteger('duration');

    const pollEmbed = new MessageEmbed()
      .setColor('#0099ff')
      .setTitle('Poll')
      .setDescription(question);

    options.forEach((option, index) => {
      pollEmbed.addField(`Option ${index + 1}`, option);
    });

    await interaction.reply({ embeds: [pollEmbed] });

    setTimeout(async () => {
      const channel = client.channels.cache.get(interaction.channelId);
      const sentMessages = await channel.messages.fetch({ limit: 1 });
      const sentMessage = sentMessages.first();

      sentMessage.reactions.cache.forEach(async reaction => {
        const optionIndex = options.findIndex(option => option === reaction.emoji.name);
        if (optionIndex !== -1) {
          const users = await reaction.users.fetch();
          const nonBotUsers = users.filter(user => !user.bot);
          const userTags = nonBotUsers.map(user => user.tag).join(', ');
          channel.send(`Option ${optionIndex + 1} received ${nonBotUsers.size} vote(s) from: ${userTags}`);
        }
      });
    }, duration * 1000);
  },
};

I'm relatively new to coding, so any assistance in rectifying my current code and providing explanations would be greatly appreciated! Feeling frustrated right now but hopeful for a solution soon!

I've experimented with updating all my packages and exploring different variations of 'MessageEmbed', 'Discord.MessageEmbed', etc.

Answer №1

For those utilizing a more recent release of discord.js, it is imperative to utilize EmbedBuilder in lieu of MessageEmbed

const { EmbedBuilder } = require('discord.js');
const pollEmbed = new EmbedBuilder()
      .setColor('#0099ff')
      .setTitle('Poll')
      .setDescription(question);

options.forEach((option, index) => {
    pollEmbed.addField({ name: `Option ${index + 1}`, value: option});
});

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

What is the process for importing DataTables using npm?

My attempt to import "datatables.net-select" using the usual method doesn't seem to be working. After checking the website, I found that the correct way to do it is: var $ = require( 'jquery' ); var dt = require( 'datatable ...

How to identify the character encoding in a node.js request

Did you know that Facebook chat has a feature where it automatically detects and displays messages in a left-to-right format when typing in English, but switches to right-to-left style when adding right-to-left characters? I'm curious about how Faceb ...

What is the process for attaching an event handler to an element that is displayed after a button click?

I need some assistance with my JavaScript code. I have a page with two links, and when the second link is clicked, certain fields are displayed. I am trying to write an onkeyup() event handler for one of these fields, but seem to be missing something. Here ...

Invoking PHP code from within Javascript will output the function as a direct string

I seem to be going in circles and missing something silly... My setup involves using CodeIgniter on the server-side and Bootstrap on the client, but that's not really the issue here... I am attempting to access a PHP value within a JavaScript functi ...

What is preventing me from successfully retrieving data at times when using curl_setopt and jQuery Ajax?

In my quest to fetch data from another server, I am using the curl_setopt PHP function along with Ajax. The function I have created seems to be working fine, but sometimes when I refresh the page and the internet connection is slow, I don't receive an ...

What is the best way to compare two 2D arrays in JavaScript?

Having an issue comparing two 2D arrays in javascript, looking to output "true" if the arrays are the same. This is the code I experimented with: ` function check(){ if (data.every() === solution.every()){ alert("example"); } else { ...

Reload the text content of a locally hosted webpage within an iframe at regular intervals

I have set up a simple webpage on my local machine to showcase the contents of some text files on a dedicated monitor. However, I am facing an issue where refreshing the entire webpage causes flickering. My goal is to only refresh the iframes and reload t ...

Accessing data attributes using AngularJS

Trying to extract the data attribute from the following code: <button ng-click="EditPlayer(name, position, number, age)" id="btnEdit" class="btn btn-successes" data-playerid="{{player.id}}">Save</button> Within my angular controller: $scope. ...

Difficulty encountered while managing dropdown functionality in Protractor using TypeScript

I'm encountering some difficulties when it comes to selecting a dropdown in Protractor. Here's the structure of my DOM: https://i.stack.imgur.com/qK8sT.png This is the XPath I'm using to select the dropdown with the value "Yes": //label[ ...

Discord between Bootstrap tabs and C3 charts: A Compatibility Str

On my website, I have implemented Bootstrap navigation tabs that each contain a chart. The issue I am facing is that when I navigate to the home page, the chart in the active tab displays perfectly fine. However, for the other tabs, the charts overlap with ...

Is this the proper formatting for JavaScript code?

Having trouble changing the CSS of elements that match b-video > p with an embed element using JQuery. Here's my code: $('div.b-video > p').has('embed').attr('style','display:block;'); Can anyone help me ...

The ASPX validation will not be able to access the .js file

I am facing an issue with client-side validation using JavaScript (.js). Despite linking the path in the head section, the ASP file doesn't seem to reach the JavaScript file. <head runat="server"> <meta http-equiv="Content-Type" content="tex ...

When sending a request from Vue.js using Axios to PHP, the issue arises that the .value property is

There is a chat box with bb smileys underneath. Clicking on the smileys adds them to the text in the input box. However, when using axios to post, the array is empty. Manually entering the smiley bbcode works fine. <input id="txtName" @keyup.enter="ad ...

What is the best way to extract the variable inside a script tag as a JSON value?

Hey, I need help figuring out how to convert a JavaScript variable into a JSON value using Python with the help of libraries like BeautifulSoup and requests. I attempted to solve this issue by following a similar topic on Stack Overflow, but unfortunately ...

Is there a way to restrict the number of times I can utilize slideToggle function?

When I continuously click on a div element in an HTML website that triggers the .slideToggle() method, it will keep opening and closing for as many times as I click. The problem arises when I stop clicking, as the <div> continues to toggle open and c ...

Issues encountered with AngularJS directive binding inner content not functioning as expected

I am currently developing a feature toggle directive, which requires a check to be performed in order to display content if the check is successful. I want the directive to replace itself with its content without creating a new child scope (so I'm try ...

Is it possible to transfer a Mongo connection to JQuery code using socket.io?

I'm currently working on setting up a global MongoDB connection in my node.js web app. Here is what I have so far: var MongoClient = require('mongodb').MongoClient; var mconn = null; MongoClient.connect('mongodb://myHost:27017/users&a ...

How can the outer function be connected to the resolve method of $routeProvider?

Here is a functional code snippet: $routeProvider.when('/clients', { templateUrl:'/views/clients.html', controller:'clientsController', resolve: { rights: function ( ...

Utilize Ajax.ActionLink on a DIV by incorporating data from the Model

Although there are similar questions on this topic already, they do not address the specific issue of using values from the model as arguments for the controller. Make DIV containing AJAX ActionLink clickable Div as Ajax.ActionLink Take a look at the fo ...

Executing a jQuery script on various elements of identical types containing different content (sizes)

I am currently working on a jQuery script that will center my images based on the text block next to them. Since I am using foundation 5, I have to use a jQuery script to override the CSS instead of using vertical-align: middle. The script looks like thi ...