Esempio n. 1
0
            async def meme(self, ctx, search: str = "windows-xp-error", *args):
                search = " ".join((search, ) + args)
                filenames = list(os.listdir(MEMESPATH))

                result = process.extractOne(search, filenames)
                filename = result[0]

                print("[Music] - Suchergebnis:", search, result)

                if result[1] >= 75:
                    player = PCMVolumeTransformer(
                        FFmpegPCMAudio(source=os.path.join(
                            MEMESPATH, filename),
                                       **FFMPEG_OPTIONS))

                    if ctx.voice_client.is_playing():
                        ctx.voice_client.stop()

                    ctx.voice_client.play(
                        player,
                        after=lambda e: print('[Music] - Fehler: %s' % e)
                        if e else None)
                    await ctx.sendEmbed(title="Memetime!",
                                        fields=[("Meme",
                                                 str(filename).split(".")[0])])
                else:
                    raise ErrorMessage(
                        message=
                        "Es wurden keine mit '{}' übereinstimmende Audiodatei gefunden."
                        .format(search))
Esempio n. 2
0
    async def say(self, ctx, *, message: str):
        """Ignore this"""
        summoned_channel = ctx.message.author.voice.channel
        if summoned_channel is not None:
            tts = gTTS(text=message, lang='en')
            tts.save(os.path.join(self.audio_directory, "tts.mp3"))

            vc = ctx.guild.voice_client
            if vc is None:
                await ctx.invoke(self.bot.get_cog("Music").voice_connect)
                if not ctx.guild.voice_client:
                    return
                else:
                    vc = ctx.guild.voice_client

            try:
                source = PCMVolumeTransformer(FFmpegPCMAudio(
                    os.path.join(self.audio_directory, 'tts.mp3')),
                                              volume=1)
                vc.play(source, after=lambda x: self.__leave(ctx))
            except Exception as e:
                fmt = 'An error occurred while processing this request: ```py\n{}: {}\n```'
                await ctx.send(fmt.format(type(e).__name__, e))

        else:
            await ctx.send("I need you in a Voice Channel to hear me")
Esempio n. 3
0
            async def _download_and_play():
                try:
                    self._guild._bot.log.debug('waiting for cache...')
                    await cache
                    self._guild._bot.log.debug('finish cache...')
                except:
                    self._guild._bot.log.error('cannot cache...')
                    self._guild._bot.log.error(traceback.format_exc())
                    async with self._aiolocks['player']:
                        if self.state != PlayerState.PAUSE:
                            await self._play()

                boptions = "-nostdin"
                aoptions = "-vn"

                self._guild._bot.log.debug(
                    "Creating player with options: {} {} {}".format(
                        boptions, aoptions, entry._local_url))

                source = SourcePlaybackCounter(
                    PCMVolumeTransformer(
                        FFmpegPCMAudio(entry._local_url,
                                       before_options=boptions,
                                       options=aoptions,
                                       stderr=subprocess.PIPE), self.volume))

                async with self._aiolocks['player']:
                    self._player = self._guild._voice_client
                    self._guild._voice_client.play(source,
                                                   after=_playback_finished)
                    self._source = source
                    self.state = PlayerState.PLAYING
Esempio n. 4
0
        async def meme(self, ctx, search: str = "windows-xp-error"):
            search = search + " " + ctx.getargs()
            filenames = list(os.listdir(memespath))

            result = process.extractOne(search, filenames)
            filename = result[0]

            print("[Music] - Suchergebnis:", search, result)

            if result[1] >= 75:
                player = PCMVolumeTransformer(
                    FFmpegPCMAudio(source=os.path.join(memespath, filename),
                                   **ffmpeg_options))

                if ctx.voice_client.is_playing():
                    ctx.voice_client.stop()

                ctx.voice_client.play(
                    player,
                    after=lambda e: print('[Music] - Fehler: %s' % e)
                    if e else None)
                await ctx.sendEmbed(title="Memetime!",
                                    color=self.color,
                                    fields=[("Meme",
                                             str(filename).split(".")[0])])
            else:
                raise commands.BadArgument(
                    message=
                    "Es wurden keine mit '{}' übereinstimmende Audiodatei gefunden."
                    .format(search))
