Sending message to specific channel, not working - node.js

Having trouble sending a bot message on a specific channel. I very simply want to have the bot send a message to #general when it activates, to let everyone know it's working again.
In the bot.on function, I've tried the classic client.channels.get().send(), but the error messages I'm getting show that it thinks client is undefined. (It says "cannot read property 'channels' of undefined")
bot.on('ready', client => {
console.log("MACsim online")
client.channels.get('#general').send("#here");
})
The bot crashes immediately, saying: Cannot read property 'channels' of undefined

The ready event doesn't pass any client parameter.
To get a channel by name use collection.find():
client.channels.find(channel => channel.name == "channel name here");
To get a channel by ID you can simply do collection.get("ID") because the channels are mapped by their IDs.
client.channels.get("channel_id");
Here is an example I made for you:
const Discord = require("discord.js");
const Client = new Discord.Client();
Client.on("ready", () => {
let Channel = Client.channels.find(channel => channel.name == "my_channel");
Channel.send("The bot is ready!");
});
Client.login("TOKEN");

You need to get the guild / server by ID, and then the channel by ID, so your code will be something like :
const discordjs = require("discord.js");
const client = new discordjs.Client();
bot.on('ready', client => {
console.log("MACsim online")
client.guilds.get("1836402401348").channels.get('199993777289').send("#here");
})
Edit : added client call

