#development
1 messages · Page 1694 of 1
async def get_economy_data():
with open("economy.json","r") as f:
users = json.load(f)
return users
async def update_economy(user, change = 0,mode ="wallet"):
users = await get_economy_data()
users[str(user.id)][mode] += change
with open("economy.json","w") as f:
json.dump(users,f)
bal = [users[str(user.id)]["wallet"],users[str(user.id)]["bank"]]
return bal
Ok
what's inside economy.json
what u want is to stop the loop once the fields you want have been added
but if you don't actually need to store the data then just remove it once you buy a new level
You might have been told this before but .json is not an appropriate database format. It will corrupt and you'll lose the entire thing.
Use a database.
if you buy a new level remove the old one
also this
If you want something simple to save data, python has shelves which look pretty damn awesome tbh
I don't code python so I haven't used this, but it seemed pretty fucking convenient to store key/value pairs 😄
I dont know how to convert what I have...im new to this
yeah
Thank you
How?
If you're new to this, take it from the people with more experience than you have: you're doing it Wrong
don't continue down this erroneous path. Take a step back, and move to a better method, because right now you are straight-up just putting red shells in a shotgun aimed straight at your foot. Don't do it.
It's fine, I'm just trying to help you here. Helping means telling you that you need to change what you're doing right now ^_^
I'm sorry for wasting your time
Don't delete it just... fix it 😦
Lol I have been trying now for 15 hours
Maybe just take a break then. Go sleep. Try again with shelve in the morning.
Alright well, the JSON attempt failed, try again 😊
You mean me saying make a new json?
No I mean stop using JSON
I would like to
Whoever told you JSON is appropriate for this is a moron.
I get jt...I dint belong...but this is the end...once thus is fixed im done
Use a database or shelve
Mongo db is the best
Ya I've heard.. I use the God awful repl
I looked into Mongo but I didn't understand it
@earnest phoenix what is the benefits of economics on a bot?
Great if you're on repl.it you literally have a database available to you, built in, provided by repl itself!
Click the Database tab and have a look at the examples.
I have %work.. it gives you money...then you can %levelshop and %buy levels then display them with %level

