Пример #1
0
 async def hotline(self, ctx, *, hotline=None):
     """Set or remove the custom hotline for the server."""
     if hotline == None:
         embed = discord.Embed(
             title="Empty Argument",
             description=
             "Please provide a custom server hotline or say `remove` to remove the current hotline!",
             color=Config.ERRORCOLOR)
     else:
         if hotline.lower() == "remove":
             embed = discord.Embed(
                 title="Hotline Removed",
                 description=
                 "I have removed the custom hotline for this server!",
                 color=embed_color(ctx.author)
                 if ctx.guild else Config.MAINCOLOR)
             Config.CLUSTER["servers"]["hotlines"].delete_one(
                 {"_id": ctx.guild.id})
         else:
             embed = discord.Embed(
                 title="Hotline Set",
                 description=
                 f"I have set the custom hotline for this server as `{hotline}`!",
                 color=embed_color(ctx.author)
                 if ctx.guild else Config.MAINCOLOR)
             Config.CLUSTER["servers"]["hotlines"].update_one(
                 {"_id": ctx.guild.id}, {"$set": {
                     "hotline": hotline
                 }},
                 upsert=True)
     await ctx.send(embed=embed)
Пример #2
0
 async def unblock(self,
                   ctx,
                   user: Union[discord.Member, discord.User, int] = None):
     """Unblock a user from creating suggestions."""
     if user == None:
         embed = discord.Embed(
             title="Empty Argument",
             description="Please provide a user to block!",
             color=Config.ERRORCOLOR)
     else:
         if isinstance(user, int):
             try:  # Use self.bot.fetch_user to turn an int into discord.User, if discord.NotFound is raised ask the user to provide a valid user.
                 user = await self.bot.fetch_user(user)
             except discord.NotFound:
                 embed = discord.Embed(
                     title="Invalid Argument",
                     description="Please provide a valid user!",
                     color=Config.ERRORCOLOR)
                 return await ctx.send(embed=embed)
         embed = discord.Embed(
             title="Unblocked",
             description=
             f"You have unblocked `{user}` from making suggestions!",
             color=embed_color(ctx.author)
             if ctx.guild else Config.MAINCOLOR)
         Config.CLUSTER["users"]["blocked"].delete_one({"_id": user.id})
         print(
             f"{Style.BRIGHT}{Fore.CYAN}[USER-UNBLOCKED]{Fore.WHITE} {Fore.YELLOW}{user.id}{Fore.WHITE} has been unblocked by {Fore.YELLOW}{ctx.author.name}{Fore.WHITE}!{Fore.RESET}"
         )
     await ctx.send(embed=embed)
Пример #3
0
    def command_help(self,
                     ctx,
                     name: str,
                     description: str,
                     usage: str,
                     aliases: list = None):
        """Generate a help embed for commands.

        Args:
            ctx (discord.Context): discord.py's context object.
            name (str): The name of the command.
            description (str): The of the command.
            usage (str): How to use the command.
            aliases (str, optional): If there are any aliases to the command. Defaults to None.

        Returns:
            discord.Embed: The generated embed.
        """
        embed = discord.Embed(
            title=name,
            description=description,
            color=embed_color(ctx.author) if ctx.guild else Config.MAINCOLOR)
        embed.set_author(
            name="Command Help",
            icon_url=
            "https://cdn.discordapp.com/emojis/512367613339369475.png?width=834&height=834"
        )
        embed.description = embed.description + f"\n\nPlease do: `{usage}`"
        if aliases:
            embed.description = embed.description + "\n\nAliases: " + ", ".join(
                [f'`{alias}`' for alias in aliases])
        return embed
