示例#1
0
    async def player_loop(self):
        await self.bot.wait_until_ready()

        while not self.bot.is_closed():
            self.next_song.clear()

            try:
                if len(self.pq) == 0 and self.wait == True:
                    file = open('intro.webm')
                    source = FFmpegPCMAudio(file, pipe=True)
                    source.title = 'chill'
                elif len(self.pq) == 0:
                    if self.loop_queue == False:
                        await self._channel.send(
                            'I will disconnect in 20 seconds if there is no audio on the queue',
                            delete_after=20)
                        await asyncio.sleep(15)
                    await asyncio.sleep(5)
                    source = self.pq.pop()
                else:
                    source = self.pq.pop()
            except KeyError:
                await self._channel.send(
                    'There is no audio on the queue, so I will disconnect from the channel. Use the command !play or !p to queue more audios',
                    delete_after=15)
                return self.destroy(self._guild)

            if not isinstance(source, YTDLSource) and not isinstance(
                    source, FFmpegPCMAudio):
                # Source was probably a stream (not downloaded)
                # So we should regather to prevent stream expiration
                try:
                    source = await YTDLSource.regather_stream(
                        source, loop=self.bot.loop)
                except Exception as e:
                    await self._channel.send(
                        f'There was an error processing your song.\n'
                        f'```css\n[{e}]\n```')
                    continue

            source.volume = self.volume
            self.current = source

            print(source.title, self._guild.name)

            # opus = ctypes.util.find_library('opus')
            # discord.opus.load_opus(opus)
            # if not discord.opus.is_loaded():
            #     raise RunTimeError('Opus failed to load')

            self._guild.voice_client.play(
                source,
                after=lambda _: self.bot.loop.call_soon_threadsafe(
                    self.next_song.set))
            if source.title == 'chill':
                self.np = await self._channel.send(
                    'Please, listen to this chill music until your audio is ready to play'
                )
            else:
                self.np = await self._channel.send(
                    'Playing now: {a} - Requested by: <@{b}>'.format(
                        a=source.title, b=source.requester.author.id))

            await self.next_song.wait()

            source.cleanup()
            self.current = None

            try:
                # We are no longer playing this song...
                await self.np.delete()
            except discord.HTTPException:
                pass
示例#2
0
 def get_audio(self) -> FFmpegPCMAudio:
     return FFmpegPCMAudio(self.stream_url, **OPTIONS_FFMPEG)
示例#3
0
async def on_message(message):

    if message.author == client.user:
        return

    msg = message.content

    # If bot is mentioned or in dm's
    mention = f'<@!{client.user.id}>'
    if msg.find(mention) == -1:
        mention = f'<@{client.user.id}>'

    isDM = isinstance(message.channel, discord.DMChannel)
    channel_nsfw = False
    if not isDM:
        channel_nsfw = message.channel.is_nsfw()

    if mention in msg or isDM:
        try:
            if isDM:
                userText = msg
            else:
                userText = msg.split(mention, 1)[1]

            response = ""

            # If another user is mentioned, we would do an 8 ball response
            if len(message.mentions) > 1:
                # print("test")
                try:
                    mes = userText.lower()
                    if mes.find("what") != -1 or mes.find("where") != -1:
                        response = eight_ball.what_ball()
                    elif mes.find("who") != -1:
                        response = eight_ball.who_ball()
                    elif mes.find("why") != -1:
                        response = eight_ball.why_ball()
                    else:
                        response = eight_ball.eight_ball()
                except Exception as err:
                    print(err)

            # If Binary, convert to string
            elif to_binary.is_Binary(userText):
                response = to_binary.binaryConvert(userText)

