def get_page(pg, _): s = 'Leaderboards for **{}**\n\n```md\n'.format(guild.name) index = pg * 10 page = sorted_users[index - 10:index] max_s = max(map(lambda u: len(str(u)), page)) if not page: return 'Page out of range' for idx, u in enumerate(page): t = datetime.utcnow() - key(u) t = format_timedelta(t, DateAccuracy.Day) join_date = key(u).strftime('%a, %d %b %Y %H:%M:%S GMT') # We try to align everything but due to non monospace fonts # it will never be perfect tabs, spaces = divmod(max_s - len(str(u)), 4) padding = '\t' * tabs + ' ' * spaces s += f'{idx+index-9}. {u} {padding}{dtype} {t} ago at {join_date}\n' s += own_rank s += '```' return s
async def _date_sort(self, ctx, page, key, dtype='joined'): if page > 0: page -= 1 guild = ctx.guild sorted_users = list(sorted(guild.members, key=key)) # Indexes of all of the pages pages = list(range(1, ceil(len(guild.members) / 10) + 1)) own_rank = '' try: idx = sorted_users.index(ctx.author) + 1 t = datetime.utcnow() - key(ctx.author) t = format_timedelta(t, DateAccuracy.Day) own_rank = f'\nYour rank is {idx}. You {dtype} {t} ago at {key(ctx.author).strftime("%a, %d %b %Y %H:%M:%S GMT")}\n' except: pass def get_page(pg, _): s = 'Leaderboards for **{}**\n\n```md\n'.format(guild.name) index = pg * 10 page = sorted_users[index - 10:index] max_s = max(map(lambda u: len(str(u)), page)) if not page: return 'Page out of range' for idx, u in enumerate(page): t = datetime.utcnow() - key(u) t = format_timedelta(t, DateAccuracy.Day) join_date = key(u).strftime('%a, %d %b %Y %H:%M:%S GMT') # We try to align everything but due to non monospace fonts # it will never be perfect tabs, spaces = divmod(max_s - len(str(u)), 4) padding = '\t' * tabs + ' ' * spaces s += f'{idx+index-9}. {u} {padding}{dtype} {t} ago at {join_date}\n' s += own_rank s += '```' return s await send_paged_message(ctx, pages, starting_idx=page, page_method=get_page)
def test_format_timedelta(date, res): assert utilities.format_timedelta(date) == res # noqa: S101 # nosec
async def last_seen(self, ctx, *, user: AnyUser): """Get when a user was last seen on this server and elsewhere User can be a mention, user id, or full discord username with discrim Username#0001""" if isinstance(user, discord.User): user_id = user.id username = str(user) elif isinstance(user, int): user_id = user username = None else: user_id = None username = user if user_id: user_clause = 'user=:user' else: user_clause = 'username=:user' guild = ctx.guild if guild is not None: guild = guild.id sql = 'SELECT seen.* FROM `last_seen_users` seen WHERE guild=:guild AND {0} ' \ 'UNION ALL (SELECT seen2.* FROM `last_seen_users` seen2 WHERE guild!=:guild AND {0} ORDER BY seen2.last_seen DESC LIMIT 1)'.format(user_clause) else: guild = 0 sql = 'SELECT * FROM `last_seen_users` WHERE guild=0 AND %s' % user_clause try: rows = (await self.bot.dbutil.execute(sql, { 'guild': guild, 'user': user_id or username })).fetchall() except SQLAlchemyError: terminal.exception('Failed to get last seen from db') return await ctx.send('Failed to get user because of an error') if len(rows) == 0: return await ctx.send( "No users found with {}. Either the bot hasn't had the chance to log activity or the name was wrong." "Names are case sensitive and must include the discrim".format( username)) local = None global_ = None for row in rows: if not guild or row['guild'] != guild: global_ = row else: local = row if user_id is None: if local: user_id = local['user'] else: user_id = global_['user'] if username is None: username = local['username'] msg = 'User {} `{}`\n'.format(username, user_id) if local: time = local['last_seen'] fmt = format_timedelta(datetime.utcnow() - time, accuracy=2) msg += 'Last seen on this server `{} UTC` {} ago\n'.format( time, fmt) if global_: time = global_['last_seen'] fmt = format_timedelta(datetime.utcnow() - time, accuracy=2) msg += 'Last seen elsewhere `{} UTC` {} ago'.format(time, fmt) await ctx.send(msg)