Esempio n. 5
0
    async def joke(self, ctx):
        with open(os.path.join(self.text_directory,
                               'jokes.json')) as jokes_file:
            jokes = json.loads(jokes_file.read())["jokes"]
            random_line = choice(range(0, len(jokes), 2))
            joke = jokes[random_line]
            await ctx.send(joke["joke"])
            await asyncio.sleep(3)
            await ctx.send(joke["punchline"])

            summoned_channel = ctx.message.author.voice.channel
            if summoned_channel is not None:
                vc = ctx.guild.voice_client

                if vc is None:
                    await ctx.invoke(self.bot.get_cog("Music").voice_connect)
                    if not ctx.guild.voice_client:
                        return
                    else:
                        vc = ctx.guild.voice_client

                try:
                    source = PCMVolumeTransformer(FFmpegPCMAudio(
                        os.path.join(self.audio_directory, 'funee_joke.mp3')),
                                                  volume=0.2)
                    vc.play(source, after=lambda x: self.leave(ctx))
                except Exception as e:
                    fmt = 'An error occurred while processing this request: ```py\n{}: {}\n```'
                    await ctx.send(fmt.format(type(e).__name__, e))
Esempio n. 6
0
    async def mlg(self, ctx):
        summoned_channel = ctx.message.author.voice.channel
        if summoned_channel is not None:
            vc = ctx.guild.voice_client

            if vc is None:
                await ctx.invoke(self.bot.get_cog("Music").voice_connect)
                if not ctx.guild.voice_client:
                    return
                else:
                    vc = ctx.guild.voice_client
            else:
                if ctx.author not in vc.channel.members:
                    return await ctx.send(f'You must be in **{vc.channel}** to request mlg.', delete_after=30)

            try:
                source = PCMVolumeTransformer(FFmpegPCMAudio(os.path.join(
                        self.audio_directory, 'mlg_airhorn.mp3'
                    )), volume=0.2)
                vc.play(source, after=lambda x: self.leave(ctx))
            except Exception as e:
                fmt = 'An error occurred while processing this request: ```py\n{}: {}\n```'
                await ctx.send(
                    fmt.format(type(e).__name__, e)
                )
Esempio n. 7
0
    async def _play(self, _continue=False):
        if self.is_paused and self._current_player:
            return self.resume()

        if self.is_dead:
            return

        with await self._play_lock:
            if self.is_stopped or _continue:
                try:
                    entry = await self.playlist.get_next_entry()
                except:
                    log.warning("Failed to get entry, retrying", exc_info=True)
                    self.loop.call_later(0.1, self.play)
                    return

                if not entry:
                    self.stop()
                    return

                self._kill_current_player()

                boptions = "-nostdin"
                if isinstance(entry, URLPlaylistEntry):
                    aoptions = entry.aoptions
                else:
                    aoptions = "-vn"

                log.ffmpeg("Creating player with options: {} {} {}".format(boptions, aoptions, entry.filename))

                self._source = SourcePlaybackCounter(
                    PCMVolumeTransformer(
                        FFmpegPCMAudio(
                            entry.filename,
                            before_options=boptions,
                            options=aoptions,
                            stderr=subprocess.PIPE
                        ),
                        self.volume
                    )
                )
                log.debug('Playing {0} using {1}'.format(self._source, self.voice_client))
                self.voice_client.play(self._source, after=self._playback_finished)

                self._current_player = self.voice_client

                self.state = MusicPlayerState.PLAYING
                self._current_entry = entry

                self._stderr_future = asyncio.Future()

                stderr_thread = Thread(
                    target=filter_stderr,
                    args=(self._source._source.original._process, self._stderr_future),
                    name="stderr reader"
                )

                stderr_thread.start()

                self.emit('play', player=self, entry=entry)
Esempio n. 8
0
    async def play(self, ctx, *, query):
        """Plays a file from the local filesystem"""

        source = PCMVolumeTransformer(FFmpegPCMAudio(query))
        ctx.voice_client.play(
            source, after=lambda e: print(f"Player error: {e}") if e else None
        )

        await ctx.send(f"Now playing: {query}")
Esempio n. 9
0
File: bot.py Progetto: JaffarA/dvc
async def tts(ctx):
    """
  Plays a TTS message
  """
    txt = ctx.message.content.replace('<tts ', '')
    a, loc = gTTS(txt), f'tmp/{randint(690000, 6900000)}.mp3'
    a.save(loc)
    await join(ctx)
    s = PCMVolumeTransformer(FFmpegPCMAudio(loc))
    ctx.voice_client.play(s)
    await ctx.send(txt)