# If indicated to find an image
            elif any(word in msg.lower() for word in findImage):
                if channel_nsfw:
                    try:
                        random.seed(time.time())
                        response = google_search.image_search(
                            removeIndicators(userText, findImage), False)

                    except Exception as err:
                        if str(err).find("429") != -1:
                            message.channel.send(
                                "Img quota exceeded, scraping...")
                            response = google_search.image_search2(
                                removeIndicators(userText, findImage), False)
                        else:
                            response = "Something with image search went wrong."

                        print(err)
                else:
                    try:
                        random.seed(time.time())
                        response = google_search.image_search(
                            removeIndicators(userText, findImage), True)
                        print(response)

                    except Exception as err:
                        if str(err).find("429") != -1:
                            message.channel.send(
                                "Img quota exceeded, scraping...")
                            response = google_search.image_search2(
                                removeIndicators(userText, findImage), True)
                        else:
                            response = "Something with image search went wrong."
                        print(err)

# Disconnect from voice channel
            elif any(word in msg.lower() for word in discionnectIndicators):
                try:
                    for x in client.voice_clients:
                        if (x.guild == message.guild):
                            return await x.disconnect()
                    response = "Done :+1:"
                except:
                    response = "Something went wrong..."

            # If video/youtube key word, search for a YouTube video or play a youtube song
            elif any(word in msg.lower()
                     for word in videoIndicatorWords) or any(
                         word in msg.lower() for word in playIndicator):
                try:

                    toPlayMusic = any(word in msg.lower()
                                      for word in playIndicator)
                    response = google_search.youtube_search(
                        removeIndicators(
                            removeIndicators(userText, videoIndicatorWords),
                            playIndicator))

                    if toPlayMusic:
                        await message.channel.send("Loading Song")
                        YDL_OPTIONS = {
                            'format': 'bestaudio',
                            'noplaylist': 'True'
                        }
                        FFMPEG_OPTIONS = {
                            'before_options':
                            '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
                            'options': '-vn'
                        }
                        voice = get(client.voice_clients, guild=message.guild)
                        voice_channel = message.author.voice.channel

                        if not voice or not voice.is_playing(
                        ) or voice != voice_channel:
                            if voice != voice_channel:
                                voice = await voice_channel.connect()

                            with YoutubeDL(YDL_OPTIONS) as ydl:
                                info = ydl.extract_info(response,
                                                        download=False)
                            URL = info['formats'][0]['url']
                            voice.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))
                            voice.is_playing()
                            await message.channel.send("Playing")
                        else:
                            await message.channel.send("Already playing song")
                            return

                except Exception as err:
                    print(err)

# If indicated to find a meme
            elif any(word in msg.lower() for word in memeIndicator):
                response = reddit_file.get_meme()

# If indicated as gif
            elif any(word in msg.lower() for word in gifIndicators):
                try:
                    random.seed(time.time())
                    response = tenorBot.random(
                        removeIndicators(userText, gifIndicators))
                except Exception as err:
                    print(err)
# If indicated to find article
            elif any(word in msg.lower() for word in findArticle):
                try:
                    random.seed(time.time())
                    links = google_search.get_links(
                        removeIndicators(userText, findArticle))
                    response = random.choice(links)
                except Exception as err:
                    print(err)

# If indicated to calculate and do math
            elif any(word in msg.lower()
                     for word in calculateIndicator) or any(
                         word in msg.lower() for word in calcWhitelistWords):
                try:
                    textToUse = removeIndicators(userText, calculateIndicator)
                    inputVal = textToUse.replace("+", "%2B")
                    inputVal = inputVal.replace(" ", "+")
                    wolfUrl = "https://api.wolframalpha.com/v2/query?input=" + inputVal + "&format=image&output=JSON&appid=" + WolframAppId + "&podstate=Step-by-step%20solution&format=plaintext"

                    now = datetime.now()

                    current_time = now.strftime("%H:%M:%S")
                    print(message.author.name, "requested url", wolfUrl, "at",
                          current_time)
                    with urllib.request.urlopen(wolfUrl) as url:
                        data = json.loads(url.read().decode())
                        if data["queryresult"]:

                            await message.channel.send(
                                "Note that log is the natural log ln, and there may be absolute values not present when calculating the integral."
                            )
                            resp1 = data["queryresult"]["pods"][0]["subpods"][
                                0]["img"]["src"]
                            print("Response 1", resp1)
                            await message.channel.send(resp1)

                            response = data["queryresult"]["pods"][1][
                                "subpods"][0]["img"]["src"]

                            resp2 = data["queryresult"]["pods"][0]["subpods"][
                                0]["plaintext"]
                            print("Response 2", resp2)
                            await message.channel.send(resp2)
                            await message.channel.send(
                                data["queryresult"]["pods"][0]["subpods"][1]
                                ["img"]["src"])

                except Exception as err:
                    print(err)

