From 7a9a41ccc960a22609050451ca29d00d0661da4e Mon Sep 17 00:00:00 2001 From: Camille Frantz Date: Wed, 20 Mar 2024 10:05:28 -0500 Subject: [PATCH] initial --- env.example | 3 +++ random_quotes.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 env.example create mode 100644 random_quotes.py diff --git a/env.example b/env.example new file mode 100644 index 0000000..2462a87 --- /dev/null +++ b/env.example @@ -0,0 +1,3 @@ +QUOTES_ACCESS_TOKEN=your_api_access_token +QUOTES_LIBRARY=link_to_your_quote_library # Can be a URL or a file +ENDPOINT=your_api_endpoint_to_post diff --git a/random_quotes.py b/random_quotes.py new file mode 100644 index 0000000..147bafb --- /dev/null +++ b/random_quotes.py @@ -0,0 +1,45 @@ +from json import loads +from dotenv import load_dotenv +from os import getenv +from random import randint +from requests import get, post + +def load_env(): + api_key = getenv('QUOTES_ACCESS_TOKEN') + quotes_library = getenv('QUOTES_LIBRARY') + if quotes_library.startswith('https',0): + quote_file = loads(get(quotes_library).text) + else: + quote_file = loads(open(quotes_library).read()) + return api_key, quote_file + +def build_post(api_key, quote_file, choice=0): + if choice == 0: + rand = randint(0, len(quote_file) - 1) + else: + rand = choice + quote = quote_file[rand]['quote'] + author = quote_file[rand]['author'] + toot = "'" + quote + "'\n\n - " + author + "\n\n#RandomQuote #quotes #quote #bot" + headers = { + "Content-Type": "application/json", + "Bearer": api_key, + "Authorization": "Bearer " + api_key + } + payload = { + "status": toot, + "visibility": "public" + } + return headers, payload + +def make_post(headers, payload): + post_endpoint = getenv('ENDPOINT') + try: + post(post_endpoint, json=payload, headers=headers) + except Exception as e: + print('An error occurred: ', e) + +if __name__ == '__main__': + api_key, quote_file = load_env() + headers, payload = build_post(api_key, quote_file) + make_post(headers, payload)