async def _splash(self, ctx): if ctx.guild.splash_url: embed = discord.Embed(title=f'Splash deste servidor!', colour=discord.Colour(random_color()), description='** **', timestamp=datetime.utcnow()) embed.set_footer(text=f'{ctx.author}', icon_url=ctx.author.avatar_url) embed.set_image(url=ctx.guild.splash_url) await ctx.send(embed=embed) else: await ctx.send( f'{ctx.author.mention} este servidor não tem uma foto de fundo no convite! ;-;' )
async def _source(self, ctx): embed = discord.Embed( title=f'Olá {ctx.author.name}, eu sou um bot feito em python, com ' + 'a API do discord e um banco de dados!', colour=discord.Colour(random_color()), description='Caso você queira ver o meu código fonte, clique [aqui]' + '(https://github.com/devRMA/Androxus)\n' + 'Caso você queira ver a documentação da API do discord ' + 'para python, clique [aqui](https://discordpy.readthedo' + 'cs.io/en/latest/index.html).', timestamp=datetime.utcnow()) embed.set_author(name='Androxus', icon_url=f'{self.bot.user.avatar_url}') embed.set_footer(text=f'{ctx.author}', icon_url=f'{ctx.author.avatar_url}') await ctx.send(embed=embed)
async def _adicionar_comando(self, ctx, comando='', resposta='', in_text='t'): in_text = convert_to_bool(in_text) if in_text is None: return await ctx.send( f'Valor ``{in_text}`` inválido! Os valores que eu aceito são: sim, não, yes, no, 0, 1' ) if ctx.message.content.count('"') < 4: return await ctx.send( 'Parece que você digitou o comando errado!\nVocê deve usar o comando assim:\n' + f'{ctx.prefix}adicionar_comando **"**comando**"** **"**resposta**"**' ) if (comando.replace(' ', '') == '') or (resposta.replace(' ', '') == ''): return await self.bot.send_help(ctx) conexao = Conexao() servidor = ServidorRepository().get_servidor(conexao, ctx.guild.id) comando_personalizado = ComandoPersonalizado(servidor, comando.lower(), resposta, in_text) try: ComandoPersonalizadoRepository().create(conexao, comando_personalizado) in_text_str = capitalize(convert_to_string(in_text)) embed = discord.Embed(title=f'Comando adicionado com sucesso!', colour=discord.Colour(random_color()), description='** **', timestamp=datetime.utcnow()) embed.set_footer(text=f'{ctx.author}', icon_url=ctx.author.avatar_url) embed.add_field( name= f'Comando: {comando.lower()}\nResposta: {resposta}\nIgnorar a posição do comando: {in_text_str}', value=f'** **', inline=False) await ctx.send(content=get_emoji_dance(), embed=embed) except Exception as e: raise e finally: conexao.fechar()
async def _botinfo(self, ctx): stopwatch_banco = Stopwatch() conexao = Conexao() stopwatch_banco.stop() # se a pessoa usou o comando, mencionando o bot: if ctx.prefix.replace("!", "").replace(" ", "") == self.bot.user.mention: # vai pegar o prefixo que está no banco prefixo = pegar_o_prefixo(self.bot, ctx, False, conexao) else: # se a pessoa não marcou o bot: prefixo = ctx.prefix embed = discord.Embed( title=f'<:Info:756712227221930102> Detalhes sobre mim!', colour=discord.Colour(random_color()), description= f'Caso você queira saber meus outros comandos, use ``{prefixo}cmds``!', timestamp=datetime.utcnow()) embed.set_author(name='Androxus', icon_url=self.bot.user.avatar_url) embed.set_footer(text=f'{ctx.author}', icon_url=ctx.author.avatar_url) embed.add_field( name=':calendar: Data que fui criado:', value=f'``{self.bot.user.created_at.strftime("%d/%m/%Y")}``', inline=True) embed.add_field( name=':older_adult: Idade:', value=f'``{datetime_format(self.bot.user.created_at)}``', inline=True) embed.add_field(name=':robot: Meu perfil:', value=f'``{str(self.bot.user)}``', inline=True) embed.add_field(name=':id: Meu id:', value=f'``{self.bot.user.id}``', inline=True) embed.add_field(name='<:WumpusCrown:756712226978660392> Meu dono:', value=f'``{self.bot.get_user(self.bot.owner_id)}``', inline=True) embed.add_field( name= '<a:pato:755774683348992060> Quantos servidores estão me usando:', value=f'``{len(self.bot.guilds)}``', inline=True) embed.add_field( name= '<a:parrot_dancando:755774679670718575> Quantas pessoas têm acesso a mim:', # observer, que aqui, estamos pegando a lista de membros e jogando para um set # pois, o "set" não permite que haja itens duplicados, ou seja, fazendo desta forma # cada item vai ser único value=f'``{str(len(set(self.bot.get_all_members())))}``', inline=True) embed.add_field(name=':ping_pong: Latência da API:', value=f'``{int(self.bot.latency * 1000)}ms``', inline=True) embed.add_field( name= '<:DatabaseCheck:756712226303508530> Tempo para se conectar ao banco:', value=f'``{stopwatch_banco}``', inline=True) this_process = psutil.Process(getpid()) embed.add_field(name='<a:loading:756715436149702806> Uso da CPU:', value=f'``{this_process.cpu_percent():.2f}%``', inline=True) embed.add_field( name=':frog: Memória RAM:', value=f'``{(this_process.memory_info().rss / (1e+6)):.2f}Mb' + '/100Mb``', inline=True) embed.add_field( name='<:WumpusPizza:756712226710356122> Versão do discord.py:', value=f'``{discord.__version__}``', inline=True) embed.add_field(name='<:python:756712226210971660> Versão do python:', value=f'``{version[0:5]}``', inline=True) embed.add_field( name=':bank: Banco de dados que estou usando:', value= f'``{InformacoesRepository().get_sql_version(conexao)[:15]}``', inline=True) comandos = 0 for cog in self.bot.cogs: # adiciona os comandos padrões no embed for command in self.bot.get_cog(cog).get_commands(): if not command.hidden: # se o comando não estiver privado comandos += 1 embed.add_field(name=':desktop: Quantos comandos eu tenho:', value=f'``{comandos}``') embed.add_field(name=':stopwatch: Quando eu liguei:', value=f'``{datetime_format(self.bot.uptime)}``', inline=True) embed.add_field(name=':watch: Última atualização que tive foi:', value=f'``{datetime_format(get_last_update())}``', inline=True) await ctx.send(embed=embed) conexao.fechar()
async def _money(self, ctx, *args): """ possibilidades de uso do comando: money → vai responder 1 dólar em reais money 10 → vai responder 10 dólares em reais money eur → vai responder 1 euro em reais money aud 5 → vai responder 5 dólares australianos em reais money eur aud 1 → vai responder 1 euro em dólares australianos """ m_from = 'USD' m_to = 'BRL' m_qtd = 1 # se a pessoa não passou nada, vai continuar com esses valores padrões if args: # se a pessoa passou pelo menos 1 argumento: # se a pessoa digitou "money 2" ou "mon 10.57" if is_number(args[0]): m_qtd = float(args[0]) else: # se o primeiro valor não for número def is_valid(value): # todas as moedas que aceita currencies = [ c.split(' - ')[0] for c in currency_exchange.currencies() ] for currency in currencies: if value == currency: return True return False # se a pessoa usar o comando assim: "money eur" if len(args) == 1: if is_valid(args[0].upper()): m_from = args[0].upper() else: # se não achou o que a pessoa passou: return await self.bot.send_help(ctx) # se a pessoa usou o comando assim: "money aud 5" elif len(args) == 2: if is_valid(args[0].upper()): m_from = args[0].upper() if is_number(args[-1]): m_qtd = float(args[-1]) else: return await self.bot.send_help(ctx) else: return await self.bot.send_help(ctx) # se a pessoa usou o comando assim: "money eur aud 1" elif len(args) == 3: if is_valid(args[0].upper()): m_from = args[0].upper() if is_valid((args[1].upper())): m_to = args[1].upper() if is_number(args[-1]): m_qtd = float(args[-1]) else: return await self.bot.send_help(ctx) else: return await self.bot.send_help(ctx) else: return await self.bot.send_help(ctx) else: # se a pessoa passou mais de 3 parâmetros: return await self.bot.send_help(ctx) result, _ = currency_exchange.exchange(m_from, m_to, m_qtd, False)[0].split(' ') um_valor, _ = currency_exchange.exchange(m_from, m_to, 1, False)[0].split(' ') result = float(f'{float(result.replace(",", "")):.2f}') um_valor = float(f'{float(um_valor):.2f}') embed = discord.Embed( title= f'🪙 {m_qtd:.2f} {m_from.lower()} = {result:.2f} {m_to.lower()}', colour=discord.Colour(random_color()), description='** **', timestamp=datetime.utcnow()) embed.set_footer(text=f'{ctx.author}', icon_url=ctx.author.avatar_url) conexao = Conexao() info = InformacoesRepository() # se ainda não tiver essa conversão no banco: if info.get_dado(conexao, f'{m_from.upper()} to {m_to.upper()}') is None: # vai criar info.create(conexao, f'{m_from.upper()} to {m_to.upper()}', f'{um_valor:.2f}') ultimo_valor = um_valor else: ultimo_valor = float( info.get_dado(conexao, f'{m_from.upper()} to {m_to.upper()}')) info.update(conexao, f'{m_from.upper()} to {m_to.upper()}', f'{um_valor:.2f}') if ultimo_valor > um_valor: msg = f'O valor diminuiu {(ultimo_valor - result):.2f}! <:diminuiu:730088971077681162>' elif ultimo_valor < um_valor: msg = f'O valor aumentou {(result - ultimo_valor):.2f}! <:aumentou:730088970779623524>' else: msg = 'Não teve alteração no valor.' embed.add_field( name=f'Com base na última vez que esse comando foi usado:\n{msg}', value= f'Fonte: [x-rates](https://www.x-rates.com/calculator/?from={m_from}&to=' f'{m_to}&amount={m_qtd})', inline=True) await ctx.send(embed=embed)
def embedHelpCommand(bot: Androxus = None, ctx: commands.Context = None, comando: str = None, descricao: str = None, parametros: list = [], exemplos: list = [], aliases: list = [], perm_pessoa: str = None, perm_bot: str = None, cor: int = None): conexao = Conexao() # se a pessoa usou o comando, mencionando o bot: if ctx.prefix.replace("!", "").replace(" ", "") == bot.user.mention: # vai pegar o prefixo que está no banco prefixo = pegar_o_prefixo(bot, ctx, False, conexao) else: # se a pessoa não marcou o bot: prefixo = ctx.prefix # se a cor não for passada, vai ser usada uma cor aleatória cor_a_usar = cor or random_color() if comando is None: comando = ctx.command.name if descricao is None: descricao = ctx.command.description # precisa fazer uma copia da lista, senão # as alterações feitas aqui # vão refletir no comando fora da função if len(parametros) == 0: parametros = ctx.command.parameters.copy() if len(exemplos) == 0: exemplos = ctx.command.examples.copy() if len(aliases) == 0: aliases = ctx.command.aliases.copy() if perm_pessoa is None: perm_pessoa = ctx.command.perm_user if perm_bot is None: perm_bot = ctx.command.perm_bot exemplo = '\n'.join(exemplos).format(prefix=ctx.prefix, author_mention=ctx.author.mention, this_channel=f'<#{ctx.channel.id}>') como_usar = f'``{prefixo}{comando}`` ' comando_esta_desativado = False if ctx.guild is not None: # se a mensagem foi enviar de um server servidor = ServidorRepository().get_servidor(conexao, ctx.guild.id) cmds_desativados = ComandoDesativadoRepository().get_commands( conexao, servidor) # for em todos os comandos desativados try: for comando_desativado in cmds_desativados: if comando in comando_desativado.comando: # vê se o comando principal, está desativado comando_esta_desativado = True break for comando_alias in aliases: # vai verificar se algum "sinônimo" desse comando, está desativado if comando_alias in comando_desativado.comando: # verifica se o comando está desativado comando_esta_desativado = True raise Exception() except Exception: # foi usado raise error, para conseguir parar os dois laços pass if parametros: # se tiver pelo menos 1 item nos parâmetros for c in range( 0, len(parametros) ): # vai adicionar `` antes, e depois dos parâmetros, em todos os itens parametros[c] = f'``{parametros[c]}``' como_usar += ' '.join( parametros) # adiciona os parâmetros no "como_usar" if aliases: for c in range( 0, len(aliases)): # vai adicionar `` antes, e depois de alias aliases[c] = f'``{prefixo}{aliases[c]}``' if len(aliases) == 1: alias = aliases[0] else: alias = ', '.join(aliases) embed = discord.Embed(title=f'``{prefixo}{comando}``', colour=discord.Colour(cor_a_usar), description=descricao, timestamp=datetime.utcnow()) embed.set_author(name='Androxus', icon_url=bot.user.avatar_url) embed.set_footer(text=f'{ctx.author}', icon_url=ctx.author.avatar_url) embed.add_field(name='**Como usar?**', value=como_usar, inline=False) if parametros: # novamente, só vai entrar, se tiver pelo menos 1 item nos parâmetros embed.add_field( name= '<a:atencao:755844029333110815> Tudo que estiver entre **<>** é obrigatório, e tudo que estiver ' 'entre **[]** é opcional.', value='** **', inline=False) embed.add_field(name='📖 Exemplo', value=exemplo, inline=False) if aliases: embed.add_field(name=':twisted_rightwards_arrows: Sinônimos', value=alias, inline=False) if perm_pessoa or perm_bot: requisito_p = '' requisito_b = '' if perm_pessoa: requisito_p = f'Você precisa ter permissão de ``{perm_pessoa}`` para usar este comando!' if perm_bot: requisito_b = f'\nEu preciso ter permissão de ``{perm_bot}`` para realizar este comando!' embed.add_field(name=':name_badge: Requisitos:', value=f'{requisito_p}{requisito_b}', inline=False) if comando_esta_desativado: # se o comando estiver desativado embed.add_field( name= "<a:atencao:755844029333110815> **O comando foi desativado por algum administrador do server!**", value="**Se você usar este comando, eu não irei responder!**", inline=False) conexao.fechar() return embed
async def on_user_update(self, before, after): if after.bot: return if not self.bot.is_ready(): return if self.bot.maintenance_mode: return conexao = Conexao() servers_with_user = [] for guild in self.bot.guilds: if guild.get_member(after.id) is not None: servers_with_user.append(ServidorRepository().get_servidor( conexao, guild.id)) conexao.fechar() if len(servers_with_user) == 0: return if before.name != after.name: embed = discord.Embed( title='Nome alterado', colour=discord.Colour(random_color()), description=f'O(A) {after.name} mudou de nome!\n' f'User: {after.mention}\n' f'Id: {after.id}\n' f'Nome antigo: {before.name}\n' f'Nome novo: {after.name}', timestamp=datetime.utcnow()) embed.set_thumbnail(url=after.avatar_url) for server in servers_with_user: if server.channel_id_log is not None: channel = self.bot.get_channel(server.channel_id_log) if (channel is not None) and server.nome_alterado: await channel.send(embed=embed) if before.discriminator != after.discriminator: embed = discord.Embed( title='Tag alterada', colour=discord.Colour(random_color()), description=f'O(A) {after.name} mudou a tag!\n' f'User: {after.mention}\n' f'Id: {after.id}\n' f'Tag antiga: {before.discriminator}\n' f'Tag nova: {after.discriminator}', timestamp=datetime.utcnow()) embed.set_thumbnail(url=after.avatar_url) for server in servers_with_user: if server.channel_id_log is not None: channel = self.bot.get_channel(server.channel_id_log) if (channel is not None) and server.tag_alterado: await channel.send(embed=embed) if before.avatar_url != after.avatar_url: url_antigo = str(before.avatar_url_as(format='webp')) if url_antigo.find('?size=') != -1: url_antigo = url_antigo[:url_antigo.rfind('?size=')] url_novo = str(after.avatar_url_as(format='webp')) async with aiohttp.ClientSession() as session: async with session.get(url_antigo) as resp: if resp.status == 200: response_antigo = BytesIO(await resp.read()) else: return async with session.get(url_novo) as resp: if resp.status == 200: response_novo = BytesIO(await resp.read()) else: return avatar_antigo = Image.open(response_antigo).resize( (512, 512), Image.ANTIALIAS) avatar_novo = Image.open(response_novo).resize((512, 512), Image.ANTIALIAS) base = Image.new('RGBA', (1024, 512), (0, 0, 0, 0)) base.paste(avatar_antigo, (0, 0)) base.paste(avatar_novo, (512, 0)) arr = BytesIO() base.save(arr, format='PNG') arr.seek(0) file = discord.File(arr, filename='avatar.png') embed = discord.Embed( title='Avatar alterado', colour=discord.Colour(random_color()), description=f'O(A) {after.name} mudou o avatar!\n' f'User: {after.mention}\n' f'Id: {after.id}\n' f'[Avatar antigo]({before.avatar_url})' f' → [avatar novo]({after.avatar_url})', timestamp=datetime.utcnow()) embed.set_image(url='attachment://avatar.png') for server in servers_with_user: if server.channel_id_log is not None: channel = self.bot.get_channel(server.channel_id_log) if (channel is not None) and server.avatar_alterado: await channel.send(file=file, embed=embed)
async def on_member_update(self, before, after): if after.bot: return if not self.bot.is_ready(): return if self.bot.maintenance_mode: return conexao = Conexao() server = ServidorRepository().get_servidor(conexao, after.guild.id) conexao.fechar() if server is None: return if server.channel_id_log is not None: channel = self.bot.get_channel(server.channel_id_log) if channel is not None: if before.nick != after.nick: if server.nick_alterado: embed = discord.Embed( title='Nick alterado', colour=discord.Colour(random_color()), description=f'O(A) {after.name} mudou de nick!\n' f'User: {after.mention}\n' f'Id: {after.id}\n' f'Nick antigo: {before.nick}\n' f'Nick novo: {after.nick}', timestamp=datetime.utcnow()) embed.set_thumbnail(url=str(after.avatar_url)) await channel.send(embed=embed) if before.roles != after.roles: if server.role_alterado: cargos = [ f'<@&{c.id}>' for c in difference_between_lists( before.roles, after.roles) ] # se a pessoa ficou com mais cargos, do que ela tinha antes if len(before.roles) < len(after.roles): desc = None if len(cargos) == 1: desc = f'Novo cargo: {cargos[0]}' elif len(cargos) > 1: desc = 'Novos cargo: ' + ', '.join(cargos) else: # se foi o contrário desc = None if len(cargos) == 1: desc = f'Cargo removido: {cargos[0]}' elif len(cargos) > 1: desc = 'Cargos removidos: ' + ', '.join(cargos) embed = discord.Embed( title='Cargos alterados', colour=discord.Colour(random_color()), description= f'O(A) {after.name} sofreu alteração nos cargos!\n' f'User: {after.mention}\n' f'Id: {after.id}\n' f'{desc}', timestamp=datetime.utcnow()) embed.set_thumbnail(url=str(after.avatar_url)) await channel.send(embed=embed) if (before.premium_since is None) and (after.premium_since is not None): if server.role_alterado: # pessoa começou a dar boost embed = discord.Embed( title='Novo booster', colour=discord.Colour(0xffdcf4), description= f'O(A) {after.name} começou a dar boost!\n' f'User: {after.mention}\n' f'Id: {after.id}\n', timestamp=datetime.utcnow()) embed.set_thumbnail(url=str(after.avatar_url)) await channel.send(embed=embed)
async def _serverinfo(self, ctx): bots = 0 for member in ctx.guild.members: if member.bot: bots += 1 embed = discord.Embed( title=f'Informações sobre este servidor!', colour=discord.Colour(random_color()), description= 'O máximo de informação que eu consegui encontrar sobre este servidor.', timestamp=datetime.utcnow()) embed.set_footer(text=f'{ctx.author}', icon_url=f'{ctx.author.avatar_url}') if ctx.guild.icon: embed.set_thumbnail(url=ctx.guild.icon_url) if ctx.guild.banner: embed.set_image(url=ctx.guild.banner_url) elif ctx.guild.splash_url: embed.set_image(url=ctx.guild.splash_url) elif ctx.guild.discovery_splash_url: embed.set_image(url=ctx.guild.discovery_splash_url) embed.add_field(name='🪧 Servidor', value=f'`{ctx.guild.name}` ({ctx.guild.id})', inline=True) if ctx.guild.description: embed.add_field(name='📕 Descrição do servidor', value=f'{ctx.guild.description}', inline=True) embed.add_field(name='👑 Dono', value=f'`{ctx.guild.owner}` ({ctx.guild.owner_id})', inline=True) embed.add_field( name=f'👥 Membros ({ctx.guild.member_count})', value=f'🧍 Pessoas: {ctx.guild.member_count - bots}\n🤖 Bots: {bots}', inline=True) embed.add_field(name='🙂 Emojis', value=f'{len(ctx.guild.emojis)}', inline=True) embed.add_field( name= f'💬 Canais ({len(ctx.guild.text_channels) + len(ctx.guild.voice_channels)})', value= f'📖 Chat: {len(ctx.guild.text_channels)}\n🗣 Voz: {len(ctx.guild.voice_channels)}', inline=True) embed.add_field(name='🏅 Cargos', value=f'{len(ctx.guild.roles)}', inline=True) embed.add_field(name='🗺 Região', value=f'{str(ctx.guild.region).capitalize()}', inline=True) embed.add_field(name='📅 Criado em:', value=f'{ctx.guild.created_at.strftime("%d/%m/%Y")}\n' f'({datetime_format(ctx.guild.created_at)})', inline=True) rank_members = [ str(c) for c in sorted(ctx.guild.members, key=lambda x: x.joined_at) ] embed.add_field( name='📥 Entrei aqui em:', value=f'`{ctx.guild.me.joined_at.strftime("%d/%m/%Y")}`\n' f'({datetime_format(ctx.guild.me.joined_at)})\n' f'Estou na posição `{rank_members.index(str(ctx.guild.me)) + 1}°` no rank dos ' 'membros mais antigos.', inline=True) await ctx.send(embed=embed)
async def _avatar(self, ctx, *args): if ctx.message.mentions: # se tiver alguma menção na mensagem embed = discord.Embed( title=f'Avatar do(a) {str(ctx.message.mentions[0])}!', colour=discord.Colour(random_color()), description='** **', timestamp=datetime.utcnow()) embed.set_footer(text=f'{ctx.author}', icon_url=ctx.author.avatar_url) embed.set_image(url=ctx.message.mentions[0].avatar_url) return await ctx.send(embed=embed) else: # se a pessoa não mencionou ninguém, entra aqui if args: # se a pessoa passou pelo menos alguma coisa if len(args) == 1: # se a pessoa passou 1item try: # vai tentar converter o argumento para int id_de_quem_ver_o_avatar = int(args[0]) # conversão # se chegou aqui, vai tentar pegar o usuário com esse id user = self.bot.get_user(id_de_quem_ver_o_avatar) # se o bot não achou um user, ele vai pega pela API do discord if user is None: try: user = await self.bot.fetch_user( id_de_quem_ver_o_avatar) except discord.errors.NotFound: user = None except discord.HTTPException: user = None # se mesmo assim, não achar o user if user is None: return await ctx.send( f'{ctx.author.mention} não consegui um usuário com este id!' ) # vai mandar o avatar desta pessoa e = discord.Embed(title=f'Avatar do(a) {str(user)}!', colour=discord.Colour( random_color()), description='** **', timestamp=datetime.utcnow()) e.set_footer(text=f'{ctx.author}', icon_url=f'{ctx.author.avatar_url}') e.set_image(url=user.avatar_url) return await ctx.send(embed=e) except ValueError: # se der erro, é porque a pessoa não passou apenas números pass # se chegou até aqui, é porque a pessoa não passou um id ou passou mais de 1 item user = None args = ' '.join(args) # listas que vão ser usadas caso a pessoa digite um nome inválido name = [] name_tag = [] nickname = [] if ctx.guild: for member in ctx.guild.members: # se a pessoa tiver um nick if member.nick is not None: # vai ver se a pessoa digitou esse nick if member.nick.lower() == args.lower(): user = member break nickname.append(member.nick.lower()) # se a pessoa passou o nome, nome#tag de algum membro: if (args.lower() == member.name.lower()) or ( args.lower() == str(member).lower()): user = member break name.append(member.name.lower()) name_tag.append(str(member).lower()) # se não achou a pessoa na guild if user is None: for _user in self.bot.users: # se a pessoa passou o nome ou nome#tag de algum user que o bot tem acesso: if (args.lower() == _user.name) or (args.lower() == str(_user)): user = _user break name.append(_user.name.lower()) name_tag.append(str(_user).lower()) # se o bot não achou a pessoa if user is None: # vai passar para set, apenas para eliminar itens repetidos name = list(set(name)) name_tag = list(set(name_tag)) nickname = list(set(nickname)) msg = f'{ctx.author.mention} Eu não achei nenhum usuário com este nome/nick.' user_by_nick = get_most_similar_items_with_similarity( args, nickname) # se veio pelo menos 1 user pelo nick if user_by_nick: # vai pegar o nick mais parecido que veio, e se a similaridade for maior que 60%: if user_by_nick[0][-1] > 0.6: msg += f'\nVocê quis dizer `{user_by_nick[0][0]}` ?' return await ctx.send(msg) # se não passou pelo return de cima, vai ver se acha algum nome parecido com o que a pessoa # digitou user_by_name_tag = get_most_similar_items_with_similarity( args, name_tag) # se veio pelo menos 1 user pelo nametag if user_by_name_tag: # se for pelo menos 60% similar: if user_by_name_tag[0][-1] > 0.6: msg += f'\nVocê quis dizer `{user_by_name_tag[0][0]}` ?' return await ctx.send(msg) # se não passou pelo return de cima, vai ver se acha algum user#tag parecido com o que a pessoa # digitou user_by_name = get_most_similar_items_with_similarity( args, name) # se veio pelo menos 1 user pelo nametag if user_by_name: # vai pegar o nome mais parecido que veio e se a similaridade for maior que 60%: if user_by_name[0][-1] > 0.6: msg += f'\nVocê quis dizer `{user_by_name[0][0]}` ?' return await ctx.send(msg) # se não passou por nenhum if de cima, vai mandar a mensagem dizendo que não achou return await ctx.send(msg) # se chegou aqui, vai mandar o avatar do user e = discord.Embed(title=f'Avatar do(a) {str(user)}!', colour=discord.Colour(random_color()), description='** **', timestamp=datetime.utcnow()) e.set_footer(text=f'{ctx.author}', icon_url=f'{ctx.author.avatar_url}') e.set_image(url=user.avatar_url) return await ctx.send(embed=e) else: # se a pessoa não passou nenhum argumento: embed = discord.Embed(title=f'Seu avatar!', colour=discord.Colour(random_color()), description='** **', timestamp=datetime.utcnow()) embed.set_footer(text=f'{ctx.author}', icon_url=ctx.author.avatar_url) embed.set_image(url=ctx.author.avatar_url) return await ctx.send(embed=embed)
async def _userinfo(self, ctx, *args): try: user = None if ctx.message.mentions: # se tiver alguma menção na mensagem user = ctx.message.mentions[0] # vai pegar a primeira menção else: # se a pessoa não mencionou ninguém, entra aqui if args: # se a pessoa passou pelo menos alguma coisa try: # vai tentar converter o primeiro argumento para int id_user = int(args[0]) # conversão if ctx.guild: user = ctx.guild.get_member( id_user ) # vai tentar pegar o membro do server com esse id if user is None: # se não achou na guild, vai ver se o bot acha user = self.bot.get_user(id_user) # se o bot não achou um user, ele vai pega pela API do discord if user is None: try: user = await self.bot.fetch_user(id_user) except discord.errors.NotFound: user = None except discord.HTTPException: user = None # se mesmo assim, não achar o user if user is None: return await ctx.send( f'{ctx.author.mention} não consegui um usuário com este id!' ) except ValueError: # se der erro, é porque a pessoa não passou número no primeiro argumento user = None # se o user for None if user is None: # se entrou aqui, é o user ainda não foi achado args = ' '.join(args) # listas que vão ser usadas caso a pessoa digite um nome inválido name = [] name_tag = [] nickname = [] # se o comando foi usado de um servidor: if ctx.guild: # vai procurar o membro passado pela pessoa for member in ctx.guild.members: # se a pessoa tiver um nick if member.nick is not None: # vai ver se a pessoa digitou esse nick if member.nick.lower() == args.lower(): user = member break # lista que vai ser usada caso não ache o membro nickname.append(member.nick.lower()) # se a pessoa passou o nome ou nome#tag de algum membro: if (args.lower() == member.name.lower()) or ( args.lower() == str(member).lower()): user = member break # listas que vão ser usadas caso não ache o membro name.append(member.name.lower()) name_tag.append(str(member).lower()) # se não achou a pessoa na guild if user is None: # vai ver se o bot acha a pessoa for _user in self.bot.users: # se a pessoa passou o nome ou nome#tag de algum user que o bot tem acesso: if (args.lower() == _user.name) or (args.lower() == str(_user)): user = _user break name.append(_user.name.lower()) name_tag.append(str(_user).lower()) # se o bot não achou nem o membro nem a pessoa if user is None: # é passado para um set, apenas para eliminar os itens repetidos name = list(set(name)) name_tag = list(set(name_tag)) nickname = list(set(nickname)) # mensagem padrão msg = f'{ctx.author.mention} Eu não achei nenhum usuário com este nome/nick.' user_by_nick = get_most_similar_items_with_similarity( args, nickname) # se veio pelo menos 1 user pelo nick if user_by_nick: # vai pegar o nick mais parecido que veio, e se a similaridade for maior que 60%: if user_by_nick[0][-1] > 0.6: msg += f'\nVocê quis dizer `{capitalize(user_by_nick[0][0])}` ?' raise InvalidArgument(msg=msg) # se não passou pelo return de cima, vai ver se acha algum nome parecido # com o que a pessoa digitou user_by_name_tag = get_most_similar_items_with_similarity( args, name_tag) # se veio pelo menos 1 user pelo nametag if user_by_name_tag: # se for pelo menos 60% similar: if user_by_name_tag[0][-1] > 0.6: msg += f'\nVocê quis dizer `{capitalize(user_by_name_tag[0][0])}` ?' raise InvalidArgument(msg=msg) # se não passou pelo return de cima, vai ver se acha algum user#tag parecido com o # que a pessoa digitou user_by_name = get_most_similar_items_with_similarity( args, name) # se veio pelo menos 1 user pelo nametag if user_by_name: # vai pegar o nome mais parecido que veio e se a similaridade for maior que 60%: if user_by_name[0][-1] > 0.6: msg += f'\nVocê quis dizer `{capitalize(user_by_name[0][0])}` ?' raise InvalidArgument(msg=msg) # se não passou por nenhum if de cima, vai mandar a mensagem dizendo que não achou raise InvalidArgument(msg=msg) else: # se a pessoa não passou nenhum argumento: user = ctx.author roles = None if hasattr(user, 'roles'): roles = ', '.join([ f"<@&{x.id}>" for x in sorted( user.roles, key=lambda x: x.position, reverse=True) if x.id != ctx.guild.default_role.id ]) if len(user.roles) > 1 else None if hasattr(user, 'top_role'): cor = user.top_role.colour.value else: cor = discord.Colour(random_color()) info2 = None badges = '' pf = user.public_flags if ctx.guild: if ctx.guild.owner_id == user.id: badges += '👑' if pf.staff: badges += '<:staff:767508404687863844>' if pf.partner: badges += '<:parceiro:767508978162073670>' if pf.hypesquad: badges += '<:hypesquad:767509441926004746>' if pf.bug_hunter or pf.bug_hunter_level_2: badges += '<:bug_hunter:767510394021216277>' if pf.hypesquad_bravery: badges += '<:hypesquad_bravery:767510882238333009>' if pf.hypesquad_brilliance: badges += '<:hypesquad_brilliance:767511165173235763>' if pf.hypesquad_balance: badges += '<:hypesquad_balance:767511585080999966>' if pf.early_supporter: badges += '<:early_supporter:767511883368366100>' if user.bot: badges += '<:bot:763808270426177538>' if pf.verified_bot_developer or pf.early_verified_bot_developer: badges += '<:dev_tag:763812174514487346>' # como o discord não deixar bots verem o profile do user # e no profile que diz se a pessoa tem nitro, vamos ver se # ela tem um gif no avatar, se tiver, ela tem nitro # ou vamos ver se ela está dando boost no servidor if user.is_avatar_animated(): badges += '<a:nitro:767516060785311744>' elif hasattr(user, 'premium_since'): if user.premium_since is not None: badges += '<a:nitro:767516060785311744>' if hasattr(user, 'premium_since'): if user.premium_since is not None: badges += '<a:boost:767518522619985930>' status = '' if hasattr(user, 'raw_status'): if user.raw_status == 'online': status = '<:online:768461948743843861>' elif user.raw_status == 'dnd': status = '<:dnd:768461948928655381>' elif user.raw_status == 'idle': status = '<:idle:768461949041246229>' elif (user.raw_status == 'offline') or (user.raw_status == 'invisible'): status = '<:offline:768461948790243349>' info1 = discord.Embed( title=f'{badges} {user.display_name} {status}', colour=cor, description='** **', timestamp=datetime.utcnow()) info1.set_footer(text=f'{ctx.author}', icon_url=ctx.author.avatar_url) info1.set_thumbnail(url=user.avatar_url) info1.add_field(name="📑 Nome e tag:", value=f'`{user}`', inline=True) info1.add_field(name="🆔 Id: ", value=f'``{user.id}``', inline=True) if hasattr(user, 'raw_status'): # se a pessoa não estiver offline ou invisivel if (user.raw_status != 'offline') and (user.raw_status != 'invisible'): if user.is_on_mobile(): plataforma = '📱 Celular' else: plataforma = '💻 Pc' info1.add_field(name="🗯 Está no:", value=f'``{plataforma}``', inline=True) if hasattr(user, 'activities'): activities = user.activities streaming = False custom = False playing = False if len(activities) != 0: for activity in activities: if (activity.type.name == 'streaming') and (not streaming): info1.add_field( name= '<:stream:768461948538454017> Fazendo live', value= f'**🎙 Plataforma**: `{activity.platform}`\n' f'**🏷 Nome da live**: `{activity.name}`\n' f'**🕛 Começou**: `{datetime_format(activity.created_at)}`', inline=True) streaming = True elif (activity.type.name == 'custom') and (not custom): if (activity.emoji is not None) or (activity.name is not None): if activity.emoji is not None: if activity.emoji.id in [ c.id for c in self.bot.emojis ]: emoji = f'{activity.emoji}' else: emoji = f'❓' else: emoji = '`🚫 Nulo`' if activity.name is not None: texto = f'`{activity.name}`' else: texto = '`🚫 Nulo`' info1.add_field( name= '<a:disco:763811701589803098> Status personalizado', value=f'🔰 Emoji: {emoji}\n' f'🖋 Frase: {texto}', inline=True) custom = True elif (activity.type.name == 'playing') and (not playing): if activity.start is not None: value = f'`{activity.name}`\n**🕛 Começou a jogar:**\n' + \ f'`{datetime_format(activity.start)}`' else: value = f'`{activity.name}`' info1.add_field(name='🕹 Jogando', value=value, inline=True) playing = True if hasattr(user, 'nick'): if user.nick is not None: info1.add_field(name="🔄 Nickname", value=f'``{user.nick}``', inline=True) info1.add_field( name="🗓 Conta criada em:", value= f'``{user.created_at.strftime("%d/%m/%Y")}``({datetime_format(user.created_at)})', inline=True) if hasattr(user, 'joined_at'): rank_members = [ str(c) for c in sorted(user.guild.members, key=lambda x: x.joined_at) ] info1.add_field( name="📥 Entrou no servidor em:", value= f'`{user.joined_at.strftime("%d/%m/%Y")}`({datetime_format(user.joined_at)})' f'\n**🏆 Está na `{rank_members.index(str(user)) + 1}°` posição, ' 'no rank dos membros mais antigos!**', inline=True) if user.premium_since is not None: info1.add_field( name= "<a:boost:767518522619985930> Começou a dar boost neste servidor em:", value=f'`{user.premium_since.strftime("%d/%m/%Y")}`(' f'{datetime_format(user.premium_since)})', inline=True) # só vai mostrar as permissões da pessoa, se ela estiver no server info2 = discord.Embed(title=f'{badges} {user.display_name}', colour=cor, description='** **', timestamp=datetime.utcnow()) info2.set_footer(text=f'{ctx.author}', icon_url=ctx.author.avatar_url) info2.set_thumbnail(url=user.avatar_url) if roles is not None: info2.add_field( name=f'🏅 Cargos({len(roles.split(", "))}):', value=roles, inline=False) all_perms = user.permissions_in(ctx.message.channel) perms = [] for atributo in dir(all_perms): if isinstance(getattr(all_perms, atributo), bool): if getattr(all_perms, atributo): perms.append(atributo) perms_traduzidas = { 'add_reactions': 'adicionar reações', 'administrator': 'administrador', 'attach_files': 'anexar arquivos', 'ban_members': 'banir membros', 'change_nickname': 'mudar apelido', 'create_instant_invite': 'criar convite', 'embed_links': 'enviar links', 'kick_members': 'expulsar membros', 'manage_channels': 'gerenciar canais', 'manage_emojis': 'gerenciar emojis', 'manage_guild': 'gerenciar servidor', 'manage_messages': 'gerenciar mensagens', 'manage_nicknames': 'gerenciar apelidos', 'manage_permissions': 'gerenciar permissões', 'manage_roles': 'gerenciar cargos', 'manage_webhooks': 'gerenciar webhooks', 'mention_everyone': 'mencionar everyone', 'read_message_history': 'ler histórico de mensagens', 'read_messages': 'ver mensagens', 'send_messages': 'enviar mensagens', 'send_tts_messages': 'enviar mensagem com tts', 'view_audit_log': 'ver registro de auditoria', 'view_channel': 'ver canal', 'view_guild_insights': 'ver desempenho do servidor', 'use_external_emojis': 'usar emojis externos' } for c in range(0, len(perms)): # vai substituir os "_" por espaços e tirar o external_emojis for perm_traducao in perms_traduzidas.items(): if perm_traducao[0] == perms[c]: perms[c] = f"``{perm_traducao[-1]}``" break if 'external_emojis' in perms: perms.pop(perms.index('external_emojis')) if len(perms) >= 1: info2.add_field( name=f'📌 Permissões neste chat({len(perms)}):', value=capitalize(', '.join(perms)), inline=False) else: info2.add_field( name=f'📌 Permissão neste chat(0):', value= 'Este usuário não tem nenhuma permissão, neste chat!', inline=False) except InvalidArgument as erro: return await ctx.send(erro.msg) async def menus_user_info(ctx, msg): def check_page1( reaction, user, msg ): # fica verificando a pagina 1, para ver se é para ir para a pagina 2 user_check = user.id == ctx.author.id reaction_check = str(reaction.emoji) == '➡' msg_check = msg.id == reaction.message.id return user_check and reaction_check and msg_check def check_page2( reaction, user, msg ): # fica verificando a pagina 2, para ver se é para ir para a pagina 1 user_check = user.id == ctx.author.id reaction_check = str(reaction.emoji) == '⬅' msg_check = msg.id == reaction.message.id return user_check and reaction_check and msg_check async def check_reactions_without_perm(ctx, bot, msg): while True: while True: reaction, user = await bot.wait_for('reaction_add', timeout=900.0) if check_page1(reaction, user, msg): break await msg.delete() msg = await ctx.send(embed=info2) await msg.add_reaction('⬅') while True: reaction, user = await bot.wait_for('reaction_add', timeout=900.0) if check_page2(reaction, user, msg): break await msg.delete() msg = await ctx.send(embed=info1) await msg.add_reaction('➡') async def check_reactions_with_perm(bot, msg): while True: while True: reaction, user = await bot.wait_for('reaction_add', timeout=900.0) if check_page1(reaction, user, msg): break await msg.clear_reactions() await msg.add_reaction('⬅') await msg.edit(embed=info2) while True: reaction, user = await bot.wait_for('reaction_add', timeout=900.0) if check_page2(reaction, user, msg): break await msg.clear_reactions() await msg.add_reaction('➡') await msg.edit(embed=info1) # se o bot tiver perm pra usar o "clear_reactions" if ctx.guild.me.guild_permissions.manage_messages: await check_reactions_with_perm(self.bot, msg) else: # se o bot não tiver permissão: await check_reactions_without_perm(ctx, self.bot, msg) msg_bot = await ctx.send(embed=info1) if info2: # se tiver o info2, significa que foi usado num servidor await msg_bot.add_reaction('➡') try: # vai fica 1 minuto e meio esperando o usuário apertas nas reações await asyncio.wait_for(menus_user_info(ctx, msg_bot), timeout=90.0) except asyncio.TimeoutError: # se acabar o tempo pass
async def _ban(self, ctx, member: discord.Member = None, *args): if isinstance(args, tuple): # se chegar como tupla, vai transformar em lista args = list(args) # se a pessoa passou pelo menos o membro, ou algum argumento if args or member: if not member: # se o membro não foi marcado # vai ver se a pessoa passou um id try: # vai tentar converter para int, o primeiro valor que a pessoa passou id = int(args[0]) except ValueError: # se não conseguir: return await self.bot.send_help(ctx) else: # se não entrou no except args.pop(0) # vai tentar achar o membro com esse id try: member = await ctx.guild.fetch_member(id) except: member = None if member is None: # se não achou o membro: return await ctx.send( f'Não consegui encontrar o membro com id `{id}`!') # vai verificar se a pessoa pode usar o comando if ctx.guild.owner == member: return await ctx.send( f'{ctx.author.mention} você não pode banir o dono do servidor! ' + '<:ah_nao:758003636822474887>') elif member == ctx.author: return await ctx.send( f'{ctx.author.mention} você não pode se banir! ' + '<:ah_nao:758003636822474887>') elif member == self.bot.user: return await ctx.send( f'{ctx.author.mention} eu não posso me banir! ' + '<:ah_nao:758003636822474887>') elif ctx.author.id in get_configs( )['owners'] or ctx.author == ctx.guild.owner: pass # se for o dono do bot, ou dono do servidor, vai ignorar as próxima verificação elif ctx.author.top_role <= member.top_role: return await ctx.send( f'{ctx.author.mention} você só pode banir pessoas que tenham cargo mais ' + 'baixo que o seu!') # se sobrou algum argumento, é porque a pessoa passou um motivo reason = None if args: reason = ' '.join(args) else: # se a pessoa não passou nada: return await self.bot.send_help(ctx) embed = discord.Embed( title=f'<a:banned:756138595882107002> Usuário banido!', colour=discord.Colour(random_color()), description=f'Usuário: {member}\nId: {member.id}\nMotivo: ' + f'{str(reason).replace("None", "nulo")}', timestamp=datetime.utcnow()) embed.set_footer(text=str(ctx.author), icon_url=ctx.author.avatar_url) msg_ban = f'{member.mention} Você foi banido do servidor {ctx.guild}!' if reason: msg_ban += f'\nPelo motivo: {reason}' try: if not member.bot: msg = await member.send(msg_ban) except: pass reason = f'Banido por: {ctx.author} —— Motivo: {str(reason).replace("None", "nulo")}' try: await ctx.guild.ban(member, reason=reason) except discord.errors.Forbidden: try: await msg.delete() except: pass await ctx.send( 'Eu não tenho permissão para banir este usuário. <a:sad:755774681008832623>' ) else: await ctx.send(embed=embed)
async def _regra_de_tres(self, ctx): # TODO await ctx.send( f'Olá {ctx.author.mention}!\nPrimeiro, qual regra de três você quer que eu faça? ' + '(``inversamente``/``diretamente``)') def check(message): return message.author == ctx.author try: msg = await self.bot.wait_for('message', check=check, timeout=30) except asyncio.TimeoutError: return await ctx.send('Tempo esgotado!') modo = None path = '' if 'inversamente'.startswith(msg.content.lower()): modo = 'i' elif 'diretamente'.startswith(msg.content.lower()): modo = 'd' if modo: if exists('discord_bot/'): path = 'discord_bot/' else: path = './' if modo == 'd': await ctx.send( 'Modo selecionado: ``diretamente proporcional``!') valores = [['primeiro', 'v1'], ['segundo', 'v2'], ['terceiro', 'v3']] pos_text_list = [[(115, 210), 'v1'], [(352, 210), 'v2'], [(115, 406), 'v3'], [(363, 406), 'x']] valores_user = [] for valor in valores: img = Image.open(f'{path}images/regra_de_tres_direta.png') draw = ImageDraw.Draw(img) font = ImageFont.truetype( f'{path}fonts/helvetica-normal.ttf', 25) black = (0, 0, 0) # rgb red = (255, 0, 0) # rgb for pos_text in pos_text_list: if pos_text[-1] == valor[-1]: draw.text(pos_text[0], pos_text[-1], red, font=font) else: draw.text(pos_text[0], pos_text[-1], black, font=font) img.save(f'{path}images/regra_de_tres_direta-edited.png') img.close() await ctx.send( f'Agora, eu preciso que você me fale o {valor[0]} valor (**{valor[-1]} na foto**).', file=discord.File( f'{path}images/regra_de_tres_direta-edited.png')) try: value = await self.bot.wait_for('message', check=check, timeout=30) try: value = int(value.content) except ValueError: try: value = float(value.content.replace(',', '.')) except ValueError: return await ctx.send( f'O valor ``{value.content}`` não é um número!' ) except asyncio.TimeoutError: return await ctx.send('Tempo esgotado!') for c in range(0, len(pos_text_list)): if pos_text_list[c][-1] == valor[-1]: pos_text_list[c][-1] = f'{value}' valores_user.append(value) mult = valores_user[-1] * valores_user[1] resp = mult / valores_user[0] embed = discord.Embed( title=f'Regra de 3!', colour=discord.Colour(random_color()), description='Passo a passo da resolução:\n' + f'**{valores_user[0]}x = {valores_user[-1]}×{valores_user[1]}**\n' + f'**{valores_user[0]}x = {mult}**\n' + f'**x = {mult}/{valores_user[0]}**\n' + f'**x = {resp:.2f}**', timestamp=datetime.utcnow()) embed.set_author(name='Androxus', icon_url=self.bot.user.avatar_url) embed.set_footer(text=f'{ctx.author}', icon_url=ctx.author.avatar_url) img = Image.open(f'{path}images/regra_de_tres_direta.png') draw = ImageDraw.Draw(img) font = ImageFont.truetype(f'{path}fonts/helvetica-normal.ttf', 25) black = (0, 0, 0) # rgb red = (255, 0, 0) # rgb pos1 = (115, 210) # x e y pos2 = (352, 210) # x e y pos3 = (115, 406) # x e y posx = (363, 406) # x e y text1 = str(valores_user[0]) text2 = str(valores_user[1]) text3 = str(valores_user[2]) x = f'{resp:.2f}' draw.text(pos1, text1, black, font=font) draw.text(pos2, text2, black, font=font) draw.text(pos3, text3, black, font=font) draw.text(posx, x, red, font=font) img.save(f'{path}images/regra_de_tres_direta-edited.png') img.close() await ctx.send( embed=embed, file=discord.File( f'{path}images/regra_de_tres_direta-edited.png')) remove(f'{path}images/regra_de_tres_direta-edited.png') else: await ctx.send( 'Modo selecionado: ``inversamente proporcional``!') valores = [['primeiro', 'v1'], ['segundo', 'v2'], ['terceiro', 'v3']] pos_text_list = [[(60, 280), 'v1'], [(400, 280), 'v2'], [(60, 370), 'v3'], [(400, 370), 'x']] valores_user = [] for valor in valores: img = Image.open(f'{path}images/regra_de_tres_inversa.png') draw = ImageDraw.Draw(img) font = ImageFont.truetype( f'{path}fonts/helvetica-normal.ttf', 25) black = (0, 0, 0) # rgb red = (255, 0, 0) # rgb for pos_text in pos_text_list: if pos_text[-1] == valor[-1]: draw.text(pos_text[0], pos_text[-1], red, font=font) else: draw.text(pos_text[0], pos_text[-1], black, font=font) img.save(f'{path}images/regra_de_tres_inversa-edited.png') img.close() await ctx.send( f'Agora, eu preciso que você me fale o {valor[0]} valor (**{valor[-1]} na foto**).', file=discord.File( f'{path}images/regra_de_tres_inversa-edited.png')) try: value = await self.bot.wait_for('message', check=check, timeout=30) try: value = int(value.content) except ValueError: try: value = float(value.content.replace(',', '.')) except ValueError: return await ctx.send( f'O valor ``{value.content}`` não é um número!' ) except asyncio.TimeoutError: return await ctx.send('Tempo esgotado!') for c in range(0, len(pos_text_list)): if pos_text_list[c][-1] == valor[-1]: pos_text_list[c][-1] = f'{value}' valores_user.append(value) mult = valores_user[0] * valores_user[1] resp = mult / valores_user[-1] embed = discord.Embed( title=f'Regra de 3!', colour=discord.Colour(random_color()), description='Passo a passo da resolução:\n' + f'**{valores_user[-1]}x = {valores_user[0]}×{valores_user[1]}**\n' + f'**{valores_user[-1]}x = {mult}**\n' + f'**x = {mult}/{valores_user[-1]}**\n' + f'**x = {resp:.2f}**', timestamp=datetime.utcnow()) embed.set_author(name='Androxus', icon_url=self.bot.user.avatar_url) embed.set_footer(text=f'{ctx.author}', icon_url=ctx.author.avatar_url) img = Image.open(f'{path}images/regra_de_tres_inversa.png') draw = ImageDraw.Draw(img) font = ImageFont.truetype(f'{path}fonts/helvetica-normal.ttf', 25) black = (0, 0, 0) # rgb red = (255, 0, 0) # rgb pos1 = (60, 280) # x e y pos2 = (400, 280) # x e y pos3 = (60, 370) # x e y posx = (400, 370) # x e y text1 = str(valores_user[0]) text2 = str(valores_user[1]) text3 = str(valores_user[2]) x = f'{resp:.2f}' draw.text(pos1, text1, black, font=font) draw.text(pos2, text2, black, font=font) draw.text(pos3, text3, black, font=font) draw.text(posx, x, red, font=font) img.save(f'{path}images/regra_de_tres_inversa-edited.png') img.close() await ctx.send( embed=embed, file=discord.File( f'{path}images/regra_de_tres_inversa-edited.png')) remove(f'{path}images/regra_de_tres_inversa-edited.png') else: await ctx.send( f'{ctx.author.mention} eu não sei o que é ' + f'``{msg.content}``! Eu aceito apenas ``inversamente`` ou ``diretamente``' )
async def _calc(self, ctx, *args): if len(args) == 0: await self.help_calc(ctx) return args = ' '.join(args) resultado = 0 try: parser = Parser() resultado = parser.parse(args).evaluate({}) if isinstance(resultado, bool): # se o resultado veio como True ou False resultado = convert_to_string(resultado) except OverflowError: resultado = '∞' except ZeroDivisionError: resultado = '∞' except Exception as exception: if 'unexpected' in exception.args[0]: await ctx.send( f'Parece que há um erro de digitação!\n```{args}```<:ah_nao:758003636822474887>' ) return elif 'undefined variable' in exception.args[0]: variavel_desconhecida = exception.args[0][exception.args[0]. find(':') + 2:] await ctx.send( f'Desculpe, mas eu não sei o que é ``{variavel_desconhecida}`` <a:sad:755774681008832623>' ) return elif 'unknown character' in exception.args[0]: await ctx.send( f'Desculpe, mas você digitou algum caracter que eu não conheço. <a:sad:755774681008832623>' ) return elif 'unmatched "()"' in exception.args[0]: await ctx.send( f'Pare que você esqueceu de abrir ou fechar algum parêntese! <:ah_nao:758003636822474887>' ) return elif 'parity' in exception.args[0]: await ctx.send( 'Não consigo resolver está equação, verifique se você digitou tudo certo!' ) return else: await ctx.send( '<a:sad:755774681008832623> Ocorreu um erro na hora de executar este comando,' + f' por favor informe este erro ao meu criador\n```{exception.args[0]}```' ) return if len(str(resultado)) >= 200: await ctx.send( 'O resultado desta equação é tão grande que não consigo enviar a resposta!' + '\n<a:sad:755774681008832623>') return embed = discord.Embed( title=f'<:calculator:757079712077053982> Resultado:', colour=discord.Colour(random_color()), description='\uFEFF', timestamp=datetime.utcnow()) embed.add_field(name=f'Calculo:', value=f'```{args}```', inline=False) embed.add_field(name=f'Resposta:', value=f'```{resultado}```', inline=False) embed.set_footer(text=f'{ctx.author}', icon_url=f'{ctx.author.avatar_url}') await ctx.send(embed=embed)
async def _help(self, ctx, *, comando=None): e = None # se o comando foi chamado pela pessoa assim: "help ..." e se a pessoa passou alguma coisa # se o comando for None, vai mostrar a ajuda do comando "help" ou qualquer outro que vier no ctx if (ctx.command.name == 'help') and (comando is not None): # vai verificar se o que a pessoa passou não foi uma categoria command = None if not self.bot.is_category(comando): command = self.bot.get_command(comando) comandos_personalizados = [] # se não achar um comando, vai procurar nos comandos personalizados if (command is None) and (ctx.guild is not None): conexao = Conexao() servidor = ServidorRepository().get_servidor( conexao, ctx.guild.id) comandos_personalizados = ComandoPersonalizadoRepository( ).get_commands(conexao, servidor) conexao.fechar() for cmd_pers in comandos_personalizados: if cmd_pers.comando == comando: e = discord.Embed( title= '<a:loop_fun:763809373046702110> Comando personalizado', colour=discord.Colour(random_color()), description= f'**Este comando só existe neste servidor!**', timestamp=datetime.utcnow()) e.set_author( name='Androxus', icon_url=f'{self.bot.user.avatar_url}') e.set_footer(text=f'{ctx.author}', icon_url=ctx.author.avatar_url) e.add_field( name=f'Comando: ```{cmd_pers.comando}```\n' f'Resposta: ```{cmd_pers.resposta}```\n' f'Ignorar posição: ```{convert_to_string(cmd_pers.in_text)}```', value='** **', inline=False) return await ctx.send(embed=e) # se achou um comando "escondido" if (command is not None) and command.hidden: command = None # se o bot não achar o comando com esse nome if command is None: embed = discord.Embed( title= 'Comando não encontrado <a:sad:755774681008832623>', colour=discord.Colour(0xFF0000), description= f'Desculpe, mas não achei a ajuda para o comando ``{comando}``', timestamp=datetime.utcnow()) embed.set_author(name='Androxus', icon_url=f'{self.bot.user.avatar_url}') embed.set_footer(text=f'{ctx.author}', icon_url=f'{ctx.author.avatar_url}') msg = '```ini\n[•] Veja se você não digitou algo errado' all_commands = [] for command in self.bot.get_all_commands(): all_commands.append(command.name) all_commands.append(command.category) for alias in command.aliases: all_commands.append(alias) comando = ctx.message.content.lower()[len(ctx.prefix ):].split(' ') if comando[0] == 'help': comando.pop(0) comando = comando[0] if ctx.guild: all_commands = all_commands + [ c.comando for c in comandos_personalizados ] sugestao = get_most_similar_item(comando, all_commands) # se a sugestão for pelo menos 50% semelhante ao comando if (sugestao is not None) and (string_similarity( comando, sugestao) >= 0.5): msg += f'\n[•] Você quis dizer "{sugestao}"?' embed.add_field(name='**Possiveis soluções:**', value=f'{msg}```', inline=False) return await ctx.send(embed=embed) else: # se a pessoa usou o comando "help diversão" vai mostrar todos os comandos # que estão nessa categoria e = embedHelpCategory(self.bot, ctx, comando) # se não passou pelo return , vai atribuir o comando ao ctx.command ctx.command = command # o help do comando money é diferente, por isso esta condição if (ctx.command is not None) and (ctx.command.name == 'money'): embed1 = embedHelpCommand(self.bot, ctx) embed1.add_field( name= f'Para saber todas as abreviações das moedas que eu aceito, clique em ➡', value=f'** **', inline=True) embed2 = discord.Embed( title=f'Todas as moedas que eu aceito no comando "money"', colour=discord.Colour(random_color()), description='** **', timestamp=datetime.utcnow()) translator = Translator() moedas = '' for c in currency_exchange.currencies(): moedas += f'{c}\n' moedas = translator.translate(moedas, dest='pt').text for c in moedas.splitlines(): abreviacao, moeda = c.split(' - ') embed2.add_field(name=f'**{abreviacao}**', value=f'{moeda}', inline=True) async def menu_help(ctx, msg): # fica verificando a pagina 1, para ver se é para ir para a pagina 2 def check_page1(reaction, user, msg): return (user.id == ctx.author.id) and (str( reaction.emoji) == '➡') and (msg == reaction.message) # fica verificando a pagina 2, para ver se é para ir para a pagina 1 def check_page2(reaction, user, msg): return (user.id == ctx.author.id) and (str( reaction.emoji) == '⬅') and (msg == reaction.message) async def check_reactions_without_perm(ctx, msg, bot): # mudas as páginas, se o bot não tiver perm pra apagar reações while True: while True: reaction, user = await bot.wait_for( 'reaction_add', timeout=900.0) if check_page1(reaction, user, msg): break await msg.delete() msg = await ctx.send(embed=embed2) await msg.add_reaction('⬅') while True: reaction, user = await bot.wait_for( 'reaction_add', timeout=900.0) if check_page2(reaction, user, msg): break await msg.delete() msg = await ctx.send(embed=embed1) await msg.add_reaction('➡') async def check_reactions_with_perm(msg, bot): # mudas as páginas, se o bot tiver perm pra apagar reações while True: while True: reaction, user = await bot.wait_for( 'reaction_add', timeout=900.0) if check_page1(reaction, user, msg): break await msg.clear_reactions() await msg.add_reaction('⬅') await msg.edit(embed=embed2) while True: reaction, user = await bot.wait_for( 'reaction_add', timeout=900.0) if check_page2(reaction, user, msg): break await msg.clear_reactions() await msg.add_reaction('➡') await msg.edit(embed=embed1) # se foi usado num servidor: if ctx.guild: # se o bot tiver perm pra usar o "clear_reactions" if ctx.guild.me.guild_permissions.manage_messages: await check_reactions_with_perm(msg, self.bot) else: # se o bot não tiver permissão: await check_reactions_without_perm( ctx, msg, self.bot) else: # se não for usado no servidor: await check_reactions_without_perm(ctx, msg, self.bot) msg_bot = await ctx.send(embed=embed1) await msg_bot.add_reaction('➡') try: # vai fica 1 minuto e meio esperando o usuário apertas nas reações await asyncio.wait_for(menu_help(ctx, msg_bot), timeout=90.0) except asyncio.TimeoutError: # se acabar o tempo pass return if e is None: e = embedHelpCommand(self.bot, ctx) return await ctx.send(embed=e)