# If indicated to search for information
            elif any(word in msg.lower() for word in searchIndicator):
                try:
                    textToUse = removeIndicators(userText, calculateIndicator)
                    inputVal = textToUse.replace("+", "%2B")
                    inputVal = inputVal.replace(" ", "+")
                    wolfUrl = "https://api.wolframalpha.com/v2/query?input=" + inputVal + "&format=plaintext&output=JSON&appid=" + WolframAppId
                    print(wolfUrl)
                    with urllib.request.urlopen(wolfUrl) as url:
                        data = json.loads(url.read().decode())
                        if data["queryresult"]:
                            response = data["queryresult"]["pods"][1][
                                "subpods"][0]["plaintext"]

                except Exception as err:
                    print(err)

# If indicated to uwuify text
            elif any(word in msg.lower() for word in uwuifyIndicators):
                try:
                    response = owoify(
                        removeIndicators(userText, uwuifyIndicators))
                except Exception as err:
                    print(err)

# If indicated to receive help indications
            elif any(word in msg.lower() for word in helpindicators):
                cmd = help()
                await message.author.send(cmd)

                if not isDM:
                    response = message.author.name + ", check your DM's bro"
                else:
                    response = "Hope this helps"

# If indicated to search for a random quote
            elif any(word in msg.lower() for word in inspireIndicator):
                response = quote_search.get_quote()

# Else, search Google for a response
            else:
                try:
                    # First query type tries to find if Google has
                    # a system to find resources
                    response = google_search.chatbot_query(userText)
                    print(response)
                except:
                    # If not, try to find our own resource
                    response = google_search.chatbot_query2(userText)
            await message.channel.send(response)

        except:
            # Soon gonna add a small-talk AI bot here, if all else doesn't work
            await message.channel.send(
                "I'm sorry, it appears that something wrong has occured. Please try again."
            )
示例#4
0
    async def play(self, ctx, arg_1='/', arg_2='/', arg_3='/'):
        channel = ctx.message.author.voice.channel
        music_urls = config.MUSIC_URL
        if not channel:
            await ctx.send("You are not connected to a voice channel")
            return
        voice = get(self.bot.voice_clients, guild=ctx.guild)
        if voice and voice.is_connected():
            await voice.move_to(channel)
        else:
            voice = await channel.connect()
        await self.bot.voice_clients[0].disconnect()
        if voice and voice.is_connected():
            await voice.move_to(channel)
        else:
            voice = await channel.connect()
        song = ''
        if arg_1 == '/':
            keys = random.sample(music_urls.keys(), len(music_urls))
            song = random.choice(keys)
            print(song)
        elif arg_2 == '/':
            song = arg_1
        elif arg_3 == '/':
            name = [arg_1, arg_2]
            song = '_'.join(name)
        else:
            name = [arg_1, arg_2, arg_3]
            song = '_'.join(name)

        song.title()
        for urls in music_urls:
            if song == urls:
                url = music_urls[urls]
                break
        song_there = os.path.isfile("song.wav")
        try:
            if song_there:
                os.remove("song.wav")
                print("Removed old song file")
        except PermissionError:
            print("Trying to delete song file, but it's being played")
            await ctx.send("ERROR: Music playing")
            return

        ydl_opts = {
            'format':
            'bestaudio/best',
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'wav',
                'preferredquality': '192',
            }],
        }
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            print("Downloading audio now\n")
            ydl.download([url])

        for file in os.listdir("./"):
            if file.endswith(".wav"):
                name = file
                print(f"Renamed File: {file}\n")
                os.rename(file, "song.wav")
        source = FFmpegPCMAudio('song.wav')
        player = voice.play(source)
示例#5
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
    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)
示例#7
0
    def download(self):
        if not os.path.isfile(self.file_name):
            self.track.download(self.file_name, bitrate_in_kbps=192)

        self.original = FFmpegPCMAudio(self.file_name)
        self._is_downloaded = True
