refactor: вынести fetch_cat в utils, добавить повторный вывод списка команд
This commit is contained in:
parent
5292f9bd0e
commit
6219ce42d0
16
bot.py
16
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:
|
||||
|
||||
@ -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)
|
||||
|
||||
18
utils/cat.py
Normal file
18
utils/cat.py
Normal file
@ -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
|
||||
Loading…
x
Reference in New Issue
Block a user