permission over write after channel creation, using discord.js - javascript

I'm having some issues with giving the message.author and staff permission to see the channel right after it's created, the issue is, when the channel's parent (category) is changed, it syncs the permissions of the parent (category), which disallows the user and staff to see the channel, I'm not sure how to fix this, I wish I explained well, if you have any questions, please ask.
Here is my code:
module.exports = {
name: 'new',
category: 'Ticket',
description: 'Creates a new ticket.',
aliases: ['newticket'],
usage: 'New',
userperms: [],
botperms: [],
run: async (client, message, args) => {
if(message.author.bot) return;
if(!message.channel.id == process.env.COMMAND_T) return;
if(!client.userTickets) {
client.userTickets = new Map();
const channels = message.guild.channels.cache.filter(channel => {
if(channel) return channel.name.startsWith('t-');
});
if(channels) {
for (i in Array.from(channels)) {
client.userTickets.set(i, +i + 1);
}
}
}
console.log(client.userTickets)
if(client.userTickets.has(message.author.id)) {
return message.channel.send('<#' + message.author.id + 'You already have a ticket, please close it then run this command again!').then(m => m.delete({timeout: 10000}));
}
message.guild.channels.create(`t-${client.userTickets.size + 1}`, {
permissionOverwrites: [
{
id: message.author.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
},
{
id: process.env.ROLE_STAFF,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
},
{
id: process.env.ROLE_MEMBER,
deny: ['VIEW_CHANNEL']
}
],
type: 'text',
}).then(async channel => {
channel.setParent(process.env.TICKET_C);
client.userTickets.set(message.author.id, client.userTickets.size + 1);
message.channel.send(`<#` + message.author.id + `>, Done, go to your ticket! ${channel}`).then(m => m.delete({timeout: 10000}));
client.users.cache.get(message.author.id).send(`Your ticket has been opened, go take a look: ${channel}`)
channel.send(`Hi <#` + message.author.id + `>, Hello and welcome to your DwaCraft ticket!`);
channel.send(`https://tenor.com/view/is-there-something-i-can-help-you-with-dan-levy-david-david-rose-schitts-creek-gif-20776045`);
const logchannel = message.guild.channels.cache.find(channel => channel.id === process.env.TICKET_L);
if(logchannel) {
logchannel.send(`There was a new ticket created by <#${message.author.id}>! Channel: <#${channel.id}>`);
}
});
}
}
Note: I've researched but I didn't find any answer.
Thanks for taking the time to read this.

Try this
message.guild.channels.create(`t-${client.userTickets.size + 1}`, {
type: 'GUILD_TEXT',
permissionOverwrites: [
{
id: process.env.ROLE_STAFF,
allow: ['VIEW_CHANNEL'],
},
{
id: message.author.id,
allow: ['VIEW_CHANNEL'],
},
],
parent: process.env.CATEGORY
});
This code is mine, but it is shortened, if you like the complete one send me DM
P.S I just have it for my ticket system

Related

distube filters not applying

I'm trying to make a discord slash commands filter using distube but when I use the slash command it didn't apply the filter that I picked but it sent the embed when filter is applied
Node: v17.7.2
Discord: ^13.2.0
can someone help me or tell me why the filter is not applying to the current music in vc?
thank you
const { MessageEmbed } = require('discord.js');
const ee = require('../../config.json');
module.exports = {
name: 'filter',
description: 'Add filter.',
usage: 'filter',
options: [
{
name: 'preset',
description: 'Filters to add.',
type: 'STRING',
required: true,
choices: [
{
name: 'BassBoost',
value: 'bassboost'
},
{
name: 'Nightcore',
value: 'nightcore'
},
{
name: 'Vaporwave',
value: 'vaporwave'
}
]
}
],
run: async(client, interaction, args) => {
const filterss = interaction.options.getString('preset');
const queue = client.distube.getQueue(interaction);
let player = client.distube.filters;
if(!queue) {
return interaction.followUp({embeds: [
new MessageEmbed()
.setColor(ee.color)
.setAuthor({name: 'Error', iconURL: 'https://i.imgur.com/81ig9jl.jpg'})
.setDescription('No songs are playing!')
]})
}
let thing = new MessageEmbed().setColor(ee.color);
if (filterss == "nightcore") {
thing.setDescription("✅ | Nightcore filter is now active!");
player.nightcore = true;
} else if (filterss == "bassboost") {
thing.setDescription("✅ | BassBoost filter is now on!");
player.bassboost = true;
} else if (filterss == "vaporwave") {
thing.setDescription("✅ | Vaporwave filter is now on!");
player.vaporwave = true;
}
return interaction.followUp({ embeds: [thing] });
}
}
From what I can find in the docs, it is recommended to use .setFilter() instead of calling client.distube.filters.<filter> = true.
I'd try changing your run code to use this instead and see if that works:
run: async(client, interaction, args) => {
// Your queue check code here
let thing = new MessageEmbed().setColor(ee.color);
if (filterss == 'nightcore') {
thing.setDescription('✅ | Nightcore filter is now active!');
client.distube.setFilter(interaction, filterss);
} else if (filterss == 'bassboost') {
thing.setDescription('✅ | BassBoost filter is now on!');
client.distube.setFilter(interaction, filterss);
} else if (filterss == 'vaporwave') {
thing.setDescription('✅ | Vaporwave filter is now on!');
client.distube.setFilter(interaction, filterss);
}
return interaction.followUp({
embeds: [thing],
});
}

