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

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()
)

Related

How to add warn count to warn command with sqlite?

So im trying to make a warn command using sqlite3
everything is fine
it warns them and stores the reason, guild id and user id in the database
but i want to check for how many warns the user got using sqlite3
i tried so many things but nothing worked
any type of help will be appreciated!..
my code :-
import discord
from discord.ext import commands
import sqlite3
class warn(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def warn(self, ctx, member: discord.Member, reason=None):
db = sqlite3.connect("warn.db")
cursor = db.cursor()
sql = ("INSERT INTO main (user_id, reason, guild) VALUES (?, ?, ?)")
val = (member.id, reason, ctx.guild.id)
cursor.execute(sql, val)
em = discord.Embed(
description=f"<:zztick:1067013663535411280> | warned **{member.mention}** for the reason: *{reason}*",
color=0x2F3136
)
em.set_footer(text=f"warn no. {DO SOMETHING}")
await ctx.send(embed=em)
db.commit()
db.close()
async def setup(bot):
await bot.add_cog(warn(bot))
thanks for reading...
You can do something like this:
#commands.command()
async def warn(self, ctx, member: discord.Member, reason=None):
db = sqlite3.connect("warn.db")
cursor = db.cursor()
# Just for checking if user already exists in table
check_user_sql = ("SELECT COUNT(*) FROM main WHERE user_id = ? AND guild = ?")
check_user_val = (member.id, ctx.guild.id)
cursor.execute(check_user_sql, check_user_val)
user_exists = cursor.fetchone()[0]
if user_exists:
# If user exists in table, it will update their warn count
update_warn_count_sql = ("UPDATE main SET warn_count = warn_count + 1 WHERE user_id = ? AND guild = ?")
cursor.execute(update_warn_count_sql, check_user_val)
else:
# If user not exists, insert a new row with a warn count of 0
insert_user_sql = ("INSERT INTO main (user_id, reason, guild, warn_count) VALUES (?, ?, ?, 0)")
insert_user_val = (member.id, reason, ctx.guild.id)
cursor.execute(insert_user_sql, insert_user_val)
# To get current warn count of user
warn_count_sql = ("SELECT warn_count FROM main WHERE user_id = ? AND guild = ?")
cursor.execute(warn_count_sql, check_user_val)
warn_count = cursor.fetchone()[0]

Hey i have made a ticket system using sqlite3 in discord.py v2 but it is not adding values in the db

As i have mentioned my bot is not adding values in the db if i try to create a ticket it just says interaction failed and there is no errors in the console.
button code:-
class CreateTicket(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
#discord.ui.button(
label="Create Ticket", custom_id="create_ticket:blurple", emoji="📩"
)
async def create_ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
if discord.utils.get(interaction.guild.text_channels, name = f"ticket-{interaction.user.name.lower().replace(' ', '-')}") != None:
await interaction.response.send_message(f"You already have a ticket open at {ticket.mention}!", ephemeral = True)
return
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
interaction.guild.me: discord.PermissionOverwrite(read_messages=True),
interaction.user: discord.PermissionOverwrite(read_messages=True)
}
db = sqlite3.connect("tickets2.db")
cursor = db.cursor()
cursor.execute(f"SELECT category_id FROM main WHERE guild_id = {interaction.user.guild.id}")
result = cursor.fetchone()
if result is None:
return
category = discord.utils.get(interaction.guild.categories, id=int(result[0]))
channel = await interaction.guild.create_text_channel(f"ticket {interaction.user.name}", overwrites=overwrites, category=category)
msg = await interaction.response.send_message(f"Channel created successfully! {channel.mention}", ephemeral=True)
# await msg.edit(f"Channel created successfully {channel.mention}")
em = discord.Embed(
title=f"Artez ticketing",
description=f"Support will be with you shortly. \n To close this ticket click the 🔒 close button.",
color=0x2F3136,
timestamp=datetime.datetime.now()
)
msg = await channel.send(content=f"{interaction.user.mention} Welcome", embed=em, view=controls())
await msg.pin()
command code:-
#client.group()
async def ticket(ctx):
return
#ticket.command()
#commands.has_permissions(manage_guild=True)
async def setup(ctx):
try:
def check(msg):
return msg.author == ctx.author
em = discord.Embed(
description="<:Tick:1050077348193652819> | Alright tell me the category id?",
color=0x2F3136
)
await ctx.send(embed=em)
category_id = await client.wait_for("message", check=check)
em = discord.Embed(
description="<:Tick:1050077348193652819> | Alright now tell me where can i send the transcripts in?",
color=0x2F3136
)
await ctx.send(embed=em)
trans_channel = await client.wait_for("message", check=check)
trans_channel_id = trans_channel.id
db = sqlite3.connect('tickets2.db')
cursor = db.cursor()
sql = ("INSERT INTO main(guild_id, category_id, trans) VALUES(?,?,?)")
val = (ctx.guild.id, category_id, trans_channel_id)
em = discord.Embed(
title=f"<a:Ticket:1049745143072305222> Ticket",
description="To create a ticket click the 📩 button.",
color=0x2F3136
)
em.set_footer(text=f"{client.user.name} Ticket • Ticketing without clutter", icon_url=client.user.avatar)
await ctx.send(embed=em, view=CreateTicket())
cursor.execute(sql, val)
db.commit()
db.close()
except Exception as er:
print(er)
i want it to add the guild id
category id
transcript channel
then i will fetch the transcript channel and category id of that guild where the ticket is created
at first it worked perfectly but today it is not working i tried everything but nothing worked.

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.

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.

Categories