1
0
Fork 0
mirror of https://github.com/myned/modufur.git synced 2024-12-25 22:57:27 +00:00

Merge branch 'dev'

This commit is contained in:
Myned 2020-03-09 12:13:55 -04:00
commit 3169229d05
No known key found for this signature in database
GPG key ID: 2EF9C0C44229D034
4 changed files with 104 additions and 99 deletions

View file

@ -94,7 +94,7 @@ class MsG(cmds.Cog):
print(f'Last updated: {self.suggested["last_update"]}') print(f'Last updated: {self.suggested["last_update"]}')
print('Updating tags...') print('Updating tags...')
content = await u.fetch('https://e621.net/tag/index.json', params={'order': 'count', 'limit': 500, 'page': page}, json=True) content = await u.fetch(f'https://e621.net/tag/index.json?order=count&limit={500}&page={page}', json=True)
while content: while content:
for tag in content: for tag in content:
self.suggested['tags'][tag['name']] = tag['count'] self.suggested['tags'][tag['name']] = tag['count']
@ -102,7 +102,7 @@ class MsG(cmds.Cog):
print(f' UPDATED : PAGE {page} / {pages}', end='\r') print(f' UPDATED : PAGE {page} / {pages}', end='\r')
page += 1 page += 1
content = await u.fetch('https://e621.net/tag/index.json', params={'order': 'count', 'limit': 500, 'page': page}, json=True) content = await u.fetch(f'https://e621.net/tag/index.json?order=count&limit={500}&page={page}', json=True)
u.dump(self.suggested, 'cogs/suggested.pkl') u.dump(self.suggested, 'cogs/suggested.pkl')
self.suggested['last_update'] = time.strftime('%d/%m/%Y/%H:%M:%S') self.suggested['last_update'] = time.strftime('%d/%m/%Y/%H:%M:%S')
@ -232,7 +232,7 @@ class MsG(cmds.Cog):
await ctx.trigger_typing() await ctx.trigger_typing()
for tag in tags: for tag in tags:
tag_request = await u.fetch('https://e621.net/tag/related.json', params={'tags': tag}, json=True) tag_request = await u.fetch(f'https://e621.net/tag/related.json?tags={tag}', json=True)
for rel in tag_request.get(tag, []): for rel in tag_request.get(tag, []):
related.append(rel[0]) related.append(rel[0])
@ -258,7 +258,7 @@ class MsG(cmds.Cog):
await ctx.trigger_typing() await ctx.trigger_typing()
for tag in tags: for tag in tags:
alias_request = await u.fetch('https://e621.net/tag_alias/index.json', params={'aliased_to': tag, 'approved': 'true'}, json=True) alias_request = await u.fetch(f'https://e621.net/tag_alias/index.json?aliased_to={tag}&approved=true', json=True)
for dic in alias_request: for dic in alias_request:
aliases.append(dic['name']) aliases.append(dic['name'])
@ -293,15 +293,16 @@ class MsG(cmds.Cog):
ident = ident if not ident.isdigit() else re.search( ident = ident if not ident.isdigit() else re.search(
'show/([0-9]+)', ident).group(1) 'show/([0-9]+)', ident).group(1)
post = await u.fetch('https://e621.net/post/show.json', params={'id': ident}, json=True) post = await u.fetch(f'https://e621.net/posts/{ident}.json', json=True)
post = post['post']
embed = d.Embed( embed = d.Embed(
title=', '.join(post['artist']), url=f'https://e621.net/post/show/{post["id"]}', color=ctx.me.color if isinstance(ctx.channel, d.TextChannel) else u.color) title=', '.join(post['tags']['artist']), url=f'https://e621.net/posts/{post["id"]}', color=ctx.me.color if isinstance(ctx.channel, d.TextChannel) else u.color)
embed.set_thumbnail(url=post['file_url']) embed.set_thumbnail(url=post['sample']['url'])
embed.set_author(name=f'{post["width"]} x {post["height"]}', embed.set_author(name=f'{post["file"]["width"]} x {post["file"]["height"]}',
url=f'https://e621.net/post?tags=ratio:{post["width"]/post["height"]:.2f}', icon_url=ctx.author.avatar_url) url=f'https://e621.net/posts?tags=ratio:{post["file"]["width"]/post["file"]["height"]:.2f}', icon_url=ctx.author.avatar_url)
embed.set_footer(text=post['score'], embed.set_footer(text=post['score']['total'],
icon_url=self._get_icon(post['score'])) icon_url=self._get_icon(post['score']['total']))
except exc.MissingArgument: except exc.MissingArgument:
await ctx.send('\N{HEAVY EXCLAMATION MARK SYMBOL} **Invalid url**') await ctx.send('\N{HEAVY EXCLAMATION MARK SYMBOL} **Invalid url**')
@ -337,12 +338,12 @@ class MsG(cmds.Cog):
@get.command(name='pool', aliases=['p'], brief='(get) Get pool from query', description='Return pool info for given query\n\nExample:\n\{p\}get pool 1145042') @get.command(name='pool', aliases=['p'], brief='(get) Get pool from query', description='Return pool info for given query\n\nExample:\n\{p\}get pool 1145042')
async def _get_pool(self, ctx, *args): async def _get_pool(self, ctx, *args):
def on_reaction(reaction, user): def on_reaction(reaction, user):
if reaction.emoji == '\N{OCTAGONAL SIGN}' and reaction.message.id == ctx.message.id and user is ctx.author: if reaction.emoji == '\N{OCTAGONAL SIGN}' and reaction.message.id == ctx.message.id and user.id is ctx.author.id:
raise exc.Abort(match) raise exc.Abort(match)
return False return False
def on_message(msg): def on_message(msg):
return msg.content.isdigit() and int(msg.content) <= len(pools) and int(msg.content) > 0 and msg.author is ctx.author and msg.channel is ctx.channel return msg.content.isdigit() and int(msg.content) <= len(pools) and int(msg.content) > 0 and msg.author.id is ctx.author.id and msg.channel.id is ctx.channel.id
try: try:
kwargs = u.get_kwargs(ctx, args) kwargs = u.get_kwargs(ctx, args)
@ -352,7 +353,7 @@ class MsG(cmds.Cog):
await ctx.trigger_typing() await ctx.trigger_typing()
pools = [] pools = []
pool_request = await u.fetch('https://e621.net/pool/index.json', params={'query': ' '.join(query)}, json=True) pool_request = await u.fetch(f'https://e621.net/pools.json?search[name_matches]={" ".join(query)}', json=True)
if len(pool_request) > 1: if len(pool_request) > 1:
for pool in pool_request: for pool in pool_request:
pools.append(pool['name']) pools.append(pool['name'])
@ -375,7 +376,7 @@ class MsG(cmds.Cog):
else: else:
raise exc.NotFound raise exc.NotFound
await ctx.send(f'**{tempool["name"]}**\nhttps://e621.net/pool/show/{tempool["id"]}') await ctx.send(f'**{tempool["name"]}**\nhttps://e621.net/pools/{tempool["id"]}')
except exc.Abort as e: except exc.Abort as e:
await e.message.edit(content='\N{NO ENTRY SIGN}') await e.message.edit(content='\N{NO ENTRY SIGN}')
@ -613,19 +614,19 @@ class MsG(cmds.Cog):
async def _get_pool(self, ctx, *, booru='e621', query=[]): async def _get_pool(self, ctx, *, booru='e621', query=[]):
def on_reaction(reaction, user): def on_reaction(reaction, user):
if reaction.emoji == '\N{OCTAGONAL SIGN}' and reaction.message.id == ctx.message.id and user is ctx.author: if reaction.emoji == '\N{OCTAGONAL SIGN}' and reaction.message.id == ctx.message.id and user.id is ctx.author.id:
raise exc.Abort(match) raise exc.Abort(match)
return False return False
def on_message(msg): def on_message(msg):
return msg.content.isdigit() and int(msg.content) <= len(pools) and int(msg.content) > 0 and msg.author is ctx.author and msg.channel is ctx.channel return msg.content.isdigit() and int(msg.content) <= len(pools) and int(msg.content) > 0 and msg.author.id is ctx.author.id and msg.channel.id is ctx.channel.id
posts = {} posts = {}
pool = {} pool = {}
try: try:
pools = [] pools = []
pool_request = await u.fetch('https://{}.net/pool/index.json'.format(booru), params={'query': ' '.join(query)}, json=True) pool_request = await u.fetch(f'https://{booru}.net/pools.json?search[name_matches]={" ".join(query)}', json=True)
if len(pool_request) > 1: if len(pool_request) > 1:
for pool in pool_request: for pool in pool_request:
pools.append(pool['name']) pools.append(pool['name'])
@ -633,7 +634,9 @@ class MsG(cmds.Cog):
await u.add_reaction(ctx.message, '\N{OCTAGONAL SIGN}') await u.add_reaction(ctx.message, '\N{OCTAGONAL SIGN}')
done, pending = await asyncio.wait([self.bot.wait_for('reaction_add', check=on_reaction, timeout=60), done, pending = await asyncio.wait([self.bot.wait_for('reaction_add', check=on_reaction, timeout=60),
self.bot.wait_for('reaction_remove', check=on_reaction, timeout=60), self.bot.wait_for('message', check=on_message, timeout=60)], return_when=asyncio.FIRST_COMPLETED) self.bot.wait_for('reaction_remove', check=on_reaction, timeout=60),
self.bot.wait_for('message', check=on_message, timeout=60)],
return_when=asyncio.FIRST_COMPLETED)
for future in done: for future in done:
selection = future.result() selection = future.result()
@ -653,13 +656,13 @@ class MsG(cmds.Cog):
else: else:
raise exc.NotFound raise exc.NotFound
page = 1 for ident in tempool['post_ids']:
while len(posts) < tempool['post_count']: post = await u.fetch(f'https://{booru}.net/posts/{ident}.json', json=True)
posts_request = await u.fetch('https://{}.net/pool/show.json'.format(booru), params={'id': tempool['id'], 'page': page}, json=True) post = post['post']
for post in posts_request['posts']:
posts[post['id']] = {'artist': ', '.join( posts[post['id']] = {'artist': ', '.join(
post['artist']), 'file_url': post['file_url'], 'score': post['score']} post['tags']['artist']), 'sample_url': post['sample']['url'], 'score': post['score']['total']}
page += 1
await asyncio.sleep(0.5)
return pool, posts return pool, posts
@ -693,8 +696,8 @@ class MsG(cmds.Cog):
order = 'order:random' order = 'order:random'
# Checks if tags are in local blacklists # Checks if tags are in local blacklists
if tags: if tags:
if (len(tags) > 5 and booru == 'e621') or (len(tags) > 4 and booru == 'e926'): if (len(tags) > 40):
raise exc.TagBoundsError(' '.join(tags[5:])) raise exc.TagBoundsError(' '.join(tags[40:]))
for tag in tags: for tag in tags:
if tag == 'swf' or tag == 'webm' or tag in blacklist: if tag == 'swf' or tag == 'webm' or tag in blacklist:
raise exc.TagBlacklisted(tag) raise exc.TagBlacklisted(tag)
@ -707,17 +710,18 @@ class MsG(cmds.Cog):
while len(posts) < limit: while len(posts) < limit:
if c == limit * 5 + (self.LIMIT / 5): if c == limit * 5 + (self.LIMIT / 5):
raise exc.Timeout raise exc.Timeout
request = await u.fetch('https://{}.net/post/index.json'.format(booru), params={'tags': ','.join([order] + tags), 'limit': int(self.LIMIT * limit)}, json=True)
if len(request) == 0:
raise exc.NotFound(' '.join(tags))
if len(request) < limit:
limit = len(request)
for post in request: request = await u.fetch(f'https://{booru}.net/posts.json?tags={"+".join([order] + tags)}&limit={int(320)}', json=True)
if 'swf' in post['file_ext'] or 'webm' in post['file_ext']: if len(request['posts']) == 0:
raise exc.NotFound(' '.join(tags))
if len(request['posts']) < limit:
limit = len(request['posts'])
for post in request['posts']:
if 'swf' in post['file']['ext'] or 'webm' in post['file']['ext']:
continue continue
try: try:
post_tags = post['tags'].split(' ') post_tags = [tag for tags in post['tags'].values() for tag in tags]
for tag in blacklist: for tag in blacklist:
if tag in post_tags: if tag in post_tags:
raise exc.Continue raise exc.Continue
@ -725,7 +729,7 @@ class MsG(cmds.Cog):
continue continue
if post['id'] not in posts.keys() and post['id'] not in previous.keys(): if post['id'] not in posts.keys() and post['id'] not in previous.keys():
posts[post['id']] = {'artist': ', '.join( posts[post['id']] = {'artist': ', '.join(
post['artist']), 'file_url': post['file_url'], 'score': post['score']} post['tags']['artist']), 'sample_url': post['sample']['url'], 'score': post['score']['total']}
if len(posts) == limit: if len(posts) == limit:
break break
@ -748,20 +752,20 @@ class MsG(cmds.Cog):
@cmds.cooldown(1, 5, cmds.BucketType.member) @cmds.cooldown(1, 5, cmds.BucketType.member)
async def pool_paginator(self, ctx, *args): async def pool_paginator(self, ctx, *args):
def on_reaction(reaction, user): def on_reaction(reaction, user):
if reaction.emoji == '\N{OCTAGONAL SIGN}' and reaction.message.id == ctx.message.id and (user is ctx.author or user.permissions_in(reaction.message.channel).manage_messages): if reaction.emoji == '\N{OCTAGONAL SIGN}' and reaction.message.id == ctx.message.id and (user.id is ctx.author.id or user.permissions_in(reaction.message.channel).manage_messages):
raise exc.Abort raise exc.Abort
elif reaction.emoji == '\N{HEAVY BLACK HEART}' and reaction.message.id == paginator.id and user is ctx.author: elif reaction.emoji == '\N{HEAVY BLACK HEART}' and reaction.message.id == paginator.id and user.id is ctx.author.id:
raise exc.Save raise exc.Save
elif reaction.emoji == '\N{LEFTWARDS BLACK ARROW}' and reaction.message.id == paginator.id and user is ctx.author: elif reaction.emoji == '\N{LEFTWARDS BLACK ARROW}' and reaction.message.id == paginator.id and user.id is ctx.author.id:
raise exc.Left raise exc.Left
elif reaction.emoji == '\N{NUMBER SIGN}\N{COMBINING ENCLOSING KEYCAP}' and reaction.message.id == paginator.id and user is ctx.author: elif reaction.emoji == '\N{NUMBER SIGN}\N{COMBINING ENCLOSING KEYCAP}' and reaction.message.id == paginator.id and user.id is ctx.author.id:
raise exc.GoTo raise exc.GoTo
elif reaction.emoji == '\N{BLACK RIGHTWARDS ARROW}' and reaction.message.id == paginator.id and user is ctx.author: elif reaction.emoji == '\N{BLACK RIGHTWARDS ARROW}' and reaction.message.id == paginator.id and user.id is ctx.author.id:
raise exc.Right raise exc.Right
return False return False
def on_message(msg): def on_message(msg):
return msg.content.isdigit() and 0 <= int(msg.content) <= len(posts) and msg.author is ctx.author and msg.channel is ctx.channel return msg.content.isdigit() and 0 <= int(msg.content) <= len(posts) and msg.author.id is ctx.author.id and msg.channel.id is ctx.channel.id
try: try:
kwargs = u.get_kwargs(ctx, args) kwargs = u.get_kwargs(ctx, args)
@ -769,17 +773,19 @@ class MsG(cmds.Cog):
hearted = {} hearted = {}
c = 1 c = 1
await ctx.trigger_typing() if not args:
raise exc.MissingArgument
async with ctx.channel.typing():
pool, posts = await self._get_pool(ctx, booru='e621', query=query) pool, posts = await self._get_pool(ctx, booru='e621', query=query)
keys = list(posts.keys()) keys = list(posts.keys())
values = list(posts.values()) values = list(posts.values())
embed = d.Embed( embed = d.Embed(
title=values[c - 1]['artist'], url='https://e621.net/post/show/{}'.format(keys[c - 1]), color=ctx.me.color if isinstance(ctx.channel, d.TextChannel) else u.color) title=values[c - 1]['artist'], url='https://e621.net/posts/{}'.format(keys[c - 1]), color=ctx.me.color if isinstance(ctx.channel, d.TextChannel) else u.color)
embed.set_image(url=values[c - 1]['file_url']) embed.set_image(url=values[c - 1]['sample_url'])
embed.set_author(name=pool['name'], embed.set_author(name=pool['name'],
url='https://e621.net/pool/show?id={}'.format(pool['id']), icon_url=ctx.author.avatar_url) url='https://e621.net/pools/{}'.format(pool['id']), icon_url=ctx.author.avatar_url)
embed.set_footer(text='{} / {}'.format(c, len(posts)), embed.set_footer(text='{} / {}'.format(c, len(posts)),
icon_url=self._get_icon(values[c - 1]['score'])) icon_url=self._get_icon(values[c - 1]['score']))
@ -809,11 +815,11 @@ class MsG(cmds.Cog):
if c > 1: if c > 1:
c -= 1 c -= 1
embed.title = values[c - 1]['artist'] embed.title = values[c - 1]['artist']
embed.url = 'https://e621.net/post/show/{}'.format( embed.url = 'https://e621.net/posts/{}'.format(
keys[c - 1]) keys[c - 1])
embed.set_footer(text='{} / {}'.format(c, len(posts)), embed.set_footer(text='{} / {}'.format(c, len(posts)),
icon_url=self._get_icon(values[c - 1]['score'])) icon_url=self._get_icon(values[c - 1]['score']))
embed.set_image(url=values[c - 1]['file_url']) embed.set_image(url=values[c - 1]['sample_url'])
await paginator.edit(content='\N{HEAVY BLACK HEART}' if keys[c - 1] in hearted.keys() else None, embed=embed) await paginator.edit(content='\N{HEAVY BLACK HEART}' if keys[c - 1] in hearted.keys() else None, embed=embed)
else: else:
@ -827,11 +833,11 @@ class MsG(cmds.Cog):
c = int(number.content) c = int(number.content)
embed.title = values[c - 1]['artist'] embed.title = values[c - 1]['artist']
embed.url = 'https://e621.net/post/show/{}'.format( embed.url = 'https://e621.net/posts/{}'.format(
keys[c - 1]) keys[c - 1])
embed.set_footer(text='{} / {}'.format(c, len(posts)), embed.set_footer(text='{} / {}'.format(c, len(posts)),
icon_url=self._get_icon(values[c - 1]['score'])) icon_url=self._get_icon(values[c - 1]['score']))
embed.set_image(url=values[c - 1]['file_url']) embed.set_image(url=values[c - 1]['sample_url'])
if ctx.channel is d.TextChannel: if ctx.channel is d.TextChannel:
with suppress(errext.CheckFailure): with suppress(errext.CheckFailure):
@ -843,11 +849,11 @@ class MsG(cmds.Cog):
if c < len(keys): if c < len(keys):
c += 1 c += 1
embed.title = values[c - 1]['artist'] embed.title = values[c - 1]['artist']
embed.url = 'https://e621.net/post/show/{}'.format( embed.url = 'https://e621.net/posts/{}'.format(
keys[c - 1]) keys[c - 1])
embed.set_footer(text='{} / {}'.format(c, len(posts)), embed.set_footer(text='{} / {}'.format(c, len(posts)),
icon_url=self._get_icon(values[c - 1]['score'])) icon_url=self._get_icon(values[c - 1]['score']))
embed.set_image(url=values[c - 1]['file_url']) embed.set_image(url=values[c - 1]['sample_url'])
await paginator.edit(content='\N{HEAVY BLACK HEART}' if keys[c - 1] in hearted.keys() else None, embed=embed) await paginator.edit(content='\N{HEAVY BLACK HEART}' if keys[c - 1] in hearted.keys() else None, embed=embed)
else: else:
@ -863,6 +869,9 @@ class MsG(cmds.Cog):
await paginator.edit(content='\N{HOURGLASS}') await paginator.edit(content='\N{HOURGLASS}')
except UnboundLocalError: except UnboundLocalError:
await ctx.send('\N{HOURGLASS}') await ctx.send('\N{HOURGLASS}')
except exc.MissingArgument:
await ctx.send('**Missing argument**')
await u.add_reaction(ctx.message, '\N{CROSS MARK}')
except exc.NotFound: except exc.NotFound:
await ctx.send('**Pool not found**') await ctx.send('**Pool not found**')
await u.add_reaction(ctx.message, '\N{CROSS MARK}') await u.add_reaction(ctx.message, '\N{CROSS MARK}')
@ -883,18 +892,18 @@ class MsG(cmds.Cog):
async def _get_paginator(self, ctx, args, booru='e621'): async def _get_paginator(self, ctx, args, booru='e621'):
def on_reaction(reaction, user): def on_reaction(reaction, user):
if reaction.emoji == '\N{OCTAGONAL SIGN}' and reaction.message.id == ctx.message.id and (user is ctx.author or user.permissions_in(reaction.message.channel).manage_messages): if reaction.emoji == '\N{OCTAGONAL SIGN}' and reaction.message.id == ctx.message.id and (user.id is ctx.author.id or user.permissions_in(reaction.message.channel).manage_messages):
raise exc.Abort raise exc.Abort
elif reaction.emoji == '\N{HEAVY BLACK HEART}' and reaction.message.id == paginator.id and user is ctx.author: elif reaction.emoji == '\N{HEAVY BLACK HEART}' and reaction.message.id == paginator.id and user.id is ctx.author.id:
raise exc.Save raise exc.Save
elif reaction.emoji == '\N{LEFTWARDS BLACK ARROW}' and reaction.message.id == paginator.id and user is ctx.author: elif reaction.emoji == '\N{LEFTWARDS BLACK ARROW}' and reaction.message.id == paginator.id and user.id is ctx.author.id:
raise exc.Left raise exc.Left
elif reaction.emoji == '\N{BLACK RIGHTWARDS ARROW}' and reaction.message.id == paginator.id and user is ctx.author: elif reaction.emoji == '\N{BLACK RIGHTWARDS ARROW}' and reaction.message.id == paginator.id and user.id is ctx.author.id:
raise exc.Right raise exc.Right
return False return False
def on_message(msg): def on_message(msg):
return msg.content.isdigit() and 0 <= int(msg.content) <= len(posts) and msg.author is ctx.author and msg.channel is ctx.channel return msg.content.isdigit() and 0 <= int(msg.content) <= len(posts) and msg.author.id is ctx.author.id and msg.channel.id is ctx.channel.id
try: try:
kwargs = u.get_kwargs(ctx, args) kwargs = u.get_kwargs(ctx, args)
@ -912,10 +921,10 @@ class MsG(cmds.Cog):
values = list(posts.values()) values = list(posts.values())
embed = d.Embed( embed = d.Embed(
title=values[c - 1]['artist'], url='https://{}.net/post/show/{}'.format(booru, keys[c - 1]), color=ctx.me.color if isinstance(ctx.channel, d.TextChannel) else u.color) title=values[c - 1]['artist'], url='https://{}.net/posts/{}'.format(booru, keys[c - 1]), color=ctx.me.color if isinstance(ctx.channel, d.TextChannel) else u.color)
embed.set_image(url=values[c - 1]['file_url']) embed.set_image(url=values[c - 1]['sample_url'])
embed.set_author(name=' '.join(tags) if tags else order, embed.set_author(name=' '.join(tags) if tags else order,
url='https://{}.net/post?tags={}'.format(booru, ','.join(tags)), icon_url=ctx.author.avatar_url) url='https://{}.net/posts?tags={}'.format(booru, '+'.join(tags) if tags else order), icon_url=ctx.author.avatar_url)
embed.set_footer(text=values[c - 1]['score'], embed.set_footer(text=values[c - 1]['score'],
icon_url=self._get_icon(values[c - 1]['score'])) icon_url=self._get_icon(values[c - 1]['score']))
@ -945,12 +954,12 @@ class MsG(cmds.Cog):
if c > 1: if c > 1:
c -= 1 c -= 1
embed.title = values[c - 1]['artist'] embed.title = values[c - 1]['artist']
embed.url = 'https://{}.net/post/show/{}'.format( embed.url = 'https://{}.net/posts/{}'.format(
booru, booru,
keys[c - 1]) keys[c - 1])
embed.set_footer(text=values[c - 1]['score'], embed.set_footer(text=values[c - 1]['score'],
icon_url=self._get_icon(values[c - 1]['score'])) icon_url=self._get_icon(values[c - 1]['score']))
embed.set_image(url=values[c - 1]['file_url']) embed.set_image(url=values[c - 1]['sample_url'])
await paginator.edit(content='\N{HEAVY BLACK HEART}' if keys[c - 1] in hearted.keys() else None, embed=embed) await paginator.edit(content='\N{HEAVY BLACK HEART}' if keys[c - 1] in hearted.keys() else None, embed=embed)
else: else:
@ -969,12 +978,12 @@ class MsG(cmds.Cog):
if c < len(keys): if c < len(keys):
c += 1 c += 1
embed.title = values[c - 1]['artist'] embed.title = values[c - 1]['artist']
embed.url = 'https://{}.net/post/show/{}'.format( embed.url = 'https://{}.net/posts/{}'.format(
booru, booru,
keys[c - 1]) keys[c - 1])
embed.set_footer(text=values[c - 1]['score'], embed.set_footer(text=values[c - 1]['score'],
icon_url=self._get_icon(values[c - 1]['score'])) icon_url=self._get_icon(values[c - 1]['score']))
embed.set_image(url=values[c - 1]['file_url']) embed.set_image(url=values[c - 1]['sample_url'])
await paginator.edit(content='\N{HEAVY BLACK HEART}' if keys[c - 1] in hearted.keys() else None, embed=embed) await paginator.edit(content='\N{HEAVY BLACK HEART}' if keys[c - 1] in hearted.keys() else None, embed=embed)
else: else:
@ -1000,7 +1009,7 @@ class MsG(cmds.Cog):
await ctx.send('\N{NO ENTRY SIGN} `{}` **blacklisted**'.format(e)) await ctx.send('\N{NO ENTRY SIGN} `{}` **blacklisted**'.format(e))
await u.add_reaction(ctx.message, '\N{NO ENTRY SIGN}') await u.add_reaction(ctx.message, '\N{NO ENTRY SIGN}')
except exc.TagBoundsError as e: except exc.TagBoundsError as e:
await ctx.send('`{}` **out of bounds.** Tags limited to 5.'.format(e)) await ctx.send('`{}` **out of bounds.** Tags limited to 40.'.format(e))
await u.add_reaction(ctx.message, '\N{HEAVY EXCLAMATION MARK SYMBOL}') await u.add_reaction(ctx.message, '\N{HEAVY EXCLAMATION MARK SYMBOL}')
except exc.FavoritesNotFound: except exc.FavoritesNotFound:
await ctx.send('**You have no favorite tags**') await ctx.send('**You have no favorite tags**')
@ -1042,11 +1051,11 @@ class MsG(cmds.Cog):
posts, order = await self._get_posts(ctx, booru=booru, tags=tags, limit=limit) posts, order = await self._get_posts(ctx, booru=booru, tags=tags, limit=limit)
for ident, post in posts.items(): for ident, post in posts.items():
embed = d.Embed(title=post['artist'], url='https://{}.net/post/show/{}'.format(booru, ident), embed = d.Embed(title=post['artist'], url='https://{}.net/posts/{}'.format(booru, ident),
color=ctx.me.color if isinstance(ctx.channel, d.TextChannel) else u.color) color=ctx.me.color if isinstance(ctx.channel, d.TextChannel) else u.color)
embed.set_image(url=post['file_url']) embed.set_image(url=post['sample_url'])
embed.set_author(name=' '.join(tags) if tags else order, embed.set_author(name=' '.join(tags) if tags else order,
url='https://{}.net/post?tags={}'.format(booru, ','.join(tags)), icon_url=ctx.author.avatar_url) url='https://{}.net/posts?tags={}'.format(booru, '+'.join(tags) if tags else order), icon_url=ctx.author.avatar_url)
embed.set_footer( embed.set_footer(
text=post['score'], icon_url=self._get_icon(post['score'])) text=post['score'], icon_url=self._get_icon(post['score']))
@ -1061,7 +1070,7 @@ class MsG(cmds.Cog):
await ctx.send('`{}` **out of bounds.** Images limited to 3.'.format(e)) await ctx.send('`{}` **out of bounds.** Images limited to 3.'.format(e))
await u.add_reaction(ctx.message, '\N{HEAVY EXCLAMATION MARK SYMBOL}') await u.add_reaction(ctx.message, '\N{HEAVY EXCLAMATION MARK SYMBOL}')
except exc.TagBoundsError as e: except exc.TagBoundsError as e:
await ctx.send('`{}` **out of bounds.** Tags limited to 5.'.format(e)) await ctx.send('`{}` **out of bounds.** Tags limited to 40.'.format(e))
await u.add_reaction(ctx.message, '\N{HEAVY EXCLAMATION MARK SYMBOL}') await u.add_reaction(ctx.message, '\N{HEAVY EXCLAMATION MARK SYMBOL}')
except exc.NotFound as e: except exc.NotFound as e:
await ctx.send('`{}` **not found**'.format(e)) await ctx.send('`{}` **not found**'.format(e))
@ -1295,8 +1304,7 @@ class MsG(cmds.Cog):
if tags: if tags:
for tag in tags: for tag in tags:
request = await u.fetch( request = await u.fetch(
'https://e621.net/tag_alias/index.json', f'https://e621.net/tag_alias/index.json?aliased_to={tag}&approved=true',
params={'aliased_to': tag, 'approved': 'true'},
json=True) json=True)
for elem in request: for elem in request:

View file

@ -40,7 +40,7 @@ class Admin(cmds.Cog):
@_prune_user.command(name='channel', aliases=['channels', 'chans', 'chan', 'ch', 'c']) @_prune_user.command(name='channel', aliases=['channels', 'chans', 'chan', 'ch', 'c'])
async def _prune_user_channel(self, ctx, user: d.User, *channels: d.TextChannel): async def _prune_user_channel(self, ctx, user: d.User, *channels: d.TextChannel):
def confirm(r, u): def confirm(r, u):
if u is ctx.author: if u.id is ctx.author.id:
if r.emoji == '\N{OCTAGONAL SIGN}': if r.emoji == '\N{OCTAGONAL SIGN}':
raise exc.Abort raise exc.Abort
if r.emoji == '\N{THUMBS UP SIGN}': if r.emoji == '\N{THUMBS UP SIGN}':
@ -92,7 +92,7 @@ class Admin(cmds.Cog):
@cmds.is_owner() @cmds.is_owner()
async def _prune_user_all(self, ctx, user: d.User): async def _prune_user_all(self, ctx, user: d.User):
def confirm(r, u): def confirm(r, u):
if u is ctx.author: if u.id is ctx.author.id:
if r.emoji == '\N{OCTAGONAL SIGN}': if r.emoji == '\N{OCTAGONAL SIGN}':
raise exc.Abort raise exc.Abort
if r.emoji == '\N{THUMBS UP SIGN}': if r.emoji == '\N{THUMBS UP SIGN}':

