#development
1 messages · Page 1745 of 1
actually Im making a board game where,
each character represents a piece,
a number - total consecutive empty squares
and + and - followed by two characters, represent a square with two pieces.
I'm curious why you have a string for that
Why are you taking input this way... sounds inconvenient for players and for you
the string is to parse and populate the board. Same as fen is for chess
Why not have some kind of object/map for that is what I'm wondering
const string = 'long12+krt89df-efdhjj67nmn';
const args = [];
const everythingElse = [];
let aux = '';
for (const s in string.split(/([+\-])/)) {
if (s.startsWith("+") || s.startsWith("-"))
args.push(s);
else
aux += s;
}
for (const s in aux.split(/((\d\w)|(\w\d))/)) {
everythingElse.push(s);
}
Just use regex and chill
Chill with bad performance 
Use matchAll
Just a matter of a few milliseconds
doesn't work for me
why?
"few milliseconds" in a game where that regex runs a lot can be significant
Is he making a game?
let s in ... iterates though the keys
Its a dc game
Not fps mobo
Also your version also uses regex and splits, and 2 for loops
so it's def slower than a for loop
Regex is fassss...
Regex = 1ms
For loop = 0.07ms
Recalculate
I don't have the code for the regex example, but it's quite obvious the regex one is slower, not only is there regex, but also a reduce and every
Nevermind... he just wants an answer
Regex is fast enough, but not as fast in comparison to manual for-loops
Fast enough
Speed is important when you're making a game
Also reduce is slow?
slower than a regular for loop most of the time
"Fast enough" isn't an excuse you should be taking when you're making a game
Bro.... it will be slow if he is making a discord game unless he has less ping
We don't know what kind of a game he's making
Also, just because something is "fast enough" doesn't mean there's no reason to make it faster
plus the regex version is barely readable
If you generally apply the "fast enough" option, you're gonna have videogames in JS/Python
There are cases when performance doesn't matter as much as it does here, like, say, a cronjob that runs once in an hour or a few
hey
does anyone know why my command handler is not closing right?
i can use command !help and it will not close the command handler. It will keep on running that exact command, eventhough the event has passed
Because it's either bad or you coded it wrong
Depending on how you're using it
You're gonna have to share your code
yup
so i have a function in my bot that starts a collector on the message that has been sent:
function Interface(message, question, callback) {
var collected = false;
var closed = false;
var qMessage;
message.channel.send(question).then((msg) => {
qMessage = msg;
});
const collector = new Discord.MessageCollector(message.channel, m => m.author.id == message.author.id, {maxMatches: 1});
collector.on("collect", msg => {
collected = true;
callback(msg, qMessage);
});
collector.on("end", () => {
closed = true;
return 0;
});
setTimeout(() => {
if (closed) return;
else if (!collected) {
collector.stop("User did not give a response within 20 seconds");
qMessage.edit(`:x: <@!${message.author.id}>, the menu closed because you did not respond within 20 seconds.`);
closed = true;
callback(false);
}
}, 20000);
}```
and even if i closed the event (i messages something, so the count should be on 1), it still doesn't stop with that exact command
@rocky hearth For loop
Forgot about the numbers but oh well
final.map(x => isNaN(x) ? x : +x); instead of just final
ok I'll take this one
https://srcb.in/s4NgGBG0u2
HELLLOOOOOOOOOOOOOO
I'm back.
Why I cant filter only with the server ID'
?
if u have ignored the .env files in .gitignore, before comitting.
Then there's no way to get it back.
@rocky hearth
const start = new Date().getTime();
const string = 'long12+krt89df-efdhjj67nmn';
const args = [];
let aux = '';
let arr = string.split(/([+\-].{2})/);
for (const s of arr) {
if (s.startsWith("+") || s.startsWith("-"))
args.push(s);
else
aux += s;
}
const everythingElse = aux.match(/((?=\d)\w)+|((?=[A-z])\d)+|[A-z]+/g)
.filter(s => s)
.map(s => {
if (isNaN(s)) return s;
else return parseInt(s);
})
console.log(args);
console.log(everythingElse);
console.log(`${new Date().getTime() - start}ms`)
use performance.now for more accuracy
no
yeah you're using regex too
?
Repl isn't meant for hosting initially, but they support uptime robots and their Hacker plan allows you to leave your repl on 24/7 as well as boosting it with better machine specs
ok
it should return, a single array though, Kuhaku
And the order is important here
how much is repl hacker plan
$7/month
k
At that point you're better off just renting a VPS, though
F
yea
Starting from here how the hell I sort the data?
When I do leaderboard.get(guild_ID) it gives me always all the servers
I've tryied with leaderboard.sort((userA, userB) => userA.bank - userB.bank);
But it always console.log all the servers and not sorted by bank.
This is the code => https://srcb.in/IcObTg0kBk
hi!
sort like from the highest to the lowest?
yes
from all guilds?
just don't separate then
just a sec
only for the guild where I write the command
I tought to make the collection becoma an array
but I dont think it would work
so if you just want to get the leaderboard, i don't think you need to create a new collection.... just filter all the collections from database
const database = await <mongo schema>.find()
const guildProfiles = database.filter(x => x.serverID == message.guild.id)
//now you sort here from guildProfiles
Hii!
so I have to delete everything we made
?
wait
code is here
const database = await <mongo schema>.find()
const guildProfiles = database.filter(x => x.serverID == message.guild.id)
//now you got the array of profiles on your guild
const sorted = guildProfiles.sort((first, second) => first.bank - second.bank, 0)
//sorted.map(x => x.userID) will show you the user id from highest bank value to the lowest
I'm sorry for asking, my brain is almost totally collapsed, but I have to write only yhis code for the leaderboard?
const start = performance.now();
const string = 'long12+krt89df-efdhjj67nmn';
const args = [];
let aux = '';
let arr = string.split(/([+\-].{2})/);
for (const s of arr) {
if (s.startsWith("+") || s.startsWith("-")) {
args.push(s);
aux += "{%}"
} else
aux += s;
}
const everythingElse = aux.match(/((?=\d)\w)+|((?=[A-z])\d)+|[A-z]+|{%}/g)
.filter(s => s)
.map(s => {
if (s === "{%}") return args.shift();
else if (isNaN(s)) return s;
else return parseInt(s);
})
console.log(everythingElse);
console.log(`${performance.now() - start}ms`);
yes, because idk that you want to make a leaderboard command before
ops, sorry 😦
np
just 1ms great!
I wonder what Feud's code's performance might be? he didnt mentioned that
0.07ms on my machine
so i'm trying to figure out why i can't make my bot read commands from another file and put responses in chat
ooh, thats insane
like, i'm not getting any errors or anything, but it's also not doing anything when i type !help or !commands
Keep in mind Kuu's version is 0.51 ms on my machine
obv, you feed rocket fuel to your machine
I didn't save my code though ugh
(node:4) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body
2021-05-12T13:55:49.148675+00:00 app[Worker.1]: content: Must be 2000 or fewer in length.
OH NO, NOT AGAIN
If someone wants to write it from the screenshots feel free
what did you put on content?
do note that when I ran that code more than 1 time it started to get increasingly lower times
probably due to regex internal optimizations
content?
yes, what did you put on content so it reached > 2000 chars
where's the error came from?
content = message
RequestHandler.push (/app/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
another one?
that didn't came from node_modules
nope, another one from the stack
how I'm supposed to fix this
try send full error with the stacks
I'm Sorry, my english Is trash, can u explain in a easier way?
for example:
orange line is the error, blue is the error stacks
2021-05-12T13:55:49.148672+00:00 app[Worker.1]: (node:4) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body
2021-05-12T13:55:49.148675+00:00 app[Worker.1]: content: Must be 2000 or fewer in length.
2021-05-12T13:55:49.148677+00:00 app[Worker.1]: at RequestHandler.execute (/app/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
2021-05-12T13:55:49.148678+00:00 app[Worker.1]: at processTicksAndRejections (internal/process/task_queues.js:95:5)
2021-05-12T13:55:49.148679+00:00 app[Worker.1]: at async RequestHandler.push (/app/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
2021-05-12T13:55:49.148702+00:00 app[Worker.1]: (node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
2021-05-12T13:55:49.148727+00:00 app[Worker.1]: (node:4) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
maybe I know
Must be 2000 or fewer in length.
maybe is mecause I tryied to send It to discord
no, shorten ur message
2.000 isnt the message limit?
yep
it is the message limit
thats why
Can you guys help me what is wrong here
async def fight(ctx, user: discord.Member):
fought = user
attacker = ctx.author
if user.id == ctx.author.id:
await ctx.send("You can't fight yourself weirdo")
else:
await ctx.send(user.mention + ", " + ctx.author.mention + " has challenged you to a duel, do you accept? (Y/N)")
def check(ctx):
return fought == ctx.author and ctx.content.lower() == 'y'
try:
await client.wait_for('reaction_add', timeout=60.0, check=check)
await ctx.send("Duel invite accepted! Fight will now begin.")
fightStart = True
except asyncio.TimeoutError:
await ctx.send('Duel invite expired.')
fightStart = False
else:
await ctx.send('Duel invite declined.')
fightStart = False```
error?
wait
internal
JIT babey
JEET
does parse using regexes?
what are you measuring? :^)
but the data are not filtered by server, in the console.log I have different guildID
function parse(string) {
const len = string.length;
const res = [];
let current_str = "";
let num_str = "";
for (let i=0; i < len; i++) {
const char = string[i];
switch (char) {
case "+":
case "-":
if (current_str) {
res.push(current_str);
current_str = "";
}
if (num_str) {
res.push(+num_str);
num_str = "";
}
res.push(char + string[++i] + string[++i]);
break;
default:
if (isNaN(char)) {
if (num_str) {
res.push(+num_str);
num_str = "";
}
current_str += char;
} else {
if (current_str) {
res.push(current_str);
current_str = "";
}
num_str += char;
}
}
}
if (current_str) {
res.push(current_str);
current_str = "";
}
if (num_str) {
res.push(+num_str);
num_str = "";
}
return res;
}
Before I close the tab...
btw the code above can definitely be improved
@cinder patio can you test this on your machine? ```js
const originalString = "long12+krt89df-efdhjj67nmn";
let final = [];
for (let i = 0; i < originalString.length; i++) {
if (
i === 0
|| ["-", "+"].some(x => originalString[i] === x)
|| isNaN(final[final.length - 1]) && !isNaN(originalString[i])
|| !isNaN(final[final.length - 1]) && isNaN(originalString[i])
) {
final.push(originalString[i]); continue;
}
if (
["-", "+"].some(x => final[final.length - 1].startsWith(x)) && final[final.length - 1].length < 3
|| ["-", "+"].every(x => !final[final.length - 1].startsWith(x)) && isNaN(originalString[i]) && isNaN(final[final.length - 1])
|| !isNaN(originalString[i]) && !isNaN(final[final.length - 1])
) {
final[final.length - 1] += originalString[i]; continue;
}
final.push(originalString[i]);
}
final.map(x => isNaN(x) ? x : +x);```
@client.command()
async def fight(ctx, user: discord.Member):
fought = user
attacker = ctx.author
if user.id == ctx.author.id:
await ctx.send("You can't fight yourself weirdo")
else:
await ctx.send(user.mention + ", " + ctx.author.mention + " has challenged you to a duel, do you accept? (Y/N)")
def check(ctx):
return fought == ctx.author and ctx.content.lower() == 'y'
try:
await client.wait_for('reaction_add', timeout=60.0, check=check)
await ctx.send("Duel invite accepted! Fight will now begin.")
fightStart = True
except asyncio.TimeoutError:
await ctx.send('Duel invite expired.')
fightStart = False
else:
await ctx.send('Duel invite declined.')
fightStart = False
Error
no, that's the code
oh, right
sec
mb then
?
@cinder patio this too:```js
function parse(text) {
const args = [];
let aux = '';
let arr = text.split(/([+\-].{2})/);
for (const s of arr) {
if (s.startsWith("+") || s.startsWith("-")) {
args.push(s);
aux += "{%}"
} else
aux += s;
}
const everythingElse = aux.match(/((?=\d)\w)+|((?=[A-z])\d)+|[A-z]+|{%}/g)
.filter(s => s)
.map(s => {
if (s === "{%}") return args.shift();
else if (isNaN(s)) return s;
else return parseInt(s);
})
return everythingElse;
}
it shouldn't tho, from my logic...
it timeouted
what is the code supposed to do?
magic
nono, my bad this time, but from this sorted array how I can Output the leaderboard?
with a for?
that works 10 times?
10 times?
0.25ms
if I throw an error inside of a .then will it still be caught by the .catch?
What the hell is your specs
test more than once
I want a leaderboard of the first 10
the first call is always slower
Then it's around 0.05
@quartz kindle this all started from here
always ^
sorted.length = 10
Slice is faster than setting length
When I declare it or after?
mine gave 0.49 then oscilated between 0.06 and 0.04
after the sorted defined
Around 0.30ms
Well, anything with for loop is fast
heckin rocket fuel
good, sorted is an Array right?
yes
Mine's only with a for loop so that's probably why it's the fastest
async def fight(ctx, user: discord.Member):
fought = user
attacker = ctx.author
if user.id == ctx.author.id:
await ctx.send("You can't fight yourself weirdo")
else:
await ctx.send(user.mention + ", " + ctx.author.mention + " has challenged you to a duel, do you accept? (Y/N)")
def check(ctx):
return fought == ctx.author and ctx.content.lower() == 'y'
try:
await client.wait_for('reaction_add', timeout=60.0, check=check)
await ctx.send("Duel invite accepted! Fight will now begin.")
fightStart = True
except asyncio.TimeoutError:
await ctx.send('Duel invite expired.')
fightStart = False
else:
await ctx.send('Duel invite declined.')
fightStart = False```
and subsequent calls?
what is wrong here can you guys help me?
Around 0.10
Always 0.02 / 0.01
I bet Tim is writing his code right now
At first I got 0.1ms now I'm getting 0.10ms
what are your specs btw?
^^
that's about 5 times faster than my pc
help-
dormammu also wasn't that powerful
intel Pentium lol
the sort is crescent, how I make it decrescent?
so what to do with it?
and with what I have to repalce?
he must be writing his machine code
^
change it from (first, second) => first - second to (first, second) => second - first
reverse
not asyncio.TimeoutError so waht?
yeah I see but fon t kbnow what is wrong
fruit.water.Watermelon is not the same as fruit.Watermelon
you need to use the full path
so can yoiu write what?
no
can't wait
??????
as I see, you're touching a quite complex stuff, if you don't know what you should replace and with what you might consider delaying that command until you're ready to handle that stuff
interactive games (like duel) are not something simple
ok
this is your error
this is the except clause
you need to fix the except definition
for(let i=0; i<sorted.length; i++){
message.channel.send(sorted[i]);
}
const classifica_monete = new Discord.MessageEmbed()
.setTitle(Questa è la classifica di ${message.guild.name})
.addField(``)
message.channel.send(classifica_monete);
This could work for the output?
why are you building the embed after sending the messages?
it will throw a new error because there's nothing inside field
Check for channel also
I want to send the leaderboard Inside an embed
oh, nope it won't work
you don't need for again
.addDescription(sorted.map((user, counter) => `${counter ++ +1} | ${client.users.cache.get(user.userID)}'s bank is ${user.bank} `).join('\n'))
use map
++ +1?
I have the same question
yes?
it works well
or just remove ++
it will be counter + 1
if you're not sure
I'll trust you
hey does anyone know what the topology destroyed error in mongodb means?
And even more important, how to fix it.
it keeps on showing up when using a certain pay command
UnhandledPromiseRejectionWarning: TypeError: (intermediate value).setTitle(...).addDescription is not a function
¯\_(ツ)_/¯
hmm, eh
sorry
setDescription
my bad
np
sounds like a redundant declaration tbf
hm
so basically you increment i for the next access then add 1
not cached most probably
what?
so (i++ +1) + ' is lower than' (i + 1) will return 1 is lower than 2
I should catch the err?
nope, wait
sorted.map((user, counter) => `${counter +1} | ${client.users.cache.get(user.userID) ? client.users.cache.get(user.userID) : 'Unknown'}'s bank is ${user.bank} `).join('\n')
definitely smells trouble if you need to use i more than once in the same loop
no
it started from 0
increment add 1 to it but still returned 0, then you added +1
so it returns 1
what?
oh
use the code i've sent above
basically i++ returns the current value and increment
so subsequent accesses will get the new value
oooo, didn't know it increment the value, thx for the information
i++ is the same as i += 1 which is the same as i = i + 1
then there's ++i
which increments and return the new value
where?
^
Thanks to u all 3
the difference Is when the i change the return
i++ = return THEN increment
++i = increment THEN return
im like 90% sure ive been assigning i++ to stuff
you can, it'll just be the number before the increment
so 3++ will return 3
++3 will return 4
it's just that subsequent calls will get the incremented value, so beware with indexes and stuff
nice
this Is not possibile
have you changed the code to this?
sorry i can't help you anymore, i need to sleep. cya
goodnight, tysm for everything
In React I am importing some modules from a file and using them in my code:
import {
Operator
} from "./components.js";
export default function App() {
const [expr, setExpr] = React.useState("0");
return (<>
// use the components here
</>)
}
But when I try to use the state variable expr inside any of the components imported it says it is undefined. How do I pass local variables to components?
How do you use them
you left out the most important part
Also show how you use expr inside the component
function Operator({
children
}) {
return (
<ChakraButton
width="10px"
height="20px"
bg="gray.400"
onClick={() => !expr.endsWith(children) && setExpr(`${expr}${children}`)}>
{children}
</ChakraButton>);
};
expr is in the first parameter of the function
{ children, expr }
also very weird formatting there
state variables are passed automatically to children?
they're not?
are you maybe thinking of react context
what the heck is that
generally you shouldn't need it unless you want to pass a variable many many levels down the hierarchy
just pass expr as a prop to Operator
slight problem i use the component too many times:
<Bracket>(</Bracket><Bracket>)</Bracket> <CE /> <AC />
<Num>7</Num> <Num>8</Num> <Num>9</Num> <Operator>/</Operator>
<Num>4</Num> <Num>5</Num> <Num>6</Num> <Operator>*</Operator>
<Num>1</Num> <Num>2</Num> <Num>3</Num> <Operator>+</Operator>
<Num>0</Num> <Decimal /> <Equals /> <Operator>-</Operator>
Are you making a calculator
what about the numbers
same thing, you cannot really avoid passing expr without contexts, which imo are supper unnecessary in most cases, including here
Also I think it should be expr={expr}
I don't thin that's a shorthand
You can also do something like:
const NumWithExp = (props) => {
<Num expr={expr}>{props.children}</Num>
}
<NumWithExp>0</NumWithExp>
```\
if you're feeling really lazy
Im tryna send a message to the user when they vote
how would i do that const voteuser = vote.user voteuser.send('Thx for voting!')
This doesnt work
because the object you get from topgg isn't a djs object lol
lmao
ok ty
then get the user from your client cache an dm them
waddu mean
is there something wrong this is not loading in the page ?```html
<p style="color:cyan;">This is a multipurpose bot and the main thing is that all commands are free*🆓 This bot is easy to use bot, this bot will do giveaways 🎉, moderation 🔱, and games 🎲. Work of mee6, Caral & give away bot all in 1 and all commands are free 🔥🔥🔥</p>
<p style="color:lightblue;">The prefix is (=) and the help command is (=help)</p>
<a href="https://top.gg/bot/785328945691885608/vote">click here to vote for me !</a>
<p style="color:deeppink;">🔱 Moderation🔱 - Can warn, kick, ban, unban, create roles, give roles, and much more with easy-to-use commands.</p>
<p style="color:deeppink;">🎉 Giveaways 🎉** - can easily create give-aways even if you don't know-how, with the help of the easy-to-use commands.</p>
<p style="color:deeppink;">🎲 Games 🎲** - can play many games like rock, paper, scissors, rolling a dice, willit, truth or dare much more</p>
<p style="color:deeppink;">🆘 Deletion 🆘** - can delete links and inappropriate words. (can be disabled.)</p>
<p style="color:deeppink;">✍️ Styles ✍️** - if you want to do an announcement, you can easily complete it.EG- you can create an embed, can bold, underline, cut your sentences.</p>
<p style="color:deeppink;">➕ Math ➗** - can solve math problems (add, square, divide) you can also use decimals and raised power. (EG- =add 123.56 2.12 or =add 10e3 20e6.)</p>
<p style="color:deeppink;">😂 Memes 😂** - do you need some memes? this bot can also do this for you!</p>
<p style="color:deeppink;">📋 Poll 📋** - can also create polls.</p>
<p style="color:yellow;">Contact staff ☎️- you can suggest commands to the staff so they can add it for you (should be under the bot rules)</p>``` pls help !
jeez
like this ```js
const newuser = Client.users.fetch(usersend)
newuser.send('Thanks for voting! You recieved 25k bobux')
fetch returns a promise, you need to wait for it to resolve before you use the return value
ok so await
25k bobux for a vote is way too much bro
Why does some actions like .roles.set requires 2fa?
do I as dev need 2fa or the user ?
it only requires 2fa on the developer's account if the server has server wide 2fa enabled
uff 2fa is annoying :C
yeah imagine caring about your privacy pffft
2fa is only annoying if you don't have a phone to login with
i mean
link with a phone once and get a desktop app
authy allows that
i used the desktop app while my phone was at a repair shop
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
dart does have mixins. I want use that
One message removed from a suspended account.
One message removed from a suspended account.
to run it in browser
One message removed from a suspended account.
One message removed from a suspended account.
dart gets compiled to js in order to work in the browser
flutter is for mobile apps
One message removed from a suspended account.
flutter does convert dart code to js, I think
One message removed from a suspended account.
I don't think it does, dart can also be compiled
One message removed from a suspended account.
One message removed from a suspended account.
So it's unlikely that it gets converted to js in flutter
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
it does get, I hope so. If we use flutter to make web apps. Isnt it?
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
yeah, they say flutter is the future.
One message removed from a suspended account.
But I dont believe google. They do drop there products quickly
One message removed from a suspended account.
meh I'd rather use typescript over dart
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
How would i make this async ```js
const usersend = vote.user.id
const newuser = await Client.users.fetch(usersend)
newuser.send('Thanks for voting! You recieved 10k bobux')
})
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
type-safety and features that aren't in js
like mixins
One message removed from a suspended account.
yes. I like dart alot.
One message removed from a suspended account.
but im getting the error that await is only an async function
dart also has type-safety
One message removed from a suspended account.
One message removed from a suspended account.
I was talking about dart
dbl.webhook.on('vote', (vote) => {
console.log(`${vote.user} has voted me`)
const webhook = new Discord.WebhookClient('', '')
webhook.send(`${vote.user} has voted me`)
const usersend = vote.user.id
const newuser = await Client.users.fetch(usersend)
newuser.send('Thanks for voting! You recieved 10k bobux')
})
One message removed from a suspended account.
One message removed from a suspended account.
now its saying ```
Redundant use of await on a return value.sonarlint(javascript:S4326)
One message removed from a suspended account.
now im getting this error
One message removed from a suspended account.
um how do i check
npm ls discord.js
ok
12.5.3
One message removed from a suspended account.
One message removed from a suspended account.
use users.fetch() just in case the user isn't cached
but that is what i was doing before
what did you do?
here
One message removed from a suspended account.
Try this
client.users.cache.get() || client.users.fetch()
ok
are you sure it's vote.user.id?
someone told me that
isn't it vote.user?
does somebody now a lib which can compile html to react?
ohh ok ty
don't think there's any
but you can use html in react
did it log <id> has voted me
nvm an error
lemme check
how do i clear logs on bitvise ssh client
anyone know]
i got this error js 0|index | TypeError: Cannot read property 'fetch' of undefined 0|index | at DBLWebhook.<anonymous> (/root/bot/structures/Client.js:39:38) 0|index | at DBLWebhook.emit (events.js:314:20) 0|index | at IncomingMessage.<anonymous> (/root/bot/node_modules/dblapi.js/src/webhook.js:83:16) 0|index | at IncomingMessage.emit (events.js:314:20) 0|index | at endReadableNT (_stream_readable.js:1241:12) 0|index | at processTicksAndRejections (internal/process/task_queues.js:84:21)
what's Client?
it needs to be your Discord client
not the class
some people call it client or bot
ye its my bot
and client.users.fetch() not client.users.cache.fetch()
yes
not users.cache.fetch()
users.fetch()
ok
console.log(Client)
they used Client.users.fetch(), no? #development message
[class Client extends BaseClient]
i used a constructor
you need the instance
now i get this
did you just remove Client.
can you send the full output
thats all it sends
I meant keep the client too
how did you initialize your client
you must have used new EconomyClient() somewhere
Wait client.users is undefined ?
how ?
1 SEC
oops all caps
so ```js
const { Client, Collection } = require("discord.js");
and then ```js
class EconomyClient extends Client {
@pale vessel
not there
ah
did you use new Client() anywhere?
nope
i use those in my command files
on all of them?
yes
const { Message } = require('discord.js')
const Client = require(`../structures/Client`)
const Discord = require('discord.js')
const stats = require('./stats')
module.exports = {
name: `vote`,
/**
* @param {Client} client
* @param {Message} message
* @param {String[]} args
*/
run: async(client, message, args) => {
}
}
that is an example command
where did you put the dbl webhook event?
Client.js
can you send the file?
ok
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.
use this.users.fetch()
this would refer to the client itself
that would be the instance
ohh yeah
i completely forgot i did that
sorry for wasting ur time
yess it worked @pale vessel ty
@lyric mountain@cinder patio welp i tried my hand at it
for that particular string, i got the same performance as google's
but for larger strings, mine is much faster
that took quite a while
show us dababy
also
dababy
gimme the code
do they?
yep
the 3 conditions were:
A - every 2 chars preceeded by + or - must be captured
B - words must be separated from numbers
C - numbers must be numbers
alright
oh and
4 - order must be maintained
made mine a bit slower than googles for small strings
but still faster for larger strings
function test(str) {
let result = [];
let len = str.length;
let xnum = /[0-9]/g;
let xstr = /[a-zA-Z]/g;
let nextnum = xnum.exec(str)?.index ?? Infinity;
let nextstr = xstr.exec(str)?.index ?? Infinity;
let nextplus = str.indexOf("+") ?? Infinity;
let nextminus = str.indexOf("-") ?? Infinity;
if(nextplus === -1) { nextplus = Infinity; }
if(nextminus === -1) { nextminus = Infinity; }
let curr = Math.min(nextnum, nextstr, nextplus, nextminus);
let next = 0;
let x = 0;
while(curr < len) {
switch(curr) {
case nextnum: {
next = Math.min(nextstr, nextplus, nextminus);
xnum.lastIndex = next;
nextnum = xnum.exec(str)?.index ?? Infinity;
result.push(Number(str.slice(curr, next)));
break;
}
case nextstr: {
next = Math.min(nextnum, nextplus, nextminus);
xstr.lastIndex = next;
nextstr = xstr.exec(str)?.index ?? Infinity;
result.push(str.slice(curr, next));
break;
}
case nextplus: case nextminus: {
next = curr + 3;
xnum.lastIndex = next;
nextnum = xnum.exec(str)?.index ?? Infinity;
xstr.lastIndex = next;
nextstr = xstr.exec(str)?.index ?? Infinity;
if(curr === nextplus) { let i = str.indexOf("+", next); nextplus = i > -1 ? i : Infinity; }
if(curr === nextminus) { let i = str.indexOf("-", next); nextminus = i > -1 ? i : Infinity; }
result.push(str.slice(curr, next));
break;
}
}
curr = next;
}
return result;
}
One message removed from a suspended account.
One message removed from a suspended account.
let let let let let let let let
gg
looping over characters is fast for small strings
but gets super slow once strings get larger
so i tried going the indexOf route
but managing 4 different indexes aint easy
please send the two strings u used here
"long12+krt89df-efdwefwoefhowuehguwhgo2380470283740823704283490820wefwefwehjj67nmn"
"long12+krt89df-efdhjj67nmn"
well, it's google
One message removed from a suspended account.
One message removed from a suspended account.
WHY ARE WE PARSING SHIT STILL
why not
Google Calling Justin Bieber...
Bieber lifts the call and he says... You know you can call me if you need someone... I need you to hold on, Heaven is a place not too far away
@lyric mountain@cinder patio i was being really dumb and over complicated everything lmao
code is now 3x smaller and a tiny bit faster
function test2(str) {
const result = [];
const reg1 = /[^0-9]/g;
const reg2 = /[^a-zA-Z]/g;
for(let i = 0; i < str.length;) {
const char = str[i];
if(!isNaN(char)) {
reg1.lastIndex = i;
let next = reg1.exec(str)?.index;
if(!next) { next = str.length; }
result.push(Number(str.slice(i, next)));
i = next;
} else if(char !== "+" && char !== "-") {
reg2.lastIndex = i;
let next = reg2.exec(str)?.index;
if(!next) { next = str.length; }
result.push(str.slice(i, next));
i = next;
} else {
result.push(str.slice(i, i += 3));
}
}
return result;
}
impressive
its basically looping over characters but advancing the index using regex with position indexes
@quartz kindle Interesting to see you use performance.now() . Didn't know about that function. I always use console.time / console.timeEnd
there's also process.hrtime() if you're on node
they all have roughly the same precision since they were all nerfed to fix the spectre problem
How would I end a message collector if there is no time limit, or no collection limit?
One message removed from a suspended account.
u can manually do that
One message removed from a suspended account.
How do I do that?
Ooh, someone should have mentioned me too, to see the tim's code
see the above link
Ty.
lul sry, i didnt know who were all the people looking into it
What type should I give to the class property that stores reference of methods of its own class
class A {
prop: Type
constructor() {
this.prop = this.doSomething
}
doSomething(num: number): string {}
doSomethingElse(num: number): string {}
}
So what Type should be? Later in program, I'll assign prop to doSomethingElse.
Function?
All the methods, that I'll assign, will be of same signature
How do I make it so it checks if like args equal Test, but how do I make it not case sensitive?
(num: false) => string
Same signature as the doSomething function
it's just that simple? I was confuse, if prop will have same this.
what if I make doSomething an anonymous function?
class A {
prop: Type
constructor() {
this.prop = this.doSomething
this.prop()
}
doSomething = (num: number) => {
return this.doSomethingElse(num)
}
doSomethingElse(num: number): string {}
}
So this wont work?
uhh
Anon functions will work tho
prop would need to be the same as doSomething
mb
I don't see why you would reassign something just to run it
I want to reassign prop dynamically to other methods
you would need to do js class Class { property?: Type | OtherType | AnotherType constructor () { this.prop = something this.prop() } }
even then its stupid
so I could change the behaviour of prop dynamically
you can have a single function an enum which tells it what to do
prop can be of a single type, as I said, the signatures of all the methods would be same.
Then you can do
this.prop = this.doSomething.bind(this)
thats a redundant bind I thought
class A {
constructor() {
this.prop = this.doSomething
this.prop()
}
doSomething = (num) => {
return this.doSomethingElse(num)
}
doSomethingElse(num) {console.log('haha')}
}
I tried this, and it worked.
I'll change doSomethingElse to anonymous funciton as well.
Actually I'm trying to implement Strategy Design Pattern here
How do I check whether a message collector was ended by collector.stop, or timing out?
there is events for that on collector. U need to look up that link again
collector.on(`end`, (collected), time => {
}``` Like this?
collector.on(`end`, (collected, reason) => {
})
Ty.
reason gives the reason collector ended. "time" | "idle" there might be one more. idr
hello, I need help with HTML: how can I make a file become from a specific page of a website?
for example
I have a file called index.html, which is the main page of the website
and I want to make a file for a /commands part of the website
One message removed from a suspended account.
One message removed from a suspended account.
Just use the <a> tag with href attribute
on the index.html? or the new file?
wdym?
Like ./commands.html
with ./ at start, yes.
ok
I am kind of lost. I should put it on the config I made for the button, or somewhere else?
cause I put in the button and it started installing an archive lmao
@median moss Well, if it’s a button you want to link a page to,
yea
but I want to know first how to make this page
.-.
like what you were explaining
uh, make the page?
So, say I want the bot to say a list, but without the comma and a space of each thing in the list, how would I do that?
language?
Javascript.
you can use array.map()
.join
or join() yes
can anybody help me host an open source bot on heroku
what's the problem you having?
im trying to host RoVer on heroku
its open source but i cant figure out where im going wrong
rover is your bots name?
its an open source bot
oh
um but which Language?
let me check
js
u mentioned standard.js?
i just pressed docs and it loaded
um never heard about it
o
i can send the github link
ig i cant help sorry
alr
can help you with node.js
wait
i think its discord.js
this is the github
did you created the procfile on this bot?
he probably didn't even create the bot
still, why don't u invite the bot itself?
yes, i know but you also said that you want to host it on heroku and that you already have bots hosted there
Hey! Can anyone recommend me Instagram libs for python other than instapy or instabot
like, why go through all the hassle to host it if you can use the original?
my preference
hm, ok then, that solves the first issue
ok
only ben can help you
yh but
ive hosted before but
ive never hosted an already coded bot
it has all the files
well, it's up to you to figure out how to work with it
also
ive hosted before but
ive never hosted an already coded bot
choose one
ive never hosted an already coded bot
so you never hosted a bot
ive coded and hosted my own on heroku
ah, you already coded one before
try the basics like creating the .procfile on the root of your project and setup the project on heroku like you already have done before
the steps are the same regardless if it's your own or another bot
here's the start command node src/index.js
https://github.com/evaera/RoVer/blob/master/package.json#L26
wait
just repeat what you've done for your bot
let me try hosting locally 1 sec
before using it you installed the node modules?
yes
You don't need a procfile for a node.js app anymore
i did let me try again
just a main entry
install git
Hi
github desktop?
no, git
git
pretty sure all the defaults are fine with git
use the default options that it offers
Oh there's a check box which will say as add to path
i did default for all
What it does is add the system variable for ya
That's fine
where do i go from here?
now open a new cmd
in the folder?
and type npm -v
anywhere you want
?
not npm
what do i put
if it is showing that then git is added to your enviromnent variables which is good
next step?
now go to your project and type npm install again
idk about the step 6 but the others yes
it was downloading at the start
any1 know how to make it so ppl can change the prefix of the bot
because i am just stooopidd
you need a database
you need to install python3 for windows
yh downoadjng
or just windows build tools
latest version?
nice call
do i do python latest version?
yeah
as i mentioned above, you're going to need a database
in a relational database you'd structure your data like this
+------------------+--------+
| id | prefix |
+------------------+--------+
| 0000000000000000 | "!" |
+------------------+--------+
where the id is used as the pk
all of that would be stored in whatever table, i.e. GUILDS
just install python3
thanks ❤️
now open a new cmd and type py
ok, now open a new cmd in your project folder and type npm install again
running
its important to close all opened cmd everytime you install a new software/library
also important to always check the version after you install anything
to see if the PATH was defined correctly
@outer void
go to your environment variables and print the paths that are there
Step by step to find where your environment variables are:
https://www.wikihow.com/Change-the-PATH-Environment-Variable-on-Windows
(the command to install windows-build-tools needs to be run in an admin instance of powershell)
on "User variables for benra" click on Path and then Edit and print it
this?
yeah...
where do i print
install windows-build-tools as mentioned above
how?
installing...
guys, im using discord.js (^12.5.3) with Typescript for my bot. The problems is that the command send() is not working on discord v12 when I try to use it with guildMemberAdd:
client.on("guildMemberAdd", async (member) => {
const channel: GuildChannel | undefined =
member.guild.channels.cache.get("841825479937359935");
channel?.send("Welcome");
});
//Returned error
Property 'send' does not exist on type 'GuildChannel'
anyone else having this issue?
guildchannel doesn't mean it's a textchannel
so it doesn't have a send method
also can't u do GuildChannel channel = ...?
like, that looks verbose af
its Typescript and implicit declarations aren't recommended
that ain't implicit
implicit would be const channel = ...
implicit = not explicitly stated
well, looks like you can't
its not possible to create "GuildChannel channel"
yeah haha
what is typescript used for?
it makes you type more
typed javascript
isn't js better? idk i've only ever cared about node
nope
js is shitty when it comes to debugging, just because of its dynamic typing
like
Kuu have you learned the way of javascript yet
let a = "something";
a = 1;
console.log(a);
that logs 1
this is so shit for debugging that I can't even start to explain why
I don't see what's wrong with it.
like, you don't know the type beforehand
and intellisense sometimes weirds out
also compiler doesn't help shit
the member parameter has type GuildMember on guildMemberAdd functions
client.on("guildMemberAdd", async (member) => {
//code
});
i personally hate types
:p
if discord.js is the same as most libs, guildchannel can be cast to textchannel
isn't java just javascript with types? i haven't used java in 4 years correct me if i'm wrong
They're both very different.
Yes
guess i'm gonna die then
Mee too
Comparing Java to JavaScript is like comparing a $1 bill and $100 bill and saying they're the same
Lets die togwthwrye6w
except you don't know the value of which one
javascript is only called like that because it was born as a browser extension of java
but they took WAY different paths
i'm only talking about syntax
even syntax is totally different
even syntax
I don't get why someone would like types
jsfuck would be descafeinatto
Types are useful for verifying something's correctness.
who the hell drinks coffee without coffee?
it's nice when libraries use types so you know what you're getting
otherwise types are useless
pretty much
Take this function for example: ```js
function isGreaterThanFive(number) {
return number > 5;
}
You can call this function in a lot of weird ways. A type-safe language may require it be written like this: ```js
function isGreaterThanFive<T: Comparable>(number: T) -> Boolean {
return number > 5;
}```
This definition would require the input be comparable (so stuff like > can be used).
i'm currently learning solidity, and it has types.. and now I realise that solidity syntax already looks better than typescripts

tbf, I do hate ts type declaration
if it was java-like it'd be just Class name = something
instead of let name: Class = something
T variable = t 🤮
after working with TS for some time i found it ok
in solidity you can say function isGreaterThanFive(uint number) returns (bool){return number > 5}
looks wayy more simple than ts

For human readability? Sure. But I don't mind either one.
Like the function keyword being called fn, fun, func, fctn, etc.
(Rust, Kotlin, Swift, ???)
Dart expects you to know other languages to learn its syntax though
I absolute loved it
I semi-like Dart's syntax.
