Exemplo n.º 1
0
 def __init__(self):
     super().__init__(
         command_prefix=self.prefix,
         help_command=None,
         allowed_mentions=discord.AllowedMentions(everyone=False, replied_user=False),
         intents=intent,
         strip_after_prefix=True,
         case_insensitive=True,
         enable_debug_events=True,
     )
     self.consts = {"qu": {}, "ch": {}, "ne": [], "tc": {}, "pci": {}, "ticket_time": {}}
     self.raw_config = ast.literal_eval(raw_save)
     self.dbclient = motor.AsyncIOMotorClient(cstr)
     self.sync_dbclient = pymongo.MongoClient(cstr)
     self.db = self.dbclient[db_name]
     self.sync_db = self.sync_dbclient[db_name]
     self.web_pass = web_pass
     self.debug = os.environ["DEBUG"] == "True"
     self.texts = common_resources.Texts
     self.default_user_settings = {
         "level_dm": False,
     }
     self.oemojis: dict[str, discord.Emoji] = {}
     self.guild_settings: DefaultDict[int, GuildSettings] = defaultdict(lambda: copy.deepcopy(DEFAULT_SETTINGS))
     print("-- Loading saves from db: ", end="")
     self.load_saves()
     print("Done")
     print("Debug mode: " + str(self.debug))
     if self.debug:
         self.loop.create_task(self.auto_reload())
     self.check(commands.cooldown(2, 2))
Exemplo n.º 2
0
    async def _build_commands(self):
        for key in self.owoe.types:

            # Avoid duplicate commands by removing them.
            if key in self.bot.all_commands.keys():
                self.bot.remove_command(key)

            helptext = f"{key.capitalize()}!"

            async def callback(self, ctx, *tags):
                tags = list(tags)
                for tag in tags:
                    if tag not in self.owoe.tags:
                        tags.remove(tag)
                url_image = await self.owoe.random_image(type_=ctx.command.name, tags=tags)
                if isinstance(url_image, str):
                    embed = discord.Embed()
                    embed.set_image(url=url_image)
                    embed.set_footer(text="Powered by weeb.sh")
                    await ctx.send(embed=embed)
                    return
                await ctx.send("No image matching your criteria was found.")

            # Ew, gross.
            command = commands.command(name=key, help=helptext)(callback)
            command = commands.cooldown(6, 12, commands.BucketType.channel)(command)
            command.instance = self
            setattr(self, key, command)
            self.bot.add_command(command)
Exemplo n.º 3
0
def cooldown(rate,
             per_sec=0,
             per_min=0,
             per_hour=0,
             type=commands.BucketType.default):
    return commands.cooldown(rate, per_sec + 60 * per_min + 3600 * per_hour,
                             type)
Exemplo n.º 4
0
    def __init__(self, config_file:str='config/config.json', commandline_args=None, *args, **kwargs):
        # Things I would need anyway
        if kwargs.get('command_prefix'):
            super().__init__(*args, **kwargs)
        else:
            super().__init__(command_prefix=get_prefix, *args, **kwargs)

        # Store the config file for later
        self.config = None
        self.config_file = config_file
        self.reload_config()
        self.commandline_args = commandline_args
        self.bad_argument = compile(r'(User|Member) "(.*)" not found')
        self._invite_link = None

        # Aiohttp session for use in DBL posting
        self.session = ClientSession(loop=self.loop)

        # Allow database connections like this
        self.database = DatabaseConnection
        self.redis = RedisConnection

        # Allow get_guild and setup for server-specific trees
        self.server_specific_families = []  # list[guild_id]
        FamilyTreeMember.bot = self
        CustomisedTreeUser.bot = self

        # Store the startup method so I can see if it completed successfully
        self.startup_time = dt.now()
        self.startup_method = None
        self.deletion_method = None

        # Add a cache for proposing users
        self.proposal_cache = ProposalCache()

        # Add a list of blacklisted guilds and users
        self.blacklisted_guilds = []
        self.blocked_users = {}  # user_id: list(user_id)

        # Dictionary of custom prefixes
        self.guild_prefixes = {}  # guild_id: prefix

        # See who voted for the bot and when
        self.dbl_votes = {}  # uid: timestamp (of last vote)
        
        # Add a cooldown to help
        cooldown(1, 5, BucketType.user)(self.get_command('help'))
