#development
1 messages · Page 665 of 1
is it against DBL to force user to join a discord server to use bot?
because i'm planning to make bot ranking system based on my server ranks
Will your bot be only for your server
no i'm planning if use has role like (ex. Premium) in my servers Give Them Cool Features in the bot
Then only give them those features if they're in your server, and leave the core/free features for everyone, including people outside your server
okay
how do i get channel id when i create it (as a bot)?
discord.js?
.then(somecoolname => somecoolname.id)
the method to create the channel returns a promise with the channel wrapped in it
depending on how you handle async, you can use it
tnx, ill try it
bruhmoment
im trying to get channel by name and send msg to it
how bad is this
you arent passing a function to .find
so basically
when a message is deleted, you want your bot to send a message in that channel?
or do you just want the id of the deleted message?
im trying to get channel by name and send msg to it
I've never really messed with channel object but that seems intuitively simple if you browse the API
if you already have the message object from delete event
delmsg.channel.send, no?
if you're not using master with partials enabled, the messageDelete event should give you a full message object, which includes message.channel
I don't understand why you would need to "find a channel name"
if you want to send a message to a different channel, then:
with an id: .get(channel_id)
with a name: .find(channel => channel.name === channel_name)
They want to send a message to a channel named "bruh" whenever a message gets deleted. This will work if every server your bot is in has a channel named that way. If you only want it to send it in a specific guild you can either return if the guild ID doesn't match the guild ID of the guild you want it to only work in or use client.channels.get("ID") to send it to a specific channel whatever the name of it may be
.find('name', 'bruh'); works too
oh, like a logging channel
works but its deprecated lul
it won't work for much longer :^)
usually things are deprecated because there is an easier way to do it
or better
^
quick richembed syntax
let inventoryEmbed = new Discord.RichEmbed()
.setColor('#0099ff')
.setTitle(`Inventory for ${player.name}`);
for(let item in player.inventory)
{
if(player.inventory.item > 0)
inventoryEmbed.addField(item, player.inventory.item);
}
that will work right?
test it
ignore the inventory object
and see if it does
we're not going to test it for you
seems right
Hello, I try to fetch a special message by using messages.fetch but it doesn't work. Here is my code : js if(message.content.startsWith(prefix + "checkset")) { let args = message.content.split(" ") console.log(args[1] + "\n" + args[2] + "\n" + args[3]) if(!args[1]) return message.channel.send("french blah blah blah !") if(!args[2]) return message.reply("id not put !") if(!args[3]) return message.reply("No emoji put !") if(args[1] != message.mentions.channels.first()) return message.reply("Channel not found !") if(!message.mentions.channels.first().messages.fetch(args[2])) return message.reply("Message not found ! Verify ID !") if(!message.mentions.channels.first().messages.fetch(args[2]).emojis.get(args[3].id)) return message.reply("Emoji not found !") message.channel.send("wouhou !") }
And my error is : if(!message.mentions.channels.first().messages.fetch(args[2])) return message.reply("Message introuvable ! Vérifiez l'ID saisi !") ^ TypeError: message.mentions.channels.first(...).messages.fetch is not a function
I used a code of an open source bot that I tested and it works good
The code of the open source bot is } } if(!channel){ message.channel.messages.fetch(msgID)
read your code very carefully
Why ?
Mmm, so what must I use ?
a text channel does contain a fetchMessage method
which is what you're probably looking for
No, i never saw it on discord.js.org
you should probably attempt to write your own code and not copy someone else's
it's all good to use someone else's code as a reference sheet to what you're supposed to do, but copying word to word is meh
oh wow I got some interesting output from a "object in" loop
Yes, but i was pretty sure that i never saw it on the library...
so, this works fine
however
when i log every item its iterating
I get every property of the object as well?

@twilit rapids Sorry to specifically ping you, but your bot uses d.js and lavalink I'm assuming. According to d.js-lavalink, you need a host js const nodes = [ { host: "localhost", port: 2333, password: "youshallnotpass" } ]; but if I'm using a VPS, the host isn't localhost. What should it be?
I don't use discord.js-lavalink
Oh really?
and do you already have a lavalink server running
nope
Then start doing that first
What are the chances that some day there will be a local offline discord client for developers to be able to code without needing to be online and be able to test
and bots need to send an IDENTIFY call via ws
yeah, thankfully discord api is like snapping legos together
generally anything you need to do is pretty simple once you find the right method
@broken shale just wondering, how did you figure that stuff out about me and my bot
how do i check discord.py version on linux
Like what language your bot ran on?
language is easy from dbl page, lava-link was assumed since I would think if you have a music bot you'd use lavalink/ytdl-core
@maiden mauve iirc it’s something having to do with object.hasOwnProperty, no idea how that works with mongo
for in loop default iterates over every property of the object
I made a quick fix but i'd rather understand why it's doing it
adding a "break;" on the last object that I defined prevents the spill
I guess it works 🤷
that's not very nice tho
yeah, essentially it's a half-way there solution as opposed to making a defined "array"
for (let property in object) {
if (object.hasOwnProperty(property)) {
// do stuff
}
}
do this
was gonna suggest the same yeah
you have to check if the item is actually in the object
By the way, how can I check if a message has this or this reaction ?
message.reactions and message.emojis doesn't work
ty Turtle
or you could use object keys
@sudden geyser /shrug
it's still technically iterating the loop of nonsense though
yeah
you could try storing the inventory in an array property of the player and iterate over that
idk if mongo does that but
mongo more like good database
yeah
maybe in the future.
this function is for a minor task comapred to how the rest of bot is coded
its not that hard to switch over to
I'd basically have to change every reference to the objects handling an array
essentially it would just be a big replace all in files
the hasownprop solution definitely works so no pressure either way
what about breaking the loop with hasownproperty as a conditional?
for... in , if break
well all my tests have shown the real elements came out first
Currently all major browsers loop over the properties of an object in the order in which they were defined. Chrome does this as well, except for a couple cases. [...] This behavior is explicitly left undefined by the ECMAScript specification. In ECMA-262, section 12.6.4
yeah I guess that works for the most part
until js gets a weird facelift
yeah if it ever went backwards you'd have the opposite problem
since I'm not coding paypal I think I'll be alright for the time being
😄
yeah it’s np
if anything ever breaks it’s a quick fix
put a little book mark in it though in case
a fun adventure in any case
thanks all for input
haha, top reply had great words of wisdom
It is plain wrong to assume a non-failing test provides any sort of concrete proof.
@client.command()
async def emoji(ctx, emoji: discord.Emoji):
await ctx.send(emoji.url)
```with this the bot have the access only for guild emojis, how can I have it for all emojis n the bot is not in the emoji guild?
to remove a deprecated field from mongodb, document.field = undefined works
any good places to host a bot? running my bot on my computer doesn't work well since I got a slow computer
Have money?
get a vps
^
Best place
Mine is $3/month
Very inexpensive
Very reliable, if you choose the right company
which one you got?
I have two, the $3 is from OVH, the other one I have is from primenodes
I havent had problems with ovh
I guess their support is slow Ive been told but havent experienced it
google cloud can get you free credit
as do a few other sizable ones
is that the micro?
My $3 ovh one is 2gb ram, 20gb storage unlimited bandwidth
ight just found some random site that offers $0.48/month
My primenodes one is $19 but that's because it's cpu is 👌
I have 0.56 so I think I'm gonna try it
ovh seems to have a lot of problems
I use it for my minecraft server 
According to Mr. Miles
@topaz fjord never had any
I don't trust it either but idc tbh
they kept replugging the Ethernet cable on the machine miles had when it was a mobo issue
"1.5 tb DDos protection" tf that supposed to mean? more storage to not get ddos'd?
I wanna put that to the test
@topaz fjord my vps has never gone down unless I restarted it, or shut it down myself
their official discord has 85 members lol
it is
why is it cheaper to choose the biggest package?
What website is that
@earnest phoenix do you know the difference between quarterly and monthly?
bruh i get way better shit for that large package price
thats honestly a steal
for larger complex bots
512mb memory
@mossy vine i pay less and get better

Anyone using that website has done 0 research
@earnest phoenix $3
Or around there
2gb ram, 20gb storage
Unlimited bandwidth
That's all I know
You never use the panel really
But yeah, it's garbage
Just select your OS and that's it really
Go back to pay
They email you the ip and stuff so you can ssh into it
But their panel is a little weird
@earnest phoenix if you select U.S. you get no VAT tax
Love living in the US 
Imagine using ovh
@tight heath been working for me for 7 months
Dont know why so many people have issues with them
My server's disk broke and it took them 2.5 weeks to repair it
using ovh?
i need help
I have a outdated apex-api and i wanted to update it and says "No Api Key found in request"
{"message":"No API key found in request"}```
Well you might want to try reading the error. It tells you the exact problem..
ik what is says but , i don't know how to put the key in the link
check the docs for that api
embed.author.icon_url: Not a well formed URL.
at item.request.gen.end (e:\somestuff\node_modules\discord.js\src\client\rest\RequestHandlers\Sequential.js:85:15)
at then (e:\somestuff\node_modules\snekfetch\src\index.js:215:21)
at process._tickCallback (internal/process/next_tick.js:68:7)
warning.js:18
(node:4276) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
warning.js:18
(node:4276) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```
What should i do?
embed.author.icon_url is not an well formed url
Not sure what you're trying to do but look in docs for the user object
if(url + "silver3.png")
{
const embedapex = new Discord.RichEmbed()
.setColor("RANDOM")
.setTitle("User Page")
.addField("Level:", `${level}`)
.addField("Rank", "Silver [III]")
.addField("Wins:",`${wins}`)
.addField("Kills:", `${hopa}`)
.addField("Platform:", `${platform}`, false)
.setAuthor(username, `${avatar}`)
.setThumbnail(`${rank}`)
.setFooter("© by Apex Stats Bot");
msg.channel.send(embedapex);
}
The api doesn't have a Rankname
and i tried to make by the image
"rank": 4,
"percentile": 99.9,
"displayName": "Rank Score",
"displayCategory": "Game",
"metadata": {
"iconUrl": "https://trackercdn.com/cdn/apex.tracker.gg/ranks/apex.png"
},
"value": 2559,
"displayValue": "2,559",
"displayType": "Unspecified"
}```
Someone?
If someone knows what should i do please DM me , i will go to sleep now.
What? Help me
at WebSocketConnection.client.ws.connection.once.event (C:\Users\X\Desktop\xerobot\node_modules\discord.js\src\client\ClientManager.js:48:41)
at Object.onceWrapper (events.js:286:20)
at WebSocketConnection.emit (events.js:198:13)
at WebSocketConnection.onClose (C:\Users\X\Desktop\xerobot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:390:10)
at WebSocket.onClose (C:\Users\X\Desktop\xerobot\node_modules\ws\lib\event-target.js:124:16)
at WebSocket.emit (events.js:198:13)
at WebSocket.emitClose (C:\Users\X\Desktop\xerobot\node_modules\ws\lib\websocket.js:191:10)
at TLSSocket.socketOnClose (C:\Users\X\Desktop\xerobot\node_modules\ws\lib\websocket.js:850:15)
at TLSSocket.emit (events.js:203:15)
at _handle.close (net.js:606:12)
(node:6836) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of
an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:6836) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that
are not handled will terminate the Node.js process with a non-zero exit code.```
Thanks!
I'm getting an args.replace is not a function error
here's the snippet
bot.on('message', msg =>{
if(!msg.content.startsWith(PREFIX)) return;
const args = msg.content.split(` `);
const url = args.replace(/<(.+)>/g, '$1');```
because its not
can you explain further?
it worked for this though https://www.youtube.com/watch?v=WQe8nZ4WBYk&list=PLVzaElkTvlQae8XJ0ujnEgz1GviufNx8h&index=4
Ever wanted to know how a core developer of DISCORD.JS uses his own library? I don't really care what you think, but if you want to leave feedback do so in t...
was tryna follow through
nvm I got it done
I kind of fixed it except for one thing
when i try to skip the song, it gives this error,
const url = args[0].replace(/<(.+)>/g, '$1');
^
TypeError: Cannot read property 'replace' of undefined```
args[0] is undefined 
@sinful lotus what do you mean by join it before replace? a temp variable?
bot.on('message', msg =>{
if(!msg.content.startsWith(PREFIX)) return;
var cont = msg.content.slice(PREFIX.length).split(" ");
var args = cont.slice(1);
const searchString = args.slice(0).join(' ');
const url = args[0].replace(/<(.+)>/g, '$1');
console.log('URL: ' + url);
console.log('Search string: ' + searchString);
const serverQueue = queue.get(msg.guild.id);
var cmd = bot.commands.get(cont[0])
if(cmd) cmd.run(bot, msg, args, queue, serverQueue, youtube, url, searchString);
else if(!cmd) msg.channel.send(`Puff! (Invalid command!)`);
}```
this is my code btw. I'm using command handlers
Wtff
It works when I queue a music
YouTube
but it doesn't work when I skip the song

