1
0
Fork 0
mirror of https://github.com/myned/modufur.git synced 2024-12-24 14:27:27 +00:00

Merge branch 'dev'

This commit is contained in:
Myned 2017-12-31 21:56:23 -05:00
commit 523ab37fe6
9 changed files with 2021 additions and 1868 deletions

File diff suppressed because it is too large Load diff

View file

@ -116,6 +116,10 @@ class Administration:
await ctx.send('**Deletion timed out**', delete_after=7) await ctx.send('**Deletion timed out**', delete_after=7)
await ctx.message.add_reaction('\N{CROSS MARK}') await ctx.message.add_reaction('\N{CROSS MARK}')
@cmds.group(aliases=['task', 'tsk'])
async def tasks(self):
pass
async def delete(self): async def delete(self):
while self.deleting: while self.deleting:
message = await self.queue.get() message = await self.queue.get()
@ -128,7 +132,7 @@ class Administration:
async def queue_for_deletion(self, channel): async def queue_for_deletion(self, channel):
def check(msg): def check(msg):
if msg.content.lower() == 'stop' and msg.channel is channel and msg.author.guild_permissions.administrator: if 'stop d' in msg.content.lower() and msg.channel is channel and msg.author.guild_permissions.administrator:
raise exc.Abort raise exc.Abort
elif msg.channel is channel and not msg.pinned: elif msg.channel is channel and not msg.pinned:
return True return True
@ -136,7 +140,7 @@ class Administration:
try: try:
async for message in channel.history(limit=None): async for message in channel.history(limit=None):
if message.content.lower() == 'stop' and message.author.guild_permissions.administrator: if 'stop d' in message.content.lower() and message.author.guild_permissions.administrator:
raise exc.Abort raise exc.Abort
if not message.pinned: if not message.pinned:
await self.queue.put(message) await self.queue.put(message)
@ -170,7 +174,7 @@ class Administration:
raise exc.Exists raise exc.Exists
except exc.Exists: except exc.Exists:
await ctx.send('**Already auto-deleting in {}.** Type `stop` to stop.'.format(ctx.channel.mention), delete_after=7) await ctx.send('**Already auto-deleting in {}.** Type `stop d(eleting)` to stop.'.format(ctx.channel.mention), delete_after=7)
await ctx.message.add_reaction('\N{CROSS MARK}') await ctx.message.add_reaction('\N{CROSS MARK}')
@cmds.group(aliases=['setting', 'set', 's']) @cmds.group(aliases=['setting', 'set', 's'])
@ -179,7 +183,7 @@ class Administration:
pass pass
@settings.command(name='deletecommands', aliases=['delcmds', 'delcmd']) @settings.command(name='deletecommands', aliases=['delcmds', 'delcmd'])
async def _settings_delete_commands(self, ctx): async def _settings_deletecommands(self, ctx):
if ctx.guild.id not in u.settings['del_ctx']: if ctx.guild.id not in u.settings['del_ctx']:
u.settings['del_ctx'].append(ctx.guild.id) u.settings['del_ctx'].append(ctx.guild.id)
else: else:
@ -197,3 +201,13 @@ class Administration:
del u.settings['prefixes'][ctx.guild.id] del u.settings['prefixes'][ctx.guild.id]
await ctx.send(f'**Prefix set to:** `{"` or `".join(prefixes if ctx.guild.id in u.settings["prefixes"] else u.config["prefix"])}`') await ctx.send(f'**Prefix set to:** `{"` or `".join(prefixes if ctx.guild.id in u.settings["prefixes"] else u.config["prefix"])}`')
@settings.command(name='deleteresponses', aliases=['delresps', 'delresp'])
async def _settings_deleteresponses(self, ctx):
if ctx.guild.id not in u.settings['del_resp']:
u.settings['del_resp'].append(ctx.guild.id)
else:
u.settings['del_resp'].remove(ctx.guild.id)
u.dump(u.settings, 'settings.pkl')
await ctx.send(f'**Delete command responses:** `{ctx.guild.id in u.settings["del_resp"]}`')

57
src/cogs/music.py Normal file
View file

