1
0
Fork 0
mirror of https://github.com/myned/modufur.git synced 2024-11-01 21:02:38 +00:00

Merge branch 'dev'

This commit is contained in:
Myned 2017-10-14 21:59:52 -04:00
commit 1c0ef754a3
10 changed files with 99 additions and 92 deletions

1
.gitignore vendored
View file

@ -4,6 +4,7 @@
*.pyc
*.DS_Store
*.pkl
*.png
# Byte-compiled / optimized / DLL files
__pycache__/

View file

@ -71,7 +71,7 @@ class MsG:
await ctx.send('✅ **Probable match:**\n{}'.format(await scraper.check_match(url)))
except exc.MatchError:
await ctx.send('❌ **No probable match.**', delete_after=10)
await ctx.send('❌ **No probable match.** Make sure the URL directs to an image file.', delete_after=10)
@reverse_image_search.error
async def reverse_image_search_error(self, ctx, error):
@ -79,8 +79,8 @@ class MsG:
return await ctx.send('❌ **Invalid url.**', delete_after=10)
async def return_pool(self, *, ctx, booru='e621', query=[]):
channel = ctx.message.channel
user = ctx.message.author
channel = ctx.channel
user = ctx.author
def on_message(msg):
if msg.content.lower() == 'cancel' and msg.author is user and msg.channel is channel:
@ -133,8 +133,8 @@ class MsG:
@commands.command(name='pool', aliases=['e6pp'], brief='e621 pool paginator', description='e621 | NSFW\nShow pools in a page format', hidden=True)
@checks.del_ctx()
async def pool_paginator(self, ctx, *kwords):
channel = ctx.message.channel
user = ctx.message.author
channel = ctx.channel
user = ctx.author
def on_react(reaction, user):
if reaction.emoji == '🚫' and reaction.message.content == paginator.content and (user is user or user.id == u.config['owner_id']):
@ -262,10 +262,10 @@ class MsG:
# Messy code that checks image limit and tags in blacklists
async def check_return_posts(self, *, ctx, booru='e621', tags=[], limit=1, previous={}):
guild = ctx.message.guild if isinstance(
ctx.message.guild, d.Guild) else ctx.message.channel
channel = ctx.message.channel
user = ctx.message.author
guild = ctx.guild if isinstance(
ctx.guild, d.Guild) else ctx.channel
channel = ctx.channel
user = ctx.author
blacklist = set()
# Creates temp blacklist based on context
@ -316,8 +316,8 @@ class MsG:
@checks.del_ctx()
@checks.is_nsfw()
async def e621_paginator(self, ctx, *args):
channel = ctx.message.channel
user = ctx.message.author
channel = ctx.channel
user = ctx.author
def on_react(reaction, user):
if reaction.emoji == '🚫' and reaction.message.content == paginator.content and (user is user or user.id == u.config['owner_id']):
@ -454,13 +454,14 @@ class MsG:
@e621_paginator.error
async def e621_paginator_error(self, ctx, error):
if isinstance(error, errext.CheckFailure):
return await ctx.send('{} **is not an NSFW channel.**'.format(ctx.message.channel.mention), delete_after=10)
return await ctx.send('{} **is not an NSFW channel.**'.format(ctx.channel.mention), delete_after=10)
# Searches for and returns images from e621.net given tags when not blacklisted
@commands.command(aliases=['e6', '6'], brief='e621 | NSFW', description='e621 | NSFW\nTag-based search for e621.net\n\nYou can only search 5 tags and 6 images at once for now.\ne6 [tags...] ([# of images])')
@checks.del_ctx()
@checks.is_nsfw()
async def e621(self, ctx, *args):
user = ctx.author
args = list(args)
limit = 1
@ -509,12 +510,13 @@ class MsG:
@e621.error
async def e621_error(self, ctx, error):
if isinstance(error, errext.CheckFailure):
return await ctx.send('{} **is not an NSFW channel.**'.format(ctx.message.channel.mention), delete_after=10)
return await ctx.send('{} **is not an NSFW channel.**'.format(ctx.channel.mention), delete_after=10)
# Searches for and returns images from e926.net given tags when not blacklisted
@commands.command(aliases=['e9', '9'], brief='e926 | SFW', description='e926 | SFW\nTag-based search for e926.net\n\nYou can only search 5 tags and 6 images at once for now.\ne9 [tags...] ([# of images])')
@checks.del_ctx()
async def e926(self, ctx, *args):
user = ctx.author
args = list(args)
limit = 1
@ -568,13 +570,13 @@ class MsG:
@favorites.command(name='get', aliases=['g'])
async def _get_favorites(self, ctx):
user = ctx.message.author
user = ctx.author
await ctx.send('{}**\'s favorites:**\n```\n{}```'.format(user.mention, formatter.tostring(self.favorites.get(user.id, set()))))
@favorites.command(name='add', aliases=['a'])
async def _add_favorites(self, ctx, *tags):
user = ctx.message.author
user = ctx.author
self.favorites.setdefault(user.id, set()).update(tags)
u.dump(self.favorites, 'cogs/favorites.pkl')
@ -583,7 +585,7 @@ class MsG:
@favorites.command(name='remove', aliases=['r'])
async def _remove_favorites(self, ctx, *tags):
user = ctx.message.author
user = ctx.author
try:
for tag in tags:
@ -602,7 +604,7 @@ class MsG:
@favorites.command(name='clear', aliases=['c'])
async def _clear_favorites(self, ctx):
user = ctx.message.author
user = ctx.author
del self.favorites[user.id]
@ -633,23 +635,23 @@ class MsG:
@_get_blacklist.command(name='channel', aliases=['ch', 'c'])
async def __get_channel_blacklist(self, ctx):
guild = ctx.message.guild if isinstance(
ctx.message.guild, d.Guild) else ctx.message.channel
channel = ctx.message.channel
guild = ctx.guild if isinstance(
ctx.guild, d.Guild) else ctx.channel
channel = ctx.channel
await ctx.send('🚫 {} **blacklist:**\n```\n{}```'.format(channel.mention, formatter.tostring(self.blacklists['guild_blacklist'].get(guild.id, {}).get(channel.id, set()))))
@_get_blacklist.command(name='me', aliases=['m'])
async def __get_user_blacklist(self, ctx):
user = ctx.message.author
user = ctx.author
await ctx.send('🚫 {}**\'s blacklist:**\n```\n{}```'.format(user.mention, formatter.tostring(self.blacklists['user_blacklist'].get(user.id, set()))), delete_after=10)
@_get_blacklist.command(name='here', aliases=['h'])
async def __get_here_blacklists(self, ctx):
guild = ctx.message.guild if isinstance(
ctx.message.guild, d.Guild) else ctx.message.channel
channel = ctx.message.channel
guild = ctx.guild if isinstance(
ctx.guild, d.Guild) else ctx.channel
channel = ctx.channel
await ctx.send('🚫 **__Blacklisted:__**\n\n**Global:**\n```\n{}```\n**{}:**\n```\n{}```'.format(formatter.tostring(self.blacklists['global_blacklist']), channel.mention, formatter.tostring(self.blacklists['guild_blacklist'].get(guild.id, {}).get(channel.id, set()))))
@ -661,8 +663,8 @@ class MsG:
@__get_all_blacklists.command(name='guild', aliases=['g'])
@commands.has_permissions(manage_channels=True)
async def ___get_all_guild_blacklists(self, ctx):
guild = ctx.message.guild if isinstance(
ctx.message.guild, d.Guild) else ctx.message.channel
guild = ctx.guild if isinstance(
ctx.guild, d.Guild) else ctx.channel
await ctx.send('🚫 **__{} blacklists:__**\n\n{}'.format(guild.name, formatter.dict_tostring(self.blacklists['guild_blacklist'].get(guild.id, {}))))
@ -693,9 +695,9 @@ class MsG:
@_add_tags.command(name='channel', aliases=['ch', 'c'])
@commands.has_permissions(manage_channels=True)
async def __add_channel_tags(self, ctx, *tags):
guild = ctx.message.guild if isinstance(
ctx.message.guild, d.Guild) else ctx.message.channel
channel = ctx.message.channel
guild = ctx.guild if isinstance(
ctx.guild, d.Guild) else ctx.channel
channel = ctx.channel
self.blacklists['guild_blacklist'].setdefault(
guild.id, {}).setdefault(channel.id, set()).update(tags)
@ -711,7 +713,7 @@ class MsG:
@_add_tags.command(name='me', aliases=['m'])
async def __add_user_tags(self, ctx, *tags):
user = ctx.message.author
user = ctx.author
self.blacklists['user_blacklist'].setdefault(user.id, set()).update(tags)
for tag in tags:
@ -750,9 +752,9 @@ class MsG:
@_remove_tags.command(name='channel', aliases=['ch', 'c'])
@commands.has_permissions(manage_channels=True)
async def __remove_channel_tags(self, ctx, *tags):
guild = ctx.message.guild if isinstance(
ctx.message.guild, d.Guild) else ctx.message.channel
channel = ctx.message.channel
guild = ctx.guild if isinstance(
ctx.guild, d.Guild) else ctx.channel
channel = ctx.channel
try:
for tag in tags:
@ -771,7 +773,7 @@ class MsG:
@_remove_tags.command(name='me', aliases=['m'])
async def __remove_user_tags(self, ctx, *tags):
user = ctx.message.author
user = ctx.author
try:
for tag in tags:
@ -804,9 +806,9 @@ class MsG:
@_clear_blacklist.command(name='channel', aliases=['ch', 'c'])
@commands.has_permissions(manage_channels=True)
async def __clear_channel_blacklist(self, ctx):
guild = ctx.message.guild if isinstance(
ctx.message.guild, d.Guild) else ctx.message.channel
channel = ctx.message.channel
guild = ctx.guild if isinstance(
ctx.guild, d.Guild) else ctx.channel
channel = ctx.channel
del self.blacklists['guild_blacklist'][str(guild.id)][channel.id]
u.dump(self.blacklists, 'cogs/blacklists.pkl')
@ -815,7 +817,7 @@ class MsG:
@_clear_blacklist.command(name='me', aliases=['m'])
async def __clear_user_blacklist(self, ctx):
user = ctx.message.author
user = ctx.author
del self.blacklists['user_blacklist'][user.id]
u.dump(self.blacklists, 'cogs/blacklists.pkl')

