Esempio n. 1
0
async def skip(ctx, queue=queue):
    global loop
    serverid = ctx.message.guild.id
    song_there = os.path.isfile("song.mp3")
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    if voice.is_playing() != None:
        voice.stop()
        video = pafy.new(queuenames[serverid[0]])
        best = video.getbest()
        source = FFmpegPCMAudio(best.url, **FFMPEG_OPTIONS)
        url, title = _search(queue[0])
        if loop == True:
            queue.append(queuenames[serverid[0]])
            queue.remove(queuenames[serverid[0]])
        else:
            queue.remove(queuenames[serverid[0]])

    else:
        voice.stop()
        video = pafy.new(queuenames[serverid[0]])
        best = video.getbest()
        source = FFmpegPCMAudio(best.url, **FFMPEG_OPTIONS)
        url, title = _search(queuenames[serverid[0]])
        if loop == True:
            queue.append(queuenames[serverid[0]])
            queue.remove(queuenames[serverid[0]])
        else:
            queue.remove(queuenames[serverid[0]])

    await ctx.send(f'Now playing {title[0]}')
    voice.play(source)
Esempio n. 2
0
    async def _play(self, ctx):

        if not self.vc.is_playing() and self.queue:
            temp = 0
            song_short = ""
            for i in range(len(self.queue[0])):
                if self.queue[0][i] == '-':
                    temp += 1
                if temp == 2:
                    break
                song_short += self.queue[0][i]

            self.do = False

            await ctx.send(f"```Now playing {song_short[13:]}```")
            await asyncio.sleep(1.40)
            for emoji in self.emojis:
                await ctx.channel.last_message.add_reaction(emoji)
            await asyncio.sleep(1.20)

            self.do = True

            if not self.loop:
                if self.queue:
                    self.source = FFmpegPCMAudio(self.queue.pop(0))

            if self.loop:
                if self.queue:
                    self.source = FFmpegPCMAudio(self.queue[0])

            self.vc.play(self.source, after=self.next_song)
Esempio n. 3
0
    async def play(self, ctx, url: str):  #Kopiera in en URL länk
        voice_channel = ctx.author.voice.channel
        try:  #ansluter till en röstkanal sen laddar ner videon och sen spelar
            voice = await voice_channel.connect()
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                ydl.download([url])
            for file in os.listdir("./"):
                if file.endswith(".mp3"):
                    os.rename(file, "song.mp3")
            source = FFmpegPCMAudio("song.mp3")
            player = voice.play(source)
            player = player

        except:
            try:  #om botten redan ansluten spelas ljudet upp  och raderar filen
                os.remove("song.mp3")
                time.sleep(1)
                voice = discord.utils.get(self.client.voice_clients,
                                          guild=ctx.guild)
                with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                    ydl.download([url])
                for file in os.listdir("./"):
                    if file.endswith(".mp3"):
                        os.rename(file, "song.mp3")
                source = FFmpegPCMAudio("song.mp3")
                player = voice.play(source)
            except:  #spelar bara upp ljudet
                voice = discord.utils.get(self.client.voice_clients,
                                          guild=ctx.guild)
                with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                    ydl.download([url])
                for file in os.listdir("./"):
                    if file.endswith(".mp3"):
                        os.rename(file, "song.mp3")
                source = FFmpegPCMAudio("song.mp3")
    async def audio_player_task(self):
        while True:
            self.next.clear()

            if self.loop:
                # YTDLSource(PCMVolumeTransformer(AudioSource)) can't be
                # rewinded, the only way is to recreate it with the same
                # source
                if self.current.state == 'downloaded':
                    recreated_source = FFmpegPCMAudio(
                        f'{self.bot.command_prefix}.mp3'.replace('..', '.'))
                else:
                    recreated_source = FFmpegPCMAudio(
                        self.current.source.stream_url,
                        **YTDLSource.FFMPEG_OPTIONS,
                    )
                # if FFmpegPCMAudio fails to read source (e.g. file is missing or
                # failed to connect to server), .read() returns b''
                if not recreated_source.read():
                    self.loop = False
                    self.voice.stop()
                    self.next.set()
                else:
                    self.current.source = YTDLSource(
                        self._ctx,
                        recreated_source,
                        data=self.current.source.data,
                        volume=self.volume,
                    )
                    self.voice.play(self.current.source,
                                    after=self.play_next_song)
            else:
                # Try to get the next song from SongQueue within
                # given timeout. If no song will be added to the
                # queue in time, the player will disconnect due
                # to performance reasons.
                try:
                    async with timeout(SONG_QUEUE_TIMEOUT):
                        self.current = await self.songs.get()
                except asyncio.TimeoutError:
                    await self.current.source.channel.send(
                        f'No new songs in queue for {SONG_QUEUE_TIMEOUT} seconds. Bot now disconnects.'
                    )
                    self.bot.loop.create_task(self.suspend())
                    self.exists = False
                    return

                # feedback to Discord (feedback on loop can produce spam)
                await self.current.source.channel.send(
                    embed=self.current.create_embed().add_field(
                        name='Loop', value=self.loop).add_field(
                            name='Volume', value=int(self.volume * 100)))

                self.voice.play(self.current.source, after=self.play_next_song)

            await self.next.wait()