View file

@ -213,19 +213,19 @@ class Tools(cmds.Cog):
@cmds.is_owner() @cmds.is_owner()
async def console(self, ctx): async def console(self, ctx):
def execute(msg): def execute(msg):
if msg.content.lower().startswith('exec ') and msg.author is ctx.author and msg.channel is ctx.channel: if msg.content.lower().startswith('exec ') and msg.author.id is ctx.author.id and msg.channel.id is ctx.channel.id:
msg.content = msg.content[5:] msg.content = msg.content[5:]
return True return True
return False return False
def evaluate(msg): def evaluate(msg):
if msg.content.lower().startswith('eval ') and msg.author is ctx.author and msg.channel is ctx.channel: if msg.content.lower().startswith('eval ') and msg.author.id is ctx.author.id and msg.channel.id is ctx.channel.id:
msg.content = msg.content[5:] msg.content = msg.content[5:]
return True return True
return False return False
def exit(reaction, user): def exit(reaction, user):
if reaction.emoji == '\N{OCTAGONAL SIGN}' and user is ctx.author and reaction.message.id == ctx.message.id: if reaction.emoji == '\N{OCTAGONAL SIGN}' and user.id is ctx.author.id and reaction.message.id == ctx.message.id:
raise exc.Abort raise exc.Abort
return False return False