Пример #4
0
 async def stats(self, ctx):
     """View some detailed statistics about the bot."""
     commands = 0
     for COG in Config.COGS:
         commands += len(set(self.bot.cogs[COG].walk_commands()))
     channels = 0
     roles = 0
     for guild in self.bot.guilds:
         channels += len(guild.channels)
         roles += len(guild.roles)
     process = psutil.Process(os.getpid())
     total_mem = psutil.virtual_memory().total
     current_mem = process.memory_info().rss
     name = f"{self.bot.user.name}'" if self.bot.user.name[
         -1] == "s" else f"{self.bot.user.name}'s"
     embed = discord.Embed(
         title=f"{name} Statistics",
         timetamp=datetime.utcnow(),
         color=embed_color(ctx.author) if ctx.guild else Config.MAINCOLOR)
     embed.add_field(
         name="📊 Bot Statistics",
         value=
         f"**Servers:** {len(self.bot.guilds)}\n**Users:** {len(self.bot.users)}\n**Channels:** {channels}\n**Roles:** {roles}\n**Shards:** {self.bot.shard_count} `[ID: {(ctx.guild.shard_id if ctx.guild else 0) + 1}]`",
         inline=False)
     embed.add_field(
         name="📋 Bot Information",
         value=
         f"**Creator:** [**Polar#6880**](https://discord.com/users/619284841187246090)\n**Bot Version:** {__version__}\n**Lines of Code:** 2790\n**Commands:** {commands}"
     )
     embed.add_field(
         name="🖥 Hardware",
         value=
         f"**discord.py Version:** v{discord.__version__}\n**Python Version:** {platform.python_version()}\n**Operating System:** {platform.system()} {platform.release()} {platform.version()}\n**Memory Usage:** {(current_mem / total_mem) * 100:.2f}% ({process.memory_info().rss / 1000000:.2f}mb)",
         inline=False)
     await ctx.send(embed=embed)
Пример #5
0
 async def support(self, ctx):
     """Obtain the link to join the bot's support server."""
     embed = discord.Embed(
         title="Support Server",
         url="https://discord.gg/VwMWj2B",
         color=embed_color(ctx.author) if ctx.guild else Config.MAINCOLOR)
     await ctx.send(embed=embed)
Пример #6
0
 async def vote(self, ctx):
     f"""Obtain the link to vote for {self.bot.user.name}."""
     embed = discord.Embed(
         title=f"Vote for {self.bot.user.name}",
         url=f"https://top.gg/bot/{self.bot.user.id}/vote",
         color=embed_color(ctx.author) if ctx.guild else Config.MAINCOLOR)
     await ctx.send(embed=embed)
Пример #7
0
 async def invite(self, ctx):
     f"""Invite {self.bot.user.name}."""
     embed = discord.Embed(
         title=f"Invite {self.bot.user.name}",
         url=
         f"https://discordapp.com/oauth2/authorize?client_id={self.bot.user.id}&permissions=26688&scope=bot",
         color=embed_color(ctx.author) if ctx.guild else Config.MAINCOLOR)
     await ctx.send(embed=embed)
Пример #8
0
 async def prefix(self, ctx, new_prefix=None):
     """View or set a prefix within a server."""
     if new_prefix == None or ctx.guild == None:
         embed = discord.Embed(
             description=
             f"Hey there, my name is { self.bot.user.name if ctx.guild == None else ctx.guild.me.display_name } and my prefix is `{get_prefix(ctx.message)}`",
             color=embed_color(ctx.author)
             if ctx.guild else Config.MAINCOLOR)
     else:
         if ctx.author.guild_permissions.manage_guild == False:
             embed = discord.Embed(
                 title="Missing Permissions",
                 description=
                 "You're missing the **Manage Server** permission which is required to change a server's prefix!",
                 color=Config.ERRORCOLOR)
         else:
             if len(new_prefix) > 5 and new_prefix.lower() != "remove":
                 embed = discord.Embed(
                     title="Prefix Too Long",
                     description=
                     "Please keep the prefix under five characters long!",
                     color=Config.ERRORCOLOR)
             else:
                 embed = discord.Embed(
                     title=f"Prefix Updated",
                     description=
                     f"My prefix is now `{ new_prefix if new_prefix.lower() != 'remove' else Config.PREFIX }`",
                     color=embed_color(ctx.author))
                 Config.CLUSTER["servers"]["prefixes"].delete_one({
                     "_id":
                     ctx.guild.id
                 }) if new_prefix.lower() == "remove" else Config.CLUSTER[
                     "servers"]["prefixes"].update_one(
                         {"_id": ctx.guild.id},
                         {"$set": {
                             "prefix": new_prefix
                         }},
                         upsert=True)
                 if new_prefix.lower(
                 ) == "remove" and ctx.guild.id in prefixes:
                     prefixes.pop(ctx.guild.id)
                 else:
                     prefixes[ctx.guild.id] = new_prefix
     await ctx.send(embed=embed)
