Recherche avancée

Médias (91)

Autres articles (50)

  • Amélioration de la version de base

    13 septembre 2013

    Jolie sélection multiple
    Le plugin Chosen permet d’améliorer l’ergonomie des champs de sélection multiple. Voir les deux images suivantes pour comparer.
    Il suffit pour cela d’activer le plugin Chosen (Configuration générale du site > Gestion des plugins), puis de configurer le plugin (Les squelettes > Chosen) en activant l’utilisation de Chosen dans le site public et en spécifiant les éléments de formulaires à améliorer, par exemple select[multiple] pour les listes à sélection multiple (...)

  • Menus personnalisés

    14 novembre 2010, par

    MediaSPIP utilise le plugin Menus pour gérer plusieurs menus configurables pour la navigation.
    Cela permet de laisser aux administrateurs de canaux la possibilité de configurer finement ces menus.
    Menus créés à l’initialisation du site
    Par défaut trois menus sont créés automatiquement à l’initialisation du site : Le menu principal ; Identifiant : barrenav ; Ce menu s’insère en général en haut de la page après le bloc d’entête, son identifiant le rend compatible avec les squelettes basés sur Zpip ; (...)

  • Déploiements possibles

    31 janvier 2010, par

    Deux types de déploiements sont envisageable dépendant de deux aspects : La méthode d’installation envisagée (en standalone ou en ferme) ; Le nombre d’encodages journaliers et la fréquentation envisagés ;
    L’encodage de vidéos est un processus lourd consommant énormément de ressources système (CPU et RAM), il est nécessaire de prendre tout cela en considération. Ce système n’est donc possible que sur un ou plusieurs serveurs dédiés.
    Version mono serveur
    La version mono serveur consiste à n’utiliser qu’une (...)

