# Help with how to build a script

**URL:** <https://community.homey.app/t/help-with-how-to-build-a-script/130690>\
**Category:** Questions & Help\
**Created:** [February 15, 2025, 1:29pm UTC](https://community.homey.app/t/help-with-how-to-build-a-script/130690 "2025-02-15T13:29:22Z")\
**Posts on this page:** 1\
**Showing post:** 11

<div class="post-metadata">

**Author:** ![Carl](https://sea1.discourse-cdn.com/flex025/user_avatar/community.homey.app/carl/32/124386_2.png) [@Carl](https://community.homey.app/u/Carl)\
**Post date:** [February 16, 2025, 7:05pm UTC](https://community.homey.app/t/help-with-how-to-build-a-script/130690/11 "2025-02-16T19:05:27Z")

</div>

Thanks for all the help so far.

I used Chat GPT to build some scripts for me.

This script returns the unit rates I’m on based on the hours of the day:

// Replace with your actual API key  
const apiKey = ‘YOUR API HERE’;

// Define the product code and tariff code for Octopus Go  
const productCode = ‘GO-VAR-22-10-14’;  
const tariffCode = ‘E-1R-GO-VAR-22-10-14-A’;

// Define the date range for fetching tariff data  
const periodFrom = new Date().toISOString();  
const periodTo = new Date(Date.now() + 24 \* 60 \* 60 \* 1000).toISOString(); // Next 24 hours

// Construct the API endpoint URL  
const url = `https://api.octopus.energy/v1/products/${productCode}/electricity-tariffs/${tariffCode}/standard-unit-rates/?period_from=${periodFrom}&period_to=${periodTo}`;

// Fetch the tariff data  
fetch(url, {  
headers: {  
‘Authorization’: `Basic ${Buffer.from(apiKey + ':').toString('base64')}`  
}  
})  
.then(response =\> {  
if (!response.ok) {  
throw new Error(`Error fetching data: ${response.statusText}`);  
}  
return response.json();  
})  
.then(data =\> {  
// Process and use the tariff data as needed  
data.results.forEach(rate =\> {  
console.log(`Price: ${rate.value_inc_vat} p/kWh`);  
console.log(`Valid From: ${new Date(rate.valid_from).toLocaleString()}`);  
console.log(`Valid To: ${new Date(rate.valid_to).toLocaleString()}`);  
});  
})  
.catch(error =\> {  
console.error(‘Error:’, error);  
});

As you can see here:

 ![Screenshot 2025-02-16 at 19.01.17](https://us1.discourse-cdn.com/flex025/uploads/athom/original/3X/0/8/08b11c7057fbe32bf54aab1301e6ffa6e0c56190.png)

Then this script is giving what appears to be live data, although I am not sure it is the actual data as it doesn’t match the live data I can see on Voltaware or Octopus Mini IHD

// Replace with your actual API key, MPAN, and Meter Serial Number  
const apiKey = ‘YOUR API HERE’;  
const mpan = ‘YOUR MPAN HERE’;  
const meterSerial = ‘YOUR METER SERIAL HERE’;

// Define the date range (last 24 hours to capture recent readings)  
const periodFrom = new Date(Date.now() - 24 \* 60 \* 60 \* 1000).toISOString().split(‘.’)[0] + ‘Z’;  
const periodTo = new Date().toISOString().split(‘.’)[0] + ‘Z’;

// Construct the Octopus API endpoint  
const url = `https://api.octopus.energy/v1/electricity-meter-points/${mpan}/meters/${meterSerial}/consumption/?period_from=${periodFrom}&period_to=${periodTo}&page_size=1`;

console.log(`🔍 Fetching live energy data from: ${url}`);

fetch(url, {  
headers: {  
‘Authorization’: `Basic ${Buffer.from(apiKey + ':').toString('base64')}`  
}  
})  
.then(response =\> {  
console.log(`🔄 API Response Status: ${response.status} ${response.statusText}`);  
if (!response.ok) {  
return response.text().then(text =\> {  
throw new Error(`⚠️ API Error: ${response.statusText} (Code: ${response.status}) - ${text}`);  
});  
}  
return response.json();  
})  
.then(async (data) =\> {  
if (data.results && data.results.length \> 0) {  
const latestConsumption = data.results[0];

```
  console.log(`✅ Latest Consumption: ${latestConsumption.consumption} kWh`);
  console.log(`🕒 Interval Start: ${new Date(latestConsumption.interval_start).toLocaleString()}`);
  console.log(`🕒 Interval End: ${new Date(latestConsumption.interval_end).toLocaleString()}`);

  // ✅ Store the consumption in a Homey variable (Tag) using the new function
  await tag('LiveEnergyUsage', latestConsumption.consumption);
  console.log(`✅ Homey tag "LiveEnergyUsage" updated successfully`);
} else {
  console.log('ℹ️ No consumption data available.');
}

```

})  
.catch(error =\> {  
console.error(‘🚨 Error:’, error.message);  
});

This is the output of that script which is not correct as that 0.168kWh latest consumption never changes. So I need to find out why it’s doing that as it only seems to pull the data from that one 30 min interval

 ![Screenshot 2025-02-16 at 19.04.00](https://us1.discourse-cdn.com/flex025/uploads/athom/original/3X/9/7/97e052424422b1bb7aea040deb8dc51101812c45.png)

---

_[View the full topic](https://community.homey.app/t/help-with-how-to-build-a-script/130690)._