Esempio n. 10
0
    def player(self):
        url = "rtmp://fms-base2.mitene.ad.jp/agqr/aandg333"

        while App.client.loop.is_running():
            with Popen(["rtmpdump", "--live", "-r", url], stdout=PIPE) as p:
                source = PCMVolumeTransformer(FFmpegPCMAudio(p.stdout,
                                                             pipe=True),
                                              volume=App.config.volume)
                self.voice.play(source, after=lambda _: p.kill())
                p.wait()

            time.sleep(5)
Esempio n. 11
0
    def player(self):
        while App.client.loop.is_running():
            with Popen([
                    "ffmpeg", "-i", App.config.radio_garden_url, "-f", "s16le",
                    "-ar",
                    str(Encoder.SAMPLING_RATE), "-ac",
                    str(Encoder.CHANNELS), "-loglevel", "warning", "pipe:1"
            ],
                       stdout=PIPE) as p:
                source = PCMVolumeTransformer(PCMAudio(p.stdout),
                                              volume=App.config.volume)
                self.voice.play(source, after=lambda _: p.kill())
                p.wait()

            time.sleep(5)
Esempio n. 12
0
 async def stream_audio(self):
     """The music loop. Connect to channel and stream. We await on `self.stream` to block on the song being played."""
     play_count = 0
     while self.streaming and play_count < 75:
         self.stream.clear()
         # need to load the song every time, it seems to keep internal state
         with path("resources", "who-can-it-be-now.mp3") as source:
             song = PCMVolumeTransformer(
                 FFmpegPCMAudio(source, options='-filter:a "volume=0.125"'))
         self.voice_client.play(song, after=self.trigger_next_song)
         play_count += 1
         await asyncio.sleep(0)  # give up timeslice for `trigger_next_song`
         await self.stream.wait()
     if self.streaming and not play_count < 75:
         await self.stop()
Esempio n. 13
0
    def play(self) -> None:
        """Start or resume playing from the queue"""
        if self.voice_client is None or not self.voice_client.is_connected():  # Check if theres a voice client in the first place
            return

        def make_audio_source(song):
            source = FFmpegPCMAudio(source=song.source_url, **Queue.ffmpeg_options)
            if not source.read():  # ensure the source url is readable, for example when ffmpeg gets 403 error, it will refresh the source url and read from that again
                song.refresh_source()
                source = make_audio_source(song)
            return source

        if not self.playing:
            self.playing = self._songs.popleft()
            self.voice_client.play(PCMVolumeTransformer(original=make_audio_source(self.playing), volume=self._volume / 100),
                                   after=self.play_next)
Esempio n. 14
0
    def player(self):
        while App.client.loop.is_running():
            with Popen([
                    "rtmpdump", "--live", "--rtmp", self.api.rtmp_url,
                    "--swfVfy",
                    "http://radiko.jp/apps/js/flash/myplayer-release.swf",
                    "--pageUrl", "http://radiko.jp", "-C", "S:", "-C", "S:",
                    "-C", "S:", "-C", f"S:{self.api.rtmp_token}"
            ],
                       stdout=PIPE) as p:
                source = PCMVolumeTransformer(FFmpegPCMAudio(p.stdout,
                                                             pipe=True),
                                              volume=App.config.volume)
                self.voice.play(source, after=lambda _: p.kill())
                p.wait()

            time.sleep(5)
Esempio n. 15
0
async def play(self, search, message, after=None, autoloop=False):
    if len(self.voice_clients) > 0:
        boptions = "-nostdin"
        aoptions = "-vn"
        files_dates = []
        for e in os.listdir("music"):
            files_dates.append(e)
        self.logger.debug(f'search: {search}')
        name, vid = self.downloader.download(search, files_dates)
        self.logger.info(f'song playing: {name}')
        _source = SourcePlaybackCounter(
            PCMVolumeTransformer(
                FFmpegPCMAudio("music" + slash + str(name),
                               before_options=boptions,
                               options=aoptions,
                               stderr=subprocess.PIPE), self.volume))
        if self.voice_clients[0].is_playing():
            self.logger.debug("stop")
            await self.stop()
        self.voice_clients[0].play(_source, after=after)
        # await message.channel.send(
        #     "playing " + name.strip(".webm") + " in  " + str(message.author.voice.channel)
        # )
        try:
            await message.channel.send(
                embed=play_track_embed(self,
                                       "".join(str(name).split(".")[:-1]),
                                       message,
                                       vid,
                                       autoloop=autoloop))
        except AttributeError:
            await self.last_song[1].channel.send(
                embed=play_track_embed(self,
                                       "".join(str(name).split(".")[:-1]),
                                       self.last_song[1],
                                       vid,
                                       autoloop=autoloop))
        if self.last_song:
            self.last_song = (search, self.last_song[1])
        else:
            self.last_song = (search, message)
    else:
        await self.join(message.author)
        await self.play(search, message)
