channel_id = ... # достаете из БД или оттуда где у вас хранится id нужного канала
channel = bot.get_channel(channel_id)
channel.send(feedback_message.content)
async def fruit_autocomplete(
interaction: discord.Interaction,
current: str,
) -> List[app_commands.Choice[str]]:
fruits = ... # Список данных полученный из БД
... # Фильтрация списка
return [
app_commands.Choice(name=fruit, value=fruit)
for fruit in fruits if current.lower() in fruit.lower()
]
@app_commands.command()
@app_commands.autocomplete(fruit=fruit_autocomplete)
async def fruits(interaction: discord.Interaction, fruit: str):
await interaction.response.send_message(f'Your favourite fruit seems to be {fruit}')
if not (duration is MISSING) ^ (until is MISSING):
raise ValueError("Exactly one of `duration` and `until` must be provided")
payload: Dict[str, Any] = {}
if duration is not MISSING:
if duration is None:
until = None
elif isinstance(duration, datetime.timedelta):
until = utils.utcnow() + duration
else:
until = utils.utcnow() + datetime.timedelta(seconds=duration)
# at this point `until` cannot be `MISSING`
payload["communication_disabled_until"] = utils.isoformat_utc(until)
data = await self._state.http.edit_member(self.id, user.id, reason=reason, **payload)
return Member(data=data, guild=self, state=self._state)
@client.command()
@app_commands.checks.has_any_role('Library Devs', 'Moderators', 492212595072434186)
async def cool(interaction: discord.Interaction):
await interaction.response.send_message('Сообщение увидит только человек с соответствующей ролью')
str
int
float
bool
disnake.abc.GuildChannel*
disnake.User or disnake.Member**
disnake.Role**
disnake.Attachment
disnake.abc.Snowflake***
Как исправить ошибкуЛибо переписать функцию, потому что во взаимодействии нет методов и атрибутов, которые вы пытаетесь использовать, либо оставить команду обычной.
for key, value in inter.text_values.items():
embed.add_field(
name=key.capitalize(),
value=value[:1024],
inline=False,
)
embed.add_field(
name='Заголовок',
value=f'{inter.text_values.get("date", "")}{inter.text_values.get("time", "")',
inline=False,
)
В чём проблема?В том что класс staffapp наследуется от commands.Cog, а не ui.Modal. Эффекта от того что вы сделаете в произвольном классе функцию callback не будет.
<@user_id>
. Любая работа с ней аналогична работе со строками.class Simple(disnake.ui.View):
"""
Embed Paginator.
Parameters:
----------
timeout: int
How long the Paginator should timeout in, after the last interaction. (In seconds) (Overrides default of 60)
PreviousButton: disnake.ui.Button
Overrides default previous button.
NextButton: disnake.ui.Button
Overrides default next button.
PageCounterStyle: disnake.ButtonStyle
Overrides default page counter style.
InitialPage: int
Page to start the pagination on.
"""
def __init__(self, *,
timeout: int = 60,
PreviousButton: disnake.ui.Button = disnake.ui.Button(emoji=disnake.PartialEmoji(name="\U000025c0")),
NextButton: disnake.ui.Button = disnake.ui.Button(emoji=disnake.PartialEmoji(name="\U000025b6")),
PageCounterStyle: disnake.ButtonStyle = disnake.ButtonStyle.grey,
InitialPage: int = 0) -> None:
self.PreviousButton = PreviousButton
self.NextButton = NextButton
self.PageCounterStyle = PageCounterStyle
self.InitialPage = InitialPage
self.pages = None
self.ctx = None
self.message = None
self.current_page = None
self.page_counter = None
self.total_page_count = None
super().__init__(timeout=timeout)
async def start(self, ctx: commands.Context, pages: list[disnake.Embed]):
self.pages = pages
self.total_page_count = len(pages)
self.ctx = ctx
self.current_page = self.InitialPage
self.PreviousButton.callback = self.previous_button_callback
self.NextButton.callback = self.next_button_callback
self.page_counter = SimplePaginatorPageCounter(style=self.PageCounterStyle,
TotalPages=self.total_page_count,
InitialPage=self.InitialPage)
self.add_item(self.PreviousButton)
self.add_item(self.page_counter)
self.add_item(self.NextButton)
self.message = await ctx.send(embed=self.pages[self.InitialPage], view=self)
async def previous(self):
if self.current_page == 0:
self.current_page = self.total_page_count - 1
else:
self.current_page -= 1
self.page_counter.label = f"{self.current_page + 1}/{self.total_page_count}"
await self.message.edit(embed=self.pages[self.current_page], view=self)
async def next(self):
if self.current_page == self.total_page_count - 1:
self.current_page = 0
else:
self.current_page += 1
self.page_counter.label = f"{self.current_page + 1}/{self.total_page_count}"
await self.message.edit(embed=self.pages[self.current_page], view=self)
async def next_button_callback(self, interaction: disnake.Interaction):
if interaction.user != self.ctx.author:
embed = disnake.Embed(description="You cannot control this pagination because you did not execute it.",
color=disnake.Colour.red())
return await interaction.response.send_message(embed=embed, ephemeral=True)
await interaction.response.defer()
await self.next()
async def previous_button_callback(self, interaction: disnake.Interaction):
if interaction.user != self.ctx.author:
embed = disnake.Embed(description="You cannot control this pagination because you did not execute it.",
color=disnake.Colour.red())
return await interaction.response.send_message(embed=embed, ephemeral=True)
await interaction.response.defer()
await self.previous()
class SimplePaginatorPageCounter(disnake.ui.Button):
def __init__(self, style: disnake.ButtonStyle, TotalPages, InitialPage):
super().__init__(label=f"{InitialPage + 1}/{TotalPages}", style=style, disabled=True)
embeds = [disnake.Embed(title="First embed"),
disnake.Embed(title="Second embed"),
disnake.Embed(title="Third embed")]
await Simple().start(ctx, pages=embeds)
Реализация «Формы» как это сделать?Открыть документацию и посмотреть
Реализация в плане кода. Подойдёт простой пример создания "Формы"Ну ладно, откроем её
import asyncio
import os
import disnake
from disnake.ext import commands
bot = commands.Bot(command_prefix=commands.when_mentioned)
class MyModal(disnake.ui.Modal):
def __init__(self) -> None:
components = [
disnake.ui.TextInput(
label="Name",
placeholder="The name of the tag",
custom_id="name",
style=disnake.TextInputStyle.short,
min_length=5,
max_length=50,
),
disnake.ui.TextInput(
label="Content",
placeholder="The content of the tag",
custom_id="content",
style=disnake.TextInputStyle.paragraph,
min_length=5,
max_length=1024,
),
]
super().__init__(title="Create Tag", custom_id="create_tag", components=components)
async def callback(self, inter: disnake.ModalInteraction) -> None:
tag_name = inter.text_values["name"]
tag_content = inter.text_values["content"]
embed = disnake.Embed(title=f"Tag created: `{tag_name}`")
embed.add_field(name="Content", value=tag_content)
await inter.response.send_message(embed=embed)
async def on_error(self, error: Exception, inter: disnake.ModalInteraction) -> None:
await inter.response.send_message("Oops, something went wrong.", ephemeral=True)
@bot.slash_command()
async def create_tag(inter: disnake.CommandInteraction):
await inter.response.send_modal(modal=MyModal())
@bot.event
async def on_ready():
print(f"Logged in as {bot.user} (ID: {bot.user.id})\n------")
if __name__ == "__main__":
bot.run(os.getenv("BOT_TOKEN"))
on_raw_reaction_add
и метод await bot.wait_for()
относятся к низкоуровневым компонентам библиотеки и их использование оправдано только если нет других способов решения проблемы.while True
, а во вторых все нажатия на реакции начнут приводить к выполнению логики Почему команды бота(disnake) не обновляются?Потому что в коде есть какая-то ошибка, препятствующая обновлению. Например намудрили с декораторами.
Команда работает верно, но почему-то в боте( слэш командах ) она не показывается, уже прошел день.Слеш-команда не может верно работать, если она не показывается. Вероятно вы сделали префикс "/", что делать нельзя, поскольку с ним слеш-команды работать не будут.
Почему команды бота(discord.py) не обновляются?Во-первых для разработки объявляется тестовый сервер и обновление на нем происходит мгновенно
bot = commands.Bot("!", test_guilds=[123456789, 987654321])