async def on_command_error(error, ctx):
if isinstance(error, commands.BadArgument):
await ctx.send("Запрос команды с ошибочным аргументом")
elif isinstance(error, commands.CommandNotFound):
await Client.send_message(ctx.message.channel, "Команда не найдена")
... # вставлять новые проверки сюда
else:
await Client.send_message(ctx.message.channel, "Неизвестная ошибка")
result is None and chann is not None
inviter_id будет None.inviter_id = None
if result is not None:
...
if chann:
embed = nextcord.Embed(
title='Leafy InviteLogger',
description=f'{member.mention} join the server!\n\n Invited by <@{inviter_id}>\n Total invitations {total_invites}',
colour=0x2b2d31
)
coroutine 'ApplicationContext.respond' was never awaited
ctx.respond(f'Вы уже использовали {us} из {kyp}',ephemeral=True)
await ctx.respond(embed=embedvar,ephemeral=True)
INSERT ... ON CONFLICT ... UPDATE
Не работает on_member_join?
import discord
class MyClient(discord.Client):
async def on_member_join(self, member):
guild = member.guild
if guild.system_channel is not None:
msg = f'{member.mention} добро пожаловать на сервер {guild.name}!'
await guild.system_channel.send(msg)
intents = discord.Intents.default()
intents.members = True
client = MyClient(intents=intents)
client.run('token')
Не работает код Discord.py?Да не работает.
библиотеки нужные я установилЗначит не установили, иначе yarl бы подтянулся
➜ ~ (test) pip install discord
...
➜ ~ (test) pip freeze | cat
aiohttp==3.8.5
aiosignal==1.3.1
async-timeout==4.0.3
attrs==23.1.0
charset-normalizer==3.2.0
discord==2.3.2
discord.py==2.3.2
frozenlist==1.4.0
idna==3.4
multidict==6.0.4
yarl==1.9.2
Python 3.1.1Что правда 3.1.1?
# checks.py
from discord.ext import commands
def is_owner():
async def predicate(ctx: commands.Context) -> bool:
return ctx.author.id == ctx.guild.owner_id:
return commands.check(predicate)
@bot.command()
@checks.is_owner()
async def test(ctx):
await ctx.send('You can manage messages.')
Как внедрить меню dropdown?Как написано в документации и примерах использования dropdown
(желательно ответьте куском кода )
import discord
from discord.ext import commands
class Dropdown(discord.ui.Select):
def __init__(self):
options = [
discord.SelectOption(label='Red', description='Your favourite colour is red', emoji=''),
discord.SelectOption(label='Green', description='Your favourite colour is green', emoji=''),
discord.SelectOption(label='Blue', description='Your favourite colour is blue', emoji=''),
]
super().__init__(placeholder='Choose your favourite colour...', min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Your favourite colour is {self.values[0]}')
class DropdownView(discord.ui.View):
def __init__(self):
super().__init__()
self.add_item(Dropdown())
class Bot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
bot = Bot()
@bot.command()
async def colour(ctx):
view = DropdownView()
await ctx.send('Pick your favourite colour:', view=view)
bot.run('token')
Многие используют from discord_slash import SlashCommandСмелое заявление о библиотеке, которая не обновлялась с 2021 года. У нее уже даже архивный репозиторий удалили и ссылка ведет на interactions.py.
Как создать слеш команды на discord.py?Открыть examples библиотеки, например basic.py, вставить свой токен и запустить. Все примеры снабжены исчерпывающими комментариями.
@bot.command
async def mute(ctx, member: discord.Member):
await member.edit(mute=True)
@client.command()
@commands.has_permissions(ban_members = True)
async def ban(ctx, member : discord.Member, *, reason = None):
await member.ban(reason = reason)
guild_ids=[TESTING_GUILD_ID]
, но и в этом случае команды нужно синхронизировать. @disnake.ui.button(label="Disable the view", style=disnake.ButtonStyle.grey)
async def disable_button(self, button: disnake.ui.Button, inter: disnake.MessageInteraction):
# We disable every single component in this view
for child in self.children:
if isinstance(child, disnake.ui.Button):
child.disabled = True
# make sure to update the message with the new buttons
await inter.response.edit_message(view=self)