lvl system for discord python sql3 - python

The level system does not work
#bot.event
async def on_message(message):
user = message.author.id
conn = sqlite3.connect('server.db')
cur = conn.cursor()
cur.execute('SELECT xp, lvl FROM users WHERE id = ?')
results = cur.fetchone()
row = results[0]
old_xp = row[0]
old_level = row[1]
new_xp = old_xp + 1
if new_xp == 2:
new_level = 1
else:
new_level = old_level
cur.execute('UPDATE users SET xp = ?, level = ? WHERE id = ?', (new_xp, new_level, user)
)
conn.commit()
conn.close()
Error:
cur.execute('SELECT xp, lvl FROM users WHERE id = ?')
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 0 supplied.

You need to pass a value for the id.
#bot.event
async def on_message(message):
user = message.author.id
conn = sqlite3.connect('server.db')
cur = conn.cursor()
cur.execute('SELECT xp, lvl FROM users WHERE id = ?', (user,))
results = cur.fetchone()
Note that you need to put a comma here: (user,)

Related

Nothing gets put into the database nor any message is sent. Have any ideas?

#commands.command()
async def Money(self, ctx, member:discord.Member):
member = ctx.message.author.name
member_id = ctx.message.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!")
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()
Nothing gets put into the database nor any message is sent. The command seems to fail.

result1 sends what's in it weird (picture below)

class EconomyCog(commands.Cog, name="Help"):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def Money(self, ctx):
db = sqlite3.connect("main.sqlite")
cursor = db.cursor()
cursor.execute(f"SELECT money FROM main WHERE member_id = {ctx.message.author.id}")
result = cursor.fetchone()
if result is None:
sql = ("INSERT INTO main(member_id, money) VALUES(?,?)")
val = (ctx.message.author.id, 500)
cursor.execute(sql, val)
await ctx.send("Because you didn't have an account, I just made one for you!")
db.commit()
else:
emoji = ":dollar:"
cursor.execute(f"SELECT money FROM main WHERE member_id = {ctx.message.author.id}")
result1 = cursor.fetchone()
embed = discord.Embed(title = f"{ctx.message.author.name}'s Money", description=f"${result1} {emoji}", color = discord.Colour.random())
await ctx.send(embed=embed)
cursor.close()
db.close()
Everything works fine, but now when the amount is sent it looks like this:
when I try the {result1[1]}(where the money is at) the command doesn't even work. What am I missing?
The tuple is of length 1, so you should be using {result1[0]} rather than {result1[1]}.
Indexes start at 0, not 1:
embed = discord.Embed(
title = f"{ctx.message.author.name}'s Money",
description=f"${result1[0]} {emoji}",
color = discord.Colour.random()
)

How to setup on_message with sqlite3 in discord.py?

