weather.ts (4523B)
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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | import fetch from 'node-fetch';
import { MessageEmbed } from 'discord.js';
const tzlookup = require("tz-lookup");
const DIRECTIONS = [
'north', 'north east',
'east', 'south east',
'south', 'south west',
'west', 'north west'
];
const MOON_PHASES = ['🌑', '🌒️', '🌓', '🌔️', '🌕', '🌖️', '🌗', '🌘️'];
const ICONS = {
'clear-day': '🌞',
'clear-night': '🌚',
'rain': '🌧️',
'snow': '❄️',
'sleet': '🌨️',
'wind': '💨',
'fog': '🌫️',
'cloudy': '🌥️',
'partly-cloudy-day': '⛅',
'partly-cloudy-night': '⛅'
};
const WEATHER_URL = 'https://api.met.no/weatherapi/locationforecast/2.0/compact';
const OPENWEATHER_URL = 'https://api.openweathermap.org/data/2.5/weather';
const GEOCODE_URL = 'https://geocode-maps.yandex.ru/1.x/?format=json';
export default async (homescope: HomeScope) => {
const { message, args, SECRETS, CONFIG, VERSION } = homescope;
if (args[0] === 'set' && args.length > 1) {
CONFIG.weather_locations[message.author.id] = args.tail().join(' ');
return message.reply(`Your weather location has \
been set to ${args.tail().join(' ')}`.squeeze());
}
const location = args[0]
? args.join(' ')
: CONFIG.weather_locations[message.author.id] || 'Cuckfield';
if (location == 'Cuckfield')
message.reply("You should set your default weather location."
+ ` Use \`${CONFIG.commands.prefix}weather set <location>\`.`);
const geokey = SECRETS.yandex.geocoder.key;
const error = (e: Error) => {
message.reply(`Error getting weather\n\`\`\`${e.message}\`\`\``);
return e;
};
let geocoder_json, weather_info, geo_object,
country_code, tz, openweather_info,
weather_body, info_body, d, c;
try {
const geocoder = await fetch(`${GEOCODE_URL}&apikey=${geokey}`
+`&geocode=${encodeURI(location)}&lang=en-US`);
geocoder_json = await geocoder.json();
geo_object = geocoder_json.response
.GeoObjectCollection
.featureMember[0].GeoObject;
country_code = geo_object
.metaDataProperty
.GeocoderMetaData
.Address
.country_code;
const [lon, lat] = geo_object.Point.pos
.split(' ')
.map(s => parseFloat(s).round_to(4));
tz = tzlookup(lat, lon)
weather_info = await fetch(
`${WEATHER_URL}?lat=${lat}&lon=${lon}`,
{
method: 'get',
headers: {
'User-Agent': `Simp-O-Matic/${VERSION} simp.knutsen.co`
}
});
openweather_info = await fetch(
`${OPENWEATHER_URL}?lat=${lat}&lon=${lon}`
+ `&units=metric&appid=${SECRETS.openweather.key}`);
weather_body = await weather_info.text();
info_body = await openweather_info.text();
d = JSON.parse(weather_body)
c = JSON.parse(info_body);
} catch (e) {
console.warn("met.no response: ", weather_body);
console.warn("openweather response: ", info_body);
return error(e);
}
const { properties } = d;
const temps = [...Array(24)].map((_, n) =>
properties.timeseries[n].data.instant.details.air_temperature);
if (!geo_object.name)
geo_object.name = 'Somewhere';
if (!geo_object.description)
geo_object.description = 'Someplace';
const embed = new MessageEmbed()
.setTitle(`Cannot get weather information from ${location}.`);
if (properties && properties.meta) embed
.setTitle(
`${properties.timeseries[0].data.instant.details.air_temperature}°C`)
.setAuthor(`${new Intl.DateTimeFormat('en-CA',
{ timeZone: tz,
timeZoneName: 'short',
hour: 'numeric',
minute: 'numeric',
//year: 'numeric',
//month: 'numeric',
//day: 'numeric',
hour12: false })
.format(new Date)},`
+ ` ${geo_object.name},`
+ ` ${geo_object.description}`,
`https://flagcdn.com/64x48/${country_code.toLowerCase()}.png`)
.setThumbnail(
`https://api.met.no/images/weathericons/png/${properties.timeseries[0].data.next_1_hours.summary.symbol_code}.png`)
.addFields(
{ name: 'daytime',
value: c.main.temp_max + '°C',
inline: true },
{ name: 'nighttime',
value: c.main.temp_min + '°C',
inline: true },
{ name: 'humidity',
value: properties.timeseries[0].data.instant.details.relative_humidity + '%',
inline: true },
{ name: 'wind',
value: `${DIRECTIONS[Math.round(properties.timeseries[0].data.instant.details.wind_from_direction / 45) % 8]}`
+ ` ${properties.timeseries[0].data.instant.details.wind_speed} ㎧`,
inline: true })
.setFooter(
'Data provided by Meteorologisk institutt (met.no) and OpenWeatherMap',
'https://0x0.st/ixd6.png');
message.channel.send(embed);
};
|