1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const API_KEY = Deno.env.get("OPENWEATHERMAP_APP_ID");
const LATITUDE = Deno.env.get("LATITUDE");
const LONGITUDE = Deno.env.get("LONGITUDE");
const CHAT_ID = Deno.env.get("TELEGRAM_CHAT_ID");
const TELEGRAM_TOKEN = Deno.env.get("TELEGRAM_TOKEN");
const THINGSPEAK_CHANNEL_ID = Deno.env.get("THINGSPEAK_CHANNEL_ID");
const fetchLatestTemperatureFromThingSpeak = async (channelId = THINGSPEAK_CHANNEL_ID, resultsCount = 1) => {
const baseUrl = "https://api.thingspeak.com/channels";
const url = `${baseUrl}/${channelId}/feeds.json?results=${resultsCount}`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const temperature = data.feeds[0]?.field3;
const createdAt = new Date(data.feeds[0]?.created_at);
const currentTime = new Date();
const oneHourAgo = new Date(currentTime.getTime() - (60 * 60 * 1000));
if (temperature === undefined || createdAt < oneHourAgo) {
throw new Error("Temperature data not found in the feed.");
}
return temperature;
} catch (error) {
// console.error("Failed to fetch temperature:", error);
return null; // or handle the error in another way
}
};
const weatherToEmoticon = {
"clear sky": "☀️",
"few clouds": "🌤",
"scattered clouds": "⛅",
"broken clouds": "☁️",
"shower rain": "🌧",
"rain": "🌧",
"thunderstorm": "⛈",
"snow": "❄️",
"mist": "🌫",
};
const fetchDataFromOpenWeatherMap = async () => {
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${LATITUDE}&lon=${LONGITUDE}&units=metric&appid=${API_KEY}`,
);
const weatherForecastData = await response.json();
const condition = weatherForecastData.weather[0].icon;
// const weatherIcon = fetch(`https://openweathermap.org/img/wn/${condition}@2x.png`); // https://openweathermap.org/img/wn/10d@2x.png
const weatherCondition = weatherForecastData.weather[0].description;
const temperature = weatherForecastData.main.temp;
const humidity = weatherForecastData.main.humidity;
const wind = weatherForecastData.wind;
return {
temperature,
humidity,
weatherCondition,
wind,
};
};
const sendTextWithTelegram = async (text: string) => {
const telegramSendUrl =
`https://api.telegram.org/bot${TELEGRAM_TOKEN}/sendMessage?chat_id=${CHAT_ID}&parse_mode=HTML&text=${text}`;
await fetch(telegramSendUrl);
};
export default async function(interval: Interval) {
const temperature = await fetchLatestTemperatureFromThingSpeak();
const weatherCondition = await fetchDataFromOpenWeatherMap();
const windspeedInKmh = Math.ceil(weatherCondition.wind.speed * 3.6);
const formattedWeatherData = `<b>Temperature:</b> <i>${temperature || weatherCondition.temperature} °C</i>%0A
<b>Humidity:</b> <i>${weatherCondition.humidity}%</i>%0A
<b>Weather:</b> <i>${weatherCondition.weatherCondition}</i>%0A
<b>Wind Speed:</b> <i>${windspeedInKmh} km/h</i>%0A
<b>Wind Direction:</b> <i>${weatherCondition.wind.deg}°</i>%0A${
!temperature ? `<b>Status:</b> On-site sensor OFFLINE%0A` : ""
}`;
sendTextWithTelegram(
formattedWeatherData,
);
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
v42
May 12, 2024