Ignoring exception in command warnings:
Traceback (most recent call last):
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 181, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\\OneDrive\Documents\Bata-Bot\cogs\Testing.py", line 51, in warnings
async with self.Client.db.cursor() as cursor:
AttributeError: 'tuple' object has no attribute 'db'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 360, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 927, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'tuple' object has no attribute 'db'
#Trouble with aiosqlite commands in a cog
1 messages · Page 1 of 1 (latest)
from unicodedata import name
import contextlib
from ast import alias
from pydoc import pager
import discord
from traceback import format_exception
from discord.ext import commands
from datetime import datetime
import sqlite3
import platform
import sys
import random
import textwrap
import io
import aiosqlite
ids = [472791039258918913]
def members(bot: commands.Bot):
memc = 0
for guild in bot.guilds:
memc += guild._member_count
return memc
class Testing(commands.Cog):
def __init__(self, Client : commands.Bot):
self.Client : commands.Bot = Client,
# Events
@commands.Cog.listener()
async def on_ready(self):
print('Warn cog has loaded')
@commands.command()
@commands.has_permissions(manage_guild=True)
async def warnings(self, ctx: commands.Context, member: discord.Member):
async with self.Client.db.cursor() as cursor:
await cursor.execute("SELECT reason, time, WarnID FROM warns WHERE user_id = ? AND guild_id = ?", (member.id, ctx.guild.id,))
things = await cursor.fetchall()
if things:
embed = discord.Embed(title=f"{member.name}'s warnings", color=discord.Color.red())
warnum = 0
for table in things:
warnum += 1
embed.add_field(name=f"warning {warnum}", value=f"Reason: {table[0]}\nTime issued: <t:{(table[1])}:F>\nID: {(table[2])}")
await ctx.send(embed=embed)
else:
await ctx.send("This user has no warnings")
await self.Client.db.commit()
There is the code.
And yes I. Do have And I do have setattr(Client, 'db', await aiosqlite.connect('database2.db')) In the main file before you ask
The error pops up when I run the command and I can’t seem to find something that would make that error happen.
And the code that I have right now at work for others soo.
Ping me if you know a fix.
Trouble with aiosqlite commands in a cog
@warm burrow first of all you should keep your variable names consistent, I don't see a reason to call your bot instance Client with a capital C, that's only going to cause confusion in the future.
Also, I think you should create your own db handler that creates connections to your SQLite database as-needed instead of keeping one persistent connection as an attribute of your bot.
I'd recommend your DB handler to be a class that you import anywhere you need it.
Here's an example of how a start of it could look:
# db_handler.py
class MyDbHandler():
def __init__(self):
self.connection = aiosqlite.connect('mydatabase')
async def execute_query(self, sql_str, sql_params):
# Execute your query here
And then wherever you want to use it you just do
from db_handler import MyDbHandler
...
handler = MyDbHandler()
await handler.execute(...
Yes but when I do that it will say there was no connection made.
As I did not await it.
As I tryed that once.
attach this db handler object to the bot in the main file or at startup
then do self.bot.db_handler.execute_query(...) (or self.client)
@warm burrow ^
Yes but wouldn’t that on run of a db command like warnings in this case have a error of no connection was made?
make the connection on startup in the main.py file
aiosqlite.connect is a corutine
Wait does that mean that there way will not work?
you might need to do
# db_handler.py
class MyDbHandler():
def __init__(self):
self.connection: aiosqlite.Connection # for typehinting purposes
async def execute_query(self, sql_str, sql_params):
# Execute your query here
async def connect(self):
self.connection = await aiosqlite.connect('mydatabase')
# main.py
bot.db_handler = MyDbHandler()
#in the on_ready event
await bot.db_handler.connect()
What do you mean by execute your query here what kind of things would I need to put there though?
And wouldn't the on ready thing in the main make a sintax error since the connect does not have the parameter and also wouldn't the db lock as then there would be two connections happening making it lock up?
?
gnoring exception in command warnings:
Traceback (most recent call last):
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 181, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\\OneDrive\Documents\Bata-Bot\cogs\Testing.py", line 51, in warnings
async with handler.cursor() as cursor:
AttributeError: type object 'MyDbHandler' has no attribute 'cursor'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 360, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 927, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'MyDbHandler' has no attribute 'cursor'
``` with yours it pops up this error.
Yours does this ```py
Ignoring exception in command warnings:
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 181, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\OneDrive\Documents\Bata-Bot\cogs\Testing.py", line 51, in warnings
async with handler.cursor() as cursor:
AttributeError: type object 'MyDbHandler' has no attribute 'cursor'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 360, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 927, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'MyDbHandler' has no attribute 'cursor'
import aiosqlite
class MyDbHandler():
def __init__(self):
self.connection: aiosqlite.Connection # for typehinting purposes
async def connect(self):
self.connection = await aiosqlite.connect('database2.db')
That was for your db handler in the file code I have.
Your code for the db handler for me was like this ```py
import aiosqlite
class MyDbHandler():
def init(self):
self.connection = aiosqlite.connect('mydatabase')
from unicodedata import name
import contextlib
from ast import alias
from pydoc import pager
import discord
from traceback import format_exception
from discord.ext import commands
from datetime import datetime
import sqlite3
import platform
import sys
import random
import textwrap
import io
import aiosqlite
from Setup.db_handler import MyDbHandler
handler = MyDbHandler
ids = [472791039258918913]
def members(bot: commands.Bot):
memc = 0
for guild in bot.guilds:
memc += guild._member_count
return memc
class Testing(commands.Cog):
def __init__(self, Client : commands.Bot):
self.Client : commands.Bot = Client,
# Events
@commands.Cog.listener()
async def on_ready(self):
print('Warn cog has loaded')
@commands.command()
@commands.has_permissions(manage_guild=True)
async def warnings(self, ctx: commands.Context, member: discord.Member):
async with handler.cursor() as cursor:
await cursor.execute("SELECT reason, time, WarnID FROM warns WHERE user_id = ? AND guild_id = ?", (member.id, ctx.guild.id,))
things = await cursor.fetchall()
if things:
embed = discord.Embed(title=f"{member.name}'s warnings", color=discord.Color.red())
warnum = 0
for table in things:
warnum += 1
embed.add_field(name=f"warning {warnum}", value=f"Reason: {table[0]}\nTime issued: <t:{(table[1])}:F>\nID: {(table[2])}")
await ctx.send(embed=embed)
else:
await ctx.send("This user has no warnings")
await self.Client.db.commit()
``` That was the code useing spaxters handler setup.
I tryed the same way with Om yours and it still errored the same way.
Anyone else have a fix as those fixes did not work?
Ping me if you know of find one.
Anything?
?
In that case just ignore the init function and do
# db_handler.py
class MyDbHandler():
async def execute_query(self, sql_str, sql_params):
connection = await aiosqlite.connect('mydatabase')
# Execute your query here
# Close the connection
Or to avoid having to manually close the connection
async def execute_query(self, sql_str, sql_params):
async with aiosqlite.connect('mydatabase') as connection:
# Execute your query here
In the execute query function, you pass in the sql query as string, and the parameters
Then inside the function you do
async with self.connection.cursor() as cursor:
await cursor.execure(sql_query, params) # the ones you accepted for in the function arguments
return await cursor.fetchall()
You can have separate functions for insert and select queries
You are doing it wrong. You execute the query in the execute query function. Not in the cog
It's not a good idea to open a connection everytime
I just want to be able to import it and have the bot work where I do self.Client.db and then the regular aiosqlite commands.
Without it erroring.
@mental adder Is there a way to do that?
The way that they are saying it is just confusing.
Well, first of all you should rename it from self.Client to self.client to reduce confusion
also show how you initialize your client in the first place
Like in the main file?
yes
@Client.event
async def on_ready():
print('Bot is ready.')
await Client.change_presence(activity=discord.Game(name="Playing someing"))
setattr(Client, 'db', await aiosqlite.connect('database2.db'))
await asyncio.sleep(3)
That is my on ready thing to initialize it for my main file, but I want to move them over to cogs.
but the set attribute does not work in cogs
Instead of using setattr, just do
Client.db = await aiosqlite.connect('database2.db')
Do I put that in the on ready in the cog or just a var?
Well, generally you shouldn't do anything in on_ready, but for now try doing it there
Forgot there was a self I had to add there so it errored for a second.
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "C:\Users\\OneDrive\Documents\Bata-Bot\cogs\Testing.py", line 45, in on_ready
self.Client.db = await aiosqlite.connect('database2.db')
AttributeError: 'tuple' object has no attribute 'db'
Pops up that error.
@commands.Cog.listener()
async def on_ready(self):
self.Client.db = await aiosqlite.connect('database2.db')
print('Warn cog has loaded')
@commands.command()
@commands.has_permissions(manage_guild=True)
async def warnings(self, ctx: commands.Context, member: discord.Member):
async with self.Client.db.cursor() as cursor:
await cursor.execute("SELECT reason, time, WarnID FROM warns WHERE user_id = ? AND guild_id = ?", (member.id, ctx.guild.id,))
things = await cursor.fetchall()
if things:
embed = discord.Embed(title=f"{member.name}'s warnings", color=discord.Color.red())
warnum = 0
for table in things:
warnum += 1
embed.add_field(name=f"warning {warnum}", value=f"Reason: {table[0]}\nTime issued: <t:{(table[1])}:F>\nID: {(table[2])}")
await ctx.send(embed=embed)
else:
await ctx.send("This user has no warnings")
await self.Client.db.commit()
That is the code right now.
Then how would it work in the cog then?
Would I have that as a global var?
As the erroring is happening in the cog.
If you set an attribute on your main file you can still use that attribute in other classes since you pass objects by reference
you shouldn't define multiple of the same event listener anyways, so just stick to on_ready in your main file
Ignoring exception in command warnings:
Traceback (most recent call last):
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 181, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\\OneDrive\Documents\Bata-Bot\cogs\Testing.py", line 51, in warnings
async with self.Client.db.cursor() as cursor:
AttributeError: 'tuple' object has no attribute 'db'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 360, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 927, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'tuple' object has no attribute 'db'
Still erroring with the set attribute on my main file.
can you print type(self.Client)
Ok that prints <class 'tuple'> in the term.
This is in the cog.
As self is not defined in the main.
So somehow your client reference has turned into a tuple
could you please rename it to client. It doesn't make sense with a capital C
like here? Client = commands.Bot(command_prefix=";", intents=discord.Intents.all())
Change that to lowecase?
Yes, and any other place where you reference that
Oh so baseicly all my files.
OK so I changed everything but now it’s saying that the capital client won’t work in the one cog.
And that was painful changing all the things.
What do you mean? The capital client?
Like how I had it before on the bot.
This.
When you told me to put this in.
Well yeah, you changed it didn't you?
All the bot ones to lower case clients yes.
So Client no longer points to Bot.
Now client does.
Yeah, so what's wrong with using self.client now?
It still prints <class 'tuple'>.
How are you loading your cogs?
@client.command()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
@client.command()
async def unload(ctx, extension):
client.unload_extension(f'cogs.{extension}')
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
That is in the main.
class Owner(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name='eval')
async def _eval(self, ctx, *, code: codeblock_converter):
"""Eval some code"""
cog = self.bot.get_cog("Jishaku")
await cog.jsk_python(ctx, argument=code)
def setup(bot):
bot.add_cog(Owner(bot))
That is in a cog.
But where it says bot it is client.
So that is how there loaded.
I mean I don't think that would make it not work with it being loaded that way.
No, it shouldn't. It's just very weird how your self.client is an instance of a tuple. It doesn't make sense
I know right.
Should I ping Bob in here and see if they know?
I'd wait for someone else to see this, I unfortunately can't help you any further.
i think somewhere in all your cogs you are accidentally setting self.client = (some, tuple)
print(self.client)
and see what it says
@warm burrow ^
@mental adder @tacit linden Ok is this right now?
It prints <class 'discord.ext.commands.bot.Bot'>.
But now it says Bot has no attribute db.
Even tho it does in the main file.
@warm burrow Hey! I use this library for my bot, so I can try to help you. Send the error you get, your main file, and the incriminated cog. Ping me when you do.
Ok.
One second.
@celest urchin Sorry it took so long for a response just saw this.
Here is the error ```py
Ignoring exception in command warnings:
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 181, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\OneDrive\Documents\Bata-Bot\cogs\Testing.py", line 49, in warnings
async with self.client.db.cursor() as cursor:
AttributeError: 'Bot' object has no attribute 'db'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 360, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 927, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'db'
Cog: ```py
from ast import Delete, alias
import asyncio
import random, string
import discord
import sqlite3
import os
from datetime import datetime
from discord.ext import commands, bridge
from discord.ext import pages
import asyncio
import aiosqlite
from easy_pil import *
from Setup.buttons import ShopView
from Setup.db_handler import MyDbHandler
client = commands.Bot(command_prefix=";", intents=discord.Intents.all())
client.remove_command('help')
client.launch_time = datetime.now()
client.load_extension('jishaku')
@client.event
async def on_ready():
print('Bot is ready.')
await client.change_presence(activity=discord.Game(name="Playing someing"))
setattr(client, 'db', await aiosqlite.connect('database2.db'))
await asyncio.sleep(3)
async with client.db.cursor() as cursor:
await cursor.execute('''CREATE TABLE IF NOT EXISTS levelsettings(levelsys INTEGER, role INTEGER, levelreq INTEGER, guild INTEGER)''')
await cursor.execute('''CREATE TABLE IF NOT EXISTS warns(user_id INTEGER, guild_id INTEGER, reason TEXT, time INTEGER, WarnID INTEGER )''')
await cursor.execute('''CREATE TABLE IF NOT EXISTS level(level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)''')
await cursor.execute('''CREATE TABLE IF NOT EXISTS afk (user INTEGER, guild INTEGER, reason TEXT)''')
await cursor.execute("CREATE TABLE IF NOT EXISTS bank (wallet INTEGER, bank INTEGER, maxbank INTEGER, user INTEGER)")
await cursor.execute("CREATE TABLE IF NOT EXISTS inv (laptop INTEGER, phone INTEGER, fakeid INTEGER, user INTEGER)")
await cursor.execute("CREATE TABLE IF NOT EXISTS shop (name TEXT, id TEXT, desc TEXT, cost INTEGER)")
Main down to the on ready.
@celest urchin There you go there is all the info
Ok that's what we need
And for those that were here before this is the new code after the fix for the print(self.client).
Just so that way it helps with any fixes.
Why are you redefining client in your cog?
That will break everything
Because in this message I am sending now it will explain why.
@commands.command()
async def serverinfo(self, ctx : commands.Context):
embed5 = discord.Embed(title="Server Information", color=discord.Colour.green())
embed5.add_field(name="Server name:", value=ctx.message.guild.name)
embed5.add_field(name="Roles:", value=len(ctx.message.guild.roles))
embed5.add_field(name="Members:", value=len(ctx.message.guild.members))
embed5.add_field(name="Channels:", value= len(ctx.message.guild.channels))
embed5.add_field(name="Created at:", value=ctx.message.guild.created_at.strftime('%a, %#d %B %Y, %I:%M %p'))
embed5.set_footer(text=f' Called by {ctx.author.name} | Hyper Tech Bots')
embed5.timestamp = datetime.now()
await ctx.send(embed=embed5)
def setup(client):
client.add_cog(Testing(client))
That is why as then the cog will not load and the bot will crash.
Like Om said, you should never define a client instance more than once, ever. There is never a reason to do so
it's only going to cause issues
Then how would I use my bot var to add the cog then?
You're already passing client to your setup function, which is automatically done when you load your cogs in your main file
Ok so now without that it sends this error ```py
Ignoring exception in command warnings:
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 181, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\OneDrive\Documents\Bata-Bot\cogs\Testing.py", line 48, in warnings
async with self.client.db.cursor() as cursor:
AttributeError: 'Testing' object has no attribute 'client'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 360, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 927, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Testing' object has no attribute 'client'
That is with this code and without the client line.
Oh so if I change where it says bot to client it will not send that error?
Try it and see
I'd advise to to stick to consistent variable naming in the future, it will only cause confusion if it's called self.bot sometimes, self.client sometimes, self.Client sometimes etc. Just pick one name and use that everywhere