1
0
Fork 0
mirror of synced 2024-05-18 19:42:28 +12:00

Clean up cat/e621 api calls

This commit is contained in:
phxntxm 2018-05-07 09:56:23 -05:00
parent 9e46f4c37c
commit 750b12f7d9

View file

@ -1,250 +1,256 @@
from discord.ext import commands from discord.ext import commands
import discord import discord
import random import random
import re import re
import math import math
import glob import glob
from bs4 import BeautifulSoup as bs from bs4 import BeautifulSoup as bs
from . import utils from . import utils
class Images: class Images:
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
@commands.command(aliases=['rc']) @commands.command(aliases=['rc'])
@utils.custom_perms(send_messages=True) @utils.custom_perms(send_messages=True)
@utils.check_restricted() @utils.check_restricted()
async def cat(self, ctx): async def cat(self, ctx):
"""Use this to print a random cat image. """Use this to print a random cat image.
EXAMPLE: !cat EXAMPLE: !cat
RESULT: A beautiful picture of a cat o3o""" RESULT: A beautiful picture of a cat o3o"""
result = await utils.request('http://aws.random.cat/meow') url = "http://thecatapi.com/api/images/get"
if result is None: opts = {"format": "src"}
await ctx.send("I couldn't connect! Sorry no cats right now ;w;") result = await utils.request(url, attr='url', payload=opts)
return
filename = result.get('file', None) image = await utils.download_image(result)
if filename is None: f = discord.File(image, filename=result.name)
await ctx.send("I couldn't connect! Sorry no cats right now ;w;") await ctx.send(file=f)
return
@commands.command(aliases=['dog', 'rd'])
image = await utils.download_image(filename) @utils.custom_perms(send_messages=True)
filename = re.search('.*/i/(.*)', filename).group(1) @utils.check_restricted()
f = discord.File(image, filename=filename) async def doggo(self, ctx):
await ctx.send(file=f) """Use this to print a random doggo image.
@commands.command(aliases=['dog', 'rd']) EXAMPLE: !doggo
@utils.custom_perms(send_messages=True) RESULT: A beautiful picture of a dog o3o"""
@utils.check_restricted() result = await utils.request('http://random.dog', attr='text')
async def doggo(self, ctx): try:
"""Use this to print a random doggo image. soup = bs(result, 'html.parser')
filename = soup.img.get('src')
EXAMPLE: !doggo except (TypeError, AttributeError):
RESULT: A beautiful picture of a dog o3o""" await ctx.send("I couldn't connect! Sorry no dogs right now ;w;")
result = await utils.request('http://random.dog', attr='text') return
try:
soup = bs(result, 'html.parser') image = await utils.download_image("http://random.dog/{}".format(filename))
filename = soup.img.get('src') f = discord.File(image, filename=filename)
except (TypeError, AttributeError): await ctx.send(file=f)
await ctx.send("I couldn't connect! Sorry no dogs right now ;w;")
return @commands.command(aliases=['snake'])
@utils.custom_perms(send_messages=True)
image = await utils.download_image("http://random.dog/{}".format(filename)) @utils.check_restricted()
f = discord.File(image, filename=filename) async def snek(self, ctx):
await ctx.send(file=f) """Use this to print a random snek image.
@commands.command(aliases=['snake']) EXAMPLE: !snek
@utils.custom_perms(send_messages=True) RESULT: A beautiful picture of a snek o3o"""
@utils.check_restricted() result = await utils.request("http://hrsendl.com/snake")
async def snek(self, ctx): if result is None:
"""Use this to print a random snek image. await ctx.send("I couldn't connect! Sorry no snakes right now ;w;")
return
EXAMPLE: !snek filename = result.get('image', None)
RESULT: A beautiful picture of a snek o3o""" if filename is None:
result = await utils.request("http://hrsendl.com/snake") await ctx.send("I couldn't connect! Sorry no snakes right now ;w;")
if result is None: return
await ctx.send("I couldn't connect! Sorry no snakes right now ;w;")
return image = await utils.download_image(filename)
filename = result.get('image', None) filename = re.search('.*/snakes/(.*)', filename).group(1)
if filename is None: f = discord.File(image, filename=filename)
await ctx.send("I couldn't connect! Sorry no snakes right now ;w;") await ctx.send(file=f)
return
@commands.command()
image = await utils.download_image(filename) @utils.custom_perms(send_messages=True)
filename = re.search('.*/snakes/(.*)', filename).group(1) @utils.check_restricted()
f = discord.File(image, filename=filename) async def horse(self, ctx):
await ctx.send(file=f) """Use this to print a random horse image.
@commands.command() EXAMPLE: !horse
@utils.custom_perms(send_messages=True) RESULT: A beautiful picture of a horse o3o"""
@utils.check_restricted() result = await utils.request("http://hrsendl.com/horse")
async def horse(self, ctx): if result is None:
"""Use this to print a random horse image. await ctx.send("I couldn't connect! Sorry no horses right now ;w;")
return
EXAMPLE: !horse filename = result.get('image', None)
RESULT: A beautiful picture of a horse o3o""" if filename is None:
result = await utils.request("http://hrsendl.com/horse") await ctx.send("I couldn't connect! Sorry no horses right now ;w;")
if result is None: return
await ctx.send("I couldn't connect! Sorry no horses right now ;w;")
return image = await utils.download_image(filename)
filename = result.get('image', None) filename = re.search('.*/horses/(.*)', filename).group(1)
if filename is None: f = discord.File(image, filename=filename)
await ctx.send("I couldn't connect! Sorry no horses right now ;w;") await ctx.send(file=f)
return
@commands.command()
image = await utils.download_image(filename) @commands.guild_only()
filename = re.search('.*/horses/(.*)', filename).group(1) @utils.custom_perms(send_messages=True)
f = discord.File(image, filename=filename) @utils.check_restricted()
await ctx.send(file=f) async def avatar(self, ctx, member: discord.Member = None):
"""Provides an image for the provided person's avatar (yours if no other member is provided)
@commands.command()
@commands.guild_only() EXAMPLE: !avatar @person
@utils.custom_perms(send_messages=True) RESULT: A full image of that person's avatar"""
@utils.check_restricted()
async def avatar(self, ctx, member: discord.Member = None): if member is None:
"""Provides an image for the provided person's avatar (yours if no other member is provided) member = ctx.message.author
EXAMPLE: !avatar @person url = member.avatar_url
RESULT: A full image of that person's avatar""" if '.gif' not in url:
url = member.avatar_url_as(format='png')
if member is None: filename = 'avatar.png'
member = ctx.message.author else:
filename = 'avatar.gif'
url = member.avatar_url if ctx.message.guild.me.permissions_in(ctx.message.channel).attach_files:
if '.gif' not in url: filedata = await utils.download_image(url)
url = member.avatar_url_as(format='png') if filedata is None:
filename = 'avatar.png' await ctx.send(url)
else: else:
filename = 'avatar.gif' try:
if ctx.message.guild.me.permissions_in(ctx.message.channel).attach_files: f = discord.File(filedata, filename=filename)
filedata = await utils.download_image(url) await ctx.send(file=f)
if filedata is None: except discord.HTTPException:
await ctx.send(url) await ctx.send("Sorry but that avatar is too large for me to send!")
else: else:
try: await ctx.send(url)
f = discord.File(filedata, filename=filename)
await ctx.send(file=f) @commands.command()
except discord.HTTPException: @utils.custom_perms(send_messages=True)
await ctx.send("Sorry but that avatar is too large for me to send!") @utils.check_restricted()
else: async def derpi(self, ctx, *search: str):
await ctx.send(url) """Provides a random image from the first page of derpibooru.org for the following term
@commands.command() EXAMPLE: !derpi Rainbow Dash
@utils.custom_perms(send_messages=True) RESULT: A picture of Rainbow Dash!"""
@utils.check_restricted() await ctx.message.channel.trigger_typing()
async def derpi(self, ctx, *search: str):
"""Provides a random image from the first page of derpibooru.org for the following term if len(search) > 0:
url = 'https://derpibooru.org/search.json'
EXAMPLE: !derpi Rainbow Dash
RESULT: A picture of Rainbow Dash!""" # Ensure a filter was not provided, as we either want to use our own, or none (for safe pics)
await ctx.message.channel.trigger_typing() query = ' '.join(value for value in search if not re.search('&?filter_id=[0-9]+', value))
params = {'q': query}
if len(search) > 0:
url = 'https://derpibooru.org/search.json' nsfw = await utils.channel_is_nsfw(ctx.message.channel, self.bot.db)
# If this is a nsfw channel, we just need to tack on 'explicit' to the terms
# Ensure a filter was not provided, as we either want to use our own, or none (for safe pics) # Also use the custom filter that I have setup, that blocks some certain tags
query = ' '.join(value for value in search if not re.search('&?filter_id=[0-9]+', value)) # If the channel is not nsfw, we don't need to do anything, as the default filter blocks explicit
params = {'q': query} if nsfw:
params['q'] += ", (explicit OR suggestive)"
nsfw = await utils.channel_is_nsfw(ctx.message.channel, self.bot.db) params['filter_id'] = 95938
# If this is a nsfw channel, we just need to tack on 'explicit' to the terms else:
# Also use the custom filter that I have setup, that blocks some certain tags params['q'] += ", safe"
# If the channel is not nsfw, we don't need to do anything, as the default filter blocks explicit # Lets filter out some of the "crap" that's on derpibooru by requiring an image with a score higher than 15
if nsfw: params['q'] += ', score.gt:15'
params['q'] += ", (explicit OR suggestive)"
params['filter_id'] = 95938 try:
else: # Get the response from derpibooru and parse the 'search' result from it
params['q'] += ", safe" data = await utils.request(url, payload=params)
# Lets filter out some of the "crap" that's on derpibooru by requiring an image with a score higher than 15
params['q'] += ', score.gt:15' if data is None:
await ctx.send("Sorry but I failed to connect to Derpibooru!")
try: return
# Get the response from derpibooru and parse the 'search' result from it results = data['search']
data = await utils.request(url, payload=params) except KeyError:
await ctx.send("No results with that search term, {0}!".format(ctx.message.author.mention))
if data is None: return
await ctx.send("Sorry but I failed to connect to Derpibooru!")
return # The first request we've made ensures there are results
results = data['search'] # Now we can get the total count from that, and make another request based on the number of pages as well
except KeyError: if len(results) > 0:
await ctx.send("No results with that search term, {0}!".format(ctx.message.author.mention)) # Get the total number of pages
return pages = math.ceil(data['total'] / len(results))
# Set a new paramater to set which page to use, randomly based on the number of pages
# The first request we've made ensures there are results params['page'] = random.SystemRandom().randint(1, pages)
# Now we can get the total count from that, and make another request based on the number of pages as well data = await utils.request(url, payload=params)
if len(results) > 0: if data is None:
# Get the total number of pages await ctx.send("Sorry but I failed to connect to Derpibooru!")
pages = math.ceil(data['total'] / len(results)) return
# Set a new paramater to set which page to use, randomly based on the number of pages # Now get the results again
params['page'] = random.SystemRandom().randint(1, pages) results = data['search']
data = await utils.request(url, payload=params)
if data is None: # Get the image link from the now random page'd and random result from that page
await ctx.send("Sorry but I failed to connect to Derpibooru!") index = random.SystemRandom().randint(0, len(results) - 1)
return # image_link = 'https://derpibooru.org/{}'.format(results[index]['id'])
# Now get the results again image_link = 'https:{}'.format(results[index]['image'])
results = data['search'] else:
await ctx.send("No results with that search term, {0}!".format(ctx.message.author.mention))
# Get the image link from the now random page'd and random result from that page return
index = random.SystemRandom().randint(0, len(results) - 1) else:
# image_link = 'https://derpibooru.org/{}'.format(results[index]['id']) # If no search term was provided, search for a random image
image_link = 'https:{}'.format(results[index]['image']) # .url will be the URL we end up at, not the one requested.
else: # https://derpibooru.org/images/random redirects to a random image, so this is exactly what we want
await ctx.send("No results with that search term, {0}!".format(ctx.message.author.mention)) image_link = await utils.request('https://derpibooru.org/images/random', attr='url')
return await ctx.send(image_link)
else:
# If no search term was provided, search for a random image @commands.command()
# .url will be the URL we end up at, not the one requested. @utils.custom_perms(send_messages=True)
# https://derpibooru.org/images/random redirects to a random image, so this is exactly what we want @utils.check_restricted()
image_link = await utils.request('https://derpibooru.org/images/random', attr='url') async def e621(self, ctx, *, tags: str):
await ctx.send(image_link) """Searches for a random image from e621.net
Format for the search terms need to be 'search term 1, search term 2, etc.'
@commands.command() If the channel the command is ran in, is registered as a nsfw channel, this image will be explicit
@utils.custom_perms(send_messages=True)
@utils.check_restricted() EXAMPLE: !e621 dragon
async def e621(self, ctx, *, tags: str): RESULT: A picture of a dragon (hopefully, screw your tagging system e621)"""
"""Searches for a random image from e621.net await ctx.message.channel.trigger_typing()
Format for the search terms need to be 'search term 1, search term 2, etc.'
If the channel the command is ran in, is registered as a nsfw channel, this image will be explicit # This changes the formatting for queries, so we don't
# Have to use e621's stupid formatting when using the command
EXAMPLE: !e621 dragon
RESULT: A picture of a dragon (hopefully, screw your tagging system e621)""" tags = tags.replace(' ', '_')
await ctx.message.channel.trigger_typing() tags = tags.replace(',_', ' ')
# This changes the formatting for queries, so we don't url = 'https://e621.net/post/index.json'
# Have to use e621's stupid formatting when using the command params = {
'limit': 5,
tags = tags.replace(' ', '_') 'tags': tags
tags = tags.replace(',_', ' ') }
url = 'https://e621.net/post/index.json' nsfw = await utils.channel_is_nsfw(ctx.message.channel, self.bot.db)
params = {'limit': 320,
'tags': tags} # e621 by default does not filter explicit content, so tack on
# safe/explicit based on if this channel is nsfw or not
nsfw = await utils.channel_is_nsfw(ctx.message.channel, self.bot.db) params['tags'] += " rating:explicit" if nsfw else " rating:safe"
# Tack on a random order
# e621 by default does not filter explicit content, so tack on params['tags'] += " order:random"
# safe/explicit based on if this channel is nsfw or not
params['tags'] += " rating:explicit" if nsfw else " rating:safe" data = await utils.request(url, payload=params)
data = await utils.request(url, payload=params) if data is None:
await ctx.send("Sorry, I had trouble connecting at the moment; please try again later")
if data is None: return
await ctx.send("Sorry, I had trouble connecting at the moment; please try again later")
return # Try to find an image from the list. If there were no results, we're going to attempt to find
# A number between (0,-1) and receive an error.
# Try to find an image from the list. If there were no results, we're going to attempt to find # The response should be in a list format, so we'll end up getting a key error if the response was in json
# A number between (0,-1) and receive an error. # i.e. it responded with a 404/504/etc.
# The response should be in a list format, so we'll end up getting a key error if the response was in json try:
# i.e. it responded with a 404/504/etc. for image in data:
try: # Will support in the future
rand_image = data[random.SystemRandom().randint(0, len(data) - 1)]['file_url'] blacklist = []
await ctx.send(rand_image) tags = image["tags"]
except (ValueError, KeyError): # Check if any of the tags are in the blacklist
await ctx.send("No results with that tag {}".format(ctx.message.author.mention)) if any(tag in blacklist for tag in tags):
return continue
# If this image is fine, then send this and break
await ctx.send(image["file_url"])
def setup(bot): return
bot.add_cog(Images(bot)) except (ValueError, KeyError):
await ctx.send("No results with that tag {}".format(ctx.message.author.mention))
return
def setup(bot):
bot.add_cog(Images(bot))