I'm trying to send a message to a specific channel in a Discord server using discord.js, but when I try to find the channel it returns undefined.
I have tried using client.channels.get('ID').send("message") and client.channels.find('name', 'bot') but both return undefined.
const duckHuntChannel = client.channels.get('ID').send("I'm a duck");
// Make some ducks
function sendDuck() {
if (huntStatus === true) {
duckHuntChannel.send("ducc")
setTimeout(sendDuck, Math.floor(Math.random() * 21) + 10);
} else {
console.log("I was gonna duck it up but I'm disabled :(");
}
}
I expected the output to simply send a message to the channel. Where did I get it wrong?
client.channels.get('ID') will return a Channel. Not to be confused with Guildchannel
Depending on which event you are, try this instead
message.guild.channels.get('ID')
Related
I try to do a anti link bot discord that only who have the VIEW_AUDIT_LOG permission can send link this is my code :
client.on("messageCreate", message => {
const { member } = message;
let blacklisted = ['http://', 'www.', 'https://'];
let foundInText = false;
if(!member.permissions.has(Permissions.FLAGS.VIEW_AUDIT_LOG)) {
for (var i in blacklisted) {
if (message.content.toLowerCase().includes(blacklisted[i].toLowerCase())) foundInText = true;
}
if (foundInText) {
const logembed = new MessageEmbed()
.setColor("DARK_AQUA")
.addField(' with message :', ` ${message.content} `, true)
if(!message.member.roles.cache.has("929434049011941386")) {
message.guild.channels.cache.get('941704496185221221').send({ content: `<#${message.author.id}> tried to send links in <#${message.channel.id}>`, embeds: [logembed] });;
message.delete();
message.channel.send("No links here, " + `${message.author}`);
}
}
}
});
but it give this error when he delete a message with link :
if(!member.permissions.has(Permissions.FLAGS.VIEW_AUDIT_LOG)) {
^
TypeError: Cannot read properties of null (reading 'permissions')
ok so here's my guess....you're hitting this event handler twice or more times...the first time is the message the user typed. you will get their member info, if you console.log(message.member). The second time through, you'll be getting another event, which is the message(s) you send as a handler.
So the easy solution is to add something like this at or near the top of this event handler:
if (message.author.bot) return;
this basically tests to see if it's a bot or not that's calling your event. It's also good hygiene to ensure you're not accepting/reacting to other bots, which could result in spam you likely don't want.
client.on("message", message =>{
if(message.channeltype = 'dm')
if (message.content === "confess")
message.channel.send("OOOOOOoooooo A SECRET??!?!?! WHAT IS IT?!??!")
message.channel.awaitMessages("response", message =>{
C = message.content
message.reply("Um.... theres two servers that this bot works on. 1: Loves in the snow or 2:🌙Moomins and Shep's Therapy Service🌙. Pick a number to send it to one of them")
client.on("message", message => { //////// SWITCH THIS LINE OUT FOR THE THING THAT WAITS FOR NEW MESSAGES
if (message.content === "2")
WDI = message.author
WDID = message.author.id
message.channel.get(WDIC2).send("Ok ok so who did it is" + WDI + "and their id is" + WDID)
message.channel.get(CC2).send(C)
if (message.content === "1")
WDI = message.author
WDID = message.author.id
message.channel.get(WDIC1).send("Ok ok so who did it is" + WDI + "and their id is" + WDID)
message.channel.get(CC1).send(C)
})
})})
Why does my bot not reply to my message?
I first put in confess then it would say the message but it doesnt detect that I continue and reply to that. WHat do I do?
Okay first off, try to be a lot more specific when asking questions there is a stackoverflow guide on how you should ask them effectively. Right now you are being unclear and I'm going to have to assume some stuff. Also, include a stack trace whenever possible, which there should have been as you provide some invalid properties, if you don't have one please include that there is not a stack trace in the question.
There is a lot of things wrong with this code. First off, the reason your bot isn't responding to you at all is because message.channeltype is not a property. Use message.channel.type instead. There is also something wrong with your message.channel.awaitMessages(). You are passing in a "response" string as a parameter, where there should be a filter. Since you don't need a filter since it is a dm channel you can just pass it in as null message.channel.awaitMessages(null, msg => { });. And awaitMessages is not the right call here. Await messages takes in messages in a certain time period, then resolving a promise with all of the collected messages. You should be using a discord.js collector. You should also not be using client.on("message") here. I'm assuming that you want to wait for messages in any channel after somebody "shared their secret". You can do that with a collector. If you want to collect messages all over the bot, or in just one discord server channel (using the filter which can be found on the docs) you can use a collector. This will wait for, in a number of milliseconds, for any event and filter out event triggers that aren't allowed. And when it gets it, it will run a lambda. Like this:
const filter = m => m.channel === message.channel && m.author = message.author); // The filter that will sort out the messages
const collector = message.channel.createMessageCollector(filter, { time: 30000 }); // creates a collector that will wait for 30 seconds
collector.on('collect', m => { // When somebody sends a message
// ...
if (message.content === '2') {
// ...
} else if (message.content === '1') {
// ...
} else {
message.reply('you need to say either 1 or 2. Please try again.');
return;
}
collector.stop(); // Makes sure that the collector no longer will receive anymore messages.
});
Final code (fill in the gaps I'm not going to code it all for you)
client.on("message", message => {
if(message.channel.type = 'dm')
if (message.content === "confess")
const filter = m => m.channel === message.channel && m.author = message.author; // The filter that will sort out the messages
const collector = message.channel.createMessageCollector(filter, {time: 30000})
collector.on('collect', message => {
const otherCollector = message.channel.createMessageCollector(filter, { time: 30000})
otherCollector.on('collect', message => {
if (message.content === '2') {
// ...
} else if (message.content === '1') {
// ...
} else {
message.reply('you need to say either 1 or 2. Please try again.');
return;
}
collector.stop(); // Makes sure that the collector no longer will receive anymore messages.
})
})
})
Also, before asking on any forum or discord server, always look up the documentation. It helps out 99% of cases, unless the docs is absolutely garbage.
Please read the docs. I'd say that the Discord.JS docs are a pretty handy reference.
For the first part, message.channeltype is not a real property, and do not use =. That is for setting variables, use == or === instead (What is the difference?). You can use message.channel.type or you can use instanceof as followed: message.channel instanceof Discord.DMChannel. Replace Discord with whatever your Discord.JS import variable is called.
Your ifs are missing some {}, they should be used as followed.:
if(message.channel instanceof Discord.DMChannel) {
//If the channel IS a DMChannel
} else return;
FYI, if you're planning to make multiple commands, I'd use a switch, and a way to convert message.content to arguments (string array).
message.channel.get is not a thing, use client.channels.cache.get. The variables C, and WDI / WDID need to have var before them.
Then you need to add a filter plus maximum messages, time limit, and minimum messages for your awaitMessages function. Plus you need then and catch, so now your code might look like this
if(message.channel instanceof Discord.DMChannel) {
if (message.content === "confess") {
message.channel.send("OOOOOOoooooo A SECRET??!?!?! WHAT IS IT?!??!")
message.reply("Um.... theres two servers that this bot works on. 1: Loves in the snow or 2:🌙Moomins and Shep's Therapy Service🌙. Pick a number to send it to one of them")
const filter = m => m.author == message.author;
message.channel.awaitMessages(filter, {/* whatever your parameters/limits are */})
.then(col => {
if (col.content === "2") {
/** Add in code */
} else if (col.content === "1") {
/** Add in code */
}
})
.catch(col => {/** Whatever you want to do if times up. */})
}
}
You may want to tweak the filter on this.
const prefixtest = ">>"
msg = message.content.toLowerCase();
if(msg.startsWith(prefixtest + "test")) {
message.delete();
setTimeout(function() {
if{message.channel.author.id == "240254129333731328"}{ //this is the bots id
message.delete();
}, 3000);
}
Sorry if my english is bad. But I can't solve this problem, i'm trying to find it on internet but nothing. How can I delete other bot messages by using their Bot ID?
There is an issue in your code, you are trying to get .author property on a Channel instead of a Message.
So you have to modify your if statement as following :
if (message.author.id === "240254129333731328")
Also, you can delay the deletion of a Message by adding .delete() method first parameter an object with a .timeout property in it that will represent the delay in milliseconds before the message being deleted. (See docs)
message.delete({ timeout: 3000 });
So you can modify your code this way :
if(msg.startsWith(prefixtest + "test")) {
if (message.author.id === "240254129333731328") {
message.delete({ timeout: 3000 });
}
}
I've got this so far:
function dailylot() {
let channel = message.guild.channels.find(channel => channel.name === "general69420")
if (!channel) {
return;
}
channel.send(".")
return;
}
function settimer() {
setTimeout(() => {
settimer()
dailylot()
console.log("Cycle")
}, 5000)
}
while (i < 1) {
console.log("set timer " + i);
settimer()
i++;
}
Doing this works but only for the guild the message is sent in. Even once removing the while loop so it activates multiple times, it just wants to go to 1 guild only. How can I retrieve the channels of all servers? bot.guilds.channels isn't a thing.
You wold need to iterate over each of the guilds in your bot and get the channels for each of tem, this is the case because different from message or guild, guilds is not a class, meaning it doesn't have properties like guilds.channels, it is a collection of other guild classes.
This is an example on how to access those channels individually:
client.guilds.forEach(guild => {
guild.channels.forEach(channel => {
// Use the channel for whatever you need
})
})
Anyone knows what could be the issue that .kick() .setMute(true/false) or even setDeaf(true/false) in discord.js libary don't seem to work. Here is also a part of the code that doesn't do anything when it should but also doesn't throw any errors. Bot was invited with maximum privileges and also code block executes the command to steMute / setDeaf / kick. Any ideas of what might cause this or what should i try logging to find the issue? THANKS!
ar msgUserId = msg.author.id
var allUsers = []
var reset = true
bot.channels.forEach((channel, id) => {
if (reset){
channel.members.forEach((user, id) => {
allUsers.push(user)
if (id == msgUserId){
reset = false
}
})
if (reset){
allUsers = []
}
}
})
if (allUsers){
var number = Math.floor((Math.random() * allUsers.length))
allUsers[number].setDeaf(true)
allUsers[number].setMute(true)
} else {
var channel = msg.channel
channel.send("You must be in a voice channel with others for this to work!")
}
Channels in bot.channels are cached for the sole purpose of metadata which are instances of Channel, you need a guild context (aka. server ID) in order to acquire a TextChannel with which the operations you say can be done.