Exemple #1
0
 async def pull(self, ctx):
     paged = pagify(
         subprocess.Popen(["git", "pull"],
                          stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE).stdout.read().decode())
     for page in paged:
         p = f"```css\n{page}```"
         await ctx.send(p)
Exemple #2
0
 async def breeds(self):
     async with self.session.get(url=self.base + "breeds",
                                 headers={"x-api-key":
                                          os.getenv("DOG")}) as resp:
         if resp.status != 200:
             return raise_for_status(resp)
         breed_list = await resp.json()
     breeds = [x["name"] for x in breed_list]
     breed_count = len(breeds)
     breeds = ", ".join(breeds)
     pages = pagify(breeds, delims=[" "], page_length=2048)
     pages = [x for x in pages]
     return pages, breed_count
Exemple #3
0
 async def reminders(self, ctx):
     reminders = await Reminder(ctx).list()
     to_send = "**Your reminders:**\n"
     if reminders:
         for reminder in reminders:
             if reminder["channel_id"] == ctx.author.id:
                 location = "Private Messages"
             else:
                 location = f"<#{reminder['channel_id']}>"
             to_send += f"\n**{reminder['id']}**: {location}: \"{reminder['reminder']}\" -" \
                        f" {get_relative_delta(reminder['expires'], append_small=True, append_seconds=False)}"
     else:
         to_send += "\n**You don't currently have any reminders set!**"
     to_send += f"\n\nSet a reminder with `{ctx.prefix}remind <here|me> <time> <reminder>`\n" \
                f"Remove a reminder with `{ctx.prefix}delreminder <id>`"
     pages = pagify(to_send)
     for page in pages:
         await ctx.send(page)
Exemple #4
0
    async def on_command_error(self, ctx: CustomContext, error):
        if isinstance(error, commands.CommandNotFound):
            return
        if not can_send(ctx):
            if can_react(ctx):
                return await ctx.message.add_reaction("❌")
            try:
                return await ctx.author.send(
                    f"I cannot send messages in {ctx.guild}!")
            except discord.Forbidden:
                return ctx.log.error(
                    f"Failed to respond to command in {ctx.guild.name}")
        if isinstance(error, commands.CommandOnCooldown):
            return await ctx.send(self.format_retry_after(error.retry_after))
        ctx.command.reset_cooldown(ctx)
        if isinstance(error, commands.CommandInvokeError):
            return await ctx.send_error(error.original)
        if isinstance(error, commands.MissingRequiredArgument):
            return await ctx.missing_argument()
        if isinstance(error,
                      (commands.BadArgument, commands.BadUnionArgument)):
            return await ctx.bad_argument(error)
        if isinstance(error, commands.NSFWChannelRequired):
            return await ctx.send_error(
                f"I cannot give you the command `{ctx.command}` in a sfw environment!"
            )
        if isinstance(error, commands.NoPrivateMessage):
            return await ctx.send_error(
                f"{ctx.command} cannot be used in private messages!")
        if isinstance(error, commands.CheckFailure):
            if isinstance(error, errors.BotMissingPermissions):
                if "embed_links" in error.missing_perms:
                    return await ctx.send(error)
                return await ctx.send_error(error)
            if ctx.command.name not in ["register"]:
                return await ctx.send_error(
                    "You don't have permission to use this command!")
            return
        if isinstance(error, errors.TooManyUsers):
            return await ctx.send_error("You provided too many users!")

        self.error_count += 1
        sentry.capture_exception(error)
        # ctx.bot.log.error(repr(error), exc_info=True if ctx.bot.debug else False)
        webhook = discord.Webhook.from_url(os.getenv("ERRORS"),
                                           adapter=discord.AsyncWebhookAdapter(
                                               ctx.bot.session))
        long = "".join(
            traceback.format_exception(type(error), error,
                                       error.__traceback__))
        em = discord.Embed(
            color=ctx.bot.error_color,
            description=f'`{type(error).__name__}: {str(error)}`')
        em.set_author(name="Error:")
        em.add_field(name="Content:", value=ctx.message.content)
        em.add_field(name="Invoker:",
                     value="{}\n({})".format(ctx.message.author.mention,
                                             str(ctx.message.author)))
        if not isinstance(ctx.message.channel, discord.abc.PrivateChannel):
            em.add_field(name="Guild:", value=ctx.guild.name)
        em.add_field(name="Channel:",
                     value="Private channel" if isinstance(
                         ctx.channel, discord.DMChannel) else
                     f"{ctx.channel.mention}\n({ctx.channel.name})")
        em.timestamp = datetime.utcnow()
        await webhook.send(embed=em, username=f"Error #{self.error_count:,}")
        pages = pagify(long)
        if pages:
            for page in pages:
                await webhook.send(f"```py\n{page}\n```",
                                   username=f"Error #{self.error_count:,}")
        await ctx.send_error(error)
