Recherche avancée

Médias (91)

Autres articles (22)

  • Publier sur MédiaSpip

    13 juin 2013

    Puis-je poster des contenus à partir d’une tablette Ipad ?
    Oui, si votre Médiaspip installé est à la version 0.2 ou supérieure. Contacter au besoin l’administrateur de votre MédiaSpip pour le savoir

  • Ajouter notes et légendes aux images

    7 février 2011, par

    Pour pouvoir ajouter notes et légendes aux images, la première étape est d’installer le plugin "Légendes".
    Une fois le plugin activé, vous pouvez le configurer dans l’espace de configuration afin de modifier les droits de création / modification et de suppression des notes. Par défaut seuls les administrateurs du site peuvent ajouter des notes aux images.
    Modification lors de l’ajout d’un média
    Lors de l’ajout d’un média de type "image" un nouveau bouton apparait au dessus de la prévisualisation (...)

  • Organiser par catégorie

    17 mai 2013, par

    Dans MédiaSPIP, une rubrique a 2 noms : catégorie et rubrique.
    Les différents documents stockés dans MédiaSPIP peuvent être rangés dans différentes catégories. On peut créer une catégorie en cliquant sur "publier une catégorie" dans le menu publier en haut à droite ( après authentification ). Une catégorie peut être rangée dans une autre catégorie aussi ce qui fait qu’on peut construire une arborescence de catégories.
    Lors de la publication prochaine d’un document, la nouvelle catégorie créée sera proposée (...)

Sur d’autres sites (3991)

  • My discord music bot works locally, but not on a server [closed]

    8 décembre 2022, par Asmondya

    I have an issue with my discord music bot that I made with discord.js v14.

    


    When I run it locally, it works fine and plays music as it should. But when I put in on a server (here I use Vultr), it doesn't work.

    


    I am not sure but it might come from FFmpeg. I am kinda desperate and cant really figure where the issue is from. I think it is FFmpeg because it is what converts the music.

    


    What happens :

    


    Me: !play a music
Bot: Now playing a music
*and right after, without playing the music*
Bot: Music finished


    


    What should normally happen is that same thing but the "music finished" should be sent when the queue is finished.

    


    The thing is that the bot works perfectly locally, but does this when it is hosted on a server. Also I don't have any error messages or else. It just doesn't play the music like if the music was 0 seconds length.

    


    I tried making sure everything is installed on the server, same as making sure ffmpeg was installed globally and I have the good version of it. Here is the answer I have to the "ffmpeg -version" command :enter image description here.

    


    Does anyone know what could be the issue or what could cause it ? I can show some code if needed, even tho it works perfectly fine locally.

    


    Here's my code :

    


    const { DisTube } = require('distube')
const Discord = require('discord.js')
const { EmbedBuilder } = require('discord.js')
const client = new Discord.Client({
  intents: [
    Discord.GatewayIntentBits.Guilds,
    Discord.GatewayIntentBits.GuildMessages,
    Discord.GatewayIntentBits.GuildVoiceStates,
    Discord.GatewayIntentBits.MessageContent,
  ]
})
const { ActivityType } = require('discord.js')
const fs = require('fs')
const dotenv = require("dotenv")
dotenv.config()
const { SpotifyPlugin } = require('@distube/spotify')
const { SoundCloudPlugin } = require('@distube/soundcloud')
const { YtDlpPlugin } = require('@distube/yt-dlp')

client.distube = new DisTube(client, {
  leaveOnStop: false,
  emitNewSongOnly: true,
  emitAddSongWhenCreatingQueue: false,
  emitAddListWhenCreatingQueue: false,
  plugins: [
    new SpotifyPlugin({
      emitEventsAfterFetching: true
    }),
    new SoundCloudPlugin(),
    new YtDlpPlugin()
  ]
})
client.commands = new Discord.Collection()
client.aliases = new Discord.Collection()

fs.readdir('./commands/', (err, files) => {
  if (err) return console.log('Could not find any commands!')
  const jsFiles = files.filter(f => f.split('.').pop() === 'js')
  if (jsFiles.length <= 0) return console.log('Could not find any commands!')
  jsFiles.forEach(file => {
    const cmd = require(`./commands/${file}`)
    console.log(`Loaded ${file}`)
    client.commands.set(cmd.name, cmd)
    if (cmd.aliases) cmd.aliases.forEach(alias => client.aliases.set(alias, cmd.name))
  })
})

