How to Send Messages to a Specific Channel Using discord.js

After scouring the internet, I have yet to find a solution to my Discord bot issue. My bot is built with Typescript and all of its commands are neatly organized in their own folder, each in a separate file.

I've come across suggestions to use

client.channels.get(`channelID`).send(`Text`)

However, this leads to errors such as Object is possibly 'undefined'. and

Property 'send' does not exist on type 'Channel'.

My goal is to make the bot send a message to every text channel from a specified list whenever someone triggers a reboot command. It started as a playful prank, but now it's causing some inconvenience with the constant requests for reboots. The bot goes offline for 3 minutes during the reboot, and I don't want it to be rendered unusable due to spamming.

In my attempt to achieve this, I'm using

client.channels.get(channels.channelnames[5]).send("This is a message.")

https://i.sstatic.net/nycQu.png

https://i.sstatic.net/YoFEM.png

Answer №1

Solution:

if(msgObject.member.guild.channels.find(channel => channel.name === channels.channelnames[5]) as Discord.TextChannel) {
    var txtchannel = msgObject.member.guild.channels.find(channel => channel.name === channels.channelnames[5]) as Discord.TextChannel
    txtchannel.send("This is a message in a channel. Don't know why you're reading this.")
}

It seems I was on the right path. Just needed to add as Discord.TextChannel, which is probably what Cynthia meant by casting the variable as a TextChannel.

This piece of code is functional. A big thank you to everyone for your assistance!

Answer №2

After reviewing the documentation at https://discord.js.org/#/docs/main/stable/class/Collection, it appears that there is no mention of a get method.

Consider using

client.channels[channels.channelnames[5]].send("Here's a message.")

In simpler terms, replace .get with square brackets in your code.

UPDATE: Upon further reflection, it seems like the issue may be related to type casting. Try converting the Channel into a TextChannel if you are certain it is a text channel.

Answer №3

If your channels are text channels, this code should work fine.

client.on('ready',(e)=>{


    let channel_ids = ['123','456','789'];

    // Loop through the list of channel ids.
    for(let i=0, l=channel_ids.length; i<l; i++){
        let channel_id = channel_ids[i];

        let this_channel = client.channels.get( channel_id );

        // Check if channel exists and is a text channel, then send a message
        if(this_channel && ['dm', 'group', 'text'].indexOf( this_channel.type ) != -1){
            this_channel.send('a cool message')
            .then(message => console.log(`Sent message: ${message.content}`))
            .catch(console.error);
        }

    }

});

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

Tips for clearing out text in a <p> tag with javascript when it exceeds a specific length of 100 characters

Is there a way to automatically truncate text to (...) when it exceeds 100 characters inside a paragraph with the class .class? For instance, if I have a long paragraph like this: <div class='classname'> <p>Lorem ipsum dolor sit ame ...

What is the process for converting strings or text to EBCDIC using JavaScript?

In the midst of developing a website, I am working on a feature that allows users to input a minimum of 256 characters/strings (with code verification), choose between ASCII or EBCDIC conversion, and view the converted text string displayed on the page bas ...

Converting the current date in Postgres to a date format in Typescript

My situation involves a specific date 2022-08-04 08:16:32.716904 // without timezone. This was created using the now() function in SQL as a timestamp with (6) milliseconds precision (i.e DateTime @db.Timestamp(6) with primsa). I am wondering how I can gen ...

Is it possible to execute this animation with a single click for repetitive playback?

CODEPEN const btt = document.querySelector('.btt'); btt.addEventListener('click', function(){ this.classList.toggle('anime'); }); Is there a way to achieve the desired effect with just one click? ...

Auto scrolling in React Native Flatlist

I'm working on a FlatList component that I want to automatically scroll. Below is the current code: <FlatList contentContainerStyle={{}} data={banners} renderItem={(item) => ( <Image source={{ uri: item.item ...

The inner radius remains constant in the Chart.js Doughnut Chart

I've been trying to create a half doughnut chart using Chart.js, similar to the image linked below. However, I'm having trouble adjusting the thickness of the pie chart. Despite using the innerRadius property, it's not producing the desired ...

Retrieve data from a collection by utilizing ng-repeat

I need help implementing a select interface on my website. Users will be able to choose a site, and then the associated country where the site is available will be displayed. To do this, I have a list of sites with information like their names and the co ...

Saucelabs is having issues with executing mocha tests within the expected time limits

Recently, I've been diving into the world of mocha and Saucelabs, but it seems like I might be making a beginner's mistake. Everything runs smoothly when I test in my browser or through a manual session on Saucelabs. However, when I try to run t ...

Implementing bidirectional data binding with Semantic UI's search dropdown feature in Vue.js

I'm currently facing an issue with the Semantic-UI searchable dropdown and Vuejs data binding. It seems like only one changed option is being model-bound, no matter which dropdown option I select. Here's a snippet of my code. I attempted to use ...

"Enhance your website with dynamic link styling by using jQuery to add

Hi there, I'm currently working on an off canvas menu and I'm trying to figure out how to add a class that will highlight the active menu item. However, the jquery code I have doesn't seem to be doing the trick. I've scoured the web for ...

The React Component is caught in a loop of continuous re-rendering and reloading

Just starting out with React and tackling my first project. Running into a bit of trouble here, so I'm sharing my code for some insight. When users input their search term and hit 'search,' they are redirected from another page to this one. ...

Encountered an issue while trying to use Figma's spellchecker extension

Despite following the instructions in the readme carefully, I am facing difficulties running the Figma spellchecker extension. Executing npm run build goes smoothly. But when I try to run npm run spellcheck, I encounter an error message in the console: co ...

Assigning values to an object in Angular: A step-by-step guide

I have a RestApi that sends me the response in Json Format with an address object containing fields such as address1, address2, city, etc. To handle this, I defined an interface within my application to outline these objects: export interface ISurveyRespo ...

What is the best way to obtain the current cursor location in draft.js?

As part of my draftjs project, I'm working on implementing a feature that allows users to easily insert links. One approach I've taken is creating a popup that appears when the shortcut cmk + k is pressed. To enhance the user experience, I am cu ...

Select and emphasize specific sections of text

Can I create an input element that looks like the one in my screenshot? I want to be able to change the value with JavaScript and highlight text by wrapping it with '*' and giving it a different color. Thank you for any assistance. ...

Modify a section of text in a standalone file that is referenced in another file using JavaScript

I have a configuration file with unique URLs for different environments. I am utilizing the object key to reference the base URL within the object. const configDev = { API: { url: 'http://api.domain.com', }, }; I am looking to a ...

What is the best way to move a card when it appears on hover?

I recently implemented a map with interactive cards that appear when hovering over hotspots, all thanks to the amazing support I received on this platform. However, I have encountered a problem where the card appears to the right of the hotspot and gets cu ...

ng-repeat not functioning properly with data defined in XMLHttpRequest

I have a problem with my HTML and AngularJS code. Initially, I defined the list in my controller which worked fine: <li ng-repeat="a in idmasVesselstableList"><a>{{a.table_name}}</a></li> And here is how I set up the controller: ...

JavaScript: Locate web addresses within a block of text and convert them into clickable hyper

How can we convert the following PHP code to JavaScript in order to replace URL links inside text blobs with HTML links? A jsfiddle has been initiated. <?php // The Regular Expression filter $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a- ...

What is causing the ng-show function to malfunction after building with phonegap?

My current javascript framework for my PhoneGap app is the Ionic Framework. I have a specific item on one of my pages that I want to make expandable and collapsible by clicking an anchor on the page. Here is what the code looks like: In the HTML file: & ...