예제 #1
0
    async def match(self, ctx: commands.Context,
                    opponent: Union[discord.Member, MemberID]):
        '''
        Play shinobi match with your friends using the characters from `Naruto Verse`

        **Steps**
        > 1. Type `{prefix}match @player_mention`
        > 2. Then both player selects the character from their respection selection boxes
        > 3. Then starts the amazing match!

        **Rules**
        > 1. You cannot repeat a move `twice` in a row
        > 2. You will have only `2 Special Moves` to perform, so use wisely
        > 3. `On timeout`, by the default the user with high health value would be decalred as a winner
        > 4. Also you can perform `healing operations twice` in the whole game, so use the heal wisely.
        '''

        if (opponent is ctx.author or opponent.bot):
            await ctx.send(embed=ErrorEmbed(
                description="*You cannot play this game yourself or with a bot*"
            ))
            return

        view1 = ShinobiMatchCharacterSelection(
            characters_data=await self.return_random_characters(ctx),
            player=ctx.author,
            ctx=ctx)
        select_msg1: discord.Message = await ctx.send(
            embed=self.return_select_help_embed(ctx.author), view=view1)

        view2 = ShinobiMatchCharacterSelection(
            characters_data=await self.return_random_characters(ctx),
            player=opponent,
            ctx=ctx)
        select_msg2: discord.Message = await ctx.send(
            embed=self.return_select_help_embed(opponent), view=view2)

        await view1.wait()
        await view2.wait()

        if view1.character is None or view2.character is None:
            return await ctx.send(embed=ErrorEmbed(
                title="One of the shinobi didn't choose his character on time."
            ))

        await select_msg1.delete()
        await select_msg2.delete()

        timer = await ctx.send('Starting the match in `3 seconds`')
        for i in range(1, 3):
            await timer.edit(f'Starting the match in `{3-i} seconds`')
            await asyncio.sleep(1)
        await timer.delete()

        view = MatchHandlerView(player1=(ctx.author, view1.character),
                                player2=(opponent, view2.character))
        view.message = await ctx.send(
            content=f'{ctx.author.mention} now your turn',
            embed=view.make_embed(),
            view=view)
예제 #2
0
 async def callback(self, response: discord.SlashCommandResponse):
     detected_urls = await detect_bad_domains(response.options.content)
     if len(detected_urls) != 0:
         embed = ErrorEmbed(title='SCAM/PHISHING/ADULT LINK(S) DETECTED')
         detected_string = '\n'.join(
             [f'- ||{i}||' for i in set(detected_urls)])
         embed.description = f'The following scam url(s) were detected:\n{detected_string}'
         embed.set_author(
             name=response.interaction.user.display_name,
             icon_url=response.interaction.user.display_avatar.url)
         await response.send_message(embed=embed, ephemeral=True)
         return
     await response.send_message(
         embed=SuccessEmbed(title="The url or the text message is safe!"),
         ephemeral=True)
예제 #3
0
def errorembed(ctx):
    return ErrorEmbed(
        title=f"No support system setup for the {ctx.guild.name}",
        description=
        "An admin can always setup the **support system** using `{}setup support #support @support_required` command"
        .format(ctx.prefix),
    )
예제 #4
0
 async def loop(self, ctx):
     """Iterates the current playing song"""
     player = self.bot.music.get_player(guild_id=ctx.guild.id)
     song = await player.toggle_song_loop()
     if song.is_looping:
         await ctx.send(embed=SuccessEmbed(description=f"```Enabled loop for {song.name}```"))
     else:
         await ctx.send(embed=ErrorEmbed(description=f"```Disabled loop for {song.name}```"))
예제 #5
0
    async def cog_check(self, ctx: commands.Context):
        """Cog wide check, which disallows commands in DMs."""
        if not ctx.guild:
            await ctx.send(embed=ErrorEmbed(
                description="Music commands are not available in Private Messages."))
            return False

        return True
예제 #6
0
    async def feedback(self, ctx, *, feed):
        """
        Sends your feedback about the server to the server owner. (This can only be done if it is enabled by the server admin)
        ``The feedback should be less than 2000 characters``
        """
        if not await ctx.prompt(
                "Are you sure that you want to **send the feedback** ?",
                author_id=ctx.author.id,
        ):
            return

        if len(feed) > 2000:
            await ctx.send(
                "\N{WARNING SIGN} The feedback should be less than 2000 characters"
            )
            return
        data = await (await self.database_class()).get(ctx.guild.id)
        if data is None or data.get("feedback") is None:
            e = ErrorEmbed(
                title="No Feedback system setup for this server!",
                description=
                "An admin can always setup the **feedback system** using `{}setup add feedback #channelname` command"
                .format(ctx.prefix),
            )
            await ctx.send(embed=e, delete_after=10)
            return

        channel = self.bot.get_channel(data.get("feedback"))

        e = Embed(
            title="Feedback sent!",
            description=f"Your feedback '{feed}' has been sent!",
        )
        await ctx.send(embed=e, delete_after=10)

        e2 = discord.Embed(
            title="New Feedback!",
            description=feed,
            colour=ctx.author.color or ctx.author.top_role.colour.value
            or discord.Color.random(),
        )
        e2.set_author(name=ctx.author.display_name,
                      icon_url=ctx.author.display_avatar.url)
        e.set_author(name=ctx.author.display_name,
                     icon_url=ctx.author.display_avatar.url)
        await channel.send(embed=e2)