client.on('ready', () => {
  console.log(`${client.user.tag} is ready to play music.`)
})

client.on('messageCreate', async message => {
  if (message.author.bot || !message.guild) return
  const prefix = "!"
  if (!message.content.startsWith(prefix)) return
  const args = message.content.slice(prefix.length).trim().split(/ +/g)
  const command = args.shift().toLowerCase()
  const cmd = client.commands.get(command) || client.commands.get(client.aliases.get(command))
  if (!cmd) return
  if (cmd.inVoiceChannel && !message.member.voice.channel) {
    return message.channel.send(`You must be in a voice channel!`)
  }
  try {
    cmd.run(client, message, args)
  } catch (e) {
    console.error(e)
    message.channel.send(`Error: \`${e}\``)
  }
})

// Add filters to the queue status :
// | Filter: \`${queue.filters.names.join(', ') || 'Off'}\` 

const status = queue =>
  `Volume: \`${queue.volume}%\` | Loop: \`${
    queue.repeatMode ? (queue.repeatMode === 2 ? 'All Queue' : 'This Song') : 'Off'
  }\` | Autoplay: \`${queue.autoplay ? 'On' : 'Off'}\``
client.distube
  .on('playSong', (queue, song) =>
    queue.textChannel.send({
      embeds: [
        new Discord.EmbedBuilder()
          .setTitle('Now playing')
          .setDescription(`\`${song.name}\` - \`${song.formattedDuration}\`\n${status(queue)}\n\nRequested by: \`${song.user.tag}\``)
          .setThumbnail(`${song.thumbnail}`)
      ]
    })
  )
  .on('addSong', (queue, song) =>
    queue.textChannel.send({
      embeds: [
        new Discord.EmbedBuilder()
          .setTitle('Song added to the queue')
          .setDescription(`${song.name} - \`${song.formattedDuration}\`\n\nRequested by: \`${song.user.tag}\``)
          .setThumbnail(`${song.thumbnail}`)
      ]
    })
  )
  .on('addList', (queue, playlist) =>
    queue.textChannel.send({
      embeds: [
        new Discord.EmbedBuilder()
          .setTitle(`Playlist added to the queue`)
          .setDescription(`\`${playlist.name}\` (${
            playlist.songs.length
          } songs)\n${status(queue)}\n\nRequested by: \`${song.user.tag}\``)
          .setThumbnail(`${song.thumbnail}`)
      ]
    })
  )
  .on('error', (channel, e) => {
    if (channel) channel.send(`An error encountered: ${e.toString().slice(0, 1974)}`)
    else console.error(e)
  })
  .on('empty', channel => channel.send('There is no one here. Im alone, again...'))
  .on('searchNoResult', (message, query) =>
    message.channel.send(`No result found for \`${query}\`!`)
  )
  .on('finish', queue => queue.textChannel.send("https://tenor.com/view/end-thats-all-folks-gif-10601784"))

client.on("ready", () => {
  client.user.setPresence({
      activities: [{
        name: 'AURORA',
        type: ActivityType.Listening
      }],
      status: "idle"
  })
})

