fasting-tracker
Version:
Türkiye'deki şehirler için iftar ve sahur saatlerini getiren, hatırlatma ve Discord Webhook desteği sunan Node.js paketi.
74 lines (61 loc) • 2.46 kB
JavaScript
const fetch = require("node-fetch");
const API_URL = "https://utku.berkaykoc.net/api/entertainment/fast-track";
/**
* Fetches iftar and sahur times for a given city.
* @param {string} city - The city name.
* @returns {Promise<Object>} - Returns an object with imsak (sahur) and iftar times.
*/
async function getFastTrack(city) {
try {
if (!city || typeof city !== "string") {
throw new Error("City name is required.");
}
const response = await fetch(`${API_URL}?city=${encodeURIComponent(city)}`);
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
throw new Error(`FastTrack API error: ${error.message}`);
}
}
/**
* Sets a reminder for iftar or sahur, with optional Discord webhook notifications.
* @param {string} city - The city name.
* @param {string} type - "imsak" or "iftar".
* @param {number} minutesBefore - Minutes before the time to send a reminder.
* @param {string} [webhookUrl] - Optional Discord webhook URL.
*/
async function setReminder(city, type = "iftar", minutesBefore = 10, webhookUrl = "") {
const times = await getFastTrack(city);
if (!times[type]) {
throw new Error(`Invalid time type: ${type}`);
}
const now = new Date();
const [hour, minute] = times[type].split(":").map(Number);
const targetTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hour, minute, 0);
const reminderTime = new Date(targetTime - minutesBefore * 60 * 1000);
const delay = reminderTime - now;
if (delay <= 0) {
throw new Error(`The specified time has already passed.`);
}
console.log(`✅ Reminder set for ${city} - ${type} in ${minutesBefore} minutes.`);
setTimeout(async () => {
const message = `🔔 **Reminder:** It's almost time for **${type.toUpperCase()}** in **${city}**!`;
console.log(message);
if (webhookUrl) {
try {
await fetch(webhookUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content: message })
});
console.log("✅ Notification sent to Discord webhook.");
} catch (error) {
console.error("❌ Failed to send Discord webhook:", error.message);
}
}
}, delay);
}
module.exports = { getFastTrack, setReminder };