예제 #7
0
    async def tally(self, ctx, poll_id: commands.MessageConverter):
        """Get polls results"""
        error_message = ErrorEmbed(
            description=f"**{poll_id.id}** is not a poll!")
        if len(poll_id.embeds) <= 0:
            await ctx.send(embed=error_message)
            return
        embed = poll_id.embeds[0]
        if poll_id.author == ctx.message.author:
            await ctx.send(embed=error_message)
            return

        if isinstance(embed.footer.text, discord.embeds._EmptyEmbed):
            await ctx.send(embed=error_message)
            return
        if not embed.footer.text.startswith('Poll'):
            await ctx.send(embed=error_message)
            return

        if len(poll_id.reactions) < 2:
            await ctx.send(embed=error_message)
            return
        valid_reactions = list(
            filter(
                lambda x: x in list(
                    map(lambda x: str(discord.PartialEmoji(name=x.emoji)),
                        poll_id.reactions)),
                list(
                    map(lambda x: str(discord.PartialEmoji(name=x.emoji)),
                        poll_id.reactions))))
        if len(list(valid_reactions)) < 2:
            await ctx.send(embed=error_message)
            return
        valid_reactions_list = list(
            map(
                lambda x: (x,
                           discord.utils.find(lambda z: str(z.emoji) == str(
                               x), poll_id.reactions).count), valid_reactions))
        valid_reactions_list.sort(reverse=True)
        valid_reactions_list = [('Option', 'Reacted Counts')
                                ] + valid_reactions_list
        embed = Embed(title='Poll Results')
        lengths = [[len(str(x)) for x in row] for row in valid_reactions_list]

        max_lengths = [
            max(map(itemgetter(x), lengths))
            for x in range(0, len(valid_reactions_list[0]))
        ]

        format_str = ''.join(map(lambda x: '%%-%ss | ' % x, max_lengths))
        embed.description = '```markdown\n' + (
            format_str % valid_reactions_list[0]
        ) + '\n' + '-' * (sum(max_lengths) + len(max_lengths) * 3 - 1)
        for x in valid_reactions_list[1:]:
            embed.description += f'\n{format_str % x}'
        embed.description += '\n```'
        embed.timestamp = poll_id.created_at
        await ctx.send(embed=embed, reference=poll_id)
예제 #8
0
 async def callback(self, response: discord.SlashCommandResponse) -> None:
     server_id = response.options.id or response.guild_id
     if not str(server_id).isdigit():
         return await response.send_message('Not a valid serverid',
                                            ephemeral=True)
     guild = self.parent.cog.bot.get_guild(int(server_id))
     if guild is not None:
         database = await self.parent.cog.database_class_server()
         await database.set(server_id, response.options.reason)
         self.parent.cog.bot.blacklist.append(int(server_id))
         channel = await self.parent.cog.bot.get_welcome_channel(guild)
         embed = ErrorEmbed(title=f'Left {guild.name}')
         embed.description = f'I have to leave the `{guild.name}` because it was marked as a `blacklist guild` by my developer. For further queries please contact my developer.'
         embed.add_field(
             name='Developer',
             value=
             f'[{self.parent.cog.bot.get_user(self.parent.cog.bot.owner_id)}](https://discord.com/users/{self.parent.cog.bot.owner_id})'
         )
         embed.add_field(
             name="Support Server",
             value=f"https://discord.gg/{LinksAndVars.invite_code.value}",
         )
         await channel.send(embed=embed)
         await guild.leave()
         log.info(f'Left guild {guild.id} [Marked as spam]')
         await response.send_message('Server added to the blacklist',
                                     ephemeral=True)
         return
     else:
         return await response.send_message('Server not found',
                                            ephemeral=True)
예제 #9
0
    async def cog_command_error(self, ctx: commands.Context, error: Exception):
        """Cog wide error handler."""
        if isinstance(error, IncorrectChannelError):
            return

        if isinstance(error, NoChannelProvided):
            return await ctx.send(embed=ErrorEmbed(
                description="You must be in a voice channel or provide one to connect to.")
            )
예제 #10
0
    async def leave(self, ctx):
        """Disconnects from a voice channel"""
        voice_state_me = ctx.me.voice

        if voice_state_me is None:
            return

        try:
            await ctx.send(embed=ErrorEmbed(description="```Left```"))
            await ctx.voice_client.disconnect()
        except:
            pass
