What I want to accomplish is to calculate the ranking of the most active users in a group.
My approach to it was to first iterate through all message history in a group, get the user name, assign the message to it and then sort it in python from highest (most often sent from a given user) to lowest, but I have no idea how to make it programmatically and I've been stuck in this code:
async def calculate_ranking(event):
#client.on(events.NewMessage)
async def calculate_ranking(event):
messages = {}
if "!ranking" in event.raw_text:
chat_id = event.chat_id
async for message in client.iter_messages(chat_id, reverse=True):
author = message.sender.username
messages[author] += 1
print(messages)
I have no idea on how to assign a message to a user
so the output would be as for example:
user1: 12 messages
user2: 10 messages
For the rank itself, you can use collections.Counter()
import collections
collections.Counter(['jon', 'alan', 'jon', 'alan', 'bob'])
# Output: Counter({'jon': 2, 'alan': 2, 'bob': 1})
So all you have left to do is to get the username.
# Your job! :)
data = dict(
username = ['jon', 'alan', 'jon', 'alan', 'bob'],
message = ['hello!', 'hey jon!', 'How are you doing?', 'Im fine', 'hola!']
)
Counter(data.username)
Related
I'm trying to assign a client role 'edit' to a group 'abc'.
All entities exists(clients, roles, group)
group_id = admin.get_group_by_path('/abc')['id']
id_client = admin.get_client_id('myclient')
admin.assign_group_client_roles(group_id, id_client,
{'name': 'edit'})
I get an error keycloak.exceptions.KeycloakPostError: 404: b'{"error":"Role not found"}'
Where can be an error?
Looking a bit a the open source code, I think you can try the following:
group_id = admin.get_group_by_path('/abc')['id']
id_client = admin.get_client_id('myclient')
clt_role = admin.get_client_role(client_id=id_client, role_name="edit")
admin.assign_group_client_roles(group_id, id_client, clt_role)
I have this code which returns a Nonetype, when I thought it would return a string. And I have been trying to find solutions on stack, but I am yet to find one.
Here is the code:
members = ['Alex', 'Danny', 'Kieran', 'Zoe', 'Caroline']
visitors = ['Scott', 'Helen', 'Raj', 'Danny']
def check_group(members, visitors):
for person in visitors:
if person in members:
print(f"Member present: {person}")
break
else:
print("No members visited")
output: Member present: Danny
You have forgottent a sin when typing members line 2.
Also, your code won't return anythings, just print the value you asked it to print.
You need to have a return statement.
So if this is part of a function then it should be something like this
def find():
members = ['Alex', 'Danny', 'Kieran', 'Zoe', 'Caroline'] visitors = ['Scott', 'Helen', 'Raj', 'Danny']
for person in visitor:
if person in member:
print(f"Member present: {person}")
retrun person
else:
print("No members visited")
return None
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))
I am restoring data for users' in a nested dictionary as follows:
user_dict = {user_name:{product:amount, product:amount}}
So, user_name is the user's user_name. The product is the what the user put in the basket(e.g. orange juice), and the amount is the amount of a specific product. So, for instance:
user_dict = {"sara" : {"orange juice": 2, "apple juice" : 4}, "ali": {"banana":3}}
what I want to do is that when a user buys some stuff and put them in the (user_dict) then logs out, when the same user logs in again, I want to get the user's basket as follows: let's say sara logged in and put some stuff in her basket(user_dict) then logged out, when sara logs in again, I want to make get sara's information from the (user_dict) in a new dictionary(called basket) like this:
basket = {"orange juice": 2, "apple juice" : 4}
Also, I want to make the basket empty if the user (user_name) who logged in does not have anything in the basket. So, I want to make users' things do not interfere and I do not want to lose any information. I have almost finished my project but this is what I am stuck at, so help me guys, please.
Here are my lines of code for this task:(but the code does not work as I want)
for key in user_dict.keys():
if user_name == key:
key_sto = " "
nested_dict = user_dict[user_name]
val = a.values()
val_in_nested = val[0]
key_in_nested = key_sto.join(a)
basket[key_in_nested] = val_in_nested
elif user_name != key :
basket = {}
I was able to solve the problem, so here is the code.
for key, amount in user_dict.items():
if key == user_name:
basket = amount
if user_name not in user_dict.keys():
basket = {}
I am new to Python 2.7 and I want the 1st column as the key column in employees and it has to check on dept 1st column and generate results.
Employees comes from a text file and dept comes from a database. I tried a lot but didn't get an easy answer. What is wrong with my code?
**Inputs :**
employees=['1','peter','london']
employees=['2','conor','london']
employees=['3','ciara','london']
employees=['4','rix','london']
dept=['1','account']
dept=['2','developer']
dept=['3','hr']
**Expected Output :**
results=['1','peter','london','account']
results=['2','conor','london','developer']
results=['3','ciara','london','hr']
results=['4','rix','london',null]
your input makes no sense. Each line overwrites the previous one data-wise. Here it seems that the digits (as string) are the keys, and some default action must be done when no info is found in dept.
To keep the spirit, just create 2 dictionaries, then use dictionary comprehension to generate the result:
employees = dict()
dept = dict()
employees['1'] = ['peter','london']
employees['2'] = ['conor','london']
employees['3'] = ['ciara','london']
employees['4'] = ['rix','london']
dept['1']=['account']
dept['2']=['developer']
dept['3']=['hr']
result = {k:v+dept.get(k,[None]) for k,v in employees.items()}
print(result)
which yields a dictionary with all the info. Note that null is None in python:
{'1': ['peter', 'london', 'account'], '4': ['rix', 'london', None], '3': ['ciara', 'london', 'hr'], '2': ['conor', 'london', 'developer']}
You could go for a class. Consider this:
class Employee:
def __init__(self, number, name, location, dept):
self.number = str(number)
self.name = name
self.location = location
self.dept = dept
def data(self):
return [self.number,
self.name,
self.location,
self.dept]
peter = Employee(1, 'peter', 'london', 'account')
print(peter.data())
['1', 'peter', 'london', 'account']
>>>