async def sec_auth(self, f, cxt): auth = await self.is_admin(cxt.message.author.id) if auth: self.command_lock = True await f(cxt) else: raise je.PermissionError()
async def rolecheck(self, cxt, correct_role): roles = [ role.name == correct_role for role in cxt.message.author.roles ] if not True in roles: raise je.PermissionError() else: return True
async def can_do(self, action, user): # TODO: specific actions to certain roles if user.id in jcommon.ADMIN_IDS: return True for role in user.roles: if role.name == MODERATOR_ROLE_NAME: return True raise je.PermissionError()
async def is_admin(self, uid): if uid in ADMIN_IDS: return True else: raise je.PermissionError()
async def c_meme(self, message, args, cxt): ''' j!meme: Adicione e mostre memes com o josé! **RECOMENDADO**: use `!htmpr` para descobrir problemas técnicos. *alias*: j!m Subcomandos: `j!meme add <trigger>;<meme>` - toda vez que alguém mandar um `!meme get <trigger>`, josé falará `<meme>`(limite de <trigger> é 96 chars) `j!meme get <trigger>` - josé falará o que estiver programado para falar de acordo com `<trigger>` `j!meme search <termo>` - procura o banco de dados de memes por um meme especÃfico `j!meme rm <meme>` - remove um meme `j!meme rename <nome antigo>;<nome novo>` - altera o `<trigger>` de um meme `j!meme owner <meme>` - mostra quem "criou" o `<meme>` `j!meme count` - mostra a quantidade de memes `j!meme stat` - estatÃsticas sobre o uso dos memes `j!meme istat <meme>` - estatÃsticas individuais sobre um meme `j!meme page <página>` - mostra a página tal de todos os memes disponÃveis(inicia de 1, não do 0) `j!meme see @user <página>` - mostra todos os memes que a @pessoa fez(`página` inicia de 0, não de 1) `j!meme check` - checa o banco de dados de memes `j!meme rand` - meme aleatório `j!meme searchc <termos>` - procura o DB de meme qual o valor do meme que bate com os termos Tenha cuidado ao adicionar coisas NSFW. ''' if len(args) < 2: await cxt.say(self.c_meme.__doc__) return command = args[1] if command == 'add': args_s = ' '.join(args[2:]) args_sp = args_s.split(';') try: meme = args_sp[0] url = args_sp[1] except IndexError: await cxt.say("Error parsing arguments") return if len(meme) > 96: await cxt.say("*não tem meme grátis*") return if meme in self.memes: await cxt.say("%s: meme já existe", (meme, )) return url = await self.do_patterns(cxt, meme, url) # create meme in database self.memes[meme] = { 'owner': message.author.id, 'data': url, 'uses': 0, } # save it because of my sanity await self.save_memes() await cxt.say("%s: meme adicionado!", (meme, )) return elif command == 'rm': meme = ' '.join(args[2:]) if meme in self.memes: meme_owner = self.memes[meme]['owner'] is_admin = await self.b_isowner(cxt) if (message.author.id == meme_owner) or is_admin: del self.memes[meme] await self.save_memes() await cxt.say("%s: meme removido", (meme, )) return else: raise je.PermissionError() return else: await cxt.say("%s: meme não encontrado", (meme, )) return elif command == 'save': done = await self.save_memes() if done: await cxt.say("jmemes: banco de dados salvo") else: raise IOError("banco de dados não salvo corretamente") return elif command == 'saveload': self.logger.info("saveloading meme database") done = await self.save_memes() if done: await cxt.say("jmemes: banco de dados salvo") else: raise IOError("banco de dados não salvo corretamente") done = await self.load_memes() if done: await cxt.say("jmemes: banco de dados carregado") else: raise IOError("banco de dados não carregado corretamente") return elif command == 'get': meme = ' '.join(args[2:]) if meme in self.memes: self.memes[meme]['uses'] += 1 await cxt.say(self.memes[meme]['data']) await self.save_memes() else: # find other memes that are like the not found one probables = [key for key in self.memes if meme in key.lower()] if len(probables) > 0: await cxt.say("Didn't you mean `%s`?", (','.join(probables), )) else: await cxt.say("%s: meme não encontrado", (meme, )) return elif command == 'search': term = ' '.join(args[2:]) term = term.lower() if term.strip() == '': await cxt.say("Pesquisas vazias não são permitidas") return # better than google probables = [key for key in self.memes if term in key.lower()] if len(probables) > 0: to_send = ', '.join(probables) # check length of message if len(to_send) > 1995: # 1 9 9 5 await cxt.say( ":elephant: Resultados muito grandes :elephant:") else: await cxt.say(self.codeblock("", to_send)) else: await cxt.say("%r: Nenhum resultado encontrado", (term, )) elif command == 'rename': args_s = ' '.join(args[2:]) args_sp = args_s.split(';') try: oldname = args_sp[0] newname = args_sp[1] except Exception as e: await cxt.say("Error parsing arguments: %r", (e, )) if oldname not in self.memes: await cxt.say("%s: meme não encontrado", (oldname, )) return # swapping old_meme = self.memes[oldname] if old_meme['owner'] != message.author.id: raise je.PermissionError() if newname in self.memes: await cxt.say("`%s`: meme já existe", (newname, )) return self.memes[newname] = { 'owner': message.author.id, 'data': old_meme['data'], } del self.memes[oldname] await cxt.say("`%s` foi renomeado para `%s`!", (oldname, newname)) await self.save_memes() return elif command == 'owner': meme = ' '.join(args[2:]) if meme in self.memes: u = discord.utils.get(self.client.get_all_members(), \ id = self.memes[meme]['owner']) await cxt.say("%s foi criado por %s", (meme, u)) else: await cxt.say("%s: meme não encontrado", (meme, )) return elif command == 'count': await cxt.say("quantidade de memes: %d", (len(self.memes), )) elif command == 'stat': stat = '' copy = dict(self.memes) inconsistency = False for k in copy: inconsistency_report = '' if 'uses' not in copy[k]: inconsistency_report += "%s, " % k inconsistency = True if inconsistency: await cxt.say("INCONSISTENCY: `%s`", (inconsistency_report, )) return i = 1 for key in sorted(copy, key=lambda key: -copy[key]['uses'])[:10]: stat += '%d. %s used %d times\n' % (i, \ key, copy[key]['uses']) i += 1 await cxt.say(self.codeblock('', stat)) return elif command == 'istat': meme = ' '.join(args[2:]) if meme in self.memes: await cxt.say(self.codeblock('', 'uses: %d'), (self.memes[meme]['uses'], )) else: await cxt.say("%s: meme não encontrado", (meme, )) return elif command == 'page': if len(args) < 3: await cxt.say("SyntaxError: `!m page <page>`") return page = args[2] try: page = int(page) except Exception as e: await cxt.say("jmemes: %r", (e, )) return if page < 0: await cxt.say("EI EI EI EI CALMAI CUZAO") return PER_PAGE = 50 min_it = PER_PAGE * (page - 1) max_it = PER_PAGE * page x = sorted(self.memes.keys()) x_slice = x[min_it:max_it] if len(x_slice) < 1: await cxt.say("*nao tem meme gratis*") return report = ', '.join(x_slice) await cxt.say(report) elif command == 'check': for key in self.memes: meme = self.memes[key] if 'uses' not in meme: await cxt.say("INCONSISTENCY(uses): %s", (key, )) self.memes[key].update({"uses": 0}) new_memes = {} for k in self.memes: v = self.memes[k] if v['data'] not in new_memes: new_memes[v['data']] = [] new_memes[v['data']].append(k) for v in new_memes: if len(new_memes[v]) > 1: await cxt.say("DUPLICATE(s): ```%s```\n", (new_memes[v], )) await cxt.say("done.") return elif command == 'see': owner = args[2] try: page = int(args[3]) except: page = 0 owner_id = await jcommon.parse_id(owner, message) from_owner = [ x for x in self.memes if self.memes[x]['owner'] == owner_id ] if len(from_owner) < 1: await cxt.say("*nao tem owner gratis*") return corte = from_owner[page * 50:(page + 1) * 50] res = len(from_owner), len(corte), ', '.join(corte) report = '''Quantidade: %d[%d],\nMemes: %s''' % (res) await cxt.say(report) elif command == 'rand': key = random.choice(list(self.memes.keys())) await cxt.say('%s: %s', ( key, self.memes[key]['data'], )) elif command == 'searchc': terms = ' '.join(args[2:]) terms = terms.lower() if terms.strip() == '': await cxt.say("Pesquisas vazias não são permitidas") return probables = [ key for key in self.memes if terms in self.memes[key]['data'].lower() ] if len(probables) <= 70: await cxt.say("Results: %s", (', '.join(probables), )) elif len(probables) > 70: await cxt.say("[%d results]", (len(probables), )) else: await cxt.say("%r: No Results", (terms, )) else: await cxt.say("Invalid command: %s", (command, )) return