Exemplo n.º 5
0
def cooldown(amount: int,
             channel_wide: bool = False,
             server_wide: bool = False):
    return commands.cooldown(
        1, amount,
        getattr(
            commands.BucketType, "guild" if server_wide else
            ("channel" if channel_wide else "user")))
Exemplo n.º 6
0
def short_cooldown(
    type: cooldowns.BucketType = cooldowns.BucketType.channel
) -> commands.Command:
    """
    Rate-limiting decorator ("once in 30s"). Limitations are channel-based by default (controlled by `type`).
    """

    return commands.cooldown(rate=1, per=30, type=type)
Exemplo n.º 7
0
    def __init__(self,
                 config_file: str = 'config/config.json',
                 *args,
                 **kwargs):
        '''Make the bot WEW'''

        # Get the command prefix from the kwargs
        if kwargs.get('command_prefix'):
            super().__init__(*args, **kwargs)
        else:
            super().__init__(command_prefix=get_prefix, *args, **kwargs)

        # Hang out and make all the stuff I'll need
        self.config: dict = None  # the config dict - None until reload_config() is sucessfully called
        self.config_file = config_file  # the config filename - used in reload_config()
        self.reload_config()  # populate bot.config
        self.bad_argument = compile(
            r'(User|Member) "(.*)" not found')  # bad argument regex converter
        self._invite_link = None  # the invite for the bot - dynamically generated
        self.shallow_users = {
        }  # id: (User, age) - age is how long until it needs re-fetching from Discord
        self.support_guild = None  # the support guild - populated by patreon check and event log
        self.session = ClientSession(
            loop=self.loop)  # aiohttp session for get/post requests
        self.database = DatabaseConnection  # database connection class
        self.redis = RedisConnection  # redis connection class
        self.server_specific_families = [
        ]  # list[guild_id] - guilds that have server-specific families attached
        FamilyTreeMember.bot = self
        CustomisedTreeUser.bot = self
        ProposalCache.bot = self
        TreeCache.bot = self
        self.startup_time = dt.now()  # store bot startup time
        self.startup_method = None  # store startup method so I can see errors in it
        self.deletion_method = None  # store deletion method so I can cancel it on shutdown
        self.proposal_cache = ProposalCache(
        )  # cache for users who've been proposed to/are proposing
        self.blacklisted_guilds = [
        ]  # a list of guilds that are blacklisted by the bot
        self.blocked_users = defaultdict(
            list)  # user_id: list(user_id) - users who've blocked other users
        self.guild_settings = {}  # guild_id: Dict - custom setings per guild
        self.dbl_votes = {}  # uid: timestamp (of last vote) - cast dbl votes
        self.tree_cache = TreeCache()  # cache of users generating trees
        cooldown(1, 5, BucketType.user)(
            self.get_command('help'))  # add cooldown to help command
