-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
199 lines (177 loc) · 5.34 KB
/
lib.rs
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
use discord_flows::{
application_command_handler,
http::HttpBuilder,
message_handler,
model::{
application::interaction::InteractionResponseType,
application_command::CommandDataOptionValue,
prelude::application::interaction::application_command::ApplicationCommandInteraction,
Message,
},
Bot, ProvidedBot,
};
use flowsnet_platform_sdk::logger;
use http_req::{
request::{Method, Request},
uri::Uri,
};
use serde::Deserialize;
use serde_json;
use std::env;
#[no_mangle]
#[tokio::main(flavor = "current_thread")]
pub async fn on_deploy() {
logger::init();
let discord_token = env::var("discord_token").unwrap();
let bot = ProvidedBot::new(&discord_token);
register_commands().await;
bot.listen_to_messages().await;
bot.listen_to_application_commands()
.await;
}
#[message_handler]
async fn handle(msg: Message) {
logger::init();
let discord_token = std::env::var("discord_token").unwrap();
let bot = ProvidedBot::new(&discord_token);
if msg.author.bot {
return;
}
let client = bot.get_client();
_ = client
.send_message(
msg.channel_id.into(),
&serde_json::json!({
"content": msg.content,
}),
)
.await;
}
#[application_command_handler]
async fn handler(ac: ApplicationCommandInteraction) {
logger::init();
let discord_token = env::var("discord_token").unwrap();
let bot = ProvidedBot::new(discord_token);
let client = bot.get_client();
client.set_application_id(ac.application_id.into());
_ = client
.create_interaction_response(
ac.id.into(),
&ac.token,
&serde_json::json!({
"type": InteractionResponseType::DeferredChannelMessageWithSource as u8,
}),
)
.await;
let options = &ac.data.options;
match ac.data.name.as_str() {
"weather" => {
let city = match options
.get(0)
.expect("Expected city option")
.resolved
.as_ref()
.expect("Expected city object")
{
CommandDataOptionValue::String(s) => s,
_ => panic!("Expected string for city"),
};
let resp_inner = match get_weather(&city) {
Some(w) => format!(
r#"
Today in {}
{}
Low temperature: {} °C,
High temperature: {} °C,
Wind Speed: {} km/h"#,
city,
w.weather
.first()
.unwrap_or(&Weather {
main: "Unknown".to_string()
})
.main,
w.main.temp_min as i32,
w.main.temp_max as i32,
w.wind.speed as i32
),
None => String::from("No city or incorrect spelling"),
};
let resp = serde_json::json!({ "content": resp_inner });
_ = client
.edit_original_interaction_response(&ac.token, &resp)
.await;
}
_ => {}
}
}
#[derive(Deserialize, Debug)]
struct ApiResult {
weather: Vec<Weather>,
main: Main,
wind: Wind,
}
#[derive(Deserialize, Debug)]
struct Weather {
main: String,
}
#[derive(Deserialize, Debug)]
struct Main {
temp_max: f64,
temp_min: f64,
}
#[derive(Deserialize, Debug)]
struct Wind {
speed: f64,
}
fn get_weather(city: &str) -> Option<ApiResult> {
let mut writer = Vec::new();
let api_key = env::var("API_KEY").unwrap_or("fake_api_key".to_string());
let query_str = format!(
"https://api.openweathermap.org/data/2.5/weather?q={city}&units=metric&appid={api_key}"
);
let uri = Uri::try_from(query_str.as_str()).unwrap();
match Request::new(&uri).method(Method::GET).send(&mut writer) {
Err(_e) => log::error!("Error getting response from weather api: {:?}", _e),
Ok(res) => {
if !res.status_code().is_success() {
log::error!("weather api http error: {:?}", res.status_code());
return None;
}
match serde_json::from_slice::<ApiResult>(&writer) {
Err(_e) => log::error!("Error deserializing weather api response: {:?}", _e),
Ok(w) => {
log::info!("Weather: {:?}", w);
return Some(w);
}
}
}
};
None
}
async fn register_commands() {
let bot_id = env::var("bot_id").unwrap_or("1124137839601406013".to_string());
let command = serde_json::json!({
"name": "weather",
"description": "Get the weather for a city",
"options": [
{
"name": "city",
"description": "The city to lookup",
"type": 3,
"required": true
}
]
});
let discord_token = env::var("discord_token").unwrap();
let http_client = HttpBuilder::new(discord_token)
.application_id(bot_id.parse().unwrap())
.build();
match http_client
.create_global_application_command(&command)
.await
{
Ok(_) => log::info!("Successfully registered command"),
Err(err) => log::error!("Error registering command: {}", err),
}
}