@ -0,0 +1,57 @@
import asyncio
import json
from datetime import datetime as dt
from urllib import parse
import re
from pprint import pprint
import discord as d
from discord import errors as err
from discord.ext import commands as cmds
from discord.ext.commands import errors as errext
import gmusicapi as gpm
import googleapiclient as gapic
import apiclient as apic
from misc import exceptions as exc
from misc import checks
from utils import utils as u
class Music:
def __init__(self, bot):
self.bot = bot
self.yt_service = apic.discovery.build('youtube', 'v3', developerKey=u.secrets['client_secrets']['client_secret'])
@cmds.group(aliases=['pl'], brief='(G) Play music', description='Play music from YouTube, Soundcloud, or Google Play Music')
async def play(self, ctx):
print(ctx.invoked_subcommand)
@play.command(name='youtube', aliases=['you', 'tube', 'yt', 'y'])
async def _play_youtube(self, ctx, *videos):
try:
if not videos:
raise exc.MissingArgument
vids = []
for video in videos:
if 'http' in video and 'youtube' in video:
vids.append(parse.parse_qs(parse.urlparse(video).query)['v'][0])
else:
vids.append(video)
print(vids)
response = self.yt_service.videos().list(part='snippet', id=','.join(vids)).execute()
pprint(response)
except exc.MissingArgument:
await ctx.send('**Invalid youtube url or ID**', delete_after=7)
await ctx.message.add_reaction('\N{CROSS MARK}')
@play.command(name='googleplaymusic', aliases=['googleplay', 'googlemusic', 'playmusic', 'play', 'gpm'])
async def _play_googleplaymusic(self, ctx, query):
pass

View file

@ -23,3 +23,11 @@ class Post:
async def _check_posts(self, user, channel): async def _check_posts(self, user, channel):
pass pass
@cmds.group(aliases=['update', 'up', 'u'])
async def updates(self, ctx):
pass
@updates.command(name='googleplaymusic', aliases=['googlemusic', 'playmusic', 'music', 'gpm'])
async def _updates_googleplaymusic(self, ctx):
pass

View file

@ -39,9 +39,9 @@ class Right(Exception):
class Save(Exception): class Save(Exception):
def __init__(self, user=None): def __init__(self, user=None, message=None):
self.user = user self.user = user
self.message = message
class GoTo(Exception): class GoTo(Exception):
pass pass

View file