Esempio n. 5
0
    async def __music_player(self):
        if self.__player:
            if self.__music_list:
                if not self.__player.is_playing() and not self.__paused:
                    actual_music = self.remove_caracteres(self.__music_list.pop(0))

                    if os.path.exists(f'./music_cache/{actual_music}.m4a'):
                        self.__player.play(FFmpegPCMAudio(f'./music_cache/{actual_music}.m4a'))

                    else:
                        self.__player.play(FFmpegPCMAudio(f'./music_cache/{actual_music}.webm'))

                    await self.__original_channel.send(f':notes: Reproduzindo {actual_music}!')
Esempio n. 6
0
async def bababooey(bot, message):
    author_voice_status = message.author.voice
    if author_voice_status is not None and author_voice_status.channel is not None:
        bababooey_audio_stream = FFmpegPCMAudio(
            'bossbot/resources/bababooey.mp3')
        voice_client = await author_voice_status.channel.connect()
        voice_client.play(bababooey_audio_stream)
        while voice_client.is_playing():
            sleep(1)
        bababooey_audio_stream.cleanup()
        await voice_client.disconnect()
    else:
        await message.channel.send(
            'https://www.youtube.com/watch?v=U_cPir6MwLM')
Esempio n. 7
0
async def play_youtube_url(youtube_url, context, channel_voice):
    # Create StreamPlayer
    voice_client = await channel_voice.connect()

    # Download song
    await context.send(':robot: Fetching song ...')
    file_id = uuid.uuid1().hex
    yt = YouTube(youtube_url)
    song_title = yt.title
    filename = '{0}.{1}'.format(file_id, extension)
    yt.streams.get_audio_only().download(filename=file_id)

    # Send message to text channel
    await context.send(
        ':musical_keyboard: Playing {0} :musical_keyboard:'.format(song_title))

    # Setting bot status
    await bot.change_presence(
        activity=Activity(type=ActivityType.playing, name=song_title))

    # Play music
    voice_client.play(FFmpegPCMAudio(filename), after=lambda: print('done'))

    # Check if audio is playing
    while voice_client.is_playing():
        await asyncio.sleep(1)

    # Disconnect after the player has finished
    os.remove(filename)
    voice_client.stop()
    await voice_client.disconnect()

    # Setting bot status
    await bot.change_presence(None)
Esempio n. 8
0
    async def play(self, ctx, query):
        """
        Play an audio clip
        - schokobons
        - raus
        """

        ydl_opts = {
            'format':
            'bestaudio/best',
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192',
            }],
        }

        await ctx.trigger_typing()
        uri = self.parse(query)
        if uri:
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                song_info = ydl.extract_info(uri, download=False)
                audio_stream = song_info["formats"][0]["url"]

            audio_source = FFmpegPCMAudio(audio_stream)
            async with Player() as player:
                vc = await player.connect(self.bot, ctx.author.voice.channel)
                await player.play(vc, audio_source)
            await ctx.send(f"Playing: {uri}")
        else:
            await ctx.send(f"Clip '{query}' not found")
