#development
1 messages · Page 757 of 1
stop trying to help if you dont know what you are answerting
In wbhooks i'm out
Shards should be able to fetch channels from each other no?
Depending on his sharding method, the channel might not be there
they cant
It could also be that his code in there is executed before the ready event?
unless you broadcastEval or make a custom function for it
Which would also cause that I guess
His code should be aware that it could be undefined
And handle that properly
i'll try the Webhook thingy
Can you do client.channels.fetch(id) tho?
Fetching a channel from the api should bypass shards
Or client.fetchChannel in stable or whatever
whats does that mean
Literally what it says?
Disable "Requires Oauth2 code grant" @earnest phoenix
Its disabled alr @summer torrent
@earnest phoenix the URL to redirect is invalid
Would using a listener for commands be bad?
Something like
// IN loader:
<MyClass>.on("ping", function(message, args)
{
message.channel.send("Pong!");
});
// IN message listener:
<MyClass>.emit("ping", message, args);
Alright, So what would be the absolute best way of doing commands?
use the command handler
aka make a list of commands e.g. files and load them all at start, so you can manage them like that
But that's just for managing them that's probably not the best performance.
If you want absolute best performance, code your commands inside the message event
Will save you a couple nanoseconds
And yes, a command handler can literally be a million different things, do whatever you feel like
I've done shit like parse commands in the raw event and use them like this client.on("/ping", message => {})
And also shit like client.on("message", message => require("commandsfile")(message))
Be creative
How can we make bot 7/24
you mean keep it online?
Yes
host
hosting, look at pinned messages
hey does anyone know why I am getting this error?
it downloads and then it says I have not installed ffmpeg
pastebin or similar please
ffmpeg/avconv what would appear it cant find ether of these
hmm i installed it and put it in my path though
or environment variables
how do I fix it?
Did you restart your terminal/ssh/system after adding to path?
yes
yeah that's good
definitely my code haha
https://paste.mod.gg/kinojawuya.py this is my code, its line 88
'name' might be referenced before assignment
The error says you're calling play on a none type
So it seems your voice variable is not getting a voice channel correctly
but I'm not a python guy
@dark swift that was taken from GitHub or a YouTube video I recognize the code
yeah, I don't understand how to use the ffmpeg and youtube dl so I watched a video, when i said my code I meant like the code I am using
not trying to take credit for it
I'm reaching maximum call stack size in my Eris bot but idk why...
here's more info: https://sentry.io/share/issue/beb64a49fba441729b5c7484d9dcc77a/
I don't recommend assigning objects
could be
It worked fine until I made some recent changes... I was trying to go from a regular client class that I'd pass into everything to a singleton
i suspect that it might mess up eris's client, but im not sure
me neither, but i just wanted to try this out
When I do it this way, I don't have to import the client class into lots of the other files
(its a TS project so i need to import it in every command and event file due to typings)
class SomeCommand extends Command {
constructor(client: Client) {
super(client, { name: "blah" });
}
}```
yea I know it's a TS project
if i made it into a singleton i wouldn't need to import the Client class in all the files where i don't need to access it, which would be a majority of the filess
im starting to suspect that it's not an eris error... i did this: ts import { Client } from "eris"; class MySingletonClient { private client: Client; constructor() { this.client = new Client(process.env.TOKEN); Object.assign(this, this.client); } }
and it still gave the same error
Hi! I use client.fetchUser(id).tag to get a user tag to show it in my bot economy top. But i get 'undefined'. What is my mistake? (discord.js)
function getNicks(obj){
let fr = '';
for (var i = 0; i < 20; i++) {
let user = client.fetchUser(obj[i].id); // undefined
fr+=user.tag+"\n";
}
return fr;
}
When I use eval 'undefined' too. (I evaled 'client.fetchUser(SOME ID)')
I thought fetchUser returns a Promise
And how I can get user tag? (I am new in js)
Thx
Ok... i've tried manually assigning all the properties from settings, that didn't solve it
I tried to make a new bot using a singleton... just the client class and logging in, and it worked fine... so the problem is somewhere in my code
Here's my entire client class in a gist... is there any suspicious code there that can cause a max call stack size error: https://gist.github.com/SinistreCyborg/3b911594808e10f6d7d022e5884e77ec
How do I find a member in a server if their username is Jasper, and the search field is jasper, JaSpEr etc
JS?
Yes
.toLowerCase() both the username and the input and see if they're equal
Collection.find()
takes a function
<Guild>.members.find(member => /* check if usernames are equal */)
Doesn't the max call stack size error occur when you make too many function calls
yeah
common if u do recursive stuff
i do have a recursive function on there
this.walk()
but i have a stop thing
It's an infinite loop somewhere
Add the code back piece by piece until it breaks
lmao ok
alright
Keep in mind that the imports and functions are still there but they're not called in the constructor
Which block did you add before it broke?
Lines 21-27
Hi, i go to shard my bopt but i have some problems, the first is the number of guilds andd members
bot.shard.fetchClientValues('guilds.size')
.then(results => {
return results.reduce((prev, guildCount) => prev + guildCount, 0)
})
.catch(console.error);
}
function getMembers() {
bot.shard.broadcastEval('this.guilds.reduce((prev, guild) => prev + guild.memberCount, 0)')
.then(results => {
return results.reduce((prev, memberCount) => prev + memberCount, 0)
})
.catch(console.error);
}```
imma console.log and check
Why getGuilds() is undefined ?
Impossible to know if you don't give us the error
Wrong way to use async await
Me ?
Huh this is... bizarre
All the events are being loaded multiple timess
it loads all the events, then loads all of them again, and again, and again
getMembers() for example return undefined for me
Doe the class you are requiring create a new instance of the singleton?
some of them do, yeah
wait not a new instance
they just run ManateeClient.getInstance()
neb, return the value from the function
@lofty hamlet e function returns immediately, it doesnt wait for the .then()
?
You need to use an async function and use await instead
Oh ok so if i want return the number of guild of my bot i do this ?
I think functions will still handle the .then iirc
import { ManateeClient, Event } from "./wherever";
export default class extends Event {
exec() {
ManateeClient.getInstance().user.id
}
}```
They do stuff like that ^
And getInstance() is in the gist from earlier
its not called yet
i was re-adding the code piece by piece, and so far, walk() hasn't been called
ok i can confirm that the client class is being initialized multiple times
console.log(readdirSync(events));
for (const file of readdirSync(events)) {
if (!file.endsWith(".js")) continue;
const event = new (require(path.join(events, file)).default)(file.split(".")[0]);
this.on(event.name, (...args: any[]) => event.exec(...args));
}```
i ran that (notice how the console.log is outside the for loop)
and i got the same array of filenames logged several times
so the constructor is being called several times
But the constructor is being initialized only once? (2 results show up but one is TS and the other is compiled JS)
...
https://tayron.is-inside.me/tTHfII5Y.png Update: Yeah Webhooks are working thx
well, are you still creating multiple instances of mantee
Instances of mantee? 
@opaque eagle I think you have a cyclic dependency
The command loader calls getInstance and getInstance calls another command loader because the instance didn't finish initializing, so the actual instance never gets created
Pass the unfinished instance onto the loader as an argument
And use the unfinished instance instead of calling getInstance
Or move the loader out of the constructor
And call it manually
function loadEvents(): any[] {
const events = path.join(process.cwd(), "dist", "Internals", "Events");
return readdirSync(events).reduce((arr: any[], file: string) => {
if (file.endsWith(".js")) {
const event = new (require(path.join(events, file)).default)(file.split(".")[0]);
arr.push(event);
}
return arr;
}, []);
}
export class ManateeClient extends Client {
private constructor() {
super(settings.token);
for (const event of loadEvents()) {
this.on(event.name, (...args) => event.exec(...args));
}
}
}```
i did that ^
still same error
(moved the loader out of the function)
- what lib
- what 'values'
The number of guilds
With varibiable than i can use
In discord.js
@modest maple
No thx it's good
But i have another question
I have 3 shards
Sorry for ping fail
But i have system of webhooks with server
const dbl = new DBL('DBLTOKEN/APİ', client);
client.on('ready', () => {
setInterval(() => {
dbl.postStats(client.guilds.size);
}, 280000);
});```
But the port is already use
im using these
No my bot is shard it's another system
can someone from before help
@boreal yarrow if client is in the DBL constructor, it'll autopost
so you don't have to post stats since it'll do it by itself
@lofty hamlet you cannot use the same port multiple times, you have to put your dbl webhook in your shardmanager
Or only in one shard
Yeah i know
@quartz kindle what i do put in my shard ?
Shardmanager*
All of bot.on ?
My logs is broken with shard
It's easier to put in only one shard
You can do something like js If(client.shard.id === 0) { let dbl = new DBL(...) dbl.webhook.on(...) }
I don't remember the exact code, but check the docs
Yeah i know
I speak bout my logs
When one command is write a logs in channel is send
But now, does'nt work with sharding
Different shards have different channels
So you have to either fetch the channel or do broadcastEval
For ?
const dmlogs = bot.channels.get("526172579141124110")
const logs = bot.channels.get("493050003657457664")
if (message.channel.type === "dm") {
if (message.length > 500) return
if (message.author.id == "471749111125770250") return
let embed = new Discord.RichEmbed()
.setTimestamp()
.setTitle("Un message privé a été envoyé au Bot")
.addField(`Envoyé par :`, `${message.author.username}#${message.author.discriminator}`)
.setColor(config.embed)
.setThumbnail(message.author.displayAvatarURL)
.addField(`Contient : `, message.content)
dmlogs.send(embed)
return
}
if (db.get(`guildPrefix_${message.guild.id}`) == null) {
db.set(`guildPrefix_${message.guild.id}`, "?")
}
const args = message.content.slice(db.get(`guildPrefix_${message.guild.id}`).length).trim().split(/ +/g)
const command = args.shift().toLowerCase()
if (message.author.bot) return
if (message.isMentioned(bot.user)) {
message.channel.send('Mon prefix sur ce serveur est : ' + db.get(`guildPrefix_${message.guild.id}`))
}
if (message.content.indexOf(db.get(`guildPrefix_${message.guild.id}`)) !== 0) return
try {
let embed = new Discord.RichEmbed()
.setTitle('Akimitsu')
.addField(`Utilisateur :`, `${message.author.username}#${message.author.discriminator}\n${message.author.id}`)
.addField(`Contenant de la commande :`, `${message.content}`)
.addField(`Nom du Discord :`, `${message.guild.name}\n${message.guild.id}`)
.setThumbnail(message.author.displayAvatarURL)
.setTimestamp()
.setColor(config.embed)
logs.send(embed)
let commandFile = require(`./commands/${command}.js`)
commandFile.run(bot, message, args, config)
} catch (e) {}
})```
System of logs
And with sharding he work just in one shard
@quartz kindle
And also my ststem of guildCreate
Wtf
He work just on the shard was launch
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 20, in <module>
AttributeError: 'Command' object has no attribute 'command'
[Program finished]```
```@bot.command(pass_context=True)
async def echo(ctx, arg):
await ctx.send(arg)```
I do not get what is wrong with it I have you written the command several times
Are you sure it's that command
Yes
Send the rest of your code, culan
do you know why isnt calling? :/
How i can make vote system with sharding ?
But my vote system does'nt work with sharding
how i do it is when the webhook hits my api it'll just update a boolean in my db
and the bot gets it from the db
File "C:\Users\Culann\Desktop\echo\echo.py", line 232, in <module>
async def bottles(ctx, amount: typing.Optional[int] = 99, *, liquid="beer"):
NameError: name 'typing' is not defined```
hello i am currently working on a sql system for your website and have a question how can i do that if you find the matching UID and AID in the SQL table then edit the EID but if you can't find it then make the board
@earnest phoenix Just try Fetchall from the row using the UID or AID at the locator, if the length of Fetchall == 0 you know it doesnt exist, you can then make / add what ever from there
@outer niche please send the rest of your code otherwise its like playing guess the shape
Oof sorry
if (isset($_POST['btn-eplistsave-add'])) {
$uid = $_GET['uid'];
$aid = $_GET['aid'];
$eid = $_POST['eid'];
if (empty($aid)) {
$error = true;
}
if (!$error) {
$eidq = mysqli_query($con, "INSERT INTO animelist (uid,aid,eid) VALUES ('$uid','$aid','$eid')");
header("Location: ../../../view.php?aid=$aid");
} else {
header("Location: ../../../view.php?aid=$aid&denied");
}
} else {
header("Location: ../../../view.php?aid=$aid&hiba");
} ```
@earnest phoenix idk what im supposed todo with this
create it only if you cannot find the specified UDI and AID
but if you find a UID and AID, edit the EID
use num_rows
but first try find specified variable, then use num_rows to check
if($getmember->num_rows == 1) {
/* ur code */
}``` smth like that
and you can do:
$error = true;
header("Location: ../../../view.php?aid=$aid&denied");
}``` instead creating another else
def SheetsMain():
SAMPLE_SPREADSHEET_ID = '129gwuo7c2STrgnNs82KDIN3FcxKccRafOk4ykO_imak'
SAMPLE_RANGE_NAME = 'File List!A4:155'
global ReturningList
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
r'C:\Users\ChillFish8\Documents\The_Innkeeper_Database\Spreadsheet/credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
Is that to log in?
learn the basics first
like
you dont know what pip is
thats like the thing u need before u can even do anything in python
Not true
You can print without using pip
you cannot say you know python unless you know how to use external modules
Okie sorry
you cant even use discord without installing an external module anyway
learn the basics
WHY WON'T YOU HELP ME???
i am
IM TELLING YOU LEARN THE BASICS
legit
if you learnt the basic things in python
you could run a discord bot
you cannot say you know python unless you know how to use external modules
You're not telling me anything about coding
Google -> Learn python, then Google -> Discord.py Docs

