@asapxgod

Почему не отправляются данные в канал и в консоли данные показываются undefined?

// создание клиента Discord
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers] });

// импорт каналов
const applicationChannel = client.channels.cache.get('1205947644791496744'); // замените ID_КАНАЛА_ЗАЯВОК на ID нужного канала
const acceptChannel = client.channels.cache.get('1205947644791496744'); // замените ID_КАНАЛА_ПРИНЯТИЯ на ID нужного канала
const declineChannel = client.channels.cache.get('1205947644791496744'); // замените ID_КАНАЛА_ОТКЛОНЕНИЯ на ID нужного канала

// функция, которая вызывается при получении нового сообщения
client.on('messageCreate', (message) => {
  // проверка, что сообщение является командой для создания кнопки
  if (message.content === '!createApplicationButton') {
    console.log('Получено сообщение с текстом: ' + message.content);
    // создание новой строки сообщения
    const actionRow = new ActionRowBuilder()
      // создание кнопки с идентификатором "submitApplication" и лейблом "Отправить заявку"
      .addComponents(
        new ButtonBuilder()
          .setCustomId('verification')
          .setLabel('Отправить заявку')
          .setStyle(ButtonStyle.Primary)
          // разрешение администратора для кнопки
      );

    // отправка сообщения с кнопкой в канал
    message.channel.send({ content: 'Нажмите кнопку, чтобы отправить заявку', components: [actionRow] });
  }
});

// инициализация клиента и подключение к Discord
client.on('interactionCreate', async interaction => {
  if (!interaction.isButton()) return;

  if (interaction.customId === 'verification') {
    console.log('Нажата кнопка с ID: ' + interaction.customId);
    // Create the modal
    const modal = new ModalBuilder()
      .setCustomId('myModal')
      .setTitle('My Modal');

    // Add components to modal

    // Create the text input components
    const favoriteColorInput = new TextInputBuilder()
  .setCustomId('yourFavoriteColorInput') // <-- Измените ID
  .setLabel("What's your favorite color?")
  .setStyle(TextInputStyle.Short)
  .setValue(interaction.components.find(component => component.customId === 'favoriteColorInput').value);

const hobbiesInput = new TextInputBuilder()
  .setCustomId('yourHobbiesInput') // <-- Измените ID
  .setLabel("What's some of your favorite hobbies?")
  .setStyle(TextInputStyle.Paragraph)
  .setValue(interaction.components.find(component => component.customId === 'hobbiesInput').value);


    // An action row only holds one text input,
    // so you need one action row per text input.
    const firstActionRow = new ActionRowBuilder().addComponents(favoriteColorInput);
    const secondActionRow = new ActionRowBuilder().addComponents(hobbiesInput);

    // Add inputs to the modal
    modal.addComponents(firstActionRow, secondActionRow);

    // Show the modal to the user
    await interaction.showModal(modal);
  }
});

// обработка модального окна
client.on('interactionCreate', async interaction => {
  if (!interaction.isModalSubmit()) return;

  if (interaction.customId === 'myModal') {
    const favoriteColor = interaction.components[0].value;
    const hobbies = interaction.components[1].value;

    console.log('В модальном окне введено:');
    console.log('Любимый цвет: ' + favoriteColor);
    console.log('Хобби: ' + hobbies);

    // функция для отправки данных в канал
    async function sendDataToChannel(interaction, favoriteColor, hobbies) {
      if (!applicationChannel) return;

      const embed = new MessageEmbed()
        .setTitle('Новые данные от пользователя')
        .setColor('#00FF00')
        .addField('Любимый цвет:', favoriteColor)
        .addField('Хобби:', hobbies);

      const acceptButton = new ButtonBuilder()
        .setCustomId('accept')
        .setLabel('Принять')
        .setStyle(ButtonStyle.Success);

      const declineButton = new ButtonBuilder()
        .setCustomId('decline')
        .setLabel('Отклонить')
        .setStyle(ButtonStyle.Danger);

      const actionRow = new ActionRowBuilder()
        .addComponents(acceptButton, declineButton);

      const message = await applicationChannel.send({ embeds: [embed], components: [actionRow] });

      // Добавить обработку события нажатия кнопки

      message.awaitInteractions({
        filter: buttonInteraction => buttonInteraction.isButton(),
        time: 15000,
        max: 1,
      }).then(async collected => {
        const buttonInteraction = collected.first();

        if (buttonInteraction.customId === 'accept') {
          console.log('Заявка принята');
          // Обработать принятие заявки
          // ...

          // Удалить сообщение с кнопками
          await message.delete();

          // Отправить сообщение в канал "Принятые"
          await acceptChannel.send(`Заявка от ${interaction.user.username} **принята**!`);
        } else if (buttonInteraction.customId === 'decline') {
          console.log('Заявка отклонена');
          // Обработать отклонение заявки
          // ...

          // Удалить сообщение с кнопками
          await message.delete();

          // Отправить сообщение в канал "Отклоненные"
          await declineChannel.send(`Заявка от ${interaction.user.username} **отклонена**!`);
        }

        await buttonInteraction.reply({ content: 'Спасибо за ваш ответ!', ephemeral: true });
      });
    }

    await sendDataToChannel(interaction, favoriteColor, hobbies);

    interaction.reply({ content: 'Спасибо за ваши данные!', ephemeral: true });
  }
});

client.login('токен');
  • Вопрос задан
  • 42 просмотра
Пригласить эксперта
Ваш ответ на вопрос

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

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