I tried to use chat GPT to use the API and I got a very bad answer:
Write state-of-the-art, well-commented code to use ninjastic API (documentation at
https://docs.ninjastic.space )to query the database to get a list of users who wrote on the Italian board (sub-boards included) from midnight of the first day of the previous day to midnight of the first day of the current month. For example on 25 December they should query from midnight on the first of November to the first of December at midnight
After a few correction and iterations i got this not working code.
import requests
from datetime import datetime, timedelta
# Constant for the base URL of the Ninjastic API
BASE_URL = "https://api.ninjastic.space"
# Helper function to calculate the date range
def calculate_date_range():
"""
Calculates the date range from midnight of the first day of the previous month
to midnight of the first day of the current month.
Returns:
start_date (str): The start date in ISO 8601 format.
end_date (str): The end date in ISO 8601 format.
"""
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() # Removes 'Z'
end_date = first_day_of_current_month.isoformat() # Removes 'Z'
return start_date, end_date
# Function to retrieve users and the number of posts from the Italian board
def get_users_and_posts_from_italian_board():
"""
Queries the Ninjastic API to retrieve a list of users who posted on the Italian board
(including sub-boards) and the total number of posts for each user within the specified date range.
Returns:
dict: A dictionary with users as keys and the number of posts as values.
"""
start_date, end_date = calculate_date_range()
# Endpoint and parameters for the API request
endpoint = f"{BASE_URL}/posts"
params = {
"after_date": start_date,
"before_date": end_date,
"board": 28, # ID of the Italian board
"child_boards": "true" # Include sub-boards
}
try:
response = requests.get(endpoint, params=params)
response.raise_for_status() # Raise an exception for HTTP errors
# Parse the JSON response
data = response.json()
results = data.get("results", []) # Extract the list of users from the response
users_posts = {}
for result in results:
user = result.get("username", "unknown")
post_count = result.get("post_count", 0)
users_posts[user] = post_count
return users_posts
except requests.exceptions.RequestException as error:
print(f"Error retrieving data: {error}")
return {}
# Main script to execute if the file is run directly
if __name__ == "__main__":
users_posts = get_users_and_posts_from_italian_board()
for user, posts in users_posts.items():
print(f"{user}: {posts}")
I understand this thread is not a support group, but maybe you can point me in the right direction?
EDIT: Yes, Now I don't get any errors anymore, yet the code doesn't end anywhere