Browse Source

fix huge mistake and release proper cog

master
Jonathan de Jong 3 years ago
parent
commit
3d78c006c4
  1. 251
      cogs/find/__init__.py
  2. 2
      setup.py

251
cogs/find/__init__.py

@ -1,57 +1,200 @@ @@ -1,57 +1,200 @@
import re
from typing import Optional
from discord.ext.commands import command
from imgurpython import ImgurClient
from imgurpython.helpers.error import ImgurClientRateLimitError
from snek import SNEK, SNEKContext, AbstractCog
imgur_re = re.compile(r'https?://\S+?\.(png|jpe?g|bmp|gif)')
class ImgurCog(AbstractCog, name="Imgur"):
def __init__(self, bot: SNEK):
self.client_id = bot.env.str("IMGUR_CLIENT_ID", None)
self.client_secret = bot.env.str("IMGUR_CLIENT_SECRET", None)
if self.client_id is None or self.client_secret is None:
raise KeyError(
"Need both IMGUR_CLIENT_ID and IMGUR_CLIENT_SECRET environment variables "
"for imgur photo uploading to work"
)
self.imgurc = ImgurClient(self.client_id, self.client_secret)
@command(aliases=["i"])
async def imgur(self, ctx: SNEKContext, url: Optional[str]):
"""Upload an image to imgur
Upload 1 image alongside the command, or give an image url."""
if url is None:
try:
ctx.message.attachments[0].height
except Exception:
await ctx.send("Sorry, but that doesn't look like an image...")
await ctx.send_help("imgur")
return
else:
url = ctx.message.attachments[0].url
if imgur_re.match(url):
async with ctx.typing():
try:
await ctx.send(
self.imgurc.upload_from_url(url).get("link").replace(
".jpg", ".png"), nocode=True)
except ImgurClientRateLimitError as e:
await ctx.send("Rate limit exceeded!")
raise e
else:
await ctx.send(
"Sorry, but that doesn't seem to look like an image URL. "
"(It has to have https:// at the beginning and end with extension png, jpg, jpeg, etc.)"
)
return
# -*- coding: utf-8 -*-
from typing import Optional, Union
import discord
from discord.ext.commands import Cog, command
from ruamel.yaml import YAML, StringIO
from snek import SNEK, SNEKContext
yaml = YAML()
yaml.boolean_representation = ['No', 'Yes']
strftime_format = "%c"
def dump_yaml(obj):
sio = StringIO()
yaml.dump(obj, sio)
return sio.getvalue()
def format_url(url: discord.Asset):
return str(url).strip("https://").strip("http://")
class FindResults:
def __init__(self, channel, guild, user, member, role, message):
self.channel: Optional[Union[discord.TextChannel, discord.VoiceChannel]] = channel
self.guild: Optional[discord.Guild] = guild
self.user: Optional[discord.User] = user
self.member: Optional[discord.Member] = member
self.message: Optional[discord.Message] = message
self.role: Optional[discord.Role] = role
async def find(any_id: int, ctx: SNEKContext):
bot = ctx.bot
chan = bot.get_channel(any_id)
if isinstance(chan, discord.DMChannel):
chan = None
guild = bot.get_guild(any_id)
user = None
try:
user = await bot.fetch_user(any_id)
except (discord.NotFound, discord.HTTPException, AttributeError):
pass
role = ctx.guild.get_role(any_id)
member = None
if user is not None:
member = ctx.guild.get_member(any_id)
message = None
for ch in ctx.guild.channels:
try:
message = await ch.fetch_message(any_id)
break
except (discord.NotFound, discord.Forbidden, discord.HTTPException,
AttributeError):
pass
return FindResults(chan, guild, user, member, role, message)
class Find(Cog):
@command(hidden=True, aliases=['nani', '', "なに", "what"])
@SNEK.is_mod()
async def find(self, ctx: SNEKContext, any_id: int):
async with ctx.typing():
results = await find(any_id, ctx)
message = results.message
channel = results.channel
server = results.guild
user = results.user
member = results.member
role = results.role
result_y = {
"Results": {
"Message": "Not Found" if message is None else {
"Sent": f"{message.created_at.strftime(strftime_format)} GMT",
"By": f"{message.author!s}",
"In": f"#{message.channel.name}",
},
"Channel": "Not Found" if channel is None else {
"In": f"^{channel.guild.name}",
"Name": f"#{channel.name}",
},
"Server": "Not Found" if server is None else {
"Name": server.name,
},
"User": "Not Found" if user is None else {
"Name": f"{user!s}",
},
"Member": "Not Found" if member is None else {
"Nick": member.nick or "(not set)",
},
"Role": "Not Found" if role is None else {
"Name": role.name,
}
}
}
await ctx.send(dump_yaml(result_y), lang="yaml")
@command(hidden=True, aliases=["なにこれ", "何これ", "nanikore", "whatis"])
@SNEK.is_mod()
async def findmore(self, ctx: SNEKContext, any_id: int):
async with ctx.typing():
results = await find(any_id, ctx)
message = results.message
channel = results.channel
guild = results.guild
user = results.user
member = results.member
role = results.role
result_y = {
"Results": {
"Message": "Not Found" if message is None else {
"Sent": f"{message.created_at.strftime(strftime_format)} GMT",
"By": f"{message.author!s} (@{message.author.id})",
"In": f"#{message.channel.name} (@{message.channel.id})",
# extra
"Content": f"{message.content!r}",
"Embed": message.embeds,
"Pinned": "Yes" if message.pinned else "No",
},
"Channel": "Not Found" if channel is None else {
"In": f"^{channel.guild.name}",
"Name": f"#{channel.name}",
# extra
"Permissions": [{"target": {"id": o[0], "type": o[3]},
"allow": o[1], "deny": o[2]} for o in
channel._overwrites],
# "Type": str(channel.type),
"Position": channel.position,
"Topic": channel.topic,
# created
"Created": f"{channel.created_at.strftime(strftime_format)} GMT"
},
"Server": "Not Found" if guild is None else {
"Name": guild.name,
# extra
"Icon": format_url(guild.icon_url_as(format="png")),
"Splash": format_url(guild.splash_url_as(format="png")),
"OwnerID": f"@{guild.owner_id}",
# created
"Created": f"{guild.created_at.strftime(strftime_format)} GMT"
},
"User": "Not Found" if user is None else {
"Name": f"{user!s}",
# extra
"Avatar": "(Default)" if user.avatar is None else
format_url(user.avatar_url_as(format="png")),
"Bot": "Yes" if user.bot else "No",
# created
"Created": f"{user.created_at.strftime(strftime_format)} GMT"
},
"Member": "Not Found" if member is None else {
"Nick": member.nick or "(not set)",
# extra
"Joined": f"{member.joined_at.strftime(strftime_format)} GMT",
"Roles": {r.id: r.name for r in results.member.roles}
},
"Role": "Not Found" if role is None else {
"Name": f"{role.name!r}",
# extra
"Colour": role.color.__str__(),
"Permissions": role.permissions.value,
# created
"Created": f"{role.created_at.strftime(strftime_format)} GMT"
}
}
}
await ctx.send(dump_yaml(result_y), lang="yaml")
def setup(bot: SNEK):
bot.add_cog(ImgurCog(bot))
bot.add_cog(Find())

2
setup.py

@ -14,7 +14,7 @@ setuptools.setup( @@ -14,7 +14,7 @@ setuptools.setup(
"Operating System :: OS Independent",
],
python_requires=">=3.6",
install_requires=["d-snek>=1.2.4", "discord.py>=1.2.5", "imgurpython==1.1.7"],
install_requires=["d-snek>=1.2.4", "discord.py>=1.2.5", "ruamel-yaml>=0.16.5"],
setup_requires=["wheel"],
extras_require={
"dev": ["ipython", "twine"],

Loading…
Cancel
Save