Ok
It's exceedingly simple to use too!
Ya..well I'm a Neanderthal in this group
But im trying
Is there anyway to fix this with my json before I convert it all to a db
I just want it work
No, don't. Stop.
Just because you've put a lot of time in a mistake, you shouldn't hang on to it. Quit while you're still ahead.
But it's not going ot be fixed
you can't put deodorant on a pile of shit and expect it to smell appealing
what if I tell you that when you finish this you ain't done?
let's say regular software have multiplicative bug amount
Well of course not. But I just need this last part to display correctly. Then I was going to go learn cogs and clean it up
software that use JSON db have exponential bug amount
You can't clean this up. You should delete it.
Stop trying to fix bad code, it's not worth it.
O.o
also, json db has the thanos issue
Snap. Data gone. Lol.
No you don't. Delete it and deal with it later
It's 100% ridiculous and pointless to hang on to code you should not be using.
But I will start over
look, let's say you finish your json-db thing
You've still learned things. The experience is not lost. But the code is.
you'll start storing data, right?
what then? to convert to regular databases later on will be harder than if you do it now
Yes I want to learn cogs and db next
why? because you'll have data
I just want this last thing to be finished
O.o
json is json, db is db
Well I mean I'm willing to learn whatever it takes
I'm sorry I appoligize for my novice
json-db is that chimera from FMA
hi guys
how could i get embed avatar from a user with oauth
i mean
if a user that doesn t have an avatar
is trying to login to a website with discord
how could i know what color is his default avatar
?
if im trying to log profile.avatar
i get null
3 votes and 5 comments so far on Reddit
so if my discriminator is 3078
what s the formula
cuz i don t get it
it quite literally says it there
See the modulo operator
Get the remainder of 3078 divided by 5
what do you get
oh
i got it
thanks :))
I think I have an error here in this line.. but im new to this and not sure. Anyone could maybe point me in the right direction?
Hey does anyone know how to make my bot stay in a VC 24/7? I wasn't able to find much online or in guides. I want it to be like how groovy (and other bots) will just stay in as long as you pay a premium, but instead of paying premium, I want it just in one server ( my own). I'm using Discord JS, thanks. Any tutorials or anything would be appreciated.
Hi, I think I was already trying to solve this issue here but didn't really manage to resolve it. All of the sudden I started getting those "user aborted request" error from I don't know where, which keep happening until the app crashes with "possible memory leaks" issue. Any ideas about it's origin?
have it join on your client on ready function? if ur not using a vps your bot will disconnect sometimes due to connection timeouts, etc
ah okay so i guess that means for now i wont be able to. Thanks.
Can i do something like join vc (channel ID)? Simplified cause I dont know exact code but something like that?
you will be able to do it
i'm using a repl
i'm saying if you don't have a vps, you will need to make it join everytime
yes so,
on your client.on ready function
make it so the bot joins your designated channel
and for your commands
dont have it disconnect or join a channel
and they bot will stay in it
wym it wont work
it will work
you just need to include it into your function lol
Hello, do you know how to adapt the avatar to the amogus mask?
let user = message.mentions.users.first() || client.users.cache.get(args[0]) || message.author
const canvas = createCanvas(867, 892);
const ctx = canvas.getContext("2d");
const background = await loadImage(
"https://cdn.discordapp.com/attachments/822225367372660806/829396711255965726/amogus_rap_editado.png"
);
ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
const avatar = await loadImage(
user.displayAvatarURL({ format: "png" })
);
ctx.drawImage(avatar, 300, 120, 230, 230);
const attachment = new Discord.MessageAttachment(
canvas.toBuffer(),
`${user.username}_amogus.jpg`
);
bezier curves
Can you draw images with those? IDk
Yea that's what the stackoverflow answers suggest
but you have to draw a rectangle the image will "clip" in
so you have to use curves
drawRoundRect 
it's not really a rectangle
I don't think that's a thing in the canvas api
what is it then?
ik
Why I'm getting this error [TypeError: Cannot read property 's' of undefined] when I try to connect with mongodb?
Can you show the full error
and the code
book about sus fungus
error, not code
okk
TypeError: Cannot read property 's' of undefined
at C:\Users\MI PC\Desktop\Mis Cosas\...\Programacion\Java Script\Archivos\node_modules\mongodb\lib\mongo_client.js:222:37
at maybePromise (C:\Users\MI PC\Desktop\Mis Cosas\...\Programacion\Java Script\Archivos\node_modules\mongodb\lib\utils.js:685:3)
at MongoClient.connect (C:\Users\MI PC\Desktop\Mis Cosas\...\Programacion\Java Script\Archivos\node_modules\mongodb\lib\mongo_client.js:221:10)
at node:internal/util:325:7
at new Promise (<anonymous>)
at node:internal/util:311:12
at Object.<anonymous> (C:\Users\MI PC\Desktop\Mis Cosas\...\Programacion\Java Script\Archivos\testing.js:8:42)
at Module._compile (node:internal/modules/cjs/loader:1091:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1120:10)
at Module.load (node:internal/modules/cjs/loader:971:32)
hmmm
My code literally is:
const { MongoClient } = require('mongodb');
const client = new MongoClient(`........`);
require('util').promisify(client.connect)()
.then(console.log)
.catch((e) => console.error(e))
client.connect already returns a promise I'm pretty sure
thx 🤝
i how to fix this pls help
wtf is happening in your terminal?
shard
Are you talking about the formatting?
my bot dont connecting
can you actually show us the errror
I wonder how you even read that
const { ShardingManager } = require('discord.js');
const settings = require('./ayarlar.json');
const manager = new ShardingManager('./bot.js', { token: settings.token, totalShards: "auto", spawnTimeout: "-1"});
(async () => {
await manager.spawn().catch(e => console.log(e))
})();
manager.on('shardCreate', shard => {
console.log(`Launched shard ${shard.id}`)
});
manager.on('death', (a, b) => {
console.log('Shard öldü, tekrar bağlanılıyor.')
client.destroy()
client.login(settings.token)
console.log(a)
console.log(b)
})
manager.on("disconnect", async (eventd, id) => {
console.log('Sharda tekrar bağlanılıyor!')
manager.respawn(30000, 30000)
})
my shard.js
here
ok what is the error
here pls wait
Also your terminal looks like a bastard child of Windows XP and baby puke. I don't know how you can not dig your eyes out looking at that
looks like a map from the great flood using dwarf fortress graphics
god how are you even reading this
too many requests is basically you spamming the API
can you give a sample code
Server setup system is available. Could it be from him? It creates channels and roles.
May I ask you a question first? How many guilds is your bot on?
here
maaan.
how the hell did you reach 35,000 guilds without sharding correctly? 
WHAT IS THIS OMG :D
im using sharding bro
client.on('message', msg => {
if (msg.content === 'kyazıyor aç') {
message.channel.startTyping()
msg.channel.send("a few moment later");
}
});
Why doesn't it work? what should I do?
Well clearly there's something in your code that spams the API but there's not much we can tell without examining the entire bot code
i buyed 2 VDS :D
how does it not work?
I did not understand too
ok and?
client.on('message', msg => {
if (msg.content === 'kyazıyor aç') {
msg.channel.startTyping()
msg.channel.send("a few moment later");
}
});```
here
And you're sending exactly kyazıyor aç in chat? noithing before or after? no uppercase letters?
how does a bot choose what custom emote to use if there are multiple of the same name
so like I may have a really complex emote name
but what stops someone from just maliciously copying it.
get the emote via it's id
im making a card & deck class for my bot and there is no good way that I see to assign each card an emote without doing every card manually
nevermind, the way javacord handles emotes, I should be able to check what server the emote is from
buyed
does anyone have an eval to leave all servers with less than 100 members for dbd.js?
why would you want to leave servers @formal trail
I want my bot to leave servers with less than 100 members in order not to accumulate unusable servers
wouldnt that be tos violation-ish
forcing the bot to leave the server
ig not
just run a script
that fetches all the guilds
if guild's member count is < 100
guild.leave
or whatever that function is
how many servers is your bot in?
my bot is in dbd.js
59
i dont do dbd.js
but if your bot is in 59 servers
you should know how to do that
https://dbd.leref.ga/functions/usdforeachguild maybe this idk
I don't move because I'm new to dbd.js and I'm starting at the discord library now
look at the docs
and fetch the guilds
after just use the guild leave function
or just go to their support sever and ask there
thanks
One message removed from a suspended account.
wuts this
One message removed from a suspended account.
totally not "bought"
oh
One message removed from a suspended account.
thats pog
One message removed from a suspended account.
@sage bobcat im trying something new, with equation generator 😉
One message removed from a suspended account.
what ya think
it plots equations , next part i have to make an interpreter for the equation from string
manually, GDI
GDI?
yeah dotnet's own 2d drawing routines
thats the next step im gonna make ye
prolly need a small tokenizer
i thougt it be cool to have that as feature
does anyone knows how can I apply toLowerCase here?
if (args[0] == 'dust2') {
let EmbedDust = new Discord.MessageEmbed()
.setColor("#1eb346")
.setTitle("Dust 2 Map")
.setImage("https://totalcsgo.com/image/callouts/dust2/overview.png")
.setFooter("pb!help for support")
message.channel.send(EmbedDust)```
args[0].toLowerCase() == 'dust2'
thx
@crimson vapor it says cannot read .toLowerCase of undefined
you could do args[0]?.toLowerCase() but that doesn't really fix the issue that you aren't making sure that args[0] is given
it answers only when I actually put the args
if it doesn't have the arg it don't send the error message
args[0]?.toLowerCase() will return a lowercase string or undefined
if its undefined then you aren't defining args correctly
my node.js is not v14 yet
ah
if (args) ?
wdym?
you could do (args[0] || '') but thats dumb
lmao
@crimson vapor so I can maybe make if(args[0])
or won't work?
Check if args[0] is undefined beforehand and if it is send an error message or something
then start comparing it
it just sends an error message when it doesn't have an args
but when I use correctly the command it works normally
and I just told you what to do
with pm2, how do you view the logs combined with the errors?
ok
--merge-logs doesn't seem to work
Alright so i am trying to set up (This person has voted) but
UnhandledPromiseRejectionWarning: Error [TOKEN_MISSING]: Request to use token, but token was unavailable to the client.
and i know for sure its right
nice
You're trying to call a method that does an API request before the client is even logged in
...
Show us the code at least
const Discord = require('discord.js');
var request = require('request');
var cheerio = require('cheerio');
function getStatData(location , $){
var selector = $('.segment-stats .value').eq(location).text();
var stat_array = $.parseHTML(selector);
var stat = 0;
if(stat_array == null || stat_array.lengh == 0){
return -1;
}else{
stat = stat_array[0].data;
}
return stat;
}
exports.run = async (client, message, args) => {
var UR_L = "http://csgobackpack.net/api/GetInventoryValue/?id=" + args[0];
if(!args[0]){
return message.channel.send("Please Enter a valid STEAMID64");
}
request(UR_L, function(err, resp, body){
$ = cheerio.load(body);
var success = getStatData(0, $);
if(success == false){
return message.channel.send("Invalid, make sure you wrote the STEAMID64, and that the user account is not private.");
}
var value = getStatData(1, $);
var items = getStatData(2, $);
var currency = getStatData(3, $);
var embed = new Discord.MessageEmbed()
.setTitle("__***CSGO Inventory***__")
.setURL(UR_L)
.addField("Current inventory",
"Number of Items: " + "__**" + items + "**__" + "\n" +
"Total Inventory Value: " + "__**" + currency + value + "**__", true)
.setTimestamp()
.setColor("#1eb346")
.setFooter("pb!help for support");
message.channel.send(embed);
})
}```
idk why but all the datas are -1, when they should be different. Does anyone know what my error is?
API Link: https://csgobackpack.net/api/
Csgobackpack API
oof why you using a deprecated lib, request
.-.
read their readme
can you send me the link pls?
its SQL, but better, you welcome
teach me SQL
ok thx
@opal plank
no
oh
erwin or another thing?
oh yea ads
both you mean
lmao
because erwin is famous for his ads
xD
accurate
XDDD
Editing djs to have stage channels for v12 go brrr
@pale vessel
const Discord = require('discord.js');
var fetch = require('node-fetch');
var cheerio = require('cheerio');
function getStatData(location , $){
var selector = $('.segment-stats .value').eq(location).text();
var stat_array = $.parseHTML(selector);
var stat = 0;
if(stat_array == null || stat_array.lengh == 0){
return -1;
}else{
stat = stat_array[0].data;
}
return stat;
}
exports.run = async (client, message, args) => {
var UR_L = "http://csgobackpack.net/api/GetInventoryValue/?id=" + args[0];
if(!args[0]){
return message.channel.send("Please Enter a valid STEAMID64");
}
fetch(UR_L, function(err, resp, body){
$ = cheerio.load(body);
var success = getStatData(0, $);
if(success == false){
return message.channel.send("Invalid, make sure you wrote the STEAMID64, and that the user account is not private.");
}
var value = getStatData(1, $);
var items = getStatData(2, $);
var currency = getStatData(3, $);
var embed = new Discord.MessageEmbed()
.setTitle("__***CSGO Inventory***__")
.setURL(UR_L)
.addField("Current inventory",
"Number of Items: " + "__**" + items + "**__" + "\n" +
"Total Inventory Value: " + "__**" + currency + value + "**__", true)
.setTimestamp()
.setColor("#1eb346")
.setFooter("pb!help for support");
message.channel.send(embed);
})
}```
still not working
you don't just change request to fetch
use it the proper way too, examples are in their docs