Sur d’autres sites (5400)

  • Music bot doesn't play livestreams anymore

    31 janvier 2019, par Silvinator

    My Discord bot played YT Livestreams all the time, but it stopped working today. The only message I get (in the console) is stream. It plays normal videos, but no streams.
    The question is, why it stopped working ? I did not change any code. Anyone got a idea ?

    client.on("message", async message => {
     var args = message.content.substring(prefix.length).split(" ");
     if (!message.content.startsWith(prefix)) return;
     var searchString = args.slice(1).join(' ');
     var url = args[1] ? args[1].replace(/<(.+)>/g, '$1') : '';
     var serverQueue = queue.get(message.guild.id);
     switch (args[0].toLowerCase()) {
       case "play":
         var voiceChannel = message.member.voiceChannel;
         if (!voiceChannel) return message.channel.send(`Du willst mit mir Karaoke singen? Da ich eh nichts besseres zu tun habe. Du suchst aber den Voice Channel aus!`);
         var permissions = voiceChannel.permissionsFor(message.client.user);
         if (!permissions.has('CONNECT')) {
           return message.channel.send('I cannot connect to your voice channel, make sure I have the proper permissions!');
         }
         if (!permissions.has('SPEAK')) {
           return message.channel.send('I cannot speak in this voice channel, make sure I have the proper permissions!');
         }
         if (url.match(/^https?:\/\/(www.youtube.com|youtube.com)\/playlist(.*)$/)) {
           var playlist = await youtube.getPlaylist(url);
           var videos = await playlist.getVideos();
           for (const video of Object.values(videos)) {
             var video2 = await youtube.getVideoByID(video.id); // eslint-disable-line no-await-in-loop
             await handleVideo(video2, message, voiceChannel, true); // eslint-disable-line no-await-in-loop
           }
           return message.channel.send(`Ich habe wohl keine andere wahl... Ich habe **${playlist.title}** der playlist zugefügt`);
         } else {
           try {
             var video = await youtube.getVideo(url);
           } catch (error) {
             try {
               var videos = await youtube.searchVideos(searchString, 10);
               var index = 0;
               var videoIndex = 1;
               var video = await youtube.getVideoByID(videos[videoIndex - 1].id);
             } catch (err) {
               console.error(err);
               return message.channel.send('Gibt es den Song überhaupt?');
             }
           }
           return handleVideo(video, message, voiceChannel);
         }
         break;
       case "skip":
         if (!message.member.voiceChannel) return message.channel.send('Du musst schon in den Voice Channel gehen, baka!');
         if (!serverQueue) return message.channel.send('Du musst schon ein song auswählen, baka!');
         serverQueue.connection.dispatcher.end('Skip command has been used!');
         return undefined;
         break;
       case "stop":
         if (!message.member.voiceChannel) return message.channel.send('Du musst schon in den Voice Channel gehen, baka!');
         if (!serverQueue) return message.channel.send('Du musst schon einen Song auswählen, baka');
         serverQueue.connection.dispatcher.end('Stop command has been used!');
         serverQueue.songs = [];
         return undefined;
         break;
       case "minfo":
         if (!serverQueue) return message.channel.send('Ich spiele immer noch nichts!');
         return message.channel.send(`ퟎ
  • Need help to create a queue system with a discord.py bot

    19 août 2024, par Zamv

    im trying to create a bot with discord.py, i'll start saying that the bot is for personal use so please don't point out that i shouldn't use ydl in the comments, ty :
Also, im a beginner, so please tell me what I can improve and any errors there are, I will be happy to listen.
That said, i've been stuck on trying to create this queue system for songs for the past 3 days, the bot was working perfectly fine and played some urls before i implemented the play_next function, now it doesn't even play the first song, even if it sends confirmation messages both in the terminal that in the discord channel, i know that the code might be a little confusing, but please i really need to know how to make this work

    


    i wrote two main functions : "play_next" to play the next song in the queue and "play", the main command.
Here is my play_next function :

    


    async def play_next(self,ctx):
        if not ctx.voice_client.is_playing: #(don't know if this is correct as I also check if the bot isn't                     playing anything in the play function)
            
            if self.song.queue: 
                next_song = self.song_queue.pop(0) #deleting the first element of the queue, so if we have (song_0, song_1 and song_2) the bot should delete (song_0) making in fact song_1 the "next" song_0
                try:
                    ctx.voice_client.play(discord.FFmpegPCMAudio(next_song), 
                                          after=lambda e: self.bot.loop.create_task(self.play_next(ctx))) #Not gonna lie here, i asked chat gpt for this line, it should make the bot automatically play the next song one after another, correct me if I am wrong

#this is not important
                    embed = discord.Embed(
                        title="Song",
                        description=f"Now playing {next_song}",
                        color = 0x1DB954
                    )
                    await ctx.send(embed=embed)
                except Exception as e:
                    print(f"Error playing the next song: {e}")

            else:
                await ctx.voice_client.disconnect()  # disconnecting from the voice channel if the queue is empty
                print("Disconnected from the voice channel as the queue is empty.")


    


    I think that the main problem of my bot is the play_next function, but here it is my "play" function :

    


        @commands.command(pass_context=True)
    async def play(self, ctx, url: str):  
        if ctx.author.voice:  # first checking if the user is in a voice channel
            if not ctx.voice_client: #then checking if the bot is already connected to a voice channel
                channel = ctx.message.author.voice.channel 
                try:
                    await channel.connect()  #then joining
                    print("I joined the voice channel!")
                except Exception as e:
                    print(f"Failed to connect to the voice channel: {e}")
                    return

            song_path = f"song_{self.song_index}.mp3" #note, im using cogs, i declared self.song_index with the value of 0 
            self.song_index += 1 #i thought that this was the easiest way of creating a new file for each song

            ydl_opts = {
                'format': 'bestaudio/best',
                'postprocesors': [{
                    'key': 'FFmpegExtractAudio',
                    'preferredcodec': 'mp3',
                    'preferredquality': '192',
                }],
                'outtmpl': song_path
            }
            try:
                with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                    print("Starting download...")
                    ydl.download([url]) #this is where it should download the song provided by the url
                    print("Download finished.")
            except Exception as e:
                await ctx.send(f"Failed to download the song: {e}")
                return

#i think that the next two if statements are the main threats
            if os.path.exists(song_path): #if there is atleast 1 song in the queue
                self.song_queue.append(song_path) #append the next one
                embed = discord.Embed(
                    title="Added to Queue!",
                    description = f"{url} has been added to the queue.",
                    color=0x33ff33
                )
                await ctx.send(embed=embed)


                if not ctx.voice_client.is_playing(): #checking if the bot is already playing something, don't know if i should put this if statement here
                    print("Starting playback...")
                    await self.play_next(ctx) #if nothing is playing, then the bot should play the next song



            else:
                await ctx.send("Failed to download or find the audio file.")

        else:
            embed = discord.Embed(
                title="❌You must be in a voice channel",
                color=0xff6666
            )
            await ctx.send(embed=embed)


    


    thanks in advance, i will try to read and answer any questions as soon as possible

    


  • Python Discord Music Bot : Playing next song while current song is playing

    8 février, par Deltrac

    I've been working on a Discord bot and got it working 90% of the time. On some occasions, the bot will be playing a song and it will stop playing and just move to the next song. My assumption is that it's because of how I am handling my play command and the play_next command as well.

    


    I've tried to re-arrange the code, change functionality, etc. without success.

    


    Here are the two commands :

    


    @client.command(name="p")
async def play(ctx, *, search_query: str):
        global bot_disconnect
        try:
        # Only start a song if the user trying to play a song is in a voice channel
            if ctx.author.voice:
                voice_channel = ctx.author.voice.channel
                voice_client = await voice_channel.connect() # Find who played the song and have the bot enter that channel
                voice_clients[voice_client.guild.id] = voice_client
            else:
                await ctx.channel.send("Get in a voice channel")
                return
        except Exception as e:
                print(e)
        try:
            if is_youtube_url(search_query):
                loop = asyncio.get_event_loop() # Let's the bot multi-task (Similar behavior to interrupts in C/C++)
                data = await loop.run_in_executor(None, lambda: ytdl.extract_info(search_query, download = False))
                video_url = data["webpage_url"] # Save the youtube video URL to variable
                song_url = data["url"] # Save the extracted URL to a variable
                title = data["title"]
            else:
                url = f"ytsearch:{search_query}"
                loop = asyncio.get_event_loop() # Let's the bot multi-task (Similar behavior to interrupts in C/C++)
                data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download = False)) 
                entry = data['entries'][0]
                video_url = entry["webpage_url"] # Save the youtube video URL to variable
                song_url = entry["url"] # Save the extracted URL to a variable
                title = entry["title"]

            if ctx.guild.id in voice_clients and voice_clients[ctx.guild.id].is_playing():
                await queue(ctx, search_query = video_url, title = title)
            else:
                player = discord.FFmpegOpusAudio(song_url, **ffmpeg_options) # THIS IS WHAT PLAYS THE ACTUAL SONG!!!!!!
                await ctx.channel.send(f"Now Playing: {video_url} \n[DOWNLOAD LINK HERE]({song_url})") # Send the video URL to discord channel and include a download link as well
                bot_disconnect = False
                voice_clients[ctx.guild.id].play(player, after=lambda e: asyncio.run_coroutine_threadsafe(play_next(ctx), client.loop))
        except Exception as e:
                print(e)



async def play_next(ctx):
    if len(queues) != 0 and queues.get(ctx.guild.id):         
        search_query = queues[ctx.guild.id].pop(0)[0] # Pull the URL from the next index
        loop = asyncio.get_event_loop() # Let's the bot multi-task (Similar behavior to interrupts in C/C++)
        print(f"{search_query}")
        data = await loop.run_in_executor(None, lambda: ytdl.extract_info(search_query, download = False))
        player = discord.FFmpegOpusAudio(data["url"], **ffmpeg_options)
        voice_client = voice_clients[ctx.guild.id]
        voice_client.play(player, after=lambda e: asyncio.run_coroutine_threadsafe(play_next(ctx), client.loop))
        await ctx.channel.send(f"Now Playing: {data['webpage_url']} \n[DOWNLOAD LINK HERE]({data['url']})") # Send the video URL to discord channel and include a download link as well
    else:
        await ctx.send("No songs in queue")


    


    I can also link the full code, if required.