Esempio n. 16
0
    async def speak_aloud(self, message, *words: str):
        ident = message.author.id
        if ident not in self.lyrebird_tokens:
            await message.channel.send(
                "I do not have a lyrebird token for you. Call set_token or generate_token_uri (in a PM)"
            )
            return

        sentence = ' '.join(words)
        log.debug("Echoing '%s' as speech...", sentence)
        await message.add_reaction(CLOCK)

        # Join the channel of the person who requested the say
        voice_client = await self.summon(message)
        if voice_client is None:
            return

        log.debug("Getting voice from lyrebird...")
        voice_bytes = await generate_voice_for_text(
            sentence, self.lyrebird_tokens[ident])
        log.debug("Got voice from lyrebird...")
        user_filename = "~/{}.wav".format(message.author.id)
        user_filename = os.path.expanduser(user_filename)
        with open(user_filename, 'wb') as fi:
            fi.write(voice_bytes)

        try:
            log.debug("Creating audio source.")
            audio_source = FFmpegPCMAudio(user_filename)
            audio_source = PCMVolumeTransformer(audio_source,
                                                volume=self.volume)
            log.debug("Created audio source.")
        except Exception as e:
            fmt = 'An error occurred while processing this request: ```py\n{}: {}\n```'
            await message.channel.send(fmt.format(type(e).__name__, e))
        else:

            def after(err):
                if err:
                    log.error("Error playing media: %s", err)
                os.remove(user_filename)

            voice_client.play(audio_source, after=after)
            await message.remove_reaction(CLOCK, self.bot.user)
Esempio n. 17
0
    async def on_voice_state_update(self, member, before, after):
        if MUSIC_MODULE:
            # *Grillenzirpen* nach Streamende
            if before.channel and before.self_stream and not after.self_stream:
                filepath = os.path.join(MEMESPATH, "grillenzirpen.wav")
                if os.path.isfile(filepath):
                    voice_client = before.channel.guild.voice_client
                    if voice_client is None:
                        voice_client = await before.channel.connect()
                    elif voice_client.is_playing():
                        voice_client.stop()
                        await voice_client.move_to(before.channel)

                    player = PCMVolumeTransformer(
                        FFmpegPCMAudio(source=filepath, **FFMPEG_OPTIONS))
                    voice_client.play(
                        player,
                        after=lambda e: print('[Music] - Error: %s' % e)
                        if e else None)
Esempio n. 18
0
async def alert(session: Session):
    vc = session.ctx.voice_client
    if not vc:
        return

    path = bot_enum.AlertPath.POMO_END
    if session.state == bot_enum.State.COUNTDOWN:
        pass
    elif session.stats.pomos_completed % session.settings.intervals == 0:
        path = bot_enum.AlertPath.LONG_BREAK_START
    elif session.state != bot_enum.State.POMODORO:
        path = bot_enum.AlertPath.POMO_START
    source = PCMVolumeTransformer(FFmpegPCMAudio(
        path, executable='../sounds/ffmpeg.exe'),
                                  volume=0.1)
    if vc.is_playing():
        vc.stop()
    vc.play(source)
    while vc.is_playing():
        await sleep(1)
