-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathmain.rs
More file actions
330 lines (265 loc) Β· 10.6 KB
/
main.rs
File metadata and controls
330 lines (265 loc) Β· 10.6 KB
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
use std::env;
use std::process::exit;
use lib::config::Config;
use songbird::{input, SerenityInit};
mod lib {
pub mod config;
pub mod player;
}
use figment::error::Kind::MissingField;
use lib::player::{SpotifyPlayer, SpotifyPlayerKey};
use librespot::core::mercury::MercuryError;
use librespot::playback::config::Bitrate;
use librespot::playback::player::PlayerEvent;
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::time::{sleep, Duration};
use serenity::Client;
use serenity::prelude::TypeMapKey;
use serenity::{
async_trait,
client::{Context, EventHandler},
framework::StandardFramework,
model::{gateway, gateway::Ready, id, user, voice::VoiceState},
};
struct Handler;
pub struct ConfigKey;
impl TypeMapKey for ConfigKey {
type Value = Config;
}
#[async_trait]
impl EventHandler for Handler {
async fn ready(&self, ctx: Context, ready: Ready) {
println!("Ready!");
println!("Invite me with https://discord.com/api/oauth2/authorize?client_id={}&permissions=36700160&scope=bot", ready.user.id);
ctx.invisible().await;
}
async fn cache_ready(&self, ctx: Context, guilds: Vec<id::GuildId>) {
let guild_id = match guilds.first() {
Some(guild_id) => *guild_id,
None => {
panic!("Not currently in any guilds.");
}
};
let data = ctx.data.read().await;
let player = data.get::<SpotifyPlayerKey>().unwrap().clone();
let config = data.get::<ConfigKey>().unwrap().clone();
// Handle case when user is in VC when bot starts
let guild = ctx
.cache
.guild(guild_id)
.expect("Could not find guild in cache.");
// Check if any of the admins are in the VC
let user_list = guild.voice_states;
let mut channel_ids: Vec<Option<id::ChannelId>> = Vec::new();
for (key, value) in user_list {
if config.discord_admins.contains(&key.to_string()) {
channel_ids.push(value.channel_id);
}
}
for i in channel_ids {
if i.is_some() {
// Enable casting
player.lock().await.enable_connect().await;
}
}
let c = ctx.clone();
// Handle Spotify events
tokio::spawn(async move {
loop {
let channel = player.lock().await.event_channel.clone().unwrap();
let mut receiver = channel.lock().await;
let event = match receiver.recv().await {
Some(e) => e,
None => {
// Busy waiting bad but quick and easy
sleep(Duration::from_millis(256)).await;
continue;
}
};
match event {
PlayerEvent::Stopped { .. } => {
c.set_presence(None, user::OnlineStatus::Online).await;
let manager = songbird::get(&c)
.await
.expect("Songbird Voice client placed in at initialization.")
.clone();
let _ = manager.remove(guild_id).await;
}
PlayerEvent::Started { .. } => {
let manager = songbird::get(&c)
.await
.expect("Songbird Voice client placed in at initialization.")
.clone();
let guild = c
.cache
.guild(guild_id)
.expect("Could not find guild in cache.");
// Check if any of the admins are in the VC
let user_list = guild.voice_states;
let mut channel_ids: Vec<Option<id::ChannelId>> = Vec::new();
for (key, value) in user_list {
if config.discord_admins.contains(&key.to_string()) {
channel_ids.push(value.channel_id);
}
}
if channel_ids.len() == 0 {
println!("Admin not in VC!");
continue;
}
let mut channel_id = id::ChannelId(0);
for i in channel_ids {
if i.is_some() {
// Choose the first channel we encounter which is non-null
channel_id = i.unwrap();
}
}
let _handler = manager.join(guild_id, channel_id).await;
if let Some(handler_lock) = manager.get(guild_id) {
let mut handler = handler_lock.lock().await;
let mut decoder = input::codec::OpusDecoderState::new().unwrap();
decoder.allow_passthrough = false;
let source = input::Input::new(
true,
input::reader::Reader::Extension(Box::new(
player.lock().await.emitted_sink.clone(),
)),
input::codec::Codec::FloatPcm,
input::Container::Raw,
None,
);
handler.set_bitrate(songbird::driver::Bitrate::Auto);
handler.play_only_source(source);
} else {
println!("Could not fetch guild by ID.");
}
}
PlayerEvent::Paused { .. } => {
c.set_presence(None, user::OnlineStatus::Online).await;
}
PlayerEvent::Playing { track_id, .. } => {
let track: Result<librespot::metadata::Track, MercuryError> =
librespot::metadata::Metadata::get(
&player.lock().await.session,
track_id,
)
.await;
if let Ok(track) = track {
let artist: Result<librespot::metadata::Artist, MercuryError> =
librespot::metadata::Metadata::get(
&player.lock().await.session,
*track.artists.first().unwrap(),
)
.await;
if let Ok(artist) = artist {
let listening_to = format!("{}: {}", artist.name, track.name);
c.set_presence(
Some(gateway::Activity::listening(listening_to)),
user::OnlineStatus::Online,
)
.await;
}
}
}
_ => {}
}
}
});
}
async fn voice_state_update(&self, ctx: Context, old: Option<VoiceState>, new: VoiceState) {
let data = ctx.data.read().await;
let config = data.get::<ConfigKey>().unwrap();
if !config.discord_admins.contains(&new.user_id.to_string()) {
return;
}
let player = data.get::<SpotifyPlayerKey>().unwrap();
let guild = ctx
.cache
.guild(ctx.cache.guilds().first().unwrap())
.unwrap();
// If user just connected
if old.clone().is_none() {
// Enable casting
ctx.set_presence(None, user::OnlineStatus::Online).await;
player.lock().await.enable_connect().await;
return;
}
// If user disconnected
if old.clone().unwrap().channel_id.is_some() && new.channel_id.is_none() {
// Disable casting
ctx.invisible().await;
player.lock().await.disable_connect().await;
// Disconnect
let manager = songbird::get(&ctx)
.await
.expect("Songbird Voice client placed in at initialization.")
.clone();
let _handler = manager.remove(guild.id).await;
return;
}
// If user moved channels
if old.unwrap().channel_id.unwrap() != new.channel_id.unwrap() {
let bot_id = ctx.cache.current_user_id();
let bot_channel = guild
.voice_states
.get(&bot_id)
.and_then(|voice_state| voice_state.channel_id);
if Option::is_some(&bot_channel) {
let manager = songbird::get(&ctx)
.await
.expect("Songbird Voice client placed in at initialization.")
.clone();
if let Some(guild_id) = ctx.cache.guilds().first() {
let _handler = manager.join(*guild_id, new.channel_id.unwrap()).await;
}
}
return;
}
}
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
let framework = StandardFramework::new();
let config = match Config::new() {
Ok(config) => config,
Err(error) => {
println!("Couldn't read config");
if let MissingField(f) = error.kind {
println!("Missing field: '{}'", f.to_uppercase());
} else {
println!("Error: {:?}", error);
exit(2)
}
exit(1)
}
};
let mut cache_dir = None;
if let Ok(c) = env::var("CACHE_DIR") {
cache_dir = Some(c);
}
let player = Arc::new(Mutex::new(
SpotifyPlayer::new(
config.spotify_username.clone(),
config.spotify_password.clone(),
Bitrate::Bitrate320,
cache_dir,
)
.await,
));
let mut client = Client::builder(
&config.discord_token,
gateway::GatewayIntents::non_privileged(),
)
.event_handler(Handler)
.framework(framework)
.type_map_insert::<SpotifyPlayerKey>(player)
.type_map_insert::<ConfigKey>(config)
.register_songbird()
.await
.expect("Err creating client");
let _ = client
.start()
.await
.map_err(|why| println!("Client ended: {:?}", why));
}