слеш-команды пропадают из меню после использования
пишу бота на питон. задача: сделать возможным использование как коанд с кастомным префиксом, так и слеш-команд с таким же функционалом. работаю с библиотекой disnake. вот код :
import re
import asyncio
import datetime
import math
import disnake
from disnake.ext import commands
from disnake.ui import Button, View
from typing import Optional
import logging
import random
import string
from config import config
logging.basicConfig(
filename="main.log",
level=logging.DEBUG,
filemode="a",
format="[%(asctime)s] [%(levelname)s] %(message)s --- main.py str %(lineno)d",
)
logger = logging.getLogger("main.py")
# --- Настройки ---
BOT_PREFIX = config.get("bot_prefix")
TIME_FORMAT = config.get("time_format")
def get_current_time() -> str:
"""Возвращает текущее время в заданном формате."""
return (
datetime.datetime.now(datetime.timezone.utc).astimezone().strftime(TIME_FORMAT)
)
BOT_TOKEN = config.get("token")
intents = disnake.Intents.all()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix="=", intents=intents)
# , test_guilds=[xxx]
bot.remove_command("help")
# slash = SlashCommand(bot, sync_commands=True)
@bot.event
async def on_ready():
"""Called when the bot is connected to Discord."""
print(f"[{get_current_time()}] [START] Main.py started")
await bot.change_presence(
activity=disnake.Activity(
name=f"за УВД в сети", type=disnake.ActivityType.watching
)
)
@bot.slash_command(
name="help",
description="Помощь",
nsfw=False,
guild_ids=[xxx],
)
async def help(hel: disnake.CommandInteraction):
await hel.response.send_message(
"Список команд: \n"
"`=help` **- помощь** \n"
"`=marhelp` **- помощь по функционалу бракосочетаний** \n"
"`=qfe` **- рассчитать qfe** (Подробнее: `=qfe -h`) \n"
"`=m_ft` **- перевести из метров в футы** (Подробнее: `=m_ft -h`) \n"
"`=ft_m` **- перевести из футов в метры** (Подробнее: `=ft_m -h`) \n"
"`=link <VID>` **- привязать VID к аккаунту** \n"
"`=linkus <пользователь> <VID>` **- привязать VID к аккаунту** (доступно только администраторам) \n"
"Чтобы получить более подробную информацию по интересующей вас команде, используйте `<команда> -h` \n"
"или `<команда> --help`"
)
print(f"[{get_current_time()}] [COMPLETE] help-slash")
@bot.command()
async def help(hel, hlp=None):
guild = hel.guild
server_id = guild.id
if hlp == None:
if (
server_id == config.get("server_id")
or server_id == xxx
or config.get("linkable") == True
):
await hel.reply(
"Список команд: \n"
"`=help` **- помощь** \n"
"`=marhelp` **- помощь по функционалу бракосочетаний** \n"
"`=qfe` **- рассчитать qfe** (Подробнее: `=qfe -h`) \n"
"`=m_ft` **- перевести из метров в футы** (Подробнее: `=m_ft -h`) \n"
"`=ft_m` **- перевести из футов в метры** (Подробнее: `=ft_m -h`) \n"
"`=link <VID>` **- привязать VID к аккаунту** \n"
"`=linkus <пользователь> <VID>` **- привязать VID к аккаунту** (доступно только администраторам) \n"
"Чтобы получить более подробную информацию по интересующей вас команде, используйте `<команда> -h` \n"
"или `<команда> --help`"
)
print(f"[{get_current_time()}] [COMPLETE] help")
else:
await hel.reply(
"Список команд: \n `=help` **- помощь** \n `=qfe` **- рассчитать qfe** (Подробнее: `=qfe -h`) \n `=m_ft` **- перевести из метров в футы** (Подробнее: `=m_ft -h`) \n `=ft_m` **- перевести из футов в метры** (Подробнее: `=ft_m -h`) \nЧтобы получить более подробную информацию по интересующей вас команде, используйте `<команда> -h` \n или `<команда> --help`"
)
print(f"[{get_current_time()}] [COMPLETE] help-notourserver")
if hlp == "-h" or hlp == "--help":
await hel.reply("Выводит доступные команды")
print(f"[{get_current_time()}] [COMPLETE] hellp: -h")
elif hlp != None and hlp != "-h" and hlp != "--help":
await hel.reply("Ошиб: неверн ввод", ephemeral=True)
print(f"[{get_current_time()}] [ERROR] hellp: incorrect input")
@bot.slash_command(
name="allowicao",
description="Выдать пропуск в ICAO",
nsfw=False,
guild_ids=[xxx],
)
async def allowicao(
ctx: disnake.GuildCommandInteraction, member: disnake.Member, time: float = 1.0
):
guild = ctx.guild
server_id = guild.id
author = ctx.author
role1 = ctx.guild.get_role(config.get("icao_role_id"))
role2 = ctx.guild.get_role(xxx)
if server_id == config.get("server_id"):
if time <= 10.0:
if role1 in author.roles or role2 in author.roles:
if role1 in member.roles or role2 in member.roles:
await ctx.response.send_message(
f"Участник <@{member.id}> является действующим сотрудником ICAO."
)
else:
await ctx.response.send_message(
f"Участнику <@{member.id}> выдан пропуск на {time} час(ов)"
)
role = ctx.guild.get_role(config.get("icao_allow_role_id"))
print(f"[{get_current_time()}] [COMPLETE] icaoallow")
await member.add_roles(
role,
reason=f"[{get_current_time()}] sotrudnik icao {ctx.author} vidal propusk na {time} chasov",
)
icaoallo = f"<:{"IcaoAllow"}:{1394942011928346684}>"
timesleep = time * 3600
await asyncio.sleep(timesleep)
await member.remove_roles(
role,
reason=f"srok deistviya propuska podoshel k kontsu ({time} hours)",
)
await ctx.response.send_message(
f"Срок действия пропуска для {member} подошел к концу"
)
print(f"[{get_current_time()}] [COMPLETE] icaoallow deleterole")
icao = f"<:{"ICAO"}:{1398891798545563658}>"
else:
await ctx.response.send_message(
f"Это доступно только сотрудникам ICAO", ephemeral=True
)
else:
await ctx.response.send_message(
f"Пропуск можно дать на 10 часов или менее", ephemeral=True
)
@bot.command()
# @commands.has_role(config.get("icao_role_id"))
async def allowicao(ctx, member: disnake.Member, time: float = 1.0):
guild = ctx.guild
server_id = guild.id
author = ctx.message.author
role1 = ctx.guild.get_role(config.get("icao_role_id"))
role2 = ctx.guild.get_role(xxx)
if server_id == config.get("server_id"):
if time <= 10.0:
if role1 in author.roles or role2 in author.roles:
await ctx.reply(f"Участнику выдан пропуск на {time} час(ов)")
role = ctx.guild.get_role(config.get("icao_allow_role_id"))
print(f"[{get_current_time()}] [COMPLETE] icaoallow")
await member.add_roles(
role,
reason=f"[{get_current_time()}] sotrudnik icao {ctx.message.author} vidal propusk na {time} chasov",
)
icaoallo = f"<:{"IcaoAllow"}:{1394942011928346684}>"
await ctx.message.add_reaction(icaoallo)
timesleep = time * 3600
await asyncio.sleep(timesleep)
await member.remove_roles(
role,
reason=f"srok deistviya propuska podoshel k kontsu ({time} hours)",
)
await ctx.reply(f"Срок действия пропуска для {member} подошел к концу")
print(f"[{get_current_time()}] [COMPLETE] icaoallow deleterole")
# await ctx.message.delete_reaction(icaoallo)
icao = f"<:{"ICAO"}:{1398891798545563658}>"
await ctx.message.add_reaction(icao)
else:
await ctx.message.add_reaction("⛔")
await ctx.reply(f"Это доступно только сотрудникам ICAO")
else:
await ctx.message.add_reaction("⛔")
await ctx.reply(f"Пропуск можно дать на 10 часов или менее")
@bot.slash_command(
name="rejecticao",
description="Отобрать пропуск в ICAO",
nsfw=False,
guild_ids=[xxx],
)
async def rejecticao(
ctx: disnake.GuildCommandInteraction, member: disnake.Member, reason: str
):
guild = ctx.guild
server_id = guild.id
author = ctx.author
role2 = ctx.guild.get_role(xxx)
role = ctx.guild.get_role(config.get("icao_allow_role_id"))
if server_id == config.get("server_id"):
if role2 in author.roles:
if role in member.roles:
await ctx.response.send_message(f"Пропуск снят. Причина: {reason}")
print(f"[{get_current_time()}] [COMPLETE] icaoallow-delete")
await member.remove_roles(
role,
reason=f"({author}) snyal propusk (prichina: {reason})",
)
print(f"[{get_current_time()}] [COMPLETE] icaoallow deleterole")
# await ctx.message.delete_reaction(icaoallo)
else:
await ctx.response.send_message(
f"У участника нет пропуска.", ephemeral=True
)
else:
await ctx.response.send_message(f"Вы не уполномочены.", ephemeral=True)
@bot.command()
async def rejecticao(ctx, member: disnake.Member, reason: str = "NE UKAZANO"):
guild = ctx.guild
server_id = guild.id
author = ctx.message.author
role2 = ctx.guild.get_role(xxx)
role = ctx.guild.get_role(config.get("icao_allow_role_id"))
if server_id == config.get("server_id"):
if role2 in author.roles:
if role in member.roles:
await ctx.reply(f"Пропуск снят. Причина: {reason}")
print(f"[{get_current_time()}] [COMPLETE] icaoallow-delete")
await member.remove_roles(
role,
reason=f"({author}) snyal propusk (prichina: {reason})",
)
print(f"[{get_current_time()}] [COMPLETE] icaoallow deleterole")
# await ctx.message.delete_reaction(icaoallo)
await ctx.message.add_reaction("❎")
else:
await ctx.message.add_reaction("⛔")
await ctx.reply(f"У участника нет пропуска.")
else:
await ctx.message.add_reaction("⛔")
await ctx.reply(f"Вы не уполномочены.")
@bot.slash_command(
name="fuck",
description="Наказать",
nsfw=False,
guild_ids=[xxx],
)
async def fuck(ctx: disnake.GuildCommandInteraction, member: disnake.Member):
guild = ctx.guild
server_id = guild.id
author = ctx.author
memb = member.id
role2 = ctx.guild.get_role(xxx)
role1 = ctx.guild.get_role(xxx)
if server_id == config.get("server_id"):
if (
role2 in author.roles
or role1 in author.roles
or ctx.author.id == xxx
):
emb = disnake.Embed(
colour=disnake.Color.greyple(),
)
emb.set_image(
url="https://production-clubhouse-avatars.s3.amazonaws.com/club_1099857793_b297f6d9-a9c4-4bc8-9ae1-4ee0496be449_thumbnail_250x250"
)
# await ctx.send(f"Участник <@{memb}> был наказан.")
await ctx.send(f"<@{memb}> был наказан.", embed=emb)
logger.info(f"админ {ctx.author.id} наказан {memb}")
else:
await ctx.response.send_message(f"Вы не уполномочены.", ephemeral=True)
@bot.command()
async def fuck(ctx, member: disnake.Member):
guild = ctx.guild
server_id = guild.id
author = ctx.message.author
memb = member.id
role2 = ctx.guild.get_role(xxx)
role1 = ctx.guild.get_role(xxx)
if server_id == config.get("server_id"):
if (
role2 in author.roles
or role1 in author.roles
or ctx.message.author.id == xxx
):
emb = disnake.Embed(
colour=disnake.Color.greyple(),
)
emb.set_image(
url="https://production-clubhouse-avatars.s3.amazonaws.com/club_1099857793_b297f6d9-a9c4-4bc8-9ae1-4ee0496be449_thumbnail_250x250"
)
# await ctx.send(f"Участник <@{memb}> был наказан.")
await ctx.send(f"<@{memb}> был наказан.", embed=emb)
logger.info(f"админ {ctx.message.author.id} наказал {memb}")
else:
await ctx.message.add_reaction("⛔")
await ctx.reply(f"Вы не уполномочены.")
# --- Запуск бота ---
bot.run(BOT_TOKEN)
все работает, но после использования одной из слеш-команд из мею пропадают все команды бота. как это исправить?
Источник: Stack Overflow на русском