View file

@ -14,7 +14,7 @@ class Info:
@commands.command(hidden=True)
async def hi(ctx):
user = ctx.message.author
user = ctx.author
hello = 'Hewwo, {}.'.format(user.mention)
if user.id == checks.owner_id:

View file

@ -34,7 +34,7 @@ class Administration:
# pass
# @_all.group(name='user')
# async def __user(self, ctx, user: d.Member):
# channels = ctx.message.guild.text_channels
# channels = ctx.guild.text_channels
# bulk_history = {}
# bulk = {}
# history = []
@ -58,7 +58,7 @@ class Administration:
# await channel.delete_messages(chunk)
# await del_sent.edit(content='🗑 **Deleted** `' + str(c) + '/' + str(sum([len(v) for v in bulk.values()])) + '` **messages.**')
# await asyncio.sleep(5)
# await ctx.send('✅ `' + str(sum([len(v) for v in bulk.values()])) + '` **of** <@' + uid + '>**\'s messages deleted from** ' + ctx.message.guild.name + '**.**')
# await ctx.send('✅ `' + str(sum([len(v) for v in bulk.values()])) + '` **of** <@' + uid + '>**\'s messages deleted from** ' + ctx.guild.name + '**.**')
# for channel in channels:
# history.extend(await channel.history(limit=None, before=dt.datetime.utcnow() - dt.timedelta(days=14)).flatten())
# await ch_sent.edit(content='🗄 **Cached** `' + str(channels.index(channel) + 1) + '/' + str(len(channels)) + '` **channels.**')
@ -69,14 +69,14 @@ class Administration:
@checks.del_ctx()
async def prune_all_user(self, ctx, uid, when=None, reference=None):
def yes(msg):
if msg.content.lower() == 'y' and msg.channel is ctx.message.channel and msg.author is ctx.message.author:
if msg.content.lower() == 'y' and msg.channel is ctx.channel and msg.author is ctx.author:
return True
elif msg.content.lower() == 'n' and msg.channel is ctx.message.channel and msg.author is ctx.message.author:
elif msg.content.lower() == 'n' and msg.channel is ctx.channel and msg.author is ctx.author:
raise exc.CheckFail
else:
return False
channels = ctx.message.guild.text_channels
channels = ctx.guild.text_channels
if reference is not None:
for channel in channels:
try:
@ -123,7 +123,7 @@ class Administration:
# print('Deleted {}/{} messages.'.format(history.index(message) + 1, len(history)))
await del_sent.edit(content='🗑 **Deleted** `{}/{}` **messages.**'.format(history.index(message) + 1, len(history)))
await asyncio.sleep(self.RATE_LIMIT)
await del_sent.edit(content='🗑 `{}` **of** <@{}>**\'s messages deleted from** {}**.**'.format(len(history), uid, ctx.message.guild.name))
await del_sent.edit(content='🗑 `{}` **of** <@{}>**\'s messages deleted from** {}**.**'.format(len(history), uid, ctx.guild.name))
except exc.CheckFail:
await ctx.send('❌ **Deletion aborted.**', delete_after=10)
except TimeoutError:
@ -164,7 +164,7 @@ class Administration:
@commands.has_permissions(administrator=True)
@checks.del_ctx()
async def auto_delete(self, ctx):
channel = ctx.message.channel
channel = ctx.channel
try:
if channel.id not in u.tasks.setdefault('management', {}).setdefault('auto_delete', []):

