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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
|
use std::{
cmp::max_by,
collections::HashMap,
process::{
id,
Stdio,
},
};
use anyhow::anyhow;
use chrono::Duration;
use diesel::row::NamedRow;
use fnv::{
FnvHashMap,
FnvHashSet,
};
use grate::tracing;
use lazy_static::lazy_static;
use poise::{
CreateReply,
FrameworkError,
};
use regex::{
Match,
Regex,
};
use serenity::{
all::{
ChannelType,
CreateMessage,
GuildId,
GuildRef,
Message,
Reaction,
ReactionType,
VoiceState,
},
client::Context,
model::{
id::{
ChannelId,
MessageId,
},
permissions::Permissions,
},
};
use tap::Pipe;
use url::Url;
use crate::{
commands::playback::songbird,
PoiseContext,
CONFIG,
};
mod rest_vec;
#[cfg(windows)]
pub mod windows;
pub use rest_vec::*;
pub async fn currently_playing(ctx: PoiseContext<'_>) -> bool {
let (_sb, call) = songbird(ctx).await.expect("no songbird");
let call = call.lock().await;
call.queue().current().is_some()
}
pub async fn users_listening(ctx: PoiseContext<'_>) -> anyhow::Result<bool> {
let Some(channel) = best_voice_channel(ctx) else {
return Ok(false);
};
let Some(guild) = ctx.guild() else {
return Ok(false);
};
guild.voice_states.iter().any(|(_, state)| state.channel_id == Some(channel)).pipe(Ok)
}
#[inline]
pub fn msg<U, E>(ctx: poise::Context<'_, U, E>) -> Option<&Message> {
match ctx {
poise::Context::Prefix(poise::PrefixContext {
msg,
..
}) => Some(msg),
_ => None,
}
}
#[inline]
pub fn err_msg<'a, U, E>(err: &'a FrameworkError<U, E>) -> Option<&'a Message> {
use FrameworkError::*;
if let Some(ctx) = err.ctx() {
return msg(ctx);
}
match *err {
UnknownCommand {
msg,
..
}
| NonCommandMessage {
msg,
..
}
| DynamicPrefix {
msg,
..
} => Some(msg),
_ => None,
}
}
#[inline]
pub fn tts<U, E>(ctx: poise::Context<'_, U, E>) -> Option<bool> {
msg(ctx).map(|msg| msg.tts)
}
#[inline]
pub fn unwrap_tts<U, E>(ctx: poise::Context<'_, U, E>) -> bool {
tts(ctx).unwrap_or(false)
}
#[inline]
pub async fn send(
ctx: &Context,
channel: ChannelId,
text: impl AsRef<str>,
tts: bool,
) -> anyhow::Result<()> {
send_result(ctx, channel, text, tts).await.map(|_| ())
}
#[inline]
pub async fn reply<U, E>(
ctx: poise::Context<'_, U, E>,
text: impl AsRef<str>,
) -> Result<poise::ReplyHandle, serenity::Error> {
let handle =
poise::send_reply(ctx, CreateReply::default().tts(unwrap_tts(ctx)).content(text.as_ref()))
.await?;
Ok(handle)
}
#[inline]
pub async fn react(
ctx: PoiseContext<'_>,
react: impl Into<ReactionType> + Send,
) -> anyhow::Result<Reaction> {
msg(ctx)
.ok_or_else(|| anyhow::anyhow!("elp"))?
.react(ctx, react)
.await
.map_err(anyhow::Error::from)
}
#[inline]
pub async fn unreact(
ctx: PoiseContext<'_>,
react: impl Into<ReactionType> + Send,
) -> anyhow::Result<()> {
msg(ctx).ok_or_else(|| anyhow::anyhow!("elp"))?.delete_reaction(ctx, None, react).await?;
Ok(())
}
#[inline]
pub fn guild_id(ctx: PoiseContext<'_>) -> anyhow::Result<GuildId> {
ctx.guild_id().ok_or_else(|| anyhow::anyhow!("not in guild"))
}
#[inline]
pub fn guild(ctx: PoiseContext<'_>) -> anyhow::Result<GuildRef<'_>> {
ctx.guild().ok_or_else(|| anyhow::anyhow!("not in guild"))
}
#[inline]
pub fn author_voice_state(ctx: PoiseContext<'_>) -> Option<(VoiceState, GuildRef)> {
let guild = ctx.guild()?;
let caller_voice = guild.voice_states.get(&ctx.author().id)?.clone();
Some((caller_voice, guild))
}
#[inline]
pub fn author_voice_channel(ctx: PoiseContext<'_>) -> Option<ChannelId> {
let (vs, _guild) = author_voice_state(ctx)?;
vs.channel_id
}
pub fn voice_states_by_channel(ctx: PoiseContext<'_>) -> HashMap<ChannelId, Vec<VoiceState>> {
let Some(guild) = ctx.guild() else {
return Default::default();
};
guild
.voice_states
.values()
.cloned()
.filter_map(|x| {
let id = x.channel_id?;
Some((id, x))
})
.fold(HashMap::new(), |mut acc, (id, state)| {
acc.entry(id).or_insert_with(|| vec![]).push(state);
acc
})
}
/// Select the most relevant voice channel for a given poise context.
///
/// - If the message's author is in a voice channel, use that.
/// - If not, pick the most populated channel (channel age tiebreaks).
pub fn best_voice_channel(ctx: PoiseContext<'_>) -> Option<ChannelId> {
if let Some(channel) = author_voice_channel(ctx) {
return Some(channel);
}
let voice_states = voice_states_by_channel(ctx);
let max_pop = voice_states.iter().map(|(_, states)| states.len()).max();
let matching_channels = voice_states
.iter()
.filter_map(|(&channel, state)| {
if state.len() == max_pop? {
return Some(channel);
}
None
})
.collect::<Vec<_>>();
if matching_channels.len() == 1 {
return matching_channels.first().cloned();
}
matching_channels.into_iter().min()
}
pub async fn send_result(
ctx: &Context,
channel: ChannelId,
text: impl AsRef<str>,
tts: bool,
) -> anyhow::Result<MessageId> {
let text = text.as_ref();
tracing::debug!(text, %channel, tts, "sending message");
let result = channel.send_message(ctx, CreateMessage::default().content(text).tts(tts)).await?;
Ok(result.id)
}
lazy_static! {
static ref REQUIRED_PERMS: Permissions = Permissions::EMBED_LINKS
| Permissions::ADD_REACTIONS
| Permissions::SEND_MESSAGES
| Permissions::SEND_TTS_MESSAGES
| Permissions::MENTION_EVERYONE
| Permissions::USE_EXTERNAL_EMOJIS
| Permissions::CONNECT
| Permissions::SPEAK
| Permissions::CHANGE_NICKNAME
| Permissions::USE_VAD
| Permissions::ATTACH_FILES;
}
lazy_static! {
pub static ref OAUTH_URL: Url = Url::parse(&format!(
"https://discordapp.com/api/oauth2/authorize?scope=bot&permissions={}&client_id={}",
REQUIRED_PERMS.bits(),
CONFIG.discord.auth.client_id,
))
.unwrap();
}
pub async fn ytdl_url(uri: &str) -> anyhow::Result<String> {
use serde_json::Value;
use tokio::process::Command;
let args = [
"-f",
"webm[abr>0]/bestaudio/best",
"--no-playlist",
"--print-json",
"--skip-download",
uri,
];
tracing::debug!(uri, "downloading info");
let mut command = Command::new(&*crate::config::YTDL_COMMAND);
command.args(args).stdin(Stdio::null());
tracing::debug!(?command, "running command");
let out = command.output().await?;
if !out.status.success() {
return Err(anyhow::anyhow!("running ytdl: {out:?}"));
}
let value = serde_json::from_reader(&out.stdout[..])?;
let mut obj = match value {
Value::Object(obj) => obj,
other => return Err(anyhow::anyhow!("ytdl output not object: {other:?}")),
};
match obj.remove("url") {
Some(v) => match v {
Value::String(uri) => Ok(uri),
other => Err(anyhow::anyhow!("url not string: {other:?}")),
},
None => Err(anyhow::anyhow!("no url")),
}
}
pub fn parse_times<A: AsRef<str>>(s: A) -> (Option<Duration>, Option<Duration>) {
lazy_static! {
static ref START_REGEX: Regex =
Regex::new(r"(?:start|begin(?:ning)?)\s*=?\s*(?:(?P<hours>\d+)h\s?)?(?:(?P<minutes>\d+)m\s?)?(?:(?P<seconds>\d+)s?)?").unwrap();
static ref DUR_REGEX: Regex =
Regex::new(r"dur(?:ation)?\s*=?\s*(?:(?P<hours>\d+)h\s?)?(?:(?P<minutes>\d+)m\s?)?(?:(?P<seconds>\d+)s?)?").unwrap();
static ref END_REGEX: Regex =
Regex::new(r"(?:end|term(?:inate|ination)?)\s*=?\s*(?:(?P<hours>\d+)h\s?)?(?:(?P<minutes>\d+)m\s?)?(?:(?P<seconds>\d+)s?)?").unwrap();
}
fn parse_match(m: Option<Match>) -> u64 {
m.and_then(|s| s.as_str().parse::<u64>().ok()).unwrap_or(0)
}
fn parse_captures<B: AsRef<str>>(r: &Regex, s: B) -> Option<Duration> {
r.captures(s.as_ref()).map(|capt| {
let hours = parse_match(capt.name("hours"));
let minutes = parse_match(capt.name("minutes"));
let seconds = parse_match(capt.name("seconds"));
let result = Duration::hours(hours as i64)
+ Duration::minutes(minutes as i64)
+ Duration::seconds(seconds as i64);
assert!(result >= Duration::zero());
result
})
}
let start_time = parse_captures(&START_REGEX, &s);
let dur = parse_captures(&DUR_REGEX, &s);
let end_time = parse_captures(&END_REGEX, s)
.or_else(|| start_time.and_then(|start| dur.map(|d| start + d)));
(start_time, end_time)
}
|