1
0
Fork 0
mirror of synced 2024-05-23 22:09:38 +12:00

remove carriage returns

This commit is contained in:
phxntxm 2018-05-07 10:01:16 -05:00
parent 750b12f7d9
commit 6145ab3df3

View file

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