How can I fetch a channel ID? - discord.js

So I have some code that creates a temporary channel and I want it so when it opens it I can send an embed to the temp channel. This is the current script:
bot.on('message', msg =>{
if(msg.content === (`${prefix}tempchannel`)) {
var server = msg.guild;
var name = msg.author.username;
server.channels.create(`${name} temp channel.`, { reason: `Temp channel for ${name}` })
msg.channel.send('Created a temp channel for you! Check your unreads.')
}})```
Could someone help me please?

GuildChannelManager.create() returns a promise of the created channel.
server.channels
.create(`${name}-temp-channel`, { reason: `Temp channel for ${name}` })
.then((channel) => channel.send("This is a new channel")); // channel callback

Related

Discord bot js - Cant get channel by id

This is my code. The output of 'channel' is always undefined. Does someone know the problem?
var channelId = "myId";
const client = new Discord.Client();
client.login(token);
var channel = client.channels.cache.get(channelId);
console.log(channel);
client.login(token) returns a promise so it's highly unlikely that you're authenticated when client.channels.cache.get(channelId) runs.
You should try changing your code to the below, so that you get your channel after you've authenticated.
client.login(token).then(x => {
var channel = client.channels.cache.get(channelId);
console.log(channel);
});

Discord.js Forward DM message to specific channel

So, I need a way to forward a message sent in the bot's dm to a specific channel in my server.
this is the code that I got so far:
execute(message, args) {
if(message.channel.type == "dm"){
let cf = args.join(' ')
const cfAdm = message.guild.channels.cache.get('767082831205367809')
let embed = new discord.MessageEmbed()
.setTitle('**CONFISSÃO**')
.setDescription(cf)
.setColor('#000000')
const filter = (reaction, user) => ['πŸ‘', 'πŸ‘Ž'].includes(reaction.emoji.name);
const reactOptions = {maxEmojis: 1};
cfAdm.send(embed)
.then(function (message) {
message.react('πŸ‘')
.then(() => message.react('πŸ‘Ž'))
/**** start collecting reacts ****/
.then(() => message.awaitReactions(filter, reactOptions))
/**** collection finished! ****/
.then(collected => {
if (collected.first().emoji.name === 'πŸ‘') {
const cfGnr = message.guild.channels.cache.get('766763882097672263')
cfGnr.send(embed)
}
})
});
}
else {
message.delete()
message.channel.send('Send me this in the dm so you can stay anon')
.then (message =>{
message.delete({timeout: 5000})
})
}
}
But for some reason that I can't seem to understand, it gives me this error:
TypeError: Cannot read property 'channels' of null
If anyone can help me, that would be greatly apreciated.
Thanks in advance and sorry for the bad english
The error here is that you are trying to call const cfAdm = message.guild.channels.cache.get('ID') on a message object from a Direct Message channel ( if(message.channel.type == "dm"){)
DMs don't have guilds, therefore message.guild is null and message.guild.channels does not exist.
You will need to first access the channel some other way. Luckily, Discord.js has a way to access all channels the bot can work with* (you don't need to muck around with guilds because all channels have unique IDs):
client.channels.fetch(ID) or client.channels.cache.get(ID)
(I have not tested this but it seems fairly straight forward)
*See the link for caveats that apply to bots in a large amount of servers.

Discord.js Sharding, How do you send an embed message with broadcastEval?

I'm trying to send an embed message to an specific channel with a sharded bot.
I've achieved sending a simple message successfully with this code:
client.shard.broadcastEval(`
(async () => {
let channel = await this.channels.get("683353482748756047");
channel.send("Hello")
})()
`)
The problem starts when I want to send an embed message. I've tried passing the variable like this:
//exampleEmbed is created
client.shard.broadcastEval(`
(async () => {
let channel = await this.channels.get("683353482748756047");
channel.send('${exampleEmbed}')
})()
`)
but the message is sent like "[object Object]".
I thought about returning the channel object back outside of broadcastEval and then sending my variable, but I've read this is not possible because you can't return full discord objects.
How should I send the embed message? Thank you for your time.
Okay, I solved it by creating the embed message inside the broadcastEval, and using the '${}' syntax to poblate it.
Example:
client.shard.broadcastEval(`
(async () => {
const Discord = require('discord.js');
let channel = await this.channels.get("683353482748756047");
if(channel){
//if shard has this server, then continue.
let message = new Discord.RichEmbed()
.setThumbnail(this.user.displayAvatarURL)
.setTitle('Title')
.addField("Something useful:", '${useful}')
.addField("Another useful thing:", '${useful2}')
.setTimestamp()
channel.send(message)
}
})()

How to make a bot greet newcomers?

I would like to make a bot that greets users that joined the server.
Any help is appreciated.
Basically, you need to listen for the guildMemberAdd event, which is when someone joins.
After that, you need to check if the server is YOUR server, get the channel, and send the welcome message.
client.on('guildMemberAdd', async member => {
if (member.guild.id !== "YOUR-GUILD-ID") return;
var channel = client.channels.cache.get('YOUR-CHANNEL-ID');
channel.send(`Welcome to the server, <#!${member.id}>!`);
});
const defaultChannel = guild.channels.find(channel => channel.permissionsFor(guild.me).has("SEND_MESSAGES"));
const userlist = newUsers.map(u => u.toString()).join(" ");
defaultChannel.send("Welcome our new users!\n" + userlist);
newUsers.clear();
this is a code sample
Welcome dm message guildMemberAdd (Discord.js Version 11.4.2)
client.on('guildMemberAdd', async member =>{
await member.send(Embed);
});
Goodbye dm message guildMemberRemove (Discord.js Version 11.4.2)
client.on('guildMemberRemove', async member =>{
await member.send(Embed);
});

Cannot send message to just created channel

I'm trying to send a message to a channel just after I created it, but it doesn't seem to work. I'm using discord.js#v12
This is the code:
message.guild.channels.create(cpl, 'text').then(ma => {
ma.setParent(cat);
ma.lockPermissions();
}).catch(err => console.log(err))
let nChannel = bot.channels.cache.find(ch => ch.name === cpl)
console.log(nChannel)
let embed = new Discord.MessageEmbed()
.setTitle("New Ticket")
nChannel.send(embed)
This is what is logged to the console:
Cannot read property 'send' of undefined
this is because you're not waiting for the channel to be created before trying to send the message. In the same way you wait for it to be ready before using .setParent() and .lockPermissions(), you should wait before using .send().
Here's how I would do it:
message.guild.channels.create(cpl, 'text').then(async (newChannel) => {
// You're inside .then, so all of this is happening AFTER the channel is created
// Wait for .setParent and .lockPermissions to fulfill
await newChannel.setParent(cat)
await newChannel.lockPermissions()
// You can now send your message
let embed = new Discord.MessageEmbed()
.setTitle("New Ticket")
newChannel.send(embed)
})

Resources