View file

@ -32,26 +32,22 @@ class Bot:
# loop = self.bot.loop.all_tasks()
# for task in loop:
# task.cancel()
if u.session:
await u.session.close()
await self.bot.logout()
await self.bot.close()
print('- - - - - - -')
print('DISCONNECTED')
print('\n/ / / / / / / / / / / /\nD I S C O N N E C T E D\n\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\\n')
# u.notify('D I S C O N N E C T E D')
@commands.command(name=',restart', aliases=[',res', ',r'], hidden=True)
@commands.is_owner()
@checks.del_ctx()
async def restart(self, ctx):
print('RESTARTING')
print('- - - - - - -')
print('\n| | | | | | | | | |\nR E S T A R T I N G\n| | | | | | | | | |\n')
if isinstance(self.bot.get_channel(u.config['startup_channel']), d.TextChannel):
await self.bot.get_channel(u.config['shutdown_channel']).send('**Restarting...** 💤')
# u.notify('R E S T A R T I N G')
# loop = self.bot.loop.all_tasks()
# for task in loop:
# task.cancel()
if u.session:
await u.session.close()
await self.bot.logout()
await self.bot.close()
os.execl(sys.executable, 'python3', 'run.py')
@ -109,9 +105,9 @@ class Tools:
@checks.del_ctx()
async def console(self, ctx):
def execute(msg):
if msg.content == 'exit' and msg.author is ctx.message.author:
if msg.content == 'exit' and msg.author is ctx.author:
raise exc.Abort
elif msg.author is ctx.message.author and msg.channel is ctx.message.channel:
elif msg.author is ctx.author and msg.channel is ctx.channel:
return True
else:
return False