예제 #11
0
 async def volume(self, ctx, vol: Union[int, float]):
     """
     Changes the volume for the current song
     `Note: Negative volume numbers will be converted to 0`
     """
     player = self.bot.music.get_player(guild_id=ctx.guild.id)
     vol = abs(vol)
     vol = max(vol, 0)
     if vol > 100:
         return await ctx.send(embed=ErrorEmbed(description='The volume should be between 0 and 100'))
     # volume should be a float between 0 to 1
     song, volume = await player.change_volume(float(vol/100))
     await ctx.send(embed=SuccessEmbed(description=f"Changed volume for **{song.name}** to {volume:.2}%"))
예제 #12
0
 async def callback(self, response: discord.SlashCommandResponse) -> None:
     database_user = await self.parent.cog.database_class_user()
     database_server = await self.parent.cog.database_class_server()
     user_check = await database_user.get(response.options.id)
     server_check = await database_server.get(response.options.id)
     if user_check is None and server_check is None:
         return await response.send_message(
             embed=ErrorEmbed(title='No data found'), ephemeral=True)
     return await response.send_message(embed=SuccessEmbed(
         title=response.options.id,
         description=
         f'Found in {database_user._Database__channel.mention if user_check is not None else database_server._Database__channel.mention}\n\n **Reason**\n```\n{user_check or server_check}\n```'
     ))
예제 #13
0
 async def on_guild_join(self, guild: discord.Guild):
     if guild.id in self.blacklist:
         channel = await self.get_welcome_channel(guild)
         embed = ErrorEmbed(title=f'Left {guild.name}')
         embed.description = f'I have to leave the `{guild.name}` because it was marked as a `blacklist guild` by my developer. For further queries please contact my developer.'
         embed.add_field(name = 'Developer', value=f'[{self.get_user(self.owner_id)}](https://discord.com/users/{self.owner_id})')
         embed.add_field(
             name="Support Server",
             value=f"https://discord.gg/{LinksAndVars.invite_code.value}",
         )
         await channel.send(embed=embed)
         await guild.leave()
         log.info(f'Left guild {guild.id} [Marked as spam]')
예제 #14
0
    async def resolved(self, ctx, member: Union[MemberID, discord.Member]):
        """
        Resolves the existing ticket!
        One needs to have manage server permission in order to run this command
        """
        if not await ctx.prompt(
                f"Are you sure that you want to **set {member} issue to resolved** ?",
                author_id=ctx.author.id,
        ):
            return

        data = await (await self.database_class()).get(ctx.guild.id)
        if data is None or data.get("support") is None:
            await ctx.send(embed=errorembed(ctx))
            return
        if member.bot:
            await ctx.send(embed=ErrorEmbed(
                description=f"{member.mention} is a bot! :robot:"))
            return
        if (not discord.utils.get(ctx.guild.roles, id=data.get("support")[-1])
                in member.roles):
            e = ErrorEmbed(
                title="Sorry !",
                description=
                f"{member.mention} has not requested any **support** !",
            )
            await ctx.send(embed=e)
            return

        await member.send(
            f"Hope your issue has been resolved in {ctx.guild.name}, {member.mention}"
        )
        await ctx.send(
            f"The issue/query for {member.mention} has been set to resolved!")
        await member.remove_roles(
            discord.utils.get(ctx.guild.roles, id=data.get("support")[-1]))
예제 #15
0
    async def wi(self, ctx, *, member: Optional[Union[discord.Member,
                                                      MemberID]]):
        """Prove anyone that they are sus!"""
        if member == "@everyone":
            desc = f"Hmmmmmmm ** {ctx.author.mention} , Hey guys {ctx.author.mention} is the sus !!!**"
            await ctx.send(ErrorEmbed(description=desc))
            return
        member = member or ctx.author
        desc = f"** {member.mention}  is the imposter**"
        text = f"{member.display_name}  is the imposter"

        embed = ErrorEmbed(description=desc, timestamp=discord.utils.utcnow())

        img = Image.open(among_us_friends)
        draw = ImageDraw.Draw(img)
        font = ImageFont.truetype(
            FileIO(BASE_DIR / os.path.join("lib", "data", "arial.ttf")), 60)
        draw.text((250, 300), text, font=font, fill="red", align="right")
        img.save("wi.png")
        embed.set_image(url="attachment://wi.png")
        await ctx.send(file=discord.File("wi.png", description=text),
                       embed=embed)
        await sleep(3)
        os.remove("wi.png")
예제 #16
0
 async def connectfour(self,
                       ctx,
                       member: Optional[Union[MemberID,
                                              discord.Member]] = None):
     """
     Play Amazing Connect Four Game
     https://en.wikipedia.org/wiki/Connect_Four#firstHeading
     """
     member = member or ctx.me
     if (member is ctx.author or member.bot and member is not ctx.me):
         await ctx.send(embed=ErrorEmbed(
             description="*You cannot play this game yourself or with a bot*"
         ))
         return
     view = ConnectFour(red=ctx.author, blue=member, auto=member is ctx.me)
     view.message = await ctx.send(embeds=[view.embed,
                                           view.BoardString()],
                                   view=view)
