def get(self, request, form=None): number = int(request.GET.get('page', 1)) if not hasattr(self, 'paginated'): queryset = self.model.objects.all() self.paginated = Paginator(queryset, self.paginate_by) context = { 'form': form or self.form_class(), 'page_obj': self.paginated.page(number), } return render(request, self.template_name, context)
async def blacklist(self, ctx: Context): """ Show blacklisted users on the bot. """ blacklist_ids = list(ctx.cache.blacklist.keys()) source = BlacklistedPageSource(ctx, blacklist_ids) pages = Paginator(source, ctx=ctx, delete_message_after=True) await pages.start()
def api_get_users(): page = ctx.request.query_string.get('page') count = ctx.request.query_string.get('count') if page: users = session.query(User).all() p = Paginator(page=int(page), object_=users, count=int(count or 10)) return dict(users=translate_time([user.as_dict() for user in p.object_list]), pagenums=p.pagenums) return dict()
async def python(self, ctx: Context, query): """ Get the docs for the latest Python version """ q = await self.scraper.search(query, page="https://docs.python.org/3/") menu = Paginator(RTFMPageSource(ctx, q[:79], "Python"), ctx=ctx, remove_view_after=True) await menu.start()
async def allcommands(self, ctx: Context): """ A list of all commands. """ menu = Paginator( AllCommandsPageSource(list(self.bot.commands), ctx), ctx=ctx, remove_view_after=True, ) await menu.start()
async def wavelink(self, ctx: Context, query): """ Get the docs for the Wavelink library """ q = await self.scraper.search( query, page="https://wavelink.readthedocs.io/en/latest/") menu = Paginator(RTFMPageSource(ctx, q[:79], "Wavelink"), ctx=ctx, remove_view_after=True) await menu.start()
async def obsidian(self, ctx: Context, query): """ Get the docs for the Obsidian.py library """ q = await self.scraper.search( query, page="https://obsidianpy.readthedocs.io/en/latest/") menu = Paginator(RTFMPageSource(ctx, q[:79], "Obsidian"), ctx=ctx, remove_view_after=True) await menu.start()
async def rtfm(self, ctx: Context, query): """ Get the docs for the discord.py library. """ q = await self.scraper.search( query, page="https://discordpy.readthedocs.io/en/stable/") menu = Paginator(RTFMPageSource(ctx, q[:79], "Discord.py"), ctx=ctx, remove_view_after=True) await menu.start()
async def custom(self, ctx: Context, doc_url, query): """ Search any Sphinx docs. """ try: q = await self.scraper.search(query, page=doc_url) except Exception as e: return await ctx.send(e) menu = Paginator(RTFMPageSource(ctx, q[:79], "Custom Docs"), ctx=ctx, remove_view_after=True) await menu.start()
class GalleryView(FormView): model = Image paginate_by = 5 template_name = 'gallery/homepage.html' form_class = CommentForm success_url = '/' def get(self, request, form=None): number = int(request.GET.get('page', 1)) if not hasattr(self, 'paginated'): queryset = self.model.objects.all() self.paginated = Paginator(queryset, self.paginate_by) context = { 'form': form or self.form_class(), 'page_obj': self.paginated.page(number), } return render(request, self.template_name, context) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): return self.form_valid(form) return self.get(request, form) def form_valid(self, form): image = form.cleaned_data.get('image') user = self.request.user button = self.request.POST.get('button') if button == 'like': _, created = Like.objects.get_or_create(image=image, user=user) if not created: try: Like.objects.get(image=image, user=user).delete() except ObjectDoesNotExist: pass elif button == 'comment' and form.cleaned_data['comment']: saved = form.save(commit=False) saved.user = user saved.save() if get_attribute(image, 'user.email') and image.user != user\ and get_attribute(image, 'user.member.notify'): EmailMessage( subject='New picture comment', body=render_to_string( 'gallery/notify.html', { 'image': image, 'from_user': user, 'domain': get_current_site(self.request).domain, }), to=[image.user.email]).send() self.success_url += f'/#{image.id}' return super().form_valid(form)
async def gist_read(self, ctx, *, gist_id: str): try: gist = await self.bot.gist.fetch_gist(gist_id) except asyncgist.NotFound: return await ctx.send("Gist was not found.") from core.context import AutoPageSource pag = commands.Paginator() for i in gist.files[0].content.split("\n"): pag.add_line(i.replace("`", "\u200b`")) source = AutoPageSource(pag) pages = Paginator(source, ctx=ctx, delete_message_after=True) await pages.start()
async def fixed(self, ctx: Context): """ Shows all fixed errors. """ errors = await self.bot.pool.fetch("SELECT * FROM command_errors WHERE fixed = True") if not errors: embed = discord.Embed(title="Errors", description="No fixed errors have been found.") return await ctx.send(embed=embed) menu = Paginator( ErrorSource(ctx, errors, title="Fixed errors", per_page=4), ctx=ctx, delete_message_after=True, ) return await menu.start()
async def view_speaking(self, ctx: commands.Context) -> None: """ View the channels Parrot can imitate people in. """ embed = ParrotEmbed(title="Parrot is learning from these channels:") channel_mentions = [] for channel in ctx.guild.channels: if channel.id in self.bot.speaking_channels: channel_mentions.append(channel.mention) paginator = Paginator.FromList( ctx, entries=channel_mentions, template_embed=embed, ) await paginator.run()
async def voices(self, ctx: commands.Context) -> None: """ List the speakers that Parrot can imitate through vo.codes. """ embed = ParrotEmbed(title="Speakers", ) embed.set_footer(text="Powered by vo.codes: https://vo.codes/") paginator = Paginator.FromList( ctx, entries=speaker_names, template_embed=embed, ) paginator.add_reaction("⏪", "back") paginator.add_reaction("⏹", "delete") paginator.add_reaction("⏩", "next") await paginator.run()
async def show_entries(self, ctx, params): entries = await self.get_entries(ctx, 'search', params) search_type = params['type'] if not entries: return await ctx.send(f'No {search_type}s found.') base = globals().get(f'{search_type.upper()}_BASE') links = [base + entry['id'][f'{search_type}Id'] for entry in entries] try: paginator = Paginator(ctx, entries=links) await paginator.paginate() except Exception as e: await ctx.send(e)
def search(): query = request.args.get("q") if query is None: return render_template("index.html") try: page = int(request.args.get("p", 1)) except (TypeError, ValueError): page = 1 searcher = Searcher() results = searcher.search_page(query, page) paginator = Paginator(results) return render_template("index.html", results=results, paginator=paginator, q=query)
def getblog(): page = ctx.request.query_string.get('page') # 此处修改了框架的query_string:返回{'a'='1','b'='balbal'} count = ctx.request.query_string.get('count') cat = ctx.request.query_string.get('cat') if page: if cat == 'all' or cat is None: blogs = session.query(Blog).order_by(Blog.created_at.desc()).all() else: blogs = session.query(Blog).filter(Blog.category == cat).order_by(Blog.created_at.desc()).all() p = Paginator(int(page), blogs, count=int(count or 6)) categories = session.query(Category).all() catobject = session.query(Category).filter(Category.id == cat).first() return dict(blogs=translate_time([blog.as_dict() for blog in p.object_list]), hasnext=p.hasnext, hasprevious=p.hasprevious, pagenums=p.pagenums, currentcat=catobject.id if catobject else None, categories=[cat.as_dict() for cat in categories]) return dict()
async def queue(self, ctx: Context): """Display the players queued songs.""" player: Player = ctx.voice_client if not player: return if player.queue.size == 0: return await ctx.send( f"The queue is empty. Use {ctx.prefix}play to add some songs!") entries = [] for index, track in enumerate(player.queue._queue): if isinstance(track, wavelink.PartialTrack): entries.append(f"`{index + 1})` {track.title}") else: entries.append(f"`{index + 1})` [{track.title}]({track.url})") pages = PaginatorSource(entries=entries, ctx=ctx) paginator = Paginator(source=pages, timeout=120, ctx=ctx, disable_view_after=True) await paginator.start()
from utils import Paginator data = list('/+0w3GdIlsXrT5BmzETBZMtYaWXJUJ91QTI1U4P/dXnRn4dHLvM70twjfh4i7NF7YJM6XWcS7Mxfww/Zkh9HOohBCtOz/HBlPpvu5yhYH7yfirlNQOl+') page = Paginator(data, 5) print(page.num_pages) p = page.page(0) print(list(p.num_range), p.object_list, page.num_pages)
async def guilds(self, ctx: Context): source = GuildPageSource(ctx, guilds=self.bot.guilds) pages = Paginator(source, ctx=ctx, disable_view_after=True) await pages.start()
async def quickstart(self, ctx: commands.Context, user: Userlike = None) -> None: """ Scan your past messages to get started using Parrot right away. """ if user is None or ctx.author == user: user = ctx.author else: if not is_admin(ctx): raise UserPermissionError( "You can only run Quickstart on yourself.") if not user.bot: raise UserPermissionError( "Quickstart can only be run on behalf of bots.") if ctx.channel.id not in self.ongoing_scans: self.ongoing_scans[ctx.channel.id] = [] # You can't run Quickstart in a channel that Quickstart is already # currently scanning for you. if user.id in self.ongoing_scans[ctx.channel.id]: if ctx.author == user: raise AlreadyScanning( "❌ You are already currently running Quickstart in this channel!" ) raise AlreadyScanning( f"❌ Quickstart is already running for {user} in this channel!") # Record that Quickstart is scanning this channel for this user. self.ongoing_scans[ctx.channel.id].append(user.id) # Tell the user off if they try to run this command in a DM channel. if ctx.channel.type != ChannelType.text: await ctx.send( f"Quickstart is only available in servers. Try running Quickstart again in a server that Parrot is in." ) return # Show the user where they can use Quickstart within this server if they # use the command in a channel where Parrot can't learn. if ctx.channel.id not in self.bot.learning_channels: embed = ParrotEmbed( title="Quickstart Channels", description= "Quickstart is available in channels where Parrot can learn from your messages. Try running Quickstart again in one of these channels:", ) channel_mentions = [] for channel in ctx.guild.channels: if channel.id in self.bot.learning_channels: channel_mentions.append(channel.mention) paginator = Paginator.FromList( ctx, entries=channel_mentions, template_embed=embed, ) await paginator.run() return # Create and embed that will show the status of the Quickstart # operation and DM it to the user who invoked the command. if ctx.author == user: name = "your" else: name = f"{user.mention}'s" embed = ParrotEmbed( description= f"**Scanning {ctx.channel.mention}...**\nCollected 0 new messages...", ) embed.set_author( name="Quickstart", icon_url="https://i.gifer.com/ZZ5H.gif", # Loading spinner ) embed.set_footer( text=f"Scanning for {user.mention}", icon_url=user.avatar_url, ) status_message = await ctx.author.send(embed=embed) await ctx.send(embed=ParrotEmbed( title="Quickstart is scanning", description= f"Parrot is now scanning this channel and learning from {name} past messages.\nThis could take a few minutes.\nCheck your DMs to see its progress." ), reference=ctx.message) # Create an iterator representing this channel's past messages. def message_filter(message: Message) -> bool: return message.author == user history = ctx.channel.history( limit=100_000, after=user.joined_at, ).filter(message_filter) # Create an object that will scan through the channel's message history # and learn from the messages this user has posted. crawler = ChannelCrawler( history=history, action=self.bot.learn_from, ) # Start the crawler and periodically update the status_message with its # progress. # Fun fact: these HAVE to be asyncio.gathered together. If they aren't, # either the updater function won't be able to run until after the # crawler has stopped, or the command will hang forever as the updater # loops into eternity as it waits for the crawler (which isn't # running) to tell it to stop. await asyncio.gather( crawler.crawl(), self.live_update_status( source_channel=ctx.channel, status_message=status_message, user=user, crawler=crawler, ), loop=self.bot.loop, ) # Update the status embed one last time, but DELETE it this time and # post a brand new one so that the user gets a new notification. if ctx.author == user: name = "you" else: name = f"{user}" embed = ParrotEmbed( description= f"**Scan in {ctx.channel.mention} complete.**\nCollected {crawler.num_collected} new messages.", ) embed.set_author(name="✅ Quickstart") embed.set_footer( text=f"Scanning for {user}", icon_url=user.avatar_url, ) if crawler.num_collected == 0: embed.description += f"\n😕 Couldn't find any messages from {name} in this channel." embed.color = ParrotEmbed.colors["red"] await asyncio.gather(status_message.delete(), ctx.author.send(embed=embed)) self.ongoing_scans[ctx.channel.id].remove(user.id) if len(self.ongoing_scans[ctx.channel.id]) == 0: del self.ongoing_scans[ctx.channel.id]