View file

@ -37,10 +37,10 @@ class Utils:
async def last_command(self, ctx):
global command_dict
if command_dict.get(str(ctx.message.author.id), {}).get('args', None) is not None:
args = command_dict.get(str(ctx.message.author.id), {})['args']
if command_dict.get(str(ctx.author.id), {}).get('args', None) is not None:
args = command_dict.get(str(ctx.author.id), {})['args']
print(command_dict)
await ctx.invoke(command_dict.get(str(ctx.message.author.id), {}).get('command', None), args)
await ctx.invoke(command_dict.get(str(ctx.author.id), {}).get('command', None), args)
# [prefix]ping -> Pong!
@commands.command(aliases=['p'], brief='Pong!', description='Returns latency from bot to Discord servers, not to user')
@ -48,8 +48,8 @@ class Utils:
async def ping(self, ctx):
global command_dict
await ctx.send(ctx.message.author.mention + ' 🏓 `' + str(round(self.bot.latency * 1000)) + 'ms`', delete_after=5)
command_dict.setdefault(str(ctx.message.author.id), {}).update({'command': ctx.command})
await ctx.send(ctx.author.mention + ' 🏓 `' + str(round(self.bot.latency * 1000)) + 'ms`', delete_after=5)
command_dict.setdefault(str(ctx.author.id), {}).update({'command': ctx.command})
@commands.command(aliases=['pre'], brief='List bot prefixes', description='Shows all used prefixes')
@checks.del_ctx()

View file

@ -1,6 +1,10 @@
base = '⚠️ **An internal error has occurred.** Please notify my master! 🐺'
async def send_error(ctx, error):
await ctx.send('{}\n```\n{}```'.format(base, error))
class Left(Exception):
pass

View file

