
I edited the above post, hoping for a review.
The code was already in English, but I translated all the variables' names into English.
I also tried perplexity AI, but it failed miserably as well.
Looks like i need to learn Phyton the hard old way.
Apparently I cannot fetch the user list:
-snip-
2025-01-25 17:41:30,824 - INFO - Retrieved 0 users.
1. Wrong endpoint, you're fetchingposts instead ofposts/authors.
2. Wrong object keys path, your code assumes the API returns an object with this format:
{
"results": [
{
"username": "TryNinja",
"post_count": 123
}
]
}
But this is the right format:
{
"data": {
"authors": [
{
"author": "TryNinja",
"count": 123
}
]
}
}
Here is the working code:
import requests
from datetime import datetime, timedelta
import logging
# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
BASE_URL = "https://api.ninjastic.space"
def calculate_date_range():
today = datetime.now()
first_day_of_current_month = datetime(today.year, today.month, 1)
first_day_of_previous_month = (first_day_of_current_month - timedelta(days=1)).replace(day=1)
start_date = first_day_of_previous_month.isoformat()
end_date = first_day_of_current_month.isoformat()
return start_date, end_date
def get_users_and_posts_from_italian_board():
start_date, end_date = calculate_date_range()
endpoint = f"{BASE_URL}/posts/authors"
params = {
"after_date": start_date,
"before_date": end_date,
"board": 28,
"child_boards": "true"
}
try:
logging.info("Fetching data from the Ninjastic API...")
response = requests.get(endpoint, params=params)
response.raise_for_status()
data = response.json()
results = data.get("data").get("authors", [])
logging.info(results)
users_posts = {result.get("author", "unknown"): result.get("count", 0) for result in results}
logging.info(f"Retrieved {len(users_posts)} users.")
return users_posts
except requests.exceptions.RequestException as error:
logging.error(f"Error retrieving data: {error}")
return {}
def write_results_to_file(users_posts, filename="users_posts.txt"):
try:
with open(filename, "w", encoding="utf-8") as file:
if not users_posts:
file.write("No users or posts found. Check API response or date range.\n")
else:
for user, posts in sorted(users_posts.items(), key=lambda x: x[1], reverse=True):
file.write(f"{user}: {posts}\n")
logging.info(f"Results written to {filename}")
except IOError as error:
logging.error(f"Error writing to file: {error}")
if __name__ == "__main__":
print("Script started...")
users_posts = get_users_and_posts_from_italian_board()
write_results_to_file(users_posts, filename="italian_board_users_posts.txt")
print("Results saved to italian_board_users_posts.txt")
2025-01-25 19:14:37,918 - INFO - Retrieved 69 users.