#development
1 messages ยท Page 936 of 1
Mhm
man, changing from v11 -> v12 has taken me so long already, still not finished ๐
literally like a month and a half now ๐
how?
regex is your best friend
and enemy sometimes tbf
So I never really ask for help anymore but right now I need some I have a command
const Discord = require("discord.js");
const bot = new Discord.Client();
const snek = require('snekfetch');
exports.run = async (client, message, args) => {
const speech = args.join(' ');
if (speech.length < 2) return message.channel.send(`${message.author.username} You must supply text for Yoda. Yes.`);
const { text } = await snek.get(`http://yoda-api.appspot.com/api/v1/yodish?text=${encodeURIComponent(speech.toLowerCase())}`);
message.channel.send(JSON.parse(text).yodish).catch(console.error);
}
It's supposed to take the text provided and return it as Yoda text but it's having issues parsing the JSON response and I get a error ```at JSON.parse (<anonymous>)7:43 AM
Jump Toat Object.exports.run (/app/commands/yoda.js:8:31)7:43 AM
at processTicksAndRejections (internal/process/task_queues.js:86:5)7:43 AM
[FATAL] Possibly Unhandled Rejection at: Promise Promise {7:43 AM
<rejected> SyntaxError: Unexpected token u in JSON at position 07:43 AM
Error is related to the website response, I have checked to make sure the site still works.
I have also attempted to use node-fetch
^
I have code for it in node-fetch 1 sec
New Yoda CMD
const Discord = require("discord.js");
const bot = new Discord.Client();
const snek = require('node-fetch');
exports.run = async (client, message, args) => {
const speech = args.join(' ');
if (speech.length < 2) return message.channel.send(`${message.author.username} You must supply text for Yoda. Yes.`);
const text = await snek(`http://yoda-api.appspot.com/api/v1/yodish?text=${encodeURIComponent(speech.toLowerCase())}`)
.then(res => res.json()) // expecting a json response
.then(json => {
message.channel.send(JSON.parse(body).yodish).catch(console.error);
});
}
Error with that ^^ is text is not defined
why did you put it inside a constant
๐คฆ๐ปโโ๏ธ you know I had a feeling it was the const
So just ```text = ()``?
also where do you define body
also where do you define
body
@sudden geyser I don't I had that as text originally just changed it a few minutes ago
Yeah lol I'll change it back to text, thanks for your help guys ๐
you don't need text = ()
simply ```js
snek(http://yoda-api.appspot.com/api/v1/yodish?text=${encodeURIComponent(speech.toLowerCase())})
.then(res => ...)```
Yeah I will do that lol it confuses me even
Hey guys I'm still having this error: ```
UnhandledPromiseRejectionWarning: Error: WHERE parameter "user_id" has invalid "undefined" value
and yet again this is my code:```js
const target = msg.mentions.users.first() || msg.author
const user = await Users.findOne({ where: { user_id: target.id } })
// Messed Up Code ^^^^^^^^^^^^^^^^^^^^^^
const items = await user.getItems()
i'm not sure what went wrong as when I console.log(target.id) it gave me my discord user id
Does the db have that user as an entry?
yes
I have another command called balance that gets the balance of the current user
and that command works like a charm
Can someone give me a solution for my bot running on discord.py turning off whenever my PC sleeps?
PM me please
Host it
@cold ivy pm2
hmm
@cold ivy your bot only works while your bot program is running, if the program stops running, so does the bot
well, thats why i said pm2
pm2 wont help
he said hes self-hosting and his pc sleeps
@quartz kindle my bot has reached 75 servers and i have done verifiacation how long untill i get this 
mine took 3 weeks
brUH
that's pretty fast
why are u look so angry 
do you have any free hosting solutions for discord.py
heroku is good but it can have frequent downtime when using a free account @cold ivy
i have a free account and i never get downtime
its been 2 months and its easy , when i want to update my code i go to github and commit changes and 3 mins later its updated
hmm, i used heroku to host an owasp juice shop ctf and there was alot of downtime
as in down you mean it does not listen for commands?
no heroku is perfect for me my bots always working
for you

Heroku works fine tbh
i guess i'll try heroku
when it is down does it still listen for commands
no
downtime means that the bot goes offline for a while
that wont work for me
Unless you get the credit from github education pack
still no
Which only lasts for 2 years
Doesnt the hobby dyno
hobby might work differently
I'm pretty sure that's what it does
2 years is a long time though
Ye
i'm sure by that time you already have money to buy a vps
pm2 or tmux
has anyone worked with sequelize?
I have
cool
I need help with this error
UnhandledPromiseRejectionWarning: Error: WHERE parameter "user_id" has invalid "undefined" value
and this is the code that I suspect is wrong is this:```js
const target = msg.mentions.users.first() || msg.author
const user = await Users.findOne({ where: { user_id: target.id } })
const items = await user.getItems()
module.exports = (sequelize, DataTypes) => {
return sequelize.define('users', {
user_id: {
type: DataTypes.STRING,
primaryKey: true,
},
balance: {
type: DataTypes.INTEGER,
defaultValue: 0,
allowNull: false,
},
}, {
timestamps: false,
})
}
this is the Users model btw
can you console.log target
i can
that would be helpful with debugging
it gives me the Discord User object
then it should work
thats the problem
what exactly is Users
it's a sequelize model
Alright so its a database
yeah
i have a file called avadb.sqlite which is the sqlite db for my bot
idk how sequelize fucked up
Doubt it's a problem from sequelize
Are you sure the error is coming from that line? I think you are trying to set it to undefined
i'm sure that the error is coming from that line
It's showing a stack trace where the error origin is /Users/daydream/Developer/ava/commands/inventory.js
on line 13
column 57
well, i guess i'm gonna try quick.db
you are making a mistake
And probably has 1/10th of the features sequelize has
quick.db
features you are almost guaranteed to use
user_id has undefined value
your're finding value but not added any value to user_id
Set id value user_id then use findOne
quick.db is useful but you can run into alot of errors if you dont know how to use it.
will starts with install error
lol
How would i sum the values inside
[ {
value: 123
}{
value: 234
}]```
iterate over the array and add up each .value
You can use <Array>.reduce for example.
already doing a forloop
just wondering wether i did my reduce correctly?
TotalRating = ShipStore.reduce(
(acc, currentRating) => {
return acc + currentRating.total
}
);```
so in ShipStore.rating is the value i need
did you try it? An example for the array you gave above: js arr.reduce((prev, val) => prev + val.value, 0); // The second argument is what the value at the start should be.
ah so currentRating.total should be ShipStore.rating instead
currentRating is the current element in the array you're running. So whatever you want to add up should be off that.
cosmitir are you using discord.py because I think it's .nsfw on a channel
๐ค
the reducer just adds the numbers after one another 0145696720381386118823171148155014339901541
instead of like .f.e the last 2 are 990 and 1541
let TotalRating = ShipStore.reduce(
(acc, val) => {
return acc + val.yrating
}, 0
);
console.log(TotalRating)```
I need help with addrole command
Ok
I'm trying to do a addrole command but i have troubles to add the role to the member
Hello. can someone tell me if there are any errors in this code
helium.on("message", async(msg) => {
let chatmoderators = ['539195184357965833', '550170362248429568', '437019658374348801', '641795527444529152']
if (msg.author.bot)return;
if(msg.channel.name !== 'helium-global-chat')return;
msg.delete()
let e = new Discord.RichEmbed()
.setTitle("Helium Global Chat")
.setAuthor(msg.guild.name, msg.guild.iconURL)
.addField("Message content", msg.content)
.setColor("RANDOM")
.setThumbnail(msg.author.avatarURL)
.setTimestamp()
.setFooter(`Helium Global Chat System || SECURITY | Guild id: ${msg.guild.id} | msg author id: ${msg.author.id} | code by Airbus A350-1000#0001. thanks to him, this bot will have a functioning global chat.`);
if(chatmoderators.includes(msg.author.id)){
e.addField("Sent By", `๐ ๏ธ Chat Moderator | **__${msg.author.tag}__**`)
}else{
e.addField("Sent By", `**__${msg.author.tag}__**`)
}
await Promise.all(helium.channels.filter(c => c.name === 'helium-global-chat').map(c => c.send(e)))
await Promise.all(helium.channels.filter(c => c.name === 'helium-global-chat').map(c => c.setTopic(`Last message is sent by <@${msg.author.id}>`)))
gcauthor = msg.author.tag
gcauthorid = msg.author.id
gccontent = msg.content
})
discord.js v11.5.1
i define the target as message.users.mentions.first() and then if i want to use target.roles.add(specific role) it doesn't work, i get that error
Cannot read property 'add' of undefined
it is
@sudden geyser ok how do i reverse it?
in php i can use !()
in python meh idk
while i wait gotta search google
php ๐คข
let rMember = message.mentions.users.first();
var rrole = message.mentions.roles.first();
rMember.role.add(rrole.id);
@pale vessel
chill
well i want to learn a bit from a lot languages
why do some people hate php
not
idk
@pale vessel help ?
outdated, Outa love, outa luck
better system exist which just out do php
i like php tho ngl
.
- PHP encourages an insecure programming style by design
- The language is a minefield of hidden security problems.
- The documentation is full of harmful advice.
- PHP created by coders who never understood - value of time, business processes, ROI, etc. Most common use for code is in business world; PHP does not understand how IT works efficiently in a business world; it is for geeks only.
- It took years for PHP to support Unicode, which has been a requirement for business solutions for years. Does it do that well now?
- Inconsistent code, libraries, frameworks, reminds me of antique shops (mix of crap, mediocre stuff, unrelated items thrown together, with the odd useful item).
dont dot post @severe quarry
just examples i found from a simple google search
Gbx dllm @honest perch
huh?
bots auto do /wp-login on domains
and md5
the reason i quit wordpress was precisely that
if you dont update it constantly, your website will be hacked
one of mine was
lmao
i'm a moderator on a web hosting service and many people either get suspended due to hacked wp installation or high load
what a pain
rip
i searched "why is php hated"
and one of the top answers basically says "it used to be bad, but now javascript is way worse"
lmao
nice
At one time, PHP, JavaScript, and C++ were considered the worst programming languages in the world. However, in December of 2015, PHP 7 was released. This version made breaking changes in order to substantially improve the language.
Consequently, PHP is no longer as awful as it used to be. By comparison, JavaScript has NOT made breaking changes, and it likely NEVER WILL.
Instead, ECMA TC39 have chosen to put a Band-Aid on JavaScript and pile on new feature after new feature in the hope that they can make you forget how execrable the language truly is. The result? Look at ECMAScript 2017: its language spec is a whopping 885 pages long!
JavaScript is now one of the most bloated programming languages in the world.
everything is bad huh
bots also target it as i said
even if you escape inputs to prevent injection attacks
it will still execute them on the way out
afaik PDO has prepared statements
One of the biggest fuck ups i ever remember
it does
PDO should be the standard database library when using php
was the string escaping that still got injection attacked just when it fetched the data instead๐คฆโโ๏ธ
rip
Lol, just finished manually entering data I received from a teacher.
HML x)
https://the-earth.is-inside.me/ADc9HJNC.png
wat
why did you hve to enter that manually?
... what is that
what's that for
Bcs we received it manually
but
like
manually how?
the values
that doesn't look manual
^
effort 100
that just looks like binary
a shit load of work
how was the original data formatted?
bruh
oh jesus
but oh well, its done now
they sent u a fucking dataframe
You know what the worst part is?
Its fucking simulation data
Like why does it have to BE THE SAME
Just lemme gen 1's and 0r;s
ig
maybe like 20 lines of code in py?
well, 2 late now
and like 5 mins lol
I have smol brain ya kno
Hey. I've got a difficult question. What to do when my database gives an error while it wants to insert/update something that wasn't caused by a user executing a command? I don't hope to come across those errors, but I guess they can happen
Might wanna give the error ๐
s
Hello. can someone tell me if there are any errors in this code
helium.on("message", async(msg) => {
let chatmoderators = ['539195184357965833', '550170362248429568', '437019658374348801', '641795527444529152']
if (msg.author.bot)return;
if(msg.channel.name !== 'helium-global-chat')return;
msg.delete()
let e = new Discord.RichEmbed()
.setTitle("Helium Global Chat")
.setAuthor(msg.guild.name, msg.guild.iconURL)
.addField("Message content", msg.content)
.setColor("RANDOM")
.setThumbnail(msg.author.avatarURL)
.setTimestamp()
.setFooter(`Helium Global Chat System || SECURITY | Guild id: ${msg.guild.id} | msg author id: ${msg.author.id} | code by Airbus A350-1000#0001. thanks to him, this bot will have a functioning global chat.`);
if(chatmoderators.includes(msg.author.id)){
e.addField("Sent By", `๐ ๏ธ Chat Moderator | **__${msg.author.tag}__**`)
}else{
e.addField("Sent By", `**__${msg.author.tag}__**`)
}
await Promise.all(helium.channels.filter(c => c.name === 'helium-global-chat').map(c => c.send(e)))
await Promise.all(helium.channels.filter(c => c.name === 'helium-global-chat').map(c => c.setTopic(`Last message is sent by <@${msg.author.id}>`)))
gcauthor = msg.author.tag
gcauthorid = msg.author.id
gccontent = msg.content
})
Run and see
ah yes, we're bots that read your code and tell you what the problem is
i have and one thing
whats the error?
(node:44) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message
at /home/container/node_modules/discord.js/src/client/rest/RequestHandlers/Sequential.js:85:15
at /home/container/node_modules/snekfetch/src/index.js:215:21
at processTicksAndRejections (internal/process/task_queues.js:97:5)```
idk why i get it tho
Might wanna give the error ๐
@ruby talon give the error? Wdym?
Hey. I've got a difficult question. What to do when my database gives an error while it wants to insert/update something that wasn't caused by a user executing a command? I don't hope to come across those errors, but I guess they can happen
@nocturne grove doesn't an error occur?
Or do you mean what if? If so, just don't let your users make them, add checks. You should always be in control of the execution or sql injection will probb occur.
Of course I check their whole input, I replace all things needed etc. But I meant errors like connection stuff
Shouldn't raise an error on the DB side
@earnest phoenix did you see the error?
@silent berry that error means the message was not found, the only way i see it happening in that code is if you delete it somewhere else, which causes your msg.delete() to not find it
ok
what would cause it to repeat the message to repeat its self where if i type one thing in the channel. it spams it.
@nocturne grove if any connection exceptions occur this will be on the side that send the request as the DB can't respond or receive anything
Shouldn't raise an error on the DB side
@ruby talon ?
I can just get an error that prevents my bot from inserting data, right?
there is bot protc on
do you have other .on("message") blocks?
yes
@nocturne grove Yes, if you are using a custom library you should add the checks yourself.
Else all exceptions should be build in and easy to handle for the script.
@nocturne grove database libraries check these kinds of errors for you and give you back an error for you to handle
which database library are you using?
djs v11.5.1
yes I understand, but what to do if an error occured when the stuff needs to happen? Wait I'll explain
let rMember = message.mentions.users.first();
var rrole = message.mentions.roles.first();
rMember.roles.add(rrole.id)
err
Cannot read property 'add' of undefined
you collect the error and log it somewhere, then show something to the user
rMember is not a member
If the DB server should be up might wanna retry
mentions.users gives you a User, not a Member
:))
@quartz kindle and what should i do ?
mentions.members
On startup of my bot, it's going to send a log, check some if his permissions and start up his counters (see if anything changed)
When an error occured at the start up counters part, some strange things can happen in the whole uptime of the bot.
(Hmm I now realise I can work around that maybe)
I know this explanation is really vague
yo @quartz kindle You are mc JS dude yes?
mc?
Why track the uptime through a DB tho
() => scaleUp(args)
?
you want to give args to the scaleUp function, correct?
do you want to hardcode them? or do you want the timeout to call a method in a class? or something else?
Why track the uptime through a DB tho
@ruby talon you probably read that because of my vague explanation xd
I meant stuff can go wrong for the entire time the bot is online, until it goes offline
I believe the third param for setTimeout/Intervals are the args
Ohh
@nocturne grove are you using cogs? (Just for info if my answer will be relevant)
'R what lang are you using?
never heard of cogs in this context, so I guess no
@nocturne grove are you using javascript?
let banEmbed = new Discord.MessageEmbed()
.setDescription("**Ban**")
.setColor("#660213")
.addField("Banned User", `${bUser}`)
.addField("Banned User ID", `${bUser.id}`)
.addField("Mod", `<@${message.author.id}>`)
.addField("Mod ID", `${message.author.id}`)
.addField("Banned on", message.channel)
.addField("Date", message.createdAt)
.addField("Reason", `${bReason}`);
error:
MessageEmbed field values may not be empty.
Why i get this if there isn't an empty field?
On your bot.
@ruby talon yes, with mysql as database
Ait
@earnest phoenix inspect your variables, one of them returns nothing probably
I would assume you have to load the commands in when starting and that your code has a DB object which then executes all commands on the db?
@earnest phoenix message.channel is an object, use it like ${message.channel} to get the mention. Or message.channel.toString() I believe
yes I have
@nocturne grove i tried in both ways bot i still got the error
If so add a test check at the start (see it as a ping), if you get an expected result switch a check var. If it failes retry but block the commands that depend on it
i told you to inspect your variables
you'll achieve nothing by guessing what's the issue
This way your script shouldn't be able to "crash"
@earnest phoenix console.log(banEmbed.toJSON())
and you will see in your console which field is empty
Or atleast thats the way I would handle it in your situation.
@ruby talon on startup, it's now already saying database connected after the, I believe, first query. So you suggest when that's not logging, I know the connection is not stable.
Hmm sounds logical, thanks
^^
and tbh, I don't think I should go too far with it. Because now I'm thinking "what if something else's happening in one of the following queries"... ๐
i hope you're not using a single connection for all of your queries
check your mysql library's docs, it should mention how to catch any error that happens
if your connection is unstable because you have a remote database, look into mysql pooling libraries
@nocturne grove idk how it works on JS but in python I would let my command class inherit my error handler class and catch the errors
i hope you're not using a single connection for all of your queries
@earnest phoenix Last week I put all my queries in one file, so it will always make a new connection and close it. Thanks you was one of them who said that ๐
Thanks for that
@quartz kindle do you prefer PostgreSQL or MySQL?
Really isn't x)
Well, the best of luck tho
thanks for the help
Any time
I use SQLite for my bots
will look into the docs I guess, and else I will just rely on the connection ๐
havent used Postgre yet, and use MySQL for my website
Use postgres over MySQL
Ait, I used 2 use SQLite too, but for my next project is pretty big so I think a postgreSQL server fits more
& glad 2 work with new things
hi, how can i check if 75% of the messages a member sends are in caps?
like "EEEEEE" is all caps and ^^ would return true
using js
so i can do something like
I really gotta learn how 2 work with regex, bcs kinds looks like enchanting table language
helllo
hmm
if (typeof (block) !== "undefined") {
lastBlock.classList.add("hidden")
}```
How do I go higher then the set kbps
you cant
its set to that
ok, idk how i'd do it
its a 3 level boosted server
OH
imma go to regex101
we get upto 384kbps audiop
So I need to boost
Channel settings and change the slider
Got yah
Note to self: dont forget to use the right var other wise u will never get it going lol
html code 
I like frontend untill a UI designer comes and says that its hella shit
Backend is more my thing tho
message.guild.fetchBans().then(bans => {
if (bans.some(u => User.includes(u.username))) {
let user = bans.find(user => user.username === User);
message.guild.members.unban(user.id, Reason);
} else if (bans.some(u => User.includes(u.id))) {
message.guild.members.unban(User.id);
} else {
message.channel.send(nue)
error
Cannot read property 'includes' of undefined
Frontend is easy 2 do but hard to make good
User object doesn't excist @earnest phoenix
Read ur error
Literally says it fam
Probb gotta remove the cap on the U
I think User is the User oject and not the member object you want
let User = message.mentions.members.first()
still a little janky
Dang
but it switches slides niceeeeee
https://crunchy-bot.live/home like 12k lines in lol
ignore the domain
just had it laying around
can someone help me please?
@earnest phoenix we can, if you give us some information
Eg, error, code, expected result ect
from the code you showed, all we can see is that User is undefined
@turbid bough fuck you found my 404 i forgot about
Wait. i'll give you the full code
thats a 404 page? lmao
HAhahah
weeb
then got yelled at by teacher for not doing some work --
Yell back
even tho they just didnt read their emails
Anime is power.
you need to return in those ifs
else they will send a message saying that you dont have permissions, or that the user was not found, but the code will continue anyway
oh, ok
Yo, is there a way to profile my code?
Like suggestions on where to change things or what to do with high intensity sections?
you mean execution speed?
in js you can time your functions with performance.now() to get an execution time reading
and it output me invalid number given
@modest maple is it just a website, or a website for a bot?
otherwise you can also use one of the many profiling and heatmap libraries
@quartz kindle Perhaps, I'm just trying to see what I should change beacuse I want to restructure things again
kinda getting spaghetti
@lethal vine are you trying to check if a string is a number?
if so
string.isdigit()
if you want, you can show your hot code
I'm trying to make an efficient reload command too
Tim, i still got the error
@modest maple is it just a website, or a website for a bot?
@turbid bough Just a site tho i intend to make the API public and access some stuff from my bot
this is my main file I run from https://i.txj69.com/5HyI1KU9qc.png
@quartz kindle
it aint pretty but its working fine more or less
add me to the open beta then
i mean, nothing i can say about that part, performance is pretty irrelevant at that point
i would do things a bit different but thats just personal preference
how can i check if a user has used a command in under 10 seconds?
like
i use 5 commands in under 5 seconds, how can i check it?
using javascript
read the docs
you can use timers and intervals
nothing will be in the docs about that
js?
for example
TypeError: args.replace is not a function
create an object and an interval of 5 seconds
every time a user uses a command, put the user in the object, and add a command counter
make the interval reset the counter every 5 secs
another way is to add a counter somewhere when a user uses a command, and set a timeout to remove said counter
the counters will keep themselves updated, and you can arbitrarily check their size at any given point
oki, thank u
what i'm doing has got nothing to do with doing anything with cooldowns
or d.js
only the js part of it
how would i be able to temporarily suspend a function for x amount of ms (400)
in js?
yh
@digital ibex uuuh, wdym
await new Promise(r => setTimeout(() => r(), 400))
ooh
i'm trying to check if a user has used x amount of commands within n seconds
@jovial nexus args.replace is not a function
check your args, they are either wrong or invalid
cant help without seeing your code
run: async(client, message, args) => {
const url = args.replace(/<(.+)>/g, '$1')
um, args is an array isnt it?
@quartz kindle How is that gonna work with button events tho?
yu
i dont think arrays have replace function
it isnt?
nope
-bot
u can join the args and then replace it
@jovial nexus how do you call the run function?
you're passing invalid args to it
@modest maple button events?
do you mean this? ```js
commands.run(client, message, args);
The hide function is being invoked by a onClick() event
are you using jquery?
nop
are you doing something like transitioning the opacity before setting the element to display:none?
yh
const args = message.content.slice(prefix.lenght).trim().split(/ +/g);
you should be able to setTimeout(() => element.style.display = "none", 300)
or something
yeah split turns string into array
@jovial nexus so args is an array
arrays dont have a .replace function
only strings do
then i need to replace args?
args is an array of words, for example if the person types command bla1 bla2 bla3 then args is [bla1,bla2,bla3]
if you want to execute the .replace function on the first argument, ie the first word the user writes after the command
do it to args[0]
run: async(client, message, args) => {
const url = args[0].replace(/<(.+)>/g, '$1')
```?
if you want to execute the replace function on all args, all words the user types, no matter the order
yes probably
then use args.map(word => word.replace())
yes, you probably want the args[0] method
TypeError: Cannot read property 'replace' of undefined
there are no args in your command then
aaa
did you type an url in your command?
ok thx now works
tim i worked out an easier way
i just passed the var to the func
and then assigned the old var after
fuck im dumb some times
let User = message.mentions.members.first();
if(message.author.id === User.id) {
const nupoti = new Discord.MessageEmbed()
.setDescription(":no_entry_sign: **You can't ban yourself!**")
.setColor("#ff9900");
message.channel.send(nupoti);
return;
}
Cannot read property 'id' of undefined
did you mention someone?
yes
is message.author undefined?
no
is User undefined?
i defined it, don't you see?
the error says it otherwise though
nvm. i solved it but i have another problem now
good
let User = message.mentions.members.first();
let Reason = args.slice(1).join(` `);
if (!User) {
const mentioneaza = new Discord.MessageEmbed()
.setDescription(":no_entry_sign: **You need to mention a person to unban!**")
.addField("Correct Usage", "lt!unban [userMention/userID]")
.setColor('#ff9900');
message.channel.send(mentioneaza);
return;
}
if (!Reason) Reason = `Unbanned by ${message.author.tag}`;
message.guild.fetchBans().then(bans => {
if (!bans.some(u => User.includes(u.username))) {
let user = bans.find(user => user.username === User);
message.guild.members.unban(user.id, Reason);
} else if (!bans.some(u => User.includes(u.id))) {
message.guild.members.unban(User.id);
let banEmbed = new Discord.MessageEmbed()
.setDescription("**Unban**")
.setColor("#ff9900")
.addField("Unbanned User", `${User}`)
.addField("Unbanned User ID", `${User.id}`)
.addField("Mod", `<@${message.author.id}>`)
.addField("Mod ID", `${message.author.id}`)
.addField("Unbanned on", `${message.channel}`)
.addField("Date", `${message.createdAt}`)
.addField("Reason", `${Reason}`);
} else {
const nue = new Discord.MessageEmbed()
.setDescription(":no_entry_sign: **That person isn't banned**")
.setColor('#ff9900');
message.channel.send(nue)
return;
}
when i use my unban command i still got the message that i don't mention anyone
so you need to look trough .users instead of .members
what does your message look when you are sending that command?
can you try console.log it out, and or try to explicit say that you are comparing with undefined
if(User === undefined) ?
sure
if i do console.log i got only undefined in the console
not User.includes
@earnest phoenix then what?
@turbid bough any idea?
im not sure, but can you check if oyu print the whole list of users mentioned?
Excuse me? cand you explain me one more time ?
Couldn't resolve the user ID to unban.
const banList = await message.guild.fetchBans();
const bannedUser = banList.find(user => user.id === User.id);
if (bannedUser) message.guild.members.unban(bannedUser, Reason);
else await message.channel.send(nue);
How to check if the bot has the correct permission to make a invite link
I try client.guild.me.hasPermission("CREATE_INSTANT_INVITE")
but it failed
client.guild is not a property.
@earnest phoenix fetchBans doesn't return a collection of users
oh ok
@smoky spire then how could i check if a member is banned?
It passes a collection of objects that have a user property
can you add slowmode to a command handler, I just want a yes or no answer.
yes
ok thx
guild.me.hasPermission("CREATE_INSTANT_INVITE")
guild not defined?
Do i need to define the guild id?
You need to define guild object, example: message.guild or client.guilds.cache.get(id)
By the way, does someone know how long does it take to have an answer from auction requests?
monthss
Oh that is sad, why so long?
let guild = message.guild;
console.log(guild.me.hasPermission("CREATE_INSTANT_INVITE"));
This report true even through the bot does not have permission?
@faint token its safer to check for channel overrides, as an invite can only be made to a channel
Oh I just said the reason for that xd
ok
I am reworking permission management for my bot, and i am getting an error (will attach in a sec) on this code. The console.log work fine and show the correct permissions but it crashes on the third line
output of the console.log (looks fine to me)
if i do it in eval like this it works. not sure why it crashes on actual use
im stumped
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Python38\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Jassm\Desktop\Alpha\modules\core\error.py", line 18, in on_command_error
ctx._ = functools.partial(ctx._, cog="ErrorHandler")
AttributeError: 'Context' object has no attribute '_'```
help
(Movement) Are you really sure it's coming from that line (shard.js 92:53)? You're also checking if a a guild member has administrator in the channel (still works)
ctx._ = functools.partial(ctx._, cog="ErrorHandler")
error = getattr(error, 'original', error)
etype = type(error)
``` thats my code
ye it is coming from shard.js 92:53, just figured out that the number im passing was a string and it doesnt like passing '8' instead of 8.
ah
should have something about that in the docs for discord.js
they just say u can pass a string number or flag
not that u can pass a number (bitfield) or string (flag)
I mean it kind of does:
- A string (see Permissions.FLAGS)
- A permission number
- An instance of Permissions
- An Array of PermissionResolvable
eh in hindsight that is a bit more clear, but most of discord.js it accepts strings instead of numbers because of snowflakes, so nobody would expect it to be different there so would be nice for a bit more clarity
yo, what would be an appropriate pythonic way for stopping midway through a command, but not stopping the script or anything else?
return probably?
Is the discordapp.com/api endpoint still open? I keep getting socket hangups from it
that didnโt work for me
`await asyncio.sleep(5)
await message.channel.send("GO to continue NO to cancel")
def check(m):
if m.content == 'GO':
return m.content == 'GO' and m.channel == message.channel
elif m.content == 'NO':
global game_on_
game_on_ = False
react_set.clear()
ultimates.clear()
return`
this is what i have
after NO id like it to exit from the command
why this dont work?
client.users.get('507367752391196682').fetchMessage('688052360915845173')
.then(message => console.log(message.content))
.catch(console.error);```
TypeError: client.users.get(...).fetchMessage is not a function
you are fetching a message, it would not use a users
is there any way to shorten this function for the args I pass into the function
client.resource.cmdUsedLogger(client, command, commandArgs, msg)
Can't I just use an underscore?
@earnest phoenix client.users.get !?
@earnest phoenix yes(?
this dont work with users?
no
@earnest phoenix What version of DJS do you have?
v11 uses client.users.get while v12 uses client.users.cache.get
Yeah client.users.get should work
How can i make a dashboard for my bot?
Basically interact with its database from a website.
Like disable and enable commands
Is there a way to know if the message is from the server where the message was sent?
@wise quartz you need to familiarize yourself with web development, look into these topics: frontend, backend, authentication, oauth2
how do i define what a command is in the default help command?
the whole "creating a dashboard" thing is too complicated to explain and too big of a concept so you'll have to research the topics yourself
Frontend, backend, authentication and oauth2?
yup
Is there yt tutorials for those?
your error is your scope
So where exactly should i be searching and search for what exactly?
i used a youtube tutorial it told me what the code does
google and the topics i said
I'm working on a commands "marketplace" of sorts with my Discord bot. I'm using JSON for information. Some JSON properly returns, but some values return as undefined. What should I do?
use a db
I did consider a db, but I want to do it in a format that's similar to package.json
Try it out and see.
I did consider a db, but I want to do it in a format that's similar to package.json
why though?
So like the way that my "marketplace" would work is that people could submit custom "packages" (command packs), and they can put info about the commands and the name and description in a JSON file that's similar to package.json
in the sense of safety?
yeah
Oh no I check that
oh
I'm going to manually check each package because it's dangerous if I don't obviously
i mean, unless you're reading the json file incorrectly, there's no reason that properties return undefined if they're there
it's not for me I'm a python developer it's for a friend so i don't know js too much and i don't have access to the bot.
So ask them to try it out? The statement works but it's better if one is able to debug themselves.
Yea there shuldn't be anything wrong with the code
if nothing works at all, you can try switching to ini or yaml
you'll have to build your own reader
json is a javascript native
JavaScript Notation Object
so for everything else you'll have to either build your own reader or use a npm package
i don't know which one is the most performant since i don't mess around with node too much
hm alright
I assume they're using Discord.js. Are they on v11 or v12.
in v12 the guilds property changed types
see:
https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=guilds
https://discord.js.org/#/docs/main/stable/class/GuildManager
tldr you're looking for the cache property on guilds
ah then read what cry said.
see above
You don't see cry's message? https://ptb.discordapp.com/channels/264445053596991498/272764566411149314/712778801838424104
Using yaml fixed my problem. Thanks so much!!
anybody know what did this got changed into
"name",```
it gived me error on find
gives
are you on v12
yes
the channels property changed types
ohk
"name",
client.settings.get(message.guild.id).modLogChannel
);``` u mean that?
uh no
look at the docs to see an example of how find is used now
click on the Collection thingy on the second link i provided
Help, why my bot isnt applied? I waited 2 weeks, the bot is off rn because I am working to pokemon commands, but it was on 2 weeks
(Ping)
be patient
Ok
okay so howcome
in this
let welcome = bot.db.get(`welcome_${member.guild.id}`)
if(welcome === null) {
return;
};
const embed = new RichEmbed()
.setAuthor(`Someone joined! it was **${member}#${member.discriminator}**`, member.displayAvatarURL)
.setThumbnail(member.displayAvatarURL)
.setColor('RED')
.setTimestamp()
.setTitle("**DELETED MESSAGE**")
.setDescription(`Someone Joined!
**User**: ${member.username}#${member.discriminator}
**Have fun!**`);
bot.channels.get(welcome).send(embed);
});```
it shows undefined
but then if you do it as a text
in the bot.channels.get(welcome).send(`new member arriving it was ${member}`)
it actually pings him
but then in the embed
it shows <@id>
nothing you can do
yeah..
authors cannot have mentions
or any kind of formatting
only field values and descriptions
so how would I change it with mentions?
what
how would I get it to work on the embed
use the description or a field value
also for the undefined
the properties you're looking for are on a user
not on a member
ty
I want to do something like:
config.package = yaml.safeLoad(fs.readFileSync(config.friendlyblobs.args[0].ok))
with args[0] being the argument of the command.
How can I do something like this?
config.package = yaml.safeLoad(fs.readFileSync(config.friendlyblobs[args[0]].ok))
So [] is the escape?
yes
args is your variable
when using "." and your variable, the variable has to be inside of []
oh alright
O, but now it's saying this
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined
It's undefined instead of a string
console log ```js
config.friendlyblobs[args[0]].ok
Let me try again with another variable--
another value
Yep same thing, let me check console log
what is the value?
When I try to console.log(config.friendlyblobs[args[0]].sku), it returns "Cannot read property 'sku' of undefined"
I know that args[0] should return a string
ok whats the config variable?
config is a json file
basially fs.readFileSync is looking for a string value and config.friendlyblobs[args[0]].ok is not a sting value or config.friendlyblobs[args[0]].sku
.sku doesnt exist apperantly
I did something wrong
I made this function but it keeps returning undefined
function afk(input) {
fs.readFile('./resource.json', 'utf-8', async function (err, data) {
let body = JSON.parse(data);
let afk = body.afk;
for (let i = 0; i < afk.length; i++) {
if (afk[i].id === input.toString()) {
return true;
}
}
return false;
})
}
Let me try again
okay correction* when I run console.log(config.friendlyblobs[args[0]]) it returns undefined
what exactly are you trying to do? @green vale
Okay let me explain it
So I'm creating a "marketplace" of some sorts for commands for my Discord bot
So like the way that my "marketplace" would work is that people could submit custom "packages" (command packs), and they can put info about the commands and the name and description in a JSON file that's similar to package.json
For the safety concerns--I review them manually (if that's what you're wondering)
@visual sandal its coming undefined becuase js if (afk[i].id === input.toString()) { return true; }
is coming up false i think
@neat gazelle answering your question from #topgg-api since this is the right place for it. When getting a user from the cache, the user is not guaranteed to be available. in order to get the user you will need to fetch from the api by using its id
guilds have an .owner and a .ownerID property for that. if .owner is not available, fetch it using the id provided by .ownerID
(in discord.js)
it's like that everywhere since the api returns the owner id in the guild object
oh i need to try this. thank you
since all you wanted was the owner's ID, you can simply use guild.ownerID directly, without needing to fetch anything
@neat gazelle Thanks for the help btw it finally worked
If the statement is false for the if statement then it should return false from the return outside the loop, right?
no. if the if statment is false then it doesnt run the the method inside it. therefore nothing is being returned so its undefined
I did this, but it's still undefined
function afk(input) {
fs.readFile('./resource.json', 'utf-8', async function (err, data) {
let body = JSON.parse(data);
let afk = body.afk;
let result = false;
for (let i = 0; i < afk.length; i++) {
if (afk[i].id === input.toString()) {
result = true;
} else {
result = false;
}
}
return result;
})
}
function afk(input) {
console.log(input);
fs.readFile('./resource.json', 'utf-8', async function (err, data) {
let body = JSON.parse(data);
let afk = body.afk;
let result = false;
console.log(data);
console.log(afk);
for (let i = 0; i < afk.length; i++) {
if (afk[i].id === input.toString()) {
result = true;
} else {
result = false;
}
}
return result;
})
}```
do that to trouble shoot and see where its coming undefined
I tried that, but lemme try again
try this as well, under your for loop do console.log(afk[i].id)
and in your else statement do return false instead
@visual sandal add a return to before fs
you should return the return value of the callback, which is the return value you specified
still undefined
what all did you try?
I tried the code you sent and the modification zSnails said
show your new code
function afk(input) {
console.log(input);
return fs.readFile('./resource.json', 'utf-8', async function (err, data) {
let body = JSON.parse(data);
let afk = body.afk;
let result = false;
console.log(data);
console.log(afk);
for (let i = 0; i < afk.length; i++) {
console.log(afk[i])
if (afk[i].id === input.toString()) {
result = true;
} else {
result = false;
}
}
return result;
})
}
then declare an empty var at the top of the function, redeclare that var inside the callback
and then return that var
wait so data is undefined
yes
@visual sandal you need to use a callback if you want a value from a callback.
nvm lol
either that or async/await
how..
Hi, please how do I use the 'get' command ? (What do I need to import ?)
I can't find it in the doc cause searching the keyword "get" isn't really effective..
category = get(guild.category_channels, name='test')
hello discord bot nothing is active what can i do?
(Oh, with Discord Py)
hello discord bot nothing is active what can i do?
@real totem What library are you using?
Discord.js?
discord.js
js.
Alright.
First, go to https://discordapp.com/developers/applications and regenerate your bot token.
Discord Developer Portal
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
Ok i solved it thanks anyway
You're welcome, I guess.
So I'm developing a bot [DJS v12], and I'm going to use quick.db (It sucks, I know, but it's the easiest thing to use).
How would I use quick.db per-guild?
Hm.
You can do ```js
db.add(${message.guild.id}_(thing you want define), (thing x2));
alright
Alright
I guess you're using quick.db for economy commands.
Nope.
Oh.
I'm creating some sort of "commands marketplace", I use Enmap for my main bot but I messed up my testing db for it
I use Node 10 and Discord.js v11.
I use v12 and Node 12
^^^^
i've been using it for like 2 years its ok
its really not
how
if somthing happens to file, all data gone
Yes, just Map.
doesnt scale at all
- I have backups on GitHub
- I have local backups
- It's not really too critical data anyway
Then, what do you recommend.
All I have in my Enmap is just prefix so
far slower than usual db
mongo is best for critical stuff
Yup, ๐ฅญdb.
Enmap works fast enough for me, and if it corrupts then that's okay since it's not critical
how
are you serious
its one of most popular sql databases
I'm pretty serious.
O_o
Maybe because I'm new to coding.
What if I host my images on Postgres?
but yea just dont use enmap at all
even if its non critical
it doesnt take long to spin up an actual database
its thre worst of the worst
i could list issues with it for ages
I do plan to migrate to Mongo at some point
That's alright.
The official site for PostgreSQL, the world's most advanced open source database
btw
hm
It's based on the same thing
if somthing happens to file, all data gone
I'm probably going to have to rewrite all of my commands
When I do move to Mongo/Postgres
i would have thought u would set it in one command and get it in your handler
There are* other settings but all of them are insignificant besides prefix
Do you all mainly speak English?
Yes
Lucky.
๐คข
๐คฎ
oh
quick db is exact same but the only slight advantage is that its based on sqlite
It's temporary while I decide what db I should use
if you cba learning sql then use mongo
Yeah I was already considering using Mongo
Firebase has DBs?
Yeah.
O_o
It's temporary while I decide what db I should use
@green vale use MySQL. Super simple and easy to use
Hm another option
mongodb
i need to switch to mongo but aaaaaaaaaaa
ive really liked mariadb
its meant to be a drop in replacement to mysql
and if you're developing a bot with node.js, it natively supports promises
that's cool
don't use firebase db
MySQL is honestly the best and easiest db to use
thats arguable
theres no "best" database
wyd
well iโm using quickdb and itโs true it isnโt really good. But can this be replaced by simple JSON files?
anything is better than using JSON for your database solution
and btw why not use firebase? i havenโt thought about it but it doenโt seem that bad, right?
@dusky marsh why? not safe?
JSON is prune or prone to corruption
^
never heard of that
how, let it be replaced by the number of servers