I created a custom discord.js-commando command to announce all the channels that my bot is currently active in, however, encountered an unexpected error

const Commando = require('discord.js-commando');

module.exports = class AnnounceCommand extends Commando.Command {
    constructor(client) {
        super(client, {
            name: 'announce',
            aliases: ['an'],
            group: 'util',
            memberName: 'announce',
            description: 'Announce something to the topmost channel in all servers the bot is in.',
            details: 'Only the bot owner may use this command.',
            examples: ['announce Hello, world!'],
            args: [
                {
                    key: 'msg',
                    label: 'message',
                    prompt: 'What should be announced?',
                    type: 'string'
                }
            ],
            guarded: true,
        });
    }

    hasPermission(msg) {
        return this.client.isOwner(msg.author);
    }

    async run(msg, args) {
        try {
            const guildsArray = Array.from(this.client.guilds.cache.values());
            guildsArray.forEach((guild) => {
                let channels = guild.channels.cache.filter((channel) => {
                    return channel.type === 'text' && channel.permissionsFor(guild.me).has(['VIEW_CHANNEL', 'SEND_MESSAGES']);
                });
                if (channels.size > 0) {
                    channels.sort((a, b) => a.calculatedPosition - b.calculatedPosition)
                      .first().send(args.msg).catch(e => console.error(e));
                }
            });
        } catch (error) {
            console.log(error);
        }
    }
};

but in console I got:

TypeError: this.client.guilds.array is not a function at AnnounceCommand.run (/home/runner/emperor-2/commands/util/announce.js:30:22)

Answer №1

The GuildManager Class within the property guilds does not have an array() method. To iterate through all guilds, you should use

this.client.guilds.cache.forEach()
.

For more information, I recommend checking out the documentation: GuildManager Class

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

Can someone help me identify the issue with my JavaScript code?

Recently, I attempted to transfer data from JavaScript to HTML using Angular. Here is the code snippet: phonecatControllers.controller('start', ['$scope', function($scope){ $scope.lloadd=true; console.log('data - '+$ ...

Issue encountered when exporting with node and mongoose

After creating some schema and exporting the model, here is the code: var mongoose = require('mongoose'); var specSchema = new mongoose.Schema({ name: String, description:String }); var qualSchema = new mongoose.Schema({ name: Str ...

Why does this asynchronous function initially return nothing, only to suddenly return all results on subsequent tries?

My current task involves inserting data into my database within a map loop. To ensure that the loop completes before proceeding, I am utilizing an async function to store all results in the variable "practicasAgregadas." This is how I invoke the function: ...

Tap and hold with Zepto

I've been on the hunt for a Zepto plugin that can handle a longClick event. While Zepto already supports longTap, which is perfect for mobile devices, I need something specifically for desktop browsers when a user clicks and holds. It's also impo ...

Prisma encountered an error with the database string: Invalid MongoDB connection string

I'm encountering an issue with my MongoDB data provider, as I am informed that my connection string is invalid. The specific error message states: The provided database string is invalid. MongoDB connection string error: Missing delimiting slash betw ...

This route does not allow the use of the POST method. Only the GET and HEAD methods are supported. This limitation is specific to Laravel

I am encountering an issue while attempting to submit an image via Ajax, receiving the following error message: The POST method is not supported for this route. Supported methods: GET, HEAD. Here is the Javascript code: $("form[name='submitProfi ...

Configuring Access-Control-Allow-Origin does not function properly in AJAX/Node.js interactions

I'm constantly encountering the same issue repeatedly: XMLHttpRequest cannot load http://localhost:3000/form. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefor ...

Utilizing Moment.js: Transforming 12-hour format to a Date object

Is there a way to convert a 12-hour string into a 24-hour Date object? day.from = day.from || moment("6:00", ["h:mm"]).format("HH:mm"); Unfortunately, I am encountering the following error: angular.js:11706 Error: [ngModel:datefmt] Expected `6:00` to be ...

At what stage in the code does the loop conclude?

While researching Selenium Webdriver framework best practices on GitHub, I came across the following code snippet: async function waitForVisible(driver, locator, retries = 3) { try { const element = await driver.findElement(locator); ...

Breaking down classes and cross-referencing them with a different DIV using JQuery

Trying to create a variable named relatedBoxes that will store checkboxes sharing similar classes as the box div. To do this, I am splitting up the classes and storing them in a variable called splitClass. Now, all that's left is to find out if any o ...

Dealing with parameters in nested routes within express.js: Best practices and tips

I've been exploring the possibilities of using nested routes for their easy way of passing variables. router.post('/postlinkone', function(req, res, next){ //define a few variables (x,y) //render or redirect to close this route router. ...

What is the method for formatting within the <textarea> element?

While working on developing a comment system, I recently made the discovery that text areas cannot be formatted to retain paragraphs, line breaks, etc. This was particularly noticeable when comparing sites like StackOverflow, which uses a text editor inste ...

reloading a webpage while keeping the current tab's URL selected

I want to incorporate a feature I saw on the jQuery website at http://jqueryui.com/support/. When a specific tab is pressed, its contents should open. However, when the page is refreshed, the same tab should remain open. I'm trying to implement this i ...

Uncovering the origin of a problematic included file

When using Sencha Touch, it is common to encounter issues related to missing files. In most cases, simply including the file resolves the issue. However, there are instances where the problem lies in a faulty include, requiring you to locate where the file ...

Difficulties arise when attempting to install nodejs on linux using the npm install nodejs command

While attempting to execute... npm install nodejs I encounter the subsequent issue: npm WARN optional Skipping failed optional dependency /chokidar/fsevents: npm WARN notsup Not compatible with your operating system or architecture: [email prot ...

SDK for generating templates with JavaScript/jQuery

I am in the process of developing an SDK in JavaScript/jQuery that can generate templates based on user input, such as profile templates and dialog templates. These templates require data from an AJAX call to be created. User input should include certain ...

Using VueJS to switch classes on multiple cards

There is a page with multiple cards, each containing its own set of status radio buttons: ok, missing, error. The goal is to be able to change the status of individual cards without affecting others. A method was created to update the class on the @change ...

Tips for aligning text in MUI Breadcrumbs

I am currently utilizing MUI Breadcrumb within my code and I am seeking a solution to center the content within the Breadcrumb. Below is the code snippet that I have attempted: https://i.stack.imgur.com/7zb1H.png <BreadcrumbStyle style={{marginTop:30}} ...

Generate listview items containing anchor tags automatically

I am currently developing a web application using Jquery Mobile. After retrieving data from a webservice function, I am utilizing an ajax call to display this data on my webpage. $('[data-role=page]').on('pageshow', function () { var u ...

Is it true that by utilizing Vue's v-for, every line of HTML code becomes a

I'm struggling to utilize v-for in order to create multiple div elements, but no matter how I attempt it (even trying to iterate over a list), the v-for doesn't seem to function properly and always turns the line into a comment when executed. No ...