How can I make the channel.send know where its being sent - javascript

I tried messing around with it and couldn't get it to work - all I want is for it to send in the channel that the user initiated the bot to talk.
client.once('ready', async () => {
// [beta]
const storedBalances = await Users.findAll();
storedBalances.forEach(b => currency.set(b.user_id, b));
client.channels.fetch("/*the channel where channel.send will go to*/").then((c) => {
channel = c;
})
console.log(`Logged in as ${client.user.tag}!`);
});

It's quite easy, in fact. If you haven't created the client.on("messageCreate", message => {}); event handler, I very strongly recommend creating it in the main file (if you use multiple files). Then, all you have to do is use message.channel.send(); inside those curly brackets {} to send message in the channel the user initiated the bot to talk. It's a good idea to check out the discord.js guide: https://discordjs.guide/#before-you-begin and watch YouTube tutorials on discord.js v13.

Related

Why doesn't my discord.js bot reply to messages? [duplicate]

This question already has an answer here:
message.content doesn't have any value in Discord.js
(1 answer)
Closed 4 months ago.
So my code is this:
const { GatewayIntentBits } = require('discord.js');
const Discord = require('discord.js');
const token = 'My Token';
const client = new Discord.Client({
intents:
[
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages
]
});
client.on('ready', () =>
{
console.log("Bot is on");
});
client.on('message', (message) =>
{
const channel = client.channels.get("1028177045773094915")
if (message.content === 'ping')
{
channel.send("pong")
}
});
// This is always the end
client.login(token);
I don't know why it is not working, it's in online but when I type anything in channel it doesnt do anything.
There are a few errors with this.
Before I get into the more complicated stuff, please know that the message event doesn't work -- use messageCreate.
The second smaller thing that I need to point out is that you don't have the MessageContent Intent enabled; that needs to be enabled for you to detect the text/attachments of a message that isn't a Direct Message to the bot, and doesn't ping/mention the bot.
Now, for the bigger stuff.
client.channels.get() isn't a function, and that's because of the Channel Cache.
I'll try my best to break down what a Cache is, but I'm not too good with this, so someone can correct me below.
A cache is similar to a pocket; when someone (being discord.js) looks inside of your pocket (the cache), that someone can only see the items inside of the pocket. It can't detect what isn't there. That's what the cache is. It's the inside of the pocket, and holds the things that you want discord.js to see.
If your item isn't in the cache, discord.js won't use it. But, you can get discord.js to look for that item elsewhere, and put it into that pocket for later.
This is the .fetch() method. It puts something that isn't in the cache, well, in the cache.
An example of using it:
const channel = await client.channels.fetch("CHANNEL_ID");
Or, what I'd call the more "traditional" way of doing it:
client.channels.fetch("CHANNEL_ID").then(channel => {
});
Now, after fetching your channel, you can call it like this:
client.channels.cache.get("CHANNEL_ID");
Another fun thing about the .fetch() method is that you can use it to shove everything in the cache, though it isn't necessary in most cases.
client.channels.fetch();
That will fetch every channel that the bot can see.
client.guilds.fetch();
That will fetch every guild the bot is in.
guild.members.fetch();
That will fetch every guild member of a guild.
And so on.
After Everything
After applying everything that I've said previously, you should wind up with code that looks like this:
const { Client, GatewayIntentBits } = require("discord.js");
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent // Make sure this is enabled in discord.com/developers/applications!
]
});
client.on("messageCreate", async(message) => {
if(message.content.toLowerCase() === "ping") {
// I added the .toLowerCase() method so that you can do PING and it works.
client.channels.fetch("1028177045773094915").then(channel => {
channel.send({ content: "pong!" });
});
}
});
client.login("Your Token");

Delete Button/Component of a specifc message (discord.js)

