2021-09-22 12:37:48 +02:00
|
|
|
use crate::SpotifyURL::Track;
|
|
|
|
use aspotify::{Client, ClientCredentials};
|
2021-09-21 23:41:50 +02:00
|
|
|
use teloxide::prelude::*;
|
|
|
|
|
2021-09-22 12:37:48 +02:00
|
|
|
enum SpotifyURL {
|
|
|
|
Track(String),
|
2021-09-21 23:41:50 +02:00
|
|
|
}
|
|
|
|
|
2021-09-22 12:37:48 +02:00
|
|
|
fn get_spotify_entry(url: &str) -> Option<SpotifyURL> {
|
2021-09-21 23:41:50 +02:00
|
|
|
if url.contains("https://open.spotify.com/track/") {
|
|
|
|
let track_id = url.rsplit('/').next().and_then(|x| x.split('?').next());
|
|
|
|
return match track_id {
|
2021-09-22 12:37:48 +02:00
|
|
|
Some(id) => Some(SpotifyURL::Track(id.to_string())),
|
|
|
|
None => None,
|
|
|
|
};
|
2021-09-21 23:41:50 +02:00
|
|
|
}
|
2021-09-22 12:37:48 +02:00
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
struct TrackInfo {
|
|
|
|
name: String,
|
|
|
|
artist: Vec<String>,
|
2021-09-21 23:41:50 +02:00
|
|
|
}
|
|
|
|
|
2021-09-22 12:37:48 +02:00
|
|
|
async fn get_spotify_track(spotify: Box<Client>, id: &String) -> Option<TrackInfo> {
|
|
|
|
match spotify.tracks().get_track(id.as_str(), None).await {
|
|
|
|
Ok(track) => Some(TrackInfo {
|
|
|
|
name: track.data.name,
|
|
|
|
artist: track.data.artists.iter().map(|x| x.name.clone()).collect(),
|
|
|
|
}),
|
|
|
|
Err(_e) => None,
|
2021-09-21 23:41:50 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[tokio::main]
|
|
|
|
async fn main() {
|
|
|
|
teloxide::enable_logging!();
|
|
|
|
log::info!("Starting Songlify...");
|
|
|
|
|
|
|
|
let bot = Bot::from_env().auto_send();
|
|
|
|
teloxide::repl(bot, |message| async move {
|
2021-09-22 12:37:48 +02:00
|
|
|
let spotify_creds =
|
|
|
|
ClientCredentials::from_env().expect("CLIENT_ID and CLIENT_SECRET not found.");
|
|
|
|
let spotify_client = Box::new(Client::new(spotify_creds));
|
|
|
|
|
|
|
|
log::info!("Connected to Spotify");
|
|
|
|
let text = message.update.text().and_then(get_spotify_entry);
|
2021-09-21 23:41:50 +02:00
|
|
|
match text {
|
2021-09-22 12:37:48 +02:00
|
|
|
Some(spotify) => match spotify {
|
|
|
|
Track(id) => {
|
|
|
|
let track_info = get_spotify_track(spotify_client, &id).await;
|
|
|
|
match track_info {
|
|
|
|
Some(info) => {
|
|
|
|
let reply = format!(
|
|
|
|
"Track information:\n\
|
|
|
|
Track name: {}\n\
|
|
|
|
Artists: {}",
|
|
|
|
info.name,
|
|
|
|
info.artist.join(", ")
|
|
|
|
);
|
|
|
|
Some(message.reply_to(reply).await?)
|
|
|
|
}
|
|
|
|
None => None,
|
|
|
|
}
|
2021-09-21 23:41:50 +02:00
|
|
|
}
|
2021-09-22 12:37:48 +02:00
|
|
|
},
|
|
|
|
None => None,
|
2021-09-21 23:41:50 +02:00
|
|
|
};
|
|
|
|
respond(())
|
|
|
|
})
|
2021-09-22 12:37:48 +02:00
|
|
|
.await;
|
|
|
|
|
|
|
|
log::info!("Exiting...");
|
|
|
|
}
|