From 6219ce42d04c4050a71b8fc10f2246f2a99d75e7 Mon Sep 17 00:00:00 2001 From: deadzilla Date: Tue, 26 May 2026 18:56:11 +0500 Subject: [PATCH] =?UTF-8?q?refactor:=20=D0=B2=D1=8B=D0=BD=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=B8=20fetch=5Fcat=20=D0=B2=20utils,=20=D0=B4=D0=BE?= =?UTF-8?q?=D0=B1=D0=B0=D0=B2=D0=B8=D1=82=D1=8C=20=D0=BF=D0=BE=D0=B2=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D1=8B=D0=B9=20=D0=B2=D1=8B=D0=B2=D0=BE=D0=B4?= =?UTF-8?q?=20=D1=81=D0=BF=D0=B8=D1=81=D0=BA=D0=B0=20=D0=BA=D0=BE=D0=BC?= =?UTF-8?q?=D0=B0=D0=BD=D0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bot.py | 16 ++++++++++++---- commands/cat.py | 31 +++++++++++-------------------- utils/cat.py | 18 ++++++++++++++++++ 3 files changed, 41 insertions(+), 24 deletions(-) create mode 100644 utils/cat.py diff --git a/bot.py b/bot.py index e73c2f0..d1da43a 100644 --- a/bot.py +++ b/bot.py @@ -63,22 +63,29 @@ async def msg(ctx, *, text: str): await ctx.send(text) -def console_input(): - bot_ready.wait() - print("Доступные команды:") +def _print_commands(): + """Вывести список доступных консольных команд.""" available = {k: v for k, v in ALL_CONSOLE_COMMANDS.items() if k != "stop"} + print("\nДоступные команды:") for idx, (name, func) in enumerate(available.items(), 1): print(f" {idx}. {name}") print(" 0. stop") + +def console_input(): + bot_ready.wait() + _print_commands() + while not stop_event.is_set(): try: choice = input("\nВыберите команду (номер): ").strip() if choice == "0": print("\nОстановка бота...") stop_event.set() + asyncio.run_coroutine_threadsafe(bot.close(), bot.loop).result(timeout=5) break try: + available = {k: v for k, v in ALL_CONSOLE_COMMANDS.items() if k != "stop"} idx = int(choice) if 0 < idx <= len(available): cmd_name = list(available.keys())[idx - 1] @@ -90,7 +97,8 @@ def console_input(): else: print(f"Неизвестная команда: {choice}") except (ValueError, IndexError): - print(f"Неизвестная команда: {choice}") + print(f"Неверный формат: {choice}") + _print_commands() except (EOFError, KeyboardInterrupt): stop_event.set() try: diff --git a/commands/cat.py b/commands/cat.py index 383dc19..cefadba 100644 --- a/commands/cat.py +++ b/commands/cat.py @@ -1,9 +1,7 @@ import discord from discord.ext import commands -import asyncio -import requests -_session = requests.Session() +from utils.cat import fetch_cat class Cat(commands.Cog): @@ -12,21 +10,14 @@ class Cat(commands.Cog): @commands.command(name="cat") async def cat(self, ctx): """Получить случайного котика""" - try: - response = await asyncio.to_thread( - _session.get, - "https://api.thecatapi.com/v1/images/search", - timeout=10 - ) - response.raise_for_status() - data = response.json() - url = data[0]["url"] - - embed = discord.Embed( - title="🐱 Котик для тебя!", - color=discord.Color.orange() - ) - embed.set_image(url=url) - await ctx.send(embed=embed) - except requests.exceptions.RequestException: + url = await fetch_cat() + if url is None: await ctx.send("Не удалось получить котика. Попробуйте позже.") + return + + embed = discord.Embed( + title="Котик для тебя!", + color=discord.Color.orange() + ) + embed.set_image(url=url) + await ctx.send(embed=embed) diff --git a/utils/cat.py b/utils/cat.py new file mode 100644 index 0000000..f3ce8d2 --- /dev/null +++ b/utils/cat.py @@ -0,0 +1,18 @@ +import asyncio + +import requests + +CAT_API_URL = "https://api.thecatapi.com/v1/images/search" + +_session = requests.Session() + + +async def fetch_cat() -> str | None: + """Получить URL случайного котика. Вернуть None при ошибке.""" + try: + response = await asyncio.to_thread(_session.get, CAT_API_URL, timeout=10) + response.raise_for_status() + data = response.json() + return data[0]["url"] + except requests.exceptions.RequestException: + return None