Hi I created the following event. It takes input one time after that it stores the guild id , channel id and role id in sqlite db . After that when someone in that particular guild mentions minimum 3 users in a particular channel , the bot gives them new role.
class ScrimsCog(commands.Cog, name='Scrims-Commands') :
def __init__(self,bot):
self.bot = bot
#commands.Cog.listener()
async def on_message(self, message):
if message.guild:
db = sqlite3.connect('main.sqlite')
cursor = db.cursor()
cursor.execute(
f"SELECT * FROM main WHERE guild_id = ?", (message.guild.id, ))
result = cursor.fetchone()
if result:
channel = self.bot.get_channel(result[2])
role = message.guild.get_role(result[1])
if role:
if message.channel == channel:
if len(message.mentions) >= 3:
await message.add_reaction(emoji="<a:tick:748476262640779276>")
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.id)
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.id, 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()
Well, I believe the code is fine it doesn't throw any error . The issue is that it perfectly take input without any error but doesn't store it into db.
I believe the problem is with my db,
code -
db = sqlite3.connect('main.sqlite',timeout=10)
cursor = db.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS main(
guild_id INTEGER,
role INTEGER,
channel_id INTEGER
)
''')
I believe the problem is here , I should take TEXT in place INTEGER but I am not sure. Answer me with What do you I am doing wrong and how should I fix that.
I answered your last question with assuming that role and channel is TEXT type in the table and that answer should've solve your problem. If you change them, it will work fine and also it will be more efficient if you define the database variable and cursor on top of the on_message event just for once. So you don't have do connect to the database everytime.

How can I tag a member in my python discord bot

So I have this leveling system in python but I wanna add an #tag so the bot mentions the member that leveled up... But I got no idea how. I already tried multiple things but they all don't work.
from discord.ext import commands
import discord
import logging
import yaml
import sqlite3
import time
import random
import re
logging.basicConfig(level=logging.INFO)
bot = commands.Bot(command_prefix='l>', description='Hype Levels')
def threshold(n):
level_threshold = 5*(n**2)+50*n+100
return level_threshold
#bot.command(pass_context=True)
async def rank(ctx):
try:
_, member = (ctx.message.content).split(' ', 1)
member = re.sub("[^0-9]", "", member)
except:
member = ctx.message.author.id
db = sqlite3.connect('users.db')
c = db.cursor()
c.execute('SELECT user.*, (SELECT count(*) FROM users AS members WHERE members.rawexp > user.rawexp) as Rank FROM users AS user WHERE id = ?',
(ctx.message.author.id, ))
user = c.fetchone()
db.close()
rank = str(user[6] + 1)
embed = discord.Embed(title='{}\'s Information'.format(ctx.message.author.name)) \
.set_thumbnail(url=ctx.message.author.avatar_url) \
.add_field(name='Rank', value='#' + rank) \
.add_field(name='Level', value=user[2]) \
.add_field(name='EXP', value='{}/{}'.format(user[3], threshold(user[2]))) \
.add_field(name='Raw EXP', value=user[4]) \
await ctx.send(embed=embed)
#bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.author.bot:
return
if message.content.startswith('l>'):
await bot.process_commands(message)
return
db = sqlite3.connect('users.db')
c = db.cursor()
c.execute('SELECT * FROM users WHERE id= ?', (message.author.id,))
user = c.fetchone()
if user is None:
await message.channel.send('Looks like you\'re new! Welcome to level 1. Initializing player...')
c.execute('INSERT INTO users(id, name, level, exp, rawexp, time) VALUES(?,?,?,?,?,?)', (message.author.id, message.author.name, 1, 0, 0, time.time()))
db.commit()
db.close()
return
if message.author.name != user[1]:
c.execute('UPDATE users SET name = ? WHERE id= ?', (message.author.name, message.author.id))
if (time.time() - user[5]) > 60:
addedexp = random.randint(10, 25)
exp = user[3] + addedexp
rawexp = user[4] + addedexp
c.execute('UPDATE users SET exp = ?, rawexp = ?, name = ?, time = ? WHERE id= ?', (exp, rawexp, message.author.name, time.time(), message.author.id))
if (exp > threshold(user[2])):
level = user[2] + 1
c.execute('UPDATE users SET exp = ?, level = ? WHERE id= ?', (0, level, message.author.id))
await message.channel.send('Wowza! You leveled up! Your level is now **{}**.'.format(level))
db.commit()
db.close()
await bot.process_commands(message)
#bot.event
async def on_ready():
print("HypeLevels V1.1")
print("Made by: Garbodonk#6347")
print("Bot Name: " + str(bot.user.name))
print("Bot ID: " + str(bot.user.id))
await bot.change_presence(activity=discord.Streaming(name='some HYPE', url="https://www.twitch.tv/hypepixelbot", type=1))
#Initialize database.
db = sqlite3.connect('users.db')
c = db.cursor()
c.execute('CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY, name TEXT, level INT, exp INTEGER, rawexp INTEGER, time REAL)')
db.commit()
bot.run('Token')
But I want to add an #tag when people level up so they get tagged
if (exp > threshold(user[2])):
level = user[2] + 1
c.execute('UPDATE users SET exp = ?, level = ? WHERE id= ?', (0, level, message.author.id))
await message.channel.send('Wowza! You leveled up! Your level is now **{}**.'.format(level))
anyone who knows how to do this? To ask me questions or something just add me on discord: Garbodonk#6347
async def command(ctx, member : discord.Member, *, reason=None) :
await ctx.send(f" can place text here if you want {member.mention} can place text here as well")```
I hope this helps.

Python Unbound Local variabel

Why my check_email error, i dont know how to fix it
def getLoginDetails():
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
if 'email' not in session:
loggedIn = False
firstName = ''
noOfItems = 0
else:
loggedIn = True
cur.execute("SELECT userId, firstName FROM users WHERE email = '" + session['email'] + "'")
userId, firstName = cur.fetchone()
if 'email' == "admin#shop.com":
check_email = True
else:
check_email = False
cur.execute("SELECT count(productId) FROM kart WHERE userId = " + str(userId))
noOfItems = cur.fetchone()[0]
conn.close()
return (loggedIn, firstName, noOfItems, check_email)
#app.route("/")
def root():
loggedIn, firstName, noOfItems, check_email = getLoginDetails()
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
cur.execute('SELECT productId, name, price, description, image, stock FROM products')
itemData = cur.fetchall()
cur.execute('SELECT categoryId, name FROM categories')
categoryData = cur.fetchall()
itemData = parse(itemData)
return render_template('home.html', itemData=itemData, loggedIn=loggedIn, firstName=firstName, noOfItems=noOfItems, categoryData=categoryData, check_email=check_email)
This makes no sense to me as I clearly initialize check_email as one of the first lines of my code, and I even labeled it as global just to be safe and make sure it was within the scope of all my methods.
Error: UnboundLocalError: local variable 'check_email' referenced before assignment
You don't assign to check_email if 'email' not in session.

Categories