DiscordAPIError: Unknown Interaction

I have been using an online guide to set up a currency bot but when I use the command to add items to the shop the terminal throws out this error and while the bot says the item has been added when I check the shop it has nothing in it. this is the exact error that i get I'm new to coding and a have little to no idea what it means any help or point towards a guide that might explain it would be greatly appreciated
DiscordAPIError: Unknown interaction
at RequestHandler.execute (c:\Users\danie\Desktop\CurrencyBot\node_modules\discord.js\src\rest\RequestHandler.js:349:13)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (c:\Users\danie\Desktop\CurrencyBot\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
at async CommandInteraction.reply (c:\Users\danie\Desktop\CurrencyBot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:99:5)
====================
Here is the code for the command
const Discord = require('discord.js')
const CurrencySystem = require("currency-system");
const cs = new CurrencySystem;
exports.run = async (client, message, args) => {
await message.deferReply();
if (message.options.getInteger('price') < 1) return message.editReply("You can't add an item for less than 1$!");
let result = await cs.addItem({
guild: message.guild,
inventory: {
name: message.options.getString('name'),
price: message.options.getInteger('price'),
description: message.options.getString('description') || 'No Description'
}
});
if (result.error) {
if (result.type == 'No-Inventory-Name') return message.editReply('There was a error, Please enter item name to add.!')
if (result.type == 'Invalid-Inventory-Price') return message.editReply('There was a error, invalid price!')
if (result.type == 'No-Inventory-Price') return message.editReply('There was a error, You didnt specify price!')
if (result.type == 'No-Inventory') return message.editReply('There was a error, No data recieved!')
} else return message.editReply('Done! Successfully added `' + message.options.getString('name') + '` to the shop!')
}
exports.help = {
name: "additem",
data: {
name: 'additem',
description: "A way to additem to shop",
options: [{
name: 'name',
type: 'STRING',
description: 'Name of Item.',
required: true,
}, {
name: 'price',
type: 'INTEGER',
description: 'Price of item',
required: true,
},
{
name: 'description',
type: 'STRING',
description: 'Description of the item. (Can\'t be Changed later.)',
required: false,
}
]
}
};
exports.conf = {
aliases: [],
cooldown: 5 // This number is a seconds, not a milliseconds.
// 1 = 1 seconds.
}

Discord.js-commando missing argument reply

I'm porting my commands from vanilla discord.js to commando framework. I had a command that, when the argument was missing, it warned the user.
const { Command } = require('discord.js-commando');
module.exports = class ServerCommand extends Command {
constructor(client) {
super(client, {
name: 'say',
aliases: ['s'],
group: 'mod',
memberName: 'say',
description: 'Make the bot speak for you.',
userPermissions: ['MANAGE_CHANNELS'],
examples: [client.commandPrefix + 'say <text>',client.commandPrefix + 'say hello world'],
args: [{
key: 'text',
prompt: 'What should the bot say?',
type: 'string',
}]
})
}
run(message, { text }) {
if (text == '' || !text)
message.say("You didn't specify what the bot should say.")
message.say(text);
message.delete();
}
}
Now, with commando, it automatically warns the user with a reply when the arg is missing.
My question is, how can I overwrite it?
Thanks in advance!
I handled this adding default property 'default': 'isempty' and then I catch it in the command's code. So, the code looks like it:
const { Command } = require('discord.js-commando');
module.exports = class ServerCommand extends Command {
constructor(client) {
super(client, {
name: 'say',
aliases: ['s'],
group: 'mod',
memberName: 'say',
description: 'Make the bot speak for you.',
userPermissions: ['MANAGE_CHANNELS'],
examples: [client.commandPrefix + 'say <text>',client.commandPrefix + 'say hello world'],
args: [{
key: 'text',
prompt: 'What should the bot say?',
type: 'string',
'default': 'isempty',
}]
})
}
run(message, { text }) {
if (text == 'isempty') return message.say("You didn't specify what the bot should say.");
message.say(text);
message.delete();
}
}

Check if userid matches one in the array

I'm attempting to check if a user's ID is in this array and if they are, also get the "text" from it.
Array:
const staff = [
{
user: '245569534218469376',
text: 'dev'
},
{
user: '294597887919128576',
text: 'loner'
}
];
I've tried if (staff.user.includes(msg.member.id)) (Which I didn't think was going to work, and didn't.)
const findUser = (users, id) => users.find(user => user.id === id)
const usersExample = [
{
id: '123456765',
text: 'sdfsdfsdsd'
},
{
id: '654345676',
text: 'fdgdgdg'
}
]
//////////////////
const user = findUser(usersExample, '123456765')
console.log(user && user.text)
The some method on an array is used to tell if an item meets a condition, it is similar to the find method but the find method returns the item where the some method return true or false.
const staff = [
{
user: '245569534218469376',
text: 'dev'
},
{
user: '294597887919128576',
text: 'loner'
}
];
const isStaff = (staff, id) => staff.some(s => s.user === id);
console.log(isStaff(staff, '123'));
console.log(isStaff(staff, '245569534218469376'));
You may try something like this:
const staff = [
{
user: '245569534218469376',
text: 'dev'
},
{
user: '294597887919128576',
text: 'loner'
}
];
let item = staff.find(item => item.user == '294597887919128576'); // msg.member.id
if (item) {
console.log(item.text);
}
One another way to do that is:
const inArray = (array, id) => array.filter(item => item.user === id).length >= 1;
const users = [
{
user: '245569534218469356',
text: 'foo'
}, {
user: '245564734218469376',
text: 'bar'
}, {
user: '246869534218469376',
text: 'baz'
}
];
console.log(inArray(users, '246869534218469376')); // true
console.log(inArray(users, '222479534218469376')); // false

Rocket Chat Realtime API in browser

I want to create a Rocket Chat client to subscribe to a channel through browser using Realtime API. Documentation here does not provide step by step procedure. Please let me know how to achieve it.
Links to any documentation would be very helpful.
I had less idea about websockets when I asked this question. For the benefit of all, mentioning the steps I followed.
Open websocket
var rocketChatSocket = new WebSocket("ws://locahost:3000/websocket");
Connect
var connectRequest = {
"msg": "connect",
"version": "1",
"support": ["1", "pre2", "pre1"]
}
rocketChatSocket.send(JSON.stringify(connectRequest));
After connecting, keep responding with {"msg":"pong"} for {"msg":"ping"} from server.
Login with authToken received by calling this API
var loginRequest = {
"msg": "method",
"method": "login",
"id": "42",
"params": [
{ "resume": "authToken" }
]
}
rocketChatSocket.send(JSON.stringify(loginRequest));
Subscribe to room
var subscribeRequest = {
"msg": "sub",
"id": "unique-id",
"name": "stream-notify-room",
"params":[
"room-id/event",
false
]
}
rocketChatSocket.send(JSON.stringify(subscribeRequest));
Send message
var request={
"msg": "method",
"method": "sendMessage",
"id": "42",
"params":
[
{
"_id": "message-id",
"rid": "room-id",
"msg": "Hello World!"
}
]
}
rocketChatSocket.send(JSON.stringify(request));
Thank you Mr Nandan,we were able to use your answer to build fully custom client to talk with the rocket chat real time api
here's the link for future people who will want the same thing
https://github.com/lalosh/rocketchat.realTimeAPI.customClient/blob/master/main.js
and here's the code in case you want to check immediately
/*
Rocket Chat Real Time API Custom Client
even though this code works great I don't know what exactly each event we listen for is doing
you can go back to rocket chat real time api for further declarations
we were able to write this code after we test real normal use case of livechat in a web page
and we listen for WebSocket connection inside the browser Network tab(by filtering ws(WebSocket) connections)
*/
let socket = new WebSocket('ws://[rocketChatIP]:[rocketChatPort]/websocket');
//note messageCount is incremented with every message
//but it can works even if you didn't change it
let messagesCount = 1;
// the variables chatToken and chatRoomId are very important
// and they are the identifier to the room(the whole chat) you are using
// if you want to get access to the chat again you need these two variables tokens
let chatToken = generateHash(17);
let chatRoomId = generateHash(17);
let subId = generateHash(17);
let roomSubId = generateHash(17);
let streamLivechatchatRoomId = generateHash(17);
let steamNotifyRoomSubId = generateHash(17);
let name = 'user28';
let email = 'user28#gmail.com';
let guestName = 'guest';
// listen to messages passed to this socket
socket.onmessage = function(e) {
let response = JSON.parse(e.data);
console.log('response', response);
// you have to pong back if you need to keep the connection alive
// each ping from server need a 'pong' back
if (response.msg == 'ping') {
console.log('pong!');
socket.send(JSON.stringify({
msg: 'pong'
}));
return;
}
// here you receive messages from server //notive the event name is: 'stream-room-messages'
if (response.msg === 'changed' && response.collection === 'stream-room-messages') {
console.log('msg received ', response.fields.args[0].msg, 'timestamp ', response.fields.args[0].ts.$date, 'from ' + response.fields.args[0].u.name);
return;
}
// receive all messages which will only succeed if you already have messages
// in the room (or in case you send the first message immediately you can listen for history correctly)
if (response.msg === 'result' && response.result) {
if (response.result.messages) {
let allMsgs = response.result.messages;
console.log('-----previous msgs---------------');
allMsgs.map(x => console.log(x))
console.log('---------------------------------')
}
}
}
//////////////////////////////////////////////
// steps to achieve the connection to the rocket chat real time api through WebSocket
//1 connect
let connectObject = {
msg: 'connect',
version: '1',
support: ['1', 'pre2', 'pre1']
}
setTimeout(() => {
socket.send(JSON.stringify(connectObject));
}, 1000)
//////////////////////////////////////////////
//2 getInitialData
let getInitialDataObject = {
msg: 'method',
method: 'livechat:getInitialData',
params: [String(chatToken), null],
id: String(messagesCount++),
}
setTimeout(() => {
socket.send(JSON.stringify(getInitialDataObject));
}, 2000)
//////////////////////////////////////////////
//3 loginByToken
let loginByToken = {
msg: 'method',
method: 'livechat:loginByToken',
params: [String(chatToken)],
id: String(messagesCount++),
}
setTimeout(() => {
socket.send(JSON.stringify(loginByToken));
}, 3000)
//////////////////////////////////////////////
//4 subscribtion
let subObj = {
msg: 'sub',
id: subId,
name: 'meteor.loginServiceConfiguration',
params: []
}
setTimeout(() => {
socket.send(JSON.stringify(subObj));
}, 4000)
//////////////////////////////////////////////
//5 register // you may skip this if you alredy registered
// or you can re use it even though you are registered.. no problems
// the crucial part is the `chatToken` and later on the `chatRoomId`
let registerObj = {
msg: 'method',
method: 'livechat:registerGuest',
params: [{
token: chatToken,
name: name,
email: email,
'department': null
}],
id: String(messagesCount++),
};
setTimeout(() => {
socket.send(JSON.stringify(registerObj));
}, 5000)
//////////////////////////////////////////////////
//6 stream-notify-room
let streamNotifyObj = {
msg: 'method',
method: 'stream-notify-room',
params: [
'null/typing',
guestName, true, {
token: String(chatToken)
}
],
id: String(messagesCount++)
};
setTimeout(() => {
socket.send(JSON.stringify(streamNotifyObj));
}, 6000)
//////////////////////////////////////////////////
//7 send a msg //use the same method to send your own messages again when you are all connected
let myMsg = {
msg: 'method',
method: 'sendMessageLivechat',
params: [{
_id: String(generateHash(17)),
rid: chatRoomId,
msg: 'first message',
token: String(chatToken),
}, null],
id: String(messagesCount++),
}
setTimeout(() => {
socket.send(JSON.stringify(myMsg));
}, 7000)
//////////////////////////////////////////////////
//8 send userPresence
let UserPresence = {
msg: 'method',
method: 'UserPresence:connect',
params: [
String(chatToken),
{
visitor: String(chatToken)
}
],
id: String(messagesCount++)
}
setTimeout(() => {
socket.send(JSON.stringify(UserPresence));
}, 8000)
/////////////////////////////////////////////////
//9 loadHistory of old messages
let loadHistory = {
msg: 'method',
method: 'livechat:loadHistory',
params: [{
token: String(chatToken),
rid: String(chatRoomId),
ts: {
$date: new Date().getTime()
}, //current point of time
limit: 50
}],
id: String(messagesCount++)
};
setTimeout(() => {
socket.send(JSON.stringify(loadHistory));
}, 9000)
/////////////////////////////////////////////////
// 10 stream-room-messages
// listen to all received messages
let roomMessagesSub = {
msg: 'sub',
id: String(roomSubId),
name: 'stream-room-messages',
params: [
String(chatRoomId),
{
useCollection: false,
args: [{
visitorToken: String(chatToken)
}]
}
]
};
setTimeout(() => {
socket.send(JSON.stringify(roomMessagesSub));
}, 10000)
/////////////////////////////////////////////////
// 11 getAgentData
let getAgentData = {
msg: 'method',
method: 'livechat:getAgentData',
params: [{
roomId: String(chatRoomId),
token: String(chatToken),
}],
id: String(messagesCount++)
}
setTimeout(() => {
socket.send(JSON.stringify(getAgentData));
}, 11000)
/////////////////////////////////////////////////
//12 stream-livechat-room
let streamLivechatRoom = {
msg: 'sub',
id: String(streamLivechatchatRoomId),
name: 'stream-livechat-room',
params: [
String(chatRoomId),
{
useCollection: false,
args: [{
'visitorToken': String(chatToken)
}]
}
]
}
setTimeout(() => {
socket.send(JSON.stringify(streamLivechatRoom));
}, 12000)
//////////////////////////////////////////
//13 stream-notify-room
let steamNotifyRoomSub = {
msg: 'sub',
id: String(steamNotifyRoomSubId),
name: 'stream-notify-room',
params: [
`${String(chatRoomId)}/typing`,
{
useCollection: false,
args: [{
token: String(chatToken)
}]
}
]
}
setTimeout(() => {
socket.send(JSON.stringify(steamNotifyRoomSub));
}, 13000)
//////////////////////////////////////
//14 userpresence 2
let UserPresence2 = {
msg: 'method',
method: 'UserPresence:online',
params: [String(chatToken)],
id: String(messagesCount++),
}
setTimeout(() => {
socket.send(JSON.stringify(UserPresence2));
}, 14000)
//////////////////////////////////////
//use it to send new messages
function sendNewMsg(msg, messagesCount) {
let myMsg = {
msg: 'method',
method: 'sendMessageLivechat',
params: [{
_id: String(generateHash(17)),
rid: chatRoomId,
msg: String(msg),
token: String(chatToken),
}, null],
id: String(messagesCount++),
}
setTimeout(() => {
socket.send(JSON.stringify(myMsg));
}, 500);
}
function generateHash(targetLength) {
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < targetLength; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
If you like to use an open source library for this purpose, here is one https://github.com/inf3cti0n95/Rocket.Chat.RealTime.API.RxJS
Here is the sample code:
import { RealTimeAPI } from "rocket.chat.realtime.api.rxjs";
const realTimeAPI = new RealTimeAPI("wss://demo.rocket.chat/websocket");
realTimeAPI.keepAlive();
const auth = realTimeApi.login(USERNAME, PASSWORD);
//Subscribe to messages and errors
auth.subscribe(
(data) => console.log(data),
(err) => console.log(err),
() => console.log('completed'));
//Subscribe to a specific channel, identified by roomId
realtimeAPI.sendMessage({
msg: 'sub',
id: '<a unique Id for subscription>',
name: 'stream-room-messages',
params: [roomId, false],
});

Categories