but I really don't know what is wrong with my code lmao
Read the docs
i don't even know if fetch supports callback
uhhhh don't think so...
but it shouldn't
from my knowledge it does not
even IF it supports it they still need to use the res.text function
I use it request on other commands and work perfectly
yeah, I will
but do you know why the command is sending the incorrect informations?
but it really isn't hard to use, if you read the readme js const body = await fetch(url).then(res => res.text()); const $ = cheerio.load(body);
you don't even need those fetch(UR_L, function(err, resp, body){ ... }anymore
debug
this
log all your variables and see where it went wrong
if you wrote all that code yourself then you might get the idea already
oh my oh my, what do we have here, a customer?
I used another code I made as base
a weeb is short on time? impossible
I need help with express js. What is wrong with my script?
Error: cannot read "password" of undefined.
express js:
const express = require('express');
const app = express();
app.use(express.json());
app.use(express.static("public"))
app.get("/login", (req,res)=>{
res.sendFile(__dirname+"/public/login.html")
});
app.post("/login", (req,res) => {
console.log(res.body.password)
console.log(res.body.name)
})
app.listen(3000)
--
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<label>Login</label>
<form method="POST" action="/login">
<input name="login"/>
<input name="password"/>
<button type="submit">send</button>
</form>
</body>
</html>
you dont think animes watch themselves, do you?

