示例#1
0
 async def playing(self, ctx):
     if Player.is_connected(ctx):
         curr = queue[ctx.guild.id]['playing'][0]
         # import math
         try:
             desc = curr['description']
             # length = math.sqrt((len(desc))) + 200
             # desc = desc[:int(length)]
             # desc = desc[:248]
             desc = desc[:148]
         except TypeError:
             desc = None
         # TODO: make it filter out newlines
         if desc is not None:
             embed = tls.Embed(ctx, title=curr['title'], url=curr['webpage_url'], description=f'{desc}...')
         else:
             embed = tls.Embed(ctx, title=curr['title'], url=curr['webpage_url'])
         try:
             embed.set_image(url=curr['thumbnail'])
         except KeyError:
             pass
         try:
             embed.set_author(name=curr['uploader'], url=curr['uploader_url'], icon_url=curr['pfp'])
         except KeyError:
             embed.set_author(name=curr['uploader'], icon_url=curr['pfp'])
         if curr['pfp'] != discord.Embed.Empty:
             embed.set_thumbnail(url=curr['pfp'])
         # log.debug(curr['pfp'])
         await ctx.send(embed=embed)
示例#2
0
    async def queue(self, ctx):
        if ctx.invoked_subcommand is None:
            try:
                if queue[ctx.guild.id]['playing']:  # If object exists in here, we show the queue
                    embed = tls.Embed(ctx, description=f"Currently {(len(queue[ctx.guild.id]['q']) + 1)} items in queue")
                    curr = queue[ctx.guild.id]['playing'][0]
                    try:
                        embed.add_field(name=f"**>**[**1**] {curr['title']}", value=f"**Artist:** {curr['author']}", inline=False)
                    except Exception:
                        embed.add_field(name=f"**>**[**1**] {curr['title']}", value=f"**Added by:** {curr['discord_mention']}", inline=False)
                    pos = 2
                    for song in queue[ctx.guild.id]['q']:
                        if pos <= 10:
                            try:
                                embed.add_field(name=f"[**{pos}**] {song['title']}", value=f"**Artist:** {song['author']}", inline=False)
                            except Exception:
                                embed.add_field(name=f"[**{pos}**] {song['title']}", value=f"**Added by:** {song['discord_mention']}", inline=False)
                        pos += 1
                    if pos > 10:
                        dif = (len(queue[ctx.guild.id]['q']) + 1) - 10
                        embed.set_footer(text=f'Plus {dif} other tracks.', icon_url=self.bot.user.avatar_url)
                    await ctx.send(embed=embed)
                else:
                    await ctx.send('The queue is currently empty.')

            except Exception as err:
                random.seed(traceback.format_exc())
                number = random.randint(10000, 99999)
                await ctx.send(f'Oops! Something went wrong! `(#{number})`')
                log.exception(f'Code #{number}', exc_info=err)
示例#3
0
 async def number_generator(self, ctx, number='1-100', *, seed=None):
     """Pseudorandom number generator.
     `.number [range] [seed]`
     Examples:
     : .number 1-100
     : .number 1-100 Test
     """
     channel = ['r', 'radio', 'radiochannel', 'setradiochannel']
     phone = ['n', 'number', 'phonenumber', 'phone']
     if number in channel:
         number = '0-256'
     if number in phone:
         number = '1000000-9999999'
     n = number.split('-')
     if seed is not None:
         random.seed(seed)
     number = random.randint(int(n[0]), int(n[1]))
     embed = tls.Embed(
         description=f'Pseudorandom number in range from {n[0]} to {n[1]}',
         timestamp=True)
     # embed = tls.Embed(timestamp=False)
     if seed is None:
         seed = 'Random'
     embed.set_footer(text=f'{number} | {seed}')
     await ctx.send(embed=embed)