Пример #9
0
 async def suggest(self, ctx, *, suggestion=None):
     """Suggest a trigger to the Positive Peter Support Server!"""
     blocked = Config.CLUSTER["users"]["blocked"].find_one(
         {"_id": ctx.author.id})
     if blocked != None:
         embed = discord.Embed(
             title="Blocked",
             description=
             f"You're blocked from making trigger suggestions{ ' for: ' + blocked['reason'] if blocked['reason'] != 'No reason specified.' else '!' }",
             color=embed_color(ctx.author)
             if ctx.guild else Config.MAINCOLOR)
     else:
         if suggestion == None:
             embed = discord.Embed(
                 title="Empty Argument",
                 description="Please provide a suggestion!",
                 color=Config.ERRORCOLOR)
         else:
             suggestion = suggestion[1:] if suggestion.startswith(
                 "[") else suggestion
             suggestion = suggestion[:-1] if suggestion.endswith(
                 "]") else suggestion
             embed = discord.Embed(title="Trigger Suggestion",
                                   description=suggestion,
                                   timestamp=datetime.utcnow(),
                                   color=embed_color(ctx.author)
                                   if ctx.guild else Config.MAINCOLOR)
             embed.set_footer(
                 text=f"Suggested by: {ctx.author} - ID: {ctx.author.id}")
             async with aiohttp.ClientSession() as session:
                 webhook = discord.Webhook.from_url(
                     Config.T_WEBHOOK,
                     adapter=discord.AsyncWebhookAdapter(session))
                 await webhook.send(embed=embed,
                                    username="******")
             embed = discord.Embed(
                 title="Trigger Suggested",
                 description=
                 "I have suggested your trigger to the Positive Peter Support Server!",
                 color=embed_color(ctx.author)
                 if ctx.guild else Config.MAINCOLOR)
     await ctx.send(embed=embed)
Пример #10
0
 async def configuration(self, ctx):
     """Configure the bot in your server to allow for custom hotlines and disable compliments as well as set a custom number of times for the bot to be triggered before sending a DM to the user."""
     if ctx.invoked_subcommand == None:
         prefix = get_prefix(ctx.message)
         embed = discord.Embed(
             title="Guild Configuration",
             description=
             f"**`{prefix}hotline` - Set the custom server hotline.\n`{prefix}compliments` - Whether compliments should be sent in {ctx.guild} or not.\n`{prefix}count` - The amount of times the bot has to be triggered to send a DM to a user.**",
             color=embed_color(ctx.author)
             if ctx.guild else Config.MAINCOLOR)
         await ctx.send(embed=embed)
Пример #11
0
 async def stop(self, ctx):
     f"""Disable or enable the {self.bot.user.name} from sending you direct messages."""
     document = Config.CLUSTER["users"]["stopped"].find_one(
         {"_id": ctx.author.id})
     embed = discord.Embed(
         title=
         f"{ 'Contuning' if document != None else 'Stopping'} Messages",
         description=
         f"I will { 'now' if document != None else 'no longer' } direct message you!",
         color=embed_color(ctx.author) if ctx.guild else Config.MAINCOLOR)
     Config.CLUSTER["users"]["stopped"].insert_one(
         {"_id": ctx.author.id}) if document == None else Config.CLUSTER[
             "users"]["stopped"].delete_one({"_id": ctx.author.id})
     await ctx.send(embed=embed)
Пример #12
0
 async def compliments(self, ctx):
     """Disable or enable compliments from being sent in the server."""
     document = Config.CLUSTER["servers"]["compliments"].find_one(
         {"_id": ctx.guild.id})
     embed = discord.Embed(
         title=
         f"Compliments { 'Enabled' if document != None else 'Disabled'}",
         description=
         f"I will { 'now' if document != None else 'no longer' } send compliments in this server!",
         color=embed_color(ctx.author) if ctx.guild else Config.MAINCOLOR)
     Config.CLUSTER["servers"]["compliments"].insert_one(
         {"_id": ctx.guild.id}) if document == None else Config.CLUSTER[
             "servers"]["compliments"].delete_one({"_id": ctx.guild.id})
     await ctx.send(embed=embed)