@ -6,7 +6,6 @@ import subprocess
import sys
import traceback as tb
import aiohttp as aio
import discord as d
from discord import utils
from discord.ext import commands
@ -32,33 +31,33 @@ async def on_ready():
bot.add_cog(info.Info(bot))
bot.add_cog(booru.MsG(bot))
u.session = aio.ClientSession(loop=bot.loop)
# bot.loop.create_task(u.clear(booru.temp_urls, 30*60))
if isinstance(bot.get_channel(u.config['startup_channel']), d.TextChannel):
await bot.get_channel(u.config['startup_channel']).send('**Started.** ☀️')
print('CONNECTED')
print(bot.user.name)
print('- - - - - - -')
print('\n\\ \\ \\ \\ \\ \\ \\ \\ \\\nC O N N E C T E D : {}\n/ / / / / / / / /\n'.format(bot.user.name))
# u.notify('C O N N E C T E D')
@bot.event
async def on_error(error):
if u.session:
await u.session.close()
await bot.logout()
await bot.close()
print('- - - - - - -')
print('ERROR')
print('\n! ! ! ! !\nE R R O R : {}\n! ! ! ! !\n'.format(error), file=sys.stderr)
tb.print_exc()
# u.notify('E R R O R')
@bot.event
async def on_command_error(ctx, error):
if not isinstance(error, commands.errors.CommandNotFound):
print('\n! ! ! ! ! ! ! ! ! ! ! !\nC O M M A N D E R R O R : {}\n! ! ! ! ! ! ! ! ! ! ! !\n'.format(
error), file=sys.stderr)
tb.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
await ctx.send('{}\n```\n{}```'.format(exc.base, error))
await exc.send_error(ctx, error)
# u.notify('C O M M A N D E R R O R')
else:
print('INVALID COMMAND : {}'.format(error), file=sys.stderr)
async def on_reaction_add(r, u):

View file

@ -1,4 +1,3 @@
import aiohttp as aio
from bs4 import BeautifulSoup
from lxml import html
@ -8,10 +7,13 @@ from utils import utils as u
async def check_match(url):
r = await u.fetch('http://iqdb.harry.lu/?url={}'.format(url))
soup = BeautifulSoup(await r.read(), 'html.parser')
value = soup.find_all('a')[1].get('href')
try:
value = BeautifulSoup(await r.read(), 'html.parser').find_all('a')[1].get('href')
except IndexError:
raise exc.MatchError
if value != '#':
return value
else:
raise exc.MatchError(value)
raise exc.MatchError

View file

@ -2,31 +2,39 @@ import asyncio
import json
import os
import pickle as pkl
import subprocess
import aiohttp as aio
import aiohttp
from pync import Notifier
print('\nPID : {}\n'.format(os.getpid()))
# def notify(message):
# subprocess.run(['terminal-notifier', '-message', message, '-title',
# 'Modumind', '-activate', 'com.apple.Terminal', '-appIcon', 'icon.png', '-sound', 'Ping'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print('PID {}'.format(os.getpid()))
try:
with open('config.json') as infile:
config = json.load(infile)
print('\"config.json\" loaded.')
print('config.json loaded.')
except FileNotFoundError:
with open('config.json', 'w') as outfile:
json.dump({'client_id': 0, 'listed_ids': [0], 'owner_id': 0, 'permissions': 126016, 'prefix': ',',
'shutdown_channel': 0, 'startup_channel': 0, 'token': 'str'}, outfile, indent=4, sort_keys=True)
raise FileNotFoundError(
'Config file not found: \"config.json\" created with abstract values. Restart \"run.py\" with correct values.')
'Config file not found: config.json created with abstract values. Restart run.py with correct values.')
def setdefault(filename, default=None):
try:
with open(filename, 'rb') as infile:
print('\"{}\" loaded.'.format(filename))
print('{} loaded.'.format(filename))
return pkl.load(infile)
except FileNotFoundError:
with open(filename, 'wb+') as iofile:
print('File not found: \"{}\" created and loaded with default values.'.format(filename))
print('File not found: {} created and loaded with default values.'.format(filename))
pkl.dump(default, iofile)
iofile.seek(0)
return pkl.load(iofile)
@ -61,14 +69,9 @@ async def clear(obj, interval=10 * 60, replace=None):
asyncio.sleep(interval)
session = None
HEADERS = {'user-agent': 'Modumind/0.0.1 (Myned)'}
async def fetch(url, *, params={}, json=False):
global session, HEADERS
async with session.get(url, params=params, headers=HEADERS) as r:
if json is True:
return await r.json()
return r
async with aiohttp.ClientSession() as session:
async with session.get(url, params=params, headers={'user-agent': 'Modumind/0.0.1 (Myned)'}) as r:
if json is True:
return await r.json()
return r