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

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.

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

Combine two JSON queries on Power BI

I am retrieving data from an Orchestrator (with a JSON code) to Power BI and for authentication I need to give the variable OrganizationUnitID as follows:
let
Path = "/odata/A",
Auth = Json.Document(Web.Contents(BaseUrl, [Headers=[#"Content-Type"="application/x-www-form-urlencoded"], Content=Text.ToBinary(Uri.BuildQueryString(Credentials))])),
Token = Auth[access_token],
A = Json.Document(Web.Contents(TenantUrl&Path, [Headers=[Accept="application/json", #"Authorization"="Bearer " & Token, #"OrganizationUnitId"="12345"]]))
in A
(PS: I did not post the entire query so that the post is not so long).
However, I would like to retrieve data for all OrganizationUnitIDs. These I can also retrieve as a query (= Id1 below), it currently comes as a list with 15 values:
let
Path = "/odata/Test",
Auth = Json.Document(Web.Contents(BaseUrl, [Headers=[#"Content-Type"="application/x-www-form-urlencoded"], Content=Text.ToBinary(Uri.BuildQueryString(Credentials))])),
Token = Auth[access_token],
Test = Json.Document(Web.Contents(TenantUrl&Path, [Headers=[Accept="application/json", #"Authorization"="Bearer " & Token]])),
value = Test[value],
#"Converted List to Table" = Table.FromList(value, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
#"Expanded Records to Table" = Table.ExpandRecordColumn(#"Converted List to Table", "Column1", {"Name","Id"}, {"Name","Id"}),
Id1 = #"Expanded Records to Table"[Id]
in
Id1
My question is: can I / how can I combine this second query with the first one, so that in the first one I can include all the 15 OrganizationUnitIds?
I have tried some solutions posted online but so far none have worked.

How to specify a destination DB while exporting data frame to mssql

I would like to export a data frame to mssql table.I used the code below but I would like to set the destination and not only the server and table name.I have a few DBs inside the server,how can i save the table in one of them?
df<-read.csv(file.choose(),header = T,sep= T)
DB= odbcConnect(dsn ='R_BISRV',uid = 'XXXX', pwd = 'XXX')
sqlSave(DB, df, tablename = 'Tanya', rownames = F,append = T)
close(DB)
I figured it out:
Data base name should be in the odbcDriverConnect() and table name in the sqlSave()
channel <- odbcDriverConnect('driver={SQL Server};server=YYY;database=YY;port=1433;
uid=XX;pwd=XXX')
# Client systems use TCP 1433 to connect to the database engine
sqlSave(channel = channel,dat = df, rownames = TRUE, tablename = "Tanya")

power query excel table mssql returns invalid column name

Here is my Customer Parameters table
let
Source = Excel.CurrentWorkbook(){[Name="Customer"]}[Content],
Customer1 = Source{0}[Customer]
in
Customer1
And my Query
let
Customer = Excel.CurrentWorkbook(){[Name="Customer"]}[Content],
Customer_Name = Customer{0}[Customer],
Source = Sql.Database("SERVER", "DATABASE", [Query="SELECT i.PriorityType as 'PRIORITY','COUNT' = COUNT(i.IncidentID)#(lf)FROM ININ_ISupport_S_Incident_Search2 (NULL) i#(lf)WHERE IncidentType IN ('Customer Support','Managed Services')#(lf)AND Organization = Customer_Name#(lf)AND IsResolved = 0#(lf)AND Active = 1#(lf)AND StateType = 'Open'#(lf)GROUP BY i.PriorityType#(lf)ORDER BY CASE#(lf) WHEN i.PriorityType = 'Code Red' THEN 1#(lf) WHEN i.PriorityType = 'Code Red RCA' THEN 2#(lf) WHEN i.PriorityType = 'High' THEN 3#(lf) WHEN i.PriorityType = 'Medium' THEN 4#(lf) WHEN i.PriorityType = 'Low' THEN 5#(lf)END ASC"])
in
Source
I am setting Organization = Customer_Name but I keep getting the following
Message=Invalid column name 'Customer_Name'
Is there a way to accomplish this
Customer_Name is not a column in your SQL table, so it fails with that message. If you want to use Customer_Name in the query, it needs to be added to the string. This is done using the & operator. In your case, you would do something like
"...AND Organization = '" & Customer_Name & "'#(lf)AND IsResolved...
That will cause problems if the customer name has a quote in it (like O'Neill), so you could do
"...AND Organization = '" & Text.Replace(Customer_Name, "'", "''") & "'#(lf)AND IsResolved...
to try and escape quotes.
Escaping quotes is not always sufficient, so if you're running this query on a database where outsiders can create customers you should avoid using the above method. If you filter the column by Customer_Name (through Table.SelectRows(tableName, each [Organization] = Customer_Name)), you should get the same result without any security concerns.

What's the raw GQL to check a ReferenceProperty?

I have the following models:
class Author(db.Model):
name = db.StringProperty()
class Story(db.Model):
author = db.ReferenceProperty(Author)
What's the raw GQL to find all Stories by a certain author. In regular SQL, I will use joins but I don't think that's available in GQL.
Edit:
I'm looking for the raw GQL way, I know how to do it the Pythonic way. For instance something like(the following is probably totally wrong):
"SELECT * FROM Story WHERE author = :1", "Shakespeare"
I want to run the above from the GAE admin Data > Data Viewer > Query the Datastore. I want the raw SQL that someone could run from a typical mysql or psql shell.
Edit2: Ah, the raw-GQL for use in the data-viewer...
Here's one way:
1) Run this and get the ID number:
SELECT * FROM Author where name = 'shakespeare'
2) Using ID number from previous query, run this:
SELECT * FROM Story where author = key('Author', 12345)
Edit: at long last, the raw GQL:
(Easiest way: Use the implicit backreference property name; in the form "modelname_set".)
qry = GqlQuery("SELECT * FROM Author WHERE name = :1", "shakespeare")
shakespeare = qry.get()
shakespeare.story_set # this property now contains all Shakespeare's stories
or
qry0 = GqlQuery("SELECT * FROM Author WHERE name = :1", "shakespeare")
shakespeare = qry0.get()
qry1 = GqlQuery("SELECT * FROM Story WHERE author = :1", shakespeare.key())
shakespeare_stories = qry1.fetch(10) # probably good to have some limit here
I prefer this way:
qry = Author.all()
qry.filter('name = ', 'shakespeare')
shakespeare = qry.get()
shakespeare.story_set # this property now contains all Shakespeare's stories
The more involved way may sometimes be necessary:
qry0 = Author.all()
qry0.filter('name = ', 'shakespeare')
shakespeare = qry0.get()
qry1 = Story.all()
qry1.filter('author = ', shakespeare.key())
shakespeare_stories = qry1.fetch(10) # probably good to have some limit here

Resources