Python discord.FFmpegPCMAudio() Examples

The following are 12 code examples of discord.FFmpegPCMAudio(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module discord , or try the search function .
Example #1
Source File: modofail.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 6 votes vote down vote up
def modofail(ctx: MtgContext, args: Optional[str]) -> None:
    """Ding!"""
    if args is not None and args.lower() == 'reset':
        redis.clear(f'modofail:{ctx.guild}')
    author = ctx.author
    if isinstance(author, Member) and hasattr(author, 'voice') and author.voice is not None and author.voice.channel is not None:
        voice_channel = ctx.author.voice.channel
        voice = ctx.channel.guild.voice_client
        if voice is None:
            voice = await voice_channel.connect()
        elif voice.channel != voice_channel:
            voice.move_to(voice_channel)
        voice.play(FFmpegPCMAudio('ding.ogg'))
    n = redis.increment(f'modofail:{ctx.guild}')
    redis.expire(f'modofail:{ctx.guild}', 3600)
    await ctx.send(f':bellhop: **MODO fail** {n}') 
Example #2
Source File: vcspam.py    From Raid-Toolbox with GNU General Public License v2.0 6 votes vote down vote up
def on_ready():
    await asyncio.sleep(1)
    voice_channel = client.get_channel(int(voice_id))
    while not client.is_closed():
        vc = await voice_channel.connect()
        vc.play(discord.FFmpegPCMAudio(filename))
        vc.source = discord.PCMVolumeTransformer(vc.source)
        vc.source.volume = 10.0
        while vc.is_playing():
            if sys.platform.startswith('linux'):
                proc = psutil.Process(int(parentprocess))
                if proc.status() == psutil.STATUS_ZOMBIE:
                    await client.logout()
                    sys.exit()
            if not psutil.pid_exists(int(parentprocess)):  # Parent is dead, Kill self :cry:
                await client.logout()
                sys.exit()
            await asyncio.sleep(0.5)
        await vc.disconnect(force=True) 
Example #3
Source File: spookysound.py    From seasonalbot with MIT License 6 votes vote down vote up
def spookysound(self, ctx: commands.Context) -> None:
        """
        Connect to the Hacktoberbot voice channel, play a random spooky sound, then disconnect.

        Cannot be used more than once in 2 minutes.
        """
        if not self.channel:
            await self.bot.wait_until_guild_available()
            self.channel = self.bot.get_channel(Hacktoberfest.voice_id)

        await ctx.send("Initiating spooky sound...")
        file_path = random.choice(self.sound_files)
        src = discord.FFmpegPCMAudio(str(file_path.resolve()))
        voice = await self.channel.connect()
        voice.play(src, after=lambda e: self.bot.loop.create_task(self.disconnect(voice))) 
Example #4
Source File: music.py    From DJ5n4k3 with MIT License 6 votes vote down vote up
def create_source(cls, ctx, search: str, *, loop, download=False):
        loop = loop or asyncio.get_event_loop()

        to_run = partial(ytdl.extract_info, url=search, download=download)
        data = await loop.run_in_executor(None, to_run)

        if 'entries' in data:
            # take first item from a playlist
            data = data['entries'][0]

        await ctx.send(f':notes: Added to queue: **{data["title"]}**')

        if download:
            source = ytdl.prepare_filename(data)
        else:
            return {'webpage_url': data['webpage_url'], 'requester': ctx.author, 'title': data['title']}

        return cls(discord.FFmpegPCMAudio(source), data=data, requester=ctx.author) 
Example #5
Source File: music.py    From DJ5n4k3 with MIT License 6 votes vote down vote up
def regather_stream(cls, data, *, loop):
        """Used for preparing a stream, instead of downloading.

        Since Youtube Streaming links expire."""
        loop = loop or asyncio.get_event_loop()
        requester = data['requester']

        to_run = partial(ytdl.extract_info, url=data['webpage_url'], download=False)
        data = await loop.run_in_executor(None, to_run)

        return cls(discord.FFmpegPCMAudio(data['url']), data=data, requester=requester) 
Example #6
Source File: basic_voice.py    From discord.py with MIT License 5 votes vote down vote up
def from_url(cls, url, *, loop=None, stream=False):
        loop = loop or asyncio.get_event_loop()
        data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))

        if 'entries' in data:
            # take first item from a playlist
            data = data['entries'][0]

        filename = data['url'] if stream else ytdl.prepare_filename(data)
        return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data) 
Example #7
Source File: basic_voice.py    From discord.py with MIT License 5 votes vote down vote up
def play(self, ctx, *, query):
        """Plays a file from the local filesystem"""

        source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))
        ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None)

        await ctx.send('Now playing: {}'.format(query)) 
