#development
1 messages · Page 787 of 1
ayy
im making a new disord bot should i use defualt js or typescript
idk the diff tho
and which one is which
@quartz kindle hm how why 25 and not 24?
typed is _type_script
the retarded one is javascript
thank you discord formatting
typescript is converted to javascript in the end anyway
^
but at least it errors are compile time
however in js you see well uh
stupid people doing stupid things
e.g making up their own properties on objects
which one should i use
if you like strictly typed langauges; typescript, otherwise go for js
js is best for dcord bots
lol no
it is atleast fo rme
Js === retarded //true
@copper cradle retarded is undefined
@uneven wyvern "11001" = "yes,yes,no,no,yes" = "16,8,4,2,1" = "16 yes, 8 yes, 4 no, 2 no, 1 yes" = "16 + 8 + 1" = 25
yooooo
😔
singlethreaded will never be the best especially on something that's dependant on so many gateway events
not really
Sometimes
OHH FUCK NOW I KNOW WHAT I DID WRONG ty Tim
the difference is that supposedly ts compiles to "good and proper" js
async/await
so your final js may look weird/complex, but maybe more efficient
Yes
and last question
ik python but i love to use js
Then learn Go
nah i would rather use rust
what ever
how do i compile all the files in ts
in single command
with a compiler
typescript docs cover that
rust is cool af
i am the trollest
@copper cradle thx
it's not that hard
10101010 10101001 10101001
no
to convert decimal to binary you divide your number by 2 until you get to 1/2, if you have remainder(s) in the division you write it up as a 1, if not, write it up as a 0, once you're done read it down to up and you got your binary num
i think numeric notiations is the first thing you cover in CS
Like a js proyect
read 👏 the 👏 docs 👏
i found nothing about setting up proj
actually imma just use defualt js
nvm i found it
i wanna implement a music player into my bot, but i feel like it'll be very taxing on the hardware. anyone know if music systems take a lot of cpu/ram? (d.js)
They eat cpu
mhmm might just stick to text & image based stuff then thanks
bc my vps has 1gig of ram hahah
each stream can easily take 20% of a single core
damm, dont know what type of cpu i got but im sure its not gonna be that powerful on a vps hosting 60 other vm's
imagine how much Rhythm costs per month
Considering they run on multiple machines apot
Alot*
But also consider it's owned by digital ocean
Zero
Lmao
Think it was made by one of the employees
he better have gotten a large amount of cash for it
I mean great publicity for DO for people wanting to host bots on their systems
Saying we host the biggest bot in discord
yeah, but if it was made by an employee with his own free time and not like sponsored from the beginning
he better be getting a cut of the profits
else its a company abusing an employee's creation
true
just like universities do with their students
getting most of the credits for the students' research and thesises
lul
I doubt they make any profits on Rhythm
how would you even profit off a bot?
He could have made it during work times, then it's usually fully owned by the company
showing ads on the website?
oh yeah that
And considering rythm has 6 million guilds and god knows how many users it seems pretty reasonable to ponder at the sheer amount they make on their premium commands that actually makes the audio quality alright not shit
the value of a company/creation is not defined only by how much profit it gets
sometimes companies operate on negative income and are still worth millions
simply because of the market reach they have
rhythm has a reach of 5 million servers and god knows 50+ million people, who are directly interested in music, so its one hell of a market reach
imagine they suddenly decide to put youtube/radio style ads in their streaming
thats instant potential millions of people reached by a single ad
although how many people are actually listening to it is probably only a couple thousand lul
Nah 5 mill servers your looking at maybe tens of thousands of players
chip gets around 70 - 100 players at a time with 14k servers
Is it possible to have the bot upload custom emoji to a server using the URL?
yes
@earnest phoenix which library do you use
discord.js
(for v11 stable)
^
Is there any way in VS2019 I can just view one tab at a time in an actual editing environment? I have these arrows and I don't like it. I am using Xamarin.IOS
https://images.vinniehat.com/i/z0iammz55urc6f2.png
That and to display the phone itself so I can see the notch
Haven't used Xamarin yet so sadly unable to help
^
dont doubt codingpro
Anyone know how to serve gzip files with nginx
I'm using the compression plugin with webpack
anyone know any good mongodb hosts?
Host it on the system that'll use it if possible
https://www.mongodb.com/cloud/atlas mongo's own service, perhaps?
Host MongoDB in the cloud with MongoDB Atlas, the official database-as-a-service, on AWS, Azure and GCP. Try free!
mongodb doesn't require much so any server rly
but yeah if you can do it on your own system it'll be faster
If you can't and do need an "external" database, their free offer is pretty good, but if that doesn't meet your needs, I'd recommend just getting a vps and installing mongo on it yourself
You can probably get a better setup for less money
possible to find in a precise channel a precise message example an id of user followed by its number of sanction? "
@wicked pivot .....what
this is more important
@hushed berry
???
on the other hand I have another question how to put the date of creation of a user in day
@hushed berry idk if that's english
pensive
"
why 80% of the bots are made using js???
because its currently the most popular language, plus its easy to learn compared to most others
looks at queue: unlikely 
whats the most popular in the queue?
No I mean that wouldn't be the reason for it being the most used language when looking at queue/a majority of bots that have been added as of late
🥣
you mean despite being easy to use (compared to most others) most bots are still shit, which suggests its not actually easy to learn?
No what I mean is a lot of them come from tutorials, templates and stuff like that
oh lul
well then its the most popular for the simple fact of popularity and community enthusiasm
what a shit reason lmao
I mean documentation is also always a big reason
Pretty much
Usually when you search for something Discord bot related JS based stuff will usually be one of the top results which obviously will pull even more people to it. It's usually people that where already programming or people programming long enough to want and try other languages that use something besides JS for their bots obviously not always the case but a lot of the time
World wide programming language usage doesn't hold much weight when talking about Discord bots
most popular on stackoverflow 2019
arent those for questions tho
most loved languages
most hated langs
lmao
Stack Overflow’s annual Developer Survey is the largest and most comprehensive survey of people who code around the world. Each year, we field a survey covering everything from developers’ favorite technologies to their job preferences. This year marks the ninth year we’ve published our annual Developer Survey results, and nearly 90,000 developers took the 20-minute survey earlier this year.
Why objective c
apple
Java and JavaScript are very different.
Jesus rust is high
Hi, I have an oylan problem that sometimes my bot stops automatically, and since I can't really find the answer to the error code, it doesn't ruin my decision, I can't solve it if it stops automatically then start it Operating System Linux server (UBUNTU 18)
is it possible to put the name of the custom status and not this?
js
user.presence.activities.find(a => a.type === "CUSTOM_STATUS").state for v.12
how to make this without refresh the page ?
What do you mean @earnest phoenix
I think sending messages.
anyone can tell me why that doesn't creates an file?
// a base64 string of a gif image
// The absolute path of the new file with its name
var filepath = "logindata.txt";
// Save with a buffer as content from a base64 image
fs.writeFile(filepath, new Buffer.from(genToken, "base64"), err => {
if (err) throw err;
console.log("The file was succesfully saved!");
});
The absolute path is the entire path to where you want to create the file
e.g. /root/myCoolFolder/logindata.tzt
oh
if (err) throw err;9:19 AM
9:19 AM
Error: ENOENT: no such file or directory, open 'app/logindata.txt'
the file exists but won't show
How can change authorized link
like when people add my bot in his servers after authorize open my own website link.
I'm searching a ez way to do a music bot in djs v12 without lavalink
@uneven wyvern use /app/ not app/ this can be the problem
it appeard but with no content in the file
What is in this file? Api key ? Token of your bot? You can use json this is more simple for use the content
Yeah Api Token what is generated by a lil fucntion
Oh
You can generate this api token directly in the code and use it
Store this in a file isn't good if this is valide only one time
@tight plinth AtlantaBot Source on GitHib is a whole Bot but also has a good Music Source
K I will try
Hello, I have a question for the DiscordBotList API in Java.
The token used to initialize the DiscordBotList object, is that of the discord bot ?
That's what I thought. So I did not find the token on the site :/
ah
no
it's good, Sorry
Thanks for reply
I know I'm probably being dumb right now, But I can't seem to find how to use lavalink anywhere. I've got it setup I just don't know how to use it.
How do I draw a line over if it's not an avatar gif
Disocrd.js v12
@warm marsh it's just an api that you can use. It has various endpoints you can connect to to use it. Most languages have a client library tho so just find one and use it's documentation to go from there
I'm using it with lua and their documentation is terrible.
lavalink has a documentation of the endpoints if you wanna make the requests yourself
Where?
Lemme find it rq
I'm using discordia
if theres nothing there for your lib
im afaik you need to implement your own
I just made my own lib on d.js
that works perfectly for my use case
other users also loved it
so I'm contented with it
Ye same don't like relying on other libs
help accept my bot with new prefix s.
nah its a public lib I created
s.
Help me
How do I draw a line over if it's not an avatar gif
Disocrd.js v12 || Sample
But when it is gif, it does so
Can the votes take time before being counted ?
If you're just checking on the site, it uses cached values so it won't always be 100% accurate
hum, Even going through the DiscordBotList API?
The API should return live values, not sure because I don't use it
How can I list all People in a role
which library
discord.js master
And as stated in the description there^^ it'll just be cached members
So you might want to make sure all members of that guild are cached before doing so
The "player" variable is me but when I retrieve it if I am an administrator, it returns "false". And if I check the identifier of a person who voted, it also returns "false"
I'm pretty sure that admin check is for like admins of the site
ah ? It's not bot admin ? Okay why not but for the vote it doesn't change anything :/
why would that have anything to do with your bot admin?
the admin thing in dbl is for the admin badge on the site and in
-bots
As we connect with a token provides for the management of our bot. it could have been the bot administrators.
but no problem that's one less worry.
now for the votes i'm having trouble doing something but I don't know.
hasVoted isn't as fast as just using the webhooks, but it should be fine for what you're doing I guess.
Did you make sure that it's actually returning false and not just something else in your code that's going wrong?
Yes i think. voted is a boolean and throwable is undefined so no error.
Do any errors appear when you run the bot
yep
Would you mind showing them
... aside from that
nothing
are you sure the file is saved
yep
New hoister
ur name has special letters
You actually mind sharing your full code
Not the lil core snippet that tells us nothing
how
copy + paste
message.guild.createRole({ name: 'Male', color: '#0000FF', hoist: true, mentionable: false });
umm so the code runs but doenst create any roles
any idea why?
TypeError: Cannot read property 'send' of undefined
When i am using
client.channels.get("ID").send("blablabla")
Yes I checked ID Is Valid
discord.js
@visual sandal Runs Fine When I use eval dunno
ok
it used to work yesterday but stopped working
today
I didn't change much code but it skips all the roles i create using the bot
what do you mean "it skips all roles i create"?
are you sure the id is valid? is it a dm channel? is the channel cached?
Not DM When I Use !eavl Command It Works so i guess channel is cached
Plus Id Is Valid
Used to work Like an hour ago
Did some bug fixing and Voils
Voila*
@quartz kindle how Can I Check if channel Is Cached?
basically client.channels.get() or client.channels.has()
get wil return undefined, has will return false
try console.log(client.channels.get(id))
also try console.log(client.channels.size)
Returning undefined
Maybe you're executing that before the client is ready
also try console.log(client.channels.find(channel => channel.name === "channel name" && channel.guild.id === "guild id"))
Which means there's no channels at all yet
he said hes using the ready event
ok nvm 🏃
so channels.size logs 173?
try the channel.find
Like WWAAAAY MORE
It was 520+ Last time used my stats command
But the bot is working if i used !ping command while making the .send comment
'517265128647950347' => Guild {
0|server | members: Collection {},
0|server | channels: Collection {},
0|server | roles: Collection {},
0|server | presences: Collection {},
0|server | deleted: false,
0|server | available: false,
0|server | id: '517265128647950347' } }
Sent this
Oh Wait
This is guild
Server
Where i am checking
@quartz kindle Server is unavailable for the bot any fix?
Or Discord is buggy?
that means the server is not available, that specific server might be having problems in the discord side
you're on v11 stable right?
Your bot is on that server?
I guess lemme check
@blissful scaffold Ofc How would it be in the client.guilds list
@quartz kindle sry for the ping but..
my message.guild.createRole() does not create a role or return an error.. just does nothing
and continues the code
@quartz kindle Yes
await doesn't work either
{'type': 'release_get', 'url': 'http://www.crunchyroll.com/en-gb/room-camp', 'name': 'Room camp', 'episode': '5'}
[10/02/20 | 14:00:06] Starting a new task
Sending Outbound response to Release.
[10/02/20 | 14:00:06] Returning Selenium_1 to free drivers, task complete
{'type': 'release_get', 'url': 'http://www.crunchyroll.com/en-gb/room-camp', 'name': 'Room camp', 'episode': '5'}
[10/02/20 | 14:00:07] Starting a new task
Sending Outbound response to Release.
[10/02/20 | 14:00:07] Returning Selenium_2 to free drivers, task complete```
We have this log, which is fine, appart from the fact that some how, the system it send two requests and adding two tasks even tho it shouldnt.
Code:
https://paste.pythondiscord.com/mibizubohe.py <--- Release event code
https://paste.pythondiscord.com/apagipahuc.py <--- Websocket organiser
@small prairie pretty much the only thing you can do is add if(!guild.available) return
at least that way your bot will work without throwing errors
Custom bot /:
you can make it retry after x time if the guild is not available
Response: daily_update
{'name': 'Room camp', 'url': 'http://www.crunchyroll.com/en-gb/room-camp', 'release_time': '14:00', 'episode': '5'}
{'name': 'Yatogame chan kansatsu nikki', 'url': 'http://www.crunchyroll.com/en-gb/yatogame-chan-kansatsu-nikki', 'release_time': '17:15', 'episode': '5'}
{'name': 'Seton academy join the pack', 'url': 'http://www.crunchyroll.com/en-gb/seton-academy-join-the-pack', 'release_time': '17:30', 'episode': '5'}
Response: daily_update
{'name': 'Room camp', 'url': 'http://www.crunchyroll.com/en-gb/room-camp', 'release_time': '14:00', 'episode': '5'}
{'name': 'Yatogame chan kansatsu nikki', 'url': 'http://www.crunchyroll.com/en-gb/yatogame-chan-kansatsu-nikki', 'release_time': '17:15', 'episode': '5'}
{'name': 'Seton academy join the pack', 'url': 'http://www.crunchyroll.com/en-gb/seton-academy-join-the-pack', 'release_time': '17:30', 'episode': '5'}```
Update to that, seems to be that the getting daily releases is causing it to add double the tasks to the sheduler
idek why
my code sends a message
then reacts to the message with emojis
then creates roles
everything used to work but now it doesn't
My Bot Banned From a server Can That Be The Case? @quartz kindle
i changed noting related to it
then it shouldnt matter
Can I Try Kicking and readding?
sure
Will It work?
pastebin
Oof Didnt Work
if (command === setup) { // Setup a server with Jonin
var errMsg;
if (message.guild.channels.find(channel => channel.name === "server-roles")) {
message.channel.send(**Code 11** \${config.prefix}errcodes to view error type`); return; } message.guild.createChannel('server-roles', { type: 'channel', permissionOverwrites: [{ id: message.id, deny: ['MANAGE_MESSAGES'], allow: ['VIEW_CHANNEL'] }] }) .catch(console.error) .then(() => { message.guild.channels.find(channel => channel.name === "server-roles").send(Channel: Server Roles+\n+Status: Set-Up+\n+Set-Up Triggered by: + message.author.username) }) .then(() => { let setupEmbed = new Discord.RichEmbed() .setColor('#FF0092') .setTitle(Roles for guild + message.guild.name) .addField(Gender (Optional):, 💙Him/Guy\n❤️Her/Gal\n💚Them/Other`, true)
.setFooter('Provided by: Jonin');
message.guild.channels.find(channel => channel.name === "server-roles").send(setupEmbed).then(function (message) {
message.react("💙")
.then(() => message.react("❤️"))
.then(() => message.react("💚"))
})
.catch(console.error)
});
message.guild.createRole({ name: 'Him/Guy', color: '#0000FF', hoist: true, mentionable: false });
message.guild.createRole({ name: 'Her/Gal', color: '#FF0000', hoist: true, mentionable: false });
console.log(`Done`);
sry
@visual sandal dont put .catch() before .then()
ok
you're not awaiting the promises either, and not catching the last two
so use .catch for creating roles
you should change everything to async/await syntax
ok
its better and more readable for using multiple promises
await message.guild.createRole()
await message.guild.createChannel()
yea.. i was still testing if it was working at all
then you dont need catch nor then
ok thx
Ah My Server was hacing problems
Having*
I did a hard restart and its work
although thanks @quartz kindle
Wait what
Still
Weird
@quartz kindle Its Like It Takes Time For Bot To Get That Server
async def on_message_edit(before, after):
with open("logs.json") as l:
log = json.load(l)
serverid = str(after.guild.id)
if not serverid in log:
return
state = str(log[serverid]["state"])
channel = client.get_channel(int(log[serverid]["channel"]))
if state == "on":
embed = discord.Embed(colour=discord.Colour.gold(), timestamp=datetime.datetime.utcnow())
embed.set_author(name="Log", icon_url=client.user.avatar_url)
embed.add_field(name="Log", value="Message Edited, Before: **{}**, After: **{}**!".format(before.content, after.content))
embed.set_footer(text="GidBot | {}".format(v))
await channel.send(embed=embed)```
Can someone help me why its doing this?
Discord.py 1.3.1
🤔
whats the error
Nothing, it just spams that random stuff when a message is edited.
only thing i can see is multiple instances running
i cant see anything that sceams out at me
:/
Add a check to compare before.content to after.content
can someone help with the javascript eval command? its sending multiple messages
dose it depends on my bot ping?
Thanks its worked lol.
@earnest phoenix show code
Ok
if (typeof(text) === "string")
return text.replace(/`/g, "`" + String.fromCharCode(8203)).replace(/@/g, "@" + String.fromCharCode(8203));
else
return text;
}
client.on("message", message => {
const args = message.content.split(" ").slice(1);
if (message.content.startsWith(config.prefix + "eval")) {
if(message.author.id !== config.ownerID) return;
try {
const code = args.join(" ");
let evaled = eval(code);
if (typeof evaled !== "string")
evaled = require("util").inspect(evaled);
message.channel.send(clean(evaled), {code:"xl"});
} catch (err) {
message.channel.send(`\`ERROR\` \`\`\`xl\n${clean(err)}\n\`\`\``);
}
}
});
@quartz kindle
no
Mmmm
@earnest phoenix does it send the same reply multiple times? or does it send different things? do you have other .on("message") in your code?
Why auto restarted the bot?
Who's a python expert please?
I think my exec command.
@earnest phoenix be more specific, what part you need help?
Just describe the issue, Army_
This image from Juice Ping ?
?
fail
sorry
@dull terrace yep
The problem is that for a few weeks I've been looking for a way to connect my bot to a voice chat room, I've looked at the documentation but I still can't find it.
Tim is witness x)
@earnest phoenix no
@zenith orchid scroll up and check the error log as well
pm2 has 2 separate logs, normal log and error log
that still doesnt help, but for now try fixing your exec errors
Hi everyone!
I have been receiving several errors similar to this one for about 30 minutes:
Error: Shard 0's Client took too long to become ready.
I have verified that it was the connection of my bot with Discord and it seems to be all right, I did a speed test and it also seems to mark a good speed up and down
What could be happening? (I rule out problems with the firewall, I haven't modified anything like that) 😅
Another example of errors that I receive
Something took too long to do.
Sounds like blocking
I already tried a test to make sure that my VM is not banned in the API and the data it provides is normal
Sounds like blocking
Lock in what way? 😅
a command in code that takes too long to execute
It was the first thing I discarded
Error: Shard 0's Client took too long to become ready.
This error throws it at me because I have a webhook as soon as the client is ready
But neither does my bot appear online, that's the problem
I didn't change anything about the events in 1 month
I can't send the code
How strange, now if it connects (and I changed absolutely nothing)
Oh no
I already found the problem
curl -I https://discordapp.com/api/v7/gateway
HTTP/2 429
date: Mon, 10 Feb 2020 18:59:36 GMT
content-type: application/json
retry-after: 447
cache-control: no-cache
set-cookie: __cfduid=d87f1ad5b7c8a7b9df9ab0ce6efd744d61581361176; expires=Wed, 11-Mar-20 18:59:36 GMT; path=/; domain=.discordapp.com; HttpOnly; SameSite=Lax
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
server: cloudflare
cf-ray: 563052365b8bf1c6-ATL```
They limited my bot? 🤔
at Function.Module._resolveFilename (module.js:548:15)
at Function.Module._load (module.js:475:25)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/rbd/pnpm-volume/85843778-0fdd-44f9-8e70-e4d22104fdd8/node_modules/.registry.npmjs.org/canvas/2.6.1/node_modules/canvas/lib/bindings.js:3:18)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)```
hm
What experience/languages would be needed to develop a web dashboard
message.guild.emojis.find(emoji => emoji.name === `Male`).delete().catch(console.error);
would this line properly find and delete a custom emoji by name...
Kk ty
and the main server that does everything can be anything ranging from python/js to java
pretty much every language
thats made to run server side
@visual sandal https://tryitands.ee
Is there a benefit to learning CSS instead of HTML
Because from what I’ve read these languages do the exact same shit
HTML, the Hypertext Markup Language, is a standard for describing the structure and presentation of information via the Internet. Web developers use HTML keywords or tags to instruct the Web browser application how to format and display the content of Web pages.
CSS is the language for describing the presentation of Web pages, including colors, layout, and fonts. It allows one to adapt the presentation to different types of devices, such as large screens, small screens, or printers. CSS is independent of HTML and can be used with any XML-based markup language.
well does the guild have an emoji called male
yes.. the previous command creates the emoji.. but the "cleanup" command doesn't delete the emojis
i get this error
(node:4) UnhandledPromiseRejectionWarning: TypeError: message.guild.emojis.find(...).delete is not a function
that error is pretty self explanitory
@shut cipher html and css complement each other, so there isn't learning one over the other, you learn both for web work since html is mainly templating while css is styling the template
big question here
do i:
upon a upvote
store time stamp
and have a loop checking if votes have an expired time stamp
or
no
do i use my cron system to just shedule the removal
yes that
thought so
looping when there isn't anything to do in the loop except an if check is stupid and expensive on cpu work
what i was thinking]
altho i do need to check if my fucking system will actually not double trigger
for what ever reason it is doing it
but that might of been an invalid kwarg given on my end]
thank you aiohttp
Does anyone know a dataset of toxic & neutral messages? All datasets i saw contain link, weird characters/unicode which hinder the networks training
Not too long comments either
if all the data sets contain messages that break your training network then it is probably the easiest to filter those messages out?
Well yes but I also couldn't find a reasonable dataset
Most of them are tweets that aren't even accurately labeled as toxic or neutral
Discord.js
I have two questions.
#1 - How do you await a response in direct messages?
#2 - Is there a more efficient way to make a reaction collector/message collector?
Please ping with response.
As in, if I have a menu where you click numbers to go to a new menu and also use a number to go to the previous page, how do I do this without having a billion .then(if () {} else if () {}) in the code?
Because the code already has over 300 lines of code. And that's with a command handler.
353
A guide made by the community of discord.js for its users.
78% of that file is the reaction collector.
you can have pages saved in an object or a class for example
then on reaction load x page
and go back to waiting
a recursive function for example
@floral bloom I think you're looking for this: https://tonybo981.gitbook.io/reaction-help-guide/
Thanks, I'll look into it! 🙂
Kral @summer torrent
?
someone can help me
if(message.content.startsWith(prefix + "bannedinfo")){
let GetIdUser = args[0]
if(!GetIdUser)return message.reply("Indiquez l'id de le présumer ban")//State id to presume ban
message.guild.fetchBans(true).then(bans => {
let users = bans.filter(UserGet => UserGet.user.id === GetIdUser)
if(users.first().username === undefined){
return message.reply("L'utilisateur n'est pas ban / l'id indiquer n'est peut être pas la bonne")//User is not banned / the id indicated may not be the correct
}else{
return message.reply(users.first().reason)
}
})
}```
what is the problem
if(users.first().username === undefined){
return message.reply("L'utilisateur n'est pas ban / l'id indiquer n'est peut être pas la bonne")//User is not banned / the id indicated may not be the correct
}``` I believe because whatever the id it sends me this
what is your djs version
v11.5.1
DiscordAPIError: Unknown User from client.users.fetch("id")
every single fucking time
ive been sitting here for 2 fucking hours trying to fix this problem
@earnest phoenix are you sure the id is valid?
@wicked pivot you can use fetchBan instead of fetchBans
message.guild.fetchBan(userID).then(ban => {
if(ban) {
// ban.reason
}
}).catch(console.error)```
it is valid
im making a leaderboard command
and i want to fetch each user's id
to prevent usernames not appearing on a user's position
im using master
show code
let money = client.db.all().filter(data => data.ID.startsWith(`nw_`)).sort((a, b) => b.data - a.data)
money.length = 10;
var finalLb = ""
var i = 0;
var index = 0;
for (i in money) {
console.log(numparse(money[i].ID))
let u = await client.users.fetch(numparse(money[i].ID)).catch(e => {})
let a = await client.users.fetch("480933736276426750")
console.log(a)
finalLb += `**${++index}. ${u ? u.tag : "Unknown User#0000"}** - ${Number(money[i].data).toLocaleString()}${client.currencyEmote}\n`;
}
const embed = new Discord.RichEmbed()
.setAuthor(`Leaderboard - Economy`, message.guild.iconURL)
.setFooter(client.user.tag, client.user.displayAvatarURL)
.setColor(client.color)
.setDescription(finalLb)
.setTimestamp()
message.channel.send(embed)
what is numparse?
i used the num-parse module
does it return a number?
if so, thats your problem
ids must be strings, not numbers
it does
return a number
theres these two annoying NaN which messes everything up
you should not be parsing user ids as numbers
split it?
user ids are bigger than javascripts maximum length for numbers
if you attempt to use an id as a number, the number will change/get rounded
see all numbers are ending with 00, one with 60
those ids are no longer valid
oh
what is?
java script
code
javascript is js yes
really really annoying value that stays says its undefined
that code is of js
yes, that is js
ohh valla
and when i try to split it
if there is an undefined in your database, then you accidentally added it
see your database documentation for how to delete rows
how are you logging those ids? console.log(money[i].ID)?
yes
when i eval money only
it doesn't return the undefined thing
[ { ID: 'nw_544922024301297691', data: '9833658' },
{ ID: 'nw_400845681574674442', data: '462045' },
{ ID: 'nw_401360645720899584', data: '100005' },
{ ID: 'nw_511776275552272387', data: '36288' },
{ ID: 'nw_555703466106814506', data: '31086' },
{ ID: 'nw_480933736276426763', data: '23595' },
{ ID: 'nw_477881279312822273', data: '18760' },
{ ID: 'nw_334514066724880385', data: '13000' },
{ ID: 'nw_364952394582196224', data: '10255' },
{ ID: 'nw_565099913269084180', data: '2806' } ]
console.log(Object.entries(money))
oh wait
i know what the problem is
you give it length 10
if the length is smaller than 10, it will be filled with undefined's to become 10
so you have to if(money.length > 10) money.length = 10
money.filter(d => d).split(' ')
not really an efficient solution since you generate a new array but this will work.
why did you break your db at the first place
idk
it just appeared out of nowhere
This works this part where i defined the user it returns nothing
money.forEach(async i => {
let user = await client.users.fetch(i.ID.split('_')[1])
finalLb += `**${++indexnum}. ${user.tag} - ${i.data}\n`
})
you cant do that
async forEach is the same as doing js for(...) { function() {} }
it will fire 10+ new async functions and not wait any of them
and if you set the length to 10, there should never be an 11th result
in fact you dont even need to set length like that in the first place
just use a regular for loop, this way to can limit it to 10 loops, and it will properly await async code
let money = client.db.all(...).filter(...).sort(...);
for(let i = 0; i < 10; i++) {
let user = await client.users.fetch(money[i].ID.split("_")[1]);
}```
for..of awaits async code properly as well correct?
yes, for, for in, for of, while and do while
basically forEach sucks haha
because its basically not an actual standalone loop, it is a method on an array that acts as a helper to loop it
works! Ty ^-^
I am trying to make a no role in server error but it is not working and no error message
async def info_error(ctx, error):
if isinstance(error, commands.MissingRole):
await ctx.send('I could not find that role.')```
Well then it's not Erroring lmao
Or atleast Ur EH isn't getting tirggered by a error
Sounds like improper error handling to me
I don't see that anything's wrong unless it would be MissingRole
You are not doing anything else if any other exception is raised
?????
You are handling MissingRole but are you handling any other errors
No
i think its @bot.on_command_error
It is not
If I were to use multiple links when a command is used.. would that be spam.. (I only have that for my //support command)
The main reason it would look like spam is because all the links would get embedded?
If the embeds don't really matter, you could put the links inside <> which will stop the embed
You could also make your command output an embed, in which you could even use masked links [text](link) to possibly make things look better.
What are some good online javascript checkers
wdym javascript checkers
literally javascript
yes
well there are linters
a js linter can help you with code syntax and a few things, but will not detect execution errors
For predicting if a message is toxic or not for example, is NLU best or NLP?
I heard NLU is recommended for such things but i want a confirmation
Is there an API or Node.js Module that gives me an URL of an Picture with a specific Hex Color?
for example the color given is: #ff0000 and then it returns me a picture with the color on it
using ytdl-core my bot can't find any video (it says 'video unavaible'). Why?
I treied with like 15 differents songs
have you tried with non copyrighted songs or whatever
well copyrighted work for me
I tried yes
@uneven wyvern alexflipnotes api has that https://api.alexflipnote.dev/color/image/ff0000
even with things that are not songs
how are you using it
embed.setThumbnail(`https://api.alexflipnote.dev/color/image/${role.hexColor}`)
@mossy vine
I'm first ttying to get the play command to work before doing others ones
maybe yt issue?
@uneven wyvern
.replace('#','')
string.slice(1)
:/ oh...
both work
now it works lul ty Tim and Cyber28
string.split("").join("").filter(t => !["#"].includes(t)).join("").split("").join("")
bruh
jesus
pastes
slice(1)into jsfuck encoder
how can I select the first 3 strings of an array?
top 3 according to what?
the first 3 strings
array.slice(0,3) ?
oh
Hi, the web version is with white screen in all browser , what can i do?
what do you mean?
Hey.
Anyone know how to add args to a get request in js?
If it were python I would do this:
get(url + 'token/', data={'email': email})
Its a XMLhttprequest
I'm currently using this
req.send(JSON.stringify({email: _email}));
I receive the request in my server but not the data.
http requests do not understand JSON data by default
if the request needs to be json, you need to specify content-type: application/json in the headers
else you need to format it as querystrings
Why max mem is 35m? My server is have 3gb
cause you probably allow the prohram heap size be that
ex on java you can set max heap
heap size is not max mem
heap size is allocated memory, used heap size is actually used memory. if memory usage grows, heap size also grows
the system sees your program using 38mb, because the program reserved 38mb. but the program is actually only using 35mb
If a person speak french dm me please
process.cpuUsage() returning as:
{ user: 35334627, system: 5890661 }
How can I convert this to percent?
user/system*100 + '%' ?
actually (user/sysyem*100) + "%"
Whats the difference?
There's no difference.
Tought so lol.
returned as: 596.9348231045501 is that correct?
oh nvm
none is correct.
It only shows the used.
You also need the total
Then add both and / by the total there is on ur machine.
What lang are you using?
oh ok I understand
@quartz kindle I tried the normal way and with querystrings.
My server just doens't say that it received any data.
I tried it with my python code and that did work, but I need js bcs it needs to run on a js only supported machine. -_-
What lang are you using?
@ruby talon js
Ait.
Idk how2 then xo
@summer torrent cpu percentage is returned by counting cpu cycles over time
you need run process.cpuUsage once, then wait some time, then run it again, then calculate the difference
its a little complicated
Oh.
So you double run and then / the first by the second.
@ruby talon the diffence of this
actually (user/system*100) + "%"
was that it wouldnt return a error, as ur code would, cause you always need to (conting) + string if you do this, but if you just do counting then..
i have a sample code for cpu calculation
@restive furnace depends on the lang.
Didn't knew it was js at the time. :))
Freestyle wdym, are you thinking the % would add before the numbers?
I don't know a lot about js. :(
@quartz kindle
@quartz kindle I tried the normal way and with querystrings.
My server just doens't say that it received any data.
I tried it with my python code and that did work, but I need js bcs it needs to run on a js only supported machine. -_-
xD
let start = [process.hrtime(),process.cpuUsage()];
await new Promise(r => setTimeout(() => r(),100));
let elap = [process.hrtime(start[0]),process.cpuUsage(start[1])];
console.log(100.0 * ((elap[1].user / 1000) + (elap[1].system / 1000)) / (elap[0][0] * 1000 + elap[0][1] / 1000000))```
@ruby talon what is your server running on?
what is your configuration for receiving?
are you receiving json data on the request body?
which content-type do you have set up?
a standard POST request done by xmlhttprequest should be something like this js xhttp.open("POST", "demo_post2.asp", true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send("fname=Henry&lname=Ford");
if you need json, you need to change it accordingly: js xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xmlhttp.send(JSON.stringify({ "email": "hello@user.com", "response": { "name": "Tester" } }));
Its in the body, content-type: application/json.
req.open("GET", url + "token/", true);
req.setRequestHeader('Content-Type', 'application/json');
req.send(JSON.stringify({'email': _email}));
I tried these other req forms:
req.send(JSON.stringify({email: _email}));
req.send(JSON.stringify({'email': 'hard.coded@example.mail'}));
Is it because I'm using a GET request?
Isn't it possible to fetch data with a GET and having params in js or ...?
usually GET requests only accept query string parameters in the url itself
Oh, but is it possible or do I need to rewrite my server code?
so to do a proper GET request you would do ```js
req.open("GET", url + "token?fname=Henry&lname=Ford", true);
req.send();
to use json, you need your server to accept POST requests
How would I retrieve the data from a POST req then in js?
The same way as a GET request?
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();```
readyState 4 = request completed
this.responseText is the full response body as text
so you need to JSON.parse() it
the function must be set before calling .send()
the way to process the response is the same for GET and POST
Whats the difference between onreadystatechange and onload?
im not sure actually
i think they are the same
but for some reason people have always used onreadystatechange
Ait.
I would assume that onreadystatechange gets triggered when the request its state chages. (pending ect idk but when console logging onreadystatechange gets triggered 4 times)
And onload only gets triggered when the request got a response.
¯_(ツ)_/¯
Aha, thats why it gets triggered 4 times.
Thanks bro. ♥️
I'll rewrite my server and test the js code.
You're a good teacher. ^^
yea, Tim is really helpful
Tim is omnipotent and omniscient. He knows everything, feels everything. He is the ultimate guide to js.
When ur a non native english speaker and u see this as chinese: omnipotent and omniscient
lmao
@quartz kindle do it no balls
Tim do you have GitHub?
ye
Send me pls papi.
If you study Tim's github you will become a god
my github has almost nothing in it
lul
my bots are all private repos
because its all old shit code
and i dont want people to judge me
lmao
I just keep my shit code archived
I do have a lot of private repos that are up to date tho, just not open source
most of my projects dont even get to github because im lazy to put them there
i only put it there if it starts getting big
and i dont wanna risk an hdd failure
I use it because I ran into a big problem and needed to reset my vps and had no backups, it was my fault though.
I just dont wanna lose my beautiful code
alot of stuff i have as open source
some of my stuff is private like my School work
and an API that has to private stuff in
Every time i try to run my bot i run into the same error
SyntaxError: missing ) after argument list
I don't know what's happening here's my code
const client = new Discord.Client();
if(msg.author.id !== my-bots-id)
{
client.on('message', msg =>
{
msg.content = msg.content += "m";
msg.channel.send(msg.content);
msg.delete();
}
});
}
please help
@quartz kindle thanks, changing ecverything to a post request fixed it.
wtf's this syntax?
msg.content = msg.content += "m";
sorry i come from a c# background in programming
So?
i dont know javascript too well
It would even be wordse in C#.
You are trying to add a value to a var in a var.
Should be: msg.content += "m";
And now it will react to all messages.
I further don't know the dp.js syntax.
ok I changed that and its still outputting
SyntaxError: missing ) after argument list
Uhu, its bcs my eye fell on that and didn't fix the error xD
oh
Shouldn't it be like this?
const Discord = require("discord.js");
const client = new Discord.Client();
if(msg.author.id !== my-bots-id)
{
client.on('message', msg =>
{
msg.content += "m";
msg.channel.send(msg.content);
msg.delete();
});
}
^^
thanks
Doesn't your IDE give you an error for that?
What IDE are you using?
Oh, I prefer Webstorm or PHPstorm from Jetbrains. (I'm a lil Jetbrains fanboy tho xo)
Or VSCode.
its now outputting the error msg is not defined shouldn't it be defined with discord?
your code is literally inside out
why are you checking the id of the message author BEFORE receiving a message?
Oh yeah lmao
I didnt even see that just saw the curly bracket and parenthesis error
// nothing exists here
client.on("message", msg => {
// now you have a message here. you can check the message author
})```
Thanks
It worked
The bot seems to only do that to my message once, doesnt delete my message and builds on its own message
you need to ignore bots
else it will respond to itself
if(msg.author.bot) return
how do i use that?
@quartz kindle how would you approach this?
const myArray = {first: "data", second: "data"};
function getItem(array, item) {
console.log("Retrieving `" + item + "`");
const myItem = array.item;
console.log("Retrieved `" + item + "`");
return myItem
}
console.log(getItem(myArray, "first"));
would be array[item]
Thanks. ^^
but I wouldn't use the term array
I know
holy shit i was just finishing my framework for d.js master, and they just made a huge update that changed everything Lol
const arraymoprelikethis = ["jup"]
Whats the name for this in js?
{first: "data", second: "data"}
An object or?
I know that its called a dictionary in py.
object
holy shit i was just finishing my framework for d.js master, and they just made a huge update that changed everything Lol
Rip...
object
Ait. ^^
How would you export (module.exports) a custom error?
eg:
myLib.js:
module.exports = { ExampleError: Error.ExampleError };
class ExampleError extends Error {
constructor(message) {
super(message);
this.name = this.constructor.name;
this.message = message;
}
}
runFile.js:
const myLib = require("./myLib");
throw new myLib.ExampleError("Hello, world.");
NVM
Found it. ^^
I would also be interested how that works @ruby talon
I don't think that edit will work
@sudden geyser it does.
how though
yeah now, but classes are not hoisted to the top, so you may need to move it below
Wdym with that?
well 1: the Error class does not share a property named ExampleError.
2: classes are not hoisted to the top of the file like functions are (class vs function). I believe you'd need to move module.exports below the class declaration then export it, but just export ExampleError instead of Error.ExampleError
If you try to require it from myLib, you'll probably get undefined the way you currently do it I believe
It works for me rn. ¯_(ツ)_/¯
And gotta keep the Error. infront of it.
Or it doesn't find it.
@modern sable pls
@modern sable @static lantern is self advertising.
ty
@quartz kindle, back to the XMLHTTPRequest.
I changed the onload to this:
In the fetch function:
req.onload = function() { return fetchData(req, "token"); }
Outside:
function fetchData(request, data) {
const reqValue = JSON.parse(request.responseText);
if (request.status === 400) throw new BadRequest(reqValue["error"]);
else if (reqValue.statusCode === 401) throw new UnauthorizedError(reqValue["error"]);
console.log(reqValue[data]);
return reqValue[data];
}
Result:
Retrieving token...
Retrieved token:
undefined
zTWFfbT5RFNWgLGFIDxbuKuiTE4Zzc87fJwkTn9zmwY
The last thing is the expected token, but its console.log'ed in place of returned.
The undefined is returned, is there a chance you know why?
And gotta keep the Error. infront of it.
Or it doesn't find it.
It won't find it because it hasn't been declared to its level. Classes are not hoisted, but functions are. AndError.ExampleErrorreturned undefined for me, unless I'm missing something. ¯_(ツ)_/¯
IDK why, if I remove the error it gives me the undefined error.
Long live code lol.
it's not a property of the Error constructor. all you need to do is export it after the class has been declared and remove the Error. from it.
such as module.exports = { ExampleError: ExampleError }
has the class been declared above where you do UnauthorizedError: UnauthorizedError and in its scope
Oh whoops, I'm dumb.
@quartz kindle, back to the XMLHTTPRequest.
I changed theonloadto this:
In the fetch function:req.onload = function() { return fetchData(req, "token"); }Outside:
function fetchData(request, data) { const reqValue = JSON.parse(request.responseText); if (request.status === 400) throw new BadRequest(reqValue["error"]); else if (reqValue.statusCode === 401) throw new UnauthorizedError(reqValue["error"]); console.log(reqValue[data]); return reqValue[data]; }Result:
Retrieving token... Retrieved token: undefined zTWFfbT5RFNWgLGFIDxbuKuiTE4Zzc87fJwkTn9zmwYExpected result:
Retrieving token... Retrieved token: zTWFfbT5RFNWgLGFIDxbuKuiTE4Zzc87fJwkTn9zmwY zTWFfbT5RFNWgLGFIDxbuKuiTE4Zzc87fJwkTn9zmwYThe last thing is the expected token, but its
console.log'ed in place of returned.
Theundefinedis returned, is there a chance you know why?
Still unanswered
where do you expect the result to be returned to?
what is the context from where the entire request is being made?
are you trying to do something like this? js function request(...) { x = new xmlhttp(...); x.onload = function() { return fetchData() } } let token = request(...);
@ruby talon
Remeber the functions with the XMLHTTPrequest from around an hour ago?
Its in this context.
If I place the function its code in the onload it does function.
But since I have to repeat the same code multiple times over an over again with little to no changes I tought it would be nice if it was in a function.
yes but how is the code called?
because js is for the most part a non-blocking synchronous language
In a function.
get_token: function(url, _email) {
const req = new XMLHttpRequest();
req.open("POST", url + "token/", true);
req.setRequestHeader('Content-Type', 'application/json');
req.send(JSON.stringify({'email': _email}));
req.onload = function() { return fetchData(req, "token"); }
}
const mySE = require('../mySE/meSE');
const local_url = "http://127.0.0.1:5000/", mail = "mail@mail.mail";
console.log("Retrieving token...");
const token = mySE.get_token(local_url, mail);
console.log("Retrieved token:\r\n" + token)
see that is the problem
🙃
js is for the most part non-blocking sync, which means this is what happens:
So I need to make it async?
token -> fires function
function -> fires req.onload()
req.onload() begins waiting
function -> has nothing left to do here
function -> returns undefined
token -> received undefined
meanwhile req.onload is waiting in limbo, and when it returns, the value goes nowhere
so you need to make use of async yes
If I make the get_token async do I need to make the fetchData async 2?
there are many ways it can be done, traditionally everyone would use callbacks: ```js
function get_token(url,email,callback) {
x.onload = function() { callback(req); }
}
get_token(url,email,function(result) {
// result returned via callback
})
today, you can use the powerful async/await style as well as Promises, which is sort of an async task
BTW sorry if these are newby mistakes, I'm pretty new to JS.
whenever you are trying to fetch anything or simmilar you should use async as you never know when your request will return the data
for example http requests
or .then
im not good at explaining
but I think you get the point
a Promise is created like this: js promise = new Promise((resolve,reject) => { // using arrow functions, or a normal function like this: function(resolve,relect) { if(error) { reject(error) } x.onload = function() { resolve(req) } })
then this promise can be accessed in a callback style, like this: js promise.then(result => { // use result here }).catch(e => { // catch error here }) or in the new async/await syntax: js result = await promise(); // error will be thrown like sync code in order to use async/await syntax, your code must be placed inside an async function, like this js async function() { result = await promise() } so unfortunately you cannot use async/await syntax in the global scope
but its useful
you can create a function that immediately returns a promise like this ```js
function request() {
return new Promise((resolve,reject) => {
// do the entire xmlhttprequest here, then finally
x.onload = function() { resolve(result); }
});
}
then you can use it as a promise everywhere in your code: ```js
request.then(result => {
console.log(result)
});
async function() {
console.log(await request())
}
lmao
Promises can be daunting at first, it took me a while to understand them
but they are essentially what Tasks/Futures are in other languages
WaY eAsIeR in python, change my mind xD
nah
python is equally as difficult if you do it properly
once you get used to the syntax its not that bad
since XMLHTTPRequest is a very old api, it doesnt have any of this modern way of using it, so you have to wrap it
idk xo
there is a newer api in browsers that might be less complicated, the Fetch api
Gracias github
Its not exactly only for browsers.
Else I wouldvé used jQuery
node/nw/electron?
Currently using node, its also meant to go into electron.
if you have access to npm, you can use one of many http libraries out there
what made you start using JS over python 🤔
i recommend got
@modest maple I need to use it for this project.
And its all a learning experience, I also need to create the same lib in Cpp. xO
I already created a Python wrapper bcs thats my main lang, so its easy.
whats the wrapper supposed todo?
Interact with my REST API xo
in my opinion, although im not well versed in py or other langs, js is easier to use and requires less code to accomplish the same things, with the exception of decades old apis of course
@quartz kindle cough cough* requests.get()
and with the exception of node's low level apis
python is litterally just
import requests
r = requests.get(url, payload)
r.json
you could do it with aiohttp also
depends if u need async or not
Jup.
because essentially it has a built in api for it, which js doesnt
Requests is enough.
but you can get any js lib and do the same thing
Every lang has its pro's and cons.
python is orientated around modules alot more than JS imo
but for example, if you try manually coding an async task, using promises in js is easier than using futures/tasks in py, i think
@quartz kindle theyre pretty similar
you can just return like a normal function
and the async generator handles the rest
if you have multiple tasks you can use gather