@Telmor

Как выдать роль по кнопке в discord.py?

У меня есть команда, которую я вызываю и появляются 5 кнопок. Нажимая на которые ПОЛЬЗОВАТЕЛИ которые захотят нажимают на кнопку и получают роль, а если ещё раз то убирают. Вопрос в чём: как сделать бесконечную кнопку (чтобы на неё можно было кликать не только вызвавшему команду, но и всем остальным пользователям сервера, но и сколько угодно раз), как отследить кто именно нажал кнопку (чтобы выдать роль).
Мой код:
@bot.command(aliases='ВыдачаИгровыхРолей')
async def __giveplayroles__(ctx):
    await ctx.channel.purge(limit = 1)
    msg = await ctx.send(
        emb = discord.Embed(title='Игровые Роли',color=0xE7EEF5, description=f'Нажмите на кнопку что бы получить роль, что бы убрать роль нажмите второй раз.'),
        components = [
            Button(style = ByttonStyle.blue, label = 'Rust'),
            Button(style = ByttonStyle.blue, label = 'Dota 2'),
            Button(style = ByttonStyle.blue, label = 'CS:GO'),
            Button(style = ByttonStyle.blue, label = 'Genshin Impact'),
            #Button(style = ByttonStyle.blue, label = 'Osu!'),
            #Button(style = ByttonStyle.blue, label = 'Minecraft'),
            #Button(style = ByttonStyle.blue, label = 'GTA')
        ])
     responce = await bot.wait_for('button_click')
     if responce.component.label == 'Rust':
        role = discord.utils.get(ctx.author.server.roles, id=864796640929251349)
        if not role in ctx.author.roles:
          role = discord.utils.get(ctx.author.guild.roles, id=864796640929251349)
          await member.add_roles(role)
  • Вопрос задан
  • 7030 просмотров
Пригласить эксперта
Ответы на вопрос 2
@x4zx
python developer
import discord
from discord import member
from discord.ext import commands
from dislash import InteractionClient, ActionRow, Button, ButtonStyle

intents = discord.Intents.all()
bot = commands.Bot(command_prefix = "!", intents = intents)
bot.remove_command("help")

inter_client = InteractionClient(bot)

@bot.event
async def on_ready():
    print(f'Вы вошли как {bot.user}')

@bot.command()
async def verif(ctx):

    emb = discord.Embed(
        description = 
        f"""
        Здраствуйте вы попали на сервер {ctx.guild.name}, пройдите верификацию чтобы получить доступ к другим каналам.
        """,
        colour = 0xFF8C00
    )
    emb.set_thumbnail(url = 'https://cdn.discordapp.com/attachments/772850448892690462/880752123418136596/947d1f802c858b540b84bc3000fc2439_1_-removebg-preview.png')
    emb.set_author(name = 'Верификация')

    row = ActionRow(
        Button(
            style = ButtonStyle.gray,
            label = 'Верифицироваться',
            custom_id = 'verif_button'
        )
    )
    await ctx.send(embed = emb, components = [row])

@bot.event
async def on_button_click(inter):

    res = 'Вы успешно верифицировались!' # ваш вывод сообщение что человек получил роль
    guild = bot.get_guild(inter.guild.id)

    if inter.component.id == "verif_button":
        verif = guild.get_role(id вашей роли)
        member = inter.author
        await member.add_roles(verif)
        await inter.reply(res, ephemeral = True)
Ответ написан
@Dovolen_toboy
P.s для ребят,которые ищут ответ и код
Ловите код для выдачи роли по кнопке. Верификация лишь пример

class Verify_button (disnake.ui.View):
    def __init__ (self):
        super().__init__(timeout=None)
        self.value: Optional[bool] = None

    @disnake.ui.button(label='Верифицироваться',style=disnake.ButtonStyle.green,emoji='✅')
    async def verify(self,button:disnake.Button,interaction:disnake.Interaction):
        role = interaction.guild.get_role(926372966487453726)
        verify_role = interaction.guild.get_role(1068443146586947634)
        await interaction.user.remove_roles(verify_role)
        await interaction.user.add_roles(role)
        await interaction.response.send_message('Вы успешно прошли верификацию!',ephemeral=True)


class Verify(commands.Cog):
    def __init__(self,bot) :
        self.bot = bot
        print('Module {} is loaded'.format(self.__class__.__name__))

    
    @commands.command(name='verify')
    @commands.has_permissions(administrator=True)
    async def verify(self,ctx):
        view=Verify_button()
        verify_embed = disnake.Embed(
            title='Верификация',
            description='Пройдите верификацию чтобы продолжить общение!'
        )
        await ctx.send(embed=verify_embed,view=view)
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы