JavaScript Discord bot encounters an issue: .sendMessage function is not recognized

Currently, I am developing a bot and testing its messaging functionality using .sendMessage method.

(I prefer the bot not to send messages upon receiving any input, hence avoiding the use of:

bot.on("message", function(message) {});

However, I am encountering an error stating that .sendMessage is not recognized as a function.

const Discord = require('discord.js');
const getJSON = require('get-json');
const BotToken = "token";
const bot = new Discord.Client();

bot.login(BotToken); 

bot.sendMessage('serverid', 'test');

I have already executed npm install discord.js assuming it was included in the discord.js package.

.setStreaming results in a similar error. Although I followed their tutorial at where they recommend using npm install --save --msvs_version=2015 discord.js, I still face this issue.

Does anyone know what could be causing this problem?

Answer №1

Attempting to dispatch a communication to the server directly is not allowed; messages can only be directed to channels. Additionally, the use of sendMessage method is no longer supported and it is recommended to utilize the send method instead.

Answer №2

I've figured it out! Check out this snippet of my code below. I plan to use this code for sending messages periodically, so the clip includes some additional details beyond your initial query. However, you should still find it helpful in understanding what you need for your own code. The key component that enables this functionality is the initial section.

var NotifyChannel;
bot.on('ready', () => {
  NotifyChannel = bot.channels.find("id", "347400244461568011");
});

var sched = later.parse.text('every 2 mins on the 30th sec');

function logTest() {
  NotifyChannel.send("This is a two minute test.");
  console.log(`Please only do this once, please. ${retrieveDate()}` + 
  `${retrieveTimestamp()}`);
  return;
}

var timer = later.setInterval(function(){ logTest(); }, sched)

Edit: tweaking the formatting

Answer №3

In order to utilize the .setPresence method along with a streaming URL, it must be integrated within the ready function.

If you're looking for a simple code snippet to help clarify the usage of these functions, here is an example that you can easily duplicate and apply:

const Discord = require('discord.js');
const bot = new Discord.Client();

bot.on('message', message => {
    const prefix = '!';
    if (message.content === prefix + 'ping') {
      message.channel.send('pong!');
    }
});

bot.on('ready', () => {
    console.log('Connecting...');
    bot.user.setStatus('available'); // Can also be set to 'idle', 'dnd', or 'invisible'
    bot.user.setPresence({
        game: {
            name: 'Your Message Here', // Displayed under 'Now Playing:'
            type: 0,
            url: 'Your Streaming URL' // Substituted with your Twitch channel URL
        }
    });
});

bot.login('YOUR_TOKEN_GOES_HERE');

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

Experiencing excessive CPU utilization from Node.js while executing the vue-cli-service serve command

Whenever I run my npm script that uses vue-cli-service serve, the CPU usage by Node exceeds 100%. How can I troubleshoot this problem? I am using a Mac and have installed Node through nvm. My Node version is 10.16 and my npm version is 6.9. ...

Tips for overriding ng-disable in AngularJSUnleashing the

This is a comment box using AngularJS: <tr> <td colspan="5"><br/>Comments* <div><textarea class="form-control" rows="3" cols="60" ng-model="final_data.drc_scope" placeholder="Add comments here" ng-disabled="is_team==0 || isDis ...

Learn how to generate a dynamic pie chart in PHP that can adjust its sections based on the user's input, giving you a fully customizable data visualization tool

let userData = [ { label: "History", data: 90 }, { label: "Science", data: 85 }, { label: "Art", data: 95 }, ]; I have written this javascript code to represent the user's data, but I want it to be more flexible an ...

Implement a delay for a specific function and try again if the delay expires

In my TypeScript code, I am utilizing two fetch calls - one to retrieve an access token and the other to make the actual API call. I am looking to implement a 1-second timeout for the second API call. In the event of a timeout, a retry should be attempted ...

Failure [ERR_STREAM_WRITE_AFTER_END]: writing past the endpoint [npm-request using socket.io]

My server has a socket server running, and on my laptop, I have a socket.io-client service. When both are turned on, they establish a connection. When other users request information from my server, the server sends that request to my laptop via a socket. ...

Having difficulty installing and executing nodemon npm in Node.js

I am encountering an issue while trying to run my Node.js project, and the error message is as follows: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="780a1d0b0c1e0d141416171c1d120b384956485648">[email protected]&l ...

Aligning Font Awesome icons inside md-buttonsFinding the perfect alignment for

I am attempting to center font awesome icons within a button so that they align perfectly with the text on a toolbar. Below is the code snippet I am working with: <div ng-app="app"> <md-toolbar> <div class="md-toolbar-tools" md-tall ...

Creating a seamless navigation experience using Material UI's react Button and react-router-dom Link

Is there a way to have the Material UI react Button component behave like a Link component from react-router-dom while preserving its original style? Essentially, how can I change the route on click? import Button from '@material-ui/core/Button' ...

Display every even number within the keys of objects that have values ending with an odd number

I need a way to print all even values that are paired with odd values in the object keys, but my code only works for arr1, arr3, and arr5. Can someone help me adjust the 'let oddArr' method (maybe using a loop) so that it will work for any array ...

Converting Vue HTML to PDF without relying on html2canvas functionality

My current challenge involves creating a PDF file from either HTML or Vue component. I have experimented with various libraries such as jsPDF, html2pdf, and vue-html2pdf, but it seems like they all rely on html2canvas, causing the UI to freeze for a few ...

Managing errors and error codes in React/Redux applications

I am currently exploring the most effective approach for managing errors, particularly when deciding between error codes and an errors object in response from my API. As I dive into building a multi-part form using react, each time a user progresses to th ...

Using webpack to bundle node_modules into your application

I am facing an issue while trying to load some modules like: moment echarts In my package.json file, I have the following versions specified: "echarts": "^3.1.10" "moment": "^2.14.1" However, I am encountering the errors below: VM2282:1 Uncaught Ref ...

Utilizing React SSR to dynamically import components based on API response

I am currently working on a SSR React app using the razzle tool, with the server running on the express framework. My goal is to dynamically load React components based on the value included in an API response. My folder structure looks like this: views ...

Utilizing a callback function to update the value of a variable that is declared outside of the getJSON function

I'm currently facing an issue with this function I have. function customCheck(username){ var result = "normal"; $.getJSON('https://api.twitch.tv/kraken/streams/' + username, function(data){ if(data.stream == null) re ...

Verify that the lower limit is not higher than the upper limit set in an Angular application

In my Angular application, I have two input fields for minimum and maximum values. I want to display an error message if the user enters a minimum value greater than the maximum value provided, or the default maximum value if none is provided. The form is ...

Converting an ISO date to a standard JS date: The straightforward approach

Can anyone help me with converting an ISO date to a Standard JS Date format? The specific format I need is: Mon `Jul 20 2020 14:29:52 GMT-0500 (Central Daylight Time)` I would appreciate any guidance on the best approach for achieving this. Thank you in a ...

JavaScript treats string as a primitive value

When it comes to JavaScript, a String is considered a primitive value. However, it can also be treated as a String object. In programming terms, a primitive value refers to a value assigned directly to a variable. This raises the question: var d = "foo"; ...

The form created using jQuery is not submitting correctly because the PHP $_FILES array is empty

Creating an HTML form dynamically in jQuery and submitting the form data via Ajax to 'add_sw.php' for processing is my current challenge. However, I have encountered an issue where the PHP script cannot access the PHP $_FILES variable as it turn ...

Having issues running `npm install` with the `--save-dev` option on a Windows 8 system

Encountering an issue on my Windows 8 while trying to install an npm package npm install grunt-contrib-uglify --save-dev Interestingly, if I run the command without --save-dev, it works just fine. npm install grunt-contrib-uglify --save-dev However, wh ...

trouble with fetching data

Within my Backbone view, I have the following code snippet: var BookView = Backbone.View.extend({ initialize: function() { this.render(); }, render: function() { this.model.fetch({ success : function(model, resp, opt) { alert(this.$el. ...