Как разрешить доступ к команде только людям с определённым id?
Я пишу discord бота(discord.py) на python, и мне нужна функция, которая будет прибавляет к полю xp пользователя указанное число xp, если id того, кто её вызвал, находится в списке admins. Вот то что я сделал:
@bot.command()
async def add_xp(ctx, member: discord.Member=None, xp=None):
"""Функция add_xp прибавляет к полю xp пользователя указанное число xp.
(только для админов).
"""
if member is None:
emb = discord.Embed(title="Укажите пользователя!", colour=discord.Colour.red())
await ctx.send(embed=emb)
else:
if xp is None:
emb = discord.Embed(title="Укажите количество XP!", colour=discord.Colour.red())
await ctx.send(embed=emb)
else:
emb = discord.Embed(title=f"Пользователю {member} добавлено {xp}XP", colour=discord.Colour.green())
cursor.execute(f"UPDATE users SET xp = xp + {xp} WHERE id = {member.id}")
await ctx.send(embed=emb)
await ctx.message.delete()
Как реализовать проверку id пользователя? Желательно чтобы не внутри функции, а в декораторе каком-нибудь.
Ответы (2 шт):
Автор решения: sigalgleb
→ Ссылка
Получить имя автора вызванной команды:
username = ctx.message.author.name
Если хотите посмотреть в сторону декораторов, то могу предложить такой вектор решения:
admins = ['admin'] # список администраторов
def admin_access(username):
def wrapper(func):
if username in admins: # проверяем находится ли пользователь в списке администраторов
func() # вызываем функцию прибавления XP
else:
... # выводим уведомление при необходимости
print('Пользователь не администратор')
return wrapper
@admin_access(username='admin')
@bot.command()
async def add_xp(ctx, member: discord.Member=None, xp=None):
...
Автор решения: Be3y4uu_K0T
→ Ссылка
Вы можете использовать специальные декораторы:
@commands.is_owner()@commands.has_role('Admin')@commands.has_any_role('Admin', 'Administrator')@commands.has_permissions(administrator=True, ban_members=True)
from discord.ext import commands
import discord as ds
import config
bot = commands.Bot(commands.when_mentioned_or(config.bot_prefix), owner_ids=config.owner_ids)
@commands.is_owner()
async def test1(ctx):
await ctx.reply('You\'re owner! In owner_ids!')
@commands.has_role('Admin')
async def test2(ctx):
await ctx.reply('You have role "Admin"!')
@commands.has_role(11432413241)
async def test3(ctx):
await ctx.reply('You have role by id 11432413241!')
@commands.has_any_role('Admin', 'Administrator')
async def test4(ctx):
await ctx.reply('You have role "Admin" or "Administrator"!')
@commands.has_permissions(administrator=True, ban_members=True)
async def test5(ctx):
await ctx.reply('You can administer the server and ban members!')
bot.run(config.ds_token, reconnect=True)
config.py
ds_token = '<token>'
guild_ids = {<guild_id>}
owner_ids = {<your_id>}
bot_prefix = '<command_prefix>'