client.login(process.env.TOKEN)


    


    It does come from my ffpmeg, I need to install one of these packages instead of the npm installation : https://github.com/BtbN/FFmpeg-Builds/releases

    


    How do I install it on a server (Vultr) ?

    


  • Making my Discord Bot automatically play music from WAV on loop

    5 décembre 2022, par Mativ9

    So I was trying to make a Discord Bot in Python, which would atomatically join a voice channel and play my own music from a list in a loop. So far it's joining the channel, shuffling the list so the music is on random, but when I try to write a code so after one song it will play the next one it crushes and doesn't play anything (tho it's joining the channel)

    


    import discord
import random
from discord.ext import commands
from discord import FFmpegPCMAudio

#playlist as a list
queue = [FFmpegPCMAudio('Iceland1.wav'), FFmpegPCMAudio('Iceland2.wav'), FFmpegPCMAudio('Iceland3.wav'), FFmpegPCMAudio('Iceland4.wav'),
         FFmpegPCMAudio('Iceland5.wav'), FFmpegPCMAudio('Iceland6.wav'), FFmpegPCMAudio('Iceland7.wav'), FFmpegPCMAudio('Iceland8.wav'),
         FFmpegPCMAudio('Iceland9.wav'), FFmpegPCMAudio('Iceland10.wav'), FFmpegPCMAudio('Norway1.wav'), FFmpegPCMAudio('Norway2.wav'),
         FFmpegPCMAudio('Norway3.wav'), FFmpegPCMAudio('Norway4.wav'), FFmpegPCMAudio('Norway5.wav'), FFmpegPCMAudio('Norway6.wav'),
         FFmpegPCMAudio('Norway7.wav'), FFmpegPCMAudio('Norway8.wav'), FFmpegPCMAudio('Norway9.wav'), FFmpegPCMAudio('Norway10.wav'),
         FFmpegPCMAudio('Norway11.wav'), FFmpegPCMAudio('Presents1.wav'), FFmpegPCMAudio('Presents2.wav'), FFmpegPCMAudio('Presents3.wav'),
         FFmpegPCMAudio('Presents4.wav'), FFmpegPCMAudio('Presents5.wav'), FFmpegPCMAudio('Presents6.wav'), FFmpegPCMAudio('Presents7.wav'),
         FFmpegPCMAudio('Presents8.wav'), FFmpegPCMAudio('Presents9.wav'), FFmpegPCMAudio('Presents10.wav'), FFmpegPCMAudio('Autumn1.wav'),
         FFmpegPCMAudio('Autumn2.wav'), FFmpegPCMAudio('Autumn3.wav'), FFmpegPCMAudio('Autumn4.wav'), FFmpegPCMAudio('Autumn5.wav'),
         FFmpegPCMAudio('Autumn6.wav'), FFmpegPCMAudio('Autumn7.wav'), FFmpegPCMAudio('Autumn8.wav'), FFmpegPCMAudio('Covers1.wav'),
         FFmpegPCMAudio('Covers2.wav'), FFmpegPCMAudio('Covers3.wav'), FFmpegPCMAudio('Covers4.wav'), FFmpegPCMAudio('Covers5.wav'),
         FFmpegPCMAudio('Covers6.wav'), FFmpegPCMAudio('Covers7.wav'), FFmpegPCMAudio('Covers8.wav'), FFmpegPCMAudio('Covers9.wav'),
         FFmpegPCMAudio('Covers10.wav'), FFmpegPCMAudio('Covers11.wav'), FFmpegPCMAudio('Covers12.wav')]

intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix='>', intents=intents)

@client.event
async def on_ready():
    global voice
    print("The Matt Bot is ready")
    print("--------------------------")
    await client.change_presence(activity=discord.Game('Matt Krupa')) #makes my bot play Matt Krupa
    channel = client.get_channel(thechannelid) #geting channel ID
    voice = await channel.connect() #connecting to channel
    random.shuffle(queue) #randomazing the playlist
    def after_song(): #moving the first song to the end so its on loop, and playling the next one
        queue.append(queue[0])
        del queue[0]
        player = await voice.play(queue[0], after=await after_song())
    player = await voice.play(queue[0], after=await after_song()) #plays song from the playlist, after the song doing the after_song() function

client.run(mytokenidontwanttoshowitsry)


    


    I wanted it to play all the songs on the infinite loop, i can't find how to correctly detect the end of a song...

    


  • discord.py music bot slowing down for longer audio queries

    1er janvier 2023, par Bobluge

    So I'm trying to make a music bot with discord.py. Shown below is a minimum working example of the bot with the problematic functions :

    


    import os

import discord
from discord.ext import commands
from discord import player as p

import yt_dlp as youtube_dl

intents = discord.Intents.default()
intents.members = True

bot = commands.Bot(command_prefix=';')