Пример #13
0
 async def count(self, ctx, count: Union[int, str] = None):
     """Set the amount of times the bot has to be triggered to DM a user."""
     if count == None:
         embed = discord.Embed(
             title="Empty Argument",
             description=
             "Please provide a number or say `remove` to remove the current count!",
             color=Config.ERRORCOLOR)
     else:
         if isinstance(count, int):
             embed = discord.Embed(
                 title="Count Set",
                 description=
                 f"I have set the count for this server to `{count}`!",
                 color=embed_color(ctx.author)
                 if ctx.guild else Config.MAINCOLOR)
             Config.CLUSTER["servers"]["count"].update_one(
                 {"_id": ctx.guild.id}, {"$set": {
                     "count": count
                 }},
                 upsert=True)
         else:
             if count.lower() == "remove":
                 embed = discord.Embed(
                     title="Count Removed",
                     description="I have removed the count for this server!",
                     color=embed_color(ctx.author)
                     if ctx.guild else Config.MAINCOLOR)
                 Config.CLUSTER["servers"]["count"].delete_one(
                     {"_id": ctx.guild.id})
             else:
                 embed = discord.Embed(
                     title="Invalid Argument",
                     description=
                     "Please provide a valid number or say `remove` to remove the current count!",
                     color=Config.ERRORCOLOR)
     await ctx.send(embed=embed)
Пример #14
0
async def restart(ctx):
    """Restart the bot's cogs."""
    embed = discord.Embed(title="Bot Restarted",
                          color=Config.MAINCOLOR
                          if ctx.guild == None else embed_color(ctx.author))
    # Print a new line and then reload each cog, as well as print that each cog has been reloaded, then print out that the bot has been fully reloaded.
    print()
    for COG in Config.COGS:
        bot.reload_extension(f"Cogs.{COG}")
        print(
            f"{Style.BRIGHT}{Fore.GREEN}[SUCCESS]{Fore.WHITE} Reloaded Cog: {COG}"
        )
    await ctx.send(embed=embed)
    print(
        f"{Style.BRIGHT}{Fore.CYAN}[BOT-RESTARTED]{Fore.WHITE} Restart by {ctx.author} - {ctx.author.id}, I'm currently in {len(bot.guilds)} servers with {len(bot.users)} users!"
    )
Пример #15
0
    async def ping(self, ctx):
        """Get the latency between our bot and Discord as well as the latency of the host."""

        # Get the time at one point, trigger typing, get the time again then subtract the two values to get the host latency. To get API latency use self.bot.latency, get round trip by adding up the two latencies.
        t1 = time.perf_counter()
        await ctx.trigger_typing()
        t2 = time.perf_counter()
        embed = discord.Embed(
            title="🏓 Pong!",
            description=
            f"Host latency is { round((t2 - t1) * 1000) }ms.\nAPI latency is { int(round(self.bot.latency * 1000, 2)) }ms.\nRound Trip took { int(round((t2 - t1) * 1000) + round(self.bot.latency * 1000, 2)) }ms.",
            color=embed_color(ctx.author) if ctx.guild else Config.MAINCOLOR)

        # Print out into the console when the round trip takes over 500 milliseconds.
        if round((t2 - t1) * 1000) + round(self.bot.latency * 1000, 2) > 500:
            print()
            print(
                f"{Style.BRIGHT}{Fore.RED}[WARNING]{Fore.WHITE} API latency is { round((t2 - t1) * 1000) }ms, host latency is { int(round(self.bot.latency * 1000, 2)) }ms, and round trip took { int(round((t2 - t1) * 1000) + round(self.bot.latency * 1000, 2)) }ms."
            )
        await ctx.send(embed=embed)
