IQ command in discord.py - discord

I wanted to make fun iq command which sends a random iq for a member which changes every 24 hours
#client.command()
async def iq(ctx):
iq = random.randint(0,200)
print(iq)
await ctx.send(f'IQ of {ctx.author.name} is ' + str(iq) + ' today')
This is my this works but it keep changing, I wanted to know if there is a option so the iq doesn't change everytime the member type iq and stay constant per member and be constent for 24 hours and then change again to a random number?

You could achieve this using the user's id as a seed using the random.seed method
#client.command()
async def iq(ctx):
random.seed(ctx.author.id)
iq = random.randint(0,200)
print(iq)
await ctx.send(f'IQ of {ctx.author.name} is ' + str(iq) + ' today')

Related

Unable to fix this on_member_join issue for discord.py on inviting someone

This is a quick bot made but I can't seem to fix the on_member_join issue.
This is what it's supposed to do:
Whenever a user joins using someone's invite link, it'll +1 to the database for the amount of invites they have.
The on_member_join will also insert into a member_invites table to save which member joins using which invite link, so it can be used later when a member leaves.
If a user leaves, it'll -1 to the amount of invites they have.
The issue is on_member_join, been trying to fix it but I simply can't.
The issues I get when trying to fix it in different ways:
The invites are added based on the amount of invite links you have rather than just +1 each
The invites doesn't even add at all
broken stuff
etc
If anyone is able to help me with this, please do. I've been trying to fix it for a long time
The code below is the one where the invites are added based on the amount of invite links you have rather than just +1 each
import discord
import sqlite3
from discord.ext import commands
bot = commands.Bot(command_prefix='!', intents = discord.Intents.all())
conn = sqlite3.connect('invites.db')
cursor = conn.cursor()
#bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
cursor.execute("CREATE TABLE IF NOT EXISTS invites (user_id INTEGER, invites INTEGER)")
cursor.execute("CREATE TABLE IF NOT EXISTS member_invites (member_id INTEGER, invite_code TEXT)")
conn.commit()
#bot.event
async def on_member_join(member):
guild = member.guild
invites = await guild.invites()
for invite in invites:
if invite.uses > 0:
inviter = guild.get_member(invite.inviter.id)
cursor.execute("SELECT user_id FROM invites")
result = cursor.fetchall()
user_ids = [r[0] for r in result]
if inviter.id not in user_ids:
cursor.execute("INSERT INTO invites(user_id, invites) VALUES (?, 1)", (inviter.id,))
else:
cursor.execute("UPDATE invites SET invites=invites+1 WHERE user_id=?", (inviter.id,))
cursor.execute("INSERT INTO member_invites(member_id, invite_code) VALUES (?, ?)", (member.id, invite.code))
conn.commit()
#bot.event
async def on_member_remove(member):
guild = member.guild
cursor.execute("SELECT invite_code FROM member_invites WHERE member_id=?", (member.id,))
result = cursor.fetchone()
if result is not None:
invite_code = result[0]
invite = await guild.invites()
for i in invite:
if i.code == invite_code:
inviter = guild.get_member(i.inviter.id)
cursor.execute("SELECT invites FROM invites WHERE user_id=?", (inviter.id,))
result = cursor.fetchone()
if result is not None:
cursor.execute("UPDATE invites SET invites=invites-1 WHERE user_id=?", (inviter.id,))
conn.commit()
cursor.execute("DELETE FROM member_invites WHERE member_id=?", (member.id,))
conn.commit()
#bot.command(name='invites')
async def invites(ctx, member: discord.Member = None):
member = member or ctx.author
cursor.execute("SELECT invites FROM invites WHERE user_id=?", (member.id,))
result = cursor.fetchone()
if result is None:
await ctx.send(f"{member.name} has not invited any users yet.")
else:
await ctx.send(f"{member.name} has invited {result[0]} users.")
bot.run("token")

How i can extract data from DB to make a variable in discord.py

mydb = mysql.connector.connect(
host='localhost',
user='root',
password='',
database='levels'
)
cursor = mydb.cursor(dictionary=True)
That is my DB setup.
and that is the embed i want to show.
#bot.command()
async def bal(ctx):
cursor.execute(f"SELECT ELO from users where ID = {ctx.author.id}")
rows = cursor.fetchall()
for row in rows:
usere = ctx.message.author.id
embedis = discord.Embed(title="・ ZELL | Professional League | User Profile ・",description=f"<#{usere}> Personal Info",color=0xc27c0e)
embedis.add_field(name="Rank Statistics:", value="", inline=True)
embedis.add_field(name=f"{ELO}")
await ctx.send(embed=embedis)
How i can extract the ELO Table from DB to make it as a Variable there to use in (name=f"{ELO}")
ELO = cursor.execute(f"SELECT ELO from users where ID = {ctx.author.id}")
You can use this to get data for variables.

