How to get the ID of a created channel in discord.js [duplicate] - discord.js

This question already has answers here:
How to create a channel then find the ID
(2 answers)
Closed 6 months ago.
I'm currently making a simple Ticket System for my Bot and I want to send a Message to the new Channel my Bot created after clicking on a Button. The Channel create and everything else worked fine, but I don't know how to get the Channel ID from that new Channel. Does anyone know more than me? (I'm using discord.js v14)
Code from the Event after clicking on the Button:
const { EmbedBuilder, PermissionsBitField } = require("discord.js")
module.exports = {
data: {
name: 'panelbutton'
},
async execute(interaction, client) {
client.config = require('../../config');
const ticketchannel = interaction.guild.channels.create({
name: `${interaction.user.username}`,
permissionOverwrites: [
{
id: interaction.guild.id,
deny: [PermissionsBitField.Flags.ViewChannel]
},
{
id: interaction.user.id,
allow: [PermissionsBitField.Flags.ViewChannel, PermissionsBitField.Flags.SendMessages],
deny: [PermissionsBitField.Flags.UseApplicationCommands]
}
]
});
const wait = new EmbedBuilder()
.setTitle('Created! :white_check_mark:')
.setDescription(`Your Channel is created!`)
.setTimestamp(Date.now())
.setFooter({
text: client.config.bot.footer
});
await interaction.reply({
embeds: [wait], ephemeral: true
});
}
}

interaction.guild.channels.create returns a Promise resolving to a GuildChannel object which has an id property.
Add await before interaction.guild.channels.create and you should be able to access the ID using ticketchannel.id.

You can use Promise.Prototype.then() or create a variable to define the channel created, which you already did.
Promise.Prototype.then():
await interaction.guild.channels.create({
name: `${interaction.user.username}`,
permissionOverwrites: [
{
id: interaction.guild.id,
deny: [PermissionsBitField.Flags.ViewChannel]
},
{
id: interaction.user.id,
allow: [PermissionsBitField.Flags.ViewChannel, PermissionsBitField.Flags.SendMessages],
deny: [PermissionsBitField.Flags.UseApplicationCommands]
}
]
}).then(channel => {
const channelID = channel.id
console.log(channelID)
})
Creating a variable:
const ticketChannel = await interaction.guild.channels.create({
name: `${interaction.user.username}`,
permissionOverwrites: [
{
id: interaction.guild.id,
deny: [PermissionsBitField.Flags.ViewChannel]
},
{
id: interaction.user.id,
allow: [PermissionsBitField.Flags.ViewChannel, PermissionsBitField.Flags.SendMessages],
deny: [PermissionsBitField.Flags.UseApplicationCommands]
}
]
})
const ticketChannelID = ticketChannel.id

Related

Pushing data to an array in already existing object with axios

i have a object which looks like this:
{
"title": "675756",
"release_date": "2022-01-16",
"series": "Better Call Saul",
"img": "https://upload.wikimedia.org/wikipedia/en/0/03/Walter_White_S5B.png",
"characters": [],
"id": 1
}
to an characters array i want to add the id of characters.
I do it by form and then i handle submit like this:
const handleSubmit = (values) => {
console.log("dodano aktora do filmu!");
console.log(values);
addActorToMovie(values);
history.goBack();
};
the addActorToMovie action:
export const addActorToMovie = (resp) => ({
type: types.ADD_CHAR_TO_MOVIE,
payload: resp,
});
and the reducer:
case types.ADD_CHAR_TO_MOVIE:
console.log(action.payload);
return {
...state,
...state.episodes.map(function (item) {
return item.id === action.payload.episodeId
? {
id: item.id,
title: item.title,
release_date: item.release_date,
series: item.series,
img: item.img,
characters: [...item.characters, action.payload.actor],
}
: { ...item };
}),
};
It all works, but the problem is that i dont want to do it loccaly. Im using an database with json-server, and I want to do an Axios Request so that it would add a data to the database.
And i don't know how to do this, when i use axios.post it adds an object to my episodes array, if im using axios.put it changes an object. Is there any possibility to push the data to an array as i do it with the code above, but with axios so that it would be added to database?
My approach looked like this:
export const addActorToMovieAxios = (value) => {
console.log(value);
return async (dispatch) => {
try {
const response = await axios.post(
`http://localhost:3000/episodes/`,
value
);
console.log(response);
dispatch(addActorToMovie(response.data));
} catch (ex) {
console.log(ex);
}
};
};
but as I said this does add a new object to an array.....
"episodes": [
{
"title": "675756",
"release_date": "2022-01-16",
"series": "Better Call Saul",
"img": "https://upload.wikimedia.org/wikipedia/en/0/03/Walter_White_S5B.png",
"characters": [],
"id": 1
},
{
"episodeId": 1,
"actor": "1",
"id": 2
}
]
So just to be clear I understand your question, you have an object that already exists in your DB, and you want to push something onto the 'characters' array in that existing object, without creating a new object, correct?
To do this, I would use Mongo for your DB and define two Mongoose Schemas, one for the existing object (let's call it TVShow) and one for the Characters within that object. Your two Schemas will look like this:
TVShowModel.js:
const mongoose = require('mongoose');
const CharacterModel = require('./CharacterModel')
const TVShowScheme = new mongoose.Schema({
title: {
type: String,
},
release_date: {
type: Date,
},
series: {
type: String,
},
img: {
type: String,
},
characters:[
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Student'
},
],
examQuestions: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'CharacterModel'
}
]
})
module.exports = mongoose.model('TVShowModel', TVShowScheme )
CharacterModel.js:
const mongoose = require('mongoose');
const CharacterModel= new mongoose.Schema({
characterName: {
type: String,
},
actorName: {
type: String,
},
}) // add any other fields you want here
module.exports = mongoose.model('CharacterModel', CharactModelScheme )
Then, create your Axios post request. Make sure you send when you send the 'value' variable to your server, it contains the id (or perhaps the unique title) of the object you'll be 'pushing' to. Push won't work in axios/react, so we'll use the 'spread' opperator instead.
Your router will look like this:
const CharacterModel= require ('../models/CharacterModel');
const TVShowModel= require ('../models/TVShowModel');
const router = express.Router();
router.post('/episodes', async function(req,res){
try{
const tvshow = await TVShowModel.find({title: req.body.title})
// edit as needed
console.log("FOUND TV Show: "+tvshow )
const characterName= req.body.characterName
const actorName = req.body.actorName
const newCharacter = new CharacterModel({
characterName,
actorName,
})
console.log("new character created: "+newCharacter)
tvshow[0].CharacterModel = [...tvshow[0].CharacterModel,newCharacter];
await tvshow[0].save()
.then(()=>res.json('New Character Added to DB'))
.catch(err=>res.status(400).json('Error: ' + err))
} catch(e){
console.log(e)
}
})
Hope this was clear!