Esempio n. 9
0
async def rand(ctx):
    channel = ctx.message.author.voice.channel
    if not channel:
        await ctx.send("Wejdź do kanału głosowego")
        return
    voice = get(client.voice_clients, guild=ctx.guild)
    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()
    lista = []
    for file in os.listdir("C:\\Users\\kacpe\\Desktop\\DiscordBot\\v2\\mp3"):
        if file.endswith(".mp3"):
            lista.append(file)
    plik = random.choice(lista)
    sciezka = f"mp3\\{plik}"
    source = FFmpegPCMAudio(sciezka)
    l = subprocess.run([
        'ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of',
        'default=noprint_wrappers=1:nokey=1', sciezka
    ],
                       stdout=subprocess.PIPE,
                       stderr=subprocess.STDOUT)
    dlugosc = float(l.stdout)
    player = voice.play(source)
    server = ctx.message.guild.voice_client
    time.sleep(dlugosc)
    await server.disconnect()
Esempio n. 10
0
    async def on_ready():
        await client.get_channel(creds.text_channel_id
                                 ).send(f"Playing {videoname}")
        vca = client.get_channel(creds.voice_channel_id)
        vc = await vca.connect()
        YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
        FFMPEG_OPTIONS = {
            'before_options':
            '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
            'options': '-vn'
        }

        if not vc.is_playing():
            with YoutubeDL(YDL_OPTIONS) as ydl:
                info = ydl.extract_info(url, download=False)
            URL = info['formats'][0]['url']
            vc.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))
            while vc.is_playing():
                await sleep(1)
            await client.close()
            os.execl(sys.executable, sys.executable, *sys.argv)
        else:
            await client.get_channel(creds.text_channel_id
                                     ).send("Already playing song")
            return
Esempio n. 11
0
async def 멜론차트(ctx):
    if not vc.is_playing():
        
        options = webdriver.ChromeOptions()
        options.add_argument("headless")

        global entireText
        YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist':'True'}
        FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
            
        chromedriver_dir = r"C:\python bot\chromedriver.exe"
        driver = webdriver.Chrome(chromedriver_dir, options = options)
        driver.get("https://www.youtube.com/results?search_query=멜론차트")
        source = driver.page_source
        bs = BeautifulSoup(source, 'lxml')
        entire = bs.find_all('a', {'id': 'video-title'})
        entireNum = entire[0]
        entireText = entireNum.text.strip()
        musicurl = entireNum.get('href')
        url = 'https://www.youtube.com'+musicurl 

        driver.quit()

        musicnow.insert(0, entireText)
        with YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(url, download=False)
        URL = info['formats'][0]['url']
        await ctx.send(embed = discord.Embed(title= "노래 재생", description = "현재 " + musicnow[0] + "을(를) 재생하고 있습니다.", color = 0x00ff00))
        vc.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS), after = lambda e: play_next(ctx))
    else:
        await ctx.send("이미 노래가 재생 중이라 노래를 재생할 수 없어요!")
Esempio n. 12
0
async def urlplay(ctx, *, url):

    try:
        global vc
        vc = await ctx.message.author.voice.channel.connect()
    except:
        try:
            await vc.move_to(ctx.message.author.voice.channel)
        except:
            await ctx.send("채널에 유저가 접속해있지 않았습니다.")

    YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
    FFMPEG_OPTIONS = {
        'before_options':
        '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
        'options': '-vn'
    }

    if not vc.is_playing():
        with YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(url, download=False)
        URL = info['formats'][0]['url']
        vc.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))
        await ctx.send(embed=discord.Embed(title="play",
                                           description="현재 " + url +
                                           "을(를) 재생하고 있습니다.",
                                           color=0x00ff00))
    else:
        await ctx.send("노래가 이미 재생되고 있습니다!")
Esempio n. 13
0
async def playmugs(ctx: Context):
    # Filter based on channel source and author role
    author_roles = [role.name for role in ctx.message.author.roles]
    if (ctx.message.channel.id != CMD_CHANNEL_ID
            or PRESIDENT_ROLE not in author_roles):
        return

    # Play mug sounds
    vc = cast(VoiceClient, ctx.voice_client)
    print("Playing music")
    vc.play(FFmpegPCMAudio("assets/mugs.mp3"))
    while vc.is_playing():
        await asyncio.sleep(0.01)
    print("Music done")

    # Add a sleep here if desired

    voice_chann = cast(VoiceChannel, ctx.voice_client.channel)
    target_channel = await bot.fetch_channel(TARGET_CHANNEL_ID)
    # NOTE: this only moves members that joined after the bot
    print(voice_chann.members)
    for user in voice_chann.members:
        if user.id == bot.user.id:
            continue
        await user.move_to(target_channel)
        await user.edit(mute=True)
