示例#1
0
    async def now_playing(self, ctx):
        _("""Displays some information about the currently playing song.""")
        current_song = self.queue[ctx.guild.id][0]

        if not (ctx.guild and ctx.author.color == discord.Color.default()):
            embed_color = ctx.author.color
        else:
            embed_color = self.bot.config.primary_colour

        playing_embed = discord.Embed(title=_("Now playing..."),
                                      colour=embed_color)
        playing_embed.add_field(name=_("Title"),
                                value=f"```{current_song.title}```",
                                inline=False)
        playing_embed.add_field(
            name=_("Artist"),
            value=nice_join([a.name for a in current_song.track_obj.artists]),
        )
        text = _("Click me!")
        if current_song.uri:
            playing_embed.add_field(
                name=_("Link to the original"),
                value=f"**[{text}]({current_song.track_obj.url})**",
            )
        if current_song.track_obj.album.images:
            best_image = sorted(current_song.track_obj.album.images,
                                key=lambda x: -x["width"])[0]
            playing_embed.set_thumbnail(url=best_image["url"])
        playing_embed.add_field(name=_("Volume"),
                                value=f"{ctx.player.volume} %")
        if ctx.player.paused:
            playing_embed.add_field(name=_("Playing status"),
                                    value=_("`⏸Paused`"))
        playing_embed.add_field(name=_("DJ"), value=ctx.player.dj.mention)
        playing_embed.add_field(
            name=_("Locked"), value=_("Yes") if ctx.player.locked else _("No"))
        playing_embed.add_field(name=_("Looping"),
                                value=_("Yes") if ctx.player.loop else _("No"))
        playing_embed.add_field(
            name=_("Explicit"),
            value=_("Yes") if current_song.track_obj.explicit else _("No"),
        )
        playing_embed.add_field(name=_("Equalizer"), value=ctx.player.eq)
        button_position = int(
            100 * (ctx.player.position / current_song.length) / 2.5)
        controller = (
            "```ɴᴏᴡ ᴘʟᴀʏɪɴɢ:"
            f" {current_song.title}\n{(button_position - 1) * '─'}⚪{(40 - button_position) * '─'}\n"
            f" ◄◄⠀{'▐▐' if not ctx.player.paused else '▶'} ⠀►►⠀⠀  ⠀"
            f" {str(timedelta(milliseconds=ctx.player.position)).split('.')[0]} /"
            f" {timedelta(seconds=int(current_song.length / 1000))}```")
        playing_embed.description = controller
        playing_embed.set_footer(
            text=_("Song requested by: {user}").format(
                user=current_song.requester.display_name),
            icon_url=current_song.requester.avatar_url_as(format="png",
                                                          size=64),
        )
        await ctx.send(embed=playing_embed)
示例#2
0
    async def stats(self, ctx):
        _("""Show some stats about the bot, ranging from hard- and software statistics, over performance to ingame stats."""
          )
        async with self.bot.pool.acquire() as conn:
            characters = await conn.fetchval("SELECT COUNT(*) FROM profile;")
            items = await conn.fetchval("SELECT COUNT(*) FROM allitems;")
            pg_version = conn.get_server_version()
        temps = psutil.sensors_temperatures()
        temps = temps[list(temps.keys())[0]]
        cpu_temp = statistics.mean(x.current for x in temps)
        pg_version = f"{pg_version.major}.{pg_version.micro} {pg_version.releaselevel}"
        d0 = self.bot.user.created_at
        d1 = datetime.datetime.now(datetime.timezone.utc)
        delta = d1 - d0
        myhours = delta.days * 1.5
        sysinfo = distro.linux_distribution()
        if self.bot.owner_ids:
            owner = nice_join([
                str(await self.bot.get_user_global(u))
                for u in self.bot.owner_ids
            ])
        else:
            owner = str(await self.bot.get_user_global(self.bot.owner_id))
        guild_count = sum(await self.bot.cogs["Sharding"].handler(
            "guild_count", self.bot.cluster_count))
        meminfo = psutil.virtual_memory()
        cpu_freq = psutil.cpu_freq()
        cpu_name = await get_cpu_name()
        compiler = re.search(r".*\[(.*)\]", sys.version)[1]

        embed = discord.Embed(
            title=_("IdleRPG Statistics"),
            colour=0xB8BBFF,
            url=self.bot.BASE_URL,
            description=_(
                "Official Support Server Invite: https://support.idlerpg.xyz"),
        )
        embed.set_thumbnail(url=self.bot.user.display_avatar.url)
        embed.set_footer(
            text=f"IdleRPG {self.bot.version} | By {owner}",
            icon_url=self.bot.user.display_avatar.url,
        )
        embed.add_field(
            name=_("Hosting Statistics"),
            value=_("""\
CPU: **{cpu_name}**
CPU Usage: **{cpu}%**, **{cores}** cores/**{threads}** threads @ **{freq}** GHz
RAM Usage: **{ram}%** (Total: **{total_ram}**)
CPU Temperature: **{cpu_temp}°C**
Python Version **{python}** <:python:445247273065250817>
discord.py Version **{dpy}**
Compiler: **{compiler}**
Operating System: **{osname} {osversion}**
Kernel Version: **{kernel}**
PostgreSQL Version: **{pg_version}**
Redis Version: **{redis_version}**""").format(
                cpu_name=cpu_name,
                cpu=psutil.cpu_percent(),
                cores=psutil.cpu_count(logical=False),
                threads=psutil.cpu_count(),
                cpu_temp=round(cpu_temp, 2),
                freq=cpu_freq.max /
                1000 if cpu_freq.max else round(cpu_freq.current / 1000, 2),
                ram=meminfo.percent,
                total_ram=humanize.naturalsize(meminfo.total),
                python=platform.python_version(),
                dpy=pkg.get_distribution("enhanced-discord.py").version,
                compiler=compiler,
                osname=sysinfo[0].title(),
                osversion=sysinfo[1],
                kernel=os.uname().release if os.name == "posix" else "NT",
                pg_version=pg_version,
                redis_version=self.bot.redis_version,
            ),
            inline=False,
        )
        embed.add_field(
            name=_("Bot Statistics"),
            value=_("""\
Code lines written: **{lines}**
Shards: **{shards}**
Servers: **{guild_count}**
Characters: **{characters}**
Items: **{items}**
Average hours of work: **{hours}**""").format(
                lines=self.bot.linecount,
                shards=self.bot.shard_count,
                guild_count=guild_count,
                characters=characters,
                items=items,
                hours=myhours,
            ),
            inline=False,
        )
        await ctx.send(embed=embed)