Exemple #5
0
    async def on_command_error(self, ctx: Context, error: CommandError):
        if isinstance(error, CommandNotFound):
            return
        if not can_send(ctx) or not can_read_history(ctx):
            if can_react(ctx) and can_read_history(ctx):
                return await ctx.message.add_reaction("❌")
            try:
                # return await ctx.author.send(_("errors", "cannot_respond", guild=str(ctx.guild)))
                return await ctx.author.send(
                    f"I cannot send messages and/or read message history in {ctx.guild}!"
                )
            except Forbidden:
                return ctx.log.error(
                    f"Failed to respond to command in {ctx.guild.name}")
        if isinstance(error, CommandOnCooldown):
            string, delete_after = self.format_retry_after(error.retry_after)
            return await ctx.reply(string, delete_after=delete_after)
        ctx.command.reset_cooldown(ctx)
        # if isinstance(error, commands.CommandInvokeError):
        #     return await ctx.send_error(error.original)
        if isinstance(error, MissingRequiredArgument):
            return await ctx.missing_argument()
        if isinstance(error, (BadArgument, BadUnionArgument)):
            return await ctx.bad_argument(error)
        if isinstance(error, NSFWChannelRequired):
            # return await ctx.send_error(_("errors", "no_nsfw", command=str(ctx.command)))
            return await ctx.send_error(
                f"I cannot give you the command `{ctx.command}` in a sfw environment!"
            )
        if isinstance(error, NoPrivateMessage):
            # return await ctx.send_error(_("errors", "no_pms", command=str(ctx.command)))
            return await ctx.send_error(
                f"{ctx.command} cannot be used in private messages!")
        if isinstance(error, MaxConcurrencyReached):
            return await ctx.send_error(error)
        if isinstance(error, CommandInvokeError):
            return await ctx.send_error(error.original)
        if isinstance(error, CheckFailure):
            if isinstance(error, BotMissingPermissions):
                if "embed_links" in error.missing_perms:
                    # noinspection PyTypeChecker
                    return await ctx.reply(error)
                return await ctx.send_error(error)
            if isinstance(error, UserMissingPermissions):
                return await ctx.send_error(error)
            # return await ctx.send_error(_("errors", "user_cannot_use"))
            return await ctx.send_error("You cannot use this command!")

        self.error_count += 1
        sentry.capture_exception(error)
        # ctx.bot.log.error(repr(error), exc_info=True if ctx.bot.debug else False)
        webhook = Webhook.from_url(os.getenv("ERRORS"),
                                   adapter=AsyncWebhookAdapter(
                                       ctx.bot.session))
        long = "".join(
            traceback.format_exception(type(error), error,
                                       error.__traceback__))
        em = Embed(color=ctx.bot.error_color,
                   description=f'`{type(error).__name__}: {str(error)}`')
        em.set_author(name="Error:")
        em.add_field(name="Content:", value=ctx.message.content)
        em.add_field(name="Invoker:",
                     value="{}\n({})".format(ctx.message.author.mention,
                                             str(ctx.message.author)))
        if not isinstance(ctx.message.channel, DMChannel):
            em.add_field(name="Guild:", value=ctx.guild.name)
        em.add_field(
            name="Channel:",
            value="Private channel" if isinstance(ctx.channel, DMChannel) else
            f"{ctx.channel.mention}\n({ctx.channel.name})")
        em.timestamp = datetime.utcnow()
        await webhook.send(embed=em, username=f"Error #{self.error_count:,}")
        pages = pagify(long)
        if pages:
            for page in pages:
                await webhook.send(f"```py\n{page}\n```",
                                   username=f"Error #{self.error_count:,}")
        await ctx.send_error(error)
