imagebot_discord/img_source.py
2024-09-03 18:42:37 +01:00

84 lines
No EOL
2.3 KiB
Python

import os
import random
import requests
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# 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 []
# Main function
def main():
random_post = fetch_random_post()
if random_post:
print(f"URL: https://danbooru.donmai.us/posts/{random_post['id']}")
image_url = get_image_url(random_post)
# if image_url:
# r = requests.get(image_url)
# with open("out.jpg","wb") as f:
# f.write(r.content)
# print(f"Image URL: {image_url}")
# else:
# print("Failed to fetch a random post.")
artist_names = get_artist_names(random_post)
if artist_names:
artists = f"{', '.join(artist_names)}"
else:
artists = "Unknown"
return f"https://danbooru.donmai.us/posts/{random_post['id']}", image_url, artists
if __name__ == "__main__":
main()