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:
commit
5eed4f3dcf
10 changed files with 1861 additions and 1778 deletions
File diff suppressed because it is too large
Load diff
|
@ -10,40 +10,40 @@ from utils import utils as u
|
||||||
|
|
||||||
class Info:
|
class Info:
|
||||||
|
|
||||||
def __init__(self, bot):
|
def __init__(self, bot):
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
|
|
||||||
# @commands.command(name='helptest', aliases=['h'], hidden=True)
|
# @commands.command(name='helptest', aliases=['h'], hidden=True)
|
||||||
# async def list_commands(self, ctx):
|
# async def list_commands(self, ctx):
|
||||||
# embed = d.Embed(title='All possible commands:', color=ctx.me.color)
|
# embed = d.Embed(title='All possible commands:', color=ctx.me.color)
|
||||||
# embed.set_author(name=ctx.me.display_name, icon_url=ctx.me.avatar_url)
|
# embed.set_author(name=ctx.me.display_name, icon_url=ctx.me.avatar_url)
|
||||||
# embed.add_field(
|
# embed.add_field(
|
||||||
# name='Booru', value='\n{}bl umbrella command for managing blacklists'.format(u.config['prefix']))
|
# name='Booru', value='\n{}bl umbrella command for managing blacklists'.format(u.config['prefix']))
|
||||||
#
|
#
|
||||||
# await ctx.send(embed=embed)
|
# await ctx.send(embed=embed)
|
||||||
|
|
||||||
@commands.command(hidden=True)
|
@commands.command(hidden=True)
|
||||||
async def hi(self, ctx, *args):
|
async def hi(self, ctx, *args):
|
||||||
dest = u.get_kwargs(ctx, args)
|
dest = u.get_kwargs(ctx, args)
|
||||||
|
|
||||||
hello = 'Hewwo, {}.'.format(ctx.author.mention)
|
hello = 'Hewwo, {}.'.format(ctx.author.mention)
|
||||||
if ctx.author.id == checks.owner_id:
|
if ctx.author.id == checks.owner_id:
|
||||||
hello += '.. ***Master.*** uwu'
|
hello += '.. ***Master.*** uwu'
|
||||||
elif ctx.author.guild_permissions.administrator:
|
elif ctx.author.guild_permissions.administrator:
|
||||||
hello = '{} **Admin** {}'.format(hello[:7], hello[7:])
|
hello = '{} **Admin** {}'.format(hello[:7], hello[7:])
|
||||||
elif ctx.author.guild_permissions.ban_members:
|
elif ctx.author.guild_permissions.ban_members:
|
||||||
hello = '{} **Mod** {}'.format(hello[:7], hello[7:])
|
hello = '{} **Mod** {}'.format(hello[:7], hello[7:])
|
||||||
await dest.send(hello)
|
await dest.send(hello)
|
||||||
|
|
||||||
@commands.group(name='info', aliases=['i'])
|
@commands.group(name='info', aliases=['i'])
|
||||||
async def info(self, ctx):
|
async def info(self, ctx):
|
||||||
if invoked_subcommand is None:
|
if invoked_subcommand is None:
|
||||||
await ctx.send('<embed>BOT INFO</embed>')
|
await ctx.send('<embed>BOT INFO</embed>')
|
||||||
|
|
||||||
@info.command(aliases=['g', 'server', 's'], brief='Provides info about a guild', hidden=True)
|
@info.command(aliases=['g', 'server', 's'], brief='Provides info about a guild', hidden=True)
|
||||||
async def guild(self, ctx):
|
async def guild(self, ctx):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@info.command(aliases=['u', 'member', 'm'], brief='Provides info about a user', hidden=True)
|
@info.command(aliases=['u', 'member', 'm'], brief='Provides info about a user', hidden=True)
|
||||||
async def user(self, ctx):
|
async def user(self, ctx):
|
||||||
pass
|
pass
|
||||||
|
|
|
@ -13,168 +13,180 @@ from utils import utils as u
|
||||||
|
|
||||||
class Administration:
|
class Administration:
|
||||||
|
|
||||||
def __init__(self, bot):
|
def __init__(self, bot):
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
self.RATE_LIMIT = u.RATE_LIMIT
|
self.RATE_LIMIT = u.RATE_LIMIT
|
||||||
self.queue = asyncio.Queue()
|
self.queue = asyncio.Queue()
|
||||||
self.deleting = False
|
|
||||||
|
|
||||||
if u.tasks['auto_del']:
|
|
||||||
for channel in u.tasks['auto_del']:
|
|
||||||
temp = self.bot.get_channel(channel)
|
|
||||||
self.bot.loop.create_task(self.queue_for_deletion(temp))
|
|
||||||
print('AUTO-DELETING : #{}'.format(temp.id))
|
|
||||||
self.bot.loop.create_task(self.delete())
|
|
||||||
self.deleting = True
|
|
||||||
|
|
||||||
@commands.command(name=',prunefromguild', aliases=[',pfg', ',prunefromserver', ',pfs'], brief='Prune a user\'s messages from the guild', description='about flag centers on message 50 of 101 messages\n\npfg \{user id\} [before|after|about] [\{message id\}]\n\nExample:\npfg \{user id\} before \{message id\}')
|
|
||||||
@commands.is_owner()
|
|
||||||
@checks.del_ctx()
|
|
||||||
async def prune_all_user(self, ctx, user, when=None, reference=None):
|
|
||||||
def yes(msg):
|
|
||||||
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.channel and msg.author is ctx.author:
|
|
||||||
raise exc.CheckFail
|
|
||||||
else:
|
|
||||||
return False
|
|
||||||
|
|
||||||
channels = ctx.guild.text_channels
|
|
||||||
if reference is not None:
|
|
||||||
for channel in channels:
|
|
||||||
try:
|
|
||||||
ref = await channel.get_message(reference)
|
|
||||||
|
|
||||||
except err.NotFound:
|
|
||||||
continue
|
|
||||||
|
|
||||||
history = []
|
|
||||||
try:
|
|
||||||
pru_sent = await ctx.send('\N{HOURGLASS} **Pruning** <@{}>**\'s messages will take some time.**'.format(user))
|
|
||||||
ch_sent = await ctx.send('\N{FILE CABINET} **Caching channels...**')
|
|
||||||
|
|
||||||
if when is None:
|
|
||||||
for channel in channels:
|
|
||||||
async for message in channel.history(limit=None):
|
|
||||||
if message.author.id == int(user):
|
|
||||||
history.append(message)
|
|
||||||
await ch_sent.edit(content='\N{FILE CABINET} **Cached** `{}/{}` **channels.**'.format(channels.index(channel) + 1, len(channels)))
|
|
||||||
await asyncio.sleep(self.RATE_LIMIT)
|
|
||||||
elif when == 'before':
|
|
||||||
for channel in channels:
|
|
||||||
async for message in channel.history(limit=None, before=ref.created_at):
|
|
||||||
if message.author.id == int(user):
|
|
||||||
history.append(message)
|
|
||||||
await ch_sent.edit(content='\N{FILE CABINET} **Cached** `{}/{}` **channels.**'.format(channels.index(channel) + 1, len(channels)))
|
|
||||||
await asyncio.sleep(self.RATE_LIMIT)
|
|
||||||
elif when == 'after':
|
|
||||||
for channel in channels:
|
|
||||||
async for message in channel.history(limit=None, after=ref.created_at):
|
|
||||||
if message.author.id == int(user):
|
|
||||||
history.append(message)
|
|
||||||
await ch_sent.edit(content='\N{FILE CABINET} **Cached** `{}/{}` **channels.**'.format(channels.index(channel) + 1, len(channels)))
|
|
||||||
await asyncio.sleep(self.RATE_LIMIT)
|
|
||||||
elif when == 'about':
|
|
||||||
for channel in channels:
|
|
||||||
async for message in channel.history(limit=None, about=ref.created_at):
|
|
||||||
if message.author.id == int(user):
|
|
||||||
history.append(message)
|
|
||||||
await ch_sent.edit(content='\N{FILE CABINET} **Cached** `{}/{}` **channels.**'.format(channels.index(channel) + 1, len(channels)))
|
|
||||||
await asyncio.sleep(self.RATE_LIMIT)
|
|
||||||
|
|
||||||
est_sent = await ctx.send('\N{STOPWATCH} **Estimated time to delete history:** `{}m {}s`'.format(int(self.RATE_LIMIT * len(history) / 60), int(self.RATE_LIMIT * len(history) % 60)))
|
|
||||||
cont_sent = await ctx.send('{} **Continue?** `Y` or `N`'.format(ctx.author.mention))
|
|
||||||
await self.bot.wait_for('message', check=yes, timeout=10 * 60)
|
|
||||||
await cont_sent.delete()
|
|
||||||
del_sent = await ctx.send('\N{WASTEBASKET} **Deleting messages...**')
|
|
||||||
await del_sent.pin()
|
|
||||||
c = 0
|
|
||||||
for message in history:
|
|
||||||
with suppress(err.NotFound):
|
|
||||||
await message.delete()
|
|
||||||
c += 1
|
|
||||||
await del_sent.edit(content='\N{WASTEBASKET} **Deleted** `{}/{}` **messages.**'.format(history.index(message) + 1, len(history)))
|
|
||||||
await asyncio.sleep(self.RATE_LIMIT)
|
|
||||||
await del_sent.unpin()
|
|
||||||
|
|
||||||
await ctx.send('\N{WASTEBASKET} `{}` **of** <@{}>**\'s messages left in** {}**.**'.format(len(history) - c, user, ctx.guild.name))
|
|
||||||
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
|
||||||
|
|
||||||
except exc.CheckFail:
|
|
||||||
await ctx.send('**Deletion aborted.**', delete_after=10)
|
|
||||||
await ctx.message.add_reaction('\N{CROSS MARK}')
|
|
||||||
|
|
||||||
except TimeoutError:
|
|
||||||
await ctx.send('**Deletion timed out.**', delete_after=10)
|
|
||||||
await ctx.message.add_reaction('\N{CROSS MARK}')
|
|
||||||
|
|
||||||
async def delete(self):
|
|
||||||
while self.deleting:
|
|
||||||
message = await self.queue.get()
|
|
||||||
await asyncio.sleep(self.RATE_LIMIT)
|
|
||||||
with suppress(err.NotFound):
|
|
||||||
if not message.pinned:
|
|
||||||
await message.delete()
|
|
||||||
|
|
||||||
print('STOPPED : deleting')
|
|
||||||
|
|
||||||
async def queue_for_deletion(self, channel):
|
|
||||||
def check(msg):
|
|
||||||
if msg.content.lower() == 'stop' and msg.channel is channel and msg.author.guild_permissions.administrator:
|
|
||||||
raise exc.Abort
|
|
||||||
elif msg.channel is channel and not msg.pinned:
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
try:
|
|
||||||
async for message in channel.history(limit=None):
|
|
||||||
if message.content.lower() == 'stop' and message.author.guild_permissions.administrator:
|
|
||||||
raise exc.Abort
|
|
||||||
if not message.pinned:
|
|
||||||
await self.queue.put(message)
|
|
||||||
|
|
||||||
while not self.bot.is_closed():
|
|
||||||
message = await self.bot.wait_for('message', check=check)
|
|
||||||
await self.queue.put(message)
|
|
||||||
|
|
||||||
except exc.Abort:
|
|
||||||
u.tasks['auto_del'].remove(channel.id)
|
|
||||||
u.dump(u.tasks, 'cogs/tasks.pkl')
|
|
||||||
if not u.tasks['auto_del']:
|
|
||||||
self.deleting = False
|
self.deleting = False
|
||||||
print('STOPPED : deleting #{}'.format(channel.id))
|
|
||||||
await channel.send('**Stopped queueing messages for deletion in** {}**.**'.format(channel.mention), delete_after=5)
|
|
||||||
|
|
||||||
@commands.command(name='autodelete', aliases=['autodel', 'ad'])
|
if u.tasks['auto_del']:
|
||||||
@commands.has_permissions(administrator=True)
|
for channel in u.tasks['auto_del']:
|
||||||
@checks.del_ctx()
|
temp = self.bot.get_channel(channel)
|
||||||
async def auto_delete(self, ctx):
|
self.bot.loop.create_task(self.queue_for_deletion(temp))
|
||||||
try:
|
print('AUTO-DELETING : #{}'.format(temp.id))
|
||||||
if ctx.channel.id not in u.tasks['auto_del']:
|
self.bot.loop.create_task(self.delete())
|
||||||
u.tasks['auto_del'].append(ctx.channel.id)
|
self.deleting = True
|
||||||
u.dump(u.tasks, 'cogs/tasks.pkl')
|
|
||||||
self.bot.loop.create_task(self.queue_for_deletion(ctx.channel))
|
@commands.command(name=',prunefromguild', aliases=[',pfg', ',prunefromserver', ',pfs'], brief='Prune a user\'s messages from the guild', description='about flag centers on message 50 of 101 messages\n\npfg \{user id\} [before|after|about] [\{message id\}]\n\nExample:\npfg \{user id\} before \{message id\}')
|
||||||
if not self.deleting:
|
@commands.is_owner()
|
||||||
self.bot.loop.create_task(self.delete())
|
@checks.del_ctx()
|
||||||
self.deleting = True
|
async def prune_all_user(self, ctx, user, when=None, reference=None):
|
||||||
print('AUTO-DELETING : #{}'.format(ctx.channel.id))
|
def yes(msg):
|
||||||
await ctx.send('**Auto-deleting all messages in {}.**'.format(ctx.channel.mention), delete_after=5)
|
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.channel and msg.author is ctx.author:
|
||||||
|
raise exc.CheckFail
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
|
||||||
|
channels = ctx.guild.text_channels
|
||||||
|
if reference is not None:
|
||||||
|
for channel in channels:
|
||||||
|
try:
|
||||||
|
ref = await channel.get_message(reference)
|
||||||
|
|
||||||
|
except err.NotFound:
|
||||||
|
continue
|
||||||
|
|
||||||
|
history = []
|
||||||
|
try:
|
||||||
|
pru_sent = await ctx.send('\N{HOURGLASS} **Pruning** <@{}>**\'s messages will take some time.**'.format(user))
|
||||||
|
ch_sent = await ctx.send('\N{FILE CABINET} **Caching channels...**')
|
||||||
|
|
||||||
|
if when is None:
|
||||||
|
for channel in channels:
|
||||||
|
async for message in channel.history(limit=None):
|
||||||
|
if message.author.id == int(user):
|
||||||
|
history.append(message)
|
||||||
|
await ch_sent.edit(content='\N{FILE CABINET} **Cached** `{}/{}` **channels.**'.format(channels.index(channel) + 1, len(channels)))
|
||||||
|
await asyncio.sleep(self.RATE_LIMIT)
|
||||||
|
elif when == 'before':
|
||||||
|
for channel in channels:
|
||||||
|
async for message in channel.history(limit=None, before=ref.created_at):
|
||||||
|
if message.author.id == int(user):
|
||||||
|
history.append(message)
|
||||||
|
await ch_sent.edit(content='\N{FILE CABINET} **Cached** `{}/{}` **channels.**'.format(channels.index(channel) + 1, len(channels)))
|
||||||
|
await asyncio.sleep(self.RATE_LIMIT)
|
||||||
|
elif when == 'after':
|
||||||
|
for channel in channels:
|
||||||
|
async for message in channel.history(limit=None, after=ref.created_at):
|
||||||
|
if message.author.id == int(user):
|
||||||
|
history.append(message)
|
||||||
|
await ch_sent.edit(content='\N{FILE CABINET} **Cached** `{}/{}` **channels.**'.format(channels.index(channel) + 1, len(channels)))
|
||||||
|
await asyncio.sleep(self.RATE_LIMIT)
|
||||||
|
elif when == 'about':
|
||||||
|
for channel in channels:
|
||||||
|
async for message in channel.history(limit=None, about=ref.created_at):
|
||||||
|
if message.author.id == int(user):
|
||||||
|
history.append(message)
|
||||||
|
await ch_sent.edit(content='\N{FILE CABINET} **Cached** `{}/{}` **channels.**'.format(channels.index(channel) + 1, len(channels)))
|
||||||
|
await asyncio.sleep(self.RATE_LIMIT)
|
||||||
|
|
||||||
|
est_sent = await ctx.send('\N{STOPWATCH} **Estimated time to delete history:** `{}m {}s`'.format(int(self.RATE_LIMIT * len(history) / 60), int(self.RATE_LIMIT * len(history) % 60)))
|
||||||
|
cont_sent = await ctx.send('{} **Continue?** `Y` or `N`'.format(ctx.author.mention))
|
||||||
|
await self.bot.wait_for('message', check=yes, timeout=10 * 60)
|
||||||
|
await cont_sent.delete()
|
||||||
|
del_sent = await ctx.send('\N{WASTEBASKET} **Deleting messages...**')
|
||||||
|
await del_sent.pin()
|
||||||
|
c = 0
|
||||||
|
for message in history:
|
||||||
|
with suppress(err.NotFound):
|
||||||
|
await message.delete()
|
||||||
|
c += 1
|
||||||
|
await del_sent.edit(content='\N{WASTEBASKET} **Deleted** `{}/{}` **messages.**'.format(history.index(message) + 1, len(history)))
|
||||||
|
await asyncio.sleep(self.RATE_LIMIT)
|
||||||
|
await del_sent.unpin()
|
||||||
|
|
||||||
|
await ctx.send('\N{WASTEBASKET} `{}` **of** <@{}>**\'s messages left in** {}**.**'.format(len(history) - c, user, ctx.guild.name))
|
||||||
|
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
||||||
|
|
||||||
|
except exc.CheckFail:
|
||||||
|
await ctx.send('**Deletion aborted.**', delete_after=10)
|
||||||
|
await ctx.message.add_reaction('\N{CROSS MARK}')
|
||||||
|
|
||||||
|
except TimeoutError:
|
||||||
|
await ctx.send('**Deletion timed out.**', delete_after=10)
|
||||||
|
await ctx.message.add_reaction('\N{CROSS MARK}')
|
||||||
|
|
||||||
|
async def delete(self):
|
||||||
|
while self.deleting:
|
||||||
|
message = await self.queue.get()
|
||||||
|
await asyncio.sleep(self.RATE_LIMIT)
|
||||||
|
with suppress(err.NotFound):
|
||||||
|
if not message.pinned:
|
||||||
|
await message.delete()
|
||||||
|
|
||||||
|
print('STOPPED : deleting')
|
||||||
|
|
||||||
|
async def queue_for_deletion(self, channel):
|
||||||
|
def check(msg):
|
||||||
|
if msg.content.lower() == 'stop' and msg.channel is channel and msg.author.guild_permissions.administrator:
|
||||||
|
raise exc.Abort
|
||||||
|
elif msg.channel is channel and not msg.pinned:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
async for message in channel.history(limit=None):
|
||||||
|
if message.content.lower() == 'stop' and message.author.guild_permissions.administrator:
|
||||||
|
raise exc.Abort
|
||||||
|
if not message.pinned:
|
||||||
|
await self.queue.put(message)
|
||||||
|
|
||||||
|
while not self.bot.is_closed():
|
||||||
|
message = await self.bot.wait_for('message', check=check)
|
||||||
|
await self.queue.put(message)
|
||||||
|
|
||||||
|
except exc.Abort:
|
||||||
|
u.tasks['auto_del'].remove(channel.id)
|
||||||
|
u.dump(u.tasks, 'cogs/tasks.pkl')
|
||||||
|
if not u.tasks['auto_del']:
|
||||||
|
self.deleting = False
|
||||||
|
print('STOPPED : deleting #{}'.format(channel.id))
|
||||||
|
await channel.send('**Stopped queueing messages for deletion in** {}**.**'.format(channel.mention), delete_after=5)
|
||||||
|
|
||||||
|
@commands.command(name='autodelete', aliases=['autodel', 'ad'])
|
||||||
|
@commands.has_permissions(administrator=True)
|
||||||
|
@checks.del_ctx()
|
||||||
|
async def auto_delete(self, ctx):
|
||||||
|
try:
|
||||||
|
if ctx.channel.id not in u.tasks['auto_del']:
|
||||||
|
u.tasks['auto_del'].append(ctx.channel.id)
|
||||||
|
u.dump(u.tasks, 'cogs/tasks.pkl')
|
||||||
|
self.bot.loop.create_task(self.queue_for_deletion(ctx.channel))
|
||||||
|
if not self.deleting:
|
||||||
|
self.bot.loop.create_task(self.delete())
|
||||||
|
self.deleting = True
|
||||||
|
print('AUTO-DELETING : #{}'.format(ctx.channel.id))
|
||||||
|
await ctx.send('**Auto-deleting all messages in {}.**'.format(ctx.channel.mention), delete_after=5)
|
||||||
|
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
||||||
|
else:
|
||||||
|
raise exc.Exists
|
||||||
|
|
||||||
|
except exc.Exists:
|
||||||
|
await ctx.send('**Already auto-deleting in {}.** Type `stop` to stop.'.format(ctx.channel.mention), delete_after=10)
|
||||||
|
await ctx.message.add_reaction('\N{CROSS MARK}')
|
||||||
|
|
||||||
|
@commands.command(name='deletecommands', aliases=['delcmds'])
|
||||||
|
@commands.has_permissions(administrator=True)
|
||||||
|
async def delete_commands(self, ctx):
|
||||||
|
if ctx.guild.id not in u.settings['del_ctx']:
|
||||||
|
u.settings['del_ctx'].append(ctx.guild.id)
|
||||||
|
else:
|
||||||
|
u.settings['del_ctx'].remove(ctx.guild.id)
|
||||||
|
u.dump(u.settings, 'settings.pkl')
|
||||||
|
|
||||||
|
await ctx.send('**Delete command invocations:** `{}`'.format(ctx.guild.id in u.settings['del_ctx']))
|
||||||
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
||||||
else:
|
|
||||||
raise exc.Exists
|
|
||||||
|
|
||||||
except exc.Exists:
|
@commands.command(name='setprefix', aliases=['setpre', 'spre'])
|
||||||
await ctx.send('**Already auto-deleting in {}.** Type `stop` to stop.'.format(ctx.channel.mention), delete_after=10)
|
@commands.has_permissions(administrator=True)
|
||||||
await ctx.message.add_reaction('\N{CROSS MARK}')
|
async def set_prefix(self, ctx, prefix=None):
|
||||||
|
if prefix is not None:
|
||||||
|
u.settings['prefixes'][ctx.guild.id] = prefix
|
||||||
|
else:
|
||||||
|
with suppress(KeyError):
|
||||||
|
del u.settings['prefixes'][ctx.guild.id]
|
||||||
|
|
||||||
@commands.command(name='deletecommands', aliases=['delcmds'])
|
await ctx.send(f'**Prefix set to:** `{"` or `".join(prefix if ctx.guild.id in u.settings["prefixes"] else u.config["prefix"])}`')
|
||||||
@commands.has_permissions(administrator=True)
|
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
||||||
async def delete_commands(self, ctx):
|
|
||||||
if ctx.guild.id not in u.settings['del_ctx']:
|
|
||||||
u.settings['del_ctx'].append(ctx.guild.id)
|
|
||||||
else:
|
|
||||||
u.settings['del_ctx'].remove(ctx.guild.id)
|
|
||||||
u.dump(u.settings, 'settings.pkl')
|
|
||||||
|
|
||||||
await ctx.send('**Delete command invocations:** `{}`'.format(ctx.guild.id in u.settings['del_ctx']))
|
|
||||||
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
|
||||||
|
|
|
@ -5,6 +5,7 @@ import os
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
import traceback as tb
|
import traceback as tb
|
||||||
|
from contextlib import suppress
|
||||||
|
|
||||||
import discord as d
|
import discord as d
|
||||||
import pyrasite as pyr
|
import pyrasite as pyr
|
||||||
|
@ -14,171 +15,200 @@ from misc import exceptions as exc
|
||||||
from misc import checks
|
from misc import checks
|
||||||
from utils import utils as u
|
from utils import utils as u
|
||||||
|
|
||||||
nl = re.compile('\n')
|
|
||||||
|
|
||||||
|
|
||||||
class Bot:
|
class Bot:
|
||||||
|
|
||||||
def __init__(self, bot):
|
def __init__(self, bot):
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
|
|
||||||
# Close connection to Discord - immediate offline
|
# Close connection to Discord - immediate offline
|
||||||
@commands.command(name=',die', aliases=[',d'], brief='Kills the bot', description='BOT OWNER ONLY\nCloses the connection to Discord', hidden=True)
|
@commands.command(name=',die', aliases=[',d'], brief='Kills the bot', description='BOT OWNER ONLY\nCloses the connection to Discord', hidden=True)
|
||||||
@commands.is_owner()
|
@commands.is_owner()
|
||||||
@checks.del_ctx()
|
@checks.del_ctx()
|
||||||
async def die(self, ctx):
|
async def die(self, ctx):
|
||||||
await ctx.message.add_reaction('\N{NEW MOON SYMBOL}')
|
await ctx.message.add_reaction('\N{NEW MOON SYMBOL}')
|
||||||
|
|
||||||
await self.bot.get_channel(u.config['info_channel']).send('**Shutting down** \N{NEW MOON SYMBOL} . . .')
|
await self.bot.get_channel(u.config['info_channel']).send('**Shutting down** \N{NEW MOON SYMBOL} . . .')
|
||||||
# loop = self.bot.loop.all_tasks()
|
# loop = self.bot.loop.all_tasks()
|
||||||
# for task in loop:
|
# for task in loop:
|
||||||
# task.cancel()
|
# task.cancel()
|
||||||
await self.bot.logout()
|
await self.bot.logout()
|
||||||
u.close(self.bot.loop)
|
u.close(self.bot.loop)
|
||||||
print('\n/ / / / / / / / / / / /\nD I S C O N N E C T E D\n\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\\n')
|
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')
|
# u.notify('D I S C O N N E C T E D')
|
||||||
|
|
||||||
@commands.command(name=',restart', aliases=[',res', ',r'], hidden=True)
|
@commands.command(name=',restart', aliases=[',res', ',r'], hidden=True)
|
||||||
@commands.is_owner()
|
@commands.is_owner()
|
||||||
@checks.del_ctx()
|
@checks.del_ctx()
|
||||||
async def restart(self, ctx):
|
async def restart(self, ctx):
|
||||||
await ctx.message.add_reaction('\N{SLEEPING SYMBOL}')
|
await ctx.message.add_reaction('\N{SLEEPING SYMBOL}')
|
||||||
|
|
||||||
print('\n| | | | | | | | | |\nR E S T A R T I N G\n| | | | | | | | | |\n')
|
print('\n| | | | | | | | | |\nR E S T A R T I N G\n| | | | | | | | | |\n')
|
||||||
await self.bot.get_channel(u.config['info_channel']).send('**Restarting** \N{SLEEPING SYMBOL} . . .')
|
await self.bot.get_channel(u.config['info_channel']).send('**Restarting** \N{SLEEPING SYMBOL} . . .')
|
||||||
# u.notify('R E S T A R T I N G')
|
# u.notify('R E S T A R T I N G')
|
||||||
|
|
||||||
u.temp['restart_ch'] = ctx.channel.id
|
u.temp['restart_ch'] = ctx.channel.id
|
||||||
u.temp['restart_msg'] = ctx.message.id
|
u.temp['restart_msg'] = ctx.message.id
|
||||||
u.dump(u.temp, 'temp.pkl')
|
u.dump(u.temp, 'temp.pkl')
|
||||||
|
|
||||||
# loop = self.bot.loop.all_tasks()
|
# loop = self.bot.loop.all_tasks()
|
||||||
# for task in loop:
|
# for task in loop:
|
||||||
# task.cancel()
|
# task.cancel()
|
||||||
await self.bot.logout()
|
await self.bot.logout()
|
||||||
u.close(self.bot.loop)
|
u.close(self.bot.loop)
|
||||||
os.execl(sys.executable, 'python3', 'run.py')
|
os.execl(sys.executable, 'python3', 'run.py')
|
||||||
|
|
||||||
# Invite bot to bot owner's server
|
# Invite bot to bot owner's server
|
||||||
@commands.command(name=',invite', aliases=[',inv', ',link'], brief='Invite the bot', description='BOT OWNER ONLY\nInvite the bot to a server (Requires admin)', hidden=True)
|
@commands.command(name=',invite', aliases=[',inv', ',link'], brief='Invite the bot', description='BOT OWNER ONLY\nInvite the bot to a server (Requires admin)', hidden=True)
|
||||||
@commands.is_owner()
|
@commands.is_owner()
|
||||||
@checks.del_ctx()
|
@checks.del_ctx()
|
||||||
async def invite(self, ctx):
|
async def invite(self, ctx):
|
||||||
await ctx.message.add_reaction('\N{ENVELOPE}')
|
await ctx.message.add_reaction('\N{ENVELOPE}')
|
||||||
|
|
||||||
await ctx.send('https://discordapp.com/oauth2/authorize?&client_id={}&scope=bot&permissions={}'.format(u.config['client_id'], u.config['permissions']), delete_after=10)
|
await ctx.send('https://discordapp.com/oauth2/authorize?&client_id={}&scope=bot&permissions={}'.format(u.config['client_id'], u.config['permissions']), delete_after=10)
|
||||||
|
|
||||||
@commands.command(name=',status', aliases=[',presence', ',game'], hidden=True)
|
@commands.command(name=',status', aliases=[',presence', ',game'], hidden=True)
|
||||||
@commands.is_owner()
|
@commands.is_owner()
|
||||||
@checks.del_ctx()
|
@checks.del_ctx()
|
||||||
async def status(self, ctx, *, game=None):
|
async def status(self, ctx, *, game=None):
|
||||||
if game is not None:
|
if game is not None:
|
||||||
await self.bot.change_presence(game=d.Game(name=game))
|
await self.bot.change_presence(game=d.Game(name=game))
|
||||||
u.config['playing'] = game
|
u.config['playing'] = game
|
||||||
u.dump(u.config, 'config.json', json=True)
|
u.dump(u.config, 'config.json', json=True)
|
||||||
else:
|
else:
|
||||||
await self.bot.change_presence(game=None)
|
await self.bot.change_presence(game=None)
|
||||||
u.config['playing'] = 'None'
|
u.config['playing'] = 'None'
|
||||||
u.dump(u.config, 'config.json', json=True)
|
u.dump(u.config, 'config.json', json=True)
|
||||||
|
|
||||||
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
||||||
|
|
||||||
|
|
||||||
class Tools:
|
class Tools:
|
||||||
|
|
||||||
def __init__(self, bot):
|
def __init__(self, bot):
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
|
|
||||||
def format(self, i='', o=''):
|
def format(self, i='', o=''):
|
||||||
if len(o) > 1:
|
if len(o) > 1:
|
||||||
return '>>> {}\n{}'.format(i, o)
|
return '>>> {}\n{}'.format(i, o)
|
||||||
else:
|
else:
|
||||||
return '>>> {}'.format(i)
|
return '>>> {}'.format(i)
|
||||||
|
|
||||||
async def generate(self, d, i='', o=''):
|
async def generate(self, d, i='', o=''):
|
||||||
return await d.send('```python\n{}```'.format(self.format(i, o)))
|
return await d.send('```python\n{}```'.format(self.format(i, o)))
|
||||||
|
|
||||||
async def refresh(self, m, i='', o=''):
|
async def refresh(self, m, i='', o=''):
|
||||||
global nl
|
output = m.content[9:-3]
|
||||||
output = m.content[10:-2]
|
if len(re.findall('\n', output)) <= 20:
|
||||||
if len(nl.findall(output)) <= 20:
|
await m.edit(content='```python\n{}\n{}\n>>>```'.format(output, self.format(i, o)))
|
||||||
await m.edit(content='```python\n{}\n{}\n>>>```'.format(output, self.format(i, o)))
|
else:
|
||||||
else:
|
await m.edit(content='```python\n{}```'.format(self.format(i, o)))
|
||||||
await m.edit(content='```python\n{}```'.format(self.format(i, o)))
|
|
||||||
|
|
||||||
async def generate_err(self, d, o=''):
|
async def generate_err(self, d, o=''):
|
||||||
return await d.send('```\n{}```'.format(o))
|
return await d.send('```\n{}```'.format(o))
|
||||||
|
|
||||||
async def refresh_err(self, m, o=''):
|
async def refresh_err(self, m, o=''):
|
||||||
await m.edit(content='```\n{}```'.format(o))
|
await m.edit(content='```\n{}```'.format(o))
|
||||||
|
|
||||||
@commands.command(name=',console', aliases=[',con', ',c'], hidden=True)
|
@commands.command(name=',console', aliases=[',con', ',c'], hidden=True)
|
||||||
@commands.is_owner()
|
@commands.is_owner()
|
||||||
@checks.del_ctx()
|
@checks.del_ctx()
|
||||||
async def console(self, ctx):
|
async def console(self, ctx):
|
||||||
def execute(msg):
|
def execute(msg):
|
||||||
if msg.content == 'exit' and msg.author is ctx.author:
|
if msg.content.startswith('exe') and msg.author is ctx.author and msg.channel is ctx.channel:
|
||||||
raise exc.Abort
|
results.cancel()
|
||||||
elif msg.author is ctx.author and msg.channel is ctx.channel:
|
return True
|
||||||
return True
|
return False
|
||||||
else:
|
|
||||||
return False
|
|
||||||
|
|
||||||
try:
|
def evaluate(msg):
|
||||||
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
if msg.content.startswith('eval') and msg.author is ctx.author and msg.channel is ctx.channel:
|
||||||
|
results.cancel()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def exit(reaction, user):
|
||||||
|
if reaction.emoji == '\N{LEFTWARDS ARROW WITH HOOK}' and user is ctx.author and reaction.message.id == ctx.message.id:
|
||||||
|
results.cancel()
|
||||||
|
raise exc.Abort
|
||||||
|
return False
|
||||||
|
|
||||||
console = await self.generate(ctx)
|
|
||||||
exception = await self.generate_err(ctx)
|
|
||||||
while not self.bot.is_closed():
|
|
||||||
try:
|
try:
|
||||||
exe = await self.bot.wait_for('message', check=execute)
|
console = await self.generate(ctx)
|
||||||
|
exception = await self.generate_err(ctx)
|
||||||
|
|
||||||
|
await ctx.message.add_reaction('\N{LEFTWARDS ARROW WITH HOOK}')
|
||||||
|
|
||||||
|
while not self.bot.is_closed():
|
||||||
|
try:
|
||||||
|
results = await asyncio.gather([self.bot.wait_for('message', check=execute), self.bot.wait_for('message', check=evaluate), self.bot.wait_for('reaction_add', check=exit)], return_exceptions=True)
|
||||||
|
print(results)
|
||||||
|
except exc.Execute:
|
||||||
|
try:
|
||||||
|
sys.stdout = io.StringIO()
|
||||||
|
sys.stderr = io.StringIO()
|
||||||
|
exec(exe.content)
|
||||||
|
|
||||||
|
except Exception:
|
||||||
|
await self.refresh_err(exception, tb.format_exc(limit=1))
|
||||||
|
|
||||||
|
finally:
|
||||||
|
await self.refresh(console, exe.content, sys.stdout.getvalue() if sys.stdout.getvalue() != console.content else None)
|
||||||
|
sys.stdout = sys.__stdout__
|
||||||
|
sys.stderr = sys.__stderr__
|
||||||
|
|
||||||
|
except exc.Evaluate:
|
||||||
|
try:
|
||||||
|
sys.stdout = io.StringIO()
|
||||||
|
sys.stderr = io.StringIO()
|
||||||
|
eval(exe.content)
|
||||||
|
|
||||||
|
except Exception:
|
||||||
|
await self.refresh_err(exception, tb.format_exc(limit=1))
|
||||||
|
|
||||||
|
finally:
|
||||||
|
await self.refresh(console, exe.content, sys.stdout.getvalue() if sys.stdout.getvalue() != console.content else None)
|
||||||
|
sys.stdout = sys.__stdout__
|
||||||
|
sys.stderr = sys.__stderr__
|
||||||
|
|
||||||
|
finally:
|
||||||
|
with suppress(d.NotFound):
|
||||||
|
await exe.delete()
|
||||||
|
|
||||||
except exc.Abort:
|
except exc.Abort:
|
||||||
raise exc.Abort
|
pass
|
||||||
await exe.delete()
|
|
||||||
try:
|
|
||||||
sys.stdout = io.StringIO()
|
|
||||||
sys.stderr = io.StringIO()
|
|
||||||
exec(exe.content)
|
|
||||||
except Exception:
|
|
||||||
await self.refresh_err(exception, tb.format_exc(limit=1))
|
|
||||||
finally:
|
finally:
|
||||||
await self.refresh(console, exe.content, sys.stdout.getvalue())
|
sys.stdout = sys.__stdout__
|
||||||
sys.stdout = sys.__stdout__
|
sys.stderr = sys.__stderr__
|
||||||
sys.stderr = sys.__stderr__
|
print('Reset sys output.')
|
||||||
except exc.Abort:
|
|
||||||
await ctx.send('\N{LEFTWARDS ARROW WITH HOOK} **Exited console.**')
|
|
||||||
finally:
|
|
||||||
sys.stdout = sys.__stdout__
|
|
||||||
sys.stderr = sys.__stderr__
|
|
||||||
print('Reset sys output.')
|
|
||||||
|
|
||||||
@commands.command(name='arbitrary', aliases=[',arbit', ',ar'])
|
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
||||||
@commands.is_owner()
|
|
||||||
@checks.del_ctx()
|
|
||||||
async def arbitrary(self, ctx, *, exe):
|
|
||||||
try:
|
|
||||||
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
|
||||||
|
|
||||||
sys.stdout = io.StringIO()
|
@commands.command(name='arbitrary', aliases=[',arbit', ',ar'])
|
||||||
exec(exe)
|
@commands.is_owner()
|
||||||
await self.generate(ctx, exe, sys.stdout.getvalue())
|
@checks.del_ctx()
|
||||||
except Exception:
|
async def arbitrary(self, ctx, *, exe):
|
||||||
await ctx.send('```\n{}```'.format(tb.format_exc(limit=1)))
|
try:
|
||||||
tb.print_exc(limit=1)
|
sys.stdout = io.StringIO()
|
||||||
finally:
|
exec(exe)
|
||||||
sys.stdout = sys.__stdout__
|
await self.generate(ctx, exe, sys.stdout.getvalue())
|
||||||
print('Reset stdout.')
|
except Exception:
|
||||||
|
await ctx.send('```\n{}```'.format(tb.format_exc(limit=1)))
|
||||||
|
finally:
|
||||||
|
sys.stdout = sys.__stdout__
|
||||||
|
print('Reset stdout.')
|
||||||
|
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
||||||
|
|
||||||
@commands.group(aliases=[',db'], hidden=True)
|
@commands.group(aliases=[',db'], hidden=True)
|
||||||
@commands.is_owner()
|
@commands.is_owner()
|
||||||
@checks.del_ctx()
|
@checks.del_ctx()
|
||||||
async def debug(self, ctx):
|
async def debug(self, ctx):
|
||||||
console = await self.generate(ctx)
|
console = await self.generate(ctx)
|
||||||
|
|
||||||
@debug.command(name='inject', aliases=['inj'])
|
@debug.command(name='inject', aliases=['inj'])
|
||||||
async def _inject(self, ctx, *, input_):
|
async def _inject(self, ctx, *, input_):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@debug.command(name='inspect', aliases=['ins'])
|
@debug.command(name='inspect', aliases=['ins'])
|
||||||
async def _inspect(self, ctx, *, input_):
|
async def _inspect(self, ctx, *, input_):
|
||||||
pass
|
pass
|
||||||
|
|
|
@ -30,88 +30,88 @@ command_dict = {}
|
||||||
|
|
||||||
class Utils:
|
class Utils:
|
||||||
|
|
||||||
def __init__(self, bot):
|
def __init__(self, bot):
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
|
|
||||||
@commands.command(name='last', aliases=['l', ','], brief='Reinvokes last command', description='Reinvokes previous command executed', hidden=True)
|
@commands.command(name='last', aliases=['l', ','], brief='Reinvokes last command', description='Reinvokes previous command executed', hidden=True)
|
||||||
async def last_command(self, ctx):
|
async def last_command(self, ctx):
|
||||||
global command_dict
|
global command_dict
|
||||||
|
|
||||||
if command_dict.get(str(ctx.author.id), {}).get('args', None) is not None:
|
if command_dict.get(str(ctx.author.id), {}).get('args', None) is not None:
|
||||||
args = command_dict.get(str(ctx.author.id), {})['args']
|
args = command_dict.get(str(ctx.author.id), {})['args']
|
||||||
print(command_dict)
|
print(command_dict)
|
||||||
await ctx.invoke(command_dict.get(str(ctx.author.id), {}).get('command', None), args)
|
await ctx.invoke(command_dict.get(str(ctx.author.id), {}).get('command', None), args)
|
||||||
|
|
||||||
# Displays latency
|
# Displays latency
|
||||||
@commands.command(aliases=['p'], brief='Pong!', description='Returns latency from bot to Discord servers, not to user')
|
@commands.command(aliases=['p'], brief='Pong!', description='Returns latency from bot to Discord servers, not to user')
|
||||||
@checks.del_ctx()
|
@checks.del_ctx()
|
||||||
async def ping(self, ctx):
|
async def ping(self, ctx):
|
||||||
global command_dict
|
global command_dict
|
||||||
|
|
||||||
await ctx.message.add_reaction('\N{TABLE TENNIS PADDLE AND BALL}')
|
await ctx.message.add_reaction('\N{TABLE TENNIS PADDLE AND BALL}')
|
||||||
|
|
||||||
await ctx.send(ctx.author.mention + ' \N{TABLE TENNIS PADDLE AND BALL} `' + str(round(self.bot.latency * 1000)) + 'ms`', delete_after=5)
|
await ctx.send(ctx.author.mention + ' \N{TABLE TENNIS PADDLE AND BALL} `' + str(round(self.bot.latency * 1000)) + 'ms`', delete_after=5)
|
||||||
command_dict.setdefault(str(ctx.author.id), {}).update({'command': ctx.command})
|
command_dict.setdefault(str(ctx.author.id), {}).update({'command': ctx.command})
|
||||||
|
|
||||||
@commands.command(aliases=['pre'], brief='List bot prefixes', description='Shows all used prefixes')
|
@commands.command(aliases=['pre'], brief='List bot prefixes', description='Shows all used prefixes')
|
||||||
@checks.del_ctx()
|
@checks.del_ctx()
|
||||||
async def prefix(self, ctx):
|
async def prefix(self, ctx):
|
||||||
await ctx.send('**Prefix:** `{}`'.format(u.config['prefix']))
|
await ctx.send('**Prefix:** `{}`'.format('` or `'.join(u.settings['prefixes'][ctx.guild.id] if ctx.guild.id in u.settings['prefixes'] else u.config['prefix'])))
|
||||||
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
||||||
|
|
||||||
@commands.group(name=',send', aliases=[',s'], hidden=True)
|
@commands.group(name=',send', aliases=[',s'], hidden=True)
|
||||||
@commands.is_owner()
|
@commands.is_owner()
|
||||||
@checks.del_ctx()
|
@checks.del_ctx()
|
||||||
async def send(self, ctx):
|
async def send(self, ctx):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@send.command(name='guild', aliases=['g', 'server', 's'])
|
@send.command(name='guild', aliases=['g', 'server', 's'])
|
||||||
async def send_guild(self, ctx, guild, channel, *, message):
|
async def send_guild(self, ctx, guild, channel, *, message):
|
||||||
await discord.utils.get(self.bot.get_all_channels(), guild__name=guild, name=channel).send(message)
|
await discord.utils.get(self.bot.get_all_channels(), guild_name=guild, name=channel).send(message)
|
||||||
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
||||||
|
|
||||||
@send.command(name='user', aliases=['u', 'member', 'm'])
|
@send.command(name='user', aliases=['u', 'member', 'm'])
|
||||||
async def send_user(self, ctx, user, *, message):
|
async def send_user(self, ctx, user, *, message):
|
||||||
await discord.utils.get(self.bot.get_all_members(), id=int(user)).send(message)
|
await discord.utils.get(self.bot.get_all_members(), id=int(user)).send(message)
|
||||||
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
||||||
|
|
||||||
@commands.command(aliases=['authenticateupload', 'authupload', 'authup', 'auth'])
|
@commands.command(aliases=['authenticateupload', 'authupload', 'authup', 'auth'])
|
||||||
async def authenticate_upload(self, ctx):
|
async def authenticate_upload(self, ctx):
|
||||||
global youtube
|
global youtube
|
||||||
flow = flow_from_clientsecrets('client_secrets.json', scope='https://www.googleapis.com/auth/youtube.upload',
|
flow = flow_from_clientsecrets('client_secrets.json', scope='https://www.googleapis.com/auth/youtube.upload',
|
||||||
login_hint='botmyned@gmail.com', redirect_uri='urn:ietf:wg:oauth:2.0:oob')
|
login_hint='botmyned@gmail.com', redirect_uri='urn:ietf:wg:oauth:2.0:oob')
|
||||||
flow.params['access_type'] = 'offline'
|
flow.params['access_type'] = 'offline'
|
||||||
webbrowser.open_new_tab(flow.step1_get_authorize_url())
|
webbrowser.open_new_tab(flow.step1_get_authorize_url())
|
||||||
credentials = flow.step2_exchange(input('Authorization code: '))
|
credentials = flow.step2_exchange(input('Authorization code: '))
|
||||||
youtube = build('youtube', 'v3', http=credentials.authorize(http.build_http()))
|
youtube = build('youtube', 'v3', http=credentials.authorize(http.build_http()))
|
||||||
print('Service built.')
|
print('Service built.')
|
||||||
|
|
||||||
@commands.command(aliases=['up', 'u', 'vid', 'v'])
|
@commands.command(aliases=['up', 'u', 'vid', 'v'])
|
||||||
@commands.has_permissions(administrator=True)
|
@commands.has_permissions(administrator=True)
|
||||||
async def upload(self, ctx):
|
async def upload(self, ctx):
|
||||||
global youtube
|
global youtube
|
||||||
attachments = ctx.message.attachments
|
attachments = ctx.message.attachments
|
||||||
try:
|
try:
|
||||||
if not attachments:
|
if not attachments:
|
||||||
raise exc.MissingAttachment
|
raise exc.MissingAttachment
|
||||||
if len(attachments) > 1:
|
if len(attachments) > 1:
|
||||||
raise exc.TooManyAttachments(len(attachments))
|
raise exc.TooManyAttachments(len(attachments))
|
||||||
mime = mimetypes.guess_type(attachments[0].filename)[0]
|
mime = mimetypes.guess_type(attachments[0].filename)[0]
|
||||||
if 'video/' in mime:
|
if 'video/' in mime:
|
||||||
with tempfile.NamedTemporaryFile() as temp:
|
with tempfile.NamedTemporaryFile() as temp:
|
||||||
await attachments[0].save(temp)
|
await attachments[0].save(temp)
|
||||||
else:
|
else:
|
||||||
raise exc.InvalidVideoFile(mime)
|
raise exc.InvalidVideoFile(mime)
|
||||||
print('https://www.youtube.com/watch?v=' + youtube.videos().insert(part='snippet',
|
print('https://www.youtube.com/watch?v=' + youtube.videos().insert(part='snippet',
|
||||||
body={'categoryId': '24', 'title': 'Test'}, media_body=http.MediaFileUpload(temp.name, chunksize=-1)))
|
body={'categoryId': '24', 'title': 'Test'}, media_body=http.MediaFileUpload(temp.name, chunksize=-1)))
|
||||||
except exc.InvalidVideoFile as e:
|
except exc.InvalidVideoFile as e:
|
||||||
await ctx.send('`' + str(e) + '` **not valid video type.**', delete_after=10)
|
await ctx.send('`' + str(e) + '` **not valid video type.**', delete_after=10)
|
||||||
except exc.TooManyAttachments as e:
|
except exc.TooManyAttachments as e:
|
||||||
await ctx.send('`' + str(e) + '` **too many attachments.** Only one attachment is permitted to upload.', delete_after=10)
|
await ctx.send('`' + str(e) + '` **too many attachments.** Only one attachment is permitted to upload.', delete_after=10)
|
||||||
except exc.MissingAttachment:
|
except exc.MissingAttachment:
|
||||||
await ctx.send('**Missing attachment.**', delete_after=10)
|
await ctx.send('**Missing attachment.**', delete_after=10)
|
||||||
|
|
||||||
@upload.error
|
@upload.error
|
||||||
async def upload_error(self, ctx, error):
|
async def upload_error(self, ctx, error):
|
||||||
pass
|
pass
|
||||||
# http.
|
# http.
|
||||||
|
|
|
@ -14,48 +14,48 @@ owner_id = u.config['owner_id']
|
||||||
|
|
||||||
|
|
||||||
def is_owner():
|
def is_owner():
|
||||||
async def predicate(ctx):
|
async def predicate(ctx):
|
||||||
return ctx.message.author.id == owner_id
|
return ctx.message.author.id == owner_id
|
||||||
return commands.check(predicate)
|
return commands.check(predicate)
|
||||||
|
|
||||||
|
|
||||||
def is_admin():
|
def is_admin():
|
||||||
def predicate(ctx):
|
def predicate(ctx):
|
||||||
return ctx.message.author.guild_permissions.administrator
|
return ctx.message.author.guild_permissions.administrator
|
||||||
return commands.check(predicate)
|
return commands.check(predicate)
|
||||||
|
|
||||||
|
|
||||||
def is_mod():
|
def is_mod():
|
||||||
def predicate(ctx):
|
def predicate(ctx):
|
||||||
return ctx.message.author.guild_permissions.ban_members
|
return ctx.message.author.guild_permissions.ban_members
|
||||||
return commands.check(predicate)
|
return commands.check(predicate)
|
||||||
|
|
||||||
|
|
||||||
def owner(ctx):
|
def owner(ctx):
|
||||||
return ctx.message.author.id == owner_id
|
return ctx.message.author.id == owner_id
|
||||||
|
|
||||||
|
|
||||||
def admin(ctx):
|
def admin(ctx):
|
||||||
return ctx.message.author.guild_permissions.administrator
|
return ctx.message.author.guild_permissions.administrator
|
||||||
|
|
||||||
|
|
||||||
def mod(ctx):
|
def mod(ctx):
|
||||||
return ctx.message.author.guild_permissions.ban_members
|
return ctx.message.author.guild_permissions.ban_members
|
||||||
|
|
||||||
|
|
||||||
def is_nsfw():
|
def is_nsfw():
|
||||||
def predicate(ctx):
|
def predicate(ctx):
|
||||||
if isinstance(ctx.message.channel, d.TextChannel):
|
if isinstance(ctx.message.channel, d.TextChannel):
|
||||||
return ctx.message.channel.is_nsfw()
|
return ctx.message.channel.is_nsfw()
|
||||||
return True
|
return True
|
||||||
return commands.check(predicate)
|
return commands.check(predicate)
|
||||||
|
|
||||||
|
|
||||||
def del_ctx():
|
def del_ctx():
|
||||||
async def predicate(ctx):
|
async def predicate(ctx):
|
||||||
with suppress(AttributeError):
|
with suppress(AttributeError):
|
||||||
if ctx.guild.id in u.settings['del_ctx'] and ctx.me.permissions_in(ctx.channel).manage_messages and isinstance(ctx.message.channel, d.TextChannel):
|
if ctx.guild.id in u.settings['del_ctx'] and ctx.me.permissions_in(ctx.channel).manage_messages and isinstance(ctx.message.channel, d.TextChannel):
|
||||||
with suppress(err.NotFound):
|
with suppress(err.NotFound):
|
||||||
await ctx.message.delete()
|
await ctx.message.delete()
|
||||||
return True
|
return True
|
||||||
return commands.check(predicate)
|
return commands.check(predicate)
|
||||||
|
|
|
@ -2,104 +2,112 @@ base = '⚠️ **An internal error has occurred.** This has been reported to my
|
||||||
|
|
||||||
|
|
||||||
async def send_error(ctx, error):
|
async def send_error(ctx, error):
|
||||||
await ctx.send('{}\n```\n{}```'.format(base, error))
|
await ctx.send('{}\n```\n{}```'.format(base, error))
|
||||||
|
|
||||||
|
|
||||||
|
class Execute(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Evaluate(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
class Left(Exception):
|
class Left(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class Right(Exception):
|
class Right(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class Save(Exception):
|
class Save(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class GoTo(Exception):
|
class GoTo(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class Exists(Exception):
|
class Exists(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class MissingArgument(Exception):
|
class MissingArgument(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class FavoritesNotFound(Exception):
|
class FavoritesNotFound(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class PostError(Exception):
|
class PostError(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class ImageError(Exception):
|
class ImageError(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class MatchError(Exception):
|
class MatchError(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class TagBlacklisted(Exception):
|
class TagBlacklisted(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class BoundsError(Exception):
|
class BoundsError(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class TagBoundsError(Exception):
|
class TagBoundsError(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class TagExists(Exception):
|
class TagExists(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class TagError(Exception):
|
class TagError(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class FlagError(Exception):
|
class FlagError(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class BlacklistError(Exception):
|
class BlacklistError(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class NotFound(Exception):
|
class NotFound(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class Timeout(Exception):
|
class Timeout(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class InvalidVideoFile(Exception):
|
class InvalidVideoFile(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class MissingAttachment(Exception):
|
class MissingAttachment(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class TooManyAttachments(Exception):
|
class TooManyAttachments(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class CheckFail(Exception):
|
class CheckFail(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class Abort(Exception):
|
class Abort(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class Continue(Exception):
|
class Continue(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
144
src/main/run.py
144
src/main/run.py
|
@ -18,115 +18,125 @@ from utils import utils as u
|
||||||
|
|
||||||
# log.basicConfig(level=log.INFO)
|
# log.basicConfig(level=log.INFO)
|
||||||
|
|
||||||
bot = commands.Bot(command_prefix=u.config['prefix'], description='Experimental miscellaneous bot')
|
|
||||||
|
|
||||||
|
def get_prefix(bot, message):
|
||||||
|
if isinstance(message.guild, d.Guild) and message.guild.id in u.settings['prefixes']:
|
||||||
|
return u.settings['prefixes'][message.guild.id]
|
||||||
|
return u.config['prefix']
|
||||||
|
|
||||||
|
|
||||||
|
bot = commands.Bot(command_prefix=get_prefix, description='Experimental miscellaneous bot')
|
||||||
|
|
||||||
# Send and print ready message to #testing and console after logon
|
# Send and print ready message to #testing and console after logon
|
||||||
|
|
||||||
|
|
||||||
@bot.event
|
@bot.event
|
||||||
async def on_ready():
|
async def on_ready():
|
||||||
from cogs import booru, info, management, owner, tools
|
from cogs import booru, info, management, owner, tools
|
||||||
|
|
||||||
bot.add_cog(tools.Utils(bot))
|
for cog in (tools.Utils(bot), owner.Bot(bot), owner.Tools(bot), management.Administration(bot), info.Info(bot), booru.MsG(bot)):
|
||||||
bot.add_cog(owner.Bot(bot))
|
bot.add_cog(cog)
|
||||||
bot.add_cog(owner.Tools(bot))
|
print(f'COG : {type(cog).__name__}')
|
||||||
bot.add_cog(management.Administration(bot))
|
|
||||||
bot.add_cog(info.Info(bot))
|
|
||||||
bot.add_cog(booru.MsG(bot))
|
|
||||||
|
|
||||||
# bot.loop.create_task(u.clear(booru.temp_urls, 30*60))
|
# bot.loop.create_task(u.clear(booru.temp_urls, 30*60))
|
||||||
|
|
||||||
if u.config['playing'] is not 'None':
|
if u.config['playing'] is not 'None':
|
||||||
await bot.change_presence(game=d.Game(name=u.config['playing']))
|
await bot.change_presence(game=d.Game(name=u.config['playing']))
|
||||||
else:
|
else:
|
||||||
await bot.change_presence(game=None)
|
await bot.change_presence(game=None)
|
||||||
|
|
||||||
print('\n\\ \\ \\ \\ \\ \\ \\ \\ \\\nC O N N E C T E D : {}\n/ / / / / / / / /\n'.format(bot.user.name))
|
print('\n\\ \\ \\ \\ \\ \\ \\ \\ \\\nC O N N E C T E D : {}\n/ / / / / / / / /\n'.format(bot.user.name))
|
||||||
await bot.get_channel(u.config['info_channel']).send('**Started** \N{BLACK SUN WITH RAYS} .')
|
await bot.get_channel(u.config['info_channel']).send('**Started** \N{BLACK SUN WITH RAYS} .')
|
||||||
# u.notify('C O N N E C T E D')
|
# u.notify('C O N N E C T E D')
|
||||||
if u.temp:
|
if u.temp:
|
||||||
channel = bot.get_channel(u.temp['restart_ch'])
|
channel = bot.get_channel(u.temp['restart_ch'])
|
||||||
message = await channel.get_message(u.temp['restart_msg'])
|
message = await channel.get_message(u.temp['restart_msg'])
|
||||||
await message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
await message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
|
||||||
u.temp.clear()
|
u.temp.clear()
|
||||||
|
|
||||||
|
|
||||||
|
@bot.event
|
||||||
|
async def on_message(message):
|
||||||
|
if message.author.bot or message.author is bot.user:
|
||||||
|
return
|
||||||
|
|
||||||
|
await bot.process_commands(message)
|
||||||
|
|
||||||
|
|
||||||
@bot.event
|
@bot.event
|
||||||
async def on_error(error, *args, **kwargs):
|
async def on_error(error, *args, **kwargs):
|
||||||
print('\n! ! ! ! !\nE R R O R : {}\n! ! ! ! !\n'.format(error), file=sys.stderr)
|
print('\n! ! ! ! !\nE R R O R : {}\n! ! ! ! !\n'.format(error), file=sys.stderr)
|
||||||
tb.print_exc()
|
tb.print_exc()
|
||||||
await bot.get_user(u.config['owner_id']).send('**ERROR** ⚠ `{}`'.format(error))
|
await bot.get_user(u.config['owner_id']).send('**ERROR** \N{WARNING SIGN} `{}`'.format(error))
|
||||||
await bot.get_channel(u.config['info_channel']).send('**ERROR** ⚠ `{}`'.format(error))
|
await bot.get_channel(u.config['info_channel']).send('**ERROR** \N{WARNING SIGN} `{}`'.format(error))
|
||||||
# u.notify('E R R O R')
|
if u.temp:
|
||||||
await bot.logout()
|
channel = bot.get_channel(u.temp['restart_ch'])
|
||||||
u.close(bot.loop)
|
message = await channel.get_message(u.temp['restart_msg'])
|
||||||
|
await message.add_reaction('\N{WARNING SIGN}')
|
||||||
|
u.temp.clear()
|
||||||
|
# u.notify('E R R O R')
|
||||||
|
await bot.logout()
|
||||||
|
u.close(bot.loop)
|
||||||
|
|
||||||
|
|
||||||
@bot.event
|
@bot.event
|
||||||
async def on_command_error(ctx, error):
|
async def on_command_error(ctx, error):
|
||||||
if isinstance(error, errext.CheckFailure):
|
if isinstance(error, errext.CheckFailure):
|
||||||
await ctx.send('\N{NO ENTRY} **Insufficient permissions.**', delete_after=10)
|
await ctx.send('\N{NO ENTRY} **Insufficient permissions.**', delete_after=10)
|
||||||
await ctx.message.add_reaction('\N{NO ENTRY}')
|
await ctx.message.add_reaction('\N{NO ENTRY}')
|
||||||
elif isinstance(error, errext.CommandNotFound):
|
elif isinstance(error, errext.CommandNotFound):
|
||||||
print('INVALID COMMAND : {}'.format(error), file=sys.stderr)
|
print('INVALID COMMAND : {}'.format(error), file=sys.stderr)
|
||||||
await ctx.message.add_reaction('\N{CROSS MARK}')
|
await ctx.message.add_reaction('\N{CROSS MARK}')
|
||||||
else:
|
else:
|
||||||
print('\n! ! ! ! ! ! ! ! ! ! ! !\nC O M M A N D E R R O R : {}\n! ! ! ! ! ! ! ! ! ! ! !\n'.format(
|
print('\n! ! ! ! ! ! ! ! ! ! ! !\nC O M M A N D E R R O R : {}\n! ! ! ! ! ! ! ! ! ! ! !\n'.format(
|
||||||
error), file=sys.stderr)
|
error), file=sys.stderr)
|
||||||
tb.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
|
tb.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
|
||||||
await bot.get_user(u.config['owner_id']).send('**COMMAND ERROR** ⚠ `{}`'.format(error))
|
await bot.get_user(u.config['owner_id']).send('**COMMAND ERROR** \N{WARNING SIGN} `{}`'.format(error))
|
||||||
await bot.get_channel(u.config['info_channel']).send('**COMMAND ERROR** ⚠ `{}`'.format(error))
|
await bot.get_channel(u.config['info_channel']).send('**COMMAND ERROR** \N{WARNING SIGN} `{}`'.format(error))
|
||||||
await exc.send_error(ctx, error)
|
await exc.send_error(ctx, error)
|
||||||
await ctx.message.add_reaction('⚠')
|
await ctx.message.add_reaction('\N{WARNING SIGN}')
|
||||||
# u.notify('C O M M A N D E R R O R')
|
# u.notify('C O M M A N D E R R O R')
|
||||||
|
|
||||||
|
|
||||||
async def on_reaction_add(r, u):
|
async def on_reaction_add(r, u):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
async def on_reaction_remove(r, u):
|
async def on_reaction_remove(r, u):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
async def reaction_add(r, u):
|
async def reaction_add(r, u):
|
||||||
bot.add_listener(on_reaction_add)
|
bot.add_listener(on_reaction_add)
|
||||||
print('Reacted')
|
print('Reacted')
|
||||||
bot.remove_listener(on_reaction_remove)
|
bot.remove_listener(on_reaction_remove)
|
||||||
|
|
||||||
|
|
||||||
async def reaction_remove(r, u):
|
async def reaction_remove(r, u):
|
||||||
bot.add_listener(on_reaction_remove)
|
bot.add_listener(on_reaction_remove)
|
||||||
print('Removed')
|
print('Removed')
|
||||||
bot.remove_listener(on_reaction_remove)
|
bot.remove_listener(on_reaction_remove)
|
||||||
|
|
||||||
# d.opus.load_opus('opus')
|
# d.opus.load_opus('opus')
|
||||||
|
|
||||||
|
|
||||||
async def wait(voice):
|
async def wait(voice):
|
||||||
asyncio.sleep(5)
|
asyncio.sleep(5)
|
||||||
await voice.disconnect()
|
await voice.disconnect()
|
||||||
|
|
||||||
|
|
||||||
def after(voice, error):
|
def after(voice, error):
|
||||||
coro = voice.disconnect()
|
coro = voice.disconnect()
|
||||||
future = asyncio.run_coroutine_threadsafe(coro, voice.loop)
|
future = asyncio.run_coroutine_threadsafe(coro, voice.loop)
|
||||||
future.result()
|
future.result()
|
||||||
|
|
||||||
|
|
||||||
@bot.command(name=',test', hidden=True)
|
@bot.command(name=',test', hidden=True)
|
||||||
@commands.is_owner()
|
@commands.is_owner()
|
||||||
@checks.del_ctx()
|
@checks.del_ctx()
|
||||||
async def test(ctx):
|
async def test(ctx):
|
||||||
def check(react, user):
|
channel = bot.get_channel(int(cid))
|
||||||
return reaction.emoji == '\N{THUMBS UP SIGN}'
|
voice = await channel.connect()
|
||||||
# channel = bot.get_channel(int(cid))
|
voice.play(d.AudioSource, after=lambda: after(voice))
|
||||||
# voice = await channel.connect()
|
|
||||||
# voice.play(d.AudioSource, after=lambda: after(voice))
|
|
||||||
test = await ctx.send('thumbs up!')
|
|
||||||
while True:
|
|
||||||
done, pending = await asyncio.wait([bot.wait_for('reaction_add', check=check), bot.wait_for('reaction_remove', check=check)], return_when=asyncio.FIRST_COMPLETED)
|
|
||||||
await ctx.send('well doneeee')
|
|
||||||
# bot.add_listener(on_reaction_add)
|
|
||||||
# bot.add_listener(on_reaction_remove)
|
|
||||||
|
|
||||||
bot.run(u.config['token'])
|
bot.run(u.config['token'])
|
||||||
|
|
|
@ -8,26 +8,26 @@ from utils import utils as u
|
||||||
|
|
||||||
|
|
||||||
async def get_post(url):
|
async def get_post(url):
|
||||||
content = await u.fetch('http://iqdb.harry.lu', params={'url': url})
|
content = await u.fetch('http://iqdb.harry.lu', params={'url': url})
|
||||||
|
|
||||||
try:
|
|
||||||
value = BeautifulSoup(content, 'html.parser').find_all('a')[1].get('href')
|
|
||||||
if value != '#':
|
|
||||||
return value
|
|
||||||
else:
|
|
||||||
raise IndexError
|
|
||||||
except IndexError:
|
|
||||||
try:
|
try:
|
||||||
raise exc.MatchError(re.search('\/([^\/]+)$', url).group(1))
|
value = BeautifulSoup(content, 'html.parser').find_all('a')[1].get('href')
|
||||||
|
if value != '#':
|
||||||
|
return value
|
||||||
|
else:
|
||||||
|
raise IndexError
|
||||||
|
except IndexError:
|
||||||
|
try:
|
||||||
|
raise exc.MatchError(re.search('\/([^\/]+)$', url).group(1))
|
||||||
|
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
raise exc.MissingArgument
|
raise exc.MissingArgument
|
||||||
|
|
||||||
|
|
||||||
async def get_image(url):
|
async def get_image(url):
|
||||||
content = await u.fetch(url)
|
content = await u.fetch(url)
|
||||||
|
|
||||||
value = html.fromstring(content).xpath(
|
value = html.fromstring(content).xpath(
|
||||||
'string(/html/body/div[@id="content"]/div[@id="post-view"]/div[@class="content"]/div[2]/img/@src)')
|
'string(/html/body/div[@id="content"]/div[@id="post-view"]/div[@class="content"]/div[2]/img/@src)')
|
||||||
|
|
||||||
return value
|
return value
|
||||||
|
|
|
@ -20,49 +20,49 @@ print('\nPID : {}\n'.format(os.getpid()))
|
||||||
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with open('config.json') as infile:
|
with open('config.json') as infile:
|
||||||
config = jsn.load(infile)
|
config = jsn.load(infile)
|
||||||
print('config.json loaded.')
|
print('LOADED : config.json')
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
with open('config.json', 'w') as outfile:
|
with open('config.json', 'w') as outfile:
|
||||||
jsn.dump({'client_id': 0, 'info_channel': 0, 'owner_id': 0, 'permissions': 126016,
|
jsn.dump({'client_id': 0, 'info_channel': 0, 'owner_id': 0, 'permissions': 126016,
|
||||||
'playing': 'a game', 'prefix': [',', 'm,'], 'token': 'str'}, outfile, indent=4, sort_keys=True)
|
'playing': 'a game', 'prefix': [',', 'm,'], 'token': 'str'}, outfile, indent=4, sort_keys=True)
|
||||||
raise FileNotFoundError(
|
raise FileNotFoundError(
|
||||||
'Config file not found: config.json created with abstract values. Restart run.py with correct values.')
|
'FILE NOT FOUND : config.json created with abstract values. Restart run.py with correct values')
|
||||||
|
|
||||||
|
|
||||||
def setdefault(filename, default=None):
|
def setdefault(filename, default=None):
|
||||||
try:
|
try:
|
||||||
with open(filename, 'rb') as infile:
|
with open(filename, 'rb') as infile:
|
||||||
print('{} loaded.'.format(filename))
|
print('LOADED : {}'.format(filename))
|
||||||
return pkl.load(infile)
|
return pkl.load(infile)
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
with open(filename, 'wb+') as iofile:
|
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)
|
pkl.dump(default, iofile)
|
||||||
iofile.seek(0)
|
iofile.seek(0)
|
||||||
return pkl.load(iofile)
|
return pkl.load(iofile)
|
||||||
|
|
||||||
|
|
||||||
def load(filename, *, json=False):
|
def load(filename, *, json=False):
|
||||||
if not json:
|
if not json:
|
||||||
with open(filename, 'rb') as infile:
|
with open(filename, 'rb') as infile:
|
||||||
return pkl.load(infile)
|
return pkl.load(infile)
|
||||||
else:
|
else:
|
||||||
with open(filename) as infile:
|
with open(filename) as infile:
|
||||||
return jsn.load(infile)
|
return jsn.load(infile)
|
||||||
|
|
||||||
|
|
||||||
def dump(obj, filename, *, json=False):
|
def dump(obj, filename, *, json=False):
|
||||||
if not json:
|
if not json:
|
||||||
with open(filename, 'wb') as outfile:
|
with open(filename, 'wb') as outfile:
|
||||||
pkl.dump(obj, outfile)
|
pkl.dump(obj, outfile)
|
||||||
else:
|
else:
|
||||||
with open(filename, 'w') as outfile:
|
with open(filename, 'w') as outfile:
|
||||||
jsn.dump(obj, outfile, indent=4, sort_keys=True)
|
jsn.dump(obj, outfile, indent=4, sort_keys=True)
|
||||||
|
|
||||||
|
|
||||||
settings = setdefault('settings.pkl', {'del_ctx': []})
|
settings = setdefault('settings.pkl', {'del_ctx': [], 'prefixes': {}})
|
||||||
tasks = setdefault('cogs/tasks.pkl', {'auto_del': [], 'auto_qual': [], 'auto_rev': []})
|
tasks = setdefault('cogs/tasks.pkl', {'auto_del': [], 'auto_qual': [], 'auto_rev': []})
|
||||||
temp = setdefault('temp.pkl', {})
|
temp = setdefault('temp.pkl', {})
|
||||||
|
|
||||||
|
@ -87,63 +87,62 @@ session = aiohttp.ClientSession()
|
||||||
|
|
||||||
|
|
||||||
def close(loop):
|
def close(loop):
|
||||||
global session
|
global session
|
||||||
|
|
||||||
if session:
|
if session:
|
||||||
session.close()
|
session.close()
|
||||||
|
|
||||||
loop.stop()
|
loop.stop()
|
||||||
pending = asyncio.Task.all_tasks()
|
pending = asyncio.Task.all_tasks()
|
||||||
for task in pending:
|
for task in pending:
|
||||||
task.cancel()
|
task.cancel()
|
||||||
# with suppress(asyncio.CancelledError):
|
# with suppress(asyncio.CancelledError):
|
||||||
# loop.run_until_complete(task)
|
# loop.run_until_complete(task)
|
||||||
# loop.close()
|
# loop.close()
|
||||||
|
|
||||||
print('Finished cancelling tasks.')
|
print('Finished cancelling tasks.')
|
||||||
|
|
||||||
|
|
||||||
async def fetch(url, *, params={}, json=False):
|
async def fetch(url, *, params={}, json=False):
|
||||||
global session
|
global session
|
||||||
|
|
||||||
async with session.get(url, params=params, headers={'user-agent': 'Modumind/0.0.1 (Myned)'}) as r:
|
async with session.get(url, params=params, headers={'User-Agent': 'Myned/Modumind/0.0.1'}) as r:
|
||||||
if json:
|
if json:
|
||||||
return await r.json()
|
return await r.json()
|
||||||
return await r.read()
|
return await r.read()
|
||||||
|
|
||||||
|
|
||||||
# def geneate_embed(**kwargs):
|
# def geneate_embed(**kwargs):
|
||||||
# embed = d.Embed(title=kwargs['title'], )
|
# embed = d.Embed(title=kwargs['title'], )
|
||||||
|
|
||||||
def get_kwargs(ctx, args, *, limit=False):
|
def get_kwargs(ctx, args, *, limit=False):
|
||||||
destination = ctx
|
destination = ctx
|
||||||
remaining = list(args[:])
|
remaining = list(args[:])
|
||||||
rm = False
|
rm = False
|
||||||
lim = 1
|
lim = 1
|
||||||
|
|
||||||
if '-d' in remaining or '-dm' in remaining:
|
if '-d' in remaining or '-dm' in remaining:
|
||||||
destination = ctx.author
|
destination = ctx.author
|
||||||
|
|
||||||
for flag in ('-d', '-dm'):
|
for flag in ('-d', '-dm'):
|
||||||
with suppress(ValueError):
|
with suppress(ValueError):
|
||||||
remaining.remove(flag)
|
remaining.remove(flag)
|
||||||
|
|
||||||
if ('-r' in remaining or '-rm' in remaining or '-remove' in remaining) and ctx.author.permissions_in(ctx.channel).manage_messages:
|
if ('-r' in remaining or '-rm' in remaining or '-remove' in remaining) and ctx.author.permissions_in(ctx.channel).manage_messages:
|
||||||
rm = True
|
rm = True
|
||||||
|
|
||||||
for flag in ('-r', '-rm', '-remove'):
|
for flag in ('-r', '-rm', '-remove'):
|
||||||
with suppress(ValueError):
|
with suppress(ValueError):
|
||||||
remaining.remove(flag)
|
remaining.remove(flag)
|
||||||
|
|
||||||
if limit:
|
if limit:
|
||||||
for arg in remaining:
|
for arg in remaining:
|
||||||
if 1 <= len(arg) <= 2:
|
if arg.isdigit():
|
||||||
with suppress(ValueError):
|
if 1 <= int(arg) <= limit:
|
||||||
if 1 <= int(arg) <= limit:
|
lim = int(arg)
|
||||||
lim = int(arg)
|
remaining.remove(arg)
|
||||||
remaining.remove(arg)
|
break
|
||||||
break
|
else:
|
||||||
else:
|
raise exc.BoundsError(arg)
|
||||||
raise exc.BoundsError(arg)
|
|
||||||
|
|
||||||
return {'destination': destination, 'remaining': remaining, 'remove': rm, 'limit': lim}
|
return {'destination': destination, 'remaining': remaining, 'remove': rm, 'limit': lim}
|
||||||
|
|
Loading…
Reference in a new issue