View file

@ -12,25 +12,23 @@ from utils import utils as u
# async def get_harry(url): # async def get_harry(url):
# content = await u.fetch('https://iqdb.harry.lu', params={'url': url}) # content = await u.fetch(f'https://iqdb.harry.lu?url={url}')
# soup = BeautifulSoup(content, 'html5lib') # soup = BeautifulSoup(content, 'html5lib')
# #
# if soup.find('div', id='show1').string is 'Not the right one? ': # if soup.find('div', id='show1').string is 'Not the right one? ':
# parent = soup.find('th', string='Probable match:').parent.parent # parent = soup.find('th', string='Probable match:').parent.parent
# #
# post = await u.fetch( # post = await u.fetch(
# 'https://e621.net/post/show.json', # f'https://e621.net/posts.json?id={re.search("show/([0-9]+)", parent.tr.td.a.get('href')).group(1)}',
# params={'id': re.search('show/([0-9]+)', parent.tr.td.a.get('href')).group(1)},
# json=True) # json=True)
# if (post['status'] == 'deleted'): # if (post['status'] == 'deleted'):
# post = await u.fetch( # post = await u.fetch(
# 'https://e621.net/post/show.json', # f'https://e621.net/posts.json?id={re.search("#(\\d+)", post["delreason"]).group(1)}',
# params={'id': re.search('#(\\d+)', post['delreason']).group(1)},
# json=True) # json=True)
# #
# result = { # result = {
# 'source': f'https://e621.net/post/show/{post["id"]}', # 'source': f'https://e621.net/posts/{post["id"]}',
# 'artist': ', '.join(post['artist']), # 'artist': ', '.join(post['tags']['artist']),
# 'thumbnail': parent.td.a.img.get('src'), # 'thumbnail': parent.td.a.img.get('src'),
# 'similarity': re.search('\\d+', parent.tr[4].td.string).group(0), # 'similarity': re.search('\\d+', parent.tr[4].td.string).group(0),
# 'database': 'Harry.lu' # 'database': 'Harry.lu'
@ -43,7 +41,7 @@ from utils import utils as u
async def query_kheina(url): async def query_kheina(url):
try: try:
content = await u.fetch('https://kheina.com', params={'url': url}, text=True) content = await u.fetch(f'https://kheina.com?url={url}', text=True)
for e in ('&quot;', '&apos;'): for e in ('&quot;', '&apos;'):
content = content.replace(e, '') content = content.replace(e, '')
@ -85,8 +83,7 @@ async def query_kheina(url):
async def query_saucenao(url): async def query_saucenao(url):
try: try:
content = await u.fetch( content = await u.fetch(
'https://saucenao.com/search.php', f'https://saucenao.com/search.php?url={url}&api_key={u.config["saucenao_api"]}&output_type={2}',
params={'url': url, 'api_key': u.config['saucenao_api'], 'output_type': 2},
json=True) json=True)
if content['header'].get('message', '') in ( if content['header'].get('message', '') in (