Correctif import + library Opus + Fix util Twitch

This commit is contained in:
Angels-dev
2024-08-09 02:05:09 +02:00
parent 586f68b0df
commit 6bfc3839f6
16 changed files with 178 additions and 1621 deletions

View File

@@ -54,17 +54,11 @@ export default {
}, 30000)
// TWITCH EVENTSUB
let dbData = guildProfile.get('guildTwitch')
if (!dbData?.enabled) return console.log(chalk.magenta(`[Twitch] Module is disabled for "${guild?.name}", please activate with \`/database edit guildTwitch.enabled True\` !`))
let client_id = process.env.TWITCH_APP_ID as string
if (!client_id) return console.log(chalk.magenta('[Twitch] App ID is not defined !'))
let client_secret = process.env.TWITCH_APP_SECRET as string
if (!client_secret) return console.log(chalk.magenta('[Twitch] App Secret is not defined !'))
let twitch = new WebSocket.client().on('connect', async connection => {
console.log(chalk.magenta('[Twitch] EventSub WebSocket Connected !'))
console.log(chalk.magenta(`[Twitch] {${guild.name}} EventSub WebSocket Connected !`))
connection.on('message', async message => { if (message.type === 'utf8') { try {
let data = JSON.parse(message.utf8Data)
@@ -75,7 +69,7 @@ export default {
// Check if the channel access token is still valid before connecting
channel_access_token = await Twitch.checkChannel(client_id, client_secret, channel_access_token, guild) as string
if (!channel_access_token) return console.log(chalk.magenta("[Twitch] Can't refresh channel access token !"))
if (!channel_access_token) return console.log(chalk.magenta(`[Twitch] {${guild.name}} Can't refresh channel access token !`))
// Get broadcaster user id and reward id
let broadcaster_user_id = await Twitch.getUserInfo(client_id, channel_access_token, 'id') as string
@@ -87,29 +81,31 @@ export default {
// Subscribe to all events required
for (let type in topics) {
console.log(chalk.magenta(`[Twitch] Creating ${type}...`))
console.log(chalk.magenta(`[Twitch] {${guild.name}} Creating ${type}...`))
let { version, condition } = topics[type]
let status = await Twitch.subscribeToEvents(client_id, channel_access_token, data.payload.session.id, type, version, condition)
if (!status) return console.error(chalk.magenta(`[Twitch] Failed to create ${type}`))
else if (status.error) return console.log(chalk.magenta('[Twitch] Erreur de connexion EventSub, veuillez vous reconnecter !'))
else console.log(chalk.magenta(`[Twitch] Successfully created ${type}`))
if (!status) return console.error(chalk.magenta(`[Twitch] {${guild.name}} Failed to create ${type}`))
else if (status.error) return console.log(chalk.magenta(`[Twitch] {${guild.name}} Erreur de connexion EventSub, veuillez vous reconnecter !`))
else console.log(chalk.magenta(`[Twitch] {${guild.name}} Successfully created ${type}`))
}
}
// Handle notification messages
else if (data.metadata.message_type === 'notification') Twitch.notification(client_id, channel_access_token, data, guild)
} catch (error) { console.error(chalk.magenta('[Twitch] ' + error)) } } })
.on('error', error => console.error(chalk.magenta('[Twitch] ' + error)))
} catch (error) { console.error(chalk.magenta(`[Twitch] {${guild.name}} ` + error)) } } })
.on('error', error => console.error(chalk.magenta(`[Twitch] {${guild.name}} ` + error)))
.on('close', () => {
console.log(chalk.magenta('[Twitch] EventSub Connection Closed !'))
console.log(chalk.magenta('[Twitch] {${guild.name}} EventSub Connection Closed !'))
twitch.connect('wss://eventsub.wss.twitch.tv/ws')
})
}).on('connectFailed', error => console.error(chalk.magenta('[Twitch] ' + error)))
}).on('connectFailed', error => console.error(chalk.magenta(`[Twitch] {${guild.name}} ` + error)))
// LAUNCH TWITCH EVENTSUB
twitch.connect('wss://eventsub.wss.twitch.tv/ws')
let dbData = guildProfile.get('guildTwitch')
if (!dbData?.enabled) return console.log(chalk.magenta(`[Twitch] {${guild.name}} Module is disabled for "${guild?.name}", please activate with \`/database edit guildTwitch.enabled True\` !`))
else if (!client_id || !client_secret) return console.log(chalk.magenta(`[Twitch] {${guild.name}} App ID or Secret is not defined !`))
else twitch.connect('wss://eventsub.wss.twitch.tv/ws')
})
}
}