I am now trying in vain to remove buttons from a bot message. I have created a command for this purpose. When executing it, it should at best remove a specific, the last or at least all buttons that are on a specific message.
I have tried various things, but in all attempts the buttons are not removed.
module.exports = {
category: 'Utilities',
description: 'Delete Buttons',
permissions: ['ADMINISTRATOR'],
callback: async ({ client, message }) => {
const channel = client.channels.cache.get('the channel id')
channel.messages.fetch('the message id').then(msg => msg.edit({components: []}));
console.log(msg)
}
}
When I try to do this, I get the following console error:
TypeError: Cannot read properties of undefined (reading 'messages')
When I try this, I neither get a console log, nor does the bot do anything ...
const { Client, Message } = require("discord.js");
module.exports = {
category: 'Utilities',
description: 'Delete Buttons',
permissions: ['ADMINISTRATOR'],
callback: async ({ client, message }) => {
client.on('ready', async () => {
const channel = client.channels.cache.get('the channel id')
channel.messages.fetch('the message id').then(msg => {
msg.edit({ components: [] })
});
},
)}
}
Maybe one of you knows a solution or an idea. :)
Thanks a lot!
When I try this, I neither get a console log, nor does the bot do anything
The second example does not do anything because you are creating a ready event handler on running your command. Meaning, it's waiting for the bot to once again be "ready", i.e. the state of having logged in to the API as it does on startup. But your bot is already ready, and will not become ready again until the next time it restarts, so nothing will happen.
As for the first example, the error you are getting suggests channel is undefined, meaning either:
A) You have the incorrect channel ID
- OR -
B) The specified channel is no longer in the channel cache
If you are 100% sure the ID is correct, we can assume the issue you are having is the latter (the channel not being in the cache). There are many ways to solve this, but one simple way is to simply fetch the channel similar to how you are trying to fetch the message. Here's an example:
const channel = await client.channels.fetch('the channel id');
const msg = await channel.messages.fetch('the message id');
msg.edit({components: []});
That should fix the issue. If it doesn't, then the issue is much more complicated and not enough information has been provided. Also note that in the above example, I swapped Promise syntax for async/await since you are using an async function anyways; I did this just to make this answer more readable, you can choose whichever format you prefer.

Delete existing categories and channels and make new ones(discord.js)?

I need some help with a code in discord.js where I delete the existing categories and channels and then make new ones. My code edits the icon and guild name so now I'm moving onto channels and whatnot. No, this is not a nuker, I'm trying to make a server rebuilder or remodeler and things similar to that. Anyways, here is my code and by the bottom is where I'd like to implement the channel deleting and replacing.
const Discord = require('discord.js');
const client = new Discord.Client();
const guild = new Discord.Guild();
const { prefix, token } = require('./config.json');
client.once('ready', () => {
console.log('Ready!');
});
client.login(token);
client.on("message", async (message) => {
if (message.content == "server") {
try {
await message.guild.setIcon("./icon.png");
await message.guild.setName("server");
message.channel.send("Successfully made server.");
} catch {
message.channel.send("Unknown error occurred while making server.");
}
}
});
If anyone could help with this, please let me know.
Your question is too broad, you should try to narrow it to something specific that you are having issues with, like #Skulaurun Mrusal told you to. However, I can give you some tips on where to start:
You can access a <Guild>'s <GuildChannelManager> - a class that gives you some ways of managing the guild channels, such as deleting or creating them - through <Guild>.channels.
If you'd like to delete a channel from this <Guild> you would do <Guild>.cache.channels.find(channel => channel.name === 'channel-name').delete()
While if you wanted to create one, you would do: <Guild>.channels.create(...).
Don't forget you need the MANAGE_CHANNELS permission to do such operations. I hope this can help you out.

Discord bot log