Esempio n. 19
0
 async def _play(self, ctx, url=None):
     if url == None:
         await ctx.send(
             'You must provide a link providing an audio or video track.')
     else:
         db_volume = db["volume"]
         if not str(ctx.guild.id) in db_volume:
             db_volume[str(ctx.guild.id)] = 1
             db["volume"] = db_volume
         if (ctx.voice_client and not ctx.author.voice.channel
                 == ctx.voice_client.channel) or (not ctx.voice_client):
             await ctx.invoke(self._join)
         source = FFmpegPCMAudio(url)
         ctx.voice_client.play(source)
         ctx.voice_client.source = PCMVolumeTransformer(
             ctx.voice_client.source, db["volume"][str(ctx.guild.id)])
         if ctx.voice_client:
             await ctx.send("Playing audio track.")
         else:
             await ctx.send("Failed to play audio track.")
Esempio n. 20
0
    def playNext(self):
        try:
            info = self.ytdl.extract_info(self.queue.pop(0),
                                          download=False,
                                          process=False)
        except Exception as e:
            print(e)  # make this an exception

        try:
            data = self.ytdl.extract_info(info['url'], download=False)
        except Exception as e:
            print(e)  # make this an exception

        if 'entries' in data:
            data = data['entries'][0]

        #print(data)
        self.current = PCMVolumeTransformer(
            FFmpegPCMAudio(data['url'], **self.FFMPEG_OPTIONS), self.volume)
        self.voice.play(self.current, after=self.finalise)
        print('playing')
        return
Esempio n. 21
0
            def play():
                try:
                    while self.sound_deque:
                        if not self.voice_client:
                            logger.warning(
                                "Trying to play sound_queue without voice client. "
                                "Clearing sound queue and returning...")
                            self.clear_queue()
                            break

                        source, volume = self.sound_deque.popleft()
                        path = source.name if hasattr(source,
                                                      "name") else source
                        volume = 2 if volume > 2 else volume  # Make sure volume can't be over 2 to preserve hearing
                        audio = PCMVolumeTransformer(FFmpegPCMAudio(path),
                                                     volume)
                        self.voice_client.play(audio)
                        while self.voice_client.is_playing(
                        ) or self.voice_client.is_paused():
                            sleep(0.05)
                finally:
                    self.sound_queue_play_lock.release()
Esempio n. 22
0
    async def on_message(self, message):
        if MUSIC_MODULE:
            # *Help I need somebody Help*
            if "i need somebody" in message.content.lower(
            ) and message.guild and message.author.voice:
                filepath = os.path.join(MEMESPATH, "help-i-need-somebody.wav")
                if os.path.isfile(filepath):
                    voice_client = message.guild.voice_client
                    if voice_client is None:
                        voice_client = await message.author.voice.channel.connect(
                        )
                    elif voice_client.is_playing():
                        voice_client.stop()
                        await voice_client.move_to(message.author.voice.channel
                                                   )

                    player = PCMVolumeTransformer(
                        FFmpegPCMAudio(source=filepath, **FFMPEG_OPTIONS))
                    voice_client.play(
                        player,
                        after=lambda e: print('[Music] - Error: %s' % e)
                        if e else None)