Exemplo n.º 8
0
class Times(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.cooldown(1, 60, commands.BucketType.user)
    @in_bot_commands()
    @commands.command(name="when",
                      help_command="!when",
                      description="Check when the hackathon starts or ends",
                      help="Check when the hackathon starts or ends"
                      )
Exemplo n.º 9
0
    def __init__(self,
                 config_file: str = 'config/config.json',
                 commandline_args=None,
                 *args,
                 **kwargs):
        # Things I would need anyway
        if kwargs.get('command_prefix'):
            super().__init__(*args, **kwargs)
        else:
            super().__init__(command_prefix=get_prefix, *args, **kwargs)

        # Store the config file for later
        self.config = None
        self.config_file = config_file
        self.reload_config()
        self.commandline_args = commandline_args

        # Add webserver stuff so I can come back to it later
        self.web_runner = None

        # Allow database connections like this
        self.database = DatabaseConnection
        self.database.config = self.config['database']

        # Store the startup method so I can see if it completed successfully
        self.startup_method = self.loop.create_task(self.startup())
        self.deletion_method = self.loop.create_task(self.delete_loop())

        # Add a cache for proposing users
        self.proposal_cache = RemovalDict()

        # Add a list of blacklisted guilds
        self.blacklisted_guilds = []

        # Dictionary of custom prefixes
        self.guild_prefixes = {}  # guild_id: prefix

        # Add a cooldown to help
        cooldown(1, 5, BucketType.user)(self.get_command('help'))
Exemplo n.º 10
0
 def predicate(ctx):
     cooldown_end = cooldown_actions.get_cooldown_end_time(
         ctx.message.author)
     if cooldown_end is None:
         return True
     else:
         now = int(time.time())
         if not now > cooldown_end:
             seconds_remaining = cooldown_end - now
             raise commands.CommandOnCooldown(commands.cooldown(1, 900),
                                              seconds_remaining)
         else:
             return True
Exemplo n.º 11
0
    def __new__(cls, name, bases, attrs, *, generator: BaseImageGenerator, **kwargs):
        for attr_name in dir(generator):
            attr = getattr(generator, attr_name)
            if not getattr(attr, "__image_generator__", False):
                continue
            signature = inspect.signature(attr)
            params = signature.parameters
            if len(params) == 2 and list(params.values())[1].annotation == ImageType:
                cmd = Command(image_paste_command(attr_name), name=attr_name)

            elif all([p.annotation == str for p in list(params.values())[1:]]):
                cmd = Command(
                    text_write_command(attr_name, len(params) - 1), name=attr_name
                )

            else:
                raise RuntimeError("Unknown image generator args")

            cooldown(1, 5, BucketType.user)(cmd)
            attrs[attr.__name__] = cmd
        self = super().__new__(cls, name, bases, attrs, **kwargs)
        return self
Exemplo n.º 12
0
    def __init__(self, _bot):
        self.bot: "bot.DemocracivBot" = _bot
        self.bot.loop.create_task(self._transform_description())

        for command in self.walk_commands():
            if command.help:
                self.bot.loop.create_task(
                    self._transform_command_help(command))

            if not command._buckets._cooldown:
                cooldown_deco = commands.cooldown(1,
                                                  config.BOT_COMMAND_COOLDOWN,
                                                  commands.BucketType.user)
                cooldown_deco(command)
Exemplo n.º 13
0
    def add_pattern(self, doc):
        async def func(self, ctx):
            await ctx.send(random.choice(doc['messages']))

        func.__name__ = doc['name']
        func.__doc__ = 'pattern: ' + doc['pattern']
        aliases = doc.get('aliases')
        seconds = doc.get('seconds')
        if seconds != 0:
            func = commands.cooldown(1, seconds if seconds else 900,
                                     commands.BucketType.guild)(func)
        func = commands.command(name=doc['name'],
                                aliases=aliases if aliases else [],
                                hidden=True)(func)
        func.instance = self
        self.__cog_commands__ += (func, )
Exemplo n.º 14
0
    def make_cmd(name: str, help_desc: 'Optional[str]',
                 embeds: 'dict[str, discord.Embed]',
                 cooldown: 'tuple[int, int]',
                 aliases: list[str]) -> commands.Command:
        if len(embeds) > 1:
            # multi-console commands require a check
            async def multi_cmd(self, ctx, *, consoles=''):
                supported_consoles = list(embeds)
                for s in supported_consoles:
                    if s in {'dsi', 'wii'}:
                        # special case for legacy channel
                        supported_consoles.append('legacy')
                # replace aliases with the expected console
                requested_consoles = {
                    get_console_name(c)
                    for c in consoles.split()
                }
                # and then check if any of the consoles are supported here
                requested_consoles = {
                    c.lower()
                    for c in requested_consoles
                    if c.lower() in supported_consoles
                }
                channel_name = ctx.channel.name if not isinstance(
                    ctx.channel, discord.DMChannel) else ''

                if not requested_consoles:
                    if channel_name.startswith(tuple(supported_consoles)):
                        requested_consoles = {'auto'}
                    else:
                        valid = set(supported_consoles)
                        for v in supported_consoles:
                            valid |= name_to_aliases[v]
                        await ctx.send(
                            f'Please specify a console. Valid options are: {", ".join(sorted(valid))}'
                        )

                        ctx.command.reset_cooldown(ctx)
                        return

                for console in requested_consoles:
                    for embed_console, embed in embeds.items():
                        cons = [embed_console]
                        if embed_console in {'dsi', 'wii'}:
                            # special case for legacy channel
                            cons.append('legacy')
                        if check_console(console, channel_name, tuple(cons)):
                            await ctx.send(embed=embed)

            cmd = multi_cmd
        else:
            # single-console commands can simply print the one embed
            async def simple_cmd(self, ctx):
                # this is kinda ugly, but basically it gets the first (and only) value of the dict
                await ctx.send(embed=next(iter(embeds.values())))

            cmd = simple_cmd

        # gotta trick the lib so it thinks the callback is inside a class
        cmd.__name__ = name
        cmd.__qualname__ = f"{cog_class.qualified_name}.{cmd.__name__}"

        # i figured this was easier than dealing with the multiple attributes for command help
        cmd.__doc__ = help_desc

        # this feels _wrong_ but is probably the best way to do this
        cooldown = commands.cooldown(cooldown[0], cooldown[1],
                                     commands.BucketType.channel)(cmd)
        cmd_obj = namespace.command(name=name, aliases=aliases)(cooldown)
        return cmd_obj
Exemplo n.º 15
0
                   embed=embed)