示例#3
0
 async def get_inputs(self):
     all_actions = [
         (
             _("Gather as much food as you can"),
             _("gathers as much food as they can"),
             None,
         ),
         (
             _("Grab a backpack and retreat"),
             _("grabs a backpack and retreats"),
             "leave",
         ),
         (_("Take a pistol and suicide"), _("gives themselves the bullet"),
          "leave"),
         (_("Ram a knife in your body"), _("commits suicide with a knife"),
          "leave"),
         (
             _("Run away from the Cornucopia"),
             _("runs away from the Cornucopia"),
             None,
         ),
         (
             _("Search for a pair of Explosives"),
             _("finds a bag full of explosives"),
             None,
         ),
         (_("Look for water"), _("finds a canteen full of water"), None),
         (
             _("Get a first aid kit"),
             _("clutches a first aid kit and runs away"),
             None,
         ),
         (
             _("Grab a backpack"),
             _("grabs a backpack, not realizing it is empty"),
             None,
         ),
         (_("Try to assault USER"), _("kills USER"), ("kill", "USER")),
         (
             _("Kill USER at the water"),
             _("assaults USER while they were drinking water at the river"),
             ("kill", "USER"),
         ),
         (
             _("Try to hide some landmines"),
             _("hides landmines at a few locations"),
             None,
         ),
         (_("Take a bath"), _("baths in the water and enjoys the silence"),
          None),
     ]
     team_actions = [
         (_("kill USER"), ("kill", "USER")),
         (_("grill at the fireplace and tell each other spooky stories"),
          None),
         (_("annoy USER"), "user"),
         (_("kill themselves by walking into a landmine"), "killall"),
         (_("have a small party and get drunk"), None),
         (_("watch animes together"), None),
         (_("enjoy the silence"), None),
         (_("attempt to kill USER but fail"), "user"),
         (_("watch a movie together"), "user"),
         (_("track down USER and kill them silently"), ("kill", "USER")),
     ]
     team_actions_2 = [
         (_("kill themselves by walking into a landmine"), "killall"),
         (_("decide they want out of here and commit suicide"), "killall"),
         (_("watch a movie together"), None),
         (_("dance YMCA together"), None),
         (_("sing songs together"), None),
         (_("have a nice romantic evening"), None),
         (_("watch the others being dumb"), None),
         (_("kiss in the moonlight"), None),
         (
             _("watch a movie together when USER suddenly gets shot by a stranger"
               ),
             ("killtogether", "USER"),
         ),
     ]
     user_actions = []
     roundtext = _("**Round {round}**")
     status = await self.ctx.send(roundtext.format(round=self.round),
                                  delete_after=60)
     killed_this_round = []
     for p in self.rand_chunks(self.players):
         if len(p) == 1:
             text = _("Letting {user} choose their action...").format(
                 user=p[0])
             try:
                 await status.edit(content=f"{status.content}\n{text}")
             except discord.errors.NotFound:
                 status = await self.ctx.send(
                     f"{roundtext.format(round=self.round)}\n{text}",
                     delete_after=60)
             actions = random.sample(all_actions, 3)
             possible_kills = [
                 item for item in self.players
                 if item not in killed_this_round and item != p[0]
             ]
             if len(possible_kills) > 0:
                 kill = random.choice(possible_kills)
                 okay = True
             else:
                 kill = random.choice(
                     [i for i in self.players if i != p[0]])
                 okay = False
             actions2 = []
             for a, b, c in actions:
                 if c == ("kill", "USER"):
                     actions2.append((
                         a.replace("USER", kill.name),
                         b.replace("USER", kill.name),
                         ("kill", kill),
                     ))
                 else:
                     actions2.append((a, b, c))
             actions_desc = [a[0] for a in actions2]
             try:
                 action = actions2[await self.ctx.bot.paginator.Choose(
                     entries=actions_desc,
                     return_index=True,
                     title=_("Choose an action"),
                 ).paginate(self.ctx, location=p[0])]
             except (
                     self.ctx.bot.paginator.NoChoice,
                     discord.Forbidden,
                     asyncio.TimeoutError,
             ):
                 await self.ctx.send(
                     _("I couldn't send a DM to {user}! Choosing random action..."
                       ).format(user=p[0]),
                     delete_after=30,
                 )
                 action = random.choice(actions2)
             if okay or (not okay and isinstance(action[2], tuple)):
                 user_actions.append((p[0], action[1]))
             else:
                 user_actions.append(
                     (p[0], _("attempts to kill {user} but fails").format(
                         user=kill)))
             if action[2]:
                 if action[2] == "leave":
                     killed_this_round.append(p[0])
                 else:
                     if okay:
                         killed_this_round.append(action[2][1])
             text = _("Done")
             try:
                 await status.edit(content=f"{status.content} {text}")
             except discord.errors.NotFound:
                 pass
         else:
             possible_kills = [
                 item for item in p if p not in killed_this_round
             ]
             if len(possible_kills) > 0:
                 target = random.choice(possible_kills)
             else:
                 target = None
             if len(p) > 2:
                 action = random.choice(team_actions)
             else:
                 action = random.choice(team_actions_2)
             users = [u for u in p if u != target]
             if not action[1]:
                 user_actions.append(
                     (nice_join([u.name for u in p]), action[0]))
             elif not target:  # fix
                 user_actions.append(
                     (nice_join([u.name for u in p]), _("do nothing.")))
             elif action[1] == "user":
                 user_actions.append((
                     nice_join([u.name for u in users]),
                     action[0].replace("USER", target.name),
                 ))
             elif action[1] == "killall":
                 user_actions.append(
                     (nice_join([u.name for u in p]), action[0]))
                 killed_this_round.extend(p)
             else:
                 if action[1][0] == "kill":
                     user_actions.append((
                         nice_join([u.name for u in users]),
                         action[0].replace("USER", target.name),
                     ))
                 elif action[1][0] == "killtogether":
                     user_actions.append((
                         nice_join([u.name for u in p]),
                         action[0].replace("USER", target.name),
                     ))
                 killed_this_round.append(target)
     await asyncio.sleep(2)
     for p in killed_this_round:
         try:
             self.players.remove(p)
         except ValueError:
             pass
     paginator = commands.Paginator(prefix="", suffix="")
     for u, a in user_actions:
         paginator.add_line(f"{u} {a}")
     for page in paginator.pages:
         await self.ctx.send(page, delete_after=60)
     self.round += 1
示例#4
0
            ids,
            ctx.author.id,
        )
        if not reminders:
            return await ctx.send(
                _("None of these reminder IDs belong to you."))
        for reminder in reminders:
            fake_task = Task(0, reminder["internal_id"], 0)
            self.bot.schedule_manager.cancel(fake_task)
        await self.bot.pool.execute(
            'DELETE FROM reminders WHERE "id"=ANY($1);',
            ids := [reminder["id"] for reminder in reminders],
        )
        await ctx.send(
            _("Removed the following reminders: `{ids}`").format(
                ids=nice_join(ids)))

    @commands.command(brief=_("Shows a list of your running reminders."))
    @locale_doc
    async def reminders(self, ctx):
        _("""Shows you a list of your currently running reminders

            Reminders can be cancelled using `{prefix}reminder cancel <id>`.

            (serves as an alias for `{prefix}reminder list`)""")
        await ctx.invoke(self.bot.get_command("reminder list"))


def setup(bot):
    bot.add_cog(Scheduling(bot))