aboutsummaryrefslogtreecommitdiffstats
path: root/cogs/search.py
blob: a124cbfa8f1ddf7134e1b8cf7f5cb8281c70f3fd (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
# This file is part of Senator Sperma
# Licensed under the GPL-3.0 License
# Copyright (C) 2026 Salmonik @ salmonik@tuta.io
# https://codeberg.org/salmonik/senator-sperma

import urllib.parse

import discord
from discord.ext import commands
import logging
from discord import AutocompleteContext
from cogs.utils import file_search as search_utils

logger = logging.getLogger(__name__)

class Search(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._cached_results = {}

    async def file_autocomplete(self, ctx: AutocompleteContext):
        """Autocomplete function for file search."""
        query = ctx.value.lower() if ctx.value else ""
        results = await search_utils.UniversalSearcher.search_copyparty_autocomplete(query, max_results=25)

        user_id = ctx.interaction.user.id
        self._cached_results[user_id] = {urllib.parse.unquote(url.split('/')[-1]): url for url in results}

        choices = []
        for url in results[:25]:
            filename = urllib.parse.unquote(url.split('/')[-1])
            display_name = filename[:99] + "…" if len(filename) > 100 else filename
            choices.append(discord.OptionChoice(name=display_name, value=filename))
        return choices

    @commands.slash_command(
        name="search",
        description="wyszukaj pliku"
    )
    @discord.option(
        name="filename",
        description="Search for a file to send",
        autocomplete=file_autocomplete
    )
    async def search(self, ctx, filename: str):
        """Send a file via URL from autocomplete selection."""
        if not filename:
            await ctx.reply("Please select a file from the autocomplete options.")
            return

        await ctx.defer()
        logger.info(f"Search command called by {ctx.author} for file: {filename}")

        cached = self._cached_results.get(ctx.author.id)
        if not cached:
            await ctx.send_followup("Search results expired. Please search again.")
            return

        matching_url = cached.get(filename)
        if not matching_url:
            await ctx.send_followup(f"File '{filename}' not found.")
            return

        try:
            await ctx.send_followup(matching_url)
            logger.info(f"Successfully sent URL: {matching_url}")
            del self._cached_results[ctx.author.id]
        except Exception as e:
            logger.error(f"Error sending URL {matching_url}: {str(e)}")
            await ctx.send_followup(str(e))

def setup(bot):
    bot.add_cog(Search(bot))