SC-Discord-Bot/llm_tools/get_buyable_ships.py

85 lines
2.6 KiB
Python

#!/usr/bin/env python3
import requests
import sqlite3
# --- Configuration ---
API_URL = "https://api.uexcorp.space/2.0/vehicles_purchases_prices_all"
with open("uex_api_key", "r") as f:
BEARER_TOKEN = f.read().strip()
DB_NAME = "buyable_ships.db"
TABLE_NAME = "buyable_ships"
def setup_database():
"""
Sets up the SQLite database and creates the table if it doesn't exist.
The table uses a composite primary key (id_vehicle, id_terminal)
to ensure each vehicle at each terminal has only one latest entry.
"""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
# Using "IF NOT EXISTS" prevents errors on subsequent runs.
# The schema is derived from your provided image.
# We use INSERT OR REPLACE later, so a primary key is important.
# (id_vehicle, id_terminal) is a good candidate for a unique key.
cursor.execute(f"""
CREATE TABLE IF NOT EXISTS {TABLE_NAME} (
id_vehicle TEXT,
id_terminal TEXT,
price_buy REAL,
vehicle_name TEXT,
terminal_name TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id_vehicle, id_terminal)
)
""")
conn.commit()
conn.close()
print("Database setup complete.")
def fetch_data_from_api():
"""
Fetches the latest vehicle purchase price data from the UAX Corp API.
Returns the data as a list of dictionaries or None if an error occurs.
"""
headers = {"Authorization": f"Bearer {BEARER_TOKEN}"}
try:
response = requests.get(API_URL, headers=headers)
response.raise_for_status() # Raise an error for HTTP errors
data = response.json()
return data.get("data", [])
except requests.RequestException as e:
print(f"Error fetching API data: {e}")
return None
def save_data_to_db(data):
"""
Saves the fetched vehicle purchase price data to the SQLite database.
"""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
for item in data:
cursor.execute(f"""
INSERT OR REPLACE INTO {TABLE_NAME} (id_vehicle, id_terminal, price_buy, vehicle_name, terminal_name)
VALUES (?, ?, ?, ?, ?)
""", (
item.get("id_vehicle"),
item.get("id_terminal"),
item.get("price_buy"),
item.get("vehicle_name"),
item.get("terminal_name")
))
conn.commit()
conn.close()
print("Data saved to database.")
if __name__ == "__main__":
setup_database()
data = fetch_data_from_api()
if data:
save_data_to_db(data)