@ -1,255 +1,260 @@
import asyncio import asyncio
from datetime import datetime as dt from datetime import datetime as dt
import json import json
import logging as log import logging as log
import subprocess import subprocess
import sys import sys
import traceback as tb import traceback as tb
from contextlib import suppress from contextlib import suppress
from pprint import pprint from pprint import pprint
from hurry.filesize import size, alternative from hurry.filesize import size, alternative
from urllib.parse import urlparse from urllib.parse import urlparse
import discord as d import discord as d
from discord import errors as err from discord import errors as err
from discord import utils from discord import utils
from discord.ext import commands as cmds from discord.ext import commands as cmds
from discord.ext.commands import errors as errext from discord.ext.commands import errors as errext
from misc import exceptions as exc 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
log.basicConfig(level=log.WARNING) log.basicConfig(level=log.WARNING)
# class HelpFormatter(cmds.HelpFormatter): # class HelpFormatter(cmds.HelpFormatter):
# #
# async def format(self): # async def format(self):
# self._paginator = cmds.Paginator() # self._paginator = cmds.Paginator()
# #
# # we need a padding of ~80 or so # # we need a padding of ~80 or so
# #
# description = self.command.description if not self.is_cog() else inspect.getdoc(self.command) # description = self.command.description if not self.is_cog() else inspect.getdoc(self.command)
# #
# if description: # if description:
# # <description> portion # # <description> portion
# self._paginator.add_line(description, empty=True) # self._paginator.add_line(description, empty=True)
# #
# if isinstance(self.command, cmds.Command): # if isinstance(self.command, cmds.Command):
# # <signature portion> # # <signature portion>
# signature = self.get_command_signature() # signature = self.get_command_signature()
# self._paginator.add_line(signature, empty=True) # self._paginator.add_line(signature, empty=True)
# #
# # <long doc> section # # <long doc> section
# if self.command.help: # if self.command.help:
# self._paginator.add_line(self.command.help, empty=True) # self._paginator.add_line(self.command.help, empty=True)
# #
# # end it here if it's just a regular command # # end it here if it's just a regular command
# if not self.has_subcommands(): # if not self.has_subcommands():
# self._paginator.close_page() # self._paginator.close_page()
# return self._paginator.pages # return self._paginator.pages
# #
# max_width = self.max_name_size # max_width = self.max_name_size
def get_prefix(bot, message): def get_prefix(bot, message):
with suppress(AttributeError): with suppress(AttributeError):
return u.settings['prefixes'].get(message.guild.id, u.config['prefix']) return u.settings['prefixes'].get(message.guild.id, u.config['prefix'])
return u.config['prefix'] return u.config['prefix']
bot = cmds.Bot(command_prefix=get_prefix, self_bot=u.config['selfbot'], formatter=cmds.HelpFormatter(show_check_failure=True), description='Modufur - A booru bot with a side of management and automated tasking\nMade by @Myned#3985\n\nNSFW for Not Safe For Wumpus commands\n(G) for group commands\n@permission@ for required permissions\n!notice! for important information\np for prefix\n\n\{\} for mandatory argument\n[] for optional argument\n... for one or more arguments', help_attrs={'aliases': ['h']}, pm_help=None) bot = cmds.Bot(command_prefix=get_prefix, self_bot=u.config['selfbot'], formatter=cmds.HelpFormatter(show_check_failure=True), description='Modufur - A booru bot with a side of management and automated tasking\nMade by @Myned#3985\n\nNSFW for Not Safe For Wumpus commands\n(G) for group commands\n@permission@ for required permissions\n!notice! for important information\np for prefix\n\n\{\} for mandatory argument\n[] for optional argument\n... for one or more arguments', help_attrs={'aliases': ['h']}, pm_help=None)
@bot.command(help='help', brief='brief', description='description', usage='usage', hidden=True) @bot.command(help='help', brief='brief', description='description', usage='usage', hidden=True)
async def test(ctx): async def test(ctx):
pass pass
# 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():
if not checks.ready: if not checks.ready:
from cogs import booru, info, management, owner, tools # d.opus.load_opus('opuslib')
for cog in (tools.Utils(bot), owner.Bot(bot), owner.Tools(bot), management.Administration(bot), info.Info(bot), booru.MsG(bot)): from cogs import booru, info, management, music, owner, tools
bot.add_cog(cog)
print(f'COG : {type(cog).__name__}') for cog in (tools.Utils(bot), owner.Bot(bot), owner.Tools(bot), management.Administration(bot), music.Music(bot), info.Info(bot), booru.MsG(bot)):
bot.add_cog(cog)
# bot.loop.create_task(u.clear(booru.temp_urls, 30*60)) print(f'COG : {type(cog).__name__}')
if u.config['playing'] is not '': # bot.loop.create_task(u.clear(booru.temp_urls, 30*60))
await bot.change_presence(game=d.Game(name=u.config['playing']))
if u.config['playing'] is not '':
print('\n> > > > > > > > >\nC O N N E C T E D : {}\n> > > > > > > > >\n'.format(bot.user.name)) await bot.change_presence(game=d.Game(name=u.config['playing']))
await bot.get_channel(u.config['info_channel']).send(f'**Started** \N{BLACK SUN WITH RAYS} `{"` or `".join(u.config["prefix"])}`')
# u.notify('C O N N E C T E D') 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(f'**Started** \N{BLACK SUN WITH RAYS} `{"` or `".join(u.config["prefix"])}`')
if u.temp['startup']: # u.notify('C O N N E C T E D')
with suppress(err.NotFound):
if u.temp['startup'][0] == 'guild': if u.temp['startup']:
dest = bot.get_channel(u.temp['startup'][1]) with suppress(err.NotFound):
else: if u.temp['startup'][0] == 'guild':
dest = bot.get_user(u.temp['startup'][1]) dest = bot.get_channel(u.temp['startup'][1])
message = await dest.get_message(u.temp['startup'][2]) else:
dest = bot.get_user(u.temp['startup'][1])
await message.add_reaction('\N{WHITE HEAVY CHECK MARK}') message = await dest.get_message(u.temp['startup'][2])
u.temp['startup'] = () await message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
u.dump(u.temp, 'temp/temp.pkl')
u.temp['startup'] = ()
checks.ready = True u.dump(u.temp, 'temp/temp.pkl')
else:
print('\n- - - -\nI N F O : reconnected, skipping initialization\n- - - -') checks.ready = True
else:
print('\n- - - -\nI N F O : reconnected, skipping initialization\n- - - -')
@bot.event
async def on_message(message):
if not u.config['selfbot']: @bot.event
if message.author is not bot.user and not message.author.bot: async def on_message(message):
await bot.process_commands(message) if not u.config['selfbot']:
else: if message.author is not bot.user and not message.author.bot:
if not message.author.bot: await bot.process_commands(message)
await bot.process_commands(message) else:
if not message.author.bot:
await bot.process_commands(message)
@bot.event
async def on_error(error, *args, **kwargs):
print('\n! ! ! ! !\nE R R O R : {}\n! ! ! ! !\n'.format(error), file=sys.stderr) @bot.event
tb.print_exc() async def on_error(error, *args, **kwargs):
await bot.get_user(u.config['owner_id']).send('**ERROR** \N{WARNING SIGN}\n```\n{}```'.format(error)) print('\n! ! ! ! !\nE R R O R : {}\n! ! ! ! !\n'.format(error), file=sys.stderr)
await bot.get_channel(u.config['info_channel']).send('**ERROR** \N{WARNING SIGN}\n```\n{}```'.format(error)) tb.print_exc()
await bot.get_user(u.config['owner_id']).send('**ERROR** \N{WARNING SIGN}\n```\n{}```'.format(error))
if u.temp['startup']: await bot.get_channel(u.config['info_channel']).send('**ERROR** \N{WARNING SIGN}\n```\n{}```'.format(error))
with suppress(err.NotFound):
if u.temp['startup'][0] == 'guild': if u.temp['startup']:
dest = bot.get_channel(u.temp['startup'][1]) with suppress(err.NotFound):
else: if u.temp['startup'][0] == 'guild':
dest = bot.get_user(u.temp['startup'][1]) dest = bot.get_channel(u.temp['startup'][1])
message = await dest.get_message(u.temp['startup'][2]) else:
dest = bot.get_user(u.temp['startup'][1])
await message.add_reaction('\N{WARNING SIGN}') message = await dest.get_message(u.temp['startup'][2])
u.temp.clear() await message.add_reaction('\N{WARNING SIGN}')
u.dump(u.temp, 'temp/temp.pkl')
# u.notify('E R R O R') u.temp.clear()
await bot.logout() u.dump(u.temp, 'temp/temp.pkl')
u.close(bot.loop) # u.notify('E R R O R')
await bot.logout()
u.close(bot.loop)
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, err.NotFound): @bot.event
print('NOT FOUND') async def on_command_error(ctx, error):
elif isinstance(error, errext.CheckFailure): if isinstance(error, err.NotFound):
await ctx.send('**Insufficient permissions**', delete_after=10) print('NOT FOUND')
await ctx.message.add_reaction('\N{NO ENTRY}') elif isinstance(error, errext.CheckFailure):
elif isinstance(error, errext.CommandNotFound): await ctx.send('**Insufficient permissions**', delete_after=10)
print('INVALID COMMAND : {}'.format(error), file=sys.stderr) await ctx.message.add_reaction('\N{NO ENTRY}')
await ctx.message.add_reaction('\N{BLACK QUESTION MARK ORNAMENT}') elif isinstance(error, errext.CommandNotFound):
else: print('INVALID COMMAND : {}'.format(error), file=sys.stderr)
print('\n! ! ! ! ! ! ! ! ! ! ! !\nC O M M A N D E R R O R : {}\n! ! ! ! ! ! ! ! ! ! ! !\n'.format( await ctx.message.add_reaction('\N{BLACK QUESTION MARK ORNAMENT}')
error), file=sys.stderr) else:
tb.print_exception(type(error), error, error.__traceback__, file=sys.stderr) print('\n! ! ! ! ! ! ! ! ! ! ! !\nC O M M A N D E R R O R : {}\n! ! ! ! ! ! ! ! ! ! ! !\n'.format(
await bot.get_user(u.config['owner_id']).send('**COMMAND ERROR** \N{WARNING SIGN} `{}` from {} in {}\n```\n{}```'.format(ctx.message.content, ctx.author.mention, ctx.channel.mention, ''.join(tb.format_exception(type(error), error, error.__traceback__ if len(str(error.__traceback__)) < 1500 else str(error.__traceback__)[:1500])))) error), file=sys.stderr)
await bot.get_channel(u.config['info_channel']).send('**COMMAND ERROR** \N{WARNING SIGN} `{}` from {} in {}\n```\n{}```'.format(ctx.message.content, ctx.author.mention, ctx.channel.mention, error)) tb.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
await exc.send_error(ctx, error) await bot.get_user(u.config['owner_id']).send('**COMMAND ERROR** \N{WARNING SIGN} `{}` from {} in {}\n```\n{}```'.format(ctx.message.content, ctx.author.mention, ctx.channel.mention, ''.join(tb.format_exception(type(error), error, error.__traceback__ if len(str(error.__traceback__)) < 1500 else str(error.__traceback__)[:1500]))))
await ctx.message.add_reaction('\N{WARNING SIGN}') await bot.get_channel(u.config['info_channel']).send('**COMMAND ERROR** \N{WARNING SIGN} `{}` from {} in {}\n```\n{}```'.format(ctx.message.content, ctx.author.mention, ctx.channel.mention, error))
# u.notify('C O M M A N D E R R O R') await exc.send_error(ctx, error)
await ctx.message.add_reaction('\N{WARNING SIGN}')
@bot.event # u.notify('C O M M A N D E R R O R')
async def on_command_completion(ctx):
with suppress(err.NotFound): # @bot.event
with suppress(AttributeError): # async def on_command(ctx):
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_resp']:
await ctx.message.delete() # pass
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}') @bot.event
async def on_command_completion(ctx):
for command in ('lastcommand', ',restart', ',die'): with suppress(err.NotFound):
if ctx.command.name == command: with suppress(AttributeError):
return 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):
await ctx.message.delete()
u.last_commands[ctx.author.id] = ctx
await ctx.message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
@bot.event
async def on_guild_remove(guild): for command in ('lastcommand', ',restart', ',die'):
print(f'LEFT : {guild.name}') if ctx.command.name == command:
return
for task, idents in u.tasks.items():
for channel in guild.channels: u.last_commands[ctx.author.id] = ctx
if channel.id in idents:
idents.remove(channel.id) @bot.event
print(f'STOPPED : {task} in #{channel.id}') async def on_guild_remove(guild):
u.dump(u.tasks, 'cogs/tasks.pkl') print(f'LEFT : {guild.name}')
# d.opus.load_opus('opus') for task, idents in u.tasks.items():
for channel in guild.channels:
if channel.id in idents:
async def wait(voice): idents.remove(channel.id)
asyncio.sleep(5) print(f'STOPPED : {task} in #{channel.id}')
await voice.disconnect() u.dump(u.tasks, 'cogs/tasks.pkl')
def after(voice, error): async def wait(voice):
coro = voice.disconnect() asyncio.sleep(5)
future = asyncio.run_coroutine_threadsafe(coro, voice.loop) await voice.disconnect()
future.result()
# suggested = u.setdefault('cogs/suggested.pkl', {'last_update': 'None', 'tags': {}, 'total': 0}) def after(voice, error):
@bot.command(name=',test', hidden=True) coro = voice.disconnect()
@cmds.is_owner() future = asyncio.run_coroutine_threadsafe(coro, voice.loop)
async def test(ctx): future.result()
post = await u.fetch('https://e621.net/post/show.json?id=1145042', json=True)
# suggested = u.setdefault('cogs/suggested.pkl', {'last_update': 'None', 'tags': {}, 'total': 0})
tags = [] @bot.command(name=',test', hidden=True)
if post['tags']: @cmds.is_owner()
temptags = post['tags'].split(' ') async def test(ctx):
cis = [] post = await u.fetch('https://e621.net/post/show.json?id=1145042', json=True)
for tag in suggested:
pass tags = []
for tag in temptags: if post['tags']:
tags.append(f'[{tag}](https://e621.net/post?tags={tag})') temptags = post['tags'].split(' ')
# tags = ' '.join(tags) cis = []
else: for tag in suggested:
tags = 'None' pass
for tag in temptags:
if post['description']: tags.append(f'[{tag}](https://e621.net/post?tags={tag})')
post_description = post['description'] if len(post['description']) < 200 else f'{post["description"][:200]}...' # tags = ' '.join(tags)
else: else:
post_description = 'None' tags = 'None'
title = ', '.join(post['artist']) if post['description']:
description = f'posted by: *[{post["author"]}](https://e621.net/post?tags=user:{post["author"]})*' post_description = post['description'] if len(post['description']) < 200 else f'{post["description"][:200]}...'
url = f'https://e621.net/post?tags={",".join(post["artist"])}' else:
# timestamp = dt.utcnow() post_description = 'None'
color = ctx.me.color
footer = {'text': post['score'], 'icon_url': 'https://images-ext-1.discordapp.net/external/W2k0ZzhU7ngvN_-CdqAa3H3FmkfCNYQTxPG_DsvacB4/https/emojipedia-us.s3.amazonaws.com/thumbs/320/twitter/103/sparkles_2728.png'} title = ', '.join(post['artist'])
# image = 'https://e621.net/post/show/54360' description = f'posted by: *[{post["author"]}](https://e621.net/post?tags=user:{post["author"]})*'
thumbnail = post['file_url'] url = f'https://e621.net/post?tags={",".join(post["artist"])}'
author = {'name': post['id'], 'url': f'https://e621.net/post/show/{post["id"]}', 'icon_url': ctx.author.avatar_url} # timestamp = dt.utcnow()
color = ctx.me.color
fields = [] footer = {'text': post['score'], 'icon_url': 'https://images-ext-1.discordapp.net/external/W2k0ZzhU7ngvN_-CdqAa3H3FmkfCNYQTxPG_DsvacB4/https/emojipedia-us.s3.amazonaws.com/thumbs/320/twitter/103/sparkles_2728.png'}
names = ('File', 'Sources', 'Description', 'tags', 'tags (ext.)') # image = 'https://e621.net/post/show/54360'
values = (f'[{post["md5"]}]({post["file_url"]}) | [{post["file_ext"]}](https://e621.net/post?tags=type:{post["file_ext"]})\n\n**Size** [{size(post["file_size"], system=alternative)}](https://e621.net/post?tags=filesize:{post["file_size"]})\n**Resolution** [{post["width"]} x {post["height"]}](https://e621.net/post?tags=width:{post["width"]},height:{post["height"]}) | [{u.get_aspectratio(post["width"], post["height"])}](https://e621.net/post?tags=ratio:{post["width"]/post["height"]:.2f})', '\n'.join([f'[{urlparse(source).netloc}]({source})' for source in post['sources']]), post_description, ' '.join(tags[:20]), ' '.join(tags[20:])) thumbnail = post['file_url']
inlines = (False, False, False, True, True) author = {'name': post['id'], 'url': f'https://e621.net/post/show/{post["id"]}', 'icon_url': ctx.author.avatar_url}
for name, value, inline in zip(names, values, inlines):
fields.append({'name': name, 'value': value, 'inline': inline}) fields = []
names = ('File', 'Sources', 'Description', 'tags', 'tags (ext.)')
embed = u.generate_embed(ctx, title=title, description=description, url=url, colour=color, footer=footer, thumbnail=thumbnail, author=author, fields=fields) values = (f'[{post["md5"]}]({post["file_url"]}) | [{post["file_ext"]}](https://e621.net/post?tags=type:{post["file_ext"]})\n\n**Size** [{size(post["file_size"], system=alternative)}](https://e621.net/post?tags=filesize:{post["file_size"]})\n**Resolution** [{post["width"]} x {post["height"]}](https://e621.net/post?tags=width:{post["width"]},height:{post["height"]}) | [{u.get_aspectratio(post["width"], post["height"])}](https://e621.net/post?tags=ratio:{post["width"]/post["height"]:.2f})', '\n'.join([f'[{urlparse(source).netloc}]({source})' for source in post['sources']]), post_description, ' '.join(tags[:20]), ' '.join(tags[20:]))
inlines = (False, False, False, True, True)
await ctx.send(embed=embed) for name, value, inline in zip(names, values, inlines):
# print(ctx.args) fields.append({'name': name, 'value': value, 'inline': inline})
# print(ctx.kwargs)
# if '<:N_:368917475531816962>' in message: embed = u.generate_embed(ctx, title=title, description=description, url=url, colour=color, footer=footer, thumbnail=thumbnail, author=author, fields=fields)
# await ctx.send('<:N_:368917475531816962>')
# logs = [] await ctx.send(embed=embed)
# async for entry in ctx.guild.audit_logs(limit=None, action=d.AuditLogAction.message_delete): # print(ctx.args)
# logs.append( # print(ctx.kwargs)
# f'@{entry.user.name} deleted {entry.extra.count} messages from @{entry.target.name} in #{entry.extra.channel.name}') # if '<:N_:368917475531816962>' in message:
# pprint(logs) # await ctx.send('<:N_:368917475531816962>')
# channel = bot.get_channel(int(cid)) # logs = []
# voice = await channel.connect() # async for entry in ctx.guild.audit_logs(limit=None, action=d.AuditLogAction.message_delete):
# voice.play(d.AudioSource, after=lambda: after(voice)) # logs.append(
# f'@{entry.user.name} deleted {entry.extra.count} messages from @{entry.target.name} in #{entry.extra.channel.name}')
bot.run(u.config['token'], bot=not u.config['selfbot']) # pprint(logs)
# channel = bot.get_channel(int(cid))
# voice = await channel.connect()
# voice.play(d.AudioSource, after=lambda: after(voice))
bot.run(u.config['token'], bot=not u.config['selfbot'])