Esempio n. 14
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. 15
0
    async def play(self, context: commands.Context, station: str = None):
        if not station:
            await context.send("Podaj nazwę stacji (w cudzysłowie)")
            return

        if not context.author.voice:
            await context.send(
                f"Dołącz najpierw do kanału głosowego, @{context.author}.")
            return

        if station not in self.stations_list.keys():
            await context.send(f"Nie odnaleziono stacji {station}")
            return
        else:
            station_url = self.stations_list.get(station)

        audio_source: AudioSource = FFmpegPCMAudio(station_url)

        try:
            voice_client: VoiceClient = await context.author.voice.channel.connect(
            )
            await self._play_stream(audio_source, voice_client)
        except ClientException as ce:
            for vc in self.bot.voice_clients:
                if vc.channel == context.author.voice.channel:
                    vc.stop()
                    await self._play_stream(audio_source, vc)
                else:
                    await context.send("Błąd odtwarzania")
                    return
        except CommandInvokeError as cie:
            await context.send(
                f"Dołącz najpierw do kanału głosowego, {context.author}.")
            return
Esempio n. 16
0
async def intro_message_0(context):
    global state
    if state != 0:
        await context.send("ERROR invalid command at this time")
        return
    state = 1

    AUDIO_CHANNEL = discord.utils.get(context.guild.channels,
                                      name="Paddy's Pub")
    await AUDIO_CHANNEL.connect()

    await context.send(file=discord.File('title_card.png'))
    await context.send(file=discord.File('time_stamp.png'))

    vc = cast(VoiceClient, context.voice_client)
    print("Playing Theme Song")
    vc.play(FFmpegPCMAudio("its-always-sunny-in-philadelphia-theme-song.mp3"))
    while vc.is_playing():
        await asyncio.sleep(0.01)
    print("Theme Song done")

    await context.send(file=discord.File('emoji/paddys.png'))
    with open('messages/intro_0_0.txt', 'r') as file:
        message = file.read()
        await context.send(message)
    await context.send(file=discord.File('chardeemacdennis.png'))
    with open('messages/intro_0_1.txt', 'r') as file:
        message = file.read()
        await context.send(message)
Esempio n. 17
0
    async def _play(self):
        """
        Heavy lifting of playing songs

        Grabs the appropiate streaming URL, sends the `now playing`
        message, and initiates playback in the vc.

        Args:
            None

        Returns:
            None

        Raises:
            None
        """
        track_url = self.current_track.getStreamURL()
        audio_stream = FFmpegPCMAudio(track_url)

        while self.voice_channel.is_playing():
            asyncio.sleep(2)

        self.voice_channel.play(audio_stream, after=self._toggle_next)

        plex_log.debug("%s - URL: %s", self.current_track, track_url)

        embed, img = self._build_embed_track(self.current_track)
        self.np_message_id = await self.ctx.send(embed=embed, file=img)
Esempio n. 18
0
async def campfire(ctx):
    
        vc.play(FFmpegPCMAudio('campfire.mp3'), after=lambda e: print("coś", e))
        while vc.is_playing():
            await asyncio.sleep(1)
        vc.stop()
        await vc.disconnect()
Esempio n. 19
0
    async def join(self, ctx):
        """ Makes SuitsBot join the voice channel """

        try:
            # Gets the voice channel the author is in
            author_voice_channel = ctx.author.voice.channel if ctx.author.voice is not None else None
            if author_voice_channel is None:  # Ignore command if author is not in voice
                await ctx.send("You are not in a voice channel right now")
                return
            if in_voice_channel(
                    author_voice_channel
            ):  # Ignore request if bot already in voice channel
                await ctx.send("The bot is already in voice with you")
                return
            # Connect to author's channel
            await ctx.send("Joining voice channel...")
            self.bot.voice = await join_audio_channel(author_voice_channel)
            if self.bot.voice:
                # Plays joining voice clip
                self.bot.voice.play(
                    FFmpegPCMAudio(SOUNDS_DIR + 'hello_there_obi.mp3'))
            else:
                await ctx.send(
                    f"I'm sorry {ctx.author.mention}, but I was not able to join {author_voice_channel}"
                )
        except Exception as e:
            await utils.report(str(e), source="join command", ctx=ctx)