Esempio n. 23
0
    async def play_current_song(self):
        """
            Play the current song of the playlist
        """
        self.stop_without_continuing()
        try:
            current_song: Song = self.playlist.get_current()
            source = PCMVolumeTransformer(
                FFmpegPCMAudio(current_song.file_name, options='-vn'), 0.5)

            def after(error):
                if error:
                    logger.error(error)
                    # sys.exit(-1)

                if self.stop_after:
                    self.stop_after = False
                    return

                if self.auto_play_next and self.bot.loop.is_running():
                    self.playlist.select_next()
                    c1 = self.play_current_song()
                    c2 = self.update_playlist_messages()

                    fut1 = asyncio.run_coroutine_threadsafe(c1, self.bot.loop)
                    fut2 = asyncio.run_coroutine_threadsafe(c2, self.bot.loop)
                    try:
                        fut1.result()
                        fut2.result()
                    except Exception as err:
                        logger.error(err)

            self.guild.voice_client.play(source, after=after)
        except EmptyPlaylistException:
            # if the playlist is empty: do nothing
            pass
    async def on_voice_state_update(member, before, after):
        ##### Channels
        from discordbot.botcmds.channels import getUserChannelCategory

        category = await getUserChannelCategory(member.guild)
        # Delete channel if empty
        if before.channel and before.channel.category and before.channel.category.name.upper() == "BENUTZERKANÄLE" and "#" in before.channel.name and before.channel.members == []:
            await before.channel.delete(reason="Kanal war leer")
            channelowner = utils.get(
                before.channel.guild.members,
                name=before.channel.name.split("#")[0],
                discriminator=before.channel.name.split("#")[1])
            EMBED = Embed(title="Sprachkanal gelöscht!")
            EMBED.set_footer(text=f'Kanal von {member.name}',
                             icon_url=member.avatar_url)
            EMBED.add_field(name="Server", value=member.guild.name)
            await channelowner.send(embed=EMBED)
        # Create new channel
        if after.channel and after.channel.name == "Sprachkanal erstellen":
            channel = utils.get(member.guild.voice_channels,
                                name=(member.name + "#" +
                                      member.discriminator))
            if channel:
                await member.edit(
                    voice_channel=channel,
                    reason=
                    "Benutzer wollte einen Kanal erstellen, besitzte aber bereits Einen"
                )
            else:
                overwrites = {
                    member.guild.default_role:
                    PermissionOverwrite(connect=False,
                                        speak=True,
                                        read_messages=True),
                    member:
                    PermissionOverwrite(connect=True,
                                        speak=True,
                                        read_messages=True,
                                        move_members=True,
                                        mute_members=True)
                }
                newchannel = await category.create_voice_channel(
                    name=(member.name + "#" + member.discriminator),
                    overwrites=overwrites,
                    reason="Benutzer hat den Sprachkanal erstellt")
                await member.edit(
                    voice_channel=newchannel,
                    reason="Benutzer hat den Sprachkanal erstellt")
                EMBED = Embed(title="Sprachkanal erstellt!")
                EMBED.set_footer(text=f'Kanal von {member.name}',
                                 icon_url=member.avatar_url)
                EMBED.add_field(name="Server", value=member.guild.name)
                await member.send(embed=EMBED)

        ##### Music
        if os.getenv("DEBUG", False):
            filespath = os.path.join(
                os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
                "botfiles")
            memespath = os.path.join(filespath, "memes")

            ffmpeg_options = {
                'options': '-vn',
                'executable': os.path.join(filespath, "ffmpeg.exe")
            }

            # *Grillenzirpen* nach Streamende
            if before.channel and before.self_stream and not after.self_stream:
                voice_client = before.channel.guild.voice_client
                if voice_client is None:
                    voice_client = await before.channel.connect()
                elif voice_client.is_playing():
                    voice_client.stop()
                    await voice_client.move_to(before.channel)

                player = PCMVolumeTransformer(
                    FFmpegPCMAudio(source=os.path.join(memespath,
                                                       "grillenzirpen.wav"),
                                   **ffmpeg_options))
                voice_client.play(
                    player,
                    after=lambda e: print('[Msuic] - Error: %s' % e)
                    if e else None)
Esempio n. 25
0
def loop_audio(path, connection, e=None):
    audio = PCMVolumeTransformer(FFmpegPCMAudio(path))
    cb = partial(loop_audio, path, connection)
    connection.play(source=audio, after=cb)