Exemple #6
0
    async def lyrics(self, ctx: Context, *, search: str):
        parser = argparser.Arguments()
        parser.add_argument("search", nargs="*")
        parser.add_argument("--spotify", "-s", action="store_true")
        parser.add_argument("--nowplaying", "-np", action="store_true")
        args, valid_check = parser.parse_args(search)
        if not valid_check:
            return await ctx.reply(args)

        em = Embed(color=self.bot.color)
        if args.spotify:
            spotify = [
                x for x in ctx.author.activities if isinstance(x, Spotify)
            ]
            if not spotify:
                return await ctx.send_error(
                    "You either don't have Spotify linked or you're not listening to anything."
                )
            artists = spotify[0].artist
            title = spotify[0].title.split("(feat.")[0]
            search = f'{title} {artists}'
        elif args.nowplaying:
            player = self.bot.lavalink.player_manager.get(ctx.guild.id)
            if not player or not player.is_playing or not player.current:
                return await ctx.send_error(
                    "I'm not currently playing anything!")
            if player.current.stream:
                return await ctx.send_error(
                    "I can't get the lyrics of a stream..")
            search = player.current.title
        base_url = "https://api.genius.com"
        url = base_url + f"/search?q={search}&page=1&per_page=1"
        async with self.bot.session.get(
                url=url, headers={"Authorization":
                                  os.getenv("GENIUS")}) as resp:
            result = await resp.json()
        try:
            result = result["response"]["hits"][0]["result"]
        except (KeyError, IndexError):
            return await ctx.send_error("Song not found")

        async with self.bot.session.get(
                url=base_url + result["api_path"],
                headers={"Authorization": os.getenv("GENIUS")}) as resp:
            json = await resp.json()

        page_url = "https://genius.com" + json["response"]["song"]["path"]
        verif = ctx.emojis(
            "music.checky"
        ) if result["primary_artist"]["is_verified"] is True else ""

        desc = f"**Artist:** [{result['primary_artist']['name']} {verif}]({result['primary_artist']['url']})\n" \
               f"**Song:** [{result['title_with_featured']}]({page_url})\n"

        if "pageviews" in result["stats"]:
            views = f"{result['stats']['pageviews']:,}"
            desc += f"**Views:** {views}\n"

        desc += f"**Lyric state:** {result['lyrics_state']}"
        page = await self.bot.session.get(page_url)
        html = BeautifulSoup(await page.text(), "html.parser")
        [h.extract() for h in html("script")]
        lyrics = html.find("div", class_="lyrics").get_text()
        desc += lyrics.replace("[", "**[").replace("]", "]**")
        first_message = True
        pages = list(pagify(desc))
        pages_length = len(pages)
        if pages_length > 5:
            return await ctx.reply(
                "Too long to send.. will have a fix for this in the future!")
        for index, page in enumerate(pages):
            em.description = page
            if first_message:
                em.set_thumbnail(url=result["header_image_url"])
                em.set_author(name=f"{result['title_with_featured']} lyrics")
                if pages_length == 1:
                    em.set_footer(
                        text=
                        "Not the song you were looking for? Add the author to your query."
                    )
                    if args.spotify or args.nowplaying:
                        em.set_footer(text="")
                    header = result["primary_artist"]["header_image_url"]
                    if header and not header.startswith(
                            "https://assets.genius.com/images/default_avatar_"
                    ):
                        em.set_image(url=header)
                first_message = False
            else:
                em.set_thumbnail(url="")
                em.set_author(name="", icon_url="")
                em.set_footer(text="")
                em.set_image(url="")
                if index == pages_length - 1:
                    em.set_footer(
                        text=
                        "Not the song you were looking for? Add the author to your query."
                    )
                    if args.spotify or args.nowplaying:
                        em.set_footer(text="")
                    header = result["primary_artist"]["header_image_url"]
                    if header and not header.startswith(
                            "https://assets.genius.com/images/default_avatar_"
                    ):
                        em.set_image(url=header)
            await ctx.reply(embed=em)