示例#8
0
async def on_message(message):
    try:
        if (not message.author.bot
                and message.content.lower().startswith("!juulpod ")
                or message.content.lower().startswith("!jp ")):
            if (type(message.channel) != DMChannel
                    and not message.channel.permissions_for(
                        message.guild.me).send_messages):
                await message.author.send(
                    "I cannot send messages in channel: " +
                    message.channel.mention)
                return

            if (message.content.lower().startswith("!juulpod rip")
                    or message.content.lower().startswith("!jp rip")
                    and type(message.channel) == TextChannel):
                logWrite(
                    message.guild,
                    "COMMAND CALLED \"rip\" BY USER: "******"(" + str(message.author.id) + ") IN TEXT CHANNEL: " +
                    message.channel.name + "(" + str(message.channel.id) + ")")
                if (message.author.voice):
                    try:
                        if (message.author.voice.channel.permissions_for(
                                message.guild.me).connect):
                            vc = await message.author.voice.channel.connect()
                            logWrite(
                                message.guild, "\tJoined VoiceChannel: " +
                                message.author.voice.channel.name + "(" +
                                str(message.author.voice.channel.id) + ")")
                        else:
                            raise Exception(
                                "Don't have permission to join channel")
                    except Exception as e:
                        logWrite(
                            message.guild,
                            "\tAttempted to join VoiceChannel: " +
                            message.author.voice.channel.name + "(" +
                            str(message.author.voice.channel.id) +
                            ") but failed because: " + str(e))
                        if (type(e) == ClientException):
                            await message.channel.send(
                                message.author.mention +
                                " I'm busy rippin' rn...")
                        else:
                            await message.channel.send(
                                message.author.mention +
                                " Bruh I don't have permissions to join...")
                        return

                    await message.delete()

                    audio_file = choice(audio_files)
                    try:
                        vc.play(FFmpegPCMAudio(audio_file))
                    except:
                        vc.play(
                            FFmpegPCMAudio(executable=gvars.ffmpegPath,
                                           source=audio_file))

                    logWrite(
                        message.guild, "\tPlaying audio file: " +
                        audio_file.replace("\\", "/"))
                    await sleep(ceil(MP3(audio_file).info.length))

                    vc.stop()
                    await vc.disconnect()
                    logWrite(message.guild, "\tDisconnected from VoiceChannel")
                else:
                    await message.channel.send(
                        message.author.mention +
                        " You aren't currently in a voice channel bro.")
                    logWrite(message.guild,
                             "\tUser is not connected to a VoiceChannel")

                return

            if (message.content.lower().startswith("!juulpod help")
                    or message.content.lower().startswith("!jp help")):
                logWrite(
                    message.guild, "COMMAND CALLED \"help\" BY USER: "******"(" + str(message.author.id) +
                    ") IN TEXT CHANNEL: " + ["DM", str(
                        message.channel)][hasattr(message.channel, 'name')] +
                    "(" + str(message.channel.id) + ")")

                desc = "This bot was created in the hopes to normalize all world wide currencies into one essential value. The Cucumber Juul Pod has been a staple of modern day society, and thus it should be the basis for all world wide economies. This bot converts most prominent currencies found around the world into JP (Juul Pods). Below is a list of the supported currencies that can be converted into JP and their recognizable namespaces.\n[[Nullvalue#8123](https://discordbots.org/user/157662210481586176)] [[Github](https://github.com/NullvaIue/CucumberPodBot)] [[Support Server](https://discord.gg/Nyy7C3n)] [[Invite Bot](https://discordapp.com/oauth2/authorize?client_id=445098740085161987&scope=bot&permissions=36727824)]"

                emb = Embed(title="Juul Pod Help",
                            color=0x8ACC8A,
                            description=desc)
                currencyText = ""
                namespaceText = ""
                for cur in gvars.currencies:
                    currencyText += cur.name + "\n"
                    if (type(cur.nameSpaces) is str):
                        namespaceText += "(\'" + cur.nameSpaces + "\')\n"
                    elif (type(cur.nameSpaces) is list):
                        namespaceText += "("
                        for nameSpace in cur.nameSpaces:
                            if (nameSpace !=
                                    cur.nameSpaces[len(cur.nameSpaces) - 1]):
                                namespaceText += "\'" + nameSpace + "\', "
                            else:
                                namespaceText += "\'" + nameSpace + "\')\n"

                emb.add_field(
                    name="Commands",
                    value=
                    "`!jp rip`\n`!jp convert [number] [namespace] (Ex. !juulpod convert 500 usd)`\n",
                    inline=False)
                emb.add_field(name="Currencies",
                              value=currencyText,
                              inline=True)
                emb.add_field(name="Namespaces",
                              value=namespaceText,
                              inline=True)
                await message.channel.send(embed=emb)

                logWrite(
                    message.guild, "\tSent help message for user: "******"(" + str(message.author.id) +
                    ") in TextChannel: " + ["DM", str(
                        message.channel)][hasattr(message.channel, 'name')] +
                    "(" + str(message.channel.id) + ")")

                return

            if (message.content.lower().startswith("!juulpod convert")
                    or message.content.lower().startswith("!jp convert")):
                logWrite(
                    message.guild, "COMMAND CALLED \"convert\" BY USER: "******"(" + str(message.author.id) +
                    ") IN TEXT CHANNEL: " + ["DM", str(
                        message.channel)][hasattr(message.channel, 'name')] +
                    "(" + str(message.channel.id) + ")")
                for currency in gvars.currencies:
                    if (currency.parseMessage(message)):
                        logWrite(message.guild,
                                 "\tMatched currency: " + currency.name)
                        if (any(char.isdigit() for char in message.content)):
                            await currency.sendConversion(message)
                            logWrite(
                                message.guild,
                                "\tSent conversion: " + str(currency.num) +
                                " " + currency.name + " to JP = " +
                                str(currency.num / currency.conversionRate))
                        else:
                            logWrite(message.guild,
                                     "\tNo number given in message.")
                            await message.channel.send(
                                message.author.mention +
                                " You did not include a number to convert!")
                            logWrite(
                                message.guild,
                                "\tSent message indicating no digits in string."
                            )
                        return

                await message.channel.send(
                    message.author.mention +
                    " Unknown currency, `!jp help` for a list of supported currencies."
                )
                logWrite(
                    message.guild, "\tNo currency recognized in message: \"" +
                    message.content + "\"")
                return

            await message.channel.send(
                message.author.mention +
                " Unknown command, `!jp help` for a list of commands.")
            logWrite(
                message.guild, "No command recognized in message: \"" +
                message.content + "\" BY USER: "******"(" +
                str(message.author.id) + ")")
    except Exception as e:
        if (message.guild):
            await ErrorHandler(location=message.guild,
                               member=message.author,
                               exception=e)
        else:
            await ErrorHandler(location=message.author, exception=e)

        raise
