#development
1 messages Ā· Page 1870 of 1
some of the code you have may not be supported
because discord.js was updated to v13, screwing everyone over with new code
The docs will help you
They also contain notes about the specific changes from version to version
the only tool will be the docs, migrating versions is not easy
that error says you uninstalled it, not updated
install it again
hate when i mix up updating and uninstalling
hey, just on the djs docs i've seen that a reply to an interaction can return an empty promise (https://discord.js.org/#/docs/main/stable/class/CommandInteraction?scrollTo=reply), which is actually my case, but i'd like to get the message object of the message that the bot just sent, for further code.
What defines if the promise will return a void or a message object ?
no
dang
you receive it as a query string in the redirect url
after the user logs in
well, the exchange token
the actual token you get when you use the exchange token
oauth stuff
if thats what you're talking about,idk what you're doing
i just wanted to use the token in the body and not my bot token directly
well the final access token you should get in the body yes
this is all i see in the body
thats not an oauth2 request
nope
then what are you doing?
receiving a normal slash command sent to the INTERACTIONS ENDPOINT URL
i thought there might be a way to use the token in the body to authorize my api calls
thats an interaction token, not an oauth token
dangnabit
i'm running two screen instances on a linux vps, until yesterday everything was fine and i could reconnect to both of them without any problem, now if i execute screen -r it shows this:
There are several suitable screens on:
1396.pts-(heres server ip) (Detached)
1191.pts-(heres server ip) (Detached)
Type "screen [-d] -r [pid.]tty.host" to resume one of them.
~```
what can i do?
let channel = msg.member.voice.channel
await joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
let connection = getVoiceConnection(channel.guild.id)
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
});
connection.subscribe(player)
let resource = createAudioResource(path.resolve(`./music/name.mp3`));
player.play(resource);
Why is the sound lagging when the bot is added to another voice channel on another server?
is the bot hosted on a limited bandwith server ?
or maybe when testing on your local machine ?
try to put it on an online vps or something
local machine
well yeah try to put it on a server
maybe a ressource issue, if you have other processes running on your computer, or just your connexion
Dont have access to a server at the moment so yeah.... but thank you for letting me know the reason
@hasty lotusdo you know maybe what causes this error:
Error: Cannot perform IP discovery - socket closed
This error appears sometimes when the bot gets kicked out of the channel
uh, without any code like this i coudn't explain it no sorry x)
The UDP connection to the voice server was closed before it could resolve the IP from the name server
or the name server is experiencing issues
yeah that's basically what it means, but why does this happen, like this, idk š
that would be cataclysmic
Except the discord voice servers are TCP
the opus packets are sent over udp
mmm true
message.guild.channels.cache.forEach(async (channel) => {
await channel.createOverwrite(muteRole, {
SEND_MESSAGES: false,
MANAGE_MESSAGES: false,
READ_MESSAGES: false,
ADD_REACTIONS: false
});
})
```is giveing me that await can only be used in a async function
:<
someone?
That is multiple screen instances running. You need to destroy one of them and then just stick to creating new windows inside of screen with control + a + C iirc
either c or C
const botname = client.user.username;
await Channel?.createWebhook(botname, {
avatar: client.user.displayAvatarURL({ format: 'png', dynamic: true, size: 128 })
})
.then(webhook => Promise.all([webhook.send({ embeds: [ChannelDeleted] }), webhook]))
.then(([_, webhook]) => webhook.delete())
.catch(() => {});
How can i make it create it once it's not generated and if it already there it sends with the webhook?
i have used multiple instances without problems until literally yesterday, also, i cant destroy just one of them without connecting to it, which is what im tryna do
a
control + a + X all of the screens in one of them and it should destroy it
help
using a command handler or a unique file?
try removing it from the loop (?) idk
maybe since you have it both in the execute() and the loop it conflicts in some manner idk
I need helpjs if (!message.content.includes("www.link1.com"||"www.link2.com")) { let errorEmbed = new Discord.MessageEmbed() .setTitle(`**Something went wrong**`) .setDescription(`.`) .setColor("RED") .setFooter(`Command ran by: ${message.author.tag} (${message.author.id})`, message.author.displayAvatarURL()) .setTimestamp() message.channel.send(errorEmbed).catch(console.error); } else { something } It's working perfectly fine when the message doesn't include www.link1.com, however, the bot is totally ignoring the second condition (www.link2.com), when the message content includes it, the bot reads it as false and sends the errorEmbed when it actually shouldn't!
How can I solve this? I don't know what's wrong
!message.content.includes('www.link1.com') || !message.content.includes('www.link2.com')
unfortunately comparison operators do not work inside of functions like includes
I already tried that method but used " " instead of ' ', still doesn't work - Should I try with ' ' instead?
Oh I see. Good to know that
shouldnt make a difference, but give it a try ig
Alright, thanks
Now it's not detecting neither link1 nor link2
just reconnect using the id
screen -r ID
or screen -r -d ID to force attach
could you please show the line of code?
thanks
you can rename the screen to make reconnecting easier
lul
What's your code for your command handler?
if (!message.content.includes("link1")||!message.content.includes("link2")) {
let errorEmbed = new Discord.MessageEmbed()
.setTitle(`**Something went wrong**`)
.setDescription(`.`)
.setColor("RED")
.setFooter(`Command ran by: ${message.author.tag} (${message.author.id})`, message.author.displayAvatarURL())
.setTimestamp()
message.channel.send(errorEmbed).catch(console.error);
} else {
let args = message.content.split(" ");
let gameLinksArray = args.slice(1);
if (gameLinksArray.some(v => !v.includes("link1")||!v.includes("link2"))) {
let errorEmbed = new Discord.MessageEmbed()
.setTitle(`**Something went wrong**`)
.setDescription(`.`)
.setColor("RED")
.setFooter(`Command ran by: ${message.author.tag} (${message.author.id})`, message.author.displayAvatarURL())
.setTimestamp()
message.channel.send(errorEmbed).catch(console.error);
} else {
something
}```
try this
if((!message.content.includes("link1")) || (!message.content.includes("link2"))
or use regexes
What would be a recommended amount of RAM for a VPS hosting a bot?
yes
Uh ok?
Alright, will try
it'll result in the same thing
not-or checks are dumb
I guess my question was poorly phrased I edited it
answer's still yes
there's no such thing as "recommended amount of ram for a bot"
š¤
answer is "as much as it needs"
Okok, thanks
ded
you could have a bot run both using 10kb or 10gb
depends on the language and library you use
depends on its function
message.guild.channels.cache.forEach((channel)=>{
channel.permissionOverwrites.create(muteRole, {
SEND_MESSAGES: false,
MANAGE_MESSAGES: false,
READ_MESSAGES: false,
ADD_REACTIONS: false
});
:<
Yeah makes sense, I know how much my bot is using right now but it's only on 2 guilds and I have no idea how to determine how much will it use in 100 guilds for example
foreach
2 -> 100 jump is quite small
don't expect a big change in ram usage
when me brain ded
which language and library?
btw it only doesn't work with links, it doesn't for simple strings as well. Is using regex still the solution to my issue?
Using discord.js
then i would guess about 100mb ram per 1000 guilds as a baseline
module.exports = {
name: "mute",
usage: "mute [@user] {time} {reason}",
cooldown: 3,
perms: ["MANAGE_MESSAGES"],
run: (client, message, args, storage) => {
const Discord = require('discord.js')
const moment = require('moment')
const GuildSchema = require("../models/guild.js");
if(!args[0]) return message.channel.send('Usage: `' + client.commands.get('mute').usage + '`');
let units = ["second", "minute", "hour", "day", "week", "month", "year"]
for(i=0; i>units.length; i++) {
let plural = [];
plural = plural.push(units[i]+"s");
console.log(plural)
}
let target = message.mentions.users.first() || message.guild.members.cache.get(args[0]);
let time = args[1]
let reason = args.slice(2).join(' ');
if(units.includes(args[2]) || unitsPlural.includes(args[2])) {
time = args.slice(1, 3).join(' ');
reason = args.slice(3).join(' ');
}
let unit = args.slice(1, 2).join(' ')
let value = args.slice(2, 3).join(' ')
let unmuteAt =moment().add(unit, value)
message.channel.send(new Discord.MessageEmbed()
.setTitle("Data")
.setDescription(`User "${target.username}" \n` +
`has been muted for "${time}" \n`+
`for the reason "${reason}" \n` +
`and would be unmuted at "${unmuteAt}" \n` +
`current time: ${moment()}`
))
let mutedRole = message.guild.roles.cache.find((n) => n.name === "Muted")
if(mutedRole === undefined) return message.channel.send('No role nammed "muted" has been found !mute setrole <id>')
message.channel.send(`i found the role "${mutedRole}" Āæwould you like it to be the one i use to sanction?`).then(async (msg) => {
await msg.react('ā
');
await msg.react('ā');
let yesFilter = (reaction, user) =>
reaction.emoji.name === "ā
" && user.id === message.author.id;
let noFilter = (reaction, user) =>
reaction.emoji.name === "ā" && user.id === message.author.id;
let yes = msg.createReactionCollector(yesFilter, { time: 20000 });
let no = msg.createReactionCollector(noFilter, { time: 20000 });
yes.on("collect", async(r) => {
GuildSchema.findOneAndUpdate({
guildID: message.guild.id
}, {
$set: {
mutedRole: mutedRole.id
}
}, {
new: true
}).then(() => {
message.channel.send(`k, the new mutedrole is ${mutedRole}`)
}).catch((err) => {
message.channel.send(storage.errorEmbed);
});
})
no.on("collect", async(r) => {
message.channel.send('ok, for set a muted role use `!mute setrole <id>`')
})
})
}
}```
the issue in your case is using not-or
can somedody help me
let me just steal some code
it doesnt work for a reason
let's read your if clause: "if message NOT contains link1 OR message NOT contains link2"
see the issue?
the proper way of doing that would be "if NOT (message contains link1 OR message contains link2)"
so, basically, not contain either options
or "if message NOT contains link1 AND message NOT contains link2"
and in that case how can I actually do "if NOT"?
!
fill this:
EXPECTED RESULT: __________
ACTUAL RESULT: __________
ahh xd
- any error that appeared in ur log
:< @quartz kindle
if (!mutedRole) {
try {
muteRole = message.guild.roles.create({data:{
name:"š | Muted",
color: "#f70404",
permissions:[]
}});
message.guild.channels.cache.forEach((channel)=>{
channel.permissionOverwrites.edit(muteRole, {
SEND_MESSAGES: false,
MANAGE_MESSAGES: false,
READ_MESSAGES: false,
ADD_REACTIONS: false
});
})
} catch(e) {
console.log(e.stack);
}
}
whats your discord.js version?
v12
brh
hello darkness my old friend
tim: "there's no update in v11"
yooo, it worked!!! thanks a lot! 
wait what
does your bot use an illegal version of discord? (better discord)
no
then what is it lol
channel.permissionOverwrites is a collection
How can you make the bot listen to the next message?
Like
bot: > Please mention a channel
user: > #general
bot: > set channel
So that the user doesnt need to use a prefix for this
With a message collector
how do i run a .bat file
Just double click it or right click execute
Or via CLI
$> mybat.bat
(Windows exclusive)
yh but i want a js file to run it
I wonder if JS even has inbuilt OS service options to work with
well, i just want a way yo run all git cmds and push a commited version
Oh yeah node has⦠well anyways no clue about GitHub and related stuff, but Iām sure you will find a way 
how can i get the user.presence discord.js v13?
why is this not working?
exec('cd ..', function(err, data) {
console.log(err)
console.log(data.toString());
});
would a 6 character string with only numbers and letters (10+26=36) have 1947792 combinations? e7ef23
How can I get a list of users who reacted to a message with a specific reaction?
message.reactions.cache.get("").users may work?
Hey @quartz kindle Can you help me please ?
what are you expecting cd .. to return?
no i mean, what are you expecting it to return?
you are executing a command, and reading the return value
well its giving me an error
thats because spawn expects a valid process to execute
There is a way to create webhook once and the bot send with it evertime?
const botname = client.user.username;
await Channel?.createWebhook(botname, {
avatar: client.user.displayAvatarURL({ format: 'png', dynamic: true, size: 128 })
})
.then(webhook => Promise.all([webhook.send({ embeds: [ChannelDeleted] }), webhook]))
.then(([_, webhook]) => webhook.delete())
.catch(() => {});
like what?
idk, what do you want it to do?
cd out of a folder, cd into a different folder, do git add, commit and push
Me ? :/
no
That's assuming that order doesn't matter, if you're doing it for say, a password, then order does matter and you'll have to do a permutation iirc
k
i'm using it to make short invite codes for games
okay, but still, how would i do that??
so all the cmds I want to do go in the array?
no, thats an array of arguments for one command
each command goes in a separate exec
oh ok
One message removed from a suspended account.
h
One message removed from a suspended account.
hug
Just wondering, but there is a weird issue with my bot. When I leave it running overnight via console, I get an error that the bot canāt connect to Discord or that handshake failed (donāt have the error right now cause Iām out). Any ideas?
does the bot stop at all?
alternatively, cd ../somefolder && git add && git commit && git push
using && is weird
false ? true : false ? true : false
i like doing those in big one liners
like 20 lined up
would be simple to fix if switches were expressions
switches should never be used
switches are ugly to look at imo
they are a code smell
I don't know, I'd rather read:
name: option.name,
value: switch (option.type) {
case 8: ...
case 7: ...
}
than what you have now
switch(expression, { one: () => { console.log("poggers") }, two: () => { console.log("not poggers") } });
or Rust's match expression
if switch statements didnt have to break out it would be so much better
PHP has one, too
my new favorite language
Modern languages offer switches without that break/comtinue stuff
Like Python's match
hope an ecmascript revision removes that necessity
or a deprecation of switch (unlikely)
$name = match(2) {
1 => 'One',
2 => 'Two',
};
echo $name; // "Two"
``` ā¤ļø
i have already deprecated it in my book
Rip switch
functions are great
then write a function mimicking switch
maybe ramda has one
const Switch = (map, value) => {
return map[value];
}
const val = Switch({1:"ONE", 2:"TWO"}, 1);
could call it get
Just wondering, but there is a weird issue with my bot. When I leave it running overnight via console, I get an error that the bot canāt connect to Discord or that handshake failed (donāt have the error right now cause Iām out). Any ideas?
Also the bot does stop completely/crashes.
(The bot is hosted on a raspberry pi)
Could be your internet being unreliable
Thatās why itās generally better to run on a VPS rather than a self hosted rpi imo
Imagine a bot
Do you know how to install cisco packet tracer?, if anyone knows can you teach me?
]: /app/node_modules/discord.js/src/structures/Webhook.js:158
2021-09-08T01:11:11.229131+00:00 app[Worker.1]: if (!this.token) throw new Error('WEBHOOK_TOKEN_UNAVAILABLE');
2021-09-08T01:11:11.229133+00:00 app[Worker.1]: ^
2021-09-08T01:11:11.229134+00:00 app[Worker.1]:
2021-09-08T01:11:11.229135+00:00 app[Worker.1]: Error [WEBHOOK_TOKEN_UNAVAILABLE]: This action requires a webhook token, but none is available.
But it's working on ready event
Without token
Code:
const botname = client.user.username;
const webhooks = await Channel.fetchWebhooks();
const webhook = webhooks.first();
if(webhook) {
await webhook.send({
embeds: [DeletedLog],
username: botname,
avatarURL: client.user.displayAvatarURL({ format: 'png', dynamic: true, size: 128 })
});
} else if(!webhook) {
await Channel?.createWebhook(botname, {
avatar: client.user.displayAvatarURL({ format: 'png', dynamic: true, size: 128 })
})
.then(webhook => Promise.all([webhook.send({ embeds: [DeletedLog] }), webhook]))
}
Someone help
I just updated to v13 and I think I did the wrong decision
can somebody help me? because my bot is not going up
and my mind is blowing up i cant figure out wth is going on
just explain your problem
here
Why no one want to help me in my problem :/
Just because itās midnight for most Europeans

because I can't figure it out
Java be like 
yeah now get rid of the break statements pls
My code ?
Break statement?
switch (5) {
case 5:
System.out.println("Five!!!");
break;
System.out.println("God damn it, break!");
}
That switch format is long gone from java
Well, java had a shitton of updates since 1.8
wtf
Plus that switch example u gave won't print
switch (aValue) {
case something -> {
doStuff
}
case otherthing -> oneliner;
case yeah -> youGetIt;
}
is the -> special syntax
it doesn't seem like syntax
Weew looks like match
var anInt = switch (name) {
case "joe" -> 1;
case "mama" -> 2;
case "who?" -> {
processThat();
yield 3;
}
}
That's lambda
Same as fat arrow
I know what lambda is, but I didn't think it was compatible with switch statements
and it doesn't seem so since it just throws an error at me
Version?
11.0.6
Outdated
what version is required
13 iirc
Or something around that
There's no issue keeping java updated tbf
Rarely something breaks suddenly like the old days
Yeah, I just prefer LTS stuff unless I want new stuff
Hello
and java's good enough where I don't need that
Ah, nope then
But anyway, you're missing a lot of juice
Like multi-line strings
Oh and records
I'm interested in virtual threads
Records are sweet
how do I import discord is the question
I've never really liked records in any language
I find them nice
Why do you define your client before initiating the djs instance?
console.log(a);
const a = "banana"
This wonāt be your only issue as a lot of things have changed
why tf did I update before I do a damnresearch 
Even unnecessary things like a few property names have changed or arenāt existing anymore
I saw for the embeds an example...
Oh, switches are getting pattern match on jdk 17
Well downgrade temporarily and work on the code before updating
.send({ embeds: [embed1, embed2] })
I tried that, but it still doesnt
Yeah method parameters and options in this case have changed too
I am telling you, I am super confused, and idk if something changed something in the index file automatically and its making bugs.. or idk wht
Just wondering, but there is a weird issue with my bot. When I leave it running overnight via console, I get an error that the bot canāt connect to Discord or that handshake failed (donāt have the error right now cause Iām out). Any ideas on a fix for this?
Also the bot does stop completely/crashes.
(The bot is hosted on a raspberry pi)
Also this is useful thanks; just wondering for another fix (if there is one).
Well try again later if Iām back at my PC if nobody has looked over it meanwhile
I downgrade it but it keeps it v13 š¦
dumb question but whats react?
that ^
Library that makes rendering web pages with state simple
Thatās not to do with an update, thatās just a general rule when programming. Using an uninitialized variable causes undefined behavior/errors in most circumstances.
Can my bot edit a message that the bot sent 1 year ago?
.. since it errors when I do so. š
How can I get a list containing the IDs of the users who reacted to a message with a specific reaction?
Please ping me when replying
I'd like to get that data to display it later this way:
//example
message.channel.send(`People who reacted with ${reaction}: \n<@${user.id}>, <@${user.id}>, <@${user.id}>`)```
Can anyone tell me why my for loop within this function is not completing, and instead only enters the first available option. My goal is to once it explores the first node depth-first, it should go back and check the others. But for some reason it only checks the first and stops.
I don't get how people can read anything when source code is THAT colored
Also spaces and newlines are your friend, you don't get lighter applications by not using 'em
Average sublime text - text editor
You haven't seen nothing yet
There is a theme on Jetbrain IDEs that make everything a rainbow iirc
Tf
its actually sublime text theme on vs code lol
wtf stop using that ew

Use let or const (const preferred - but not for beginners)
var is old
it isn't typically used anymore cause of the issues it caused
so let is most commonly used in its place
let is for when you wanna define a variable that can change values, and const is ofc for a var thats value never changes
ahh gotcha thanks
In basic terms, You can redefine the value of a variable using the let keyword, const you can't do such.
man everytime I use any other language I just love python more and more
kekw
Excuse me, I want to ask. Why if someone tags me, it doesn't show up in history mentions. In fact, all roles do not appear only a few.
skill issue
try restarting discord
I've been in and out of Discord. I've also reinstalled discord. I've also tried logging out and logging back in.
Still same
6k is nothing for some ppl
So, is it not logged in because of history mentions due to too many pings?
This should be in the history mentions
maybe the 6903 pings are starting a war with each other trying to be the first in your mentions list
whats the best way to keep a user logged in?
and how do i make a "global" variable" that could be access from any file??
umm
// global.js
module.exports = variable
// every_file.js
const variable = require("global.js");
globals.foo = "value"

what is globals
foo // "value"
window for node?
they said every file
Yes
wouldn't you have to redeclare it
no
lemme try
Sjsjsbsbsbs
frappajappajooza
It's technically not a variable
You just use foo
I think doing foo = "bar" also works, without any keyword
eh const const = (k, v) => window[k] = v;
so i wouldn't have to get the globals object?
how about i just use esbuild with auto imports
and pipe the data to npx node
i just import everything from db.js so i don't have to reconnect mongo for every file
not really that hard
Which one worked btw
global
and what
like
global.idk = () => stinky===me
Although it's a bad practice since it could collide with a variable with the same name

tru
require(`./db.js`)
const chalk = require(`chalk`)
global.success = (str) => {
console.log(chalk.green(str))
}
global.failed = (str) => {
console.log(chalk.red(str))
}
global.warning = (str) => {
console.log(chalk.orange(str))
}
this is what i was planning to use for the global variable
does that mean i cant use .fineOneAndUpdate?
is there a way to get our bots to auto accept friend requests? if the bot is friends will it be able to DM the user even if they have this disabled?
with bots there isn't such a concept such as friends
that's rude
racist
when the bots become aware discord will be sorry
so i need to ask the user to enable direct messages if i want to send them a DM
shucks
whats the best way to keep a user logged in?
localSotrage / session / cookies
yos
Hello.
Today I'm trying to send a attachment with interaction.reply function but he send me one error and i ask if someone can help me for fix this ?
Thanks you!
Error:
/moontest/node_modules/discord.js/src/util/DataResolver.js:125
throw new TypeError('REQ_RESOURCE_TYPE');
^
TypeError [REQ_RESOURCE_TYPE]: The resource must be a string, Buffer or a valid file stream.
at Function.resolveFile (/moontest/node_modules/discord.js/src/util/DataResolver.js:125:11)
at Function.resolveFile (/moontest/node_modules/discord.js/src/structures/MessagePayload.js:240:41)
at /moontest/node_modules/discord.js/src/structures/MessagePayload.js:205:85
at Array.map (<anonymous>)
at MessagePayload.resolveFiles (/moontest/node_modules/discord.js/src/structures/MessagePayload.js:205:56)
at CommandInteraction.reply (/moontest/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:97:64)
at Object.exports.run (/moontest/commands/Images/avatar.js:24:22)
at Query.onResult (/moontest/events/interactionCreate.js:28:41)
at /node_modules/mysql2/lib/commands/query.js:72:16
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
[Symbol(code)]: 'REQ_RESOURCE_TYPE'```
I think i donāt use correct syntax?
Then check this out
https://www.section.io/engineering-education/session-management-in-nodejs-using-expressjs-and-express-session/
thx! ill look into this

where did you define "attachment" ?
line 23
Dosen't attachment take a file path / url / uri ?
No, as you can see I am getting the user's avatar from the discord API? Therefore, I use the MessageAttachment () function to get it
<>.send({
files: [{
attachment: 'entire/path/to/file.jpg',
name: 'file.jpg'
}]
})
This is from the docs
yes but i generate by discord
You can just put the avatar url
If you don't
then do it like this
files: [
attachment
]
@earnest phoenix
same, nothing appears
void only
i was passing ephemeral on false and it's working š
thx u bro
was looking at some old code from my data structures class...holy shit this gave my eyes cancer just looking at it 
i wish i never saw that
do anybody know "Restler"?
its like a requesting app for apis for mobile
I actually wanted to learn database integration in discord.py, does anyone have a link to any docs I can go through?
nvm
how do i delete a cookie in expressjs?
app.get("/test",(req,res)=>{
console.log("hi")
res.clearCookie("hello")
console.log(req.cookies)
//es.cookie("hello","hi").status(200).send("lol")
})
req.cookies should be an empty object {}
It is probably clearing the cookie, just not mutating the req object
ah
res is response, req is request
clearing cookies from res, means they will not be sent in your response
doesnt remove them from the received request
Anyone know how to set buildpack on Heroku?
I'm installing Quart and I need to set it to Python
app.get("/login",validToken,(req,res))
validToken:
async function validToken(req,res){
res.send("test")
}
you cant set headers after they are sent
How do you make it so a SLASH command that has a "@ user" field added can access all users?
Like for example, in a channel that only staff can see, you could use the dyno /avatar @ user for ppl who cant even see the channel, how do you do this?
so slash command for specfic channels?
not really, Ive made a ticket like system where one of the commands is an adduser command, where itd then add another user to the ticket, but how do i make it so u can @ the user if they cant see the channel?
example:
my bot
Set the options type to 6
U need to click on the user 
Cuz user is a optional parameter and u need to hit tab or click on it to highlight it and use it
my bot doesnt list the user if they cant see the channel, but dyno can, how do i fix this?
The option is not selected
cant click on it cause it doesnt even show up
Click on user
ok
You can also press tab
^
is there a way i can make it where if you just type smt like
/ticket create
itll create it and not require the user
and if u type
/ticket create
and add a space at the end itll then auto require the user
You can make user optional
i currently have
im just trying to find if theres a way i can make it optional if u just type "/ticket create" and then required if you type "/ticket create ", like as soon as u add the space to the end it then auto selects the user option
you can make user the first option, I donāt think the pressing space thing is an option but tab would work
Uh.
Why can't a bot edit a message that was sent a year ago?
.. and the error makes no sense.
best question is: why would a bot edit a message that was sent a year ago?

could be a pinned message
or a message in an announcement channel or something like that
Edit: resolved.
@bright thorn you're trying to install a package from github but you don't have git installed
Just wondering, but there is a weird issue with my bot. When I leave it running overnight via console, I get an error that the bot canāt connect to Discord or that handshake failed (donāt have the error right now cause Iām out). Any ideas on a fix for this?
Also the bot does stop completely/crashes.
(The bot is hosted on a raspberry pi)
Discord became aware of covid and rejected the handshake
lol
Can anyone help me and tell me how to create a webhook in channel and send with it everytime?
const botname = client.user.username;
await Channel?.createWebhook(botname, {
avatar: client.user.displayAvatarURL({ format: 'png', dynamic: true, size: 128 })
})
.then(webhook => Promise.all([webhook.send({ embeds: [DeletedLog] }), webhook]))
.then(([_, webhook]) => webhook.delete())
.catch(() => {});
Jaheeek!
const webhooks = await channel.fetchWebhooks();
const webhook = webhooks.first();
How can i make the bot fetch the webhook he create ?
{"client_id": ["Value \"undefined\" is not snowflake."]}
I get this error if I want to put like process.env.REACT_APP_CLIENT_ID in my React App
I see this error on my page not in the console
Hi
There is something i have been trying to do
whenever a certain Exception is raised when calling functions in a class
i want to call another function which solves that error in python
lemme give you some example
def some_function():
try:
# do_something
except Exception:
some_other_function()
i want to do this globally for a class
everyone use udp
Hello
Is there a way to like, check if the reaction from a message has been removed by a bot or by the user itself?
wat library u use?
discord.js
reaction removals don't appear on audit logs
Yeah there's collector.on('remove' (reaction, user) event handler but I need to check if the reaction was removed by a bot or by the user itself
:skull: issue
no worries lol
@opaque fern
@ebon pulsar no ads
š„ŗ
So where i do
Not here
have you actually asked anything?
How to verify our own bot
Ok

it was a choose one question

Ok
š

Guilded > *
ayy, using * as all
Ofc
almost forgot that worked
speaking up to normies has to be like that
guildead
guildalive

the #MakeYourOwnDiscordChallenge
anyone who uses OVH?
I've used them before
The CPU wasn't good enough. Only 1 vCore for the lowest tier. 2GB of ram and 200GB ssd is a good starter VPS. I had multiple OVH instances, but then I moved to 1 Contabo VPS
anything is better than heroku
haha knew it
I actually have enough in Heroku
the problem is the updates, have to commit shit on GitHub and a full restart takes almost 2 minutes
I mean, that'll be no faster with your own machine
not unless you know how to setup a full CI workflow
but that'll still probably take the same time
You'll want to overspec a bit so that you have some room to grow if you intend to grow large. If you use any of the popular libs like discord.js and don't practice efficient memory management, then you'll want more ram. I still want more ram anyways despite my bot only taking 175MB at 4.6K guilds
yeah, it's like a drug
wanting better even if near perfection was already achieved š
I have plenty to spare 
although I really wanna change this dedi
but
transferring everything over is gonna be pain
anyways, my bot isn't a big thing
I've got plenty of room
on my machine it starts up very fast
like 2 to 4 seconds after hitting ts-node index
yeah but you're not having to re-clone the repo, build the container and then deploy
Ts-node on prod

not compiling and pushing to prod 
but doesn't the VPS let you manage files?
yeah, but thats a real bad habbit
in real time like your pc?
use docker, and save yourself a bunch of pain

if you say pm2 tim

you're gonna get a 
all my homies fuck their machines raw
real men use screen/tmux
raw, on action deployment
bad deploy? Just restore the vps insert buff doge
idk how to configure all that crap so /shrug
time to go to work. Later
my bot only weighs 114 MB (not counting node_modules)
excluding db?
db is in Firebase
if I count everything aside from the pics and node modules it's just 1 MB
maybe I should start compressing the pics 
literally pointless doing that
yeah, it'll only reduce about 10%
images are already compressed, your space savings are generally very very very small
not even 10%
some pics actually compress to 70% without losing quality
when i use git pull it tells me my project is already up to date but it is not, how do i fix this?
you'd be better off just lossy encoding or a webp encoder setup to customise it
but in reality, 113MB isnt really much
ikr
but some day it'll be 500 MB I'm afraid
unless the designer stops making content xD
at that moment the designer will have to be me xD
then store them on some other server and just do links to the images
could
thats what I do with Crunchy when managing hundreds of gigabytes of images
but I know for sure it's faster reading just the file
mmm you'd be suprised
š
for images bellow 1MB storing them on a database tends to be faster than the normal filesystem (also able to make better use of caching)
also, if you're using this with a bot, then it's generally slower / less scalable for you because you're uploading it every time.

if you're uploading the original images every time, just upload them once somewhere and link them
if you're using them for backgrounds and stuff on canvas, keep them loaded in memory
use lust because lust is good and yes
ads
we be speed
but yes lust is good and yes
\o/
exactly
when i use git pull it tells me my project is already up to date but it is not, how do i fix this?
have you actually committed the changes
and pushed those changes
to the right branch
yes
@drowsy crag we got it here as well
How to embed this
function menuselection(menu) {
switch(menu.values[0]) {
case "Option 1": menu.reply.send("Moderation Cmd -: ```$lock, $unlock, $ban, $kick, $unban```", true)
break;
How to add embed command in it
message.channel.send({embeds[embed]}}
Where i want to add this line
menu.reply line
All you have to do is change your message to embed.
How to put playing
Invite Cater bot in our status?
function menuselection(menu) {
switch(menu.values[0]) {
case "Option 1": menu.reply.send("Moderation Cmd -: ```$lock, $unlock, $ban, $kick, $unban```", true)
break;
case "Option 2":
menu.reply.send("the reply for option 2", true)
break;
case "Option 3":
menu.reply.send("the reply for option 3", true)
break;
}
}
@earnest phoenix full code is this
As i said just change to embed message you sent
And its better to edit message sending new one doesnt seem good
@earnest phoenix actually can i share replit multiplier link coz i cant identify
Can anyone help me make this memory efficient?
/**
* @param {number[]} heights
* @return {number}
*/
const largestRectangleArea = (heights) => {
const getChains = (arr) => {
const toReturn = [];
for (let i = 0; i < arr.length; i++) {
for (let j = arr.length; j > i; j--) {
toReturn.push(arr.slice(i, j))
}
}
return toReturn;
}
const getSmallest = (arr) => {
return Math.min(...arr)
}
const getMagic = (arr) => {
return getSmallest(arr) * arr.length;
}
return getMagic(getChains(heights).sort((a, b) => getMagic(b) - getMagic(a))[0]);
}```
Because a very long input is making the js v8 engine go crazy
and crash in runtime
This is the input š¤£
why tho
Because I gotta solve this https://leetcode.com/problems/largest-rectangle-in-histogram/description/
and this very specific input is a part of the program test
what a weird puzzle
My code is working except for these eternity long arrays
js probably optimises this but I recommend moving functions outside of functions first of all
I assume those array values are long lived hence why they aren't getting garbage collected
would run the code on my own to play around with things but not on computer
idk why but my code returns 0
any ways you could think of to reduce the array size?
const len = arr.length:
for (let i=0; i < len; ...) {
for (let j = len; ...) {
}
I'm not exactly a big person on those unrealistic puzzle questions lmao
I haven't checked out the exact puzzle details but if you're going to be storing huge amounts of things in arrays you should either increase memory usage by node (isn't ideal) but the best solution is to well not use so many elements
Got a workaround... but this is the next input š¦
I wanna solve this
/**
* @param {number[]} heights
* @return {number}
*/
const largestRectangleArea = (heights) => {
const getChains = (arr) => {
const toReturn = [];
for (let i = 0; i < arr.length; i++) {
for (let j = arr.length; j > i; j--) {
toReturn.push(arr.slice(i, j))
}
}
return toReturn;
}
const getSmallest = (arr) => {
return Math.min(...arr)
}
const getMagic = (arr) => {
return getSmallest(arr) * arr.length;
}
const checkEqual = (arr) => {
return arr.every((item, index) => {
return item === arr[0]
});
}
if (checkEqual(heights)) {
return heights.length * heights[0];
}
return getMagic(getChains(heights).sort((a, b) => getMagic(b) - getMagic(a))[0]);
}```
My code till now... might help you
Successfully crashed vsc when I pasted the array...
Got a way... not to save in array... but to process it when generated
Wait I'm so confused, why is the output of [2, 1, 2] 3
fuck
Ok since ur solving ill not post the answer here
is there a width limit for the rectangle?
otherwise isnt the largest rectangle most likely gonna be 1 height N width?
2021-09-08T18:37:16.841144+00:00 app[Worker.1]: var status = mentionedMember.presence.status;
2021-09-08T18:37:16.841145+00:00 app[Worker.1]: ^
2021-09-08T18:37:16.841146+00:00 app[Worker.1]:
2021-09-08T18:37:16.841147+00:00 app[Worker.1]: TypeError: Cannot read properties of null (reading 'status')
If the user is offline
Good evening,
does anyone know how I can post the total number of servers in my bot? By adding the number of servers on each shard
Hii
Is it normal for the bot to be offline every once in a while?
I'm hosted it in repl.it and uptimerobot
And i selected interval 5 minutes
i thought repl.it wasn't supported anymore
i'd be surprised
check your code too to see if there are any errors
Can i host it on glitch ?
It's online 12 hours after 12 hours it will be offline for 5 minutes
It's normal ?
Ummm .. I'll try it
np

man this is by far the most useless restriction I've ever come across
lol
top.gg supports sending the count from individual shards
so you dont need to count them yourself, as long as you send the shard ids in the request
Yes I just saw, I had to post manually the number of server ^^
Thanks
ha! no scam anchors inside other anchors, no steam nitro ads! 
how do I delete something from a collection? For example the collection named "test
client.test.delete(key)
Does this work?
<Member>.roles
Hey guys is it possible to host my discord bot on an old machine that runs on windows 7? If yes then how? Cause the only way i know to start my bot right now is by doing node . In vscode but is this even possible in windows 7?
Wait really?
probably
Will it run?
Oooo
Imma do that
How do i fire up my bot from node though? Rn i just do it from the terminal in vscode
You'd open your command prompt in the bot directory then run the command
That's what you're doing when you're in vscode
How can i make it so my bot also works with mention as prefix. Its has prefix which is . and i want it so it also works like botMention``command
if(!message.content.toLowerCase().startsWith(dbPrefix)) return
const args = message.content.slice(dbPrefix.length).split(/ +/g);
const command = args.shift()?.toLowerCase()
if(!command) return
// if(!command || commands.has(command) || aliases.get(command)) return
const cmd = commands.get(command) || aliases.get(command)
if(!cmd) return console.log(`Command not found or Disabled`)
try {
await cmd.run({ client, message, args })
} catch (error) {
console.log(error)
}
You can check if the message starts with a mention of your bot (<@...>)
And since the prefix is separated from the command by a space, you don't need to slice by the prefix length.
Instead just break it up by spaces (remove .slice(...)) and .shift() out the first arg (which will be the mention or prefix)
i made one too, give me a sample input and the answer to see if i get the correct output
did you end up doing it?
How can i like when if i am going to send in channel
message.channel.send({ content: 'test' })
message.channel.send({ content: 'test2' })
message.channel.send({ content: 'test3' })
How i set timeout for each message
And if the message is in event too
Do you want to wait for X amount of seconds before sending another message
Yes like if bot will send a message and it need to send another one it wait 5s then send it like that
well you could just use setTimeout
What if the message in event ?
that will work ?
It will be only one message
I tried it but my solution wasn't right
Then you could consider pushing your messages on to a queue and execute them in order
I don't know how to do this :/
e.g.
let op = [];
on("message", (msg) => {
op.push(() => msg.channel.send("yeah"));
})
setInterval(() => op.shift()?.(), 5000);
This is a basic example that just pushes the operation to send a message into op and calls it later.
Oh thx
though I personally don't recommend it
because that's going to be a global queue
but if that's what you want go ahead
ah, i made one but i need something bigger with a known answer to test it (also wanted to compare performance xd)
But that what i need for ratelimit right ?
For webhook
Your library should handle rate limits for you
I am using webhooks to send logs so yea bot gets ratelimit
just ask your question pls
I need help fixing my command to deploy slash commands globally cause it didnt deploy globally I found out recently
I'm trying to add a role to an user, but I get the error that .add is undefined. What's the correct code for this/what am I doing wrong?
var role = message.member.guild.roles.cache.find(role => role.id === "885269051125932113");
let mention = message.mentions.users.first();
console.log(mention.member);
if (!mention) {
message.reply("Please mention an user!");
} else {
mention.roles.add(role);
mention.roles.remove("877244655866093638");
}
Error:
mention.roles.add(role) TypeError: Cannot read property 'add' of undefined.
Youāre getting a user object
User objects donāt have roles
Get the member object of the mentioned user instead
* Required Modules
*/
const { Client, Intents, Collection } = require("discord.js"),
client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS] }),
{ readdirSync } = require("fs"),
{ prefix, token, color } = require("./settings.json"),
{ REST } = require('@discordjs/rest'),
{ Routes } = require('discord-api-types/v9');
/**
* Ready event
*/
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
// Place your client and guild ids here
const clientId = '123456789012345678';
const guildId = '876543210987654321';
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
const rest = new REST({ version: '9' }).setToken(token);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationCommands(clientId),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
client.login(token)``` where am I messing up 
well where are you
in index
trying to global deploy
where do I get clientid and guildid
my id?
nvm
dumb question
where is guild ID tho
Guild id is the id of the guild you want to deploy your commands to
so do I remove that if wanna do global or?
Global commands take about an hour to register, Iād recommend using guild commands as those are instant if youāre testing
how do I deploy global?
Not sure, I donāt use djs+Iām typing one handed on mobile rn so I canāt look into it
client.application.commands
Use the app command manager to register/edit/delete (global) commands
Take a look at the methods, itās self explaining
Examples are documented as well
And yeah keep in mind it can take up to one hour until they are deployed in any guild
@boreal iron
* Required Modules
*/
const { Client, Intents, Collection } = require("discord.js"),
client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS] }),
{ readdirSync } = require("fs"),
{ prefix, token, color } = require("./settings.json"),
{ REST } = require('@discordjs/rest'),
{ Routes } = require('discord-api-types/v9');
/**
* Ready event
*/
client.on("ready", () => console.log(`[ ${client.user.username} ] : Connected to Discord!`))
client.commands = new Collection()
client.color = color
/**
* Load all the available commands
*/
for (let dir of readdirSync("./commands/")) {
let commands = readdirSync(`./commands/${dir}/`).filter(file => file.endsWith(".js"));
for (let file of commands) {
const command = require(`./commands/${dir}/${file}`)
command.category = dir
if (!command.data) continue;
client.commands.set(file.replace(".js", ""), command)
}
}
/**
* Message Event
*/
client.on("messageCreate", async (message) => {
if (!message.guild || message.author.bot) return;
if (message.content.startsWith("!deploy")) {
if (message.author.id !== "450634297871695896") return message.channel.send(`āļø | This command can only be used by server owner.`)
const rest = new REST({ version: '9' }).setToken(token);
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationCommands(clientId),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
return message.channel.send("ā
| Slash commands will be deployed soon..")
}
})
/**
* Interaction Event
*/
client.on("interactionCreate", async (interaction) => {
if (!interaction.isCommand()) return;
await interaction.deferReply().catch(err => { })
const { commandName } = interaction;
const command = client.commands.get(commandName)
if (!command) return interaction.followUp("Unknown Command: Can not find this command in bot.")
.catch(console.warn)
if (command.category === "nsfw" && !interaction.channel.nsfw) return interaction.followUp("This command is restricted to nsfw channels.")
try {
if (command) await command.run(client, interaction)
} catch (err) {
console.log(err)
return interaction.followUp(`Something went wrong while executing the command.`)
}
})
client.login(token)``` is the original code used
what do I change in that
Iām drivingā¦
You will have to create your own command handler being able to register commands or edit them if your local command files have changed
Pushing your commands over and over again is useless API spam
is that what its doing?
The docs I mentioned are explaining well how to use the create method to register commands or set etc
Stop driving while on your phone fake 
this is the index file btw
Yeah expected it to be the index 
do I keep await rest.put( Routes.applicationCommands(clientId), { body: commands }, ); as client id or put as my bots ID?
Thatās the reason I said:
Pushing your commands over and over again is useless API spam
Not needed as djs has inbuilt methods to push them
* Required Modules
*/
const { Client, Intents, Collection } = require("discord.js"),
client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS] }),
{ readdirSync } = require("fs"),
{ prefix, token, color } = require("./settings.json"),
{ REST } = require('@discordjs/rest'),
{ Routes } = require('discord-api-types/v9');
/**
* Ready event
*/
client.on("ready", () => console.log(`[ ${client.user.username} ] : Connected to Discord!`))
client.commands = new Collection()
client.color = color
/**
* Load all the available commands
*/
guild.commands.fetch()
.then(commands => console.log(`Fetched ${commands.size} commands`))
.catch(console.error);
/**
* Message Event
*/
client.on("messageCreate", async (message) => {
if (!message.guild || message.author.bot) return;
if (message.content.startsWith("!deploy")) {
if (message.author.id !== "603411112901214218") return message.channel.send(`āļø | This command can only be used by server owner.`)
const rest = new REST({ version: '9' }).setToken(token);
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationCommands(clientId),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
return message.channel.send(":white_check_mark: | Slash commands will be deployed soon..")
}
})
/**
* Interaction Event
*/
client.on("interactionCreate", async (interaction) => {
if (!interaction.isCommand()) return;
await interaction.deferReply().catch(err => { })
const { commandName } = interaction;
const command = client.commands.get(commandName)
if (!command) return interaction.followUp("Unknown Command: Can not find this command in bot.")
.catch(console.warn)
if (command.category === "nsfw" && !interaction.channel.nsfw) return interaction.followUp("This command is restricted to nsfw channels.")
try {
if (command) await command.run(client, interaction)
} catch (err) {
console.log(err)
return interaction.followUp(`Something went wrong while executing the command.`)
}
})
client.login(token)```
Thatās the site I posted a few mins ago
what I have so far
to be honest I paid for having my bot made, think could help me find out when home


Will take a few hours and will be early in the morning anyways which means I will jump into my bed
so that a yes or no
Actually I canāt as Iām only available while driving lol
I mean building a proper command handler isnāt hard
yes but the fact he did it completely different means something is up
How can I make that if check to run only after the for loop from above is over?
donāt get me wrong but you canāt expect to drive a car without knowing how to do so
Im willing to pay depending on price if you willing to help
Wouldnāt be an issue if I only had time to do so lol

Expecting to be back at PC at Saturday
Maybe Friday evening
Just be patient maybe someone else can help u
08.09 18:30:27 [PebbleHost Loader] ----------------------------------------------
08.09 18:30:27 [Bot] Startup /index.js:22
08.09 18:30:27 [Bot] Startup guild.commands.fetch()
08.09 18:30:27 [Bot] Startup ^
08.09 18:30:27 [Bot] Startup ReferenceError: guild is not defined
08.09 18:30:27 [Bot] Startup at Object.<anonymous> (/index.js:22:1)
08.09 18:30:27 [Bot] Startup at Module._compile (node:internal/modules/cjs/loader:1101:14)
08.09 18:30:27 [Bot] Startup at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
08.09 18:30:27 [Bot] Startup at Module.load (node:internal/modules/cjs/loader:981:32)
08.09 18:30:27 [Bot] Startup at Function.Module._load (node:internal/modules/cjs/loader:822:12)
08.09 18:30:27 [Bot] Startup at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
08.09 18:30:27 [Bot] Startup at node:internal/main/run_main_module:17:47
08.09 18:30:28 [PebbleHost] Server shut down (running)
08.09 18:30:28 [PebbleHost] Server stopped```
after I editted
Itās also worth to search the web for some examples how to do so to get back into coding
I would, but my brain is slowly deteriorating from my brain damage (the memory portion)
frontal lobe damage
started to get worse after I was 17
had since birth
brb
slash commands are only working in my server 
Ive already paid like 40 on this bot lmao
for development

This is precisely why you donāt hire shady devs for money
Please ping when replying
I can provide more info if needed
Thatās a simplified version of how I handle it
How am I supposed to know if shady
Can you help?
Wut?
Huh how can I help you?
Trying to be more detailed⦠will take a while to write
- create a function to load your local command files into a map for example
- create another function to actually load the commands (register/edit/delete)
The function should do;
- fetch the global commands registered by Discord
- loop through thr frtched commands
- check if your local command map HAS the registered command
If yes, then check it the name, description or options match each other, if not update the command
If no, delete the registered command as it doesnāt exist locally anymore
- if the loops of registered commands end but thr there are still local commands missing, then register them
These two loops (fetched registered commands & locally loaded ones) are merched together
.addSubcommand(subcommand =>
subcommand
.setName("user")
.setDescription("send you all informations off a user.")
.addUserOption(option => option.setName("target".setDescription("lol"))))
why does i get this error? (btw first time in djs 13 i like 12 more)
Attention - English might be drunk
you mean cuz my text? (sry im german)
you have "target".setDescription("lol")
strings dont have a setDescription function

easily fixable by hacking the string prototype :^)
Or write the object by hand instead of using this ugly methods
Less characters to write, no need to fucking import the ugly messageembed class and no confusion
If you wanna add multiple fields then call the method multiple times
Or just use new lines
i wanna make it look like that (my old v12 bot)
.addField()
.addField()
ā¦
Those are just like breaks
\n
why does it not work in 13?
Because v12 had a damn weird compatibility of supporting basically not well formatted inputs
Anyway just add the line breaks and remove the brackets of the array