Esempio n. 20
0
async def queue(ctx, url=None):
    log(ctx.message.content, ctx.message.author)

    # joining channel
    try:
        channel = ctx.message.author.voice.channel
        if not channel:
            await ctx.send("You must be connected to a voice channel")
            return
        voice = get(client.voice_clients, guild=ctx.guild)
        if voice and voice.is_connected():
            await voice.move_to(channel)
        else:
            voice = await channel.connect()
    except AttributeError:
        await ctx.send("You must be connected to a voice channel")
        return

    # downloads and queues song if url exists
    if url:
        youtube.enqueue(url)
    else:
        await ctx.send(f"Usage: `{config.PREFIX}play [youtube url]`")
        return

    # plays the song
    song = youtube.pop_queue()
    voice.play(FFmpegPCMAudio(song))
    await ctx.send(f"Playing: {song}")
Esempio n. 21
0
async def play2(ctx, url):
    channel = ctx.message.author.voice.channel
    print("my channel was ", channel)
    await ctx.send(channel)
    voice = await channel.connect()
    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=ctx.guild)

    if not voice.is_playing():
        with YoutubeDL(YDL_OPTIONS) as ydl:
            args = ctx.message.content.split(" ")
            betterargs = " ".join(args[1:])
            #info = ydl.extract_info('https://www.youtube.com/watch?v=' + betterargs, download=False)
            info = ydl.extract_info(
                'https://www.youtube.com/watch?v=zczFoOBe1eQ', download=False)
        URL = info['formats'][0]['url']
        voice.source = discord.PCMVolumeTransformer(voice.source, volume=1.0)
        voice.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))
        voice.is_playing()
    else:
        await ctx.send("Already playing song")
        return
Esempio n. 22
0
async def ispovest(ctx):

    ispovest = random.choice(os.listdir("Ispovesti"))
    video_name = ispovest[:-4]
    video_link = 'Ispovesti/' + ispovest

    # check where the message was typed

    if ctx.voice_client is None:

        channel = ctx.author.voice.channel

        await channel.connect()

    YDL_OPTIONS = {'format': 'bestaudio/best',

                   'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',

                   'restrictfilenames': True,

                   'noplaylist': True,

                   'nocheckcertificate': True,

                   'ignoreerrors': False,

                   'logtostderr': False,

                   'quiet': True,

                   'no_warnings': True,

                   'default_search': 'auto',

                   # bind to ipv4 since ipv6 addresses cause issues sometimes
                   'source_address': '0.0.0.0'

                   }

    FFMPEG_OPTIONS = {'options': '-vn'}
    # voice = get(bot.voice_client, guild=ctx.guild)

    server = ctx.message.guild

    voice_channel = server.voice_client

    if not voice_channel.is_playing():

        voice_channel.play(FFmpegPCMAudio(
            source=video_link, **FFMPEG_OPTIONS))

        voice_channel.is_playing()

        await ctx.send(video_name)

    else:

        await ctx.send("Cekaj da zavrsim pricu")

        return
Esempio n. 23
0
async def play(ctx, url):

    voice = discord.utils.get(bot.voice_clients, guild=ctx.guild)

    if ctx.voice_client is None:

        channel = ctx.author.voice.channel

        await channel.connect()

    ydl_opts = {'format': 'bestaudio'}

    server = ctx.message.guild

    voice_channel = server.voice_client
    FFMPEG_OPTIONS = {
        'before_options':
        '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
        'options': 'vn'
    }
    if not voice_channel.is_playing():
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            info = ydl.extract_info(url, download=False)
            url2 = info['formats'][0]['url']
            print(url2)
            voice_channel.play(FFmpegPCMAudio(source=url2, **FFMPEG_OPTIONS))

        voice_channel.is_playing()

    else:

        await ctx.send("Cekaj da se zavrsi play ili kucaj '!stop'.")

    return
