Skip to content

Commit

Permalink
Merge pull request #34 from ramazanoacar/add/all-data-of-user-for-a-s…
Browse files Browse the repository at this point in the history
…pecific-month

Add all data of user for a specific month
  • Loading branch information
berkingurcan authored Oct 11, 2024
2 parents 61db12d + 33cf756 commit 4897d4a
Show file tree
Hide file tree
Showing 5 changed files with 137 additions and 8 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,17 @@ Additionally, need to enable google drive api to use sheet sharing functionality
**Usage:**
`/get-blockchain-summary`
#### **`/get-user-monthly-data-to-csv`**
**Description:** Export a specific user's monthly qualified contribution data for each day of a month
**Usage:**
`/get-user-monthly-data-to-csv username: <username> date: <date>`
* **username:** User handle of requested user.
* **date:** "YYYY-MM" format date.
--------------
## Contributions
Expand Down
27 changes: 27 additions & 0 deletions leader_bot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
write_users_to_csv,
write_ai_decisions_to_csv,
write_users_to_csv_monthly,
write_all_data_of_user_to_csv_by_month,
)
from leaderboard_functions import (
create_leaderboard_by_month,
Expand Down Expand Up @@ -607,4 +608,30 @@ async def on_command(interaction: discord.Interaction):
await interaction.followup.send(f"An error occurred: {e}", ephemeral=True)


@tree.command(
name="get-user-monthly-data-to-csv",
description="Gets all db data for specific user for a month and export it to csv.",
guild=discord.Object(id=config.GUILD_ID),
)
async def on_command(interaction: discord.Interaction, username: str, date: str):
try:
await interaction.response.defer()

file_path = "user_monthly_data.csv"
result = write_all_data_of_user_to_csv_by_month(file_path, username, date)
if "successfully" in result:
await interaction.channel.send(file=discord.File(file_path))
os.remove(file_path)
await interaction.followup.send(
"User monthly data is here: ", ephemeral=True
)
else:
await interaction.followup.send(
"User monthly data is not found", ephemeral=True
)
except Exception as e:
logger.error(f"Error in get-user-monthly-data-to-csv command: {e}")
await interaction.followup.send(f"An error occurred: {e}", ephemeral=True)


client.run(config.DISCORD_TOKEN)
60 changes: 60 additions & 0 deletions leader_bot/helpers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import pandas as pd
import github_tracker_bot.mongo_data_handler as rd
from typing import List
import calendar


def csv_to_structured_string(file_path):
Expand All @@ -16,3 +19,60 @@ def csv_to_structured_string(file_path):
structured_string += row_string + "\n"

return structured_string


def get_user_data_for_a_month(users: List[rd.User], username: str, month: str):

for user in users:
if (
user.user_handle == username
and user.qualified_daily_contribution_number_by_month.get(month)
):

return user

return None


def get_monthly_user_data_from_ai_decisions(ai_decisions):
if not ai_decisions or not ai_decisions[0]:
raise ValueError("Empty ai_decisions list")

date_nonqualified_qualified = {}

for decision_list in ai_decisions:
for decision in decision_list:
date = decision.response.date
if date not in date_nonqualified_qualified:
date_nonqualified_qualified[date] = [
0,
0,
] # first element is nonqualified, second is qualified

if decision.response.is_qualified:
date_nonqualified_qualified[date][1] += 1
else:
date_nonqualified_qualified[date][0] += 1
return dict(sorted(date_nonqualified_qualified.items()))


def get_since_until_y_m_d(date: str):
"""
Args:
date (str): The input date as a string in the format 'YYYY-MM'
(e.g., '2024-10' for October 2024).
Returns:
tuple: A tuple containing two strings:
- 'since': The first day of the month in 'YYYY-MM-DD' format (e.g., '2024-04-01').
- 'until': The last day of the month in 'YYYY-MM-DD' format (e.g., '2024-04-30').
Example:
>>> get_since_until_y_m_d('2024-10')
('2024-10-01', '2024-10-31')
"""
year, month = map(int, date.split("-"))
last_day = calendar.monthrange(year, month)[1]
since = f"{date}-01"
until = f"{date}-{last_day}"
return since, until
45 changes: 38 additions & 7 deletions leader_bot/sheet_functions.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
import os
import sys
import csv
from typing import List

from github_tracker_bot.mongo_data_handler import AIDecision

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

import config

from typing import List
from log_config import get_logger
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
from db_functions import fetch_db_get_users, get_ai_decisions_by_user_and_timeframe
from github_tracker_bot.mongo_data_handler import AIDecision
from helpers import get_monthly_user_data_from_ai_decisions, get_since_until_y_m_d
from config import GOOGLE_CREDENTIALS

from db_functions import fetch_db_get_users
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

logger = get_logger(__name__)

Expand Down Expand Up @@ -478,3 +476,36 @@ def delete_user(discord_handle: str):
logger.error(f"Failed to clear Google Sheets data: {e}")

update_data(config.SPREADSHEET_ID, RANGE_NAME, updated_data)


def write_all_data_of_user_to_csv_by_month(file_path: str, username: str, date: str):
try:
since, until = get_since_until_y_m_d(date)
ai_decisions = get_ai_decisions_by_user_and_timeframe(username, since, until)
date_dict = get_monthly_user_data_from_ai_decisions(ai_decisions)
if not date_dict:
return "No data found for the specified month."

with open(file_path, mode="w", newline="") as file:
writer = csv.writer(file)
writer.writerow(
["username", "date", "is_qualified", "total_qualified_so_far"]
)
total_qualified = 0
for date, [nonqualified, qualified] in date_dict.items():
qualified = True if qualified != 0 else False
total_qualified += qualified
writer.writerow(
[
username,
date,
qualified,
total_qualified,
]
)

return "successfully"

except Exception as e:
logger.error(f"Failed to write to CSV: {e}")
return f"Failed to write to CSV: {e}"
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@

setup(
name="pgt_leaderbot",
version="0.3.2",
version="0.3.3",
packages=find_packages(),
)

0 comments on commit 4897d4a

Please sign in to comment.