Esempio n. 26
0
    async def on_call(self, ctx, args, **flags):
        if args[1:].lower() == 'list':
            lines = [f'{k:<15}| {v}' for k, v in LANG_LIST.items()]
            lines_per_chunk = 30
            chunks = [
                f'```{"code":<15}| name\n{"-" * 45}\n' +
                '\n'.join(lines[i:i + lines_per_chunk]) + '```'
                for i in range(0, len(lines), lines_per_chunk)
            ]

            p = Paginator(self.bot)
            for i, chunk in enumerate(chunks):
                e = Embed(title=f'Supported languages ({len(lines)})',
                          colour=Colour.gold(),
                          description=chunk)
                e.set_footer(text=f'Page {i + 1} / {len(chunks)}')
                p.add_page(embed=e)

            return await p.run(ctx)

        text = args[1:]

        voice_flag = not flags.get('no-voice',
                                   isinstance(ctx.channel, DMChannel))

        if voice_flag:
            if not ctx.author.voice:
                return '{warning} Please, join voice channel first'

            if not ctx.author.voice.channel.permissions_for(ctx.author).speak:
                return '{error} You\'re muted!'

            if not ctx.author.voice.channel.permissions_for(
                    ctx.guild.me).connect:
                return '{error} I don\'t have permission to connect to the voice channel'

            if ctx.guild.voice_client is None:  # not connected to voice channel
                try:
                    vc = await ctx.author.voice.channel.connect()
                except Exception:
                    return '{warning} Failed to connect to voice channel'
            elif ctx.author not in ctx.guild.voice_client.channel.members:  # connected to a different voice channel
                await ctx.guild.voice_client.move_to(ctx.author.voice.channel)

                vc = ctx.guild.voice_client
            else:  # already connected and is in the right place
                vc = ctx.guild.voice_client

        try:
            volume = float(flags.get('volume', 100)) / 100
        except ValueError:
            return '{error} Invalid volume value'

        program = ['espeak-ng', text, '--stdout']

        speed_flag = flags.get('speed')
        if speed_flag is not None:
            try:
                speed = int(speed_flag) + 80
            except ValueError:
                return '{error} Invalid speed value'

            program.extend(('-s', str(speed)))

        language_flag = flags.get('language', 'en-us')

        if language_flag not in LANG_LIST:
            return '{warning} Language not found. Use `list` subcommand to get list of voices'

        language = language_flag

        woman_flag = flags.get('woman', False)
        quiet_flag = flags.get('quiet', False)

        if woman_flag:
            if quiet_flag:
                return '{error} Can\'t apply both woman and quiet flags'

            language += f'+f{random.randrange(1, 5)}'

        elif quiet_flag:
            language += '+whisper'
        else:
            language += f'+m{random.randrange(1, 8)}'

        program.extend(('-v', language))

        process, pid = await create_subprocess_exec(*program)
        stdout, stderr = await execute_process(process)

        with TemporaryFile() as tmp:
            tmp.write(stdout)
            tmp.seek(0)
            audio = PCMVolumeTransformer(FFmpegPCMAudio(tmp, **ffmpeg_options),
                                         volume)

            if flags.get('file', not voice_flag):
                try:
                    await ctx.send(file=File(stdout, filename='tts.wav'))
                except Exception:
                    await ctx.send('Failed to send file')

        if voice_flag:
            if vc.is_playing():
                vc.stop()

            vc.play(audio)
            await ctx.react('✅')
Esempio n. 27
0
    async def on_call(self, ctx, args, **flags):
        if args[1:].lower() == 'list':
            lines = [f'{k:<10}| {v}' for k, v in self.langs.items()]
            lines_per_chunk = 30
            chunks = [
                f'```{"code":<10}| name\n{"-" * 35}\n' +
                '\n'.join(lines[i:i + lines_per_chunk]) + '```'
                for i in range(0, len(lines), lines_per_chunk)
            ]

            p = Paginator(self.bot)
            for i, chunk in enumerate(chunks):
                e = Embed(title=f'Supported languages ({len(lines)})',
                          colour=Colour.gold(),
                          description=chunk)
                e.set_footer(text=f'Page {i + 1} / {len(chunks)}')
                p.add_page(embed=e)

            return await p.run(ctx)

        voice_flag = not flags.get('no-voice',
                                   isinstance(ctx.channel, DMChannel))

        if voice_flag:
            if not ctx.author.voice:
                return '{warning} Please, join voice channel first'

            if not ctx.author.voice.channel.permissions_for(ctx.author).speak:
                return '{error} You\'re muted!'

            if not ctx.author.voice.channel.permissions_for(
                    ctx.guild.me).connect:
                return '{error} I don\'t have permission to connect to the voice channel'

            if ctx.guild.voice_client is None:  # not connected to voice channel
                try:
                    vc = await ctx.author.voice.channel.connect()
                except Exception:
                    return '{warning} Failed to connect to voice channel'
            elif ctx.author not in ctx.guild.voice_client.channel.members:  # connected to a different voice channel
                await ctx.guild.voice_client.move_to(ctx.author.voice.channel)

                vc = ctx.guild.voice_client
            else:  # already connected and is in the right place
                vc = ctx.guild.voice_client

        try:
            volume = float(flags.get('volume', 100)) / 100
        except ValueError:
            return '{error} Invalid volume value'

        language_flag = flags.get('language')
        if language_flag:
            if language_flag not in self.langs:
                return '{warning} language not found. Use `list` subcommand to get list of voices'

        tts = gtts.gTTS(args[1:],
                        lang=language_flag or 'en',
                        slow=flags.get('slow', False),
                        lang_check=False)

        with TemporaryFile() as tts_file:
            partial_tts = partial(tts.write_to_fp, tts_file)

            try:
                await self.bot.loop.run_in_executor(None, partial_tts)
            except Exception:
                return '{error} Problem with api response. Please, try again later'

            tts_file.seek(0)

            audio = PCMVolumeTransformer(
                FFmpegPCMAudio(tts_file, **ffmpeg_options), volume)

            if voice_flag:
                if vc.is_playing():
                    vc.stop()

                vc.play(audio)
                await ctx.react('✅')

            if flags.get('file', not voice_flag):
                try:
                    tts_file.seek(0)
                    await ctx.send(
                        file=File(tts_file.read(), filename='tts.mp3'))
                except Exception:
                    await ctx.send('Failed to send file')