예제 #17
0
 async def tictactoe(self,
                     ctx,
                     member: Optional[Union[MemberID,
                                            discord.Member]] = None):
     """
     Play Tictactoe with yourself or your friend!
     """
     member = member or ctx.me
     if (member is ctx.author or member.bot and member is not ctx.me):
         await ctx.send(embed=ErrorEmbed(
             description="*You cannot play this game yourself or with a bot*"
         ))
         return
     view = TicTacToe(player2=member,
                      player1=ctx.author,
                      auto=member is ctx.me)
     view.message = await ctx.send(
         f"Tic Tac Toe: X goes first aka {ctx.author.mention}", view=view)
예제 #18
0
 async def giveaway_stop(self, ctx: commands.Context,
                         giveaway_id: Union[commands.MessageConverter,
                                            discord.Message]):
     """
     Cancels the specified giveaway
     `Note: This also deletes that giveaway message`
     """
     if not await ctx.prompt(
             f"Do you really want to **stop/delete** the giveaway with id **{giveaway_id.id}** hosted in {giveaway_id.channel.mention}?\n`Note: This action is irreversible!`"
     ):
         return
     try:
         await self.get_giveaway_config(giveaway_id.id)
     except AttributeError as e:
         return await ctx.send(ErrorEmbed(title=str(e)))
     database = await self.database_class()
     await database.delete(giveaway_id.id)
     await giveaway_id.delete()
     self.get_giveaway_config.invalidate(self, giveaway_id.id)
     await ctx.send(embed=SuccessEmbed(
         title=f'The giveaway with id {giveaway_id.id} deleted successfully!'
     ))
예제 #19
0
    async def process_commands(self, message):
        ctx = await self.get_context(message, cls=Context)

        if ctx.command is None:
            return

        if ctx.author.id in self.blacklist:
            embed = ErrorEmbed(title='Blacklisted User!')
            embed.description = 'You have been `blacklisted` from using my commands. For further queries please contact my developer.'
            embed.add_field(name = 'Developer', value=f'[{self.get_user(self.owner_id)}](https://discord.com/users/{self.owner_id})')
            embed.add_field(
                name="Support Server",
                value=f"https://discord.gg/{LinksAndVars.invite_code.value}",
            )
            await ctx.send(embed=embed, delete_after=5)
            return

        if ctx.guild is not None and ctx.guild.id in self.blacklist:
            return

        bucket = self.spam_control.get_bucket(message)
        current = message.created_at.timestamp()
        retry_after = bucket.update_rate_limit(current)
        author_id = message.author.id
        if retry_after and author_id != self.owner_id:
            self._auto_spam_count[author_id] += 1
            if self._auto_spam_count[author_id] >= 5:
                await self.add_to_blacklist(author_id)
                del self._auto_spam_count[author_id]
                await self.log_spammer(ctx, message, retry_after, autoblock=True)
            else:
                self.log_spammer(ctx, message, retry_after)
            return
        else:
            self._auto_spam_count.pop(author_id, None)

        try:
            await self.invoke(ctx)
        except:
            pass
예제 #20
0
 async def update_blacklist(self):
     database = await self.db.new(Database.database_category_name.value, Database.user_blacklist_channel_name.value)
     async for message in database._Database__channel.history(limit=None):
         cnt = message.content
         try:
             data = loads(str(cnt))
             data.pop("type")
             data_keys = list(map(str, list(data.keys())))
             self.blacklist.append(int(data_keys[0]))
         except Exception as e:
             log.error(e)
             continue
     database = await self.db.new(Database.database_category_name.value, Database.server_blacklist_channel_name.value)
     async for message in database._Database__channel.history(limit=None):
         cnt = message.content
         try:
             data = loads(str(cnt))
             data.pop("type")
             data_keys = list(map(str, list(data.keys())))
             self.blacklist.append(int(data_keys[0]))
             guild = self.get_guild(int(data_keys[0]))
             if guild is not None:
                 channel = await self.get_welcome_channel(guild)
                 embed = ErrorEmbed(title=f'Left {guild.name}')
                 embed.description = f'I have to leave the `{guild.name}` because it was marked as a `blacklist guild` by my developer. For further queries please contact my developer.'
                 embed.add_field(name = 'Developer', value=f'[{self.get_user(self.owner_id)}](https://discord.com/users/{self.owner_id})')
                 embed.add_field(
                     name="Support Server",
                     value=f"https://discord.gg/{LinksAndVars.invite_code.value}",
                 )
                 await channel.send(embed=embed)
                 await guild.leave()
                 log.info(f'Left guild {guild.id} [Marked as spam]')
         except Exception as e:
             log.error(e)
             continue
     self.blacklist = list(set(self.blacklist))
     log.info('Blacklist Data updated')