So, I created a discord.js bot and added the following into index.js:
client.on("guildCreate", guild = {
const logsServerJoin = client.channels.get('757945781352136794');
console.log(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`);
client.channels.cache.get('channel id paste here').send(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`);
var guildMSG = guild.channels.find('name', 'general');
if (guildMSG) {
guildMSG.send(` Hello there! My original name is \`Bryant\`!\n\ This bot created by **R 1 J 4 N#7686**\n\ For more info
type \`/help\`!\n\ \`Bryant - Official Server:\`
https://discord.gg/UsQFpzy`);
} else {
return;
}
});
// Logs of the bot leaves a server and changed the game of the bot
client.on("guildDelete", guild = {
client.channels.cache.get('757945781352136794').send(`The bot just
left ${guild.name}, Owned by ${guild.owner.user.tag}`);
console.log(`The bot has been left ${guild.name}, Owned by ${guild.owner.user.tag}`);
logsServerLeave.send(`The bot has been left ${guild.name}, Owned by ${guild.owner.user.tag}`);
});
It does not show any error in the terminal. It is supposed to log me where the bot joined and left in the mentioned channel but does not 🤷‍♂️. Can anyone help me out with this?
If you are getting no console log and no message in the channel / an error telling you that the channel could not be found, the issue is most likely in how you are registering the events, make sure client is an instance of the discord.js Client, below is a minimal working example
const { Client } = require("discord.js")
const client = new Client()
client.on("guildCreate", guild => {
console.log(`The bot just joined to ${guild.name}, Owned by ${guild.owner.user.tag}`)
})
client.login("yourtoken")
If you are trying to get the logs from your bot alert you in your home discord server you can do this multiple ways: Getting the channel from cache, Constructing the channel or Using webhooks. Currently you are trying to fetch the channel from cache. Although a decent solution it can fall down when using sharding later down the line. Personally I prefer webhooks as they are the easiest and most isolated.
Channel from cache
This technique is very similar to the way you were doing it.
const channel = client.channels.cache.get('757945781352136794')
channel.send('An Event occurred')
Just place this code anywhere you want to log something and you'll be fine.
Constructing the channel
const guild = new Discord.Guild(client, { id: '757945781352136794' });
const channel = new Discord.TextChannel(guild, { id: '757945781352136794' });
channel.send('An Event occurred')
This method is similar to fetching the channel from cache except it will be faster as you are constructing your home guild and channel and then sending to it. Mind you will need a client which you can get from message.client
Webhooks
My Favourite method uses webhooks. I recommend you read up on how discord webhooks work in both Discord and Discord.js
You will also need to create a webhook. This is very easy. Go into the channel you want the webhooks to be sent to and then go to integrations and create a new webhook. You can change the name and profile as you wish but copy the url and it should look something like this:
https://discord.com/api/webhooks/757945781352136794/OkMsuUHwdStR90k7hrfEi5*********
The last part of the path is the webhook token and the bit before is the channel ID
I recommend you create a helper function that can be called like this:
sendWebhook('An event occurred');
And then write the function to create and then send to the webhook
function sendWebhook(text) {
const webhook = new Discord.WebhookClient('757945781352136794', 'OkMsuUHwdStR90k7hrfEi5*********');
webhook.send(text);
webhook.destroy();
}
This will not be very dynamic and will be a pain to change the channel but for constant logging ( like guild joins and leaves ) I think it is the best solution
The problem is probably that you don't have "Privileged Gateway Intents" enabled. To turn them on, go to https://discord.com/developers, click on your application, then on "Bot" then scroll down and enable "PRESENCE INTENT" and "SERVER MEMBERS INTENT" and save. It should probably work for you now.

Discord Bot Node JS simple error .send

I'm having a weird issue while following this tutorial. Building a JS Discord bot, literally only 33 lines in and its throwing errors about .send being undefined. I've googled around and I can't find anything that has helped get any closer to working this out.
const fs = require("fs");
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
client.login(config.token);
client.on("ready", () => {
client.user.setGame(`on ${client.guilds.size} servers`);
console.log(`Ready to serve on ${client.guilds.size} servers, for ${client.users.size} users.`);
});
client.on("guildMemberAdd", (member) => {
console.log(`New User ${member.user.username} has joined ${member.guild.name}` );
member.guild.defaultChannel.send(`${member.user} has joined this server`);
});
client.on("message", (message) => {
if (!message.content.startsWith(config.prefix) || message.author.bot) return;
if (message.content.startsWith(config.prefix + "ping")) {
message.channel.send("pong!");
} else
if (message.content.startsWith(config.prefix + "foo")) {
message.channel.send("bar!");
}
});
client.on("error", (e) => console.error(e));
client.on("warn", (e) => console.warn(e));
client.on("debug", (e) => console.info(e));
When ran, the console.log works without fuss, but the message to default channel throws the following error in PowerShell
C:\Users\super\Desktop\autoslap\mybot.js:18
member.guild.defaultChannel.send(`${member.user} has joined this server`);
^
TypeError: Cannot read property 'send' of undefined
Any help would be appreciated, getting frustrated over what is probably something so simple.
I know this is a late reply and you might've already figured out how to do this, but I will still explain to those who may need help.
As of 03/08/2017, there is no more Default Channel in guilds on
Discord. The #general default channel can be deleted, and the
guild.defaultChannel property no longer works - From
https://anidiots.guide/frequently-asked-questions.html
If you want an alternative, the code from https://anidiots.guide/frequently-asked-questions.html may do the trick. Just enter the site and scroll down until you see Default Channel!
If your bot has admin perms, its "first writable channel" is the one at the top. It could be any channel, so if their default channel was deleted you can potentially annoy a lot of people.
Hope this helps!
javascript node.js discord discord.js
You would get that error if the default channel of the server has been deleted. Previously, you weren't able to delete the default channel but now you can. To be sure, make a new server and try it there.

Categories

Resources