Text eval

And pep8 nonsense
This commit is contained in:
Unknown 2018-05-08 10:34:34 -04:00
parent d196931124
commit 054a8422a0

View File

@ -1,14 +1,11 @@
import discord
import asyncio import asyncio
from discord.ext import commands
from redbot.core import Config, checks
from redbot.core.utils.chat_formatting import pagify, box
import os
import re import re
import discord
from discord.ext import commands
from redbot.core import Config, checks
from redbot.core.utils.chat_formatting import pagify, box
class CCRole: class CCRole:
""" """
@ -26,7 +23,6 @@ class CCRole:
self.config.register_guild(**default_guild) self.config.register_guild(**default_guild)
@commands.group(no_pm=True) @commands.group(no_pm=True)
async def ccrole(self, ctx): async def ccrole(self, ctx):
"""Custom commands management""" """Custom commands management"""
@ -46,7 +42,7 @@ class CCRole:
author = ctx.author author = ctx.author
channel = ctx.channel channel = ctx.channel
cmdlist = self.config.guild(ctx.guild).cmdlist cmdlist = self.config.guild(guild).cmdlist
if await cmdlist.get_raw(command, default=None): if await cmdlist.get_raw(command, default=None):
await ctx.send("This command already exists. Delete it with `{}ccrole delete` first.".format(ctx.prefix)) await ctx.send("This command already exists. Delete it with `{}ccrole delete` first.".format(ctx.prefix))
@ -62,6 +58,7 @@ class CCRole:
answer = await self.bot.wait_for('message', timeout=120, check=check) answer = await self.bot.wait_for('message', timeout=120, check=check)
except asyncio.TimeoutError: except asyncio.TimeoutError:
await ctx.send("Timed out, canceling") await ctx.send("Timed out, canceling")
return
arole_list = [] arole_list = []
if answer.content.upper() != "NONE": if answer.content.upper() != "NONE":
@ -76,6 +73,7 @@ class CCRole:
answer = await self.bot.wait_for('message', timeout=120, check=check) answer = await self.bot.wait_for('message', timeout=120, check=check)
except asyncio.TimeoutError: except asyncio.TimeoutError:
await ctx.send("Timed out, canceling") await ctx.send("Timed out, canceling")
return
rrole_list = [] rrole_list = []
if answer.content.upper() != "NONE": if answer.content.upper() != "NONE":
@ -85,12 +83,14 @@ class CCRole:
return return
# Roles to use # Roles to use
await ctx.send('What roles are allowed to use this command? (Must be comma separated)\nSay `None` to allow all roles') await ctx.send(
'What roles are allowed to use this command? (Must be comma separated)\nSay `None` to allow all roles')
try: try:
answer = await self.bot.wait_for('message', timeout=120, check=check) answer = await self.bot.wait_for('message', timeout=120, check=check)
except asyncio.TimeoutError: except asyncio.TimeoutError:
await ctx.send("Timed out, canceling") await ctx.send("Timed out, canceling")
return
prole_list = [] prole_list = []
if answer.content.upper() != "NONE": if answer.content.upper() != "NONE":
@ -106,6 +106,7 @@ class CCRole:
answer = await self.bot.wait_for('message', timeout=120, check=check) answer = await self.bot.wait_for('message', timeout=120, check=check)
except asyncio.TimeoutError: except asyncio.TimeoutError:
await ctx.send("Timed out, canceling") await ctx.send("Timed out, canceling")
return
if answer.content.upper() in ["Y", "YES"]: if answer.content.upper() in ["Y", "YES"]:
targeted = True targeted = True
@ -115,12 +116,16 @@ class CCRole:
await ctx.send("This command will be **`selfrole`**") await ctx.send("This command will be **`selfrole`**")
# Message to send # Message to send
await ctx.send('What message should the bot say when using this command?\nSay `None` to send the default `Success!` message') await ctx.send(
'What message should the bot say when using this command?\n'
'Say `None` to send the default `Success!` message')
try: try:
answer = await self.bot.wait_for('message', timeout=120, check=check) answer = await self.bot.wait_for('message', timeout=120, check=check)
except asyncio.TimeoutError: except asyncio.TimeoutError:
await ctx.send("Timed out, canceling") await ctx.send("Timed out, canceling")
return
text = "Success!" text = "Success!"
if answer.content.upper() != "NONE": if answer.content.upper() != "NONE":
text = answer.content text = answer.content
@ -141,29 +146,31 @@ class CCRole:
[p]ccrole delete yourcommand""" [p]ccrole delete yourcommand"""
guild = ctx.guild guild = ctx.guild
command = command.lower() command = command.lower()
if not await self.config.guild(ctx.guild).cmdlist.get_raw(command, default=None): if not await self.config.guild(guild).cmdlist.get_raw(command, default=None):
await ctx.send("That command doesn't exist") await ctx.send("That command doesn't exist")
else: else:
await self.config.guild(ctx.guild).cmdlist.set_raw(command, value=None) await self.config.guild(guild).cmdlist.set_raw(command, value=None)
await ctx.send("Custom command successfully deleted.") await ctx.send("Custom command successfully deleted.")
@ccrole.command(name="list") @ccrole.command(name="list")
async def ccrole_list(self, ctx): async def ccrole_list(self, ctx):
"""Shows custom commands list""" """Shows custom commands list"""
guild = ctx.guild guild = ctx.guild
commands = await self.config.guild(ctx.guild).cmdlist() cmd_list = await self.config.guild(guild).cmdlist()
if not commands: if not cmd_list:
await ctx.send("There are no custom commands in this server. Use `{}ccrole add` to start adding some.".format(ctx.prefix)) await ctx.send(
"There are no custom commands in this server. Use `{}ccrole add` to start adding some.".format(
ctx.prefix))
return return
commands = ", ".join([ctx.prefix + c for c in sorted(commands.keys())]) cmd_list = ", ".join([ctx.prefix + c for c in sorted(cmd_list.keys())])
commands = "Custom commands:\n\n" + commands cmd_list = "Custom commands:\n\n" + cmd_list
if len(commands) < 1500: if len(cmd_list) < 1500:
await ctx.send(box(commands)) await ctx.send(box(cmd_list))
else: else:
for page in pagify(commands, delims=[" ", "\n"]): for page in pagify(cmd_list, delims=[" ", "\n"]):
await ctx.author.send(box(page)) await ctx.author.send(box(page))
await ctx.send("Command list DM'd") await ctx.send("Command list DM'd")
@ -177,20 +184,18 @@ class CCRole:
except ValueError: except ValueError:
return return
cmdlist = self.config.guild(guild).cmdlist cmdlist = self.config.guild(guild).cmdlist
cmd = message.content[len(prefix):].split()[0] cmd = message.content[len(prefix):].split()[0].lower()
cmd = await cmdlist.get_raw(cmd.lower(), default=None) cmd = await cmdlist.get_raw(cmd, default=None)
if cmd: if cmd is not None:
await self.eval_cc(cmd, message) await self.eval_cc(cmd, message)
async def _get_roles_from_content(self, ctx, content): async def _get_roles_from_content(self, ctx, content):
content_list = content.split(",") content_list = content.split(",")
role_list = []
try: try:
role_list = [discord.utils.get(ctx.guild.roles, name=role.strip(' ')).id for role in content_list] role_list = [discord.utils.get(ctx.guild.roles, name=role.strip(' ')).id for role in content_list]
except: except (discord.HTTPException, AttributeError): # None.id is attribute error
return None return None
else: else:
return role_list return role_list
@ -223,14 +228,13 @@ class CCRole:
if cmd['targeted']: if cmd['targeted']:
try: try:
target = discord.utils.get(message.guild.members, mention=message.content.split()[1]) target = discord.utils.get(message.guild.members, mention=message.content.split()[1])
except: except IndexError: # .split() return list of len<2
target = None target = None
if not target: if not target:
out_message = "This command is targeted! @mention a target\n`{} <target>`".format(message.content.split()[0]) out_message = "This custom command is targeted! @mention a target\n`{} <target>`".format(
message.content.split()[0])
await message.channel.send(out_message) await message.channel.send(out_message)
return return
else: else:
target = message.author target = message.author
@ -251,37 +255,39 @@ class CCRole:
await target.remove_roles(*rrole_list) await target.remove_roles(*rrole_list)
except discord.Forbidden: except discord.Forbidden:
await message.channel.send("Permission error: Unable to remove roles") await message.channel.send("Permission error: Unable to remove roles")
await message.channel.send(cmd['text'])
# {'text': text, 'aroles': arole_list, 'rroles': rrole_list, "proles", prole_list, "targeted": targeted} out_message = self.format_cc(cmd, message, target)
await message.channel.send(out_message)
# def format_cc(self, command, message): def format_cc(self, cmd, message, target):
# results = re.findall("\{([^}]+)\}", command) out = cmd['text']
# for result in results: results = re.findall("{([^}]+)\}", out)
# param = self.transform_parameter(result, message) for result in results:
# command = command.replace("{" + result + "}", param) param = self.transform_parameter(result, message, target)
# return command out = out.replace("{" + result + "}", param)
return out
# def transform_parameter(self, result, message): def transform_parameter(self, result, message, target):
# """ """
# For security reasons only specific objects are allowed For security reasons only specific objects are allowed
# Internals are ignored Internals are ignored
# """ """
# raw_result = "{" + result + "}" raw_result = "{" + result + "}"
# objects = { objects = {
# "message" : message, "message": message,
# "author" : message.author, "author": message.author,
# "channel" : message.channel, "channel": message.channel,
# "server" : message.server "server": message.server,
# } "target": target
# if result in objects: }
# return str(objects[result]) if result in objects:
# try: return str(objects[result])
# first, second = result.split(".") try:
# except ValueError: first, second = result.split(".")
# return raw_result except ValueError:
# if first in objects and not second.startswith("_"): return raw_result
# first = objects[first] if first in objects and not second.startswith("_"):
# else: first = objects[first]
# return raw_result else:
# return str(getattr(first, second, raw_result)) return raw_result
return str(getattr(first, second, raw_result))