Untitled

mail@pastecode.io avatar
unknown
javascript
a year ago
5.8 kB
1
Indexable
Never
const { Client, GatewayIntentBits, MessageEmbed } = require('discord.js');
const fetch = require('node-fetch');
const { SlashCommandBuilder } = require('discord.js-slash-commands');

const client = new Client({
  intents: [GatewayIntentBits.Guilds],
});

// Map to store user configurations
const userConfigurations = new Map();

client.once('ready', () => {
  console.log(`Bot is online!`);

  // Register the slash commands
  const commands = [
    new SlashCommandBuilder()
      .setName('setaparat')
      .setDescription('Set up Aparat live alerts')
      .addStringOption((option) =>
        option
          .setName('username')
          .setDescription('Your Aparat username')
          .setRequired(true)
      )
      .addStringOption((option) =>
        option
          .setName('message')
          .setDescription('Custom notification message')
      )
      .addChannelOption((option) =>
        option
          .setName('channel')
          .setDescription('Channel to send live alerts')
      ),
    new SlashCommandBuilder()
      .setName('help')
      .setDescription('Show bot commands and their descriptions'),
    new SlashCommandBuilder()
      .setName('cancelaparat')
      .setDescription('Cancel Aparat live alerts')
      .addStringOption((option) =>
        option
          .setName('username')
          .setDescription('Your Aparat username')
          .setRequired(true)
      )
  ];

  client.guilds.cache.forEach(async (guild) => {
    try {
      const commandData = await guild.commands.set(commands.map((cmd) => cmd.toJSON()));
      console.log(`Slash commands registered in guild: ${guild.name} (ID: ${guild.id})`);
    } catch (error) {
      console.error(`Error registering slash commands in guild: ${guild.name} (ID: ${guild.id})`, error);
    }
  });

  startLiveAlerts();
});

client.on('interactionCreate', async (interaction) => {
  if (!interaction.isCommand()) return;

  if (interaction.commandName === 'setaparat') {
    const username = interaction.options.getString('username');
    const message = interaction.options.getString('message');
    const channel = interaction.options.getChannel('channel') || interaction.channel;

    if (!username) {
      await interaction.reply('Please provide your Aparat username.');
      return;
    }

    // Store user configuration
    userConfigurations.set(interaction.user.id, { username, message, channel });
    await interaction.reply(`Aparat live alerts set up for ${username}.`);

    // You can add code here to save the configuration to a database or file if needed
  } else if (interaction.commandName === 'help') {
    const embed = new MessageEmbed()
      .setColor('#0099ff')
      .setTitle('Bot Commands')
      .setDescription('List of available bot commands and their descriptions')
      .addField('/setaparat', 'Set up Aparat live alerts\nUsage: /setaparat <username> [message] [channel]')
      .addField('/cancelaparat', 'Cancel Aparat live alerts\nUsage: /cancelaparat <username>')
      .addField('/help', 'Show bot commands and their descriptions');

    await interaction.reply({ embeds: [embed] });
  } else if (interaction.commandName === 'cancelaparat') {
    const username = interaction.options.getString('username');

    if (!username) {
      await interaction.reply('Please provide your Aparat username.');
      return;
    }

    // Remove user configuration
    const removed = userConfigurations.delete(interaction.user.id);
    if (removed) {
      await interaction.reply(`Aparat live alerts canceled for ${username}.`);
    } else {
      await interaction.reply(`No Aparat live alerts found for ${username}.`);
    }

    // You can add code here to remove the configuration from a database or file if needed
  }
});

async function startLiveAlerts() {
  setInterval(async () => {
    for (const [userId, { username, message, channel }] of userConfigurations.entries()) {
      const streamData = await fetchStreamData(username);

      if (streamData && !streamData.is_live) {
        // User is not live, clear their configuration
        userConfigurations.delete(userId);
      } else if (streamData && streamData.is_live) {
        // User is live, send live alert
        sendDiscordNotification(userId, streamData, message, channel);
      }
    }
  }, 60000); // Check every minute
}

async function fetchStreamData(username) {
  try {
    const response = await fetch(`https://www.aparat.com/api/video/live/livehash/${username}`);
    if (response.ok) {
      const data = await response.json();
      return data.video_live_hash;
    } else {
      console.error('Failed to fetch stream data from Aparat:', response.status, response.statusText);
      return null;
    }
  } catch (error) {
    console.error('Error fetching stream data from Aparat:', error);
    return null;
  }
}

async function sendDiscordNotification(userId, streamData, message, channel) {
  const user = await client.users.fetch(userId);

  if (!user) return;

  const defaultNotificationMessage = `New stream available: [${streamData.title}](${streamData.url})\nThumbnail: ${streamData.thumbnail}`;

  const notificationMessage = message
    ? message
        .replace('{title}', streamData.title)
        .replace('{url}', streamData.url)
        .replace('{thumbnail}', streamData.thumbnail)
    : defaultNotificationMessage;

  const notificationEmbed = new MessageEmbed()
    .setColor('#0099ff')
    .setTitle('Aparat Live Alert')
    .setURL(streamData.url)
    .setThumbnail(streamData.thumbnail)
    .setDescription(notificationMessage);

  channel.send({ embeds: [notificationEmbed] })
    .catch((error) => {
      console.error(`Error sending Aparat live alert to user: ${user.tag}`, error);
    });
}

client.login('YOUR_BOT_TOKEN');