@Ildarich

Как сделать обновление кнопок?

У меня в боте есть кнопки, отвечающие за выключение/включение уведомлений6378a78524334686372959.png

Нажимаешь на кнопку и нужная роль удаляется/добавляется. Все работает, но одно "но". Мне нужно, чтоб после нажатия на зеленую кнопку, она становилась красной и наоборот.6378a83e54619179004224.png

P.S.: Красная кнопка выдает роль уведомления, а зеленая - удаляет.
  • Вопрос задан
  • 142 просмотра
Решения вопроса 1
Alexandre888
@Alexandre888 Куратор тега discord.js
Javascript-разработчик
const defaultButtonGreen = new ActionRowBuilder()
  .addComponents(
    new ButtonBuilder()
    .setCustomId('defaultButtonGreen')
    .setLabel('green')
    .setStyle(ButtonStyle.Success),
  ),
  defaultButtonRed = new ActionRowBuilder()
  .addComponents(
    new ButtonBuilder()
    .setCustomId('defaultButtonRed')
    .setLabel('red')
    .setStyle(ButtonStyle.Danger),
  );

await interaction.reply({ content: "message", components: [defaultButtonGreen, defaultButtonRed] });
const message = await interaction.fetchReply();

const collector = message.createMessageComponentCollector({
  componentType: ComponentType.Button,
  time: 60000
});

collector.on('collect', async i => {
  if (i.customId === "defaultButtonGreen") {
    defaultButtonGreen.components[0].setStyle(
      defaultButtonGreen.components[0].data.style === 3 ? ButtonStyle.Danger : ButtonStyle.Success
    );

    await i.update({ components: [defaultButtonGreen, defaultButtonRed] })
  } else if (i.customId === "defaultButtonRed") {
    defaultButtonRed.components[0].setStyle(
      defaultButtonRed.components[0].data.style === 4 ? ButtonStyle.Success : ButtonStyle.Danger
    );

    await i.update({ components: [defaultButtonGreen, defaultButtonRed] })
  }
});

по нажатию на одну из двух кнопок, она будет менять цвет на противоположный (красный => зелёный, зелёный => красный).
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
Syjalo
@Syjalo
Представьте себе бота
У вас есть ряды с кнопками. Можно просто находить нужную кнопку и роль, менять цвет кнопки и добавлять или снимать роль.
const roleIds = {
  giveaways: 'id',
  events: 'id',
}

const hasRole = (customId) => interaction.member.roles.cache.has(roleIds[customId]);
const getStyle = (customId) => hasRole(customId) ? ButtonStyle.Success : ButtonStyle.Danger;

const components = [
  new ActionRowBuilder()
    .setComponents(
      new ButtonBuilder()
        .setCustomId('giveaways')
        .setLabel('Конкурсы')
        .setStyle(getStyle('giveaways'))
    ),
  new ActionRowBuilder()
    .setComponents(
      new ButtonBuilder()
        .setCustomId('events')
        .setLabel('Ивенты')
        .setStyle(getStyle('events'))
    ),
]

const response = await interaction.reply({ components });

const collector = response.createMessageComponentCollector({
  componentType: ComponentType.Button,
  filter: (i) => i.user.id === interaction.user.id,
  time: 60000,
});

collector.on('collect', async (i) => {
  const { customId } = i;
  const roleId = roleIds[customId];

  if (hasRole(customId)) await i.member.roles.remove(roleId);
  else await i.member.roles.add(roleId);

  components
    .flatMap((row) => row.components)
    .find((component) => component.customId === customId)
    .setStyle(getStyle(customId));

  await i.update({ components });
});

collector.on('ignore', async (i) => await i.reply({ content: 'Не для вас', ephemeral: true }));

Для добавления новой кнопки нужно просто добавить новый ряд и добавить id роли в объект.
Ответ написан
Комментировать
Ваш ответ на вопрос

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

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