yeah I would prefer help than belittling thanks
can someone give me a link to a client.on function that is always looking for reactions to messages?
i cant find it in the docs
discord.js
not really a function, but here you go
https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=e-messageReactionAdd
how can i let my bot send an message when it joins an server?
what library
Line of code
result = ast.literal_eval(result)
Error
Ignoring exception in command question:
Traceback (most recent call last):
File "C:\Users\Just_Allexx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 79, in wrapped
ret = await coro(*args, **kwargs)
File "C:/Users/Just_Allexx/Desktop/Bots/Qbot/qbot.py", line 18, in question
result = ast.literal_eval(result)
File "C:\Users\Just_Allexx\AppData\Local\Programs\Python\Python36-32\lib\ast.py", line 48, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "C:\Users\Just_Allexx\AppData\Local\Programs\Python\Python36-32\lib\ast.py", line 35, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
{
^
SyntaxError: unexpected EOF while parsing
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Just_Allexx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\bot.py", line 863, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Just_Allexx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 728, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Just_Allexx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 88, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: SyntaxError: unexpected EOF while parsing (<unknown>, line 1)
Where have I typoed?
Okay, I see
@stray garnet listen for the guildCreate event
uh no
you'd be spamming everytime you establish a handshake with the gateway nevermind, d.js pipes it to the same event
Help
Error
embed.author.icon_url: Not a well formed URL.
at item.request.gen.end (e:\somestuff\node_modules\discord.js\src\client\rest\RequestHandlers\Sequential.js:85:15)
at then (e:\somestuff\node_modules\snekfetch\src\index.js:215:21)
at process._tickCallback (internal/process/next_tick.js:68:7)
warning.js:18
(node:4276) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
warning.js:18
(node:4276) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```
Command:
``` const url = 'https://trackercdn.com/cdn/apex.tracker.gg/ranks/';
if(url + "silver3.png")
{
const embedapex = new Discord.RichEmbed()
.setColor("RANDOM")
.setTitle("User Page")
.addField("Level:", `${level}`)
.addField("Rank", "Silver [III]")
.addField("Wins:",`${wins}`)
.addField("Kills:", `${hopa}`)
.addField("Platform:", `${platform}`, false)
.setAuthor(username, `${avatar}`)
.setThumbnail(`${rank}`)
.setFooter("© by Apex Stats Bot");
msg.channel.send(embedapex);
}```
Source:
``` "rankScore": {
"rank": 4,
"percentile": 99.9,
"displayName": "Rank Score",
"displayCategory": "Game",
"metadata": {
"iconUrl": "https://trackercdn.com/cdn/apex.tracker.gg/ranks/apex.png"
},
"value": 2559,
"displayValue": "2,559",
"displayType": "Unspecified"
}```
embed thumbnail needs to be a url
you're passing an int
Are you sure setAuthor is a direct link to the image
No
i want to set it like a thumbnail to the player who use the command to show his in-game rank photo
oh i see something now the avatar is undefined
I solved it!
Ty for help anyway
Hi I'm Having trouble with global variables
global port, questions, pointer
port = 'website for questions'
questions = requests.post(port, json={}).text
questions = ast.literal_eval(questions)['result'][0]
pointer = 0
But, in my program
@client.command(aliases=['quest', 'q', 'start', 'play', 'ask'])
async def question(ctx):
print(port)
print(questions)
port is defined, but questions is not for no reason
is the error literally just "questions is not defined"
@halcyon nymph global variables are a bit meh. I redefine things each time for global variables, or make it a function that returns stuff
global variables tend to be bad practice most of the time
you could create your command in a cog and use self to store data which you need multiple times in different cmds
How else can I pass variables into async commands that can change on the fly
I'd recommend cogs
Idk what cogs are
having to open a file each time you run a command isn't ideal
I don’t think files would work because I need it to change
writing to json files
or simply don't
Again having to open each command is not ideal
more often than not, it will lead to corruption
cogs would make it so much easier
I think I’ll just use a class
true
Because classes are global aren’t they?
a cog is just a class
Oh, I didn’t know what you were talking about
lol
Suppose you write this extension
someextension.py
from discord.ext import commands
class SomeCog(commands.Cog):
@commands.command()
async def foo(self, ctx, ...):
...
@commands.Cog.listener()
async def on_some_event(self, args):
...
# This is important
def setup(bot):
bot.add_cog(SomeCog())```
In your main code file in the same directory, you could load it like this
`bot.py`
```py
from discord.ext import commands
extensions = ['someextension']
bot = commands.Bot(command_prefix='')
...
for ext in extensions:
bot.load_extension(ext)
bot.run(token)```
tada
Yeah, cheers
no worries
I think it does
Da someone code for writing all on pv
what
(without tell me "don't use heroku" pls) I am trying to host my py bot on Heroku with GitHub (https://github.com/ssebastianoo/herokuisatest) but it doesn't read the Procfile do you know why?
don't use heroku
@indigo geyser why not use uptime Robot
Who can help me
what did you define message as
@vestal crystal it doesen't work. it goes offline after 1 hour of inactivity
Yeah, that's the downside
And you have to take Repl open
Yeah!
so, VSC is better
Are you sure you pushed those changed to heroku
I don't like heroku becuase I have to pay
Heroku bad
no u
It's bad for bots
I can't pay for a vps
heroku is bad
But you're time limited on heroku
i will create a new account
So what's the point it's just going to go down anyway
pls stop
That is much too much effort than its worth
there are cheap vps linked in this channels pins
I CAN'T PAY
Buy a raspberry pi
Why can't you afford like $1 a month
How to make it written that my bot is online?
What do you mean
I don't understand the question Edward
Nice
Good job discord
You suck as usual
Debit card.
And my parents will not pay for this
Ask for a rasp pi for a birthday or something
Yes
???
This
my parents pay for my vps 
and my domain
The ??? will disappear when the bot is approved

It will disappear when the bot will be in this server, to be precise. Approved != On this server 
So is he not yet approved? Sorry, I did not know how long should I wait?
logically
How do we make that there is the server number or is our bot discord (Sorry , I speak French)
api
@topaz fjord my VPS is $70 a month and java is fucking it

nou
yes
yes
127.0.0.1
Heroku is gay
^
Heroku bad
Just use an overpowered k8s setup
Btw once aero gets $$$
We'll upgrade that
mmmmm
I'll probably switch all workers to GG for the low latency
And upgrade our current ones
What
Yeet
Mine only contact when they want $$$
I don't have one 
need a domain?
sugar daddy
I need a domain, or several lul
But im gonna be a responsible adult and pay for it with my lunch money
Rip
Do you actually make money off your bot?
I make money off Groovy; my bot is currently indev
300 bucks in domains holy shit
@tight heath yes I do
@quartz kindle I also have other sources of income lmao
But Groovy pays a fair amount
I also have a sponsor for aero so
@tight heath well yeah lul, but its nice when a bot is self sustainable
True
I lose $10 per month for keeping up my bot
But as said aero is indev

i need help
For the first prod deploy
how to get list of servers
Yes
I answered you in general
But we need a sharding manager
Because sharding in k8s is a tad more complicated
and that is?
@small prairie Want a easy code?
i got the count
but not the names
Learn discord.js
I need to add wss there
And then we can mostly start
I was experimenting with djs shards today, i wrote a weird script with the sharding manager to allow for custom number of processes with x shards each
i can get the total but not the lest
Well we have aether
@small prairie Did you code asleast one single part of your bot yourself?
It just needs refinement
yeah man evberuything
no
i just dont know this part
We start without using d.js' shardingmanager
Could you actually help
That's why we're ignoring him
me?? oof
What do you want to do @small prairie?
@small prairie How old are you?
List guilds in djs
Are you using discord.js?
yeah
12?

@trail dagger just stop
not your buisness
Calm tf down Emil
whatever this server is not ebing helpfull atm will be back later
I am calm?
Watch him go to Discord.js official
What part of the code do you need help with? show us the error
You can get the list of servers using client.guilds then you need to extract the names from it. You can use array.map() for example which works on collections
Stop the belittle and either contribute to helping (even though as ravy says that question was answered twice already) or stay quiet
Lmao
A code is not something you "find", is something you learn, and we try to teach, not give code for people to copy/paste without understanding
ravy didn't understand 👀
But cool that you found a solution
@quartz kindle I personally don't like the djs sharding manager so this is how we did it
- this sends the request to the pod containing total shards and shards to be launched https://git.farfrom.earth/aero/aether/blob/master/lib/Aether.js
- and this manages launching and reconnecting etc https://git.farfrom.earth/aero/aero/blob/master/lib/Manager.js
Both are connected via ws
Cool, ill check it out later, im on the phone now
Next steps are adding wss and signing, as well as an eval event
And then I can use it in prod

What i did was passing a process id into shardArgs and incrementing it on each process launch so the forked client knows whish shards to spawn in the client options lul
Oh that's cool
Well currently each pod will only launch one shard
So ig could get shards from hostname

ohno
I got it down to 80mb ram at 1.5k servers
(does anybody know how to eval an emit? I'm trying to be a lazy dev but eval only returns true and doesn't emit the event)
Lmao
Tbf I cache all members
why
Because 62 servers is nothing
lmao I reboot my bot every now and again just to delete the cache
I disabled all events except guild create/delete/update, clear all stores on the raw guild create event
Then use the raw message event to handle messages

It starts memory leaking
Speaking of memory leaks, the zucc package causes a huge memory leak in djs master
At least it did everytime i tried it
@topaz fjord you can disable guild subscriptions
on the v4 lazy loading pr
disabling events isnt supported by discord so theres no reason to do it
at most you save a couple bytes of allocations that are almost free to gc since you'll most likely be using a generational collector
Also zlib-sync was finally fixed for node v12, it cuts down djs's cpu usage by half
@quartz kindle i used uws and it caused some d.js callbacks to run before the event actually completed


anyone know how to fix that on git GUI?
(entire file is being flagged instead of specific code)
Add a newline at the end of the file?
like, just hit enter a few times?
No, just one empty new line at the end
yeah
nah still showing
yeah all i did was make new line and save, still throwing "no new line"
hmm... idk;
😭
js question: if you assign a variable at the beginning of a command.js file, will it get overwritten from multiple instances (busy bot)?
ex:
let damage = 0;
function doit () {
damage = 25;
return true;
}
function doit2 () {
damage = 45;
return true;
}
I've run into a small pickle with displaying a variable change that can't be the function return
Hey, I need help. I want to create a personnal prefix for each server. I made it : ```js
if(message.content.startsWith(prefix + "prefix")) {
let args = message.content.split(" ")
if(!message.guild.member(message.author).hasPermission("ADMINISTRATOR")) return message.reply("Permissions insuffisantes.")
if(!args[1]) return message.reply("Le préfixe actuel est " + prefix + ". Si vous souhaitez le changer, précisez le nouveau préfixe.")
if(args[1].length > 1) return message.reply("La longueur du préfixe doit être d'un seul caractère.")
if(args[1] === prefix) return message.reply("Le préfixe actuel est déjà celui précisé !")
prefix = args[1]
fs.writeFile("./administration/prefix.json", JSON.stringify(prefixies), (err) => {
console.error(err)
})
message.channel.search("Le préfixe a bien été changé en `" + prefix + "`.")
}```
But the output is : (node:11828) UnhandledPromiseRejectionWarning: DiscordAPIError: Bots cannot use this endpoint at item.request.gen.end (c:\Users\Megaport\Desktop\TimeBot\node_modules\discord.js\src\client\rest\RequestHandlers\Sequential.js:85:15) at then (c:\Users\Megaport\Desktop\TimeBot\node_modules\snekfetch\src\index.js:215:21) at <anonymous> at process._tickCallback (internal/process/next_tick.js:188:7) warning.js:18 (node:11828) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2) warning.js:18 (node:11828) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. can someone help me ?
JSON.stringify(prefixies) variable name intentional?
const prefixies = JSON.parse(fs.readFileSync("./administration/prefix.json", "utf8"))```
I've this
Hoff you can't use the search endpoint
message.channel.search("Le préfixe a bien été changé en `" + prefix + "`.")
Hoff in stable, check out the TextChannel class for fetching messages. In master, check out the MessageStore
lol
Fuck me
fatigue is always a contributing error 😄
Hey, it's an awareness poster
Don't code in the wee hours unless your jacked on caffeine 😄
speaking of coffee
I need to solve a "repeated code" problem
use functions?
hold on ill paste it
sting: {
reqLevel: 1,
mpCost: 2,
errorStr: "Sting requires 2 MP.",
cast: async (player, message, target) => {
let spellDmg = Math.floor(player.maxHP / 20);
if(target.hasSHIELD)
spellDmg = Math.floor(spellDmg * 0.75);
else if(target.hasSHIELD2)
spellDmg = Math.floor(spellDmg * 0.60);
target.currentHP -= spellReturn;
await message.channel.send( `${player.name} casts **STING** on ${target.name}! Damage done: ${spellDmg}! Remaining HP: ${target.currentHP}/${target.maxHP}` );
return true; // necessary to continue file. Some spells have false returns for case-by-case validation.
}
},
so I decided to make every spell an object for clean looking c ode
but then I realized, "if every damaging spell just causes damage, that should be the return"
in other words, the handler could reduce target hp etc.
how about you also return an object like idk
however, the function itself needs the change to display properly
If all of them are a similar format like that, use a class?
{ damage: 5000, paralysis: true, ... }
yeah 1 option is a multi return
Hey guys, my bot had 68 upvotes and now has 2. Can someone help me?
if I push it all to the handler the cast function pretty much just becomes a "switch case" for damage done
Oh, Ty @late hill <3
not the worst idea though
porting 5 lines of repeated code just to stomp on my idea a little bit
Nice run script
Ah
nice one line bans.json
999

Discord.js and JSON
How would I make a JSON based leaderboard?
I've tried a lot, but nothing has worked...
JSON file:
{
"users": {
"userID": {
"points": 100
}
}
}
Ping with response please!
have you thought about not using json files as a database
.json files can corrupt when they are written on a lot. Which can cause you to loose all your data. Use a database like Mongo or SQLite
@floral bloom
@floral bloom as people have said its worth the time investment to figure out a simple db, but the answer to your question is a number of string editting techniques and fs commands
Thanks, but I think I found a way.
yeah, I started off doing something similar with my bot
and by 15 users I was already having issues with fs object and json
cannot write file in use
I'm re-coding an old bot and it's never had issues with JSON files being corrupted IIRC.
It has over 120 users in the database.
its not only that, json has strict formatting rules and restrictive data types
if your die hard committed to keeping json 🤷
mess up formatting and your file is unreadable
if you use the non sync methods, you risk corruption by writing twice at the same time to the same file
if you use the sync ones, you're locking the whole process to do the write
mongodb/mongoose made all my db issues brainless
I removed so much annoying json code
it literally took me as long as it took to format the json correctly as it did to learn mongo
for example, one of the most annoying parts of json was the discord snowflake
you can't store it as an integer in js because its too long
I use an NPM package to deal with the 1e problem...
Ace, are you familiar with any other db besides json or just stubborn to leave it? I don't mean to be condescending just curious
there is literally no advantage to keeping it that way unless a local file is a necessity for some reason
I know a very tiny bit of SQL but that's it.
here's an example of how simple mongoose is
const player = await players.findOne({"flake":message.author.id, "serverId":message.guild.id});
if(!player) {
player = new players({ flake: message.author.id , name: message.author.username , serverId: message.guild.id});
await player.save();
await message.channel.send('`' + player.name + ', you now have a Loaf Bot user profile! Type ?help in the chat room to see all commands.`').catch( (e) => { console.log(e); } );
}
that's my code to check for a new player in db
I mean, it looks more simple, but what does it take to create the database?
mongodb gives you a free host up to 512 MB
then you just need to do a little research on connecting it to nodejs
it'
No, I mean, how do you create the database?
keywords coming in here but
mongodb ... specifically mongoose is models and schemas
my "model" is players
and my "schema" is the players stats
that is a Schema, in other words a map of all the variables in the model
as soon as you .save a schema, it goes onto the db
then on the actual db it looks like this
but everything is found by properties as you saw above
Huh.
Ok, I'll look into it, thanks.
👍
I was stubborn in json but after crossing the learning curve of mongo(mongoose specifically) I would NEVER do that again with any project
I just use JSON because that's the only thing that I could actually make work
yeah, it's quick to get up and running because you don't have to leave your project folder
but it also quickly becomes a project of itself
Is it completely free?
Mongo is, yes
as long as you don't exceed the limit
my project is 82 KB / 512 MB with 30 users
Okay. And what is the cluster name for?
@maiden mauve btw if the name of the value is the same as the key in an object you can write it a lot shorter
{server : server, flake : flake} is the same as {server, flake}
:)
orly?
yup
so basically in that instance
if i did something like
const flake = message.author.id;
const serverId = message.guild.id;
the shorter version would work?
😉
On the bot page how can i get this as the background?
a clean background, no background decoration
background-color @trail dagger
Any recommendations for a bot language, I've coded in Javascript but I'm kinda bored I'd like to learn a new language.
java
Alright
Go is really fun
Rust is also a solid choice if you'd like to try something different
Ok, I guess will give them a try. Which is most recommended for command line?
command line apps?
What?
Which is most recommended for command line?
Yeah, Meaning doesn't require to be compiled or doesn't use something external for compiling.
out of those 3, only python
the others need to be compiled
although the build tools have ways of running directly (./gradlew run, cargo run)
Ok, Thanks!
asd
how do i get a text doc. to a py file
just replace the ext to .py
Also if you are using the default IDLE you can press ctrl+n and make one from there.
eg filename.txt to filename.py
idk how to replace
what OS
either way if you dont have a python idle, get one
it will make your life a lot easier
i have a idle
@tight heath lul, i think its a general consensus that uws is bad. i think its being deprecated/removed soon
@quartz kindle everyone on d.js discord told me it's bad, but it's still officially listed

Windows 10 is my operating system
also they should provide some benchmarks/statistics about those extra packages, like "how much improvement do you get from them"
@west spoke Windows 10 is my operating system I just need to know how to transfer the file
the most impactful one i could notice was zlib-sync, and supposedly zucc should be even better, but i cant use it because it leaks
@outer niche you want to change a .txt file to a .py file?
Yes
Ok
I don't see how that helps me
Don't see where it says how to transfer it into a python file
you just rename it
That does not do anything
python files are just text files with a .py extension, its literally the same file just with a different name
Accept I can't get it to go into a python file
why cant you?
Idk
what are you trying to do?
Oml
"transfer the file" is rather ambiguous
I want to transfer the text document into a python file
that is not a thing
textdocument.txt can be renamed to textdocument.py
does the text document have python code in it?
then do what i told you
I want to put it into a Python file
you do that by doing what we're telling you
That's not helping me
you need to enable windows file extensions, so you can see them, and change them
a python file IS a text file, it's just the programs that read it need it to be .py for formatting
if you dont enable file extensions, then you see "file.py" but in reality its "file.py.txt"
we're telling you all you have to do is change the file extension
still not helping
did you enable file extensions?
cant
No
well
the system auto hides them to make it look clean
if you execute a few commands, you can make them visible
@quartz kindleno
how do you see files then?
Idk
It is only the final name like I said
show a picture?
do .py at the end
then your files look like i said "filename" and not "filename.extension"
so you need to enable file extensions
so you can see them
you cant edit them if you cant see them
o
your files need to be shown as "py.txt" and "echo premium.py" and "new text document (.txt"
not the way they are now
the link i sent you explains how to enable file extensions
@quartz kindle and like I said before I cannot enable the file extender
why not?
did you go to where the link said to go?
Yes I went to the link I still do not understand it I type it into my computer and nothing pulls up
you dont know how to use the control panel?
Open Control Panel > Appearance and Personalization. Now, click on Folder Options or File Explorer Option, as it is now called > View tab. In this tab, under Advanced Settings, you will see the option Hide extensions for known file types. Uncheck this option and click on Apply and OK.
click on the start menu and type "control panel"
Computer settings or what
then click on "appearence and personalization" like it says above
there's an option in file explorer itself
view -> file extensions or something like that
yes there is, but i thought this way would be easier for him to find it lol
I only see the properties
did you open the control panel?
There is no option for the control panel
are you on a mac

I asked if it was through the actual computer
i said to click on the start menu and type it
All right I'm on the control panel
@outer niche just YouTube how
now click on appearence and personalization
I did I can't find anything
Learn how to show and hide file extensions in Windows 10 with this simple step-by-step tutorial video.
based on the screenshot they posted above
it seems they're on a mac
not on a windows machine
lol
Disable what
There's nothing there to disable
Un tick it
Got it
ok
now close everything and go back to your files
you should see your "py" file is now called "py.txt"
yes
👏
now rename it, and change ".txt" to ".py"
Got it
congrats
The file does not ope
that took way to long
Neither of them do
Open the closest real quick
python files are not supposed to be opened by double clicking
they are supposed to be run by python
My other one opens
NightzToday at 11:53 PM
that took way to long
because they're a child with probably almost to no past CS experience lol
ie: open the command line in the right folder and type "python yourfile.py"
@earnest phoenix 😂
It will not stay open
i told you why
you can also google "how to run a python file"
did anyone ask if the PC is plugged in? 
Honestly, I try to imagine a positive scenario but if you don't even know the basics of windows file extensions and handling
I cannot keep the bot running if the python file does not stay open
a "intro to programming" may be in order
Python tutorial for beginners - Learn Python for machine learning and web development. 🔥Get My Complete Python Programming Course with a 90% Discount (LIMITE...
Keeping up out open does not have anything to do with python
@outer niche you obv don't know basic...
@outer niche your in here with a lot of people who have been coding for years and we're all getting the vibe your asking the wrong questions
if you can't do logical thinking and have no prior experience working with "the behinds" programming is most likely not for you
meaning that your starting in the middle rather than at the root of your problem
just putting out a TIL
When file stays open but the two that we just did do not which is where I am confused
are you following a tut?
Following what
tutorial
^
I'm not going to open it
"I don't want a fishing pole, I want to know why my fish isn't cooking"
I had someone else help me with this last night that kept that file open all the time but the two files that I just did from doing what you guys told me to do does not stay open
@outer niche, you obviously do not know any basic knowledge of programming, I suggest you to watch some YouTube videos on basics of python. rules state that we shouldn't don't spoon-feed you.
Now if you guys are really helping me anymore so I'm just going to go find someone that can thank you for your help
you got help, your problem is that you want someone to do it for you instead of thinking for yourself

Rule 7.
" b. If you are a beginner, have a will to learn and do not expect to be spoon-fed."

Is that why all my bots ate operational with at least 20 commands each
So why can't you get it to work if clearly you know how to code already
you don't even know how to run a single file, but you have multiple bots?
Yes


so it took you like 30 minutes to enable file extensions but you have multiple bots that work....
🤔
Is that a problem
it's highly suspect that you have misinterpreted what people do here
you don't answer basic questions about how to program
you aren't asking a specific question that makes sense to anyone
@outer niche all these bots written in python?
Yes
@outer niche so you have made multiple functional bots in python? but you don't know how to run a file or enable file extensions
wut
@mossy vine The role Special Bot they means
I think it was written in JS however idk
Any reason I'd get 301 when I can open the url in my browser?
what url
yes
Yeah, trying to get there programmatically is giving me 301
oof
it's a redirect
Yeah I fixed it
it wanted www.
wait now I'm getting forbidden
Outdated api hurts
Well I got that to work
now Im just having a different problem, I can't seem to concat on my array
it doesnt error, but it's just empty
console ftw?
for the win

_