though, legit, i got errands to run
Meaning res.body is undefined
yes
yea, use req
i barely used express though
you're missing the form processing https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/forms
Ok
or it could be req, lol
Have you tried logging req.body and see what it returns
@umbral zealot in the form tag
what does value mean
value=" "
do I have to add that?
really?
name isn't usually enough
id and name have to be the same?
I always do both just for sure, and yes, try both being the same
https://flaviocopes.com/express-forms/ seems to think you need to add other stuff too like express.urlencoded but I'm not sure about it
Anyone know if it's possible to send data from a nodejs server to another nodejs server and have the other nodejs server parse the data sent?
welcome to IPC
What
if they are in the same process, use IPC
otherwise, use http/api
search IPC
you'll see what i mean
aight, time to head out

Ok
message.guild.members.cache.filter(m => !m.user.bot).size how do i account for members not inside of the cache
fetch all members first
await message.guild.members.fetch();
message.guild.members.cache.filter(m => !m.user.bot).size```
just add that first line, assuming you have the intent
Is there a way for discord bots you can do something like client.uptime ect I can not find anything in the docs I use discord.py
I don't see many mention of it in the documentation. One way would be to save the timestamp when the ready event is called (which may be triggered multiple times).
hello so I am trying to use canvacord to make the rank card, and the rank is always 1...
and when I do user.rank it gives me an error
does anyone here know what is wrong and what I have to do to fetch their rank
btw im using discord-xp
please ping me if you know what is going on
User@DESKTOP-4N2JIA7 MINGW64 ~/Documents/Projects/Main Projects
$ git remote add origin https://github.com/Vigintillionn/repo
fatal: not a git repository (or any of the parent directories): .git
User@DESKTOP-4N2JIA7 MINGW64 ~/Documents/Projects/Main Projects
$ git remote -v
fatal: not a git repository (or any of the parent directories): .git
anyone knows why I keep getting this error?
ok nvm I was in wrong folder lol
mingw havnt seen that for a while 😛
I'm looking for a bot that watches roles and automatically applies higher roles according to the roles people have. For example: to receive role A in a server, you must first acquire roles 1, 2, and 3. Normally, I'd have to manually check everyone's roles and manually tag the people with those 3 roles with the 'A' role but with hundreds of users, this is way too much. What I'm using this for is my gaming guild. As people achieve clears in game, they get tagged for that achievement automatically with another bot I use. I want a ranking system based on those clears in order to lock less experienced people out of harder content.
YAGPDB has this function in "Role commands" but it's not automated. My users would have to manually enter commands for the bot to tag them. It's already way too much to ask them to read anything, so we can forget hoping they can figure out how to copypasta commands.
Am I the only one who thought djs v13 was released when they pinged
probably
i saw a few of the new changes tho, like the timeout getting removed from <Message>.delete()
not a lot of major changes so far
here's the link: https://github.com/monbrey/guide/blob/master/guide/additional-info/changes-in-v13.md
i thought it was 12.6
lmao
Nooooo. They removed disableMentions which I made D:
use allowedMentions instead
I don't even use discord.js lol
use D++ :^)

Also, Tim. It took me a month or two, but I finally migrated to postgres and things perform so much better than on maria and/or redis
So nice to not have to worry about performance being an issue for a while
@pale vessel do you know the intents site thing that has the easy generator?
Ok for some random reason
When I move my main dashboard page from / to /server/:serverID it decides to not load any of my static files
any reason it would do this?
Isnt discord removing fetching all members from a guild
When was that said?
Saw some notes of Discord.js dev's scolding some person who was fetching all menbers
Havent heard anything of the sort
Most bots DO fetch all members
But that scaled poorly
Cuz too many members might cause u to skip a heartbeat
how are you loading them?
the fetchAllMembers option was removed
not guild.members.fetch()
Ah, thats what I meant. Sorry
Well I fixed it now 
exdee
Help pleeeeease
Once I launch my bot it takes like 10 minutes for this to appear the first time, since then it keeps popping multiplied in intervals until it reaches point where the whole app crashes on "MaxListenersExceededWarning: Possible EventEmitter memory leak detected..." 
You might have put a .on inside of a .on or other function which gets called often. Don't do that.
do you think client.on inside db.connect might be causing that?
cuz I only got client.on and client.on ready - each once - inside my DB connection
why would you do that
smells like bad design
👀 real talk
because I don't really know what I'm doing 😂
I just wanted to make a bot and now when it got big I'm hitting my head on this
what is the correct design then?
separate them?
is that what you mean?
and do you think the abort requests were caused by that? I'll figure out soon ig tho 😆
[
im trying to use an anime quote api and this is the code
def get_anime():
response = requests.get("https://animechan.vercel.app/api/random")
json_data = json.loads(response.text)
quote = "**" + json_data[0]['q'] + "** *-" + json_data[0]['a'] + "*"
return(quote)
and im getting this error message for some reason
json_data[0] is wrong
Blocking 
so i have a report command, i wanna make it so the Bot grabs the message link of the report so the staff can review where the timestamp of the report came from, how would i grab the message link of the origins of the report?
your library should provide a message url in the message object

One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
what happens when you zip your desktop or something
One message removed from a suspended account.
One message removed from a suspended account.
is anyone familiar with fastify here
It'll make a zip file with shortcuts
how do I update my bot information on the site? javascript
post to the api

Anyone?
@client.command()
async def buy(ctx,item,amount = 1):
await open_account(ctx.author)
res = await buy_this(ctx.author,item,amount)
if not res[0]:
if res[1]==1:
await ctx.send("That object isn't there!")
return
if res[1]==2:
await ctx.send(f"You don't have enough money in your wallet to buy that! {amount}")
return
await ctx.send(f"You just bought {amount} {item} level.")
async def buy_this(user,item_name,amount):
item_name = item_name.lower()
name_ = None
for item in lvlshop:
name = item["name"].lower()
if name == item_name:
name_ = name
price = item["price"]
break
if name_ == None:
return [False,1]
cost = price*amount
users = await get_economy_data()
bal = await update_economy(user)
if bal[0]<cost:
return [False,2]
try:
index = 0
t = None
for thing in users[str(user.id)]["level"]:
n = thing["item"]
if n == item_name:
old_amt = thing["amount"]
new_amt = old_amt + amount
users[str(user.id)]["level"][index]["amount"] = new_amt
t = 1
break
index+=1
if t == None:
obj = {"item":item_name , "amount" : amount}
users[str(user.id)]["level"].append(obj)
except:
obj = {"item":item_name , "amount" : amount}
users[str(user.id)]["level"] = [obj]
with open("economy.json","w") as f:
json.dump(users,f)
await update_economy(user,cost*-1,"wallet")
return[True,"Worked"]
@client.command()
async def gbuy(ctx,item,amount = 1):
await open_account(ctx.author)
res = await gbuy_this(ctx.author,item,amount)
if not res[0]:
if res[1]==1:
await ctx.send("That object isn't there!")
return
if res[1]==2:
await ctx.send(f"You don't have enough money in your wallet to buy that! {amount}")
return
await ctx.send(f"You just bought {amount} {item}.")
async def gbuy_this(user,item_name,amount):
item_name = item_name.lower()
name_ = None
for item in gstore:
name = item["name"].lower()
if name == item_name:
name_ = name
price = item["price"]
break
if name_ == None:
return [False,1]
cost = price*amount
users = await get_economy_data()
bal = await update_economy(user)
if bal[0]<cost:
return [False,2]
try:
index = 0
t = None
for thing in users[str(user.id)]["inv"]:
n = thing["item"]
if n == item_name:
old_amt = thing["amount"]
new_amt = old_amt + amount
users[str(user.id)]["inv"][index]["amount"] = new_amt
t = 1
break
index+=1
if t == None:
obj = {"item":item_name , "amount" : amount}
users[str(user.id)]["inv"].append(obj)
except:
obj = {"item":item_name , "amount" : amount}
users[str(user.id)]["inv"] = [obj]
with open("economy.json","w") as f:
json.dump(users,f)
await update_economy(user,cost*-1,"likes")
return[True,"Worked"]
They are identical except for the currency
One allows a negative balance
How to fix?
One allows a negative balance
is that a json database

But being the case what do I do?
hmmmmmmmmm

which one allows a negative balance
what
Its 2 diff stores... buy works.. if a user dosent have enough money it returns false 2.. but gbuy dosnet it just makes the balance negative
Each store uses a different currency
does djs 12 support stage channels?
tbh idk lol
Omg ty

Lol
found it
@client.command()
async def gbuy(ctx,item,amount = 1):
await open_account(ctx.author)
res = await gbuy_this(ctx.author,item,amount)
if not res[0]:
if res[1]==1:
await ctx.send("That object isn't there!")
return
if res[1]==2:
await ctx.send(f"You don't have enough money in your wallet to buy that! {amount}")
return
await ctx.send(f"You just bought {amount} {item}.")
async def gbuy_this(user,item_name,amount):
item_name = item_name.lower()
name_ = None
for item in gstore:
name = item["name"].lower()
if name == item_name:
name_ = name
price = item["price"]
break
if name_ == None:
return [False,1]
cost = price*amount
users = await get_economy_data()
bal = await update_economy(user)
if bal[0]<cost:
return [False,2]
try:
index = 0
t = None
for thing in users[str(user.id)]["inv"]:
n = thing["item"]
if n == item_name:
old_amt = thing["amount"]
new_amt = old_amt + amount
users[str(user.id)]["inv"][index]["amount"] = new_amt
t = 1
break
index+=1
if t == None:
obj = {"item":item_name , "amount" : amount}
users[str(user.id)]["inv"].append(obj)
except:
obj = {"item":item_name , "amount" : amount}
users[str(user.id)]["inv"] = [obj]
with open("economy.json","w") as f:
json.dump(users,f)
await update_economy(user,cost*-1,"likes")
return[True,"Worked"]
thats the one that dont work?
Yes
res = await buy_this(ctx.author,item,amount)
res = await gbuy_this(ctx.author,item,amount)
waoot
O.o
Ok

Ty anyhow
O.o maybe my savior is coming
lmao
You saw that too lol
nah jesus abondoned us
I hate this code
why does it reply with winner is undefined
?
wait
foind it
i shall use a collector
because js is bad
no u
no u
because ur variable is wrong
-.-
sorry my eyes
ye
yes
k
i havent worked a lot with reactions
ah, ok
hey guys how do u add prefixes to bots that ur making?
we add an if condition where if a message starts with a certain word or symbol then it's a command
for example... if you want the prefix to be "--" then this code
client.on('message',(message)=>{
if ( message.content.startsWith("--") ) { // This is what i'm talking about
//do some actions
} ;
});
uh hehe sorry where do u find that?
i wrote that
ooh ok
wait how?
if ( message.content.startsWith("~") ) { // This is what i'm talking about
//do some actions
} ;
});
?
oop
im so bad at bot amking TvT
nop TvT first timer
ohhh then you have to because it's one of the programming languages used to build discord bots
ooh
mainly Javascript or Python
hehe idek how to do that TvT
there are websites that teaches you how to. For javascript, w3schools.com.
ooh ok
...if you prefer javascript
you can use other languages for developing bots too tho.
oh mk
PHP is not even weird to write discord bots in ¯\_(ツ)_/¯
yes
I saw a bash script which connects into Discord and acts as an bot.
if it's well maintained then why not
there's a dot in the end. remove it
scroll a bit you will see javascript
yes
oooh okie
import time
import threading
import time
q = []
class QueueManager:
def __init__(self,num):
self.q = []
self.Node = None
self.num = num
def insert(self, val):
self.q.append(val)
def update(self):
while True:
#the time delay is there to test the queue system
time.sleep(1)
if len(self.q) > 10:
if self.Node == None:
self.Node = QueueManager(self.num + 1)
#this is splits the array and puts it in the Node within itself simular to a binary search tree
self.Node.q = [self.q[i] for i in range(len(self.q)) if i >= len(self.q) / 2]
self.q = [self.q[i] for i in range(len(self.q)) if i <= len(self.q) / 2]
#for each node it makes a thread this just activates it
th = threading.Thread(target=self.Node.update)
th.start()
else:
self.Node.q = [self.q[i] for i in range(len(self.q)) if i >= len(self.q) / 2]
self.q = [self.q[i] for i in range(len(self.q)) if i <= len(self.q) / 2]
if self.q != []:
self.q.pop()
print(f'{self.num} has {self.q} \n')
test = QueueManager(1)
t = threading.Thread(target=test.update)
t.start()
while True:
test.insert(input())
print(test.q)
this is a queue system algorithm I been working on to test a certain concept not sure if the increase in threads is a good idea however does improve the speed at which it handles the increase of data
yea I just had an idea of a queue system that splits itself into two threads to handle data but the problem is having more threads might not be a good thing
i actually use some loadbalancing depending on the number of request i get for my AI ive made for one of my Bots, sure its in js but works quite well
if i get more requests to the AI i spawn new Worker threads on different threads
if the requests are done the worker threads despawn
like i say i want up to 5 workers, i can just configure it, if i get 500 requests each worker will handle 100 of them
gives better performance on the AI Classification
@lusty quest also I was wondering when a bot crashes due to spam which part crashes the program the is receives the information and sends it to the server or the server where the source code is running at
bot crashing due to spam? never happened to me, but the load is mostly on your side.
the one time ive got close to crashing due to spam where when ive had a small issue with an API that caused the API to return over 1 million results. This didnt crashed the bot just gave it a ping delay of almost 10 minutes and got the entire VPS to break out in sweat.
yea bot spams are usually rare
not really
I mean depends on the spam usually
something like one guy spamming it can happen often but spams where you just have a bunch of people all spamming at once is rare
one guy spamming you probably wont notice if you dont run the bot on a toaster
yea pretty much
I might make a discord bot that handles multiple messages at once without crashing
lol my smaller bot handles a few million messages a day and without even noticing
and almost all of them are send to my AI for classification
I ment like thousands of messages all being sent like super fast
depending on what you do with the messages they usually only take a few ms to get resolved
how can i save some info in a bot like if i need to save. Like if i do !warzone ...#..battle and i want the next time the user does !warzone then he gets the info of the user after it
use a database, not json. json is fine for static stuff not dynamic stuff
database
you could, but its not persistant
if your process restarts for what ever reason its gone
true but a db for only the name of the stats is to small to use a db right?
lol no
its only like ....#2312 battle thats it
and for how many things did you want to do this? like if you only want to do it for one thing you could hardcode it into a json file, but if you want to make it for mutiple servers and more entries use a DB
or use a key store database
well i did read the user has also a TAG item in discord.js maybee i can add it in there?
you could
so i can read it from there so the i dont need to save it in a db
also the .env is that for every server different or 1 for all the servers?
the .env stores enviroment variables for the entire process
oke its the same with that for let the admin select a channel 😄
but if you want to make the entire thing dynamic i still suggest some sort of proper database
if you want to make per guild configs, i can already suggest using a database
even if you only store 3 things
its only to get this
and they now have to use like !warzoneweekly ....#21312 battle
then you dont have to store anything
yea i have that but i want the user only use that once and then do like !warzoneweekly
why?
easy`r for the user
why? just call the API instead of your local storage
doesnt change anything for the user
and will be dynamic
yea they dont have to type every time the ...#23213 battle
you need an API key for this, to get an API key your bot has to be added to the page
they have to use it once and then do like !warzone weekly and can do like more commands like solo, duo, trio, or quads
i dont get your idea you want to show weekly stats from a single battle?
so they dont have to enter the whole sting
no its weekly but i want so have like this first time its like !warzoneweekly .....#213123 battle and when they do it again they only have to do like !warzoneweekly. then they get the information
you could make it a bit more fancy then.
Create a database where you store the Warzone Username of the Discord users.
if a user uses the Warzone command you just look up the stats for the Discord user that ran the command using the Stored username
-> Will give you the ability to use the solo,duo, etc stuff
and the thing you want to do probably will cause issues. but if you want to do it, its your bot.
and it sounds like you want to store the stuff for mutiple users, so i would suggest to use a Database
lol i dont have any access to a server db like i dont want to use a db on my pc to run it day and night
they are not that hard to use, but there are a few things to keep in mind, if you use "Free" Hosters like repl.it they delete the entire project and pull it again from github -> makes using SQlite based databases a pain in the asss
MongoDB atlas offers free DBs
you get a Small Database for free, sure wont work if your bot blows up and gets millions of users, but to get started its good
ill look in that may its something thx for the help.
is tracking number of commands used a part of storing user data?
Is there any downloadable version of the discord developer docs? Won't take the risk of having Opera open while I'm coding on Atom
did you reference them to a single user?
yep
then yes
cough repl has their own database
oki
which cannot be viewed even on public repls
yea but repl.it sucks
i agree but who else cares ¯_(ツ)_/¯
download source code
and what should i upload in my id? (im a student so what id)
then i rather suggest using MongoDB atlas who uses services with decent rep for hosting the DBs
i did and i got a plain html page with no css
they run the Databases on AWS or Google or Azure
needs to be an offical document, like passport
or drivers license
cant you use their hosting provider directly
alright
google firebase is free if you dont cross the quota limit
MongoDB atlas also gives you directly clustering, even the free DB is a Replica set of 3 Servers
if one server catches fire you dont loose data
catches fire more like causes fire
you have 3 Servers, 1 Main server and 2 Replica sets, the main server sends the data it stores to the 2 other Servers so you have reduntand Storage and high Aviability
aviability
anyways imma go add my weebsocket shit to my lib
Why doesn't the reactionAdd event in discord.js detect reactions on messages sent before the bot was online?
probably because you cache messages, and the cache gets cleared everytime you restart your bot.
What?
do you cache messages?
nvm messages get automatically cached.
still means everytime you restart your bot the cache gets cleared and the older messages don’t get cached again.
Is there a limit to how many OAuth2 redirects you can set on your Discord developer dash? I'm at 13 redirects and can't seem to add a 14th
Hello
who can help me
with a code
im trying to get a guild by a specified id, but it cant find
what the
use fetch
And also... why are you putting the response in a custom header
the request it's fine
but
when itry to get the guild by the id
it cant find
when i try manually
it works
Nvm. Looks like there is a limit of 13 redirect URIs... That sucks 😒
why u need so many
Are you sure there isn't an empty space or something in the guild id you receive
nope
They redirect back to a link on my site with a parameter for Google Analytics tracking
lol putting the response in a header
So I can see where the invite came from
why are you sending an html response to an xhr request
you need to enable partials for them
Probably you do alot of client.on('message',
yes
rent a VPS
rent?
You need a machine that runs your bot's code 24/7. So either your own computer, or a VPS
uh how?
Wdym how?
my computer is on but my bot is offline
is your computer running the code of your bot?
also this was my first time having made my own bot
do you know how a bot works?
uh does this count?
yea not really?
define "this"
no- i didnt mean the word TvT
its mah first time making my own bot sooo yea lol
Okay so first of all, I'm not sure how repl.it works so I couldn't tell you. Also, I'm pretty sure you're only supposed to have one message listener.
message listener? whats that?
client.on("message"...
Well, I would recommend you to learn some basic programming concepts and a little JavaScript before getting into making a bot. But it's up to you
Some people learn programming by making a bot. But it's usually not the best way to go about it
Oops
so i have this code to try and run the command and if there is an error it will send a message but why if there is an error it does console.log() it but it doesnt send a message?
try {
command.run(client, message, args);
} catch (error){
console.error(error);
message.channel.send(`OOPS, an error occured. ${error}`);
}```
wut-
usually never
lol
Mmhm
its good to start off with something more normal
nop
like learning how the language works in the first place
learning the basics
maybe making a web server using express in js
something that doesn't require much knowledge you know
It's like trying to learn the piano by trying to play a really hard song. It's gonna take a shit load of time and you won't be a good piano player nonetheless
Why is this giving error? token is working
its not that ideal to jump straight into something advanced without prior knowledge
i did but it was definitly not a good decision
woops
can someone help?
uhh does watching yt tutorials help?
i learned it with that but it wasnt a good decision
learn the basics and stuff and if you think you have learned good enough try doing something more advanced and work your way up
i jumoed straight inot making bots
but can somebody help now?
you can read faster than you can hear
lol
a human can read 250 words in a minute
for a video you only hear 150 in a minute
lol
also text guides are usually better
as text guides can easily be updated
unlike a youtube video
which is why most youtube tutorials are also old and outdated
😅
so i have this code to try and run the command and if there is an error it will send a message but why if there is an error it does console.log() it but it doesnt send a message?
try {
command.run(client, message, args);
} catch (error){
console.error(error);
message.channel.send(`OOPS, an error occured. ${error}`);
}```
?
does the bot have permissions to send the message?
yep
ok yep im doomed : D
do u need whole index.js?
I just need my bot to stay online and thats it TvT
^
99% who use ur bot are not bot devs and wont give a shit about it
no only like embed fields may not be empty
i just want it to do
i dont care if others dont care
what is your user going to do with that information
i want it to work
if you want to have a quick debug message, make a channel on your support discord where you send the errors in. but console is mostly more than enough
yes but i want this to work, can you help me?
🙄
i just want this to work if you cant help be quit
did you get errors in the console?
i just want it i dont care abt ur opinion
why it doesnt work
yes
would be ironic if the error trys to send the function to send the error as a error
do u need index.js?
i need the error
there is only the error i created by myself nothing more
can someone help pls? maybe like a command or message line? or whatever?
try using .catch(console.error) after the send() and let us know
the error is more than likely too long to send
okay
which is why you should 👏stop👏logging👏messages👏to👏discord👏
shut up
Oop
you're a moron
this probably just gonna say [Error error]
error.stack gang
Err is an object, no?
if you want to send it, send it as file
u mean this?
try {
command.run(client, message, args);
} catch (error){
message.channel.send(`OOPS, an error occured. ${error}`)
.catch(console.error(error));
}```
take advantage of the new discord feature
\
an error has a toString override, no?
ohh right
try error.message on the message
okay
it only sends the error to the console nothing more
ur right i forgot toString is a thing
but does it make the bot crash?
ye it doesnt send a message from the command it logs the error and does nothing more and if u use another command the bot still works
im surrounded by pros and im crying cuz ive made the biggest mistake i couldve ever made TvT
do u need index.js maybe?
let me see the error
#CryingIntheClub
trying to exist
jk
lolz

trasheds is not defined
i created the error by myself to test the system
It seems he's producing an error to test it

So that he can get his "debug channel" 
are you sure that the error is logged in the catch clause
yes do u need to see index.js?
first time you're not invisible
console.log("a") in the catch clause




