#development
1 messages · Page 1987 of 1
so if a member dont join a thread, they can't see thread in the channels list either, right?
hmm ok
active threads also show up when you hover over a channel afaik
i'm not sure if you need to join them or not for them to appear
good morning indeed
yes i dont see people using it much.
additionally, if the thread is private you can invite a member
so can the bot too invite peoples?
probably
although I'd not rely on private threads
since discord was dumb enough to make it boost-only
no one
i agree
Is there a word you call discord.js buttons and dropdowns?
Is there like an overall word or sentence for it?
interactions
Interactions? Sure!
i know this is probably self explanatory but i ran npm i discord.js
that downloaded d.js v12 didnt it
cuz theirs a file in node modules calld discord-12
It got changed to npm ui discord.js
?
Just try it
Uninstalls a package
ah
so how do i get v13? though
is it just npm i discord.js@13.14.0
or did it just install both or somthing for compatability
there isnt v13.14.0
i cant remember the version number of the top of my head i just remember there being a 4 in it
To install a specific version run npm i PACKAGE@VERSION
yee
Or to install the latest stable one, npm i package@latest
Just try npm i discord.js@latest
Ay!
wait shouldn't it be ui instead of i
unknown command: "ui"
ah
how?
I learned mongodb from CodeLyon, and he uses it like this
oh I didn't use await (well, quick.db don't need it so I never had to put async/await)
async await is very important for db calls
already exists in esm modules and deno
Yes
learning from videos is a baaaaad thing
not because their content, but because they don't get updated
fireship
fireship?
awesome yt channel
fireship isn't much better
all they try to do is give you an introductory into what some tool is about
the issue is getting the habit of learning from videos instead of documentation/actual searching
I wrote the documentation after a video on English writing
code most people here clearly don't learn best from videos
wha....
callback(new error_1.MongoServerError(document));
^
MongoServerError: The field 'ownedCards' must be an array but is of type object in document {_id: ObjectId('621679876f6cc343063b8670')}
at MessageStream.messageHandler (/workspace/node_modules/mongodb/lib/cmap/connection.js:462:30)
at MessageStream.emit (node:events:520:28)
at processIncomingData (/workspace/node_modules/mongodb/lib/cmap/message_stream.js:108:16)
at MessageStream._write (/workspace/node_modules/mongodb/lib/cmap/message_stream.js:28:9)
at writeOrBuffer (node:internal/streams/writable:389:12)
at _write (node:internal/streams/writable:330:10)
at MessageStream.Writable.write (node:internal/streams/writable:334:10)
at Socket.ondata (node:internal/streams/readable:754:22)
at Socket.emit (node:events:520:28)
at addChunk (node:internal/streams/readable:315:12) {
ok: 0,
code: 2,
codeName: 'BadValue'
}
not always there'll be a video for your exact case, that's why so many "programmers" don't even know how to use stackoverflow
I didn't save it as array tho
and end up with a ton of boilerplate without knowing what it's doing
yeah
The field 'ownedCards' must be an array
You can learn from watching videos, but not the kind of "follow the tutorial" we see from #development. Presentations, talks, and slides introducing or building on software are a great way to learn new things imo
Fireship does that but not to the extent of other videos I've seen
yeah because he wants you to buy fireship pro
lmao
$25 a month yikes
why that error?
with 25 a month you buy a metric ton of courses
idk if mongo has this, but did u refactor the current data and structure?
refactor?
like, if it previously accepted Arrays it'll expect Arrays
for the subject of the courses and how many he has, isn't worth it to me personally
even if u changed the type, u still need to change the current content
else it'll conflict
I've seen some others, like jetbrains academy also charge a lot but have a lot more and spread out the subjects
nope
It's like this from the start
I'll delete all the mongo data and check
anyways there's no data at all
same
then idk, check the docs
ok
I think push is the one
giving error
await profileModel.findOneAndUpdate({userID: message.author.id}, {$push: {ownedCards: {rarity: [`${chsa}`]}, all: [`${chsa}`]}});
How can i add a function to message so when i do message.embed() it sends embed message
That can be done by modifying the prototype, but that would lead to prototype pollution, which is not a good idea, just make a helper method and use it
It's not really a big deal unless ur making a library though. discord.js would never create a message.embed function
my message create funtion
still though, not a great practice to modify the prototype
helper function is just the way to go
pass in your message object to the helper function and your embed
yeah
One message removed from a suspended account.
Just wanna use protoype to learn
you could extend the message class couldn't you? Or does djs prevent that
Not only could it cause prototype pollution, but you wouldn't really need that method on every message instance, if you modify the prototype, that method will also be present on every message instance, which can increase the memory usage unexpectedly
Although this wasn't really a problem in the older discord.js versions where extendable structures existed
Eeeeh I doubt you would see a change. V8 definitely makes sure to optimize that.
Can i get example?
would be a lot more painful anyway
Although our V8 engine still initializes a marker for unused or "overused" object slots, because it has to help the GC and stuff, it's a hassle to optimize that anyway
async function embed(message, embed) {
return await message.reply({embeds: [embed]});
}
and just call it like any other function
Calling this function everytime with message comes like death for me
That's the nature of helper methods, especially external ones
modifying the internal lib of djs also sounds like death waiting to happen but up to you
You could replace the Message class from the require.cache
no prototype pollution then
I had client.send(type, text) it didnt cause any problem
Oh because it was it
Not prototype
discord.js internally uses that class, so replacing it that way wouldn't replace it in the library, which is the reason why the users who used extendable structures were mad, as they were removed entirely
it's like 6 extra characters
it still would
AFAIK require.cache is global. Replacing the Message before discord.js uses it will do it
please just use the function
Okay
You can't replace it before discord.js uses it, since it imports everything it needs before anything in your code is executed, which would make it impossible to replace it in the context of the library, although the only thing you can to is to modify the library yourself, which is not a good idea
The helper method is the best option 
even with the prototype or function it's not going to compose well
you can only reply and only with an embed. nothing more, nothing less. want to include some message content, or an attachment? too bad
You could, but what I mean is that the code in the libraries are already executed in a partial way before you even import them, which is what makes it impossible to replace those internally used classes, which reminds me of that guy
"Ah yes, kill all the bots that use extendable structures properly"
discord.js™️
const nFilter = (int) => int.message.id === n.id && int.user.id === interaction.member.id;
const nCollector = interaction.channel.createMessageComponentCollector({ nFilter, max: 1, componentType: 'BUTTON', time: 30000 });
How to check each value in the nFilter example check the value of int.message.id, n.id int.user.id and interaction.member.id? I want to check each value of those?
I tried debugging, didn't know what I was doing, honestly.
I JUST REALISED, it's filter: nFilter. 
Well, problem solved.
the best way to check it is to make a Set and check if it's size is 1
wait how do you want to check them exactly? You want to check if all of them are the same
Did I do something incorrect?
did ya search in SO or in the docs?
usually everything can be found there
gives this
ohhh
wait
I have to put it without [] right?
I have it like this
the whole thing is in brackets, so it's an object
I can't really help u with mongo
and very few here are experient with it
well hi
what you need help with
@earnest phoenix ^
It's a mongoose action.
if (code913) throw new IDFKException();
I think it's rarity: { $each: ['my stuff'] }
Yes so it says insert each item from this array into "rarity"
Because it's an array type it has to use it.
oh
will give it a try
rarity is an array
something like this?
await profileModel.findOneAndUpdate({userID: message.author.id}, {$push: {ownedCards: {rarity: {$each: [`${chsa}`]}}, all: chsa}});
in the dark of the night, I wonder
is mongo really easier than sql?
idk, it feels very messy and confusing
nah it's not, i'm just coding shorter so it looks messy
for many people, it probably is initially
that's the thing, like, people say it's easier, but from everything I see around it feels extremely confusing
I can't even imagine maintaining a big database transaction
Python is hard for me
for me too
not that kind of confusing
like, it's the kind of thing you write once and never maintains
cuz u need a specific mindset to understand what and why you did something
that's what u think
it looks cool when using it but the coding is extremely bad
I mean, eventually it'll start to break apart
bots are services, and services are never truly finished
well i've maintained many commands but it's inefficient
yeah
$each didn't work
it says ownedCards is marked as array in document
the document
you need to wrap the rarity with push
not the owned cards
oh
what did I do to you mongodb....
/workspace/node_modules/mongodb/lib/cmap/connection.js:462
callback(new error_1.MongoServerError(document));
^
MongoServerError: The dollar ($) prefixed field '$push' in 'ownedCards.$push' is not valid for storage.
at MessageStream.messageHandler (/workspace/node_modules/mongodb/lib/cmap/connection.js:462:30)
at MessageStream.emit (node:events:520:28)
at processIncomingData (/workspace/node_modules/mongodb/lib/cmap/message_stream.js:108:16)
at MessageStream._write (/workspace/node_modules/mongodb/lib/cmap/message_stream.js:28:9)
at writeOrBuffer (node:internal/streams/writable:389:12)
at _write (node:internal/streams/writable:330:10)
at MessageStream.Writable.write (node:internal/streams/writable:334:10)
at Socket.ondata (node:internal/streams/readable:754:22)
at Socket.emit (node:events:520:28)
at addChunk (node:internal/streams/readable:315:12) {
ok: 0,
code: 52,
codeName: 'DollarPrefixedFieldName'
}
Can a thread be permanent like text channels?
You can have it active or archived in a text channel
does anyone here know how to delete a file with aws-sdk
aws-sdk pls delete file with magick kthxbai
or even better, how can i bulk make everything public in a do space
Threads are temporary text channels, so they can't stay unarchived on their own forever, the maximum duration a thread can stay unarchived on it's own is 1 week, although staff members can unarchive the channel when it gets archived, so you can for example give your bot the permission to unarchive threads and unarchive that thread when it gets archived
don't joke about that stuff here tim
we trust you so much we can't tell the difference between you helping and trolling
On the off chance someone here has experience with this, I would greatly appreciate any help/advice I can get on fixing this repo: https://github.com/Jwaffled/MathExpressionParser/tree/master/WaffleCompiler/Core
My current issue is that I got the greater than and less than tokens to work properly, but it crashes when I try to use other operators, because I structured it to return a bool and such, which isn't correct
a good troll is indistinguishable from advice
jester's privilege 😉
I have to cache for the parent of a channel that I want to create?
GuildChannelManager.create(nomeServer, [{ parent: categoria }]);```
I have some HTTP server for a personal site I'd like to host. Where should I look?
no you just need to use it correctly
remove the []
only graphs?
{ parent: categoria }
vercel or netlify or github pages
categoria Is basically the category ID
categore 👀
my brain is dying
Somebody here to check a link for me for Discord scam?
Can’t inspect the website on mobile
well i can if you explain me what you need
bruh what... wtf is that lol
anyone?
What kind of nitro beggar checks scams to see if they're legit
I'm getting troubles about passing a costant from a file.js to file1.js
I get them as undefined
are both files requireing each other?
syntax errors..
30+ mins changing stuff
await profileModel.findOneAndUpdate({userID: message.author.id}, { $push: {`ownerCards.$.${rarity}`: {$each: [chsa]}, $push: {all: {$each: [chsa]}}}});
what's wrong
"Property Assignment expected" in ownerCards.$
',' expected
Declaration or statement expected
ok
oh yeah
it solved all
tysm
the check doesn't work
let check = await profileData.all;
let truemsg;
if (check.includes(chsaa)) {
check is an array
profileData is the user's profileData got from the db
ok
whats the point of archived threads if people can still message there?
so the thread is marked as inactive and is harder to find
e.g. using threads for questions and archiving them so people can still look at them and reply if they have something to say
this appears
and how long can a thread be? Is there any limitation?
depends on the server
servers with boosts can set the time longer
the longest is a week
shortest is a day
with some points in between
no, I mean the message counts.
ah, no message limit
we can hv a thread forever right
theoretically yes
I hv used threads like this to better organize channels,
and let members join their interest of threads
oo
I know what ur thinking, don't try sending a message every X minutes to keep it alive
btw, u can just use those characters if u want that tree-like organization
y though?
¯_(ツ)_/¯
api abuse
i keep almost putting the middle finger instead of the pointer finger reaction
├ Do
├ It
├ Like
└ This
may be, but those hash icons will still show on channels
yea
well, yea
because threads are not optimized for that.
you might as well create a regular channel for that
yeah, thx
but doing it once a day/week wont hurt. Then?
does discord notices the pattern?
I'd not chance it
as klay said, threads aren't really meant to be kept open for too long, there HAS to be a reason they didn't just add an unlimited time option
if you keep it open for too long, they will notice it eventually
it doesn't push anything ```js
await profileModel.findOneAndUpdate({userID: message.author.id}, { $push: {[ownerCards.$.${rarity}]: {$each: [${chsa}]}, $push: {all: {$each: [chsa]}}}});
no errors
are you sure you want to do
{
$push: {
[`ownerCards.$.${rarity}`]: {
$each: [`${chsa}`]
},
$push: {
all: {
$each: [chsa]
}
}
}
}
``` and not ```js
{
$push: {
[`ownerCards.$.${rarity}`]: {
$each: [`${chsa}`]
},
all: {
$each: [chsa]
}
}
}
``` ?
i mean, it doesnt make sense to have one push inside another
then show the error?
syntax error
"Property assignment expected"
oh wait no
my code was the problem
will try and see
it didn't update ownedCards.rarity but did update all
rarity is the card's rarity so it adds in the correct rarity
You're supposed to do:
{
$push: {
[`ownerCards.${rarity}`]: {
$each: [`${chsa}`]
},
all: {
$each: [chsa]
}
}
}
yep changed it for that
and same
well, will check "unstringing" chsa in the ownedCards like in all
Is it not pushing the specified element to the ownerCards.<rarity> array?
yeah that
oops
ownedCards...
Typos are the worst
will check now
hey guys i have an error: java.java:104:23: error: local variable voornaamtext is accessed from within inner class; needs to be declared final```java
String addon1 = voornaamtext.getText();
public void actionPerformed(ActionEvent e) {
String addon1 = voornaamtext.getText();
String addon2 = achternaamtext.getText();
String addon3 = tussenvoegseltext.getText();
String naam = addon1 + " " + addon3 + " " + addon2;
String addon4 = straattext.getText();
String addon5 = huistext.getText();
String straat = addon4 + " " + addon5;
String addon6 = plaatstext.getText();
String addon7 = postcodetext.getText().concat(letterstext.getText());
String postcode = addon6 + " " + addon7;
System.out.println(naam + "\n" + straat + "\n" + postcode);
System.out.println(straat);
System.out.println(postcode);
voornaamtext.setText("");
achternaamtext.setText("");
tussenvoegseltext.setText("");
straattext.setText("");
huistext.setText("");
plaatstext.setText("");
postcodetext.setText("");
letterstext.setText("");
verstuurbutton.setEnabled(false);
JTextArea textvak = new JTextArea();
textvak.setBounds(20,240,240,140);
frame.add(textvak);
textvak.setText(naam + "\n" + straat + "\n" + postcode);
}
tysm worked
oh god
wtf
Java probably doesn't want nested classes to be able to access variables from their parent classes
i.e.
class A {
int b = 5;
class C {
public C(int d) {
System.out.println(b + d);
}
}
}
So the compiler is asking you to mark b as final so it can't be modified.
how can I pick 10 of an array?
instead of array[0] and so on that picks 1 i want to pick multiple (10)
ten of what? apples? oranges? the first ten? last 10? a random sample of ten?
the first 10
they can
but why the error
because you can't change the value of a variable to be passed to an inner class (reference issues)
first of all, you don't need to declare the whole thing, just use e -> { code here } for events (or any other functional interface)
second, define a new variable to hold the value to be passed to the inner class
you can also use an anonymous class or an object array
or an atomic variable
in your case, you could do ```java
YourClass voornaamtext = ...;
voornaamtext = ...; // changing the variable value
YourClass finalVoornaam = voornaamtext;
public void actionPerformed(ActionEvent e) {
String addon1 = finalVoornaam.getText(); // this wont error
}
or for atomic: ```java
AtomicReference<YourClass> voornaamtext = new AtomicReference(...);
voornaamtext.set(...); // changing the atomic value
public void actionPerformed(ActionEvent e) {
String addon1 = voornaamtext.get().getText(); // this wont error
}
private Node ParseGreaterThanLessThan()
{
var lhs = ParseAddSubtract();
while (true)
{
Func<double, double, bool> compareOp = null;
if (_tokenizer.Token == Token.GreaterThan)
{
compareOp = (a, b) => a > b;
} else if (_tokenizer.Token == Token.LessThan)
{
compareOp = (a, b) => a < b;
} else if (_tokenizer.Token == Token.Equals)
{
compareOp = (a, b) => a == b;
}
if (compareOp == null)
{
return lhs;
}
_tokenizer.NextToken();
var rhs = ParseAddSubtract();
lhs = new NodeBinary(lhs, rhs, compareOp);
}
}
public abstract class Node
{
public abstract double Eval(IContext ctx);
}
``` I have this setup for a function, and I need Eval to return bool when the the last generic arg of `Func` is bool, but I have no idea how to accomplish that
That last lhs = new NodeBinary() line doesn't work because NodeBinary takes a Func<double, double, double> and not a Func<double, double, bool>
What are you doing anyways 🤔
math parsing
Maybe have the function return either 0 or 1 instead a boolean?
or use an enum to store all possible values, not sure if java has those
oh
because I use this for calling it ```cs
public Node ParseExpression()
{
var expr = ParseGreaterThanLessThan();
if (_tokenizer.Token != Token.Eof)
{
throw new SyntaxError($"Unexpected characters at end of expression");
}
return expr;
}
I think I might need a complete redesign
But I'm not sure where to start tbh
Well If I were u I'd group all binary expressions into one to make parsing a lot easier
and I wouldn't create functions while parsing
What would be perfect is if I could inherit from the Node class but override the type signature to be bool
create an AST first and then run it
But I don't believe that's possible sadly
I'll look into ASTs, I've heard of them but I don't have any idea how to create one or what it is
It's basically a tree structure which represents the program
Oh that's similar to what I'm doing
looking at this, if it's right then that's what I'm doing pretty much
so for example a + b would be
BooleanExpression {
op: "+",
left: Identifier { name: "a" },
right: Identifier { name: "b" }
}
yeah that's it
but I see that you're also creating the functions while parsing
yeah
It'd be better to create the full AST first then traverse it
look into recursive descent parsers
So i have two interface types here
does anyone know if you can overload interfaces so if ACK = Failure, error response properties become available
pp
You'd need something like
interface PayPalBaseNVPResponse {
ACK: 'Success';
}
interface PayPalNVPErrorResponse {
ACK: 'Failure';
L_SHORTMESSAGE0: string;
L_ERRORCODE0: string;
}
export type PayPalNVPResponse = PayPalBaseNVPResponse | PayPalNVPErrorResponse;
When you check if ACK === 'Failure', it will type narrow down to the error response interface
that works beautifully thanks a bunch!
Any idea how to make fs to edit a file without permissions?
i want to edit /etc/hostapd/hostapd.conf but just root can edit it
and for some reason my user can’t be root
become root and give your user edit permissions
how can i do that?
do you have root access to the machine?
or is it a hosting service that does not give you root access?
It's just my raspberry pi, i already fixed it tho, thanks
Does fs corrupt files or something? Because for some reason when i modify the hostapd.conf file the service stops working, then it works again only if i delete it and paste everything again manually.
Fs is...iffy, to say the least
You need to exert extreme caution when writing to files to not have 2 operations running at once
puts the prefix as space for some reason
const filter2 = (reaction, user) => {
return (msg) => msg.author.id === messageCreate.author.id
}
let prefix = await messageCreate.channel.awaitMessages({ filter3, max: 1, errors: ["time"], time: 30000 })
if (!prefix.first())
return client.sendTime(
messageCreate.channel,
"You took too long to respond."
);
prefix = prefix.first();
prefix = prefix.content;
await client.database.guild.set(messageCreate.guild.id, {
prefix: prefix,
DJ: GuildDB.DJ,
});
that filter wont work
first of all you define filter2 but use filter3
second, you cant do that
{ filter3 } is a shortcut for { filter3: filter3 } but filter3 is not a valid option
here filter3
const filter3 = (reaction, user) => {
return user.id === messageCreate.author.id &&
["1️⃣", "2️⃣"].includes(reaction.emoji.name);
};
this won't work anymore
let emoji = await ConfigMessage.awaitReactions(
(reaction, user) =>
user.id === messageCreate.author.id &&
["1️⃣", "2️⃣"].includes(reaction.emoji.name),
{ max: 1, errors: ["time"], time: 30000 }
)
I'm trying to use this https://discordjs.guide/popular-topics/reactions.html#listening-for-reactions-on-old-messages to fix it
thats a completely different thing, it has nothing to do with the code you showed about prefixes
prefix used to = let prefix = await messageCreate.channel.awaitMessages( (msg) => msg.author.id === messageCreate.author.id, { max: 1, time: 30000, errors: ["time"] } );
that makes more sense
then your problem is somewhere else
umm
what is messageCreate?
run: async (client, messageCreate, args, { GuildDB }) => {
you'll need to show more code then
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
sendTime(Channel, Error) {
let embed = new MessageEmbed()
.setDescription(Error);
Channel.send({ embeds: [embed]});
}
you need to physically put \n
multi line strings in code don't translate to new lines being inserted into the string
let me test quickly
iirc
"this\
will\
turn\
into\
this"
// "this will turn into this"
it doesn't matter for \
that's not what they doing?
isn't this what their expected result is?
not sure if the extra indentations were what caused the error
Are you using \?
bruh
yeah
remove the indentation
or strip them using a function
cause that code looks ugly
@lucid prawnread this again ^
ok
I can use let emoji = await ConfigMessage.awaitReactions( (reaction, user) => user.id === messageCreate.author.id && ["1️⃣", "2️⃣"].includes(reaction.emoji.name), { max: 1, errors: ["time"], time: 30000 } ).
instead of filter3
@tasks.loop(minutes=10.0)
async def update_stats():
print("run")
plt.clf()
plt.cla()
y = []
s = int(time.time())
for i in range(36):
a = s - 3600
b = a - 3600
count = 0
for g in client.guilds:
if f"u{g.id}.json" not in os.listdir("data"):
continue
with open(f"u{g.id}.json", "r") as f:
data = json.load(f)
for t in data['blocked']:
if int(t) > b and int(t) <= a:
count += 1
count += i
y.append(count)
x = [i for i in range(1, 37)]
print(x, y)
#x.reverse()
# setup axis labels
ax1 = plt.gca()
ax1.set_ylabel('URLs')
ax1.set_xlabel('hours ago')
# plot
plt.xticks(rotation=17)
ax1.spines['bottom'].set_color('white')
ax1.spines['top'].set_color('white')
ax1.spines['right'].set_color('white')
ax1.spines['left'].set_color('white')
ax1.tick_params(axis='x', colors='white')
ax1.tick_params(axis='y', colors='white')
ax1.yaxis.label.set_color('white')
ax1.xaxis.label.set_color('white')
ax1.title.set_color('white')
ax1.set_facecolor((0.0, 0.0, 0.0))
plt.plot(x,y, label='Blocked')
# beautify the x-labels
plt.gcf().autofmt_xdate()
plt.gca().set_xlim(36, 1)
#plt.gca().set_xlim(1, 11)
plt.fill_between(x, y, 0,
facecolor="blue", # The fill color
color='blue', # The outline color
alpha=0.2) # Transparency of the fill
plt.legend(labelcolor='white', facecolor='black')
plt.suptitle('---Recent Player Counts---', color='white')
plt.gcf().set_facecolor('xkcd:black')
#plt.show()
n = "graph.png"
plt.savefig(n)
this is not working, It does not give me any errors
any ideas
you're still not providing a valid filter
look
this has nothing to do with filters
anyone have a idea for me?
{
filter: your filter here,
max: your max here,
time: your time here,
...etc
}
you are not giving it a filter option
{ emojiFilter } would become { emojiFilter: emojiFilter } instead of { filter: emojiFilter }
{ filter3 } is not the same as { filter }
{ () => {} } is not the same as { filter }
the name filter has to be the correct name
why do they even have so many filters for the same thing
so you have to do either { filter } or { filter: filter3 } or { filter: () => {} }
understood?
yes I'm dumb sorry
see the difference?
oh ok
messageCreate.channel.awaitMessages({ filter: filter2, max: 1, errors: ["time"], time: 30000 })
yes?
yes
yay
gg
const { ShardingManager } = require('discord.js');
const manager = new ShardingManager('./bot.js', {
totalShards: "auto",
token: process.env['Token'],
spawnTimeout: -1,
respawn: true
});
manager.on("shardCreate", shard => {
shard.on('reconnecting', () => {
console.log(`Reconnecting shard: [${shard.id}]`);
});
shard.on('spawn', () => {
console.log(`Spawned shard: [${shard.id}]`);
});
shard.on('ready', () => {
console.log(` Shard [${shard.id}] is ready`);
});
shard.on('death', () => {
console.log(`Died shard: [${shard.id}]`);
});
shard.on('error', (error) => {
console.error(error)
})
});
manager.spawn(manager.totalShards, 5500, -1).catch(e => console.log(e))
looks right to me
this normal?
Error [SHARDING_READY_DIED]: Shard 0's process exited before its Client became ready.
theree should be an error above
Died shard: [0]
Spawned shard: [0]
Error [SHARDING_READY_DIED]: Shard 0's process exited before its Client became ready.
at Shard.onDeath (/home/runner/mika/node_modules/discord.js/src/sharding/Shard.js:161:16)
at Object.onceWrapper (node:events:510:26)
at Shard.emit (node:events:402:35)
at Shard._handleExit (/home/runner/mika/node_modules/discord.js/src/sharding/Shard.js:399:10)
at ChildProcess.emit (node:events:390:28)
at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12) {
[Symbol(code)]: 'SHARDING_READY_DIED'
}
does it run fine without shard
with it and without
?
The bot still runs with that error
whats the actual error
Shard 0's process exited before its Client became ready.
why would that appear without shard
yes
when I use shards
I get this error
Shard 0's process exited before its Client became ready.
the manager hsa something wrong then hold on
i just have manager.spawn();
might be why
yes
reject(new Error('SHARDING_READY_TIMEOUT', this.id));
^
Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready.
how to create htmlImageElement in nodejs
I want to make a channel where sending messages is not allowed, instead members have to create threads to start discussion on any topic.
Is it possible?
I tried but then, threads inherit channel permissions. and messages cant be send their too
You need to send a message in order to start a thread
why can i not here the audio from the bot?
module.exports = {
name: "play",
aliases: ["pl"],
usage: "play <song>",
description: "play a song",
run: async (client, message, args) => {
let stream = ytdl("https://www.youtube.com/watch?v=QnL5P0tFkwM", {
filter: "audioonly",
opusEncoded: true,
encoderArgs: ['-af', 'bass=g=10,dynaudnorm=f=200']
});
const { joinVoiceChannel, createAudioPlayer, createAudioResource, StreamType, setVolume, NoSubscriberBehavior } = require('@discordjs/voice');
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Play,
},
});
const connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
})
const resource = createAudioResource(stream, {
inputType: StreamType.Opus,
inlineVolume: true
});
await player.play(resource)
resource.volume.setVolume(100);
await console.log(resource)
await connection.subscribe(player)
}
};```
it logs this;
yoo.. another custom css doubt.. im trying to use some shortcut ways to enhance my css.. why aint this block quote thingy working
"theoretically" it shld look like this
im a newbie in css so pls help
btw do you know how to update this? like.. idk it aint updating
Please stop using ytdl for music bots
Maybe it's the
- padding top + padding bottom.
- height of the blockquote.
- css being css.
reason?
Youtube tos
and what could be the alternatives?
Soundcloud
If a thread gets auto archived, and then a mod unarchive it back. Does the members who have joined the thread get reset?
Do they have to join again?
Is there something similar for soundcloud or Spotify
Soundcloud has an api
wasn't it always against the tos just they weren't really acting on it before 💀
they really won't care or do anything unless you grow to the size of rythm but yeah
yeah im gonna grow my bot and cry myself to sleep when it gets banned
you cant even use spotify
come on now lets be realistic 
So I have to redefin the top and bottom paddings? Hmm
But y ain't it dotted
how does postgres differ from mysql/mariadb
ive never used postgres
apparently its "better" according to the community
better according to the community is why i hate npm
postgres is better because it's not oracle
i dont see why people hate oracle so much but anyways mariadb is oss
without oracle we wouldnt have a lot of the tools we have today
with pg you can generate test data with
insert into your_table
SELECT generate_series(1,100000), 'some value' as column_name
I cry every day working on auctions because it doesn't have this lol
oh no sim cards use java how could we live without java!
over 2 billion devices
You forgot 2020
0 devices running java
just 3
@spark flint why is there just a picture of minified javascript
blame @royal portal

Refused to load the image 'https://scontent-bos3-1.cdninstagram.com/thissupposedtobeaimagelink' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.
what causes that error ?
i tried googling it and having a hard time understanding what it even means
bruh can you really do that
do what lol
block people from using your images via security policies
no-
yes
lol no im making a insta-dp like website n my website is blocking from using images from 3rd party sources
using=loading
got it lol
it started happening after i installed flask-talisman cuz i want users to go to https:// by default
n apparently it goes the security polices too n which i didnt know how to use/work with
omfg why is it so hard to use chakra.ui dynamic sizes with next.js images this shit is taking me hours
html width overrides css
there's nothing you can do because next image has 3 divs forcing your image to be the same size
I used the useBreakpointValue hook but that's still not really working properly
show code
thats probably sun
Can I forward a message starting from the message.id?
wdym forward
store the id of a message for send it in a different momento to another chat
if the message still exists, yes
Tim is the person that makes me still believe in humanity
how I search for the message?
messageId = id;
how can I search for the message?
fetch the message by id
discord.js usually first looks in the cache to check if the object is there
if you set force to true discord.js will ignore the cache
ok, then still don't get how to pass the id as an arg
I don’t know the specific method because I use detritus but I know it’s possible
neither do I
lmao
.then(message => console.log(message.content))
.catch(console.error);```
anyone know sql
INSERT INTO guilds (id, logs)
VALUES ($1, $2)
ON CONFLICT (id)
DO UPDATE SET logs = $2
is this sql query valid?
im just trying to upsert
$1 and $2 will be populated with actual values in the code
cuz I use node postgres
askin cuz copilot made this for me
If I have a JSON object like this:
{
'Hello, this has spaces.': 'i have spaces to',
'ur mom: 'idk'
}
How would I access those objects? I can't necessarily do:
someObject.Hello, this has spaces;
in what language
JavaScript
object['key']
ah. ty
what lib are you using link?
im using postgresql
it runs atop the native pg lib
I want to use raw sql
bruh
I don't wanna use an orm
just help me with my question or don't
don't tell me to go use another lib
ur not helping with that
just a suggestion 
will you help me or not
do interaction button's functions go inactive some time later?
i'm doing a registeration system with buttons on a different system that gives user the role (interaction user of command) but i'm worried about that
like do i need to store a database for that
I don't think they do
How can i check that user vote to my bot in top gg?
no its not auto incrementing
since im storing discord guild ids
It does but the site cache will show the result sometimes hours later
is it ok if I do
UPDATE bot SET scanned = scanned + 1
without using the WHERE clause
I only have a single column in the table
or do I need to do
UPDATE bot SET scanned = scanned + 1
WHERE id = 1
It's fine without the WHERE, technically.
It'll just increment all the values in the scanned column, even though you only have one row.
Me personally, if you have a table with only one row, it probably doesn't make sense to include it in your database.
Well I just store statistics for my bot there
console log user
btw, only guild members have a kick method
so yeah, you need to get the guild member instead of the user in order to kick them
I use a single row for updating a secret key that expires every week after its generated. Only time ill use a single rowed table
Help me on my bot: can someone tell me how to find a REST API for my bot?
What kind of REST API.
requirements:
must be a REST API
well if you're nihilistic you may be interested in hypixel's api
It's those image links That you can put text or stuff on them just by editing the link. , I can show you what it is if you want
My bot script is BDscript
here
When I tried to use an api, it gave error
try visiting that url in your browser
check the endpoint url
do i need to enable something in the discord developer portal dashboard to allow my bot to play audio inside voice channels?
can i just do this then?
const client = new discord.Client({
intents: allIntents
});```
uhhhhh
workspace/commands/useful/battle.js:212
await profileModel.findOneAndUpdate({ userID: message.author.id }, { $inc: { gold: coinamount } });
^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1032:15)
at Module._compile (node:internal/modules/cjs/loader:1067:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at /workspace/handlers/command.js:20:24
at Array.forEach (<anonymous>)
there IS async
const Discord = module.require("discord.js");
const memberModel = require('../../database/welcome')
module.exports = {
name: "suggest",
description: "Anything",
run : async (client, message, args) => {
const msg = args.join(" ");
if (!msg) {
return message.channel.send("Add a suggestion please");
}
const data = await memberModel.findOne({
GuildID: message.guild.id,
})
if (!data) return;
const guild = await client.guilds.cache.get(data.GuildID);
const schannel = await guild.channels.cache.get(data.ChannelID)
await message.channel.send(
`${message.author}, Your Suggestion has been submitted!`
);
const embed = new Discord.MessageEmbed()
.setTitle("New Suggestion")
.setDescription(`${msg}`)
.setFooter(`Suggested by ${message.author.tag}`)
.setColor("RANDOM");
console.log(schannel)
schannel.send({ embeds: [embed] })
.then(function (message, str) {
message.react(":suggestionyes:946209266044370964");
message.react(":suggestionx:946208906521231420");
})
.catch(function () {});
},
};```
schannel is undefined
oh ok
Where’s your code causing the error? Can’t see it in the screenshot
it's in the end
and nope, I didn't close async by mistake abov
e
it's in the end too
Well it’s so poorly formatted I can’t see if it’s wrapped in another (sync) function
idk what happened with this code but since some time, I can't use await in it
It your database code wrapped in any other function? Like foreach etc?
ok
That’s why proper indentation is so important
so js setTimeout(function () { to ```js
setTimeout(function async () {
lol
now I know
async function
ok
Alright
TypeError: interaction.reply is not a function
at Object.run (/home/runner/mika/commands/Music/bassboost.js:80:32)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
I use return client.sendTime(interaction, for message to be a embed
is the interaction an instance of CommandInteraction
bruh
when finally activated bot after some weeks
they keys are repeating and giving error
I made it unique
and made the bot to firstly check if there's already a key
well key or document
can someone tell me why my bot fails to play an audio-live?
like, you run the command, after 5 seconds the audio stops
well, any errors?
Is it possible to change what the title says for an alert() function in a website? I want it to say something else for the title (rn it says: Website says:)
Well, thats my endpoint url script.
https://some-random-api.ml/canvas/youtube-comment/$username/$message/$authorAvatar
check the documentation
that's not how you provide parameters
use https://some-random-api.ml/canvas/youtube-comment?username=$username&var=$var...
pog. Telk's api
IT WORKED
THANK YOU SO MUCH

const channel = interaction.channel;
const collector = channel.createMessageComponentCollector(options);
collector.on('collect', async i => {
// randomly throws unknown interaction error
await i.update({content:"stuff"});
});
I keep randomly getting unknown interaction errors from code like this. is this incorrect? are failed interaction errors common?
note ~ works like 95% of the time
does it happen instantly or after 3s?
no idea, but the only errors in my log are from unknown interactions lol
@lyric mountain you're the java wizard, you got any idea what causes this? fixed it, it's something weird about package access level not working with multiple classloaders
for reference, AstPrinter and Expr.Visitor are both in the same package and have no access specifiers, so it should work in theory
interaction events have a time limit of 3 seconds before they expire
sometimes due to network slowness or slowness in the discord api, you receive them already expired or too close to expiration to respond to them in time
this is very common issue when using interaction events via gateway
I'm able to set a timeout for the message collector though, which is the 'interaction' in this case, no?
wdym?
like, the button collector event from the collector is the 'interaction' in the cast of the i.update... no?
the interaction would be the button interaction
you have to respond within 3s or defer it
you might want to defer it first
but im able to set the timeout for the collector, doesnt that also set the timeout for the interactions potential response time?
like, if i make 'wait_s' set to 60, it waits 60 seconds for the interaction
no
You’re mixing things, once a client has pressed your button you need to respond to API within 3s
the 3 seconds time limit is discord waiting for you
it has nothing to do with your code
ooooooohhhhhhhhh
Doesn’t matter if you reply with a message or defer the response but you have to respond to the API with something within 3s
if discord does not receive any response using that interaction's unique token, it deletes the interaction from their end
Or the interaction fails
ok ok im following now. so then how would i defer the reply within the collectors on collect event?
just i.deferReply() ?
If you respond to the interaction by telling the API you will respond later (deferring) you will have time to respond with actual message
But you still have to confirm to the API once an interaction happens you’re there and yes you received the event
however, that will not make a difference if you're already using .update() immediately anyway
I mean if haven’t any async calls and can respond within the 3s there’s literally no need to defer the response
see this is whats got me i think. all my collector does is literally update the interaction right away. surely... if thats all its doing, it wouldnt be able to simply defer the reply either. cause isnt it just a case of my network is too slow in receiving the interaction data to actually respond to it?
wouldnt that also happen with the defer?
exactly
yea, i've set it to deferReply and use editReply atm, seems to work the same, but idk if it will stop the occasional error
you have 3 options, none of them are a real solution
- complain to discord
- use interactions via webhook instead of gateway
- check the interaction timestamp and ignore it if its older than 2-3s
I mean you should get rid of the collector anyways
Interactions have an unique ID you can work with to indentify the action and handle it’s request
this is intreaguing.
no idea how i'd change how interactions are processed in that way (#2)
Any user initiated interaction will trigger the interaction event
interactionCreate i assume?
so basically your suggesting i could remove the collector for the interaction, and then process the interactions similar to how i would with commands?
ie: do some processing there to handle them..
Correct, just by building a handler for actions other than commands, too
In the same you’re dealing with slash commands
I’m dealing with it like with slash commands handling the interactions by checking if the unique ID exists in my interaction files and if so execute it’s code
I’ve got literally two handlers checking if an interaction is a command or something else then dealing with it like you do with commands
you need a webserver and a domain name with ssl
create a route or subdomain, setup a webserver, and add the url to your discord dev page
once you add the url there, you will no longer receive interactionCreate events, you will only receive them via the webserver
i might look into that and see how easy im able to switch things over to it lol
that'd be better for responding to interactions long after they are sent too i guess
also, the webserver needs to comply will all the discord security crap
so you probably want to use a library for it
i made one myself, but there are others
interesting. so I can basically get my server to get send the interaction webhook data which i can then process from there?
yes
that seems like more work than its worth tbh
if your bot needs features that can only work via gateway, its not worth it
but if your bot could be moved to interaction-only, it is worth it
At the end it doesn’t require an active gateway connection but still needs to be able to receive the requests - it needs to be online anyways
getting rid of the gateway altogether means byebye shards, byebye disconnections and reconections, byebye bloat from events you dont need
Only for a certain size of the bot tbh
If you already use a library anyway
I've literally just rewrote a crap ton of code to support sharding
~ side note: easier than i thought 🙂
well then its not worth it
but interactions via websocket are this iffy
one thing you could try tho, but its still uncertain, is to have a separate bot with 0 intents
iffy?
to receive interactions only
iffy - uncertain
Oh ok
Yee ty driving 
unfortunately going a webhook route isnt viable for this particular bot 😦
I will be looking into that though for sure. probably make a small tester bot to check it all out
I remember someone in here had setup aws lambdas or something to handle his interactions
that seemed pretty nifty 😛
The advantage of a gateway connection is that event usually don’t disappear
While an offline webserver can not deal with requests and they are probably gone forever
wouldnt be too hard to write a dedicated node app to handle all the webhooks.
nope, you can scale with node cluster of pm2 cluster for example
i honestly dont think my site has been offline other than when i've caused it 😄
and you dont need any special configuration to scale like you do with shards
docker tim, DOCKER! 😛
Well the size isn’t an issue but your backend has to respond to the request
tbh, i was wondering how i'm going to handle multiple shards with docker
like, i dont have it setup to spawn a new container for each shard
one docker or multiple dockers?
i use docker-compose to combine multiple docker services under one roof
one docker per shard seems like a very bad idea
better than the former
should be fine for upto say 3-4 shards, but yea
one docker instance can run multiple prcesses and use multiple cores, can it not?
tbf my bot has like 3 servers.. so... not exactly a worry atm 😄
yes
so then there is no need for mroe than one
just make one docker that runs multiple things
as long as im willing to scale vertically and get more ram etc, yea one container could potentially handle it all at scale
you wont need to scale horizontally unless you hit millions of guilds
Still one powerful container wastes less resources on itself than lots of containers
there is also some library to improve the sharding for d.js
it makes some shards internal and spawns threads and combines methods or something
yes
another well known library that does it is kurasuta
although its known to have some issues at times
a single node process can only ever use 1 cpu core, however a single shard will never fully use one core
so you want to get as many shards under one process as a single core can handle
yea that makes sense
~ I've actually been slowly optimizing various parts of the overall dockerized framework that I use. Hoping to eventually release it for others to use if they wanted 🙂
Tbh I don’t think there a perfect way to start at 0 and being able to scale to something larger without optimizing or recoding things
Whatever you try to plan or do at some point you expectations are blown up which requires a rethink of your infrastructure and ecosystem and therefore some work, recode etc
I have all of my gateway cons on one thread and my bot logic on another
very responsive
yea this is very true. often as things scale the logic that was once fine becomes a bottleneck and refactors are a must.
there is a certain point in scaling that you have to give up on performance and focus on stability instead
At least cost and efficiency wise
for example, nothing beats a local database, but if you get into horizontal scaling then you will want to exchange performance for availability, adding several databases over the wire, increasing latency and decreasing performance, but retaining availability
yea, tbh at my current scale i just want stability. i can easily scale up later as required
focusing too much on availability too early can give you bad performance, focusing too much on performance can give you availability issues at a certain point
(`Link`)
nice link
wait i got a question lol
im sending it
(`Link`)
How do I make that text a working hyperlink?
ok thank you!
[website](http://url "some tooltip text")
try doing <link> in normal message
like this is my actual code so far:
client.channels.cache.get(global.config.server.channels.log).send(`Test`)
ohh, would it work in a normal messagr tho?
or only embeds
only embeds
only embeds
try
oh they want to set a name?
oh thats fine, I just want to send the link somehow
without the link turning into an embed
http >:o
they add the s for me anyway
(`<link>http://google.com/</link`)
https:google.com is also valid 🤯
no
I can't use the link tag in the `
does this work for suppressing the embeds also?
make it send what i sent lol
or is it used for something els
channel.send(`<${url}>`)
ohhh ok that helps, tysm!
idk test it
its a new thing
so like this?
(`Test \n <${https://universe
list.xyz/server/${guild.id}/}>`
use ${} if you have a variable
if you have raw text you dont need ${}
😂 the bot list person again
so like this?
(`Test \n <${{https://universe
list.xyz/server/${guild.id}/}>`
wait ima also try that
no
No
Nvm
I'm so lost 😦
do you understand what string templates are?
yes, i know what they are
well you are not using them correctly
bcs I don't understand it so much 😅
they are just literals enclosed in backticks
const variable = "abc";
`some text here plus some ${variable} here`;
= some text here plus some abc here
...
man this is so confusing 😭
Look at Tim’s example
not to give you the answer, but this is how it should be:
const site = `https://universelist.xyz/server/${guild.id}`;
const link = `[Test](${site} "This will take you to some website")`;
Hey Tim was there a specific reason you literally told me to fuck off with my process dilemma?
Doesn’t it make sense to be able to reload the code structure without reconnecting to the gateway and database?
^^
you risk dirtying your process with bad data basically, leaving things unclosed, memory uncleansed, etc
if your code structure is as simple as attaching a required file to an event listener, then yes its easy to do, thats how people reload commands
but if you have anything more complex than that, then its suddenly much much harder
Hmm so it requires not to mix the child’s data with the master in order to get rid of any data and memory when killing the child process
client.on("message", message => {
if (message.author.bot) return false;
if (message.author.id !== "YourID") { // Example Condition
message.suppressEmbeds(true) // Removes all embeds from the message.
}
})
found this on stackoverflow. Could I do something like this?
in my start file
try
you want to remove all embeds from all messages that people send in your server?
Yeah I mean that’s what I’m doing with my commands, too which creates the possibility to reload them
I was thinking about to move the event listers to modules, too in order to be able to reload them completely
But I was actually looking for another way to reload the entire (child) process without the need to reconnect anything
no
then dont it
if the child holds the connection, you cannot restart the child without severing the connection. you can attempt to reload every single thing inside the child without touching the connection
what you can do tho, if this is a discord connection, is to store the session data and resume
however you will still lose all your memory and cache
hey btw, ty @quartz kindle && @boreal iron . our earlier discussion was quite insightful 🙂
That’s why the idea was that the master holds any active connection and the child sends its request to the master which will handle it
the connection itself or only the connection information?
because if the master holds the connections itself, then its the same as running internal sharding, all shards in the same process
The master holds the connections not only the information
The child will emit an event the master receives with the data the master processes
Like an event listener for database calls, gateway calls whatever
Or sharing the instances with the child process like I would share (pass) my arguments to a module
But that goes a little bit off my experience here
That’s why I’m asking
so you have all the discord shards in the master process?
and the children are just the command/event processors?
Talking about sharding?
i'll shard you

btw i finished my websocket benchmarks, and detritus is the slowest lib lul
No I’m not talking about discord shards at all
Should I use discord.js itself for sharding, or do I use some other library for this?
only database connections? then you're fine
leave the connections in the master
Discord-hybrid-Sharding I think it’s called
👍
The first package which combines Sharding Manager & Internal Sharding to save a lot of ressources. Latest version: 1.4.5, last published: 9 days ago. Start using discord-hybrid-sharding in your project by running npm i discord-hybrid-sharding. There are no other projects in the npm registry using discord-hybrid-sharding.
That’s what I use
Yeah and the gateway connection for now just for now as I’m never require sharding anyways
then youre fine
Alright
your child processes should be stateless
you should be able to destroy and restart them as you wish
unless specific children can only do specific jobs
how many bot instances are you running and what is your average resource usage? if you know off hand 🙂
It’s a rewrite which isn’t completed yet so idk yet