示例#4
0
 async def roll_dice(self, ctx, dice='1d6', extra=None):
     """Roll a dice!
     `.roll [type]`
     Type:
     [number of dice to roll] d [number of sides the dice has]
     """
     if dice != '1d2':
         d = dice.split('d')
         rolls = []
         total = 0
         # Hard limits
         if int(d[0]) >= 1000000:
             d[0] = '1000000'
         if int(d[1]) >= 1000000000000:
             d[1] = '1000000000000'
         dice = f'{d[0]}d{d[1]}'
         for x in range(int(d[0])):
             roll = random.randint(1, int(d[1]))
             rolls.append(roll)
             total += roll
             # print(roll)
             # dbg(roll)
         r_rolls = rolls
         rolls = str(rolls)[1:-1]
         embed = tls.Embed(ctx, description=f'You rolled a {total}!')
         text = f'{dice} die | Rolled {rolls}'[:2039]
         if len(text) >= 2039 and len(r_rolls) > 1:
             text = f'{text}, more...'
         # dbg(r_rolls)
         embed.set_footer(text=text)
         await ctx.send(embed=embed)
     else:
         await tls.Command.execute(self, ctx, 'coin')
示例#5
0
 async def remove(self, ctx, loc: int):
     if Player.is_connected(ctx):
         embed = tls.Embed(ctx, description=f"Removed {queue[ctx.guild.id]['q'][loc - 2]['title']} from the queue.")
         try:
             del queue[ctx.guild.id]['q'][loc - 2]
             await ctx.send(embed=embed)
         except IndexError:
             await ctx.send(f'Nothing at index location {loc} exists!')
示例#6
0
 async def name_generator(self, ctx, sex=None, *, seed=None):
     """Name generator.
     `.name [sex] [seed]`
     Sexes:
     : Male - 1, M
     : Female - 2, F
     : Other - 3, Default"""
     if sex is None:
         if seed is not None:
             random.seed(seed)
         sex = random.randint(1, 3)
     sex = tls.Enums(general.Sex).find(sex)
     if sex.value == 1:  # First Names
         fr = names.NameURLs.male
     elif sex.value == 2:
         fr = names.NameURLs.female
     else:
         fr = names.NameURLs.first
     mr = names.NameURLs.middle
     lr = names.NameURLs.last
     f = requests.get(fr.value).json()['data']  # First
     m = requests.get(mr.value).json()['RandL']['items']  # Middle
     la = requests.get(lr.value).json()['data']  # Last
     lt = la
     if seed is not None:
         random.seed(seed)
     f = random.choice(f)
     if seed is not None:  # So middle name is not always the same between sexes
         if sex.value == 2:  # Female gets default, others get extra seeding.
             random.seed(seed)
         else:
             random.seed(f'{sex.value}{seed}')
             # random.seed(f'{seed}{seed}')
     m = random.choice(m)
     if seed is not None:
         random.seed(seed)
     la = random.choice(la)
     if seed is not None:
         random.seed(seed)
     lx = random.randint(1, 6)
     if lx == 2 or lx == 6:
         if seed is not None:
             random.seed(f'{seed}-{seed}')
         lx = random.choice(lt)
         if seed is not None:
             random.seed(seed)
         r = random.randint(1, 2)
         if r == 1:
             la = f'{la}-{lx}'
         else:
             la = f'{lx}-{la}'
     embed = tls.Embed(description=f'{f} {m} {la}', timestamp=True)
     if seed is None:
         seed = 'Random'
     embed.set_footer(text=f'{sex.value} | {seed}')
     await ctx.send(embed=embed)
示例#7
0
 async def flip_coin(self, ctx):
     flip = random.randint(1, 2)
     embed = tls.Embed(ctx,
                       description=f'You flipped a coin!',
                       timestamp=True)
     if flip == 1:
         embed.set_thumbnail(url=assets.Images.Coins.Quarter.heads)
         embed.set_footer(text='It landed on Heads!')
     else:
         embed.set_thumbnail(url=assets.Images.Coins.Quarter.tails)
         embed.set_footer(text='It landed on Tails!')
     await ctx.send(embed=embed)
示例#8
0
 async def game(self, ctx, _type: int, *, _game):
     parse = _game.split(' -s ', 1)
     if len(parse) > 1:
         activity = discord.Streaming(name=parse[0], url=parse[1])
     else:
         activity = discord.Activity(type=_type, name=_game, flags=None)
         jack = json.json.orm['activity']
         jack[str(self.bot.user.id)] = activity.to_dict()
         json.json.orm['activity'] = jack
         # json.json.orm['activity'][self.bot.user.id] = activity.to_dict()
     await self.bot.change_presence(activity=activity)
     activity = activity.to_dict()
     if activity['type'] == 1:
         embed = tls.Embed(title=assets.Game.type[activity['type']],
                           description=activity['name'],
                           url=activity['url'],
                           timestamp=datetime.datetime.utcnow())
     else:
         embed = tls.Embed(title=assets.Game.type[activity['type']],
                           description=activity['name'],
                           timestamp=datetime.datetime.utcnow())
     embed.set_footer(icon_url=self.bot.user.avatar_url,
                      text=f'Updated game.')
     await ctx.send(embed=embed)
