<filename>ercot.py
"""
Original author: xnaas (2022)
License: The Unlicense (public domain)
"""
import requests
from sopel import plugin


BASE_URL = "https://www.ercot.com/api/1/services/read/dashboards"


@plugin.commands('ercot')
@plugin.output_prefix('[ERCOT] ')
@plugin.rate(server=3)
def ercot_status(bot, trigger):
    
    try:
        # Status
        url_status = f'{BASE_URL}/daily-prc.json'
        result = requests.get(url_status).json()['current_condition']
        status = result['state'].title()
        op_res = result['prc_value']
        # Frequency
        url_freq = f'{BASE_URL}/ancillaryServices.json'
        freq = requests.get(url_freq).json()['data'][719]['currentFrequency']
        # Demand
        url_demand = f'{BASE_URL}/todays-outlook.json'
        r = requests.get(url_demand).json()['data']
        demandIndex = max(index for index, value in enumerate(r) if value['forecast'] == 0)
        usage = r[demandIndex]['demand']
    except Exception as e:
        return bot.reply(str(e))

    bot.say(f'Status: {status} ({freq}Hz) | Demand: {usage:,}MW | Reserve: {op_res}MW')