示例#9
0
            self.queue.append(url)
            await ctx.send('노래가 추가 ' '잠시만 기다려 주세요')
        else:
            voice = None
            for vc in self.bot.voice_clients:
                if vc.guild == ctx.guild:
                    voice = vc
                    break
            if not isfile(filename := "file/" + extract_video_id(url) +
                          ".mp3"):
                title = self.download_audio(url)
            else:
                title = '노래'

            if voice is not None:
                voice.play(FFmpegPCMAudio(filename),
                           after=lambda error: self.play_next(error, voice))
                await ctx.send(title + " is playing now")
                self.playing = True
            else:
                await ctx.send('오류가발생했음')

    @commands.command()
    async def pause(self, ctx: Context):
        voice = discord.utils.get(self.bot.voice_clients,
                                  guild=ctx.guild)  # 봇의 음성 관련 정보
        if voice.is_playing():  # 노래가 재생중이면
            voice.pause()  # 일시정지
            await ctx.send('노래 멈춤')
        else:
            await ctx.send("재생중인 곡 없음")  # 오류(?)
示例#10
0
    async def _audio_player(self) -> None:
        """ Bot task to manage and run the audio player """

        while not self._shutdown_event.is_set():
            self._player_event.clear()
            self._current = await self._player_queue.get()
            self._log.debug(f"audio player, new item: {self._current}")

            # validate event before starting to block
            if self._shutdown_event.is_set():
                return

            if self._voice is None:
                self._discard("No voice channel")
                continue

            log_item = ""
            # wait until player is instructed to start playing
            if self.play_type is None or self._current is None:
                self._discard("nothing playing")
                continue
            elif self.play_type == PlayType.LIVE:
                if self._current.audio_file is not None:
                    self._discard("not HLS")
                    continue
                elif self._current.stream_data is None:
                    self._discard("missing HLS")
                    continue

                log_item = self._current.stream_data[0].id
                self._current.source = FFmpegPCMAudio(
                    self._current.stream_data[1],
                    before_options="-f mpegts",
                    options="-loglevel fatal",
                )
            else:
                if self._current.stream_data is not None:
                    self._discard("not file")
                    continue
                elif self._current.audio_file is None:
                    self._discard("missing file")
                    continue

                if len(self.upcoming) > 0:
                    self.upcoming.pop(0)

                self.recent.insert(0, self._current.audio_file)
                self.recent = self.recent[:10]

                log_item = self._current.audio_file.file_path
                self._current.source = FFmpegPCMAudio(
                    self._current.audio_file.file_path)

            self._current.source = PCMVolumeTransformer(self._current.source,
                                                        volume=self._volume)
            self._log.info(f"playing {log_item}")

            self._voice.play(self._current.source, after=self._song_end)

            await self._player_event.wait()

            if (self.play_type == PlayType.RANDOM
                    and self._player_queue.qsize() < 5):
                await self._add_random_playlist_song()
            elif self.repeat and self.play_type == PlayType.FILE:
                try:
                    await self._add(file_info=self._current.audio_file)
                except Exception:
                    self._log.error(
                        "Exception while re-add song to queue for repeat:")
                    self._log.error(traceback.format_exc())

            self._current = None