View File

@@ -1,5 +1,5 @@
import { GuildQueue, Track } from 'discord-player'
import { PlayerMetadata } from '../../utilsPlayer/metadata'
import { PlayerMetadata } from '../../utils/player'
export default {
name: 'audioTrackAdd',

View File

@@ -1,5 +1,5 @@
import { GuildQueue, Track } from 'discord-player'
import { PlayerMetadata } from '../../utilsPlayer/metadata'
import { PlayerMetadata } from '../../utils/player'
export default {
name: 'audioTracksAdd',

View File

@@ -1,10 +1,10 @@
import { GuildQueue, Track } from 'discord-player'
import { PlayerMetadata } from '../../utilsPlayer/metadata'
import { GuildQueue } from 'discord-player'
import { PlayerMetadata } from '../../utils/player'
import dbGuild from '../../schemas/guild'
export default {
name: 'disconnect',
async execute(queue: GuildQueue<PlayerMetadata>, track: Track) {
async execute(queue: GuildQueue<PlayerMetadata>) {
// Emitted when the bot leaves the voice channel
queue.metadata.channel.send("J'ai quitté le vocal !")

View File

@@ -1,9 +1,9 @@
import { GuildQueue, Track } from 'discord-player'
import { PlayerMetadata } from '../../utilsPlayer/metadata'
import { GuildQueue } from 'discord-player'
import { PlayerMetadata } from '../../utils/player'
export default {
name: 'emptyChannel',
async execute(queue: GuildQueue<PlayerMetadata>, track: Track) {
async execute(queue: GuildQueue<PlayerMetadata>) {
// Emitted when the voice channel has been empty for the set threshold
// Bot will automatically leave the voice channel with this event
queue.metadata.channel.send(`Je quitte le vocal car il est vide depuis trop longtemps.`)

View File

@@ -1,5 +1,5 @@
import { GuildQueue, Track } from 'discord-player'
import { PlayerMetadata } from '../../utilsPlayer/metadata'
import { GuildQueue } from 'discord-player'
import { PlayerMetadata } from '../../utils/player'
export default {
name: 'emptyQueue',

View File

@@ -1,5 +1,5 @@
import { GuildQueue, Track } from 'discord-player'
import { PlayerMetadata } from '../../utilsPlayer/metadata'
import { PlayerMetadata } from '../../utils/player'
export default {
name: 'playerSkip',

View File

@@ -1,5 +1,5 @@
import { GuildQueue, Track } from 'discord-player'
import { PlayerMetadata } from '../../utilsPlayer/metadata'
import { PlayerMetadata } from '../../utils/player'
import dbGuild from '../../schemas/guild'
export default {

View File

@@ -4,7 +4,7 @@ import axios from 'axios'
import path from 'path'
import fs from 'fs'
interface Game {
export interface Game {
name: string
link: string
}

View File

@@ -1,6 +1,7 @@
import { Guild, TextChannel, EmbedBuilder } from 'discord.js'
import { Guild, TextChannel, EmbedBuilder, hyperlink } from 'discord.js'
import axios, { AxiosHeaderValue } from 'axios'
import dbGuild from '../schemas/guild'
import chalk from 'chalk'
interface NotificationData {
metadata: {
@@ -26,14 +27,14 @@ interface Condition {
export async function checkChannel (client_id: string, client_secret: string, channel_access_token: string, guild: Guild) {
let guildProfile = await dbGuild.findOne({ guildId: guild?.id })
if (!guildProfile) return console.log(`Database data for ${guild?.name} does not exist, please initialize with \`/database init\` !`)
if (!guildProfile) return console.log(chalk.magenta(`[Twitch] Database data for ${guild?.name} does not exist, please initialize with \`/database init\` !`))
let dbData = guildProfile.get('guildTwitch')
if (!dbData?.enabled) return console.log(`Twitch module is disabled for "${guild?.name}", please activate with \`/database edit guildTwitch.enabled True\` !`)
if (!dbData?.enabled) return console.log(chalk.magenta(`[Twitch] module is disabled for "${guild?.name}", please activate with \`/database edit guildTwitch.enabled True\` !`))
if (!await validateToken(channel_access_token)) {
let channel_refresh_token = dbData.channelRefreshToken
if (!channel_refresh_token) return console.log('No refresh token found in database !')
if (!channel_refresh_token) return console.log(chalk.magenta('[Twitch] No refresh token found in database !'))
let GetAccessFromRefresh = await refreshToken(client_id, client_secret, channel_refresh_token)
if (!GetAccessFromRefresh) return false;
@@ -93,22 +94,25 @@ export async function getUserInfo (client_id: string, access_token: string, type
}
export async function notification (client_id: string, channel_access_token: string, data: NotificationData, guild: Guild) {
if (!guild) return console.log(chalk.magenta('[Twitch] Can\'t find guild !'))
let { subscription, event } = data.payload
let guildProfile = await dbGuild.findOne({ guildId: guild?.id })
if (!guildProfile) return console.log(`Database data for ${guild?.name} does not exist, please initialize with \`/database init\` !`)
let guildProfile = await dbGuild.findOne({ guildId: guild.id })
if (!guildProfile) return console.log(chalk.magenta(`[Twitch] {${guild.name}} Database data does not exist, please initialize with \`/database init\` !`))
let dbData = guildProfile.get('guildTwitch')
if (!dbData?.enabled) return console.log(`Twitch module is disabled for "${guild?.name}", please activate with \`/database edit guildTwitch.enabled True\` !`)
if (!dbData?.enabled) return console.log(chalk.magenta(`[Twitch] {${guild.name}} Module is disabled, please activate with \`/database edit guildTwitch.enabled True\` !`))
let liveChannelId = dbData.liveChannelId
if (!liveChannelId) return console.log('No live channel id found in database !')
if (!liveChannelId) return console.log(chalk.magenta(`[Twitch] {${guild.name}} No live channel id found in database !`))
let liveChannel = guild.channels.cache.get(liveChannelId) as TextChannel
if (!liveChannel) return console.log(`\u001b[1;35m Can't find channel with id ${liveChannelId}`)
if (!liveChannel) return console.log(chalk.magenta(`[Twitch] {${guild.name}} Can't find channel with id ${liveChannelId}`))
let liveMessageInterval
if (subscription.type === 'stream.online') {
console.log(`\u001b[1;35m Stream from ${event.broadcaster_user_name} is now online, sending Discord message...`)
console.log(chalk.magenta(`[Twitch] {${guild.name}} Stream from ${event.broadcaster_user_name} is now online, sending Discord message...`))
let stream_data = await getStreams(client_id, channel_access_token, event.broadcaster_user_login)
let user_profile_image_url = await getUserInfo(client_id, channel_access_token, 'profile_image_url')
@@ -116,39 +120,51 @@ export async function notification (client_id: string, channel_access_token: str
let embed = new EmbedBuilder()
.setColor('#6441a5')
.setTitle(stream_data.title)
.setURL(`https://twitch.tv/laytho_`)
.setAuthor({ name: `${event.broadcaster_user_login.toUpperCase()} EST ACTUELLEMENT EN LIVE !`, iconURL: user_profile_image_url })
.setURL(`https://twitch.tv/${event.broadcaster_user_login}`)
.setAuthor({ name: `🔴 ${event.broadcaster_user_name.toUpperCase()} EST ACTUELLEMENT EN LIVE ! 🎥`, iconURL: user_profile_image_url })
.setDescription(`Joue à ${stream_data.game_name} avec ${stream_data.viewer_count} viewers`)
.setImage(stream_data.thumbnail_url.replace('{width}', '1920').replace('{height}', '1080'))
.setTimestamp()
let message = await liveChannel.send({ content: `Hey @everyone ! <@${dbData.liveBroadcasterId}> démarre son live sur **Twitch** !`, embeds: [embed] })
let hidden = hyperlink('démarre un live', 'https://www.youtube.com/watch?v=dQw4w9WgXcQ&pp=ygUJcmljayByb2xs')
let message = await liveChannel.send({ content: `Hey ! <@${dbData.liveBroadcasterId}> ${hidden} sur **Twitch**, venez !`, embeds: [embed] })
dbData.liveMessageId = message.id
guildProfile.set('guildTwitch', dbData)
guildProfile.markModified('guildTwitch')
await guildProfile.save().catch(console.error)
liveMessageInterval = setInterval(async () => {
let stream_data = await getStreams(client_id, channel_access_token, event.broadcaster_user_login)
if (!stream_data) return console.log(chalk.magenta(`[Twitch] {${guild.name}} Can't find stream data for ${event.broadcaster_user_name}`))
embed.setTitle(stream_data.title)
.setDescription(`Joue à ${stream_data.game_name} avec ${stream_data.viewer_count} viewers`)
.setImage(stream_data.thumbnail_url.replace('{width}', '1920').replace('{height}', '1080'))
.setTimestamp()
message.edit({ content: `Hey @everyone !\n<@${dbData.liveBroadcasterId}> est en live sur **Twitch**, venez !`, embeds: [embed] }).catch(console.error)
}, 60000)
}
else if (subscription.type === 'stream.offline') {
console.log(`\u001b[1;35m Stream from laytho_ is now offline, editing Discord message...`)
let message = liveChannel.messages.cache.find(message => message.id === dbData.liveMessageId)
if (!message) return console.log(`\u001b[1;35m Can't find message with id ${dbData.liveMessageId}`)
if (!message.embeds[0]) return console.log(`\u001b[1;35m Can't find embed in message with id ${dbData.liveMessageId}`)
console.log(chalk.magenta(`[Twitch] {${guild.name}} Stream from ${event.broadcaster_user_name} is now offline, editing Discord message...`))
let message = await liveChannel.messages.fetch(dbData.liveMessageId as string)
if (!message) return console.log(chalk.magenta(`[Twitch] {${guild.name}} Can't find message with id ${dbData.liveMessageId}`))
if (!message.embeds[0]) return console.log(chalk.magenta(`[Twitch] {${guild.name}} Can't find embed in message with id ${dbData.liveMessageId}`))
let duration = new Date().getTime() - new Date(message.embeds[0].data.timestamp ?? 0).getTime()
let seconds = Math.floor(duration / 1000)
let minutes = Math.floor(seconds / 60)
let hours = Math.floor(minutes / 60)
let duration_string = `${hours ? hours + 'H' : ''} ${minutes % 60 ? minutes % 60 + 'M' : ''} ${seconds % 60 ? seconds % 60 + 'S' : ''}`
let duration_string = `${hours ? hours + 'H ' : ''}${minutes % 60 ? minutes % 60 + 'M ' : ''}${seconds % 60 ? seconds % 60 + 'S' : ''}`
let user_profile_image_url = await getUserInfo(client_id, channel_access_token, 'profile_image_url')
let embed = new EmbedBuilder()
.setColor('#6441a5')
.setAuthor({ name: `C'EST FINI, LE LIVE A DURÉ ${duration_string} !`, iconURL: user_profile_image_url })
.setAuthor({ name: `C'EST FINI, LE LIVE A DURÉ ${duration_string} ! 📼`, iconURL: user_profile_image_url })
.setTimestamp()
message.edit({ content: `Re @everyone ! <@${dbData.liveBroadcasterId}> a terminé son live sur **Twitch** !`, embeds: [embed] })
message.edit({ content: `Re !\n<@${dbData.liveBroadcasterId}> a terminé son live sur **Twitch** !`, embeds: [embed] }).catch(console.error)
clearInterval(liveMessageInterval)
}
}