class Music(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.yt-dlp_opts = {
            'format': 'bestaudio/best',
            'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
            'restrictfilenames': True,
            'noplaylist': True,
            'playlistend': 1,
            'nocheckcertificate': True,
            'ignoreerrors': False,
            'logtostderr': False,
            'quiet': True,
            'no_warnings': True,
            'default_search': 'auto',
            'source_address': '0.0.0.0', # bind to ipv4 since ipv6 addresses cause issues sometimes
        }
        self.ffmpeg_opts = {
            'options': '-vn',
            # Source: https://stackoverflow.com/questions/66070749/
            "before_options": "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5",
        }
        self.cur_stream = None
        self.cur_link = None

    @commands.command(aliases=["p"])
    async def play(self, ctx, url):
        yt-dlp = youtube_dl.YoutubeDL(self.ytdl_opts)
        data = yt-dlp.extract_info(url, download=False)
        filename = data['url']  # So far only works with links
        print(filename)
        audio = p.FFmpegPCMAudio(filename, **self.ffmpeg_opts)
        self.cur_stream = audio
        self.cur_link = filename

        # You must be connected to a voice channel first
        await ctx.author.voice.channel.connect()
        ctx.voice_client.play(audio)
        await ctx.send(f"now playing")

    @commands.command(aliases=["ff"])
    async def seek(self, ctx):
        """
        Fast forwards 10 seconds
        """
        ctx.voice_client.pause()
        for _ in range(500):
            self.cur_stream.read()  # 500*20ms of audio = 10000ms = 10s
        ctx.voice_client.resume()

        await ctx.send(f"fast forwarded 10 seconds")

    @commands.command(aliases=["j"])
    async def jump(self, ctx, time):
        """
        Jumps to a time in the song, input in the format of HH:MM:SS
        """
        ctx.voice_client.stop()
        temp_ffempg = {
            'options': '-vn',
            # Keyframe skipping when passed as an input option (fast)
            "before_options": f"-ss {time} -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5",
        }
        new_audio = p.FFmpegPCMAudio(self.cur_link, **temp_ffempg)
        self.cur_stream = new_audio
        ctx.voice_client.play(new_audio)
        await ctx.send(f"skipped to {time}")


bot.add_cog(Music(bot))
bot.run(os.environ["BOT_TOKEN"])


    


    My requirements.txt file :

    


    discord.py[voice]==1.7.3
yt-dlp==2021.9.2


    


    To play a song in Discord the following format is used :

    


    ;p 


    


    Where is any link that yt-dlp supports. Under normal circumstances, the ;p command is used with songs that are relatively short, to which seek() and jump() work extremely quickly to do what they are supposed to do. For example if I execute these sequence of commands in Discord :

    


    ;p https://www.youtube.com/watch?v=n8X9_MgEdCg  <- 4 min song


    


    And when the bot starts playing, spam the following :

    


    ;ff
;ff
;ff
;ff
;ff


    


    The bot is able to almost instantly seek five 10-second increments of the song. Additionally, I can jump to the three minute mark very quickly with :

    


    ;j 00:03:00


    


    From some experimentation, the seek() and jump() functions seem to work quickly for songs that are under 10 minutes. If I try the exact same sequence of commands but with a 15 minute song like https://www.youtube.com/watch?v=Ks9Ck5LfGWE or longer https://www.youtube.com/watch?v=VThrx5MRJXA (10 hours classical music), there is an evident slowdown when running the ;ff command. However, when I include a few seconds of delay between firings of the ;ff command, the seeking is just as fast as previously mentioned. I'm not exactly sure what is going on with yt-dlp/FFmpeg behind the scenes when streaming, but I speculate that there is some sort of internal buffer, and songs that pass a certain length threshold are processed differently.

    


    For longer songs, the seek() command takes longer to get to the desired position, which makes sense since this site specifies that -ss used as an input option loops through keyframes (as there must be more keyframes in longer songs). However, if the following commands are run in Discord :

    


    ;p https://www.youtube.com/watch?v=VThrx5MRJXA  <- 10 hour classical music
;j 09:00:00                                     <- jump to 9 hour mark
;j 00:03:00                                     <- jump to 3 minute mark


    


    The first seek command takes around 5 to 10 seconds to perform a successful seek, which isn't bad, but it could be better. The second seek command takes around the same time as the first command, which doesn't make sense to me, because I thought less keyframes were skipped in order to reach the 3 minute mark.

    


    So I'm wondering what's going on, and how to potentially solve the following :

    


      

    • What is actually going on with the seek() command ? My implementation of seek() uses discord.py's discord.player.FFmpegPCMAudio.read() method, which apparently runs slower if the song's length is longer ? Why ?
    • 


    • Why does input seeking for long YouTube videos take almost the same time no matter where I seek to ?
    • 


    • How the yt-dlp and FFmpeg commands work behind the scenes to stream a video from YouTube (or any other website that YTDL supports). Does yt-dlp and FFmpeg behave differently for audio streams above a certain length threshold ?
    • 


    • Potential ways to speed up seek() and jump() for long songs. I recall some well-known discord music bots were able to do this very quickly.
    •