Esempio n. 24
0
 async def leave(self, ctx):
     voice_client = await self.get_current_voice_client()
     if voice_client:
         bye = FFmpegPCMAudio("Cogs/VoiceClient/farewell.mp3")
         voice_client.play(bye)
         await asyncio.sleep(2.5)
         await voice_client.disconnect()
Esempio n. 25
0
async def play(ctx,*args):
    if len(args) == 0:
        await ctx.send("Which song to play?")
    if len(args)>1:
        searchterm = ' '.join(args)
        print(searchterm)
    elif len(args)==1:
        searchterm = args[0]
        print(searchterm)
    
    first_url = "https://www.youtube.com"
    results = YoutubeSearch(searchterm,max_results=10).to_json()
    res = eval(results)
    url = first_url + res['videos'][0]['url_suffix']

    channel = ctx.message.author.voice.channel
    vc = await channel.connect()
    #'format': 'bestaudio', 
    YDL_OPTIONS = {'noplaylist':'True'}
    FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}

    if not vc.is_playing():
        with YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(url, download=False)
        URL = info['formats'][0]['url']
        vc.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))
        await ctx.send("Now Playing: "  + res['videos'][0]['title'])
        vc.is_playing()
    else:
        await ctx.send("Already playing song")
        return
Esempio n. 26
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. 27
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. 28
0
async def oynat(ctx):
    await gel(ctx)
    key = ctx.message.content

    input = key.replace("-oynat ", "")

    YDL_OPTIONS = {
        'format': 'bestaudio/best',
        'noplaylist': 'False',
        'default_search': 'auto'
    }
    FFMPEG_OPTIONS = {
        'before_options':
        '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
        'options': '-vn'
    }
    voice = get(client.voice_clients, guild=ctx.guild)

    if not voice.is_playing():
        with YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(input, download=False)

        if str(input).startswith('http'):
            URL = info['formats'][0]['url']
        else:
            ##URL = info['entries'][0]['formats'][0]['url']
            print(info)

        ctx.channel.send('oynatıyorum')
        voice.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))
        voice.is_playing()
    else:
        await ctx.send("dur bi")
        return
Esempio n. 29
0
async def play_sound(ctx, file_name: str):
    opus = ctypes.util.find_library('opus')
    load_opus(opus)

    if not exists(f"sounds/{file_name}.mp3"):
        await ctx.send("This sound has been injected!")
        return

    if not ctx.author.voice and not ctx.author.voice.channel:
        await ctx.send(f"{ctx.author.name} is not in a voice channel")

    client.currently_playing = True

    voice_channel = ctx.author.voice.channel

    vc = await voice_channel.connect()
    vc.play(
        FFmpegPCMAudio(executable=join(script_path, "bin", "ffmpeg"),
                       source=join(script_path, "sounds", f"{file_name}.mp3")))

    while vc.is_playing():
        await sleep(.1)

    client.currently_playing = False

    await vc.disconnect()
    await ctx.message.delete()
Esempio n. 30
0
async def coco(ctx):
    with con:
        con.execute(f'INSERT INTO coldOnes (time, username) VALUES (?,?);',
                    (datetime.datetime.now(), ctx.author.id))
        cursor = con.execute("SELECT COUNT(*) FROM coldOnes")
        myresult = cursor.fetchall()
    chance = randint(1, 100)
    if chance > 90:
        await ctx.send("I'm gnot a gnelf, I'm gnot a gnoblin, I'm a gnome, and you've been GNOMED!".format(myresult[0][0]), hidden=True)
    else:
        await ctx.send(f"Nice! {myresult[0][0]} cold ones have been opened!", hidden=True)
    if not ctx.author.voice:
        return
    channel = ctx.author.voice.channel
    if not channel:
        return
    await channel.connect()
    # Generate a number between 1 and 1000
    audiochance = randint(1, 1000)
    # figure out what track this corrisponds to
    index = bisect_right(tracks, (audiochance, ''))
    source = FFmpegPCMAudio(tracks[index][1])
    ctx.voice_client.play(source)
    while ctx.voice_client.is_playing():
        await asyncio.sleep(1)
    await ctx.voice_client.disconnect()