Пример #16
0
 async def block(self,
                 ctx,
                 user: Union[discord.Member, discord.User, int] = None,
                 reason=None):
     """Block a user from creating suggestions."""
     if user == None:
         embed = discord.Embed(
             title="Empty Argument",
             description="Please provide a user to block!",
             color=Config.ERRORCOLOR)
     else:
         if isinstance(user, int):
             try:  # Use self.bot.fetch_user to turn an int into discord.User, if discord.NotFound is raised ask the user to provide a valid user.
                 user = await self.bot.fetch_user(user)
             except discord.NotFound:
                 embed = discord.Embed(
                     title="Invalid Argument",
                     description="Please provide a valid user!",
                     color=Config.ERRORCOLOR)
                 return await ctx.send(embed=embed)
         embed = discord.Embed(
             title="Blocked",
             description=
             f"You have blocked `{user}` from making suggestions{ f' for: {reason}' if reason != None else '!' }",
             color=embed_color(ctx.author)
             if ctx.guild else Config.MAINCOLOR)
         Config.CLUSTER["users"]["blocked"].update_one({"_id": user.id}, {
             "$set": {
                 "reason":
                 "No reason specified." if reason == None else reason
             }
         },
                                                       upsert=True)
         print(
             f"{Style.BRIGHT}{Fore.RED}[USER-BLOCKED]{Fore.WHITE} {Fore.YELLOW}{user.id}{Fore.WHITE} has been blocked by {Fore.YELLOW}{ctx.author.name}{Fore.WHITE}{ f'for: {reason}' if reason != None else '!' }{Fore.RESET}"
         )
     await ctx.send(embed=embed)
Пример #17
0
    async def on_message(self, message):
        """Whenever a message is sent check if a response should be sent.

        Args:
            message (discord.Message): The sent message.
        """
        if message.author.bot == False:
            enabled = Config.CLUSTER["users"]["stopped"].find_one(
                {"_id": message.author.id})
            value = enabled["value"] if enabled else True
            if value:
                for trigger in self.triggers["suicide"]:
                    trigger = trigger.lower()
                    variants = [
                        trigger,
                        trigger.replace("'", ""),
                        trigger.replace("i'm", "im"),
                        trigger.replace("i'm", "i am"),
                        trigger.replace("want to", "wanna"),
                        trigger.replace("can't", "cant"),
                        trigger.replace("can't", "can not"),
                        trigger.replace("don't", "dont"),
                        trigger.replace("don't", "do not")
                    ]
                    for variant in variants:
                        if variant in message.content.lower():
                            try:
                                Config.CLUSTER["users"][
                                    "detections"].update_one(
                                        {"_id": message.author.id},
                                        {"$inc": {
                                            "detections": 1
                                        }},
                                        upsert=True)
                            except pymongo.errors.WriteError:
                                document = Config.CLUSTER["users"][
                                    "detections"].find_one(
                                        {"_id": message.author.id})
                                Config.CLUSTER["users"][
                                    "detections"].update_one(
                                        {"_id": message.author.id}, {
                                            "$set": {
                                                "detections":
                                                len(document["detections"]) + 1
                                            }
                                        })
                            detections = Config.CLUSTER["users"][
                                "detections"].find_one(
                                    {"_id": message.author.id})
                            count = 3
                            if message.guild:
                                count = Config.CLUSTER["servers"][
                                    "count"].find_one(
                                        {"_id": message.guild.id})
                                count = count["count"] if count else 3
                            if detections["detections"] >= count:
                                embed = discord.Embed(
                                    title="Suicide Prevention",
                                    description=
                                    f"Hey there {message.author.name}, based on your previous message I have detected hints of suicidal thoughts. If you are considering suicide please contact your local suicide prevention hotline, to find your hotline please visit [this](https://en.wikipedia.org/wiki/List_of_suicide_crisis_lines) website.",
                                    color=embed_color(message.author)
                                    if message.guild else Config.MAINCOLOR)
                                if message.guild:
                                    hotline = Config.CLUSTER["servers"][
                                        "hotlines"].find_one(
                                            {"_id": message.guild.id})
                                    if hotline is not None:
                                        embed.add_field(
                                            name="**Server Side Hotline**",
                                            value=hotline["hotline"])
                                try:
                                    await message.author.send(embed=embed)
                                except discord.Forbidden:
                                    pass
                                Config.CLUSTER["users"][
                                    "detections"].update_one(
                                        {"_id": message.author.id},
                                        {"$set": {
                                            "detections": 0
                                        }})
                            break
                if message.guild:
                    if Config.CLUSTER["servers"]["compliments"].find_one(
                        {"_id": message.guild.id}) == None:
                        for trigger in self.triggers["compliment"]:
                            lower_trigger = trigger.lower()
                            variants = [
                                lower_trigger,
                                lower_trigger.replace("'", ""),
                                lower_trigger.replace("i'm", "im"),
                                lower_trigger.replace("i'm", "i am")
                            ]
                            for variant in variants:
                                if variant in message.content.lower():
                                    if isinstance(
                                            self.triggers["compliment"]
                                        [trigger], list):
                                        try:
                                            await message.channel.send(
                                                choice(
                                                    self.triggers["compliment"]
                                                    [trigger]))
                                        except discord.Forbidden:
                                            pass
                                    else:
                                        try:
                                            await message.channel.send(
                                                self.triggers["compliment"]
                                                [trigger])
                                        except discord.Forbidden:
                                            pass
                                    break