示例#9
0
    async def play(self, ctx, url=None):
        if await Player.can_connect(ctx, False):
            await Player.join(ctx.message.author)
        if Player.is_connected(ctx):
            try:
                if url is not None:
                    async with ctx.typing():
                        info, data = await Player.info(url, loop=self.bot.loop, ctx=ctx)
                        # log.debug(info)
                        if info is not None:
                            if len(info) > 1:
                                playlist = data['title']
                            else:
                                playlist = None
                            embed = tls.Embed(ctx)
                            for item in info:  # Append tracks to queue. Eventually it'll just be pfp and data.
                                try:
                                    item.update({'discord_mention': ctx.author.mention})
                                    extractor = Player.Extractor.fetch(data)
                                    queue[ctx.guild.id]['q'].append(item)
                                    # log.debug(item)
                                except KeyError as err:
                                    log.error(err)
                                    # break
                            if playlist is None:
                                item = await Player.process_picture(item, extractor[0])
                                try:
                                    # log.debug(queue[ctx.guild.id]['q'][-1]['extractor'])
                                    embed.set_author(name=item['uploader'], url=item['uploader_url'], icon_url=queue[ctx.guild.id]['q'][-1]['pfp'])
                                except KeyError as err:
                                    embed.set_author(name=item['uploader'], icon_url=queue[ctx.guild.id]['q'][-1]['pfp'])
                                embed.add_field(name=f"{item['title']}", value=f"has been added to the queue.", inline=False)
                            else:
                                embed.add_field(name=f"{len(info)} tracks added from", value=f" playlist **{playlist}**", inline=False)
                            await ctx.send(embed=embed)

                else:  # If no URL specified, try to resume
                    Player.resume(ctx)

                await Player.loop(self, ctx)

            except Exception as err:
                random.seed(traceback.format_exc())
                number = random.randint(10000, 99999)
                await ctx.send(f'Oops! Something went wrong! `(#{number})`')
                log.exception(f'Code #{number}', exc_info=err)
示例#10
0
 async def loop(cls, self, ctx):
     if not Player.is_playing(ctx) and not Player.is_paused(ctx) and len(queue[ctx.guild.id]['q']) > 0:
         while Player.has_queue(ctx):
             if not Player.is_playing(ctx) and not Player.is_paused(ctx):
                 try:
                     try:
                         url = queue[ctx.guild.id]['q'][0]['webpage_url']
                     except Exception:
                         url = queue[ctx.guild.id]['q'][0]['id']
                     stream = await YTDLSource.create_source(url=url, loop=self.bot.loop)
                     Player.play(ctx, stream)
                     new = queue[ctx.guild.id]['q'].pop(0)
                     if 'ie_key' in new:  # if Playlist object
                         if new['ie_key'].lower() == 'youtube':
                             added_by = new['discord_mention']
                             data_trunk, new = await Player.info(new['id'], loop=self.bot.loop, ctx=ctx)
                             # new = new[0]  # Format into usable form
                             new.update({'discord_mention': added_by})
                     extractor = Player.Extractor.fetch(new)
                     new = await Player.process_picture(new, extractor[0])
                     # log.debug(new)
                     queue[ctx.guild.id]['playing'].insert(0, new)
                     queue[ctx.guild.id]['player'] = stream
                     embed = tls.Embed(ctx, title=new['title'], url=new['webpage_url'], description='is now playing.')
                     # log.debug(new['pfp'])
                     try:
                         embed.set_author(name=new['uploader'], url=new['uploader_url'], icon_url=new['pfp'])
                     except KeyError as err:
                         embed.set_author(name=new['uploader'], icon_url=new['pfp'])
                     # embed.set_image(url=new['thumbnail'])
                     try:
                         await ctx.send(embed=embed)
                     except Exception as e:
                         log.warn(f'> {e}')
                 except Exception as err:
                     log.debug(f'> {err}')
                     pass
             await asyncio.sleep(4)