held = [
    "https://cdn.discordapp.com/attachments/741845376314769468/743703038195138580/tenor_1.gif",
    "https://cdn.discordapp.com/attachments/741845376314769468/743703037914251284/tenor_2.gif",
    "https://cdn.discordapp.com/attachments/741845376314769468/743703037490626600/tenor_3.gif",
    "https://cdn.discordapp.com/attachments/741845376314769468/743703037167796324/tenor_4.gif",
    "https://cdn.discordapp.com/attachments/741845376314769468/743689816985698394/tenor.gif"
]
lala = [
    0x1abc9c, 0x9b59b6, 0x99aab5, 0x7289da, 0xa84300, 0xf1c40f, 0xe91e63,
    0x546e7a
]
t = todoroki.command()
cd = commands.cooldown(1, 12, commands.BucketType.user)
owner = 552492140270452736


@bot.command()
@cd
async def bug(ctx, *, msg: str):
    own = bot.get_user(552492140270452736)
    lol = bot.get_channel(726671245621592175)
    serverinvite = await ctx.message.channel.create_invite(
        reason='Requested by ' + str(ctx.message.author.name))
    color = discord.Color(value=0x00ff00)
    em = discord.Embed(color=color, title="Bug reported!")
    em.description = f"Bug : {msg}\nBug sent by {ctx.author}\nInvite : [Link]({serverinvite})"
    await lol.send(embed=em)
    await own.send(ctx.author.id)
Exemplo n.º 16
0
def cooldown(*args):
    return commands.cooldown(1, int(args[0]), commands.BucketType.user)
Exemplo n.º 17
0
    def __init__(self, bot):
        """Procedurablly build reaction commands."""

        with open("reactions.json") as fobject:
            self.data = json.load(fobject)

        count = 0
        # TODO Add a help field to this mess.
        for key in self.data:

            # Avoid duplicate commands.
            if key in bot.all_commands.keys():
                continue

            # Avoid non-dictionary values.
            # Make sure that there exists a value with key "images", and that it's a list.
            elif (not isinstance(self.data[key], dict)
                  or not isinstance(self.data[key].get("images"), list)):
                continue

            # This signifies the type of message to be sent.
            message_indicator = self.data[key].get("message")

            # No message.
            if message_indicator is None:
                helptext = f"{key.capitalize()}!"

                async def callback(self, ctx):
                    await _send_image(ctx,
                                      self.data[ctx.command.name]["images"])

            # Zero-length string.
            elif not message_indicator:
                helptext = f"{key.capitalize()} a user!"

                async def callback(self, ctx, *, user: str):
                    message = await _generate_message(ctx, ctx.command.name,
                                                      user)
                    await _send_image(ctx,
                                      self.data[ctx.command.name]["images"],
                                      message)

            # Custom message.
            else:
                helptext = f"{key.capitalize()}!"

                async def callback(self, ctx):
                    await _send_image(ctx,
                                      self.data[ctx.command.name]["images"],
                                      self.data[ctx.command.name]["message"])

            # Ew, gross.
            aliases = self.data[key].get("aliases", [])
            for alias in aliases:
                if alias in bot.all_commands.keys():
                    aliases.remove(alias)
            command = commands.command(name=key,
                                       help=helptext,
                                       aliases=aliases)(callback)
            command = commands.cooldown(6, 12,
                                        commands.BucketType.channel)(command)
            command.instance = self
            setattr(self, key, command)
            count += 1