0
src/temp/__init__.py Normal file
View file

View file

@ -15,6 +15,7 @@ async def get_post(url):
filesize = int(image.headers['Content-Length']) filesize = int(image.headers['Content-Length'])
if filesize > 8192 * 1024: if filesize > 8192 * 1024:
raise exc.SizeError(size(filesize, system=alternative)) raise exc.SizeError(size(filesize, system=alternative))
except ValueError: except ValueError:
raise exc.MissingArgument raise exc.MissingArgument

View file

@ -82,9 +82,10 @@ def dump(obj, filename, *, json=False):
jsn.dump(obj, outfile, indent=4, sort_keys=True) jsn.dump(obj, outfile, indent=4, sort_keys=True)
settings = setdefault('misc/settings.pkl', {'del_ctx': [], 'prefixes': {}}) settings = setdefault('misc/settings.pkl', {'del_ctx': [], 'del_resp': [], 'prefixes': {}})
tasks = setdefault('cogs/tasks.pkl', {'auto_del': [], 'auto_rev': [], 'periodic_gpm': []}) tasks = setdefault('cogs/tasks.pkl', {'auto_del': [], 'auto_hrt': [], 'auto_rev': [], 'periodic_gpm': []})
temp = setdefault('temp/temp.pkl', {'startup': ()}) temp = setdefault('temp/temp.pkl', {'startup': ()})
secrets = setdefault('secrets.json', {'client_secrets': {'client_id': '', 'client_secret': ''}}, json=True)
RATE_LIMIT = 2.2 RATE_LIMIT = 2.2
color = d.Color(0x1A1A1A) color = d.Color(0x1A1A1A)