Esempio n. 28
0
 def play_audio(self, voice) -> None:
     """play mp3 of song in voice channel"""
     voice.play(FFmpegPCMAudio(os.path.join(self.CACHED_MUSIC_DIR, self.queues[0])), after=self._delete)
     voice.source = PCMVolumeTransformer(voice.source)
     voice.source.volume = 0.07
Esempio n. 29
0
    async def _play(self, _continue=False):
        """
            Plays the next entry from the playlist, or resumes playback of the current entry if paused.
        """
        if self.is_paused:
            return self.resume()

        if self.is_dead:
            return

        with await self._play_lock:
            if self.is_stopped or _continue:
                try:
                    entry = await self.playlist.get_next_entry()
                except:
                    log.warning("Failed to get entry, retrying", exc_info=True)
                    self.loop.call_later(0.1, self.play)
                    return

                # If nothing left to play, transition to the stopped state.
                if not entry:
                    self.stop()
                    return

                # In-case there was a player, kill it. RIP.
                self._kill_current_player()

                boptions = "-nostdin"
                # aoptions = "-vn -b:a 192k"
                if isinstance(entry, URLPlaylistEntry):
                    aoptions = entry.aoptions
                else:
                    aoptions = "-vn"

                log.ffmpeg("Creating player with options: {} {} {}".format(boptions, aoptions, entry.filename))

                source = PCMVolumeTransformer(
                    FFmpegPCMAudio(
                        entry.filename,
                        before_options=boptions,
                        options=aoptions,
                        stderr=subprocess.PIPE
                    ),
                    self.volume
                )
                log.debug('Playing {0} using {1}'.format(source, self.voice_client))
                self.voice_client.play(source, after=self._playback_finished)

                self._current_player = self.voice_client

                # I need to add ytdl hooks
                self.state = MusicPlayerState.PLAYING
                self._current_entry = entry

                self._stderr_future = asyncio.Future()

                stderr_thread = Thread(
                    target=filter_stderr,
                    args=(self._current_player._player.source.original._process, self._stderr_future),
                    name="stderr reader"
                )

                stderr_thread.start()

                self.emit('play', player=self, entry=entry)
Esempio n. 30
0
    async def play(self):

        while self.tracks and len(self.connected_users()) > 1:
            try:
                track = self.tracks[self.trackindex]
                song = track.song

                self.current = track

            except IndexError:
                if not self.repeat:
                    await self.stop()
                    return
                else:
                    self.trackindex = 0
                    continue

            await self.display_normal()

            audio = song.getbestaudio()
            try:
                audio.url
            except AttributeError:
                raise NoVideoError
            source = FFmpegPCMAudio(audio.url, **self.FFMPEG_OPTIONS)
            source = PCMVolumeTransformer(source)
            try:
                self.voice.play(source)
            except ClientException:
                raise BrokenConnectionError

            while self.isplaying() or self.ispaused():
                await sleep(1)
                if self.skipper:
                    self.skipper = False
                    self.voice.stop()
                    break
                elif self.breaker:
                    return
                elif self.goback:
                    pos = self.tracks.index(self.current)
                    old_track = self.old_tracks[len(self.old_tracks)-1]
                    self.tracks = self.tracks[0:pos] + [old_track] + self.tracks[pos:len(self.tracks)]
                    self.old_tracks.remove(old_track)
                    self.voice.stop()
                    break

            if self.onerepeat:
                continue
            elif self.repeat:
                self.trackindex += 1
            else:
                if self.goback:
                    self.goback = False
                    continue

                try:
                    self.tracks.remove(track)
                    self.old_tracks.append(track)
                except ValueError:
                    pass
                continue

        await self.stop()
        return