예제 #21
0
    async def support(self, ctx):
        """Open support ticket if enabled by the server admins"""
        if not await ctx.prompt(
                "Are you sure that you want to **raise a support query** ?",
                author_id=ctx.author.id,
        ):
            return

        data = await (await self.database_class()).get(ctx.guild.id)
        if data is None or data.get("support") is None:
            await ctx.send(embed=errorembed(ctx))
            return
        channel = self.bot.get_channel(data.get("support")[0])

        if ctx.message.author == ctx.guild.owner:
            await ctx.send(
                f"{ctx.message.author.mention} really you need support ??! **LOL !** :rofl:"
            )
            return

        if channel == ctx.message.channel:
            await ctx.send(
                embed=ErrorEmbed(
                    description=
                    f"{ctx.message.author.mention} This command can't be run inside the {ctx.message.channel.mention}"
                ),
                delete_after=4,
            )
            return
        if (discord.utils.get(ctx.guild.roles, id=data.get("support")[-1])
                in ctx.message.author.roles):
            await ctx.send(embed=ErrorEmbed(
                description=
                f"{ctx.message.author.mention} you already applied for the support , please check the {channel.mention} channel."
            ))
            return
        try:
            await ctx.message.author.add_roles(
                discord.utils.get(ctx.guild.roles, id=data.get("support")[-1]))
        except Exception as error:
            await ctx.send(embed=ErrorEmbed(description=error))
            return

        if ctx.channel.guild is ctx.guild:
            per = ctx.author.mention
            e = Embed(
                title="Help Required",
                description=f"{per} in {ctx.channel.mention} needs support!",
            )
            await channel.send(
                "@here",
                embed=e,
                allowed_mentions=discord.AllowedMentions(everyone=True,
                                                         users=True,
                                                         roles=True),
            )
            await ctx.send("**Help Desk** has been has been notifed!")
            e = Embed(
                title="Support Requirement Registered",
                description=
                f"Your need for the support in **{ctx.guild.name}** has been registered",
            )
            await ctx.message.author.send("Hello", embed=e)
            return
예제 #22
0
    async def polltime(self, ctx):
        """Create polls easily"""
        def check(m):
            return m.author == ctx.author and m.channel == ctx.channel

        questions = [
            "What should be the **strawpoll title**?",
            "Write the **description** of the strawpoll.",
            "How many option(s) should be there? (Min 2 and Max 10)",
            "In which channel do you want to host this **strawpoll**?",
        ]

        answers = []
        options = []
        all_messages = [ctx.message]

        for i, question in enumerate(questions):
            embed = Embed(title=f"Question {i+1}", description=question)
            question_message = await ctx.send(embed=embed)
            all_messages.append(question_message)
            try:
                message = await self.bot.wait_for("message",
                                                  timeout=60,
                                                  check=check)
                if i == 2:
                    all_messages.append(message)
                    try:
                        int(message.content)
                    except:
                        await ctx.send(embed=ErrorEmbed(
                            description=
                            f"{message.content} you provided is **not an number**, Please **rerun the command again**!"
                        ),
                                       delete_after=2)
                        await self.delete_message(all_messages)
                        return
                    if int(message.content) < 2:
                        await ctx.send(embed=ErrorEmbed(
                            description=
                            "The no. of options cannot be **less than 2**, Please **rerun the command again**!"
                        ),
                                       delete_after=2)
                        await self.delete_message(all_messages)
                        return
                    if int(message.content) > len(self.reactions):
                        await ctx.send(embed=ErrorEmbed(
                            description=
                            "The no. of options cannot be **greater than 10**, Please **rerun the command again**!"
                        ),
                                       delete_after=2)
                        await self.delete_message(all_messages)
                        return
                    for i in range(int(message.content)):
                        option_question = await ctx.send(f"**Option {i+1}**")
                        all_messages.append(option_question)
                        try:
                            options_message = await self.bot.wait_for(
                                "message", timeout=60, check=check)
                            all_messages.append(option_question)
                        except:
                            await ctx.send(
                                "You didn't answer the questions in Time",
                                delete_after=2)
                            await self.delete_message(all_messages)
                            return
                        options.append(options_message.content)

            except:
                await ctx.send("You didn't answer the questions in Time",
                               delete_after=2)
                await self.delete_message(all_messages)
                return
            answers.append(message.content)

        question, description, poll_channel = (
            answers[0],
            answers[1],
            await
            commands.TextChannelConverter(answers[-1]
                                          ).convert(ctx=ctx,
                                                    argument=answers[-1]),
        )
        if not isinstance(poll_channel, discord.TextChannel):
            await ctx.send(embed=ErrorEmbed(
                description=
                "Wrong text channel provided! Try again and mention the channel next time! :wink:"
            ),
                           delete_after=2)
            await self.delete_message(all_messages)
            return

        if len(options) == 2 and options[0] == "yes" and options[1] == "no":
            reactions = ["\U00002705", "\U0000274c"]
        else:
            reactions = self.reactions

        description = []
        for x, option in enumerate(options):
            description += "\n\n {} {}".format(reactions[x], option)
        embed = Embed(title=question, description="".join(description))
        react_message = await poll_channel.send(embed=embed)
        for reaction in reactions[:len(options)]:
            await react_message.add_reaction(reaction)
        embed.set_footer(text="Poll ID: {}".format(react_message.id))
        await react_message.edit(embed=embed)
        await ctx.send(
            f'Done :ok_hand: Hosted the poll in {poll_channel.mention}',
            delete_after=2)
        await self.delete_message(all_messages)