Пример #18
0
 async def help(self, ctx):
     """View the help menu or information on a certain command."""
     if ctx.invoked_subcommand == None:
         prefix = get_prefix(ctx.message)
         embed = discord.Embed(color=embed_color(ctx.author) if ctx.
                               guild else Config.MAINCOLOR)
         embed.set_author(
             name="Command Help",
             icon_url=
             "https://cdn.discordapp.com/emojis/512367613339369475.png?width=834&height=834"
         )
         if ctx.author.id in Config.OWNERIDS:
             embed.add_field(
                 name="Block",
                 value=
                 f"`{prefix}block <User> [Reason]`\n*Block a user from creating suggestions.*",
                 inline=False)
         if ctx.guild:
             if ctx.author.guild_permissions.manage_guild:
                 embed.add_field(
                     name="Configuration",
                     value=
                     f"`{prefix}configuration <Option> [Value]`\n*Configure the bot in your server to allow for custom hotlines and disable compliments as well as set a custom number of times for the bot to be triggered before sending a DM to the user.*",
                     inline=False)
         embed.add_field(
             name="Help",
             value=
             f"`{prefix}help [Command]`\n*View the help menu or information on a certain command.*",
             inline=False)
         embed.add_field(
             name="Hug",
             value=
             f"`{prefix}hug [User]`\n*Hug someone or receive a hug from the bot.*",
             inline=False)
         embed.add_field(
             name="Invite",
             value=f"`{prefix}invite`\n*Invite {self.bot.user.name}.*",
             inline=False)
         embed.add_field(
             name="Ping",
             value=
             f"`{prefix}ping`\n*Get the latency between our bot and Discord as well as the latency of the host.*",
             inline=False)
         embed.add_field(
             name="Prefix",
             value=
             f"`{prefix}prefix [New Prefix]`\n*View or set a prefix within a server.*",
             inline=False)
         if ctx.author.id in Config.OWNERIDS:
             embed.add_field(
                 name="Restart",
                 value=f"`{prefix}restart`\n*Restart the bot's cogs.*",
                 inline=False)
         embed.add_field(
             name="Stats",
             value=
             f"`{prefix}stats`\n*View some detailed statistics about the bot.*",
             inline=False)
         embed.add_field(
             name="Suggest",
             value=
             f"`{prefix}suggest <Suggestion>`\n*Suggest a trigger to the Positive Peter Support Server!*",
             inline=False)
         embed.add_field(
             name="Support",
             value=
             f"`{prefix}support`\n*Obtain the link to join the bot's support server.*",
             inline=False)
         embed.add_field(
             name="Unblock",
             value=
             f"`{prefix}unblock <User> [Reason]`\n*Unblock a user from creating suggestions.*",
             inline=False)
         embed.add_field(
             name="Vote",
             value=
             f"`{prefix}vote`\n*Obtain the link to vote for {self.bot.user.name}.*",
             inline=False)
         await ctx.send(embed=embed)