aboutsummaryrefslogtreecommitdiffstats
path: root/src/commands/web.rs
blob: f8b866724685e3e9447ab7cd012a2c2a7f5d3672 (plain) (blame)
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
use std::time::Duration;

use poise::serenity_prelude as serenity;
use scraper::{Html, Selector};

use crate::Data;
use crate::error::{Error, Result};
use crate::lang;

type Context<'a> = poise::Context<'a, Data, Error>;

/// Search the web via DuckDuckGo
#[poise::command(slash_command)]
pub async fn web(ctx: Context<'_>, #[description = "Search query"] query: String) -> Result<()> {
    ctx.defer().await?;

    let url = format!(
        "https://html.duckduckgo.com/html/?q={}",
        urlencoding(&query)
    );
    let html = ctx
        .data()
        .http_client
        .get(&url)
        .timeout(Duration::from_secs(15))
        .send()
        .await?
        .text()
        .await?;

    let results = {
        let document = Html::parse_document(&html);

        let result_selector = Selector::parse(".result").unwrap();
        let title_selector = Selector::parse(".result__title a").unwrap();
        let snippet_selector = Selector::parse(".result__snippet").unwrap();

        let mut results = Vec::new();
        for result in document.select(&result_selector).take(5) {
            let title = result
                .select(&title_selector)
                .next()
                .map(|a| a.text().collect::<String>())
                .unwrap_or_default();

            let url = result
                .select(&title_selector)
                .next()
                .and_then(|a| a.attr("href"))
                .unwrap_or("")
                .to_string();

            let snippet = result
                .select(&snippet_selector)
                .next()
                .map(|s| s.text().collect::<String>())
                .unwrap_or_default();

            let clean_url = if let Some(encoded) = url.split("uddg=").nth(1) {
                let encoded = encoded.split('&').next().unwrap_or(encoded);
                url_decode(encoded)
            } else {
                url.to_string()
            };

            results.push((title, clean_url, snippet));
        }
        results
    };

    if results.is_empty() {
        ctx.say(lang::L_WEB_NO_RESULTS).await?;
        return Ok(());
    }

    let mut embed = serenity::CreateEmbed::default()
        .title(lang::fmt_web_title(&query))
        .color(0x00aaff);

    for (i, (title, url, snippet)) in results.iter().enumerate() {
        embed = embed.field(
            format!("{}. {title}", i + 1),
            format!("{url}\n{snippet}"),
            false,
        );
    }

    ctx.send(poise::CreateReply::default().embed(embed)).await?;
    Ok(())
}

fn url_decode(s: &str) -> String {
    let mut result = String::new();
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        match c {
            '+' => result.push(' '),
            '%' => {
                let hi = chars.next().and_then(|c| c.to_digit(16));
                let lo = chars.next().and_then(|c| c.to_digit(16));
                if let (Some(hi), Some(lo)) = (hi, lo) {
                    result.push(char::from_u32((hi << 4) | lo).unwrap_or('�'));
                } else {
                    result.push('%');
                }
            }
            _ => result.push(c),
        }
    }
    result
}

fn urlencoding(s: &str) -> String {
    s.chars()
        .map(|c| match c {
            'A'..='Z' | 'a'..='z' | '0'..='9' | '_' | '-' | '.' | '~' => c.to_string(),
            ' ' => "+".to_string(),
            _ => format!("%{:02X}", c as u8),
        })
        .collect()
}

pub fn commands() -> Vec<poise::Command<Data, Error>> {
    vec![web()]
}