예제 #23
0
 async def error_handler(self, ctx, error, *args, **kwargs):
     await ctx.send(embed=ErrorEmbed(description='No song in the queue'), delete_after=5)
예제 #24
0
 async def remove_song(self, ctx, index: int):
     """Song the specified song using its index value"""
     player = self.bot.music.get_player(guild_id=ctx.guild.id)
     song = await player.remove_from_queue(int(index))
     await ctx.send(embed=ErrorEmbed(f"```Removed {song.name} from queue```"))
예제 #25
0
 async def stop(self, ctx):
     """Stops the Music Player"""
     player = self.bot.music.get_player(guild_id=ctx.guild.id)
     await player.stop()
     await ctx.send(embed=ErrorEmbed(description="```Stopped```"))
    async def whosthatpokemon(self, ctx: commands.Context):
        """Play Who\'s That Pokemon?"""
        async with ctx.typing():
            wtp = await self.bot.dagpi.wtp()
            question = wtp.question
            answer = wtp.name.lower()

            e = Embed(title="Who's That Pokemon?",
                      timestamp=ctx.message.created_at)
            e.set_footer(
                text=f"{ctx.message.author} reply within 30secs to answer.",
                icon_url=ctx.message.author.avatar.url,
            )
            e.set_image(url=question)

            question_message = await ctx.send(
                "You have 3 chances, **Chance: 1/3**", embed=e)

        answerembed = discord.Embed(
            title=f"The Pokemon is: {wtp.name.capitalize()}",
            description=
            f"```Here is the Info\n\nAbilities: {', '.join(list(map(lambda x: x.capitalize(),wtp.abilities)))}```",
            timestamp=ctx.message.created_at,
        )
        answerembed.add_field(name="**Height**", value=f"{round(wtp.height)}m")
        answerembed.add_field(name="**Weight**",
                              value=f"{round(wtp.weight)} kg")
        answerembed.add_field(name=":id:", value=wtp.id)
        answerembed.set_image(url=wtp.answer)
        answerembed.set_footer(text=wtp.name.capitalize(), icon_url=wtp.answer)
        answerembed.set_author(name=wtp.name.capitalize(),
                               url=wtp.link,
                               icon_url=wtp.answer)
        for i in range(3):
            try:
                answer_content = await self.bot.wait_for(
                    "message",
                    timeout=30,
                    check=lambda m: m.author == ctx.author and m.channel == ctx
                    .channel,
                )
            except asyncio.TimeoutError:
                try:
                    await answer_content.delete()
                except (discord.NotFound, discord.Forbidden,
                        discord.HTTPException):
                    pass
                await ctx.send(embed=ErrorEmbed(
                    description=
                    "Well you didn't atleast once.\n Thus I won't be telling you the answer! :rofl:. **Baka**"
                ))
                return
            await asyncio.sleep(0.8)
            if answer_content.content.lower() != answer:
                try:
                    await answer_content.delete()
                except (discord.NotFound, discord.Forbidden,
                        discord.HTTPException):
                    pass
                await ctx.send(
                    embed=ErrorEmbed(
                        description="Please try again! :no_entry:"),
                    delete_after=3,
                )
                await question_message.edit(
                    content=f"You have {3-(i+1)} chances, **Chance: {i+1}/3**",
                    embed=e,
                )
                pass
            elif answer_content.content.lower() == answer:
                try:
                    await answer_content.delete()
                except (discord.NotFound, discord.Forbidden,
                        discord.HTTPException):
                    pass
                answerembed.color = discord.Color.green()
                await question_message.edit(
                    content=
                    f"**Yes you guessed it right!** in {i+1} chance(s), {ctx.author.mention}",
                    embed=answerembed,
                )
                return
            elif i + 1 == 3 and answer_content.content.lower() != answer:
                try:
                    await answer_content.delete()
                except (discord.NotFound, discord.Forbidden,
                        discord.HTTPException):
                    pass
                answerembed.color = discord.Color.red()
                await question_message.edit(
                    content=
                    f"Well you couldn't **guess it right in 3 chances**. Here is your **answer**!, {ctx.author.mention}",
                    embed=answerembed,
                )
                return

        try:
            await answer_content.delete()
        except (discord.NotFound, discord.Forbidden, discord.HTTPException):
            pass
        answerembed.color = discord.Color.red()
        await question_message.edit(
            content=
            f"Well you couldn't **guess it right in 3 chances**. Here is your **answer**!, {ctx.author.mention}",
            embed=answerembed,
        )
