This is my table
#client.event
async def on_ready():
db = sqlite3.connect('Smilewin.sqlite')
cursor = db.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS Introduce(
guild_id TEXT,
channel_id TEXT,
boarder TEXT,
status TEXT
)
''')
I wanted to store anything from a normal text to something like this ☆゚ ゜゚☆゚ ゜゚☆゚ ゜゚☆゚ ゜゚☆゚ ゜゚☆
(basically anything)
When I try to store ☆゚ ゜゚☆゚ ゜゚☆゚ ゜゚☆゚ ゜゚☆゚ ゜゚☆ It is giving an error.
Traceback (most recent call last):
File "C:\Users\ardil\Desktop\Desktop app\ANAPAH\Code\ReactV9\Smilewin-env\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\ardil\Desktop\Desktop app\ANAPAH\Code\ReactV9\SmileWinbot.py", line 618, in on_command_error
raise error
File "C:\Users\ardil\Desktop\Desktop app\ANAPAH\Code\ReactV9\Smilewin-env\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\ardil\Desktop\Desktop app\ANAPAH\Code\ReactV9\Smilewin-env\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\ardil\Desktop\Desktop app\ANAPAH\Code\ReactV9\Smilewin-env\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'text'
The code which I use to store that special symbols is:
#client.command()
#commands.has_permissions(administrator=True)
async def setboarder(ctx, *,boarder):
db = sqlite3.connect('Smilewin.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT boarder FROM Introduce WHERE guild_id = {ctx.guild.id}")
result = cursor.fetchone
if result is None:
sql = ("INSERT INTO Introduce(guild_id, boarder) VALUES(?,?)")
val = (ctx.guild.id , boarder)
embed = discord.Embed(
colour= 0x00FFFF,
title = "ตั้งค่ากรอบเเนะนําตัว",
description= f"กรอบได้ถูกตั้งเป็น {boarder}"
)
message = await ctx.send(embed=embed)
await message.add_reaction('✅')
elif result is not None:
sql = ("UPDATE Introduce boarder = ? WHERE guild_id = ?")
val = (boarder , ctx.guild.id)
embed = discord.Embed(
colour= 0x00FFFF,
title = "ตั้งค่ากรอบเเนะนําตัว",
description= f"กรอบได้ถูกอัพเดตเป็น {boarder}"
)
message = await ctx.send(embed=embed)
await message.add_reaction('✅')
cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()
I want to know is it possible to store that kind of data in sqlite. If yes how can I do it please provide some example. thank you so much
There is an error in your update query which may or may not have some bearing on the problem.
"UPDATE Introduce boarder = ? WHERE guild_id = ?"
is missing the keyword SET. The statement should be:
"UPDATE Introduce SET boarder = ? WHERE guild_id = ?"
I don't see how the exception traceback relates to this problem. It also seems unrelated to whether the db can store your unicode strings; it can.
Try fixing this bug and see how you go.
Related
basically im trying to make a discord card collection bot, so i have this one command where it goes in database and pick 3 random cards to drop but it give me this error :
``
File "d:\rococo-2.0\core.py", line 440, in dropcard
cardNames = await query(f"SELECT cardname FROM Cards WHERE filename = '{cardsToDrop[0]}' OR filename = '{cardsToDrop[1]}' OR filename = '{cardsToDrop[2]}'", cardDBCommand) #get the names of the cards to drop
~~~~~~~~~~~^^^
IndexError: list index out of range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "d:\rococo-2.0\ven\Lib\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "d:\rococo-2.0\ven\Lib\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "d:\rococo-2.0\ven\Lib\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
here is the drop command block:
#bot.command(aliases = ["D", "d", "drop"])
async def dropcard(ctx):
dropTimeStr = datetime.now().strftime("%H:%M:%S")
userList = await query("SELECT userid FROM Users", userDBCommand)
lastDrop = datetime.strptime("00:00:00", "%H:%M:%S")
message = str()
if userList == None:
await query(f"INSERT INTO Users (userid, username, lastdrop) VALUES ({ctx.author.id}, '{ctx.author.name}', '{dropTimeStr}')", userDBCommand, ctx)
elif str(ctx.author.id) not in userList:
await query(f"INSERT INTO Users (userid, username, lastdrop) VALUES ({ctx.author.id}, '{ctx.author.name}', '{dropTimeStr}')", userDBCommand, ctx)
elif str(ctx.author.id) in userList and await query(f"SELECT lastdrop FROM Users WHERE userid = {ctx.author.id}", userDBCommand, ctx) == None:
await query(f"UPDATE Users SET lastgrab = '{dropTimeStr}' WHERE userid = {ctx.author.id}", userDBCommand, ctx)
elif str(ctx.author.id) in userList and str(ctx.author.id) != botAdminId:
lastDrop = datetime.strptime(await query(f"SELECT lastdrop FROM Users WHERE userid = {ctx.author.id}", userDBCommand, ctx), "%H:%M:%S")
if (datetime.strptime(dropTimeStr, "%H:%M:%S") - lastDrop).seconds < 300 and str(ctx.author.id) != botAdminId:
await ctx.send(ctx.author.mention + ", you can drop a card only every 5 minutes.", delete_after = 60)
return
else:
await query(f"UPDATE Users SET lastdrop = '{dropTimeStr}' WHERE userid = {ctx.author.id}", userDBCommand) #update last drop time
cardPathList = await query("SELECT filename FROM Cards ORDER BY cardname", cardDBCommand) #get all cards
cardRarity = await query("SELECT rarity FROM Cards ORDER BY cardname", cardDBCommand) #list of rarities
while True:
cardsToDrop = random.choices(cardPathList, cardRarity) #k = 3
if set(cardsToDrop).__len__() == cardsToDrop.__len__(): break #if there are no duplicates, break the loop
cardNames = await query(f"SELECT cardname FROM Cards WHERE filename = '{cardsToDrop[0]}' OR filename = '{cardsToDrop[1]}' OR filename = '{cardsToDrop[2]}'", cardDBCommand) #get the names of the cards to drop
imageCreation(cardsToDrop, GREY, os.path.abspath("Temp/drop.png")) #create the image
``
Can someone help me with that error ?
tell me if needed more info about my code, new to stackoverflow
I tried to change the name of the files, even changing the name of files in the sql request but its still showing me the same error
You are trying to access an index which doesn't exist, make sure you have three elements exist in cardsToDrop list object otherwise, it'll throw IndexOutOfRange for sure.
The following is the code that has to do with the balance, as u might notice that there are various currencies and for that I have done add_field quite a few times, it would be really nice if you could tell me if there is a way to do it in a shorter and/or easier way...anyways coming to the main problem.
Main.py
async def equilibrium(user: discord.Member):
db = await aiosqlite.connect("balance_db.db")
cursor = await db.cursor()
await cursor.execute(f"SELECT * FROM bal WHERE user_id = {user.id} ")
result = await cursour.fetchall()
print (result)
if result:
return
if not result:
await cursor.execute(f"INSERT INTO bal(user_id, cash, crystals, event_pearls, weapon_shards, fusion_earring, merging_stones, enhancing_stones) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (user.id, 500, 0, 0, 0, 0, 0, 0, 0))
await db.commit()
await cursor.close()
await db.close()
#bot.command(aliases=['bal'])
async def balance(ctx, user:discord.Member=None):
if user is None:
user = ctx.author
await equilibrium(user=user)
db = await aiosqlite.connect("balance_db.db")
cursor = await db.cursor()
await cursor.execute(f"SELECT * FROM bal WHERE user_id = {user.id} ")
balem = discord.Embed(title=f"**{user.mention}'s balance**", color=discord.Color.blue())
balem.add_field(name="Cash:", value=f":GenesisCrystal: {result[1]}", inline=True)
balem.add_field(name="crystals:", value=f":GenesisCrystal: {result[2]}", inline=True)
balem.add_field(name="event pearls:", value=f":GenesisCrystal: {result[3]}", inline=True)
balem.add_field(name="weapon shards:", value=f":GenesisCrystal: {result[4]}", inline=True)
balem.add_field(name="fusion earring:", value=f":GenesisCrystal: {result[5]}", inline=True)
balem.add_field(name="merging stones:", value=f":GenesisCrystal: {result[6]}", inline=True)
balem.add_field(name="enhancing stones:", value=f":GenesisCrystal: {result[7]}", inline=True)
await ctx.send(embed=balem)
upon testing and doing '(serverprefix) bal' it gives the following error:
INFO discord.client logging in using static token
2022-09-12 23:45:43 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 7338538a9635f5cf39dba129dc8621fa).
[]
2022-09-12 23:45:44 ERROR discord.ext.commands.bot Ignoring exception in command balance
Traceback (most recent call last):
File "C:\Users\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Desktop\CodingPAIN.py", line 50, in balance
balem.add_field(name="Cash:", value=f":GenesisCrystal: {result[1]}", inline=True)
IndexError: list index out of range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
The Bot is Online
I am using the following:
python version 9.3x (9.3.13 precisely)
aiosqlite as the database (i know about the mordern aiosqlite method of writing the code, but I am much more familiar with the old, or the sqlite3 method
I am just a beginner, help of any kind would be appriciated
Looks like you need to change result = await cursor.fetchall() to result = await cursour.fetchall()[0].
Sqlite's fetchall() returns a list of tuples (something like [(1,), (2,)], so you need to index to the first tuple, then loop through that.
So, I was making a discord bot for an RP server with 4k members in emergency.
My goal was to store the lawyers database in a json file that would be hosted on one of my computers for testing. Here is my code:
import discord
import datetime
from typing_extensions import IntVar
from discord import member
from discord.embeds import Embed
import json
from discord.ext import commands
from discord.colour import Color
import asyncio
#Vars
lawyersdict = {}
prefix = "<"
client = commands.Bot(command_prefix=prefix)
#Misc Stuff
client.remove_command("help")
#Embeds-
#RegEmbed
regembed = discord.Embed (
colour = discord.colour.Color.from_rgb(64, 255, 0),
title = 'Success',
description = 'Successfully registered you in the database as a lawyer!'
)
regembed.set_author(name='GVRP. Co',
icon_url='https://cdn.discordapp.com/avatars/921176863156609094/51441aaab15838c9a76c0488fd4ee281.webp?size=80')
regembed.timestamp = datetime.datetime.utcnow()
#Invalid
factembed = discord.Embed (
colour = discord.colour.Color.from_rgb(255, 64, 0),
title = 'Uh oh',
description = 'Seems like an error occured! Please try again.'
)
factembed.set_author(name='UselessFacts',
icon_url='https://cdn.discordapp.com/avatars/921176863156609094/51441aaab15838c9a76c0488fd4ee281.webp?size=80')
factembed.timestamp = datetime.datetime.utcnow()
#CMDS-
#Register Command
#client.command(aliases=['reg'])
async def register(ctx):
if ctx.author == client.user:
return
else:
if isinstance(ctx.channel, discord.channel.DMChannel):
await ctx.send("Sorry, you cannot use this command in a DM for security reasons.")
else:
channel = await ctx.author.create_dm()
def check(m):
return m.content is not None and m.channel == channel
await channel.send(f"Hello {ctx.author.mention}! Please tell a little bit about yourself! You have 5 minutes. (To cancel the command, type 'cancel')")
await asyncio.sleep(0.3)
descmsg = await client.wait_for('message', check=check, timeout=300)
if descmsg.content == "cancel":
await channel.send(f"Cancelled command!")
else:
await channel.send(f"Almost there! You just need to enter the hiring price! You have 2 minutes. (between 450$ & 50,000$)")
await asyncio.sleep(0.3)
pricemsg = await client.wait_for('message', check=check, timeout=180)
if any(c.isalpha() for c in pricemsg.content):
if any(c.isalpha() for c in pricemsg.content):
await channel.send("Oops, you didnt typed a number! Make sure you didnt typed it without a coma! Please re-send the command.")
else:
def PrcCheck(num: int):
if num <= 50000 and num >= 450:
return True
else:
return False
if PrcCheck(int(pricemsg.content)):
desc = {
f"{str(ctx.author.id)}" : {
"Description" : f"{descmsg.content}",
"Price" : int(pricemsg.content),
"IsActive" : "true"
}
}
jsonobj = json.dumps(desc, indent=4, sort_keys= True)
with open('lawyers.json', mode='w') as outfile:
obj = json.load(json.dump(lawyersdict, outfile))
obj.append(desc)
obj.write(jsonobj, outfile)
await channel.send(embed=regembed)
else:
await channel.send(f"The price you entered is too low or too high! Price entered: ``{pricemsg.content}``. Please re-send the command.")
#client.event
async def on_ready():
print(f"Ready! Logged in as {client.user}")
client.run("Bot Token")
Here is the Compiler Error (Python 3.9):
Ignoring exception in command register:
Traceback (most recent call last):
File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\theli\OneDrive\Bureau\Discord Bots\GVRP. Co UtilBot\launcher.py", line 82, in register
obj = json.load(json.dump(lawyersdict, outfile))
File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
AttributeError: 'NoneType' object has no attribute 'read'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'read'
I tried to look at other posts to see if there was a solution. But it was a post from 2015 which didn't solve my problem.
My goal here was to append details about the Discord User who entered the info and has entered my command to register.
Thank you for reading this post
obj = json.load(json.dump(lawyersdict, outfile))
You're using the result of json.dump() as the argument to json.load().
But json.dump() doesn't return anything. So you're effectively calling json.load(None).
As John Gordon said above dump return None therefore you cant load it .
To continue your comment, then yes json.load(outfile) is what you need to do but only later.
the file is open for w (write) and its currently an open file, so you can do it right away but after the with statement, by creating another io open call using the with context or with just an open.
So I have two tables, Servers and Strikes. In the Servers table, I have a max strikes value. I want to compare the strikes a user has to the max strikes specified in the Servers table. I tried this:
#commands.command(name='strike', pass_ctx= True)
#commands.has_permissions(manage_messages=True)
async def strike(self, ctx, member : discord.Member):
first_strike = 1
cursor = await self.client.db.cursor()
await cursor.execute(f"SELECT Strikes_Have FROM Strikes WHERE Guild_ID = {ctx.guild.id} AND User_ID = {member.id}")
result = await cursor.fetchone()
if result == None:
cursor = await self.client.db.cursor()
sql = f"INSERT INTO Strikes(Guild_ID, User_ID, Strikes_Have) VALUES({ctx.guild.id}, {member.id}, {first_strike})"
else:
cursor = await self.client.db.cursor()
sql = f"UPDATE Strikes SET Strikes_Have = Strikes_Have + 1 where Guild_ID = {ctx.guild.id} AND User_ID = {member.id}"
if result["Strikes_Have"] == result["MAX_STRIKES"]:
await ctx.message.channel.send(f"{member} has the max amount of stirkes specified by the server")
await cursor.execute(sql)
await self.client.db.commit()
await cursor.close()
await ctx.message.channel.send(f"Striked {member}")`
But got this error:
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/pi/EndorCore/cogs/Mod.py", line 225, in strike
if result["Strikes_Have"] == result["MAX_STRIKES"]:
IndexError: No item with that key
The error message you're getting currently is being caused by you trying to access a column of data which doesn't exist in the strikes table.
To get the max strikes value, you need to query that table and get the number, then compare the two.
For example:
cursor.execute(f"SELECT Strikes_Have FROM Strikes WHERE Guild_ID = {ctx.guild.id} AND User_ID = {member.id}")
user_result = cursor.fetchone()
cursor.execute(f"SELECT MAX_STRIKES FROM Servers WHERE Guild_ID = {ctx.guild.id}")
server_result = cursor.fetchone()
if user_result["Strikes_Have"] == server_result['MAX_STRIKES']:
print("User has max strikes")
import discord
from discord.ext import commands
import sqlite3
from config import settings
client = commands.Bot(command_prefix = settings['PREFIX'])
client.remove_command('help')
connection = sqlite3.connect('server.db')
cursor = connection.cursor()
#client.event
async def on_ready():
cursor.execute("""CREATE TABLE IF NOT EXISTS users (
name TEXT,
id INT,
cash bigint,
rep INT,
lvl INT
)""")
for guild in client.guilds:
for member in guild.members:
if cursor.execute(f"SELECT id FROM users WHERE id = {member.id}").fetchone() is None:
cursor.execute(f"INSERT INTO users VALUES ('{member}', {member.id}, 0, 0, 1)")
else:
pass
connection.commit()
print('Bot connected')
#client.event
async def on_member_join(member):
if cursor.execute(f"SELECT id FROM users WHERE id = {member.id}").fetchone() is None:
cursor.execute(f"INSERT INTO users VALUES ('{member}', {member.id}, 0, 0, 1)")
connection.commit()
else:
pass
#client.command(aliases = ['balance', 'cash'])
async def __balance(ctx, member: discord.Member = None):
if member is None:
await ctx.send(embed = discord.Embed(
description = f"""Баланс пользователя **{ctx.author}** составляет **{cursor.execute("SELECT cash FROM users WHERE id = {}".format(ctx.author.id)).fetchone()[0]} :leaves:**"""
))
else:
await ctx.send(embed = discord.Embed(
description = f"""Баланс пользователя **{member}** составляет **{cursor.execute("SELECT cash FROM users WHERE id = {}".format(member.id)).fetchone()[0]} :leaves:**"""
))
client.run(settings['TOKEN'])
cmd:
Bot connected
Ignoring exception in command __balance:
Traceback (most recent call last):
File "C:\Users\gnati\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "bot.py", line 48, in __balance
description = f"""Баланс пользователя **{ctx.author}** составляет **{cursor.execute("SELECT cash FROM users WHERE id = {}".format(ctx.author.id)).fetchone()[0]} :leaves:**"""
TypeError: 'NoneType' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\gnati\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\gnati\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\gnati\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'NoneType' object is not subscriptable
The problem occurs with this line of code:
description = f"""Баланс пользователя **{ctx.author}** составляет **{cursor.execute("SELECT cash FROM users WHERE id = {}".format(ctx.author.id)).fetchone()[0]} :leaves:**"""
The error TypeError: 'NoneType' object is not subscriptable suggests that what is going on is that this code:
cursor.execute("SELECT cash FROM users WHERE id = {}".format(ctx.author.id)).fetchone()
is returning None. The error occurs when the code then tries to subscript the resulting value (the [0] that follows the code above) to retrieve the first element in what is expected to be a sequence of values. Since None is not a sequence, and therefore does not have a "first element", the error results.
There's no way for me to tell you why this query is returning None. It could be that everything is set up perfectly, but the user with the specified id doesn't exist in the database, or possibly something about your database setup is wrong.
go to link discord.com/developers/ and select your bot. Click to tab Bot
and add SERVER MEMBERS INTENT and SERVER MEMBERS INTENT. replace in code
client = commands.Bot(command_prefix = settings['PREFIX'])
to
client = commands.Bot(command_prefix = settings['PREFIX'], intents = discord.Intents.all())