Поиск фото с Гугла и отправка его через бота Discord Python

from disnake import ApplicationCommandInteraction
from disnake.ext.commands import Cog, Bot, slash_command, param


class Search(Cog):
    def __init__(self, bot: Bot):
        self.bot: Bot = bot

    @slash_command()
    async def image(
            self,
            inter: ApplicationCommandInteraction,
            req: str = param(name="Search images in google")
    ):
        image = []  # способ как достать изображения
        await inter.send(file=image)


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

Я пробовал использовать всяческие библиотеки , по типу icrawler но ничего не получилось так как они сохряняют изображение в память ПК , а мне нужно чтобы все это держалось в функции


Ответы (1 шт):

Автор решения: anonymus

Вам нужно будет использовать внешний API для поиска изображений (например, Google Custom Search API), поскольку Discord сам по себе не предоставляет такую функциональность. Во-вторых, в вашем коде нужно будет правильно обработать полученные данные и отправить их в Discord.

Примерная реализация:

from disnake import ApplicationCommandInteraction, File
from disnake.ext.commands import Cog, Bot, slash_command, param
import requests
import os

# Вам нужно будет получить API ключ и идентификатор поискового движка у Google
GOOGLE_API_KEY = 'YOUR_GOOGLE_API_KEY'
GOOGLE_CSE_ID = 'YOUR_GOOGLE_CSE_ID'


class Search(Cog):
    def __init__(self, bot: Bot):
        self.bot: Bot = bot

    @slash_command()
    async def image(
            self,
            inter: ApplicationCommandInteraction,
            req: str = param(name="query", description="Search images in google")
    ):
        # Формирование запроса к Google Custom Search API
        search_url = f"https://www.googleapis.com/customsearch/v1?q={req}&cx={GOOGLE_CSE_ID}&key={GOOGLE_API_KEY}&searchType=image"
        response = requests.get(search_url)
        data = response.json()

        # Получение ссылки на изображение
        image_url = data['items'][0]['link']

        image_response = requests.get(image_url)
        filename = f"temp_image.{image_url.split('.')[-1]}"
        with open(filename, 'wb') as image_file:
            image_file.write(image_response.content)

        await inter.send(file=File(filename))

        os.remove(filename)


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

Также нужно задать GOOGLE_API_KEY и GOOGLE_CSE_ID для работы с Google Custom Search API. После получения изображения с помощью API, скрипт сохраняет его локально и отправляет как файл через Discord, после чего удаляет временный файл.

UPD: Вы можете использовать io.BytesIO из стандартной библиотеки Python. Это позволит вам создать файловый объект в памяти, который может быть использован библиотекой disnake для отправки изображения.

Примерная реализация

from disnake import ApplicationCommandInteraction, File
from disnake.ext.commands import Cog, Bot, slash_command, param
import requests
import io

# Ваши данные API
GOOGLE_API_KEY = 'YOUR_GOOGLE_API_KEY'
GOOGLE_CSE_ID = 'YOUR_GOOGLE_CSE_ID'


class Search(Cog):
    def __init__(self, bot: Bot):
        self.bot: Bot = bot

    @slash_command()
    async def image(
            self,
            inter: ApplicationCommandInteraction,
            req: str = param(name="query", description="Search images in google")
    ):
        search_url = f"https://www.googleapis.com/customsearch/v1?q={req}&cx={GOOGLE_CSE_ID}&key={GOOGLE_API_KEY}&searchType=image"
        response = requests.get(search_url)
        data = response.json()

        # Проверка наличия изображений в результатах поиска
        if 'items' in data and data['items']:
            image_url = data['items'][0]['link']
            image_response = requests.get(image_url)

            if image_response.status_code == 200:
                # Использование BytesIO вместо записи на диск
                image_bytes = io.BytesIO(image_response.content)
                filename = f"image.{image_url.split('.')[-1]}"

                # Отправка изображения в Discord
                await inter.send(file=File(image_bytes, filename=filename))
            else:
                await inter.send('Не удалось загрузить изображение.')
        else:
            await inter.send('Изображения по вашему запросу не найдены.')


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

В этом коде объект BytesIO создаётся непосредственно из содержимого ответа сервера (тело ответа на запрос изображения)

UPD 2:

import disnake
import requests
import io
from disnake.ext.commands import Bot, Cog, slash_command
from disnake import ApplicationCommandInteraction, File

class SearchImages(Cog):
    def __init__(self, bot: Bot):
        self.bot = bot
        self.pixabay_api_key = "-KEY"

    @slash_command()
    async def image(self, inter: ApplicationCommandInteraction, search_query: str):
        image_url = self.get_image_url(search_query)
        if image_url is not None:
            image_bytes = self.get_image_bytes(image_url)
            await inter.send(file=File(fp=image_bytes, filename="image.png"))
        else:
            await inter.send("Изображение не найдено.")

    def get_image_url(self, search_query: str) -> str:
        params = {
            'key': self.pixabay_api_key,
            'q': search_query,
            'image_type': 'photo',
            'per_page': 3
        }
        response = requests.get('https://pixabay.com/api/', params=params)
        response_json = response.json()
        hits = response_json.get('hits')
        if hits and len(hits) > 0:
            return hits[0]['webformatURL']  # Возвращает URL первого изображения
        return None

    def get_image_bytes(self, image_url: str) -> io.BytesIO:
        response = requests.get(image_url)
        image_bytes = io.BytesIO(response.content)
        image_bytes.seek(0)  # Перемещаем указатель в начало файла
        return image_bytes

def setup(bot: Bot):
    bot.add_cog(SearchImages(bot))
→ Ссылка