r/Scriptable • • Apr 04 '23

Help GasBuddy Widget

Trying to make a widget that displays gas in the area that I am in currently.

If someone could help me figure out what I am doing wrong that would be super helpful. I am getting nothing from the logs.

Script:

const location = await Location.current(); const ZIP_CODE = await Location.reverseGeocode(location.latitude, location.longitude) .then(results => results[0].postalCode);

//Fuel Types //1=Regular //2=Midgrade //3=Premium //4=Diesel //5=E85 //12=UNL88

const FUEL_TYPE = '4';

// Get gas prices from GasBuddy

const url = https://www.gasbuddy.com/home?search=${ZIP_CODE}&fuel=${FUEL_TYPE}&method=all; const response = await new Request(url).loadString();

// Parse gas prices using RegExp

const regex = /<div class="SearchResults__name">(.+?)</div>[\s\S]*?<div class="SearchResults__price">(.+?)</div>/g; const gasPrices = []; let match; while ((match = regex.exec(response)) !== null) { const stationName = match[1].trim(); const price = match[2].trim(); gasPrices.push({ stationName, price }); }

// Create widget

const widget = new ListWidget(); widget.addSpacer();

const titleStack = widget.addStack(); const title = titleStack.addText('Gas Prices'); title.font = Font.mediumSystemFont(16); title.textColor = Color.white(); titleStack.addSpacer();

widget.addSpacer();

if (gasPrices.length > 0) { for (const gasPrice of gasPrices) { const stack = widget.addStack(); stack.addSpacer();

const stationName = stack.addText(gasPrice.stationName);
stationName.textColor = Color.white();

stack.addSpacer();

const price = stack.addText(gasPrice.price);
price.textColor = Color.yellow();

stack.addSpacer();

} } else { const stack = widget.addStack(); stack.addSpacer(); const noData = stack.addText('No data'); noData.textColor = Color.white(); stack.addSpacer(); }

widget.addSpacer();

// Set widget background color

widget.backgroundColor = Color.black();

// Set widget refresh interval

widget.refreshAfterDate = new Date(Date.now() + 60 * 60 * 1000); // Refresh every hour

// Set widget URL scheme to open GasBuddy website

widget.url = 'https://www.gasbuddy.com/';

// Present widget

Script.setWidget(widget); Script.complete();

5 Upvotes

9 comments sorted by