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)
|
await ctx.send(text)
|
||||||
|
|
||||||
|
|
||||||
def console_input():
|
def _print_commands():
|
||||||
bot_ready.wait()
|
"""Вывести список доступных консольных команд."""
|
||||||
print("Доступные команды:")
|
|
||||||
available = {k: v for k, v in ALL_CONSOLE_COMMANDS.items() if k != "stop"}
|
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):
|
for idx, (name, func) in enumerate(available.items(), 1):
|
||||||
print(f" {idx}. {name}")
|
print(f" {idx}. {name}")
|
||||||
print(" 0. stop")
|
print(" 0. stop")
|
||||||
|
|
||||||
|
|
||||||
|
def console_input():
|
||||||
|
bot_ready.wait()
|
||||||
|
_print_commands()
|
||||||
|
|
||||||
while not stop_event.is_set():
|
while not stop_event.is_set():
|
||||||
try:
|
try:
|
||||||
choice = input("\nВыберите команду (номер): ").strip()
|
choice = input("\nВыберите команду (номер): ").strip()
|
||||||
if choice == "0":
|
if choice == "0":
|
||||||
print("\nОстановка бота...")
|
print("\nОстановка бота...")
|
||||||
stop_event.set()
|
stop_event.set()
|
||||||
|
asyncio.run_coroutine_threadsafe(bot.close(), bot.loop).result(timeout=5)
|
||||||
break
|
break
|
||||||
try:
|
try:
|
||||||
|
available = {k: v for k, v in ALL_CONSOLE_COMMANDS.items() if k != "stop"}
|
||||||
idx = int(choice)
|
idx = int(choice)
|
||||||
if 0 < idx <= len(available):
|
if 0 < idx <= len(available):
|
||||||
cmd_name = list(available.keys())[idx - 1]
|
cmd_name = list(available.keys())[idx - 1]
|
||||||
@ -90,7 +97,8 @@ def console_input():
|
|||||||
else:
|
else:
|
||||||
print(f"Неизвестная команда: {choice}")
|
print(f"Неизвестная команда: {choice}")
|
||||||
except (ValueError, IndexError):
|
except (ValueError, IndexError):
|
||||||
print(f"Неизвестная команда: {choice}")
|
print(f"Неверный формат: {choice}")
|
||||||
|
_print_commands()
|
||||||
except (EOFError, KeyboardInterrupt):
|
except (EOFError, KeyboardInterrupt):
|
||||||
stop_event.set()
|
stop_event.set()
|
||||||
try:
|
try:
|
||||||
|
|||||||
@ -1,9 +1,7 @@
|
|||||||
import discord
|
import discord
|
||||||
from discord.ext import commands
|
from discord.ext import commands
|
||||||
import asyncio
|
|
||||||
import requests
|
|
||||||
|
|
||||||
_session = requests.Session()
|
from utils.cat import fetch_cat
|
||||||
|
|
||||||
|
|
||||||
class Cat(commands.Cog):
|
class Cat(commands.Cog):
|
||||||
@ -12,21 +10,14 @@ class Cat(commands.Cog):
|
|||||||
@commands.command(name="cat")
|
@commands.command(name="cat")
|
||||||
async def cat(self, ctx):
|
async def cat(self, ctx):
|
||||||
"""Получить случайного котика"""
|
"""Получить случайного котика"""
|
||||||
try:
|
url = await fetch_cat()
|
||||||
response = await asyncio.to_thread(
|
if url is None:
|
||||||
_session.get,
|
await ctx.send("Не удалось получить котика. Попробуйте позже.")
|
||||||
"https://api.thecatapi.com/v1/images/search",
|
return
|
||||||
timeout=10
|
|
||||||
)
|
|
||||||
response.raise_for_status()
|
|
||||||
data = response.json()
|
|
||||||
url = data[0]["url"]
|
|
||||||
|
|
||||||
embed = discord.Embed(
|
embed = discord.Embed(
|
||||||
title="🐱 Котик для тебя!",
|
title="Котик для тебя!",
|
||||||
color=discord.Color.orange()
|
color=discord.Color.orange()
|
||||||
)
|
)
|
||||||
embed.set_image(url=url)
|
embed.set_image(url=url)
|
||||||
await ctx.send(embed=embed)
|
await ctx.send(embed=embed)
|
||||||
except requests.exceptions.RequestException:
|
|
||||||
await ctx.send("Не удалось получить котика. Попробуйте позже.")
|
|
||||||
|
|||||||
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