Example #8
Source File: audio.py    From MangoByte with MIT License 5 votes vote down vote up
def play_next_clip(self):
		clip = self.next_clip()

		try:
			self.voice.play(discord.FFmpegPCMAudio(clip.audiopath), after=self.done_talking)
		except discord.errors.ClientException as e:
			if str(e) == "Not connected to voice.":
				raise UserError("Error playing clip. Try doing `?resummon`.")
			else:
				raise

		self.voice.source = discord.PCMVolumeTransformer(self.voice.source)
		self.voice.source.volume = clip.volume
		print("playing: " + clip.audiopath)
		if self.last_clip != None and clip.audiopath != self.last_clip.audiopath:
			remove_if_temp(self.last_clip.audiopath)
		self.last_clip = clip

	# try queueing an mp3 to play 
Example #9
Source File: music.py    From apex-sigma-core with GNU General Public License v3.0 5 votes vote down vote up
def create_player(self, voice_client):
        """
        Creates a player instance for a voice client
        to deliver the item's music data to.
        :param voice_client: The voice client to use for delivery.
        :type voice_client: discord.VoiceClient
        :return:
        :rtype:
        """
        await self.download()
        if self.location:
            audio_source = discord.FFmpegPCMAudio(self.location)
            if voice_client:
                if not voice_client.is_playing():
                    voice_client.play(audio_source) 
Example #10
Source File: music.py    From DJ5n4k3 with MIT License 5 votes vote down vote up
def play_(self, ctx, *, search: str):
        """Request a song and add it to the queue.

        This command attempts to join a valid voice channel if the bot is not already in one.
        Uses YTDL to automatically search and retrieve a song.

        Parameters
        ------------
        search: str [Required]
            The song to search and retrieve using YTDL. This could be a simple search, an ID or URL.
        """
        await ctx.trigger_typing()

        vc = ctx.voice_client

        if not vc:
            await ctx.invoke(self.connect_)

        elif ctx.author not in ctx.guild.voice_client.channel.members:
            return await ctx.send(":notes: Please join my voice channel to execute this command.", delete_after=20)

        player = self.get_player(ctx)

        # If download is False, source will be a dict which will be used later to regather the stream.
        # If download is True, source will be a discord.FFmpegPCMAudio with a VolumeTransformer.
        source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop, download=False)
        await player.queue.put(source) 
Example #11
Source File: stream_player.py    From Firetail with MIT License 5 votes vote down vote up
def from_url(cls, url, *, loop=None):
        loop = loop or asyncio.get_event_loop()
        data = await loop.run_in_executor(None, ytdl.extract_info, url)

        if 'entries' in data:
            # take first item from a playlist
            data = data['entries'][0]

        filename = ytdl.prepare_filename(data)
        return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data) 
Example #12
Source File: serversmasher.py    From Raid-Toolbox with GNU General Public License v2.0 4 votes vote down vote up
def music_player_main(voice_channel,server):
    vc = await voice_channel.connect()
    while True:
        clear()
        print(colored("Channel: {}".format(voice_channel.name),menucolour))
        print()
        print(colored("1. Play YouTube Link.",menucolour))
        print(colored("2. Pause Player",menucolour))
        print(colored("3. Resume Player",menucolour))
        print(colored("4. Stop Player",menucolour))
        print(colored("5. Volume Adjustment",menucolour))
        print(colored("6. Disconnect",menucolour))
        try:
            player_choice = await loop.run_in_executor(ThreadPoolExecutor(), inputselection,'Option: ')
            if int(player_choice) == 1:
                clear()
                url = await loop.run_in_executor(ThreadPoolExecutor(), inputselection,'YouTube Link to play: ')
                try:
                    if os.path.isfile('RTBFiles/ServerSmasher/file.mp3'):
                        os.remove('RTBFiles/ServerSmasher/file.mp3')
                        print ("Removed old .mp3.")
                    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                        ydl.download([url])
                    vc.play(discord.FFmpegPCMAudio('RTBFiles/ServerSmasher/file.mp3'))
                    vc.source = discord.PCMVolumeTransformer(vc.source)
                    vc.source.volume = 1.0
                except Exception as e:
                    await loop.run_in_executor(ThreadPoolExecutor(), inputselection, str(e))
            elif int(player_choice) == 2:
                vc.pause()
            elif int(player_choice) == 3:
                vc.resume()
            elif int(player_choice) == 4:
                vc.stop()
            elif int(player_choice) == 5:
                clear()
                newvol = await loop.run_in_executor(ThreadPoolExecutor(), inputselection,'New Volume: ')
                try:
                    vc.source.volume = float(int(newvol))
                except Exception as e:
                    await loop.run_in_executor(ThreadPoolExecutor(), inputselection,e)
            elif int(player_choice) == 6:
                await vc.disconnect(force=True)
                await music_player_channel_select(server)
        except Exception as e:
            continue