#Trouble with aiosqlite commands in a cog

1 messages · Page 1 of 1 (latest)

warm burrow
#
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'
#
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

mental adder
#

@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.

mental adder
#

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(...
warm burrow
#

As I did not await it.

#

As I tryed that once.

warm burrow
#

So how would I do that then @mental adder

#

Any ways to solve that?

tacit linden
#

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 ^

warm burrow
tacit linden
tacit linden
warm burrow
tacit linden
# warm burrow 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()
warm burrow
warm burrow
warm burrow
#

?

warm burrow
# mental adder I'd recommend your DB handler to be a class that you import anywhere you need it...
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.
warm burrow
# tacit linden you might need to do ```py # db_handler.py class MyDbHandler(): def __init__...

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.

warm burrow
#
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.

warm burrow
#

Anything?

warm burrow
#

?

mental adder
#

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
tacit linden
tacit linden
tacit linden
warm burrow
#

Without it erroring.

#

@mental adder Is there a way to do that?

#

The way that they are saying it is just confusing.

mental adder
#

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

warm burrow
mental adder
#

yes

warm burrow
#

@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

mental adder
#

Instead of using setattr, just do

Client.db = await aiosqlite.connect('database2.db')
warm burrow
#

Do I put that in the on ready in the cog or just a var?

mental adder
#

Well, generally you shouldn't do anything in on_ready, but for now try doing it there

warm burrow
warm burrow
# mental adder Well, generally you shouldn't do anything in `on_ready`, but for now try doing i...
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.

mental adder
#

Why are you doing it in a cog?

#

Just do it in your main file

warm burrow
#

Would I have that as a global var?

#

As the erroring is happening in the cog.

mental adder
#

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

warm burrow
#
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.

mental adder
#

can you print type(self.Client)

warm burrow
#

This is in the cog.

#

As self is not defined in the main.

mental adder
#

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

warm burrow
#

Change that to lowecase?

mental adder
#

Yes, and any other place where you reference that

warm burrow
#

Oh so baseicly all my files.

warm burrow
#

And that was painful changing all the things.

mental adder
#

What do you mean? The capital client?

warm burrow
#

Like how I had it before on the bot.

warm burrow
mental adder
#

Well yeah, you changed it didn't you?

warm burrow
#

So Client no longer points to Bot.

#

Now client does.

mental adder
#

Yeah, so what's wrong with using self.client now?

warm burrow
mental adder
#

How are you loading your cogs?

warm burrow
#
@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.

warm burrow
mental adder
#

No, it shouldn't. It's just very weird how your self.client is an instance of a tuple. It doesn't make sense

warm burrow
#

I know right.

warm burrow
mental adder
#

I'd wait for someone else to see this, I unfortunately can't help you any further.

tacit linden
#

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 ^

signal trailBOT
#

Here's the slash options example.

#

Here's the slash cog example.

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.

warm burrow
#

Even tho it does in the main file.

celest urchin
#

@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.

warm burrow
#

One second.

#

@celest urchin Sorry it took so long for a response just saw this.

warm burrow
# celest urchin <@472791039258918913> Hey! I use this library for my bot, so I can try to help y...

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'

#
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

tacit linden
warm burrow
#

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.

tacit linden
#

That will break everything

warm burrow
#

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))
warm burrow
mental adder
#

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

warm burrow
mental adder
#

You're already passing client to your setup function, which is automatically done when you load your cogs in your main file

warm burrow
# mental adder You're already passing `client` to your setup function, which is automatically d...

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'

warm burrow
mental adder
#

Because you called it self.bot in that file

#

not self.client

warm burrow
mental adder
#

Try it and see

warm burrow
#

OMG THANK YOU SO MUCH!

mental adder
#

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