The ready event does not pass a parameter. To gain the bot's client, simply use the variable that you assigned when you created the client.
From your code, it looks like the bot variable, where you did const bot = new Discord.Client();.
From there, using the bot (which is the bot's client), you can access the channels property!

Related

I just made a welcome and goodbye message for my discord.js bot but it doesn't send the messages to the required channels

Here's my code,
Welcome message:
client.on('guildMemberAdd', async member => {
if(member.guild.id !== "737222740305641472")return;
const channel = guild.channels.cache.get("750952211659620413")
if (!channel) return;
let data = await canva.welcome(member, { link: "https://imgur.com/a/BPTpkDT", blur: false })
const attachment = new Discord.MessageAttachment(
data,
"welcome-image.png"
);
channel.send(
"Welcome message here",
attachment
);
});
And my goodbye message's code:
client.on('guildMemberRemove',(member) => {
if(member.guild.id !== "737222740305641472")return;
guild.channels.cache.get('781737515421138984').send(`Goodbye message here`);
});
I'd like to make it clear that I dont get any error's in my console and that I've given the bot all the perms it needs to send messages.
Also, I've already declared my guild before, so that isn't supposed to be the problem.
Can anyone tell what I'm doin wrong?
As directed by this comment, it is appearent that you have not enabled privilliged intents for your application. For your application to listen to events such as guildMemberAdd and guildMemberRemove you would have to enable to Members Intent from the Discord Developer Portal. Here is what you would be looking for:
This can be found under
Your Application > Bot > ( Scroll down ) Privilleged Gateway Intents > Server Members Intent ( toggleable ).
This was a change introduced in the Discord API version v8 for the intents to be mandatorily enabled for such API requests.

How edit messages in Discord.js V12 using message ID

There is the way to edit a message on DiscordJS
To do this, we just need to pass it to the function, the client variable.
exports.myNewFunction = async function myNewTestFunction(client)
First, in order to edit a message using the Discord.JS API, we will need to find the server's GuildID.
const guild = client.guilds.cache.get(`Your Guild ID`);
Now, we're going to need to find the channel the message is on. For this, we will use the channel ID
const channel = guild.channels.cache.find(c => c.id === `Your message Channel` && c.type === 'text');
Finally, let's go to the editing part of the message. For this, we will only need to provide the ID of the message that you want to be edited.
channel.messages.fetch(`Your Message ID`).then(message => {
message.edit("New message Text");
}).catch(err => {
console.error(err);
});

UnhandledPromiseRejectionWarning when trying to send message

I am trying to send a message through discord.js and I am getting the following error:
(node:10328) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined
Here is my code:
// Init
const Discord = require("discord.js");
const bot = new Discord.Client();
const channel = bot.users.cache.get('4257');
// Vars
// Code
bot.on("ready", () => {
console.log("The Bot is ready!");
channel.send("Test");
});
// Login
bot.login(" "); // I will hide this.
What is wrong? Is it the id on the channel variable? I just put in the id of my bot since I didn't know what to put in it.
At first I gave it all the permissions under "Text Permissions", but I also tried giving him admin privs. It still didn't work. What am I doing wrong?
The problem is this line:
const channel = bot.users.cache.get('4257');
Here's what's wrong with it:
const channel = bot.users.cache // this returns a collection of users, you want channels.
.get('4257'); // this is a user discriminator, you want a channel ID
Here's how to fix it:
const id = <ID of channel you want to send the message to>
const channel = bot.channels.cache.get(id)
// ...
channel.send('Test')
Here's an example:
const channel = bot.channels.cache.get('699220239698886679')
channel.send('This is the #general channel in my personal Discord')
How to get a Channel ID
ChannelManager Docs
const channel is empty here. You need to make sure value should be assigned in it.
channel.send("Test");
If its not mendatory that value will come then use try-catch.
try {
channel.send("Test");
} catch(e) {
console.log(e)
}
Please support with vote or answered if it helps, thanks.

I keep getting an error in discord.js "discord is not defined" OR I get no response from the bot. Not even an error/

I am coding a discord bot using discord.js.
FOR SOME REASON it says Discord not defined error or the bot has no response. Please could you help me? I have never had this error before. Here's the code.
I have include this command in the same main.js file:
if(cmd === `${prefix}help`){
reporthelp = "Report a user. Requires a channel named `reports`to work!";
kickhelp = "Kick a user from the server. Requires a channel named `incidents` to work; you must have the manage messages permission.";
banhelp = "Ban a user from the server. Requires a channel named `incidents` to qork; toy need the BAN MEMBERS permission to use this command!";
warnhelp = "**COMMAND COMING SOON!**";
requiredperms = "**Embed Links, channel named `incidents`; channel named `reports`; channel named `suggestions`; Kick Members, Ban Members, Manage Roles, Manage Members.**"
helpEmbed = new Discord.RichEmbed()
.setDescription(" 💬 **__Help Is Here!__** 💬")
.setColor("#936285")
.addField("**/report #user <reason>**", reporthelp)
.addField("**(COMING SOON)** /warn #user <reason>", warnhelp)
.addField("**/kick #user <reason>**", kickhelp)
.addField("**/ban #user <reason>**", banhelp)
.addField("**/mytag**", "Shows you **your** discoord username#discrim and your user ID. Requires Embed Links permission.")
.addField("**/invite**", "Get a linkto incite meto our server, and an invite link to my suppoer server")
.addField("**/owner**", "see who currently owns the bot")
.addField("**/git**", "**SOURCE CODE AVAILIBLE SOON**")
.addField("**/token**", "View the bot's super secret bot token!")
.addField("**/serverinfo**", "displays some basic server information!")
.addField("**/botinfo**", "displays basic bot information!")
.addField("**/ping**", "Get the bot to respond with `pong` ")
.addField("**/hosting**", "Bot finds a good website for bot/web hosting")
.addField("**/quotes**", "bot responds with some lovely quotes!")
.addField("**__Required Permissions__**", requiredperms)
// .addField("**COMING SOON!**/suggest <suggestion>", "suggest something. Requires channel named `suggestions`")
.setTimestamp()
.setFooter("Use /invite to invite me to your server!")
return message.channel.send({embed: helpEmbed});
}
This is how I've defined everything:
const botconfig = require("./botconfig.json");
const tokenfile = require("./token.json");
const Discord = require("discord.js");
const bot = new Discord.Client({disableEveryone: true});
bot.on("ready", async () => {
console.log(`${bot.user.username} is active in ${bot.guilds.size} servers!`);
bot.user.setActivity("rewriteing main.js...", {type: "WATCHING"});
//bot.user.setGame("Lookin' out for ya!");
});
bot.on("message", async message => {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
const prefix = botconfig.prefix;
const messageArray = message.content.split(" ");
const cmd = messageArray[0];
const args = messageArray.slice(1);
const bicon = bot.user.displayAvatarURL;
I either get no response/error, or I get the error discord is not defined.
I'm also very new here, sorry If I didn't ask a question clearly...
The code is correct, but I had redfined discord in a different part of the file....
my advice would be to alays read the code over again!

How to send message using Bale bot into group?

How to send message using Bale bot into group?
for send message using BaleBot, we need to have id of User/Group and have an accessHash. But I can`t get accessHash for send mesage to Group.
It's not too hard, if you have id and access_hash of the group(or channel). you should just make the Peer and after that put it in send_message function.
look at this code. It push a "Hello" to a specified channel after getting start by client.
Note: Remember group and channel are similar.
const SDK = require("balebot");
const BaleBot = SDK.BaleBot;
const TextMessage = SDK.TextMessage;
const Group = SDK.Group;
let bot = new BaleBot('token');
bot.hears(["/start"], (message, responder) => {
console.log(responder._peer)
bot.send(new TextMessage("hello"),responder.peer).then((res) => {
console.log(res)
}).catch((err) => {
console.log(err)
});
});

Resources