applications.commands
.applications.commands
вы можете в разделе "OAuth" в панели управления:def is_special():
async def predicate(ctx):
guild = bot.get_guild(365017572336731127)
if not (member := guild.get_member(ctx.author.id)):
return
return guild.get_role(129386605897151407) in member.roles
return commands.check(predicate)
@bot.command()
@is_special()
async def cmd(ctx, ...):
...
import logging
...
log = logging.get_logger("mybot")
@client.event
async def on_reaction_add(reaction, user):
if reaction.message.channel.id != 815951876708892672:
log.debug("Игнорируем реакцию в канале %s", reaction.message.channel.name)
return
if reaction.emoji == "\N{PISTOL}": # Указываем символ юникода по его имени, в данном случае - https://www.fileformat.info/info/unicode/char/1f52b/index.htm
role = discord.utils.get(user.server.roles, name="PUBG") # CamelCase/CapWords названия переменных, по хорошему, должны использоваться только для названий классов: https://www.python.org/dev/peps/pep-0008/#class-names
await user.add_roles(role)
log.info("Выдал роль %s пользователю %s", role.name, user.name)
requirements.txt
должен содержать только названия библиотек доступных в индексе PyPi.discord.ext
и discord.utils
- части, включенные в библиотеку discord.py
, не нужно их указывать отдельно, так как отдельно их и не существует @bot.event
async def on_message(message):
if not message.author.bot and bot.user in message.mentions:
await message.reply("Im doing things")
await bot.process_commands(message)
repr(role)
).", ".join(m.mention for m in ctx.author.roles)
discord.py
имеет "расширение" для команд, с вещью, под названием "конвертеры", используйте их.@bot.command()
async def massrole(ctx, role: discord.Role): # discord.Role здесь будет использоваться как конвертер:
# https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.RoleConverter
for member in ctx.guild:
if role not in member.roles:
await member.add_roles(role)
if amount > 100:
await ctx.send("Too many messages, aborting...")
return
if ctx.message.reference and (msg := ctx.message.reference.resolved) and isinstance(msg, discord.Message):
await ctx.send(msg.content)
else:
await ctx.send("You need to reply to an existing message")
def is_booster(): # https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#checks
"""Check if author is guild booster"""
async def predicate(ctx):
return ctx.author.premium_since
return commands.check(predicate)
@bot.command()
@is_booster()
async def cmdname(ctx):
...
@commands.has_role
принимает в качестве аргумента целое число, и данный аргумент не является именованным (**kwargs, arg=value): @commands.has_role(419038437452554077)
Подскажите, как исправить ошибку
@bot.command()
async def test(ctx):
msg = "hello"
for server in bot.guilds:
for channel in server.channels:
...
bot.leave_guild
не существует в текущей версии библиотеки. Большая часть функциональности в rewrite версии библиотеки была перемещена в соответствующие модели. on_connect
вызывается при подключении к Discord, а не при добавлении бота на сервер.on_guild_join
: https://discordpy.readthedocs.io/en/stable/api.htm...GUILD_BLACKLIST = [779450659245255793, 853811295717358421, ...] # Список ID
@bot.event
async def on_guild_join(guild):
if guild.id in GUILD_BLACKLIST:
print(f"Guild {guild.name} ({guild.id}) is blacklisted! Leaving…"
await guild.leave()