imagebot/image_source.py
2025-03-22 22:36:15 +02:00

89 lines
2.3 KiB
Python

import os
import random
import requests
# Danbooru API base URL
base_url = "https://danbooru.donmai.us/posts.json"
# Parameters from .env file
search_query = os.getenv("searchquery")
banned_tags = os.getenv("bannedtags").split(",")
danbooru_user = os.getenv("danbooru_user")
danbooru_apikey = os.getenv("danbooru_apikey")
# Function to fetch a random post
def fetch_random_post():
try:
tags = search_query.split()
tags = tags[:2]
params = {
"tags": " ".join(tags),
"random": "true",
"login": danbooru_user,
"api_key": danbooru_apikey,
}
response = requests.get(base_url, params=params)
response.raise_for_status()
posts = response.json()
filtered_posts = [
post
for post in posts
if not any(tag in post["tag_string"] for tag in banned_tags)
]
if filtered_posts:
random_post = random.choice(filtered_posts)
return random_post
else:
print("No posts found matching the criteria.")
return None
except requests.exceptions.RequestException as e:
print(f"Error fetching data: {e}")
return None
def get_image_url(post):
if "large_file_url" in post:
return post["large_file_url"]
else:
print("Image URL not found in the post data.")
return None
def get_artist_names(post):
return post["tag_string_artist"].split(",") if "tag_string_artist" in post else []
def main():
try:
random_post = fetch_random_post()
if random_post:
print(f"URL: https://danbooru.donmai.us/posts/{random_post['id']}")
print(random_post["tag_string_character"])
image_url = get_image_url(random_post)
artist_names = get_artist_names(random_post)
if artist_names:
artists = f"{', '.join(artist_names)}"
else:
artists = "Unknown"
else:
return main()
except Exception:
return main()
return (
f"https://danbooru.donmai.us/posts/{random_post['id']}",
image_url,
artists,
random_post["tag_string_character"],
)
if __name__ == "__main__":
main()