Accessing an object's instance variable from an array

Teaching myself Ruby so please bear with me. If I create an object with several defining attributes and push this object into an array how do I access one of those attributes in another method to use it in a control flow scheme? I'm making a banking ATM program for fun. My code is below...
class Bank
class AccountMaker
attr_accessor :account_number, :name, :balance, :pin
def initialize(account_number, name, balance, pin)
#account_number = account_number
#name = name
#balance = balance
#pin = pin
end
end
def initialize
#accounts = []
end
def add_account(account_number, name, balance, pin)
account = AccountMaker.new(account_number, name, balance, pin)
#accounts << account
end
def login_screen(accounts)
def account_number_login(accounts)
puts "Please enter your 7 digit account number."
account_number_input = gets.chomp
puts accounts.instance_variable_get(:account_number)
if (/^\d{7}$/ === account_number_input) and (account_number_input === (what should go here) )
thank_you_msg()
pin_login(account_number_input)
else
error_msg()
account_number_login()
end
end
I have more code after this but its not pertinent to the question. Essentially I want to extract from the accounts array :account_number and use it in the if statement within the Login_screen function to see if the account actually exists. Any and all help would be appreciated.
accounts is an array. So you have to access one of its elements' account_number instance variable. For example the first element's:
# accounts[0] would return an instance of `AccountMaker `
accounts[0].instance_variable_get(:account_number)
Also, you don't need to use instance_variable_get, since you already declared it as accessor. So, you can just call account_number method on it.
accounts[0].account_number

bad use of variables in db.query

I'm trying to develop a blog using webpy.
def getThread(self,num):
myvar = dict(numero=num)
print myvar
que = self.datab.select('contenidos',vars=myvar,what='contentTitle,content,update',where="category LIKE %%s%" %numero)
return que
I've used some of the tips you answer in this web but I only get a
<type 'exceptions.NameError'> at /
global name 'numero' is not defined
Python C:\xampp\htdocs\webpy\functions.py in getThread, line 42
Web GET http://:8080/
...
I'm trying to make a selection of some categorized posts. There is a table with category name and id. There is a column in the content table which takes a string which will be formatted '1,2,3,5'.
Then the way I think I can select the correct entries with the LIKE statement and some %something% magic. But I have this problem.
I call the code from the .py file which builds the web, the import statement works properly
getThread is defined inside this class:
class categoria(object):
def __init__(self,datab,nombre):
self.nombre = nombre
self.datab = datab
self.n = str(self.getCat()) #making the integer to be a string
self.thread = self.getThread(self.n)
return self.thread
def getCat(self):
'''
returns the id of the categorie (integer)
'''
return self.datab.select('categorias',what='catId', where='catName = %r' %(self.nombre), limit=1)
Please check the correct syntax for db.select (http://webpy.org/cookbook/select), you should not format query with "%" because it makes code vulnerable to sql injections. Instead, put vars in dict and refer to them with $ in your query.
myvars = dict(category=1)
db.select('contenidos', what='contentTitle,content,`update`', where="category LIKE '%'+$category+'%'", vars=myvars)
Will produce this query:
SELECT contentTitle,content,`update` FROM contenidos WHERE category LIKE '%'+1+'%'
Note that I backquoted update because it is reserved word in SQL.

How can I add text to my column's select statement

I want to prepend text to sql select,
I can do this:
SELECT (1328724983-time)/60/60 AS status
FROM voting
WHERE account = 'ThElitEyeS' AND vid = 1
This will show time left.
What I'd like to do is this though:
SELECT 'Please try after' + (1328724983-time)/60/60 AS status
FROM voting
WHERE account = 'ThElitEyeS' AND vid = 1
Is there any way I can accomplish this?
Just use cast or convert to convert it all to varchar for instance.
SELECT 'Please try after' + CAST((1328724983-time)/60/60 as varchar(80)) AS status
FROM voting
WHERE account = 'ThElitEyeS' AND vid = 1;
See the MSDN on Cast / Convert
Based on your comments you can do:
SELECT 'Please try again after' + CAST(MyColForHours as varchar(25)) + ' hours', AnyOtherColumns FROM Table
Was trying this today and getting an error
SQL0420N Invalid character found in a character string argument of the function "DECFLOAT". SQLSTATE=22018
Apparently we now need to use || instead of + to join the sections.
http://www-01.ibm.com/support/docview.wss?uid=swg21448700

Resources