#development
1 messages Β· Page 1250 of 1
Doing 'one' || 'two' will always return one because it's not an empty string (or a falsey value)
Hmm got it
aye
hasPermission('ADMINISTRATOR') || hasPermission('MANAGE_MESSAGES')
hm got that
can this work ? js if(2 < messagecount > 100 )return message.channel.send(`THE NO. OF MESSAGES TO BE CLEARED SHOULD BE BETWEEN 2 AND 100 !`);
oh sry me nub π
i edited it to reverse sign idk why
can you compare two stuff like that?
thats what i wonder
nice
okk
ah
you'll have to use &&
isnt it || for that example?
2 < messagecount > 100 is supposed to say "more than 2 AND less than 100"
|| operator is for or but this seperates to 2 different functions to be parsed and coerced to a boolean
but if you look at the response return message.channel.send(THE NO. OF MESSAGES TO BE CLEARED SHOULD BE BETWEEN 2 AND 100 !);
it just doesnt work now i feel
between
so it must be less than 100 and more than 2
if(2 > messagecount && messagecount > 100 )return message.channel.send(`THE NO. OF MESSAGES TO BE CLEARED SHOULD BE BETWEEN 2 AND 100 !`);```
if (messagecount > 100 || messagecount < 1) {
// Send the message
}```
make it or, because for that to trigger, message count has to be smaller than 2 and bigger than 100 at the same time which is impossible
i feel i am becoming dumb making my bot π
Learn badics of JavaScript or the programming language before making a bot
@earnest phoenix i have been confused with operators now
This is the best way to learn and not run into many issues
Everything allows operators
Volt's snippet allows the operator though
permissions dont
why permissions specifically
in the ''
Permissions resolvables can be an array
I gave you a snippet
hmm
hasPermission('ADMINISTRATOR') || hasPermission('MANAGE_MESSAGES')
Did this not work
Or just array check with flags
["ADMINISTATOR", "MANAGE_MESSAGES"].some(p => <GuildMember>.hasPermission(p));```
well my issue is solved so thank you !
Some functions and methods do not allow arrays or multiple params, as if you tried "ADMINSTRATOR" || "MANAGE_MESSAGES"
The reason it would always apply the administrator permission check is because, || operator checks if the first given arguments exists as in it's coerced to a boolean, if not continue, but in strings, they are always true
ohk !
Are empty strings coerced to false boolean?
messagecollectorstuff {
}
reactioncoolectorstuff {
}
``` is there a way to make the reaction collector run only after the message collector is done?
Yep, empty strings with no chars is false
@silver lintel Collectors have an end event, after the message collector, execute the given function as a parameter
<someMessageCollector>.on("end", ...fn)```
im only diong this because i need to run an await thing
but it doesnt work in a collector
Message.channrl.awaitMessages()({
//Need await here
}).catch (() => {});
hi
if i setup an express.js server on my computer without configuring the router port forwarding stuff it probably won't work outside of localhost right?
Message.channrl.awaitMessages()({
//Need await here
}).catch (() => {});
@silver lintel channrl
@earnest phoenix You obviously can't read buffer of something null, or something that has no buffer
oh
Could you tell me what I need to do? So that I can start
This never happened to me
const express = require("express");
const app = express();
app.post("/dsl_webhook", (request, response) => {
console.log(JSON.stringify(request.body));
});
const listener = app.listen(process.env.PORT, () => {
console.log("Your app is listening on port " + listener.address().port);
});
This does literally nothing when i test the DSL webhook.... why?
There is no output except Your app is listening on port 347238192689234823534923748
Make sure your port is open and there's no firewall that's blocking your requests
The port is open
i'll retest with HTTPS
Could you tell me what I need to do? So that I can start
@earnest phoenix Try reading buffer of something with node-fetch
ok sir
I'll try
@slender thistle the express.js server works fine with both HTTP and HTTPS
I'll try using phin to send a POST request to https://codeco-discord-bot.code913.repl.co/dsl_webhook with some sample data
@earnest phoenix
oh okok
I would have to put this on all assets?
.png
@slender thistle
const phin = require("phin");
// AFTER the express.js shit
phin({
url: "https://codeco-discord-bot.code913.repl.co/dsl_webhook",
method: "POST",
data: {
guild: 1234,
user: 1234,
type: "test"
}
});
still no work
Load fonts with jimp but to get buffer from links or image file paths, use node-fetch @earnest phoenix
ok
which port is the express server running on
understood
process.env.PORT changes randomly every time my program is run on repl.it
Oh well, try 8080
ok
@slender thistle 8080 works
lemme test the webhook with :8080 in front of the domain name
ok
THAT BRUH MOMENT WHEN YOU REALIZE IT WORKS AND IT JUST DIDN'T LOG IT IN THE CONSOLE man i'm retarded

ok so it works
but for some reason it logs undefined into the console
request.body is how you read POST request data in express.js right?
@earnest phoenix Let's not post links that have crypto miners in them btw, thanks
k
@earnest phoenix Let's not post links that have crypto miners in them btw, thanks
@slender thistle what do you think is better, getting bombarded with adverts or a cryptominer that is set to NOT take more than 5% of CPU
Adverts at least are less scummy than having your users mine shit without their consent π
that emoji existed and i didn't know wtf
@quartz kindle how would I read data from POST requests in express?
I have this rn:
app.post("/dsl_webhook", (request, response) => {
console.log(request.body);
})
it logs undefined in the console when i test the DSL webhook
tahpscreept
Yeah, I can see the anys
so
its just a test
what exactly does it do
mine?
yep
evals my code remotely
lmfao
i meant what is express.js doing when it recieves a POST request to /panels
*receives
fuck my english
you need to use the body-parser middleware

i thought it is normal JS
wait you can't send JS objects directly
please ignore my dumbness
Can't JS objects be visualized as JSON objects though
im pretty sure you gotta stringify it
Bruv, use inspect method of util to turn your object to a string
actually maybe im wrong
Literally
Nah, I think it should be stringified in any case
ok
which would make sense in any case
im not sure actually now
cuz i know axios handles a lot of that stuff in the background
@earnest phoenix I literally said the images not the fonts
Giving people existential crisis since my birth

No, it's stringified internally, as far as I'm aware
have you seen what i did yesterday?
which of these?
uhh
How to play poketwo
Let's assume I did but please explain
read above it aswell for context
It's ok

π what the fuck
iim dead serious lol, i went to request them for verification status on my bot to increase its rate limits
just running a test to have even more reason to request it
Pls work
you doofus
YES! IT WORKS! 
{
guild: '721707451375943740',
user: '503948134439976972',
type: 'test',
query: '?test=data¬RandomNumber=8'
}
wait did i just log normal JS instead of JSON into the console without it saying [object Object]



Of course, console can parse normal js objects without being stringified
smh
i once tried doing:
var smth = {};
console.log(smth);
and it outputted [object Object]
i wonder if youtube also has verified bots
100% gonna pokemon the fuck out of this and get my bot verified on discord, twitch and youtube

How ironic is it for my discord bot to get verification on another platform before i get it here?
fairly ironic I'd say
from the info they provided i should hear back within 2-3 days
meanwhile discord.....
well...
you get the idea

pretty much
not very experienced with web http shit
i am a down-to-earth node.js boi
so
what are headers and how do i check if the guy that sent the POST request sent the authorization header as my set password
3.1050K
sounds good
@earnest phoenix theres basically 3 things in a request, headers, parameters and body
headers usually arent exposed, params are in the url, body is the content of the payload
req.headers does not exists 
how you even checking for req.headers?
hey could anyone help me?
there is a !queue join (your message) command
where you can join a queue (your name will appear in the embed) with your tryped message behind your name
however, it actually deletes after someone else joins.
this is the code:
// If queueMessageId is still 0, no queue has been created
if (queueMessageId === 0) {
message.channel.send('A queue does not currently exist sailor '+ "<@" + message.author.id + ">");
// Otherwise, the queue already exists, so users can join
} else {
message.channel.messages.fetch(queueMessageId).then(queueMessage => {
if (addUserToQueue(message.member.displayName, message.member.id, args)) {
assembleQueueMessage();
queueMessageText += ' ' + message.content.slice(Config.prefix.length).replace(/^queue *join/, '').trim()
if (Config.useEmbeds) {
queueMessage.edit(embedQueue.setDescription(queueMessageText));
} else {
queueMessage.edit(queueMessageText);
}
} else {
message.channel.send(`${message.author} already entered the ship queue!`);
}
})
.catch(console.error);
}
}```
i tried installing the server count thingy on my bot, it says this (replace 'my bot dbl client token thingy' with my actuall token thingy)
const dbl = new DBL('MY BOT DBL CLIENT TOKEN THINGY', client);
^
ReferenceError: client is not defined
at Object.<anonymous> (D:\Download\Memes\Batch 2\CooldownsUPDATED\index.js:5:180)
[90m at Module._compile (internal/modules/cjs/loader.js:1076:30)[39m
[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)[39m
[90m at Module.load (internal/modules/cjs/loader.js:941:32)[39m
[90m at Function.Module._load (internal/modules/cjs/loader.js:782:14)[39m
[90m at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)[39m
[90m at internal/main/run_main_module.js:17:47[39m```
how do i fix this? thanks
well you haven't defined any variable called client
@kindred musk then you didnt define your client
what is your bot client's variable?
what, this is a commision bot i got i just added the lines of code from the documentation idk node.js

then use bot instead of client
though if you comissioned the bot you should likely ask the person who made it to do the changes
so to change that to const bot = new Bot.Client();
cuz i havent played with music/audio or opus
what?
so i likely dont know the answer for ur question Awsome
everyone comes after me
but they always receive help first
no offence
but it is really frustating
@earnest phoenix you would need to fetch the audit logs for that
first off
if (command === 'queue' && subcommand === 'join') {
// If queueMessageId is still 0, no queue has been created
if (queueMessageId === 0) {
message.channel.send('A queue does not currently exist sailor '+ "<@" + message.author.id + ">");
// Otherwise, the queue already exists, so users can join
} else {
message.channel.messages.fetch(queueMessageId).then(queueMessage => {
if (addUserToQueue(message.member.displayName, message.member.id, args)) {
assembleQueueMessage();
queueMessageText += ' ' + message.content.slice(Config.prefix.length).replace(/^queue *join/, '').trim()
if (Config.useEmbeds) {
queueMessage.edit(embedQueue.setDescription(queueMessageText));
} else {
queueMessage.edit(queueMessageText);
}
} else {
message.channel.send(`${message.author} already entered the ship queue!`);
}
})
.catch(console.error);
}
}```
now its redable
take a look at https://anidiots.guide/coding-guides/using-audit-logs for starters, @earnest phoenix , but you'll need to filter by bans, not by message delete
whats the issue awsome/
look
lookinh
attempts to magically guess what the original question meant
okay
with test test after their name
so as you see i used !queue join hello
it worked
but as soon as someone else joins with another message
mine gets deleted
the message or the queue?
as you see my friend joined iwht the message !test test
the message
behind the names
well nothing here is deleting messages so it must be part of some other code.
should i pastebin?
i guess that'd helpa bit
https://hastb.in/ please, pastebin has ads and kills my eyes
there's nothing about message deletion here either
also doing !queue test test shouldn't be triggering anything except line 350.
indeed theres no deletion
hmm what is the problem then?
you sure there isnt something else on another file doing the deletions?
or another process. or another bot.
it is my index
well, something else than this particular bot's code is deleting messages.
because this isn't it.
maybe because of this line:
if (userAdded) {
assembleQueueMessage();
if (Config.useEmbeds) {
queueMessage.edit(embedQueue.setDescription(queueMessageText));
} else {
queueMessage.edit(queueMessageText); ```
if someone gets added
there's nothing about deleting messages here.
you'd still get the bot name
even if you edit the embed payload
you see basically this
@umbral zealot tpye something

β
wut
you'd see that
if you edit with blank
the message itself doesnt get deleted
if you send an empty edit im pretty sure api throws an error too
so its not empty
i have a prefix command that changes the prefix for my bot and if you change it to \ it crashes the bot anyone know how to prevent this?
I dunno at this point the best advice is to just start console.log(allthethings) and figure out what your values are, what gets triggered, what changes your variables, etc.
what? of course it's not bad.
of course it is
why is it bad
use a debugger for debugging
you follow the script as it runs
you see real time variables and values
yeah I get that debuggers are better but saying console logs are bad is a ridiculous statement.
yeah I get that debuggers are better but saying console logs are bad is a ridiculous statement.
unless you know whats wrong, console wont do any good other than a bunch fo try and errors
which they dont know whats wrong
so follow the code with a debugger instead
@errant perch show us the code and the error
Unexpected number in JSON at position 255
are you manually editing a json file???
userData.serverprefix = args[1]
fs.writeFile("./prefix.json", JSON.stringify(file), err => {
if (err) console.error(err);
});
message.channel.send(`Server Prefix set to ${args[1]}`)
break;```
no
then something went wrong in your stringify because that shouldn't happen, it should have been escaped.
@errant perch \ is escaping that "
yes
just "\\"
how do i prevent people from doing it though
you really shouldn't be using a json file as a database anyway
that's your main problem
but im lazy


Why shouldnβt I use a JSON file as a database?
A JSON file is not suitable for use as a database for several reasons.
Firstly, you will incur a major performance hit as you need to read from and write to the file on each query and modification. This brings a major performance impact especially when the amount of data increases.
Second, you cannot concurrently write to a JSON file - only one write can be performed at a time. This is part of what causes the performance impact, but perhaps more importantly may introduce unexpected results and even file corruption.
JSON files are also human readable and easily accessible by end users. This means that your database and application will be vulnerable to attacks, especially as database reads are rarely checked for malicious code (Which usually happens on write).
What should I use instead?
An actual database, to put it bluntly. SQL, NoSQL, whatever takes your fancy. Some SQL databases are SQLite, PostgreSQL and MariaDB, while NoSQL databases include things like MongoDB, RethinkDB, ArangoDB and many more.
What can I use a JSON file for?
JSON files are best used to store static data, in other words data that doesnβt need to change often or programmatically. In practice, this means configuration and other application data that needs to be defined by a human - which is what JSON excels at.
Also see: #development message
^^
being lazy isn't the same as taking the wrong decisions and endangering your own settings.
Be lazy. Corrupt JSON. Lose all data. Mass send messages saying 'sorry for incovenience'. Mob of angry users who lost their settings. Regret life decisions. Using database after being a stubborn cuck
it'll be easier to use a proper database, so use that laziness to your advantage.

here, most of the code is done for you you lazy bastard π https://enmap.evie.dev/complete-examples/per-server-settings
It'll bite your own bum in the end
lazy devs at least find good solutions for problems
i've just lost all motivation and hope
so your fault if the data is corrupt and irreversible
Actually good devs are lazy devs, because they'll make sure to write good code that they'll never have to fix in the future
so right now you're having to fix a problem that would not happen in a database.
which wont keep newest data
right that's still stupid, not lazy, though.
just use a database, I literally gave you an example that's going to be super easy to implement even for a lazy bum like you
ok if i must
successfully helped someone point a shotgun away from their own foot
sometimes you just wanna get shot
you backed up a json file in google docs?
then by all means,use JSON database
yes
Those who do not learn history are doomed to repeat it.
dont have im too lazy to get one
why not leave it guys
can i add my bot here ?
cmon im enjoying the constant berating
oh no, he's crazy
It was constructive criticism π
more like a fair warning tbh, its better to do stuff properly right away than regret later
can i add my bot here ?
Answer pls
@woven gale #502193464054644737
+help
How can i add ? Please tell me i cant find it @opal plank

I am from turkey can u tell me ? Can i add or not if i can add how?
turkey is good
Yeah i added
it prefer it over ham
then wait
Okey
3 weeks
What
i have had my bot submitted for 5 weeks
wait 3 weeks
:/ ok
4% left

im pretty sure you cant
you need to loop each entry
yes
fetch 50 and then filter them

@peak osprey https://discordjs.guide/
so close

@commands.has_permissions(administrator=True)
async def changeprefix(self, ctx, prefix):
"""Change the servers prefix. Note: Only server admins can use this command."""
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
await ctx.send(f'Prefix changed to `{prefix}`')```
This code has given me the `FileNotFoundError: [Errno 2] No such file or directory: 'prefixes.json'` error. I have the file with the same name, but do I need it to be `cogs/prefixes.json`?
This is discord.py btw
try it and see
Also read: #development message
@misty sigil we've made an infinite loop of referencing! π
It's silly I wish I could use @potent eagle in here it would be useful π
btw guys this wass my problem
this is when i join the queue
this is what happens when someone else joins.
look
could someone please have a look at my code
what
what the fuck are you saying m8?
srry
okay it's all good.
@autumn aspen please don't say anything, if you can't do anything.
@keen solstice #commands
@eternal osprey i will take a look at the code, please be patient
Is there a way to reload my index.js file without having to restart my bot?
@eternal osprey Hey! i have read your code! but i can't understand it! so i came up with tips
i highly doubt you'd be able to re-require your index cache
@autumn aspen please don't say anything, if you can't do anything.
@earnest phoenix yo can u like stop be rude
Ok I think u have to change ur "attitude"
I am sick right now, please drop the conversation, thanks.
https://kooleyy.is-inside.me/gSg4DuUi.png we should stopβ’οΈ
Zobros
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee ._.
@eternal osprey If possible please rewrite your code to
- Have Command Handler
- Have Event Handler
- Put function in JS file
both command and event handler can be done by usingfsmodule
it will greatly improve your code readiblity and performance
okay, sorry buddy!
how does a reload command work though 
π€’
||If you give up,you delete and re-require cache|| @thick gull
Don't judge his code, he's a beginner, and he's willing to learn, and not expecting spoonfeeding code.
const evtFiles = await readdir("./events/");
client.log("log", `Loading a ${evtFiles.length} events.`);
evtFiles.forEach(file => {
const eventName = file.split(".")[0];
const event = require(`./events/${file}`);
client.on(eventName, event.bind(null, client));
});
this is beauty π
make it one line smh
i remember my code to be like that
await readdir? why not readdirSync
why the fuck did you spoonfeed code?
dynamic handling commands, i got something similar
though the problem is that events require different params
using fs and JSON.parse /s
unifying it is a pain
There's a lot of command handler out there
one use fs
one manually register command
nor am i interested in copying that
I mean that's just part of a bot's code I could copy/paste.
it's not exactly going to work without more work to integrate it.
that's why you don't spoonfeed beginner
Starwoman
yeah I'm aware of how spoonfeeding works and why it's bad, kthx
he isnt spoonfeeding here
i wasnt asking for code either way
I was comparing my beautiful code with Erwin's.
i just showed my events
and hind is dynamically handling them
hind i am so fucking sorry
Hey, admitting your faults is the first step to being a better person! 
though in my case cuz typescript i'd need to massively work on that
i thought you give code to awsome guy
Nah. I have guides for that though.
i am so fucking sorry
They may or may not have small mistakes in them preventing them from being copy/pasted directly.
It's fine, Star. ^_^
hi
1h vs 8h from before
massive improvement but i still think i can tune it down to 40 if i try hard enough
code

no
1 Either use a webhook
2 or check if user voted every x second and if they voted, put it in a list (not recommended)
AAAAAAAAH
why?!
im waiting 4x more than the API docs say the ratelimit is
WHAT THE FUCK
someone please do explain

19 joins, thats 19 seconds,+ 11 seconds when the bucket limit is down to 1 remaining, thats 30 seconds
and i still get ratelimit
NANI THE FUCK
collection.update_one({"_id": author_id}, {"$set":{"purse":str(purse + coinstogive)}}, upsert=True)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: can only concatenate str (not "int") to str
any1 know why?
you cant add an integer to a string
try converting the integer in str(purse + coinstogive) (idk what one the int is) to a string before continuing
means
oh wait no
im dumb
are you tryna add 2 values together?
@drifting wedge
yes
maybe one is a string
and then sending it to mongo
and cant be added to a int
well its a number
try converting the one you believe is a string to a number
so i can turn it into a int?
if you are trying to add 2 integers together and one is a string, it'll fail so
if you think one of these 2 values is a string, convert them before adding
can only concatenate str (not "int") to str
indicates that its trying to add a integer to a string
basically like "this will have a " + 0 + "% success rate"
basically json features in vs code dont load the document fully when its above 5000 chars
@eternal osprey are you using JS as DB?
to prevent your pc from, well, oofing
If yes, please switch
i would recommend changing your strategy if these files are a normal thing in your workspace
and for god damn sake, dont use a json db
please
i know but this is just for now
i don't want to start all over
and i am only known with json databases.
you can just change your json db to quick.db
quick.db is like the most easy db to use for a small project
that can't be all
i can help you migrate from json to quick.db
sure
basiclly
the easiest way is to
read data from json and transfer it to quick.db
so you have to loop throught the data
not that difficult, but can be a bit challenging when you have many nested properties
^
Object.keys(yourDbObject) returns all keys from that object, which you can then loop through
It's not hard
Object.keys(yourDbObject).forEach(key => {
let valueToKey = yourDbObject[key]
// set value to quick.db's database here, using "key" as key and "valueToKey" as value
// example: db.set(key,keyToValue)
})
that can be done in the node.js live shell, no need to make a script for it
just open cmd, type in node and you are set
hmm
how do i store this mesage behind my name?
// If queueMessageId is still 0, no queue has been created
if (queueMessageId === 0) {
message.channel.send('A queue does not currently exist sailor '+ "<@" + message.author.id + ">");
// Otherwise, the queue already exists, so users can join
} else {
message.channel.messages.fetch(queueMessageId).then(queueMessage => {
if (addUserToQueue(message.member.displayName, message.member.id, args)) {
assembleQueueMessage();
queueMessageText += ' ' + message.content.slice(Config.prefix.length).replace(/^queue *join/, '').trim()
if (Config.useEmbeds) {
queueMessage.edit(embedQueue.setDescription(queueMessageText));
} else {
queueMessage.edit(queueMessageText);
}
} else {
message.channel.send(`${message.author} already entered the ship queue!`);
}
})
.catch(console.error);
}```
cuz
if someone else joins with a message
it gets delete (the previous mesage)
i have been trying to fix this for over 2 freakin days.
anyone that can help
How do I use catch to catch an error?
What was setNickname changed to?
Nevermind, just figured it out
if(command == 'clown'){ //clown
if(message.mentions.roles.size || message.mentions.everyone) {return message.reply('Improper mention.')}
if(!message.member.hasPermission('ADMINISTRATOR')) return message.channel.send('You must be an admin to use this!')
let newClown = message.mentions.users.first()
if(Clowns.has(newClown.id)) {
Clowns.delete(newClown.id)
message.channel.send('removed clown')
}
else {
Clowns.add(newClown.id)
message.channel.send('new clown!')
}}
client.on('message', function(message){
if(Clowns.has(message.author.id)) {
message.react('π€‘')
}
})
``` I finally got this to work properly, but after I use the command once and do it two more times, it gets really slow at reacting. Is my code just slow or is there something wrong?
<user>.send
Yes but by ID
get them from the cache
get the id from the cache
because when I use the cache one it says cannot read property of undefined
so do i needa store the member list fiorst?
are you sure itβs a valid ID?
user.send(`${message.author.id}`);```
724066932701134979 is me
says user isnt defined or not usable
are you in the cache?
try .fetch() 
fetch returns a promise iirc
so lemme do my .then
TypeError: client.users.cache.fetch is not a function
at D:\dbots\Emit\commands\purchase.js:22:49
at processTicksAndRejections (internal/process/task_queues.js:97:5)
oop
don't use cache
okie
fetching doesn't require cache
collection.update_one({"_id": author_id}, {"$set":{"purse":str(purse - int(arg))}}, upsert=True)
collection.update_one({"_id": member_id}, {"$set":{"purse":str(purse + int(arg))}}, upsert=True)```
fetching doesn't require cache
@strong geode I need to login too, right?
because it uses the client token
how can i make sure that the arg is an int
!isNaN if you want to make a return part for your code like if(!isNaN(args[3]))return; wrong language
arg.isdigit() returns True if the arg is a number
it sends the message to me, but for sum reason it says user.send isnt a function
Imagine seeing Python and suggesting JS functions
agreed
lmao
jk
Imagine seeing Python and suggesting JS functions
@slender thistle I didnt read his code, just saw he wanted to check if its a int
@slender thistle I didnt read his code, just saw he wanted to check if its a int
so did i π
What do I want to say about this
You want to say that somehow python is better?
Nothing other than "why try to blindly help"
what if hes using some npm package to implement python in js code?
Imagine seeing Python and suggesting JS functions
@slender thistle I prefer to give answers in a different language, since it would explain how to go about something, but not spoonfeed
Last time I checked pymongo wasn't an npm package
idk bro
dude you dont needa flex ur superior coding skills
Well it'd be a failed parse/cast then
My main point is, you suggesting an "isNaN" function when there's no such thing in Python is only confusing for a beginning Python dev
IsNaN wouldn't be hard to implement in another lang regardless
And oh boy, that "beginning" part should be emphasized with bold caps
Well, there's no NaN anyway
More like if arg.isdigit(): arg = int(arg)
public static bool IsNaN (object obj)
{
return double.TryParse(obj, out double unusedDouble);
}
Something like that for C# I'd imagine
Or try/catch an explicit cast
mmm exceptions
I'd imagine that's how tryParse is implemented
Exception handling to return a Boolean
hey how do i save my messages?
it started happening recently
if (command === 'queue' && subcommand === 'join') {
// If queueMessageId is still 0, no queue has been created
if (queueMessageId === 0) {
message.channel.send('A queue does not currently exist sailor '+ "<@" + message.author.id + ">");
// Otherwise, the queue already exists, so users can join
} else {
message.channel.messages.fetch(queueMessageId).then(queueMessage => {
if (addUserToQueue(message.member.displayName, message.member.id, args)) {
assembleQueueMessage();
queueMessageText += ' ' + message.content.slice(Config.prefix.length).replace(/^queue *join/, '').trim()
if (Config.useEmbeds) {
queueMessage.edit(embedQueue.setDescription(queueMessageText));
} else {
queueMessage.edit(queueMessageText);
}
} else {
message.channel.send(`${message.author} already entered the ship queue!`);
}
})
.catch(console.error);
}
}``` i want to save the args put in by the users
so it doesn't get deleted
and stays in the embed
how can i do that?
cuz i have a problem
letter
@earnest phoenix are you doing something like startsWith or contains?
but no-one knows the answer
nvm i found out why it does that
any help?
cuz i have a problem
@eternal osprey double check your{and}count
@thick gull yes?
n v m
if arg2 == True:
collection.update_one({"_id": author_id}, {"$set":{"purse":purse - arg}}, upsert=True)
collection.update_one({"_id": member_id}, {"$set":{"purse":purse + arg}}, upsert=True)
if arg2 == False:
await ctx.send('Please use a valid amount of money!')```
does this work?
the purse - arg or purse + arg is giveng some error
Is there a way to look for a certain word within a sentence? I tried to make a "bad word" filter but whenever someone said class, it triggered as ass. I used the message.content.includes command for it.
try using regex
do I need to end breaks for switches?
break;
or only on the last break?
you need breaks but it's optional on last because it's going to break out anyway
if you don't add break, it'll continue looking in the switch until the end
which defeats the purpose
there seems to be a trend of people who ask questions and don't stay for the answer
but idk
@drifting wedge if arg2 == True:
arg = int(arg)
im trying to run a bot 24/7 and im trying to do this technique but my command prompt says invalid path ThisPC\Desktop\DiscordBot and it says the system cannot find the path specified
just run the program from the ide console
if(PersonWritingCommand == 173489654144696320) {
const str = message.content.toLowerCase()
const badWord = ['word1', 'word2', 'word3', 'word4', 'word5', 'word6', 'word7']
const LookForCuss = str.search(badWord)
if(LookForCuss) {return message.reply('cuss detected')}
}
``` Any idea why this doesn't work? I've never used regex before, sorry if this seems simple.
The ID should be a string
it's python
it's js
WAIT
i'm retarded
.search takes in a string or regex pattern to search for, not an array
Is there a way to seach for words in an array?
something about it made me think it's py 
The code shouldn't even execute
an example regex that matches "ass" by itself: \bass\b
Can something like that work in an array?
you could create a single regex that matches every bad word in your bad-words-array
array.some()?
that too
How can I check if a string is just numbers
you can use !isNaN(number)
@drifting wedge if arg2 == True:
arg = int(arg)
@slender thistle why would you ever do == True or == False...?
@pale vessel so number would be the string
yes
!isNaN(args[1])
it'll try to convert it to a number and check
yeah
that checks whether a number is Not a Number or not. adding ! makes it do the opposite
k thanks

I usually do if x == False if it's something public and the thing is supposed to be stricly False
strictly
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for -: 'str' and 'int'
arg2 = arg.isdigit()
if arg2 == True:
arg = int(arg)
collection.update_one({"_id": author_id}, {"$set":{"purse":purse - arg}}, upsert=True)
collection.update_one({"_id": member_id}, {"$set":{"purse":purse + arg}}, upsert=True)
if arg2 == False:
await ctx.send('Please use a valid amount of money!')
await ctx.send(f'You have given {member.mention} {arg} coins!')```
What's purse
for purs in prs:
purse = purs["purse"]
bnk = collection.find(memberid)
for bk in bnk:
bank = bk["bank"]
inventory = collection.find(memberid)
for invt in inventory:
inv = invt["inventory"]```
its a currency system
purse is the money you have on you
I usually do
if x == Falseif it's something public and the thing is supposed to be stricly False
@slender thistleif !xis the same. It just looks amateur to compare booleans within a conditional
p.s. strictly False and not anything generically falsey
Oh wait, are you saying x could be something other than a Boolean?
In some cases it can. Not here though.
But it's more verbose so I don't blame anyone for doing it
I'm used to strict type languages. But ig you could do that if it implicitly parses like "True" == True
I sometimes don't get a single fucking idea of what my variables return in if aaa: π
Ehhh
"E" is true, "" is not
I'd be very careful returning dynamic datatypes
Leads to a lot of avoidable runtime errors
We're talking Python here
Sigh, right
π
I do use type annotations a lot though
Though eh...
Nested Dicts and Unions for Lists is a bleh
if not not "E": ...
if not not not not not not not not not not not False
help
Let's be actually helpful
β yes β xd
@earnest phoenix what's your code looking like
this fucking channel man istg
YEET
Please stay away from this channel if you're not going to help
they asked for your code
@sonic lodge which one
the javascript file?
that's your bot.js file?
yeah
why does that look exactly like the code i copied pasted when i started making a discord bot
Β―_(γ)_/Β―
...
ok
that is some old old old code
discord.io deprecate as fuc man
like three years ago
Skid
so i'm 91.75% sure that isn't your bot.js file
@earnest phoenix if you wanna be insane donβt be skid
var logger = require('winston');
var auth = require('./auth.json');
// Configure logger settings
logger.remove(logger.transports.Console);
logger.add(new logger.transports.Console, {
colorize: true
});
logger.level = 'debug';
// Initialize Discord Bot
var bot = new Discord.Client({
token: auth.token,
autorun: true
});
bot.on('ready', function (evt) {
logger.info('Connected');
logger.info('Logged in as: ');
logger.info(bot.username + ' - (' + bot.id + ')');
});
bot.on('message', function (user, userID, channelID, message, evt) {
// Our bot needs to know if it will execute a command
// It will listen for messages that will start with `-`
if (message.substring(0, 1) == '!') {
var args = message.substring(1).split(' ');
var cmd = args[0];
args = args.splice(1);
switch(cmd) {
// !ping
case 'ping':
bot.sendMessage({
to: channelID,
message: 'Pong!'
});
break;
// Just add any case commands if you want to..
}
}
});``` yup
quick ass google search found it
found it here too
Lolll
yeah im new to this type of shit
its quite obviously copypasted
So donβt copy codes
so go and learn some js i say it'll make it so much easier
Learn the basic
genuinely
how can i fix this
if(PersonWritingCommand == 173489654144696320) {
const badWord = ['word1', 'word2', 'word3', 'word4', 'word5', 'word6', 'word7']
const badWordCheck = badWord.some(e => message.content.toLowerCase().includes(e))
if(badWordCheck) {
{return message.reply('cuss detected')}
}
}
``` this still detects if I type a bunch of gibberish like this dasjndsjfdnkjsfnword1jkasdnfjsd as long as one of the words is in it. How can I make it so it only triggers if the word is by itself like "blah blah blah word1 blah blah blah"

combine regex and .some
turn each word into a regex that detects the word by itself and use that in .some instead
so I can't just do it through an array?
you can
change your array of words to an array of regexes and in .some, see if the current regex matches the given string
@misty sigil I did not understand you
I had this problem a while ago and I didn't know the reason @misty sigil
@misty sigil here
It has changed and nothing has happened, but the main problem is there @misty sigil
Kinda decent, do the same stuff for suggestion.
um so
i made a user object
and i send a msg to the user
and it sends
bc i got the msg
and?
but it sends user.send isnt a function
then it's not a proper user object.
yes
DMs
const user = client.users.fetch('724066932701134979').then((user) => {
user.send(${message.author.id});
})
message.author.send
fetch returns a promise iirc
const member = message.guild.member(user);
Ok what do I do to make it work @misty sigil
k
member.send
member.send
@solemn leaf is that stuff like sending dms to people and not people who asked it ?
message.author.send
Wdym of that ?
I really need help for music function lol, I failed on every tutorial lol.
Can embed accept no url images?
@fickle arch what are you struggling on with it?
hey
from requests_html import HTML, HTMLSession
# Nike SNKRS Lauch Calendar
NIKE_SNKRS_URL = 'https://www.nike.com/fr/launch'
# Create requests-html session Object
s = HTMLSession()
# Create response for Nike SNKRS Launch
r = s.get(NIKE_SNKRS_URL)
# Contains the HTML
html_of_site = r.html
# Functions
def get_nike_shoes(html_of_site=html_of_site):
'''Return the first five shoes in the launch calendar.'''
select = "div[class='d-sm-tc va-sm-m']"
shoes_and_releases = html_of_site.find(select)
list_of_shoes = []
for shoe_and_release in shoes_and_releases:
list_of_shoes.append(shoe_and_release.text)
return list_of_shoes[0:5]
def get_links(html_of_site=html_of_site):
'''Return the first five links for the shoes in the launch calendar.'''
select = "a[class^='ncss-col-sm-8']"
links_for_shoes = html_of_site.find(select)
list_of_links = []
for link in links_for_shoes:
list_of_links.append(list(link.absolute_links)[0])
return list_of_links[0:5] ```
i want to scrape this part too:
the p
how can i do that in my code?
i am using opera gx
don't know about opera
don't know
on firefox i just do this
which would get me this
/html/body/div[1]/div/div/div[1]/div[1]/div[2]/div/div[3]/h2/span/div
downloading firefox right now
hold on
this is how i am accessing the other info
select = "div[class='d-sm-tc va-sm-m']"
can't i just do
https://requests.readthedocs.io/projects/requests-html/en/latest/
you're using this lib, right?
select = "div[p]
well you'd be selecting any div with a p child
that's why you'd use xpath instead
yeah
specific path to an element
okay let me get firefox
okay
i have firefox installed
how do i select the xcode thingy?
nvm got it
/html/body/div[2]/div/div/div[1]/div/div[3]/div[2]/div/section/div/div/div/div/p
the xpath
so now i should just put it in?
Oh I love xpaths
hmm
It's best to be as vague as possible so it's now resilient to changes in the page. Kinda like regex
/html/*/selection/ul/li[1] for example
I forgot xpaths queries though
But you can select where text property= "something" too
Or n-child of x
And it has conditional ANDs
A lot like regex really
hey
your object is undefined. undefined objects do not have any properties.
using aframe
how can i <a-entity kinema-body="radius: 0.8" movement-controls="fly: false" position="0 0 4" look-controls>
look controlls but replace with like moving mouse
TypeError: Cannot read property 'aliases' of undefined
what is this error?
@main chasm Basically, youβre missing a period somewhere. Show your code
lipd thats not always the case. that error simple means your grabbing a property from an undefined object. a missing . can be a cause, but its not the only cause. if you were to grab a property that doesn't exist on another property that doesn't exist on a Object with a Type, it will throw that error.
@vernal rivet fixed thank u su much for help