how to insert checkbox as array into mongodb

I don't know why it's not being inserted. it doesn't show an error or anything so i couldn't figure out the problem.
the tags [ '61c2102d165a5af742091a70', '61c37621165a5af742093a1a' ].
here is my insert function:
insert: async(req,res)=> {
const {userid,tags}=req.body;
console.log("userid", userid)
console.log("tags", tags) //tag [ '61c2102d165a5af742091a70', '61c37621165a5af742093a1a' ]
try {
User.findByIdAndUpdate(
userid,
{ $push: { tags: {$each : tags } }} ,
);
return res.status(200).send({msg:"success"});
} catch (error) {
console.log(error);
res.status(500).send({ msg: "Something went wrong" });
}
}
my user schema:
tags: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Tag'
}]
tag schema:
const TagSchema = new Schema({
name: {
type: String
},
type: {
type: Object,
},
timestamp: {
type: Date,
default: Date.now
},
});
Most codes i saw do it like that but i couldn't figure out why mine isn't working
Since you are using async, you can make use of await to see it if is saved or not. Rewriting logic in this way you can catch saved instance and return success or failure.
insert: async(req,res)=> {
const {userid,tags}=req.body;
console.log("userid", userid)
console.log("tags", tags) //tag [ '61c2102d165a5af742091a70', '61c37621165a5af742093a1a' ]
const doc = await User.findByIdAndUpdate(
userid,
{ $push: { tags: {$each : tags } }} ,{new:true}
);
if (!doc) return res.status(500).send({ msg: "Something went wrong" });
return res.status(200).send({msg:"success"});
}

How to remove role to access channel with discord.js?

I would like to avoid members to see a specific channel.
I tried this but I don't understand why it doesn't work.
I'm using discord.js v12 module.
const memberRole = await msg.guild.roles.cache.find((role: any) => role.name === "member")
const permissionOverwrites = [{id: memberRole.id, deny: ['VIEW_CHANNEL']}];
const channel = await msg.guild.channels.create(`channel`, {
type: "text",
permissionOverwrites,
reason : "test",
});
Iif I could remove the entire role from this channel it would be perfect.
thanks
You're using v11 code with the v12 module. In your case you would need:
let permissionOverwriteArray = [{id: memberRole.id, deny: ['VIEW_CHANNEL']}]
guild.channels.create('new-channel', { type: 'text', permissionOverwrites: permissionOverwriteArray, reason: 'New channel!' });

Mongoose's push acting weird

