So I want to get the json keys and compare them with the variable q
Json file
{
"api_key": "YOUR AUTOBUY API KEY",
"prefix": "PREFIX FOR BOT COMMANDS (for e.x !redeem, ?claim, etc",
"redeem_message": "Thanks for redeeming your order for {0}, I have added the ROLE_NAME_HERE role.",
"role_id": "REPLACE THIS WITH THE ID OF THE ROLE YOU WANT TO GIVE UPON REDEEMING",
"redeem_channel_id": "REPLACE THIS WITH THE CHANNEL ID WHERE PEOPLE CAN USE THE REDEEM COMMAND",
"bot_token": "PUT YOUR DISCORD BOT TOKEN HERE"
}
Code
import json
def search(q):
with open("config.json") as f:
data = json.load(f)
for obj in data:
print(data[obj])
search(q="role_id")
Expected output: REPLACE THIS WITH THE ID OF THE ROLE YOU WANT TO GIVE UPON REDEEMING (cause q = role_id and I want it to return the value of the key)
Actual output:
YOUR AUTOBUY API KEY
PREFIX FOR BOT COMMANDS (for e.x !redeem, ?claim, etc
Thanks for redeeming your order for {0}, I have added the ROLE_NAME_HERE role.
REPLACE THIS WITH THE ID OF THE ROLE YOU WANT TO GIVE UPON REDEEMING
REPLACE THIS WITH THE CHANNEL ID WHERE PEOPLE CAN USE THE REDEEM COMMAND
PUT YOUR DISCORD BOT TOKEN HERE
Super simple, no need for a for loop if you just need one value:
import json
def search(q):
with open("config.json") as f:
data = json.load(f)
print(data[q])
search(q="role_id")
below
data = {'A':12,'B':13}
q = 'A2'
value = data.get(q)
if value is not None:
print(value)
else:
print('{} not found'.format(q))
Related
I've been getting the hang of Discord.py lately. Managing dictionaries, bot arguments, all that jazz. To finish off point management in my bot, I want to make a leaderboard. Following this answer, i structured my code slightly differently from them.
#bot.command(pass_context=True)
async def testboard(ctx, top:int=10):
total=[]
total = sorted(total,reverse=True)
board=discord.Embed(title = f'Top {top} highest awarded monkes.')
index = 1
if index == top:
return
else:
index += 1
for str in points:
userid = points[str]
user= bot.get_user(userid)
if index==1:
badge="\U0001F947"
elif index==2:
badge="\U0001F948"
elif index==3:
badge="\U0001F949"
else:
badge="\U0001F539"
board.add_field(name=f"**{badge}{index}. {user}**",value=(f"{points[str]} points"), inline=False)
await ctx.send(embed=board)
While it does display the points stored in my database, it doesn't do it from greatest to least, and doesn't display the name of the user.
As seen here: Result
I suspect it's because how my dictionary is structured.
{"userid": 0, "userid": 8, "userid": 0, "userid": 35, "userid": 11, "userid": 6}
Perhaps I can grab the name of the variable? If so, how can I do that?
The reason the username is just showing up as "None" is this portion of the code:
userid = points[str]
user= bot.get_user(userid)
If the str variable from the for loop is the user id, then the userid variable you are creating here is the point score for that user, not the id itself, so bot.get_user returns None because it won't find a user with, for example, an ID of 0. Change those lines to the following:
user= bot.get_user(int(str))
Secondly, the points are not in order because dictionaries are not ordered at all, so you would have to sort the objects manually. One way to do that is to get the entries of the dictionary, including both the key (the userid) and the value (number of points), sort it by points, and then iterate through it in a for loop:
for (userid, score) in sorted(points.items(), key=lambda entry: entry[1], reverse=True):
user= bot.get_user(int(userid))
if index==1:
badge="\U0001F947"
elif index==2:
badge="\U0001F948"
elif index==3:
badge="\U0001F949"
else:
badge="\U0001F539"
board.add_field(name=f"**{badge}{index}. {user}**",value=(f"{score} points"), inline=False)
I changed a couple of variable names here, most importantly str which is the class name for the string type, so it could potentially cause conflicts. Also, per your comment, the get_user method seems to require an integer and won't do conversion automatically.
I encountered such a problem, I do not know how to set the name of this collection through the code when creating a collection, that is, I write:
cluster = MongoClient("link")
db = cluster.BananiData
collection = db.ctx.guild.id
but the name is set as ctx.guild.id, I need to insert the server ID in the name, how can this be implemented?
P.S: I use python
code:
cluster = MongoClient("mongodb+srv://Bananchik:hdkkIFkk6VKywSDH#cluster0.olcto.mongodb.net/<BananiData>?retryWrites=true&w=majority")
db = cluster.BananiData
collection = db.ctx.guild.id
#collection = cluster.BananiData.LevelSystem
class DataBases(commands.Cog):
""" ФСБ? """
def __init__(self, bot):
self.bot = bot
#commands.command()
#commands.check(permissions.is_owner)
async def test_db(self, ctx):
await ctx.send(collection)
await ctx.send("DB id created")
for member in ctx.guild.members:
print(member)
post = {
"_id": member.id,
"xp": 0,
"lvl": 1,
"message_count": 0
}
if collection.count_documents({"_id": member.id}) == 0:
collection.insert_one(post)
print(f"Пользователь **{member.name}** добавлен в базу данных")
It is a good practice to enclose the name you want to assign to a collection inside a
square bracket if you are using python.
Example:
If you want to create a collection by the name "SampleCollection", you could use the below command, even though
. operator works.
collection = db["SampleCollection"]
Therefore,
You should change the collection initialization code like the following:
collection = db[ctx.guild.id]
Note: Make sure that ctx.guild.id variable is of type str else it won't work.
so right now I am trying to create a command which allows the user to modify their channel's details on an embed. The only problem I have here is that I need to manually specific a number for where the embed field is. Is there a way for the bot to scan through the whole embed for a specific name and return the fields position? (I have a example linked below)
message = guild.get_message(63861098570842132)
embed = next(embed for embed in message.embeds)
embed.fields[0].value = "New value" #Issue Here
await message.edit(embed=embed)
https://gyazo.com/967101d666e78dcccef945f3c5d6e280 >Example of the embed
Get the embed in form of a dict, loop through every field and if it's the field you want, simply change it's value. Then convert the dict to a discord.Embed obj and edit the message
# This is the user input
user_input = {'field name': 'some name', 'field value': 'some value'}
# Getting the embed and converting it to a dict
embed = message.embeds[0]
embed_dict = embed.to_dict()
for field in embed_dict['fields']:
if field['name'] == user_input['field name']:
field['value'] = user_input['field value']
# Converting the embed to a `discord.Embed` obj
edited_embed = discord.Embed.from_dict(embed_dict)
# Editing the message
await message.edit(embed=edited_embed)
Reference:
discord.Embed.to_dict
discord.Embed.from_dict
message.edit
I need to loop through commits and get name, date, and messages info from
GitHub API.
https://api.github.com/repos/droptable461/Project-Project-Management/commits
I have many different things but I keep getting stuck at string indices must be integers error:
def git():
#name , date , message
#https://api.github.com/repos/droptable461/Project-Project-Management/commits
#commit { author { name and date
#commit { message
#with urlopen('https://api.github.com/repos/droptable461/Project Project-Management/commits') as response:
#source = response.read()
#data = json.loads(source)
#state = []
#for state in data['committer']:
#state.append(state['name'])
#print(state)
link = 'https://api.github.com/repos/droptable461/Project-Project-Management/events'
r = requests.get('https://api.github.com/repos/droptable461/Project-Project-Management/commits')
#print(r)
#one = r['commit']
#print(one)
for item in r.json():
for c in item['commit']['committer']:
print(c['name'],c['date'])
return 'suc'
Need to get person who did the commit, date and their message.
item['commit']['committer'] is a dictionary object, and therefore the line:
for c in item['commit']['committer']: is transiting dictionary keys.
Since you are calling [] on a string (the dictionary key), you are getting the error.
Instead that code should look more like:
def git():
link = 'https://api.github.com/repos/droptable461/Project-Project-Management/events'
r = requests.get('https://api.github.com/repos/droptable461/Project-Project-Management/commits')
for item in r.json():
for key in item['commit']['committer']:
print(item['commit']['committer']['name'])
print(item['commit']['committer']['date'])
print(item['commit']['message'])
return 'suc'
In python xmpp module, I'm able to retrieve the nickname of any contacts as follows:
self.connection.auth(userJid.getNode(), self.password)
self.roster = self.connection.getRoster()
name = self.roster.getName(buddyJid)
..where buddyJid is of the form user#gmail.com.
Now, I need to retrieve the nickname of the user who authenticates the connection (userJid). I cannot find the name using the above method.
Which method can I use retrieve the name of the current user?
This information is not in the roster. You will need to query the clients individually and get their vCard by sending this IQ :
<iq from='stpeter#jabber.org/roundabout'
id='v1'
type='get'>
<vCard xmlns='vcard-temp'/>
</iq>
Thank you nicholas_o, this is a sample function I put together based your suggestion. (The XML logic isn't ideal, but it was sufficient for the simple task I needed this for)
def vcard(disp, jid):
msg = xmpp.protocol.Iq()
msg.setType('get')
msg.setTo(jid)
qc = msg.addChild('vCard')
qc.setAttr('xmlns', 'vcard-temp')
rep = disp.SendAndWaitForResponse(msg)
# to see what other fields are available in the XML output:
# print rep
userid=fname=lname=title=department=region=None
for i in rep.getChildren():
for j in i.getChildren():
if j.getName() == "TITLE":
title = j.getData().encode('utf-8')
for k in j.getChildren():
if k.getName() == "GIVEN":
fname = k.getData().encode('utf-8')
if k.getName() == "FAMILY":
lname = k.getData().encode('utf-8')
if k.getName() == "ORGUNIT":
department = k.getData().encode('utf-8')
if k.getName() == "REGION":
region = k.getData().encode('utf-8')
return fname, lname, title, department, region