Exemplo n.º 18
0
def short_cooldown(f):
    return commands.cooldown(rate=5, per=20.0,
                             type=commands.BucketType.user)(f)
Exemplo n.º 19
0
    def wrapper(command) -> commands.Command:
        if cd:
            command = commands.cooldown(rate, per, bucket)(command)
            command.cooldown_after_parsing = True

        return commands.check(check)(command)
Exemplo n.º 20
0
def long_cooldown(f):
    return commands.cooldown(rate=1, per=20.0,
                             type=commands.BucketType.user)(f)
Exemplo n.º 21
0
def default_cooldown(f):
    return commands.cooldown(rate=5, per=30.0,
                             type=commands.BucketType.user)(f)
Exemplo n.º 22
0
import itertools
import io

import discord
import lifesaver
from PIL import Image, ImageDraw, ImageFont
from discord.ext import commands

from .converters import TierList
from .utils import image_renderer, draw_word_wrap

standard_cooldown = commands.cooldown(1, 3, commands.BucketType.user)

brain_heights = [
    155,
    181,
    188,
    165,
    179,
    190,
    210,
    194,
]

tier_colors = [
    (255, 127, 127),
    (255, 191, 127),
    (255, 223, 127),
    (255, 255, 127),
    (191, 255, 127),
    (127, 255, 127),
Exemplo n.º 23
0
import asyncio
import requests
from deku import *
import deku as todo
from discord import Embed
import platform
import sys
from psutil import Process
from platform import python_version
from discord.ext import commands
from discord.ext.commands import command, BucketType, cooldown, Cog
from discord import __version__ as discord_version
import discord, json, time, datetime, json, psutil, platform

cc = commands.command()
sm = commands.cooldown(1, 14, commands.BucketType.user)
cyan = 0, 255, 255
yell = 255, 255, 0
ung = 191, 0, 255
vi = 143, 0, 255
liyr = os.environ.get("LIYRIK")
q = os.environ.get("BRAINLY")
k = os.environ.get("KEYEMAS")
say = os.environ.get("SS")
go = os.environ.get("go")
key = os.environ.get("keygo")
numkey = os.environ.get("numbertoken")
joox = os.environ.get("JOOX")
twit = os.environ.get("TWIT")
memek = os.environ.get("MEMEK")
wea = os.environ.get("WEA")
Exemplo n.º 24
0
        else:
            # compose string accordingly
            breakdown = (
                "HackTX 2021 " + ("begins " if start > austin() else "ends ") + "in " + time_left(event)
=======
            breakdown = "Changeathon has ended. Come back next year :))"
        else:
            # compose string accordingly
            breakdown = (
                "Changeathon " + ("begins " if start > austin() else "ends ") + "in " + time_left(event)
>>>>>>> fb1d025f3d8eed90f94d9173a47e8da755c3bba1
            )

        await ctx.send(breakdown)

    @commands.cooldown(1, 60, commands.BucketType.guild)
    @in_bot_commands()
    @commands.command(name="schedule",
                      help_command="!schedule",
                      description="See the hackathon schedule",
                      help="See the hackathon schedule"
                      )
    async def schedule(self, ctx):
        embeds = []

        for day, events in sched.items():
            if day >= austin().day:
<<<<<<< HEAD
                full_day = ["Saturday", "Sunday"][day - 30]  # 30 since that was the first day

                embed = discord.Embed(