I'm making a discord.py bot and I'm currently on the economy part, but I'm encountering a strange error that I've never ran into before and has most of the python discord help dumbfounded. The error is as follows:
Command raised an exception: AttributeError: 'Result' has no attribute 'execute'
I'm having trouble understanding the meaning of this error due to the fact that I'm executing it on a cursor object, and not a result?
For those who need the code, here you go:
# Imports
import discord
from discord.ext import commands
from random import randrange
import asyncio
import time
import aiosqlite
# Def balance funcs
def getBal(ctx, user : discord.Member):
main = aiosqlite.connect('main.db')
cursor = main.cursor()
cursor.execute(f"SELECT balance FROM MainTable WHERE member_id = {user.id} AND guild_id = {ctx.guild.id}")
result = cursor.fetchone()
if result:
return
if not result:
sql = "INSERT INTO MainTable(balance, guild_id, member_id, warns) VALUES(?,?,?,?)"
val = (0, ctx.guild.id, user.id, 0)
cursor.execute(sql, val)
main.commit()
cursor.close()
main.close()
# Def main class
class Balance(commands.Cog):
#commands.command(aliases=['bal'])
async def balance(self, ctx, user : discord.Member = None):
if user == None:
user = ctx.author
getBal(ctx, user)
else:
getBal(ctx, user)
main = aiosqlite.connect('main.db')
cursor = main.cursor()
cursor.execute(f"SELECT balance FROM MainTable WHERE member_id = {user.id} AND guild_id = {ctx.guild.id}")
result = cursor.fetchone()
if result is not None:
if user is None:
embed = discord.Embed(title=f"**{ctx.author.mention}'s Balance**", description=f"**{ctx.author.mention}** has **{result[0]}** coins.", color=0xffffff)
await ctx.send(embed=embed)
else:
embed = discord.Embed(title=f"**{user.mention}'s Balance**", description=f"**{user.mention}** has **{result[0]}** coins.", color=0xffffff)
await ctx.send(embed=embed)
else:
await ctx.send("Critical Error! Please contact the developers.")
# Initialize
def setup(bot):
bot.add_cog(Balance(bot))
print('Balance is loaded')
You should read documentation for aiosqlite because it works different then standard sqlite3
You need
cursor = await main.execute(...)
EDIT:
It may also need to use await in every function. And add async before def
async def get_balance(ctx, user : discord.Member): # PEP8: readable names
main = await aiosqlite.connect('main.db')
cursor = await main.execute(f"SELECT balance FROM MainTable WHERE member_id = {user.id} AND guild_id = {ctx.guild.id}")
result = await cursor.fetchone()
if result:
return
# there is no need to check `not result`
sql = "INSERT INTO MainTable(balance, guild_id, member_id, warns) VALUES(?,?,?,?)"
val = (0, ctx.guild.id, user.id, 0)
cursor = await main.execute(sql, val)
await main.commit()
await cursor.close()
await main.close()
and later you have to run it also with await
await get_balance(ctx, user)
PEP 8 -- Style Guide for Python Code
Related
I have a aiosqlite Python database for a discord bot using Nextcord.
I have one table that works fine but the second one just wont update or maybe even create (I'm not sure). I'm wondering if it being in a class for a Nextcord cog is something to do with the issue.
I tried almost everything I could think of even using chatGPT. I Have no idea why its like this and don't use SQL DS's enough to know why. I have been trying to fix this for over 3 months so any help would be appreciated.
The code is here:
async def create_tables(self):
if self.db is not None:
await self.db.execute('CREATE TABLE IF NOT EXISTS econ (spin_tokens INTEGER, tokens INTEGER, slash_cmds INTEGER, status INTEGER, dank INTEGER, user INTEGER)')
await self.db.execute('CREATE TABLE IF NOT EXISTS daily (daily_claim INTEGER, daily_claimed_stamp INTEGER, daily_streak INTEGER, user INTEGER)')
async def commit(self):
await self.connect.commit()
#commands.Cog.listener()
async def on_ready(self):
self.bot.db = await aiosqlite.connect("econ.db")
await asyncio.sleep(3)
await self.create_tables()
await self.bot.db.commit()
print("DB ready...")
print("-----------")`
async def get_dval(self, user):
async with self.bot.db.cursor() as cursor:
await cursor.execute("SELECT daily_claim, daily_claimed_stamp, daily_streak FROM daily WHERE user = ?", (user.id,))
data = await cursor.fetchone()
print(data)
if data is None:
await self.daily_make(user)
return 0, 0, 1, 0
(daily_claim, daily_claimed_stamp, daily_streak) = data[0], data[1], data[2]
return daily_claim, daily_claimed_stamp, daily_streak
async def dclaimed_update(self, user, mode="daily_claim"):
now = datetime.now()
now_time = now.strftime("%H.%M")
print(now_time)
if self.db is not None:
await self.db.execute(f'''UPDATE daily SET daily_claim = now_time WHERE user = (user.id)''')
await self.db.commit()
#nextcord.slash_command(description="adds to bal")
async def daily(self, interaction : Interaction):
now = datetime.now()
now_time = now.strftime("%H.%M")
print(now_time)
daily_claim, daily_claimed_stamp, daily_streak = await self.get_dval(interaction.user)
if daily_claim == 0:
resK = await self.dclaimed_update(interaction.user)
daily_claim, daily_claimed_stamp, daily_streak = await self.get_dval(interaction.user)
await interaction.send("Sugg")
else:
await interaction.send("No")
import discord
import mysql.connector
client = discord.Client(intents=discord.Intents.all())
mylb = mysql.connector.connect(
host='localhost',[![enter image description here][1]][1]
user='root',
password="",
database="worst")
cursor = mylb.cursor()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
if message.content.startswith('$howareyou'):
await message.channel.send('fine')
a = 0
if message.content.startswith('$cash'):
cursor.execute("select cash from mudit")
b = cursor.fetchone()
await message.channel.send(b[0])
c = int(b[0])
if message.content.startswith('$daily'):
a = a+10
await message.channel.send(a)
sql = ("""UPDATE mudit SET cash = (%s) WHERE id = (1)"""%(c+10))
# sql = "insert into mudit (id,cash) values (%s,%s)"
cursor.execute(sql)
mylb.commit()
client.run('my token')
UnboundLocalError: cannot access local variable 'c' where it is not associated with a
value
In this code I want that my variable c should fetch the value in integer format and store it that is present in my database's cash column.I unpacked the list and converted that unpacked value in integer but still my variable c is not storing the value as a literal.
Here is how it could be done (note: using global variables like this is not really ideal, but this may at least get you going):
import discord
import mysql.connector
...
client =
mylb =
cursor =
c = None # Declare a global "c".
#client.event
async def on_ready():
...
#client.event
async def on_message(message):
...
if message.content.startswith('$cash'):
...
#
# Write to the global c.
#
global c
c = int(b[0])
if message.content.startswith('$daily'):
a = a+10
await message.channel.send(a)
#
# Check that c has previously been set.
#
assert c is not None
sql = ("""UPDATE mudit SET cash = (%s) WHERE id = (1)"""%(c+10))
# sql = "insert into mudit (id,cash) values (%s,%s)"
cursor.execute(sql)
mylb.commit()
This works because the global declaration of c is what is written when the $cash event happens, and that global c is used when event $daily happens. Of course, if your events arrive in an unexpected order, or you get duplicates, or you have multiple threads, etc etc, all kinds of problems can occur. But it should work.
class EconomyCog(commands.Cog, name="Help"):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def Money(self, ctx, member:discord.Member):
member = ctx.author
member_id = ctx.author.id
db = sqlite3.connect("main.sqlite")
cursor = db.cursor()
cursor.execute(f"SELECT member_id FROM main WHERE member_id = {member_id}")
result = cursor.fetchone()
if result is None:
sql = (f"INSERT INTO main(member_id, money) VALUES(?, ?)")
val = (member_id, 500)
cursor.execute(sql, val)
db.commit
await ctx.send("Because you didn't have an account, I just made one for you!")
db.close
cursor.close
elif result is not None:
db = sqlite3.connect("main.sqlite")
cursor = db.cursor()
cursor.execute(f"SELECT * FROM main WHERE member_id = {member_id}")
result = cursor.fetchone()
embed = discord.Embed(title = f"{member}'s Money", description = f"{result[1]} <:BitCoin:929595745500274689>", color = discord.Colour.random)
await ctx.send(embed=embed)
I don't get any errors but also when the command is triggered nothing happens. You have any clue to why it won't work?
These lines do nothing. They don't call functions, they just mention the function objects:
db.commit
...
db.close
cursor.close
It's exactly like writing:
7
It is syntactically legal, but does nothing.
To call them, you MUST use parens. Also note that you don't need to refetch the member record in the else; you can have that first query serve both purposes:
async def Money(self, ctx, member:discord.Member):
member = ctx.author
member_id = ctx.author.id
db = sqlite3.connect("main.sqlite")
cursor = db.cursor()
cursor.execute(f"SELECT * FROM main WHERE member_id = ?", (member_id,))
result = cursor.fetchone()
if result is None:
sql = (f"INSERT INTO main(member_id, money) VALUES(?, ?)")
val = (member_id, 500)
cursor.execute(sql, val)
db.commit()
await ctx.send("Because you didn't have an account, I just made one for you!")
else:
embed = discord.Embed(title = f"{member}'s Money", description = f"{result[1]} <:BitCoin:929595745500274689>", color = discord.Colour.random)
await ctx.send(embed=embed)
cursor.close()
db.close()
I need to get an emoji as an emoji object for reaction roles but i whatever i do i ether get the error
discord.ext.commands.errors.PartialEmojiConversionFailure: Couldn't convert " " to PartialEmoji.
if i am using discord.PartialEmoji or
discord.ext.commands.errors.EmojiNotFound: Emoji " " not found.
if i am using discord.Eomji.
Example Code where these errors happen
#commands.command()
async def test(self,ctx,emoji: discord.Emoji = None):
await ctx.send(emoji)
Edit:
At first the reaction role should be created like this:
#commands.command()
async def reactionrole(self,ctx,msgid: int = None,emoji: discord.Emoji = None , role: discord.Role = None ):
if msgid is None:
await ctx.send('Use the following template to create reactionroles (ex. treactionrole <#messageid> <emoji> <#role>)')
elif emoji is None:
await ctx.send('Use the following template to create reactionroles (ex. treactionrole <#messageid> <emoji> <#role>)')
elif role is None:
await ctx.send('Use the following template to create reactionroles (ex. treactionrole <#messageid> <emoji> <#role>)')
else:
if ctx.message.author.guild_permissions.manage_roles:
db = sqlite3.connect("db.sqlite")
cursor = db.cursor()
sql = ("INSERT INTO reaction_role(message_id,emoji,role) VALUES(?,?,?)")
val = (msgid,emoji,str(role))
msg = await ctx.channel.fetch_message(int(msgid))
await msg.add_reaction(emoji)
cursor.execute(sql,val)
db.commit()
cursor.close()
db.close()
else:
await ctx.author.send('You dont have the permission to use reactionroles on this Server!')
Then if an reaction happens an method should get the message out of the db where the msgid and the emoji is the same as the reacted one like this:
async def reaction_roles_role(msgid,emoji):
db = sqlite3.connect("db.sqlite")
cursor = db.cursor()
cursor.execute(f"SELECT role FROM reaction_role WHERE message_id = {msgid} and emoji = {emoji}")
result = cursor.fetchone()
return result
Are you using default emojis for this or Emojis from other servers? Because discord.Emoji only works with custom Emojis from servers with your bot on it.
If you wanna get all of these you have to do something like this:
#commands.command()
async def test(self, ctx, emoji):
print(str(emoji))
And for reaction roles you could compare in on_raw_reaction_add like this:
if str(payload.emoji) == str(your_emoji_here):
I made an on_message event that gives you role whenever you mention 3 people in a specific channel , Now I am trying to integrate it with database so it can be used on multiple guilds.
What I've write:
class ScrimsCog(commands.Cog, name='Scrims-Commands') :
def __init__(self,bot):
self.bot = bot
#commands.Cog.listener()
async def on_message(self,message):
db = sqlite3.connect('main.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {message.guild.id}")
result = cursor.fetchone()
if result is None:
return
else:
cursor.execute(f"SELECT role FROM main WHERE guild_id = {message.guild.id}")
if not channel.id == channel_id:
return
if len(message.mentions) >= 3:
await message.add_reaction(emoji="<a:tick:748476262640779276>")
role = discord.utils.get(message.guild.roles, name=role)
user = message.author
await user.add_roles(role)
await self.bot.process_commands(message)
#commands.group(invoke_without_command=True)
async def scrimsmod(self,ctx):
await ctx.send('Available Setup Commands: \nscrimsmod channel <#channel>\nscrimsmod role <message>')
#scrimsmod.command()
async def channel(self, ctx, channel:discord.TextChannel):
if ctx.message.author.guild_permissions.manage_messages:
db = sqlite3.connect('main.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {ctx.guild.id}")
result = cursor.fetchone()
if result is None:
sql = ("INSERT INTO main(guild_id, channel_id) VALUES(?,?)")
val = (ctx.guild.id, channel.id)
await ctx.send(f" Default Registration Channel has been set to {channel.mention}")
elif result is not None:
sql = ("UPDATE main SET channel_id = ? WHERE guild_id = ?")
val = (channel.id, ctx.guild.id)
await ctx.send(f"Default Registration Channel has been updated to {channel.mention}")
cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()
#scrimsmod.command()
async def role(self, ctx,role: discord.Role):
if ctx.message.author.guild_permissions.manage_messages:
db = sqlite3.connect('main.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT role FROM main WHERE guild_id = {ctx.guild.id}")
result = cursor.fetchone()
if result is None:
sql = ("INSERT INTO main(guild_id, role) VALUES(?,?)")
val = (ctx.guild.id, role)
await ctx.send(f"Default role to give on correct registration have been set to `{role}`")
elif result is not None:
sql = ("UPDATE main SET role = ? WHERE guild_id = ?")
val = (role, ctx.guild.id)
await ctx.send(f"Default role to give on correct registration have been updated to `{role}`")
cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()
def setup(bot):
bot.add_cog(ScrimsCog(bot))
print("Scrims cog is loaded!")
From now I think the problem is with on_message part, the channel.id , channel-id, role are undefined but even if I define them it still doesn't work.
f-string maybe causing problems, try this..
cursor.execute("SELECT channel_id FROM main WHERE guild_id = ?", [message.guild.id])
At first, if you connect to the database under the on_message event, this this reduces the efficiency of your bot. And for the other problems, you have to change the commands parameters like these
async def channel(self, ctx, channel):, async def role(self, ctx,role):
instead of these role: discord.Role channel: discord.TextChannel.
Then, when you want to call the channel or the role, you must use discord.utils.get,
for channels:
await ctx.send(f"Default Registration Channel has been updated to {discord.utils.get(ctx.guild.text_channels, name=channel).mention}")
for roles:
await ctx.send(f"Default role to give on correct registration have been updated to {discord.utils.get(ctx.guild.roles, name=role)}")
So when the users using the role or channel commands, they must write the exact channel.
And when you comparing the channel id with the database, you can also use discord.utils.get like this:
channel_in_database = discord.utils.get(ctx.guild.text_channels, name="in here, you need to connect to the database and take the channel name for this guild.")
then, if not channel_in_database.id == ctx.channel.id:, or maybe you can(I'm not 100% sure that will work) take the channel name from database for that guild and do:
if "channel name from the database" == ctx.channel.name
If one of these raises any problem or if you still have unanswered problems, just comment