How to add check in embed definitions? - python-3.x

Hi there I'm trying to add checks to my embed definitions that return the users information from the sql database.
What I'd like to achieve is to check if the user has set a gametag and then if the data isn't there then don't show it on their profile.
However, I'm was able to pass a check to see if the user data is in the database if the result is None it will turn Steam None where as I rather not show it altogether.
Here is what I'm working with:
#commands.group(invoke_without_command=True)
async def profile(self, ctx, user: discord.Member=None):
user = user or ctx.author
db = sqlite3.connect('profiles.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT profile FROM profile WHERE username={user.id}")
result = cursor.fetchone()
cursor.execute(f"SELECT steam FROM profile WHERE username={user.id}")
result2 = cursor.fetchone()
if result is None:
await ctx.send(f"{user.display_name}'s bio has not been created yet.")
elif result4:
steam = f"**Steam** [{result2[0]}](http://steam.com/{result2[0]})" #return data from database.
else:
steam = "" # return nothing if nothing returned from database.
desc = f"{(result[0])} \n\n {steam}:" # define a embed description as f-string
embed = discord.Embed(title=f"{user.name}'s Profile", description=desc, color=user.colour)
await ctx.send(embed=embed)```

If I understand correctly, you do not want result2[0] to be None, whereas you are checking for result to be None. Make sure to check for both result2 and result2[0] to be not None and that should fix it.
Also, if that is supposed to stop the embed creation, you might want to return after the await ctx.send(...) (under "if result == None:").

Related

How can I use something stored in a DataBase? SQLite / Python

So, I am new at DataBases and I have a question. I first made a re-search in the internet but could not find anything or actually I could not understand correctly what they were explaining. Before starting with my question I want to say that I am currently working in a Discord Bot in Python as Main Language and I am trying to create a per-server-prefix system. I have already made it once but in .JSON format. Then I heard that using .JSON to save this kind of Data is not actually good so I moved to DataBases. Now, my question is:
I have stored the guild_id and prefix in my DB, how could I use that for a per-server-prefix system? I have not tried anything yet except writing the Code to store both Texts. I would really love if anyone could explain to me not just tell me the Code! Any answer will be appreciated <3.
Main.py:
def get_prefix(client, message):
db = sqlite3.connect("main.sqlite")
cursor = db.cursor()
cursor.execute(f"SELECT prefix FROM prefixes WHERE guild_id = {message.guild.id}")
result = cursor.fetchone()
if result is None:
return "/"
else:
client = commands.Bot(command_prefix = get_prefix)
Prefixes.py (COGS):
#commands.command()
#commands.has_permissions(administrator=True)
async def prefix(self, ctx, prefix=None):
db = sqlite3.connect("main.sqlite")
cursor = db.cursor()
cursor.execute(f"SELECT prefix FROM prefixes WHERE guild_id = ?", ctx.guild.id)
result = cursor.fetchone()
if result is None:
sql = ("INSERT INTO prefixes(guild_id, prefix) VALUES(?,?)")
val = (ctx.guild.id, prefix)
await ctx.channel.send(f"{prefix}")
elif result is not None:
sql = ("UPDATE prefixes SET prefix = ? WHERE guild_id = ?")
val = (prefix, ctx.guild.id)
await ctx.channel.send(f"update `{prefix}`")
cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()
That is pretty much the whole code. If you think anything should be changed or have any suggestions, answer in the comments!
All you need to do is, after the else, put return result. For example:
result = cursor.fetchone()
if result is None:
return "/"
else:
return result
cursor.fetchone() returns a tuple with each element requested in the row, as you only requested the prefix, it will contain just that (e.g: ("!",)) which is permitted as your command_prefix callable can return a string or tuple of strings.
Warning:
You may want to add a check to ensure that someone doesn't specify an empty string (A zero length string with nothing in it) as their prefix, otherwise your bot will attempt to run every message it sees as a command
References: discord.ext.commands.Bot.command_prefix

Python Compare lists

So I have this script,
good_users=[]
async def callposts(ctx):
g0=str(ctx.guild)
g=g0.replace(' ','_')
sqluse(g)
x="SELECT authorid, COUNT(*) FROM posts GROUP BY authorid"
mycursor.execute(x)
k=mycursor.fetchall()
for user in k:
if user[1] > 7:
good_users.append(user)
k.remove(user)
print(user)
return k
async def kick(ctx, uid):
await ctx.guild.kick(ctx.guild.get_member(int(uid)))
#client.command(pass_context = True)
async def post_check(ctx):
ausers=list(ctx.guild.members)
lowposters= await callposts(ctx)
for user in ausers:
if user == client.user:
print(user.name+" is a bot!")
ausers.remove(user)
elif user.id in exempt:
print(user.name+" is exempt!")
ausers.remove(user)
elif user.id in good_users:
print(user.name+" is a good user!")
ausers.remove(user)
else:
await kick(ctx,user.id)
print(ausers)
What I am trying to do here is remove inactive users. So I have 2 lists that I want to compare the memberlist to, exempt and good_users. I also am checking to make sure it isn't the bot. So this script removes the bot from the list but it doesn't remove the user that's in exempt or good users. So in turn it tries to kick everyone that's not a bot. They are trying to take over!
I'm looking this over but right now I'm sick so not 100%.
The prints are just for troubleshooting purposes however, all but the firt print in the callpost function print nothing and that one for some reason only prints the user, now it isn't printing the bot so the bot may not be in the list to get removed.
Any thoughts?
You're never appending anything to exempt_users and because of the scope of good_users it is only filled with users within callposts() because you're not returning it when calling it in post_check().
Changing the following should fix your problem:
Return good_users from callposts()
Add a new variable to where you call callposts() in post_check() like
lowposters, good_users = await callposts(ctx)
So I finally figured this out, the script was looking at user.id as an attribute of user object. To fix that I had to use
elif str(user.id) in exempt): and elif str(user.id) in good_users:

Removing field value from embed issue

Hi I'm wanting to add a check to a embed field.
Currently when it's None it will just leave a name="Steam" value and a empty value="[{result2[0]}](http://steamcommunity.com/profiles/{result2[0]}).
I'm wanting to make a check to see if result2 is in the database - I put an if statement if result2: before the embed field - if it does not return None it will show the embed field.` If result returns a None Type then don't show the embed field.
Not sure if this is possible.
Here is an example and a mockup edited in paint
The one marked 1 is what results I'm getting if check returns None
The one marked 2 is what result I get if the check returns a not
None
The one marked 3 is mocked up in paint version of what result
I'd like to have if None is returned.
Here is the code I'm working with:
#commands.group(invoke_without_command=True)
async def profile(self, ctx, user: discord.Member=None):
user = user or ctx.author
db = sqlite3.connect('profiles.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT profile FROM profile WHERE username={user.id}")
result = cursor.fetchone()
cursor.execute(f"SELECT steam FROM profile WHERE username={user.id}")
result2 = cursor.fetchone()
if result is None:
await ctx.send(f"{user.display_name}'s bio has not been created yet.")
return
else:
desc = f"**Bio:**\n{(result[0])}"
embed = discord.Embed(title=f"{user.display_name}'s Profile", description=desc, color=user.colour)
if result2: #here I add the check before adding the embed field
embed.add_field(name="Steam", value=f"[{result2[0]}](http://steamcommunity.com/profiles/{result2[0]})")
await ctx.send(embed=embed)
Help would be appreciated.
It looks like result2 is a list containing None, or something similar. Let's directly check result2[0] as well as result2
if result2 and result2[0]:
embed.add_field(name="Steam", value=f"[{result2[0]}](http://steamcommunity.com/profiles/{result2[0]})")

How to fix TypeError: '>' not supported between instances of 'NoneType' and 'int'

I'm setting up a login form using Python/Flask/mysql.connector however I'm getting the error File "F:\Python\Apps\webapp\app.py", line 84, in login
if result > 0: TypeError: '>' not supported between instances of 'NoneType' and 'int'.
I've tried different things like changing the if statement for something different and verifying that dictionary is true, but I get the same error.
#Login
#app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
#Get Form
username = request.form['username']
password_candidate = request.form['password']
#Get user by username
result = cursor.execute("SELECT * FROM users WHERE username = %s", [username])
if result > 0:
#Get stored hash
data = cursor.fetchone()
password = data['password']
#compare the Passwords
if sha256_crypt.verify(password_candidate, password):
#Passed
session['logged_in'] = True
session['username'] = username
flash('You are now logged in', 'success')
return redirect(url_for('dashboard'))
else:
error = 'Invalid Login'
return render_template('login.html', error=error)
#Close connection
cursor.close()
else:
error = 'Username not found'
return render_template('login.html', error=error)
return render_template('login.html')
I expected the form to sign you in if the information you use to register is valid or display a fail login if the information is not valid. Obviously this information will be pulled from mysql database.
result = cursor.execute("SELECT * FROM users WHERE username = %s", [username])
This line is causing the problem. It is returning you a null value possibly because the username does not exist.
I see you have an if...else to handle this, but if the value of result is None, you cannot compare it with an integer value - 0 in this case.
In python, you can just check if a value is not None by doing this:
if result:
# code
else:
# code
Hope this helps. Good luck.
I fixed the issue.
I changed from import mysql.connector to from flask_mysqldb import MySQL
Remove the mysql.connector config and added the Database details per the example below
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'scott'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'users'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
After that I had to initialize the app
mysql = MySQL(app)
And the last part was creating a cursor like the example below.
cursor = mysql.connection.cursor()
I also change my if statement to reflect #Harshal Parekh advice.
Instead of
if result > 0:
I used
if result:
Hopefully this helps somebody else.

Using Another File As A Variable/Data source

I have written some code for a system, I have imported another file which stores all the information for login details. But when I go to test it and try to login it keeps coming up with "INCORRECT". Both of the code files are attached.
I have tried changing the names of the files, variables and changing the login details but it still doesn't work.
from database import user_data, pasw_data, no_file
name = user_data
code = pasw_data
def user_check():
user = input("USERNAME >>")
if user == name:
pasw_check()
else:
print("INCORRECT")
def pasw_check():
pasw = input("PASSWORD >>")
if pasw == code:
print("ACCESS GRANTED")
user_check()
This is the file, which stores all the login info, named database.py
user_data = ["123"]
pasw_data = ["python"]
You're checking a string (user) and a list (user_data) for equality. They aren't equal at all. The list just happens to contain a string that's equal to your query. You should use in to search lists (and strings, dictionaries, tuples, etc) for data:
if user in user_data:
print("I'm in!")

Resources