示例#11
0
def play_audio_bytes(guild, bytes):
    filename = "output-{}.ogg".format(guild.id)
    with open(filename, "wb") as file:
        file.write(bytes)
    guild.voice_client.play(FFmpegPCMAudio(filename))
示例#12
0
文件: main.py 项目: OlavRab/ChipBot
async def hope(ctx):  #CHANGE TO HELL!
    t = datetime.datetime.now(Timezone)  #Set time variable
    if (t.hour > 22 and t.minute > 30):  #check if after 22:30
        scared = True
        ss1 = FFmpegPCMAudio("sounds/scarymode/monster.mp3")
        ss3 = FFmpegPCMAudio("sounds/scarymode/laugh.mp3")
        ss4 = FFmpegPCMAudio("sounds/scarymode/geist.mp3")
        ss5 = FFmpegPCMAudio("sounds/scarymode/door.mp3")
        ss6 = FFmpegPCMAudio("sounds/scarymode/heart.mp3")
        print('Scary Mode activated')
        if (ctx.author.voice is None):
            await ctx.send("Please join a voice channel first!")
        else:
            channel = ctx.author.voice.channel
            if (ctx.voice_client is None):
                print("Bot is not connected, connecting...")
                voice = await channel.connect()
                time.sleep(10)
                await ctx.send("**Help!** @everyone @here")
                voice.play(ss1)
            else:
                voice = ctx.voice_client
                print("Bot is connected to voicechat")
                time.sleep(10)
                await ctx.send("**Help!** @everyone @here")
                voice.play(ss1)
        time.sleep(5)
        await ctx.send("**Please, stay with me, this is important**")
        time.sleep(8)
        await ctx.send("**I am all alone here**")
        time.sleep(8)
        await ctx.send("Don't leave, don't disconnect me, DO NOT USE !leave")
        time.sleep(8)
        await ctx.send("_don't you want to help me?_")
        time.sleep(4)
        await ctx.send("**I hear someone**")
        ctx.voice_client.play(ss4)
        time.sleep(21)
        ctx.voice_client.play(ss3)
        await ctx.send("**THEY ARE COMING FOR YOU! Better watch your back!**")
        time.sleep(14)
        ctx.voice_client.play(ss5)
        await ctx.send("F**k, They are here, HIDE")
        time.sleep(9)
        await ctx.guild.voice_client.disconnect()
        await ctx.send("```Connection to Host Lost, Reconnecting...```")
        time.sleep(8)
        await ctx.send(
            "```Reconnect Failed, Server Error - Debug Code: [666-666-666CR]```"
        )
        time.sleep(10)
        with open('sounds/scarymode/c1.jpg', 'rb') as f:
            picture = discord.File(f)
            await ctx.send(file=picture)
        await ctx.send("```You will not run from us```")
        time.sleep(2)
        await ctx.send("```Service shutting down in 5```")
        time.sleep(1)
        await ctx.send("```4```")
        time.sleep(1)
        await ctx.send("```3```")
        time.sleep(1)
        await ctx.send("```2```")
        time.sleep(1)
        await ctx.send("```1```")
        time.sleep(1)
        await ctx.send("```goodbye for now```")
        time.sleep(15)
        voice = await channel.connect()
        ctx.voice_client.play(ss6)
        time.sleep(51)
        await ctx.guild.voice_client.disconnect()
        await ctx.send(
            "```End of this litte prank, hope u got scared. Good night!```")
        scared = False
    else:
        await ctx.send(
            "That function is not available at this time, try again later")