예제 #27
0
    async def on_command_error(self, ctx: commands.Context, error):
        if (ctx.cog is not None
                and ctx.cog.qualified_name.lower() == 'Music'.lower()):
            return
        error_channel = await self.bot.fetch_channel(
            ChannelAndMessageId.error_logs_channel.value)
        if isinstance(error, commands.CommandOnCooldown):
            e1 = ErrorEmbed(title="Command Error!", description=f"`{error}`")
            e1.set_footer(text=f"{ctx.author.name}")
            await ctx.channel.send(embed=e1,
                                   delete_after=self.delete_after_time)

        elif isinstance(error, (NoChannelProvided, IncorrectChannelError)):
            return

        elif isinstance(error, commands.MissingRequiredArgument):
            e4 = ErrorEmbed(title="Command Error!", description=f"`{error}`")
            e4.set_footer(text=f"{ctx.author.name}")
            await ctx.channel.send(embed=e4,
                                   delete_after=self.delete_after_time)

        elif isinstance(error, commands.CommandNotFound):
            e2 = ErrorEmbed(title="Command Error!", description=f"`{error}`")
            e2.set_footer(text=f"{ctx.author.name}")
            await ctx.channel.send(embed=e2,
                                   delete_after=self.delete_after_time)

        elif isinstance(error, commands.BotMissingPermissions):
            e = ErrorEmbed(description=error)
            await ctx.send(embed=e, delete_after=self.delete_after_time)

        elif isinstance(error, commands.MissingPermissions):
            e = ErrorEmbed(description=error)
            await ctx.send(embed=e, delete_after=self.delete_after_time)

        elif isinstance(error, commands.UserInputError):
            await ctx.send(
                embed=Embed(
                    description=
                    f"There was something **wrong** with your **input**!\n Please type\n ```)help {ctx.command.name}```,\n to know how to use the command"
                ),
                delete_after=self.delete_after_time,
            )

        elif isinstance(error, commands.NotOwner):
            return

        elif isinstance(error, commands.CheckFailure):
            return

        elif isinstance(error, commands.CheckAnyFailure):
            return

        elif isinstance(error, commands.EmojiNotFound):
            await ctx.send(
                embed=ErrorEmbed(
                    description=
                    f"The emoji provided {error.argument} was **not found!**"),
                delete_after=self.delete_after_time,
            )

        elif isinstance(error, commands.PartialEmojiConversionFailure):
            return

        elif isinstance(error, commands.BadInviteArgument):
            return

        elif isinstance(error, commands.PartialEmojiConversionFailure):
            return

        elif isinstance(error, commands.RoleNotFound):
            await ctx.send(embed=ErrorEmbed(description=error),
                           delete_after=self.delete_after_time)

        elif isinstance(error, commands.NSFWChannelRequired):
            await ctx.send(
                embed=ErrorEmbed(
                    description=
                    f"{error.channel.mention} is an **NSFW Channel**! **{ctx.command.name}** can be run only in **NSFW Channels**! :triumph:"
                ),
                delete_after=self.delete_after_time,
            )

        elif isinstance(error, commands.MissingRole):
            await ctx.send(
                embed=ErrorEmbed(
                    description=
                    f"You **need** the following **role**: **{' '.join(error.missing_role)}**"
                ),
                delete_after=self.delete_after_time,
            )

        elif isinstance(error, commands.MissingAnyRole):
            await ctx.send(
                embed=ErrorEmbed(
                    description=
                    f"You **need** the following **role**: **{' '.join(error.missing_roles)}**"
                ),
                delete_after=self.delete_after_time,
            )

        elif isinstance(error, commands.BotMissingRole):
            await ctx.send(
                embed=ErrorEmbed(
                    description=
                    f"I **need** the following **role**: **{' '.join(error.missing_role)}**"
                ),
                delete_after=self.delete_after_time,
            )

        elif isinstance(error, commands.BotMissingAnyRole):
            await ctx.send(
                embed=ErrorEmbed(
                    description=
                    f"I **need** the following **role**: **{' '.join(error.missing_roles)}**"
                ),
                delete_after=self.delete_after_time,
            )

        elif isinstance(error, commands.BadBoolArgument):
            await ctx.send(embed=ErrorEmbed(description=error),
                           delete_after=self.delete_after_time)

        elif isinstance(error, commands.BadColourArgument):
            await ctx.send(embed=ErrorEmbed(description=error),
                           delete_after=self.delete_after_time)

        elif isinstance(error, commands.ChannelNotFound):
            await ctx.send(embed=ErrorEmbed(description=error),
                           delete_after=self.delete_after_time)

        elif isinstance(error, commands.MessageNotFound):
            await ctx.send(embed=ErrorEmbed(description=error),
                           delete_after=self.delete_after_time)

        elif isinstance(error, commands.MemberNotFound):
            await ctx.send(embed=ErrorEmbed(description=error),
                           delete_after=self.delete_after_time)

        elif isinstance(error, commands.GuildNotFound):
            await ctx.send(embed=ErrorEmbed(description=error),
                           delete_after=self.delete_after_time)

        elif isinstance(error, commands.UserNotFound):
            await ctx.send(embed=ErrorEmbed(description=error),
                           delete_after=self.delete_after_time)

        elif isinstance(error, commands.ChannelNotReadable):
            await ctx.send(
                embed=ErrorEmbed(
                    description=
                    f"I need the **read message history** permission in that channel! In order to execute **{ctx.command.name}**"
                ),
                delete_after=self.delete_after_time,
            )

        elif isinstance(error, commands.DisabledCommand):
            return

        elif isinstance(error, commands.MaxConcurrencyReached):
            await ctx.send(embed=ErrorEmbed(description=error),
                           delete_after=self.delete_after_time)

        elif isinstance(error, commands.PrivateMessageOnly):
            await ctx.send(
                embed=ErrorEmbed(
                    description=f"**{ctx.command.name}** works only in **DM's**"
                ),
                delete_after=self.delete_after_time,
            )

        elif isinstance(error, commands.NoPrivateMessage):
            await ctx.send(
                embed=ErrorEmbed(
                    description=
                    f"**{ctx.command.name}** doesn't work in **DM's**"),
                delete_after=self.delete_after_time,
            )

        elif isinstance(error, commands.CommandOnCooldown):
            l = self.bot.get_command(ctx.command.name)
            left = l.get_cooldown_retry_after(ctx)
            e = ErrorEmbed(title=f"Cooldown left - {round(left)}")
            await ctx.send(embed=e, delete_after=self.delete_after_time)

        elif isinstance(error, commands.CommandInvokeError):
            e7 = ErrorEmbed(
                title=
                "Oh no, I guess I have not been given proper access! Or some internal error",
                description=f"`{error}`"[:2000],
            )
            e7.add_field(name="Command Error Caused By:",
                         value=f"{ctx.command}")
            e7.add_field(name="By", value=f"{ctx.author.name}")
            e7.set_footer(text=f"{ctx.author.name}")
            await ctx.channel.send(embed=e7,
                                   delete_after=self.delete_after_time)

            e = Embed(
                title=f"In **{ctx.guild.name}**",
                description=f"User affected {ctx.message.author}",
            )
            if ctx.guild.icon:
                e.set_thumbnail(url=ctx.guild.icon.url)
            if ctx.guild.banner:
                e.set_image(url=ctx.guild.banner.with_format("png").url)
            e.add_field(name="**Total Members**", value=ctx.guild.member_count)
            e.add_field(
                name="**Bots**",
                value=sum(1 for member in ctx.guild.members if member.bot),
            )
            e.add_field(name="**Server ID**", value=ctx.guild.id, inline=True)
            await ctx.send(
                "**Error report was successfully sent**",
                delete_after=self.delete_after_time,
            )
            try:
                raise error
            except Exception:

                await error_channel.send(
                    embeds=[e7, e],
                    file=discord.File(
                        io.BytesIO(str(traceback.format_exc()).encode()),
                        filename="traceback.txt",
                    ),
                )

        else:
            haaha = ctx.author.avatar.url
            e9 = ErrorEmbed(title="Oh no there was some error",
                            description=f"`{error}`"[:2000])
            e9.add_field(name="**Command Error Caused By**",
                         value=f"{ctx.command}")
            e9.add_field(
                name="**By**",
                value=f"**ID** : {ctx.author.id}, **Name** : {ctx.author.name}",
            )
            e9.set_thumbnail(url=f"{haaha}")
            e9.set_footer(text=f"{ctx.author.name}")
            await ctx.channel.send(embed=e9,
                                   delete_after=self.delete_after_time)

            e = Embed(
                title=f"In **{ctx.guild.name}**",
                description=f"User affected {ctx.message.author}",
            )
            if ctx.guild.icon:
                e.set_thumbnail(url=ctx.guild.icon.url)
            if ctx.guild.banner:
                e.set_image(url=ctx.guild.banner.with_format("png").url)
            e.add_field(name="**Total Members**", value=ctx.guild.member_count)
            e.add_field(
                name="**Bots**",
                value=sum(1 for member in ctx.guild.members if member.bot),
            )
            e.add_field(name="**Server ID**", value=ctx.guild.id, inline=True)
            await ctx.send(
                "**Error report was successfully sent**",
                delete_after=self.delete_after_time,
            )
            try:
                raise error
            except Exception:
                await error_channel.send(
                    embed=e,
                    file=discord.File(
                        io.BytesIO(
                            str(traceback.format_exc()).encode(),
                            filename="traceback.txt",
                        )))