forked from Paris-Developers/Mirror-TS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWeather.ts
185 lines (173 loc) · 5.18 KB
/
Weather.ts
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
//Call: Slash command weather or w
//Returns weather from a single specified city
import {
ChatInputApplicationCommandData,
CommandInteraction,
CacheType,
Permissions,
MessageEmbed,
} from 'discord.js';
import { Bot } from '../Bot';
import { SlashCommand } from './SlashCommand';
import fetch from 'node-fetch';
import { find } from 'geo-tz';
import config from '../../config.json';
import { Option, Subcommand } from './Option';
import { ApplicationCommandOptionTypes } from 'discord.js/typings/enums';
import { colorCheck } from '../resources/embedColorCheck';
type emojiConverter = { [index: string]: string };
const weatherEmoji = {
Rain: ':cloud_rain:',
Thunderstorm: ':thunder_cloud_rain:',
Drizzle: ':cloud_rain:',
Snow: ':cloud_snow:',
Clear: ':sunny:',
Clouds: ':cloud:',
Mist: ':fog:',
} as emojiConverter;
type cardinalIndex = { [index: number]: string };
const cardinalDir = {
0: 'N',
1: 'NNE',
2: 'NE',
3: 'ENE',
4: 'E',
5: 'ESE',
6: 'SE',
7: 'SSE',
8: 'S',
9: 'SSW',
10: 'SW',
11: 'WSW',
12: 'W',
13: 'WNW',
14: 'NW',
15: 'NNW',
16: 'N',
} as cardinalIndex;
export class Weather implements SlashCommand {
name: string = 'weather';
description: string = 'Weather data for a provided city';
options: (Option | Subcommand)[] = [
new Option(
'city',
'City to query',
ApplicationCommandOptionTypes.STRING,
true
),
new Option(
'state',
'Two letter state code',
ApplicationCommandOptionTypes.STRING,
false
),
];
requiredPermissions: bigint[] = [
Permissions.FLAGS.SEND_MESSAGES,
Permissions.FLAGS.EMBED_LINKS,
];
async run(
bot: Bot,
interaction: CommandInteraction<CacheType>
): Promise<void> {
try {
if (!interaction.options.getString('city')) {
const embed = new MessageEmbed()
.setColor(colorCheck(interaction.guild!.id))
.setDescription('Empty message, please provide a city');
interaction.reply({ embeds: [embed] });
return;
}
//if it encounters an error it will run the code under the catch function
let jsonData;
let query = interaction.options.getString('state') //if we have a state lets add it to the string
? `${interaction.options.getString(
'city'
)},US-${interaction.options.getString('state')}`
: interaction.options.getString('city');
//Pulls data from the API and stores as a JSON object
let res = await fetch(
`http://api.openweathermap.org/data/2.5/weather?q=${query}&appid=${config.weather_token}`
);
jsonData = await res.json();
if (jsonData.cod == '404') {
const embed = new MessageEmbed()
.setColor(colorCheck(interaction.guild!.id))
.setDescription(`Error: City not found, try again`);
interaction.reply({ embeds: [embed] });
return;
}
//define current weather coniditions
let condition = jsonData.weather[0].main;
//define current temperatures
let cTemp = Math.round(jsonData.main.temp - 273.15);
let fTemp = Math.round((cTemp * 9) / 5 + 32);
//define daily high temperatures
let cHigh = Math.round(jsonData.main.temp_max - 273.15);
let fHigh = Math.round((cHigh * 9) / 5 + 32);
//define timezone and sunrise
let timezone = find(jsonData.coord.lat, jsonData.coord.lon);
let sunrise = new Date(jsonData.sys.sunrise * 1000).toLocaleString(
'en-US',
{ timeZone: timezone[0] }
);
sunrise = sunrise.split(', ')[1].slice(0, 4);
//define sunset
let sunset = new Date(jsonData.sys.sunset * 1000).toLocaleString(
'en-US',
{
timeZone: timezone[0],
}
);
sunset = sunset.split(', ')[1].slice(0, 4);
//define humidity and wind ## NOTE WIND COMES IN AT M/S
let humidity = `${jsonData.main.humidity} %`;
let kmhWind = Math.round(jsonData.wind.speed * 3.6);
let mphWind = Math.round(kmhWind * 0.621371);
let windDir =
mphWind == 0 ? '' : cardinalDir[Math.round(jsonData.wind.deg / 22.8)]; // if there's no wind, set it to blank
//capitalizes the first letter of each word in the string called
let str = '';
let cityArray = interaction.options.getString('city')!.split(' ');
for (let step = 0; step < cityArray.length; step++) {
str +=
cityArray[step][0].toUpperCase() +
cityArray[step].slice(1).toLowerCase() +
' ';
}
//creates message embed and edits modifiers
const embed = new MessageEmbed()
.setColor(colorCheck(interaction.guild!.id))
.setTitle(`**Current Weather in ${str}**`)
.addFields(
//adds multiple embed fields simultaneously
{
name: `Temp: ${fTemp}°F (${cTemp}°C) \nHigh: ${fHigh}°F (${cHigh}°C)`,
value: `${condition} ${weatherEmoji[condition]}`,
inline: false,
},
{
name: 'Wind:',
value: `${mphWind} mph (${kmhWind} kmh) \n${windDir}`,
inline: true,
},
{
name: 'Daylight:',
value: `:sun_with_face: ${sunrise}\n:new_moon_with_face: ${sunset}`,
inline: true,
},
{ name: 'Humidity:', value: `${humidity}`, inline: true }
)
.setTimestamp();
//sends embed to the channel
interaction.reply({ embeds: [embed] });
} catch (err) {
bot.logger.commandError(interaction.channel!.id, this.name, err);
interaction.reply({
content: 'Error: contact a developer to investigate',
ephemeral: true,
});
return;
}
}
}