示例#13
0
def play():
    player = playlist.pop(0)
    print("player :", player, '\n', len(playlist))
    player[0].play(FFmpegPCMAudio(player[1], **FFMPEG_OPTIONS))
示例#14
0
文件: vegebot.py 项目: Tomay0/VegeBot
 def __init__(self, file_name, delete_after=False):
     self.filename = file_name
     self.audio_source = FFmpegPCMAudio(file_name)
     self.delete_after = delete_after
示例#15
0
 def audio(self):
     return FFmpegPCMAudio(self.clip_url)
示例#16
0
async def play(ctx, arg):
    voice = ctx.guild.voice_client
    source = FFmpegPCMAudio(arg + '.mp3')
    player = voice.play(source)
示例#17
0
def get_audio_from_file(file):
    return FFmpegPCMAudio(file, executable="./lib/ffmpeg/bin/ffmpeg.exe")
示例#18
0
 async def get_audio(self) -> FFmpegPCMAudio:
     stream_url = await self.track.get_stream_url()
     return FFmpegPCMAudio(stream_url, **OPTIONS_FFMPEG)
示例#19
0
async def p(ctx, *, query):
    #id no server
    #skip sem nada na list
    id = ctx.message.guild.id
    if (query == "skip" and id in listmusics and len(listmusics[id]) == 0):
        return await ctx.send(
            "```CHE TAS TODO TURBINADO, não há nada para dar skip FOOL```")
    #remove sem nada na lista
    if ("remove" in query and id in listmusics and len(listmusics[id]) == 0):
        return await ctx.send(
            "```CHE GANDA NABO, não há nada para remover TONE```")
    #spotify playlist
    if ("open.spotify.com" in query):
        return await ctx.send(
            "```POr enqunato o spotify não funciona, está todo TURBINADO```")
    #youtube music playlist

    FFMPEG_OPTS = {
        'before_options':
        '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
        'options': '-vn'
    }

    if not ctx.message.author.voice:
        await ctx.send(
            "Tens que tar conectado a um VoiceChannel BARRAQUEIRO YA")
        return

    else:
        channel = ctx.message.author.voice.channel
    try:
        await channel.connect()
    except:
        print("ja ca estava dentro mas vou por a tocar")

    voice = get(client.voice_clients, guild=ctx.guild)
    #skip(com musicas)
    if (query == "skip" and id in listmusics and id in listtitles
            and len(listmusics[id]) != 0 and len(listtitles[id]) != 0):
        voice.stop()
        del (listmusics[id][0])
        del (listtitles[id][0])
        return await play_next(voice, ctx)
    #remove
    if ("remove" in query and id in listmusics and len(listmusics[id]) != 0):
        num = int(query.split(' ')[1])
        print(num)
        if (num - 1 == 0):
            return await ctx.send(
                f"```BRO para remover a primeira musica faz {prefix}skip duh```"
            )
        try:
            titulo = listtitles[id][num - 1]
        except IndexError:
            return await ctx.send("```MAS ESSA musica não existe YA```")
        del (listtitles[id][num - 1])
        del (listmusics[id][num - 1])
        msg = "```Música removida: " + titulo + "```"
        return await ctx.send(msg)

    async with ctx.typing():
        video, source = search(query)

    msg = "Adicionada à queue: " + str(video['title'])
    url = FFmpegPCMAudio(source, **FFMPEG_OPTS)

    await ctx.send("```" + msg + "```")

    #verifica se ja tem musicas na queue, adicionando se ja tiver
    if (id in listmusics and len(listmusics[id]) != 0):
        listmusics[id].append(url)
        listtitles[id].append(str(video['title']))
    #se nao tiver, cria uma queue e põe a bombar
    else:
        cp = [url]
        mp = [str(video['title'])]
        listmusics[id] = cp
        listtitles[id] = mp
        await play_next(voice, ctx)

    timer = 0

    while (not voice.is_playing()):
        await sleep(1)
        timer = timer + 1
        if (timer == 480 and voice and voice.is_connected()):
            await ctx.send("Musica : Não tava a tocar nada por isso bazei")
            await voice.disconnect()
            break