So I've spent the last 2 days working on this and I am going crazy, here is my code (part of it):
const mongoose = require('mongoose')
mongoose.connect('',{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
const postsSchema = new mongoose.Schema({
_id: String,
posts: Array,
upvotes: Number,
downvotes: Number,
fans: Array,
dmUserWhenUpvoted: Boolean,
dmUserWhenDownVoted: Boolean
})
const postsModel = mongoose.model("Posts",postsSchema)
/**
*
* #param {Object} user
*/
async function getPosts(user){
if(!user) user = message.author
let posts = await postsModel.findOne({_id: user.id})
if(posts === null){
let newData = new postsModel({
_id: user.id,
posts: [],
upvotes: 0,
downvotes: 0,
fans: [],
dmUserWhenUpvoted: false,
dmUserWhenDownVoted: false
})
await newData.save()
posts = await postsModel.findOne({_id: user.id})
}
return {
_id: user.id,
posts: posts.posts,
upvotes: posts.upvotes,
downvotes: posts.downvotes,
fans: posts.fans,
dmUserWhenUpvoted: posts.dmUserWhenUpvoted,
dmUserWhenDownVoted: posts.dmUserWhenDownVoted,
account: posts
}
}
these are the 2 methods i used to push:
let getposts = await getPosts()
postsModel.updateOne(
{_id: message.author.id},
{
"$push": {
"posts": {
id: s.id,
upvotes: 0,
downvotes: 0
},
}
},
function(err, response) {
console.log(err)
console.log(response)
}
)
console.log(getposts.account)
await message.delete()
this method doesn't push anything when i logged posts.account and the error logs as null
method 2:
let getposts = await getPosts()
getposts.account.posts.push({
id: s.id,
upvotes: 0,
downvotes: 0
})
await getposts.account.save(function(err){
console.log(err)
});
console.log(getposts.account)
await message.delete()
when I log getposts.account, it logs the array (posts) with the pushed object inside it, but when i went to my dashboard and viewed my collection, its empty. Hope someone can help me with my problem, this problem only occurs to this part of the code, I use method 2 to push all my stuff in different collections and it works
Ok, turns out you don't actually even need to specify an array of arbitrary mongoose objects with posts: [new mongoose.Schema({}, {versionKey: false, _id: false})]. This will get the job done just the same: posts: Array, which is what you had originally anyway.
So let's imagine we have just one document in your Posts collection:
{
"_id" : ObjectId("6039b9ff08e0c46c9c04f963"),
"fans" : [ ],
"posts" : [ ],
"upvotes" : 0,
"downvotes" : 0,
"dmUserWhenUpvoted" : false,
"dmUserWhenDownVoted" : false,
}
As you can see, the posts field is empty. To push a new post object into it, you will need this code (or a variation of it):
const postsModel = mongoose.model('Posts');
const addPosts = () => {
postsModel.findOne({_id: '6039b9ff08e0c46c9c04f963'})
.then(post => {
post.posts.push({
id: 'some_id_here',
upvotes: 0,
downvotes: 0
})
post.save()
})
}
addPosts()
I am more of a then guy, but if you prefer awaiting, it will look like so:
const postsModel = mongoose.model('Posts');
const addPosts = async () => {
const post = await postsModel.findOne({_id: '6039b9ff08e0c46c9c04f963'})
post.posts.push({
id: 'some_id_here_1',
upvotes: 0,
downvotes: 0
});
await post.save();
return 'ok';
}
addPosts().then(r => console.log(r))

List of administrators

I am trying to make the bot to show all the members that has the administrator permission through a field.
Edit: I haven't upload all the code so I edited it, I am sorry!
command(client, 'serverinfo', message => {
const { guild } = message
const { name, region, memberCount, owner, } = guild
const icon =guild.iconURL()
const member = message.member;
const Administrators = member.hasPermission("ADMINISTRATORS")
const embed = new Discord.MessageEmbed()
.addFields(
{
name: 'Server Owner',
value: owner.user.tag,
inline: true,
},
{
name: 'Members in server',
value: memberCount,
inline: true,
},
{
name: 'Region',
value: region,
inline: true,
},
{
name: 'Administrators',
value: (`Currently all administrators are: ${Administrators.user}`)
},
)
message.channel.send(embed)
})
GuildMember.hasPermission() returns a boolean of whether the given member has the given permission, not an array of GuildMembers.
If you want an array (or collection in this case), you must filter() the GuildMemberManager.cache collection, and then map() it.
const administrators = message.guild.members.cache.filter((member) =>
member.hasPermission('ADMINISTRATOR')
);
console.log(
`Administrators:\n${administrators.map(({ id }) => `<#${id}>`).join('\n')}`
);

Resources