the thing is
i can just say learn the basics here, because.
thats what you need
to even install d.pu
d.py*
You mean mysql_real_escape_string?
mysqli_real_escape_string
But mysqli has a replacement
php7 has only supported mysqli_* so xd
Well SO says
Prepared statements only. Because nowhere escaping is the same thing. In fact, escaping has absolutely nothing to do with whatever injections, and shouldn't be used for protection.
While prepared statements offer the 100% security when applicable.
tbh ye, but i tested it and it works perfectly to block sql injections
for me
¯_(ツ)_/¯
Yeah it makes sense that it works
But it's like using the wrong tool for the job lul
Hammering a nail with a machete
yep
anyone know a bot that can moderate, join and leave logs, and leveling roles?
o sorry
ok
like there are thousands with it
What should I use when coding in C++?
literally any code editor/ide
Okay
codeblocks and visual studio are popular options
But don't you need a compiler
yes
What compiler should you sue
most ides will include the compiler iirc
use*
I don't feel like wasting a shit ton of space on Visual Studio so I installed vsc instead
if you are on linux, g++
I am on Windows
Ok
guys
what is best hosting place
for the best ping
?
Europe ?
or france
or ..
?
@lusty dew did you add the binaries to PATH
or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ g++ version
+ ~~~
+ CategoryInfo : ObjectNotFound: (g++:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException```
@vast holly check pins
Yea I am pretty sure
run the executable from directly where it is
@vast holly discord has servers in many places, so it depends on guilds
@mossy vine huh
there is no "best"
choose whatever you want
50-150 ping doesnt matter, and you wont get anything higher than that
it generally doesn't matter
you would ideally want a vps nearest to the api servers
which is NYC i think
but again it doesn't matter because of internal latency and the latency of the server region
Im new to this, once I export my bot, if i add new content to it, would I need to replace all the files or only a certain few?
im getting 124 ping on a vps hosted in somewhere east europe
i know, ping is usually 50-150 unless api is shitting itself
hypers, if you are debugging and running the program directly with node, just edit the files you need to edit and restart the process, if the app is published you will need to republish it again after editing
alright ty
Yea g++ still isn't working
yeah i dont think i can help you, i dont use windows, sorry
... okay
can anyone help me with g++ compiler from MinGW
it isn't recognizing g++ command
how do you do a random pic command that provides new and fresh pics without nsfw
and since ur not a big bot you dont have weeb.sh
exactly
If you are getting the pics from reddit you wanna randomize the pics you get
if I had an array i would need to refresh it a couple of times a day or it will get old
i can do that
no
but with random puppy
you can use Math.random()
so you wouldn't have to refresh your array 😂
Wgat
if I had an array i would need to refresh it a couple of times a day or it will get old
You wouldn't
If you want new pictures to be displayed
add more to the array
🤔
Then where will the pics come from
yea
cant guarantee not nsfw
noo u cant
Yes?
how
Reddit has an nsfw filter
it does?
oh
but you can implement a filter to return nsfw subreddits
Here is how I would do it using random puppy
let subreddits = [
//array of subreddits
]
let sub = subreddits[Math.floor(Math.random() * subreddits.length)]
randomPuppy(sub) // blah blah blah
Yep
What are the bennefits of making your client a class instead of doing client = commands.Bot()
I want to get position of role on role list. but .position gives me an incorrect position
example : 1st role on role list, seems to be lowest
Are you trying to get the highest role or what?
well yes
(I am using master)
Doesn't it go in order of when it was added
the higher the position the lower the role is in the list
or am I wrong
it follows a ranking system
a position of 1 is going to be the highest
wait no
Ah mk
I thought it went in order of when it was added
Highest being the lowest in the list cause it was added first
yeah actually i think it is, a role with a position of 1 is going to be the highest role
Yea
Well yes
Idk
and don't really care ima go back to my work
would this be a good package to use for sqlite stuff in python
https://pypi.org/project/aiosqlite/
try it and seeee tm
🤔
Why waste my time on something that’s possibly not good when I can get feedback from other people that help me make a decision on what’s good or not
Idk why you need a asyncio SQL lite
As the queries r async anyway and are quick enough to probably be faster than an asyncio version of the lib
We don't need . thanks
-dotpost @earnest phoenix
@earnest phoenix
Please do not post dots to clear your messages/get attention. It adds absolutely nothing to the conversation and just causes spam If you need to get attention, then say hello everyone. If you need to clear your messages, then press the Esc key. If you do not follow these instructions you will be muted.
also this is development
I am trying to call a class method in another file but I get this
self.create_engine('sqlite:///:memory', echo=True)
print("Successfully created an engine")```
XD
oof
wrong thing
File "star.py", line 29, in <module>
StarDatabase.create_eg()
TypeError: create_eg() missing 1 required positional argument: 'self'
xd
I get that
but I don't get what self would even be
You're trying to make a class?
Yea
By making a function
No
See the issue
class StarDatabase():
async def create_eg(self):
self.create_engine('sqlite:///:memory', echo=True)
print("Successfully created an engine")
You're calling self
Before assign it
Self just means
The class object gets that thing
you need to assign it like a var
E.g
Self.stuff = xyz
Why is it a required thing
Also I kinda see similarities with js
Doing self.zyx just is trying to call a property that don't exist
Unless u assign it
👀
Okay
so when I tried defining it
it moved it to an __init__ function inside the class
Yh
Yh
then use it inside the other funcs
Yh
so like
class StarDatabase():
def __init__(self):
self.engine = create_engine('sqlite:///:memory', echo=True)
async def create_eg(self):
self.engine
print("Successfully created an engine")
?
or
If you have the create engine in the init function that's where it is creating the db
Hm
So calling self.engine in the async function is pointless
so would i just define self.engine then in the create_eg func give it a value?
Yh
class StarDatabase():
def __init__(self):
self.engine
async def create_eg(self):
self.engine = create_engine('sqlite:///:memory', echo=True)
print("Successfully created an engine")
Maybe?
I'm not sure wether it will like the self.engine by itself being undefined
You might just need to play around with it
Cuz you might not actually need the _ init_ function if youre only doin that
It tells me to move it to an __init__ func
PyCharm?
Yea
Ah yeah.
I read youe thingy.
I wouldn't use the self if you're only going to use it for what it is rn.
If you wanna use it further in other functions ect sure.
If not I would ignore the PyCharm notification.
For what it is rn I wouldn't even put it in a class tbh.
🤷♂️
when i try to add a reaction with a unicode character i get this TypeError [ERR_UNESCAPED_CHARACTERS]: Request path contains unescaped characters (node-fetch)
@slim heart can you show some code?
maybe encode it?

tanku
np
@bot.command()
async def owner(ctx):
e = discord.Embed(title="Test", colour=0xFF0000)
msg = await ctx.send(embed=e)
em = discord.Embed(title="Test was edited", colour=0xFF0000)
await ctx.message.edit(embed=em)
How would i make the ctx.message.edit edit the bots message variable msg?
A Message instance is returned from <Messageable>.send
you call .edit on that returned instance
So msg.edit
What would be the best way to make a database in python? make it in a seperate file or?
What do you mean "in a separate file"?
Working with the db?
What?
Are you talking about interacting with your database in your bot's main file or using one db file for everything?
I am making a database for my bot
I am talking about doing all the db stuff in a seperate file is it wise
Like creating the tables and such
you aren't planning on using actual text/json files as a database are you
ah
But I haven't ever used it in python so I am not sure how I should go about doing this
I'd say it depends
I plan on making my own functions to help handle the db
Attach a connection to your bot variable and then work with it anywhere where it's necessary
How would I do that
Attach the sqlite connection to bot?
to the variable yes
bot.x = sqlite.connect(...)
Okay
Should the text be highlighted like that?
or is it just a pycharm thing
Ima assume it’s a pycharm thing
its a pycharm thing
Ah okay
Btw
How would I make it so I don’t have to create the table in the on_ready event
Like
How can I explain this
I wanna make a func that creates all the tables when called
And call that func in the on_ready event
I’d assume I’d make the function in a different file then import the function into the main file and call it that way right?
It doesn't have to be in a separate file
youre using sqlite yea?
also, you need an async lib
aiosqlite?
no
If you want to use a thin wrapper around sqlite3 and make it work with asyncio, consider using this: https://gist.github.com/Rapptz/c1ff9fc7dc15194f305eb13e6cb57de1
you cant use the built in one
its blocking
i literally linked you soemthing
welcome to programming
Lmfao
tis a pain in the ass to do anything other than 1+1
Python is a pain in the ass period
pow(e,0) 
easier than js ¯_(ツ)_/¯
Any language is pain in the ass at this point
That's preferences
X is easier for someone than Y but for someone else Y is easier than X
literally any non-async lib will cause problems
You can use sqlite if you are 100000% sure it won't hang your entire bot because it stopped somewhere for too long
or an async lib
What the hell is the difference between what I am doing and what they are doing
🤔
They are using sqlite3
yeah but its being wrapped so it doesnt block your bot
So what am I supposed to do with it
make a file, chuck that code inside it, import the file, and use it
🤔
the usage is p much the same, you just have to await everything
Flashbacks to me being yelled at for not using f-strings in d.py server
Now it's sync vs async here
Flashbacks to being disrespected in d,py server
Still happens
just dont ask questions when vex is around and youll be fine
also dont ask stupid questions
Tbh I'm grateful for that since f-strings are 10/10
Any question can be considered stupid depending on who you are asking
dumb question:
It's usually the ones that need common sense to be applied
Questions that would need a look at from a more experienced Python coder for more efficiency etc is not that dumb objectively
Time to do something people tell you not to do xd
IE my code
Wtf
Couldn't you just for-loop that 🤣
yea
Yea
👌
dude i did everything the way you werent supposed to
for example...
I see nothing wrong there
overrode _inject and _eject

Sounds interesting
Does anyone wanna collab on a py bot
I may not know Jack shit about python but hey it’ll be a fun ride 😉
Nah I’m kidding
Hmmm
Odd
@stable horizon Didn't you say that everything is the same you just gotta await it
I have
you havent awaited something
Everything is awaited
'_ContextManagerMixin'
that is a wrapper for something that has yet to be awaited
Idk then
whats your code?
I’ve awaited everything
from custommods import asqlite
async def create_tables():
db = await asqlite.connect('pystar.sqlite')
cursor = await db.cursor()
await cursor.execute('''CREATE TABLE IF NOT EXISTS users(
user_id TEXT,
warns INT,
mutes INT,
reports INT,
bans INT,
joined_at DATE)''')
hm
I got it working
I made a typo in one of the awaits
Every time you wanna query the db you gotta reconnect to it?
Wdym
bot.db = await connect to db
Hm
I was just going to do
from custommods import asqlite
async def create_tables():
db = await asqlite.connect('pystar.sqlite')
cursor = await db.cursor()
await cursor.execute('''CREATE TABLE IF NOT EXISTS users(
user_id TEXT,
warns INT,
mutes INT,
reports INT,
bans INT,
joined_at DATE)''')
async def find_one():
db = await asqlite.connect('pystar.sqlite')
make my own functions
efficiency says dont, but you do you
Oh wait yea
But wait
won't I still be connecting everytime I use the db by attaching it to the client
if I call that variable I am still connecting to it am I not
okay
is there any specific way I have to do it
or can any file I make have access to client.db
could pass client as an argument
How so?
to your function...
Oh
I thought you meant to something else
lol
Wait do you mean define client.db in the main file or inside the file where I make the functions @stable horizon
main file
Hm
How will I do that if i have to await it
Oh wait
nvm
oof
Okay nevermind my way didn't work
class StarClient(commands.Bot):
async def on_ready(self):
await create_tables()
print('Logged on as {0}!'.format(self.user))
async def on_message(self, message):
await self.process_commands(message)
client = StarClient(command_prefix="p$")
client.db = await asqlite.connect('pystar.sqlite')
since my client is setup like that
I don't see how I could make client.db async
do it in on_ready
How do I create a node for a music bot through lavalink?
@stable horizon
How so
on_ready is run when the cache is filled. your client is defined when you do client()
check your awaits again
you said that last time 
This time I am 100% sure
the error says otherwise tho

could.... try awaiting it twice? thats a terrible solution but...
@Dough#2688 just download lavalink cli and start it thats your new node
they gone
i dont think so i just think uncached
or if they are using js
no theyre gone
kk
they could use https://npmjs.com/package/lavalink

Is that customized discord?
Wee wooo
wait fuck. i dont know what youre talking about.
LMAO
its not better discord
I don't really care tbh
I used to use better discord
but then I stopped
It got annoying
Wtf is this package
js it would seem
i will not be subjecting myself to the torture of looking at js
but in python
kthnx for coming to my ted talk
Lol
Yea
I know
Oh wait
I see what this is
I am stupid
xd
I am trying to recreate a js package in python
called random puppy
for the hell of it

await cursor.execute('''SELECT (?) FROM ? WHERE ?''', table, values, cond)
Just checking myself isn't this a valid sql query?
depends on the sql library you're using
but from most libraries i've seen, it should be 'QUERY' not '''QUERY'''
also check with that library if that is the correct way of using prepared statements
most of them dont let you use prepared statements for table names
I am using python sqlite3 package
and your variables are switched
pretty sure pythons built in sqlite3 package allows me to use prepared statements like that
and it is '''QUERY'''
# This is the qmark style:
cur.execute("insert into people values (?, ?)", (who, age))
# And this is the named style:
cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})
print cur.fetchone()```
this should be the correct way
yes, it should be cursor.execute('SELECT * FROM tablename WHERE field = ?''', (condition))
async def find_one(client, table, cond):
cursor = await client.db.cursor()
await cursor.execute('''SELECT * FROM ? WHERE ?''', (table, cond))
which isn't what I want
i mean, you can try, but from the js sqlite libraries ive used it doesnt work
you would have to hardcode the table name
Hm
I am pretty sure they don't
I have used js libraries and parameterized tablenames
and it worked
better-sqlite3 being one of
em*
Maybe not all of em do?
No, you can't do that, with SQLite or with most other SQL products. Parameter binding is for binding parameters, not replacing any old bit of the query that you fancy
you cannot pass table names as parameters in an sql query
but i mean, go ahead and try it
maybe it works in your library
@quartz kindle on python """text""" are multiline like on js `text
text2`
ah ok
await cursor.execute('''SELECT * FROM ? WHERE ?''', (table, cond))
File "C:\Users\SecretUsername\Desktop\PyStar\custommods\asqlite.py", line 122, in execute
return await self._post(self._cursor.execute, sql, parameters)
File "C:\Users\SecretUsername\Desktop\PyStar\custommods\asqlite.py", line 31, in _call_entry
result = entry.func(*entry.args, **entry.kwargs)
sqlite3.OperationalError: near "?": syntax error
Hm
Idk if that is the FROM ? or the WHERE ?
It's both
You need to tell SQL where to select values from and where to locate said values
await find_one(client, 'users', 'user_id=479603748382179329')
E.g SELECT * FROM {TABLE} would everything in the table
Yes
I know
But I am doing what you should do at least I am pretty sure I am
await find_one(client, 'users', 'user_id=479603748382179329')
2nd param table 3rd cond
You haven't got the ? In ()
Both
Yes ik I just checked my db
Ok
If it's SQL lite it needs
Select * from {table name} where {column name}=?
Atleast that's what's working on my system
just try """SELECT * FROM ? WHERE ?=?""", (x, y, z,)
Nope
Tim was right
you can't paramertize tablenames
I specified the tablename in the sql query and it worked
ah
hmm
if the table name is user defined
i might need to rethink a system myself
sleep bruh
SQL is exausting
idk how to concatenate in python, but theorically "SELECT * FROM " + tablename + " WHERE " + condition + " = ?"
but you need to validate/sanitize those variables
Hm
no string formatting for us 🙃
you could just use f strings cant you
yeah
👀
you cant use f string? why not?
isnt f string the same as ` in js?
string templating
theyre regarded as being the worst possible thing to use with SQL and python
as theyre the easiest todo with a SQL injection attack
How else would you do it
okay
yes, but there is no difference between f string and string concatenation security wise
or there is?
throwback to when someone found an sql injection in my bot, but my bot doesn't use sql 
just cleaner
you should still be able to use "?", (x,)
wesley wat
lmao
but basically F strings and .format are liable to SQL injection attacks but ? method doesnt
idk why
the easiest way to do it is to run it against a list of your valid tables
like if(variable exists in list of tables) continue
make it only run the query if the table name is an actual table name that exists
@modest maple Again what is the difference between concatenation and f strings, like tim said
how does it make it more vulnerable
i honestly cant tell you
@modest maple f stirngs and format have nothing to do with the ? method
the ? method is sqlite parameterization, everyone should use it always
but parameterization cant be used with table names
you can use ? in python as another method of string formatting
the rest of the sql query is made by strings and string manipulation
? in sql is not string formatting
or does it have other uses in non-sql python ?
it has non-sql uses
oh
if table == list of table names:
//do query
else:
return
it does the same job as f strings and .format
but for some reason
isnt liable to sql attacks
can you show an example?
i honestly have no idea why
of using ? for strings
hmm idk
i use f strings for everything execept sql cuz theyre just easier
i might be mistaken actually it might be an sql only thing
@quartz kindle
if table == list of table names:
//do query
else:
return
Mean like that?
you need in not ==
wait
i found this