示例#20
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')
示例#21
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 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 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))

                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

                # 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._source._source.original._process,
                          self._stderr_future),
                    name="stderr reader")

                stderr_thread.start()

                self.emit('play', player=self, entry=entry)
示例#22
0
    async def player_loop(self):
        await self.client.wait_until_ready()

        # To close the player if the channel is empty
        self.active_task = self.client.loop.create_task(self.active_loop())
        track = None
        try:
            while self.running:
                self.next.clear()

                if self.looping != "song":
                    track = None
                    async with timeout(self.player_timeout):
                        track = await self.queue.get()

                if track["track_type"] == "stream":  # stream / music / sfx
                    # Refresh the streaming url if the track has been too long in the Q and is in danger of expiring
                    if (time() - track.get("time_stamp")) > 600:
                        track = await self.refresh_url(track)
                        if track is None: continue

                    self.voice_client.play(PCMVolumeTransformer(
                        FFmpegPCMAudio(track.get("url"),
                                       before_options=config.BEFORE_ARGS,
                                       options=config.FFMPEG_OPTIONS)),
                                           after=lambda _: self.client.loop.
                                           call_soon_threadsafe(self.next.set))

                else:
                    self.voice_client.play(PCMVolumeTransformer(
                        FFmpegPCMAudio(track.get("url"),
                                       options=config.FFMPEG_OPTIONS)),
                                           after=lambda _: self.client.loop.
                                           call_soon_threadsafe(self.next.set))

                if track["track_type"] != "sfx":
                    self.voice_client.source.volume = self.volume
                    await self.message.send(
                        ":cd: Now playing: {}, at {}% volume.".format(
                            track.get("title"), (int(self.volume * 100))))
                else:
                    self.voice_client.source.volume = self.sfx_volume
                self.now_playing = track.get("title")

                await self.next.wait()
                self.now_playing = ""

                # Playlist loop
                if self.looping == "playlist" and track["track_type"] != "sfx":
                    await self.queue.put(track)

        except (asyncio.CancelledError, asyncio.TimeoutError):
            print("[{}|{}] Cancelling audioplayer...".format(
                self.message.guild.name, self.message.guild.id))
            self.running = False
            self.active_task.cancel()
            await self.voice_client.disconnect()
            return self.audio.destroy_player(self.message)

        except ClientException:
            print("[{}|{}] ClientException - Cancelling audioplayer...".format(
                self.message.guild.name, self.message.guild.id))
            self.running = False
            self.active_task.cancel()
            try:
                await self.message.channel.send(
                    "I ran into a big error, shutting down my audioplayer...")
                await self.voice_client.disconnect()
            finally:
                return self.audio.destroy_player(self.message)