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

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

Related

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.

Django: executing UPDATE query always returns rowcount 0

I'm new to programming and I'm not sure, whether the problem is in me or in the Django code. I call link method from my view and update field MatchId on Record model. Database is SQL Server 2017.
My view:
class RecordViewSet(viewsets.ModelViewSet):
"""
API for everything that has to do with Records.
Additionally we provide an extra `link` action.
"""
queryset = Record.objects.all().order_by("Id")
serializer_class = RecordSerializer
permission_classes = [permissions.IsAuthenticated]
#action(methods=["post"], detail=False)
def link(self, request, *args, **kwargs):
idToMatch = request.POST.getlist("Id")
recordsToMatch = Record.objects.filter(Id__in=idToMatch)
lastMatchId = Record.objects.latest("MatchId").MatchId
matchedSuccesfully = recordsToMatch.update(MatchId=lastMatchId + 1)
if matchedSuccesfully > 1:
return Response(data=matchedSuccesfully, status=status.HTTP_200_OK)
else:
return Response(data=matchedSuccesfully, status=status.HTTP_404_NOT_FOUND)
For some reason matchedSuccessfully always returns zero. Relevant Django code:
def execute_sql(self, result_type):
"""
Execute the specified update. Return the number of rows affected by
the primary update query. The "primary update query" is the first
non-empty query that is executed. Row counts for any subsequent,
related queries are not available.
"""
cursor = super().execute_sql(result_type)
try:
rows = cursor.rowcount if cursor else 0
is_empty = cursor is None
finally:
if cursor:
cursor.close()
for query in self.query.get_related_updates():
aux_rows = query.get_compiler(self.using).execute_sql(result_type)
if is_empty and aux_rows:
rows = aux_rows
is_empty = False
return rows
I rewrote execute_sql as follows:
def execute_sql(self, result_type):
"""
Execute the specified update. Return the number of rows affected by
the primary update query. The "primary update query" is the first
non-empty query that is executed. Row counts for any subsequent,
related queries are not available.
"""
cursor = super().execute_sql(result_type)
try:
if cursor:
cursor.execute("select ##rowcount")
rows = cursor.fetchall()[0][0]
else:
rows = 0
is_empty = cursor is None
finally:
if cursor:
cursor.close()
for query in self.query.get_related_updates():
aux_rows = query.get_compiler(self.using).execute_sql(result_type)
if is_empty and aux_rows:
rows = aux_rows
is_empty = False
return rows
and now it works, but I'm unsure if there is a more elegant way to resolve this since now I have to ship this exact code everywhere. Source code at:
https://github.com/django/django/blob/main/django/db/models/sql/compiler.py
I've faced the same issue and came to the same point in django's depths.
In my case — the problem was in trigger configured for UPDATE.
It should have return ##ROWCOUNT as a result, but in my case it didn't.
Btw, the thing I did (due to restriction on editing triggers) — overrided save method in base model for such models to force_update=True:
class BaseModel(models.Model):
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
if self._state.adding:
super().save(force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)
else:
try:
super().save(force_insert=force_insert, force_update=True, using=using, update_fields=update_fields)
except DatabaseError as e:
if str(e) == 'Forced update did not affect any rows.':
pass
else:
raise e
class Meta:
managed = False
abstract = True

IQ command in discord.py

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

sqlite3 selecting values based on python variables

I am trying to select a value from my python SQL table based on a variable that the user inputs, through Tkinter. My database has a column named employee_username and has the employee's usernames and their password in 1 row. Username is entered by the user in a tkinter window
My code looks like this:
import sqlite3
import password_database
import tkinter
conn = sqlite3.connect('passwordDb.db')
c = conn.cursor()
username=entry_user.get()
password=entry_user.get()
database_username=c.execute(SELECT * FROM passwordDb WHERE
employee_username=username)
if database_username!=' ':
print('you entered a username which is not in the database')
else:
running=True
When I run this code I am not able to get any results. How do I manage to check if the value the user enters is in my database and how to I retrieve employee's password attached to the username.
Thanks in advance
Your code is not complete but I guess i understand you.
Before you query the database, you need to strip of white spaces from the username or the input
username = input("username")
db_username = username.strip() #this removes the white space
# you can then check to see if the username is none...
records = cur.fetchall(); # this would return all matching records, loop through
if not database_user is None:
...
else:
print("your username is bad")
I see few mistakes
First: query should be as string, and it should have ? and username should be tuple (username, ) as argument
c.execute("SELECT * FROM passwordDb WHERE employee_username=?", (username, ))
Second: you have to use fetchall() or fetchone()` to get list with results or first result.
rows = cur.fetchall()
row = cur.fetchone()
Third: execute() doesn't have to return value so there is no sense to comparer with string " ". fetchall()/fetchone()` returns row(s) with result(s) so you can check how many rows it returned.
rows = cur.fetchall()
if len(rows) != 1:
print("your username is bad or duplicate")
or
rows = cur.fetchall()
if cur.rowcount != 1:
print("your username is bad or duplicate")

Google analytics API data to SQL via Python 2.7

Out of my depth here.
Have an assignment to download data from web and get it into SQL lite.
have pieced together some different code.
the key code is below. Suggestions on fixing how to get the data into the SQL table appreciated.
The API code works fine, It downloads a header row, and rows containing a country name and visitor numbers from that country. so its the SQL that i'm trying to write thats failing. No errors, just no data going in.
return service.data().ga().get(
ids='ga:' + profile_id,
start_date='2016-04-01',
end_date='today',
metrics='ga:users',
dimensions='ga:country').execute()
def print_results(results):
print()
print('Profile Name: %s' %results.get('profileInfo').get('profileName'))
print()
Print header.
output = []
for header in results.get('columnHeaders'):output.append('%30s' % header.get('name'))
print(''.join(output))
Print data table.
start databasing results
if results.get('rows', []):
for row in results.get('rows'):
output = []
for cell in row:output.append('%30s' % cell)
cur.execute('SELECT max(id) FROM Orign')
try:
row = cur.fetchone()
if row[0] is not None:start = row[0]
except:
start = 0
row = None
cur.execute('''INSERT OR IGNORE INTO Origin (id, Country, Users)
VALUES ( ?, ?, )''', ( Country, Users))
conn.commit()
cur.close()
print(''.join(output))
start = 0
else:
print('No Rows Found')
if __name__ == '__main__':
main(sys.argv)

Resources