Пример #1
0
 def __init__(self, bot):
     self.bot = bot
     self.data_path = bundled_data_path(self)
     self.adjectives: List[str] = []
     self.nouns: List[str] = []
     self.verbs: List[str] = []
     asyncio.create_task(self.register_words())
Пример #2
0
    def make_wheeze_img(self, template, avatar):
        # print(template.info)
        template = template.convert("RGBA")

        if type(avatar) != str:
            avatar = avatar.convert("RGBA")
            template.paste(avatar, (60, 470), avatar)
        else:
            font_loc = str(bundled_data_path(self) / "impact.ttf")
            font1 = ImageFont.truetype(font_loc, 40)
            draw = ImageDraw.Draw(template)
            margin = 40
            offset = 470
            count = 0
            for line in textwrap.wrap(avatar, width=10):
                count += 1
                if count == 6:
                    draw.text((margin, offset), f"{line}...", fill=(0, 0, 0), font=font1)
                    break
                draw.text((margin, offset), f"{line}", fill=(0, 0, 0), font=font1)
                offset += font1.getsize(line)[1]
        temp = BytesIO()
        template.save(temp, format="PNG")
        temp.name = "wheeze.png"
        return temp
Пример #3
0
    def generateText(self, text):
        # global impact, textFont

        txtColor = (20, 20, 20)
        bgColor = (224, 233, 237)
        # bgColor = (100, 0, 0)
        imgSize = (160, 200)

        # Create image
        image = Image.new("RGB", imgSize, bgColor)

        # Draw text on top
        draw = ImageDraw.Draw(image)

        # Load font for text
        textFont = self.computeAndLoadTextFontForSize(draw, text, imgSize[0])

        w, h = draw.textsize(text, font=textFont)
        xCenter = (imgSize[0] - w) / 2
        yCenter = (50 - h) / 2
        draw.text((xCenter, 10 + yCenter), text, font=textFont, fill=txtColor)
        impact = ImageFont.truetype(str(bundled_data_path(self)) + "/impact.ttf", 46)
        draw.text((12, 70), "IS NOW", font=impact, fill=txtColor)
        draw.text((10, 130), "ILLEGAL", font=impact, fill=txtColor)

        # Convert to CV2
        cvImage = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)

        # cv2.imshow('text', cvImage)

        return cvImage
Пример #4
0
    def make_banner(self, text: str, colour: str) -> BytesIO:
        im = Image.new("RGBA", (300, 100), (0, 0, 0, 0))
        font = ImageFont.truetype(str(bundled_data_path(self) / "impact.ttf"),
                                  18)
        draw = ImageDraw.Draw(im)
        size_w, size_h = draw.textsize(text, font=font)
        W, H = (size_w + 25, 100)

        images = []
        for i in range(0, W):
            im = Image.new("RGBA", (W, H), colour)
            draw = ImageDraw.Draw(im)
            draw.text((((W - size_w) / 2) - i, (100 - size_h) / 2),
                      text,
                      font=font,
                      fill="white")
            draw.text((10 + W - i, (100 - size_h) / 2),
                      text,
                      font=font,
                      fill="white")
            images.append(np.array(im))

        temp = BytesIO()
        temp.name = "temp.gif"
        imageio.mimwrite(temp, images, "gif", duration=0.02)
        temp.seek(0)
        im.close()
        return temp
    async def register(self, ctx, *, name: str):
        """Register an account with Motorsport

        Usage: !register <name>
        Example: !register Jasper Akerman
        """
        author = ctx.author
        guild = ctx.guild
        membershipinfo = await self.database.member(author).get_raw()
        if membershipinfo["Name"] == "":
            await self.database.member(author).Name.set(name)
            await self.database.member(author).MemberID.set(author.id)
            await self.database.member(author).Joined_Date.set(
                str(datetime.datetime.now().strftime("%d/%m/%y"))
            )
            shopper_role = ctx.guild.get_role(482965019189968927)
            await author.add_roles(shopper_role)

            embed = discord.Embed(
                title="Motorsport Management",
                colour=author.top_role.colour,
                description="Dear {},\n\nThank you for registering a membership with us at Premium Deluxe Motorsport!".format(
                    name
                ),
            )
            embed.set_thumbnail(url="https://i.imgur.com/xJyIgAQ.png")
            MemberRanks = [x.name for x in author.roles]
            finalrank = [x for x in MemberRanks if x in self.cardlist.keys()]
            card_loc = "template/{}.png".format(self.cardlist[finalrank[-1]])
            img_loc = str(bundled_data_path(self) / card_loc)
            img = Image.open(img_loc)
            draw = ImageDraw.Draw(img)
            font_loc = str(bundled_data_path(self) / "template/BebasNeue.ttf")
            font = ImageFont.truetype(font_loc, 24)
            msg = name
            draw.text((650, 183), msg, (44, 44, 44), font=font)
            msg = author.top_role.name
            draw.text((651, 253), msg, (44, 44, 44), font=font)
            msg = str(datetime.datetime.now().strftime("%d/%m/%y"))
            draw.text((650, 323), msg, (44, 44, 44), font=font)
            filename = "users/" + str(author.id) + ".png"
            img.save(str(bundled_data_path(self) / filename))
            image = discord.File(str(bundled_data_path(self) / filename))
            embed.set_image(url="attachment://" + str(author.id) + ".png")
            await ctx.send(file=image, embed=embed)
        else:
            await ctx.send("You are already registered!")
Пример #6
0
    def __init__(self, bot_instance):
        super().__init__()
        self.bot: bot = bot_instance

        data_dir = data_manager.bundled_data_path(self)
        self.sarcastic_image = (data_dir / "img.png").read_bytes()

        self.bot.add_listener(self.add_sarcasm, "on_message")
Пример #7
0
 def __init__(self, COG):
     BaseWriter.__init__(self, self._init, self._paint_module,
                         self._paint_text, self._finish)
     self.format = "PNG"
     self.dpi = 300
     self._image = None
     self._draw = None
     self.FONT = str(bundled_data_path(COG) / "arial.ttf")
Пример #8
0
 async def view(self, ctx):
     """View your Sketch"""
     sketch = await self.config.user(ctx.author).image_data()
     if sketch == False:
         sketch = bundled_data_path(self) / "sketch.png"
     else:
         sketch = BytesIO(base64.b64decode(sketch))
     await ctx.send(file=discord.File(sketch, "sketch.png"))
Пример #9
0
    def __init__(
        self,
        bot,
        *args,
        **kwargs,
    ):

        super().__init__(
            *args,
            **kwargs,
        )
        self.bot = bot
        self.config = Config.get_conf(
            self,
            identifier=78945698745687,
            force_registration=True,
        )

        self.guild_defaults = {
            "settings": {
                "announcement_channel": None,
                "is_announcement_enabled": False,
            },
            WallSpamRule.__class__.__name__: DEFAULT_OPTIONS,
            MentionSpamRule.__class__.__name__: DEFAULT_OPTIONS,
            DiscordInviteRule.__class__.__name__: DEFAULT_OPTIONS,
            SpamRule.__class__.__name__: DEFAULT_OPTIONS,
            MaxWordsRule.__class__.__name__: DEFAULT_OPTIONS,
            MaxCharsRule.__class__.__name__: DEFAULT_OPTIONS,
            WordFilterRule.__class__.__name__: DEFAULT_OPTIONS,
            ImageDetectionRule.__class__.__name__: DEFAULT_OPTIONS,
        }

        self.config.register_guild(**self.guild_defaults)
        self.data_path = bundled_data_path(self)

        # rules
        self.wallspamrule = WallSpamRule(self.config)
        self.mentionspamrule = MentionSpamRule(self.config)
        self.inviterule = DiscordInviteRule(self.config)
        self.spamrule = SpamRule(self.config, self.bot, self.data_path)
        self.maxwordsrule = MaxWordsRule(self.config)
        self.maxcharsrule = MaxCharsRule(self.config)
        self.wordfilterrule = WordFilterRule(self.config)
        self.imagedetectionrule = ImageDetectionRule(self.config)
        self.allowedextensionsrule = AllowedExtensionsRule(self.config)

        self.rules_map = {
            "wallspamrule": self.wallspamrule,
            "mentionspamrule": self.mentionspamrule,
            "inviterule": self.inviterule,
            "spamrule": self.spamrule,
            "maxwordsrule": self.maxwordsrule,
            "maxcharsrule": self.maxcharsrule,
            "wordfilterrule": self.wordfilterrule,
            "imagedetectionrule": self.imagedetectionrule,
            "allowedextensionsrule": self.allowedextensionsrule,
        }
Пример #10
0
    def __init__(self, bot):
        self.bot = bot
        self.config = Config.get_conf(self,
                                      identifier=79797979795642,
                                      force_registration=True)

        kink_fp = bundled_data_path(self) / "kink.json"
        extremekink_fp = bundled_data_path(self) / "extremekink.json"
        prof_fp = bundled_data_path(self) / "prof.json"
        nsfwprof_fp = bundled_data_path(self) / "nsfwprof.json"
        trope_fp = bundled_data_path(self) / "trope.json"
        nsfwtrope_fp = bundled_data_path(self) / "nsfwtrope.json"
        universe_fp = bundled_data_path(self) / "universe.json"

        with kink_fp.open("r") as kinks:
            self.KINKLIST = json.load(kinks)
        with extremekink_fp.open("r") as ekinks:
            self.EXTREMEKINKLIST = json.load(ekinks)
        with prof_fp.open("r") as profs:
            self.PROFLIST = json.load(profs)
        with nsfwprof_fp.open("r") as nsfwprofs:
            self.NSFWPROFLIST = json.load(nsfwprofs)
        with trope_fp.open("r") as tropes:
            self.TROPELIST = json.load(tropes)
        with nsfwtrope_fp.open("r") as nsfwtropes:
            self.NSFWTROPELIST = json.load(nsfwtropes)
        with universe_fp.open("r") as universe:
            self.UNIVERSELIST = json.load(universe)
Пример #11
0
 async def current(self, ctx):
     """Show the current wordlist."""
     v = await self.config.guild(ctx.guild).fp()
     if str(v) == str(bundled_data_path(self) / 'words.txt'):
         await ctx.send('The wordlist is set to the default list.')
     else:
         await ctx.send(
             f'The wordlist is set to `{str(v)[str(v).find("Hangman")+8:-4]}`.'
         )
Пример #12
0
    async def load_data(self):
        """
        Initial loading of data from bundled_data_path and config
        """
        self.asset_path = bundled_data_path(self) / "assets"
        self.current_map = await self.config.current_map()

        if self.current_map:
            await self.current_map_load()
Пример #13
0
 async def _get_worddict(self, ctx):
     """Get the proper worddict for the current locale."""
     locale = await ctx.bot.db.locale()
     if locale not in CHARS:
         await ctx.send('Your locale is not available. Using `en-US`.')
         locale = 'en-US'
     with open(bundled_data_path(self) / f'{locale}.txt') as f:
         worddict = [line.strip().lower() for line in f]
     return worddict, locale
Пример #14
0
    def __init__(self, bot):
        self.bot = bot
        self.config = Config.get_conf(self,
                                      identifier=99978023461,
                                      force_registration=True)

        gifs_fp = bundled_data_path(self) / "gifs.json"
        with gifs_fp.open("r", encoding='utf-8') as gifs:
            self.gifs = json.load(gifs)
Пример #15
0
    def __init__(self, bot):
        self.bot = bot
        self.config = Config.get_conf(self,
                                      identifier=79797979795641,
                                      force_registration=True)

        tag_fp = bundled_data_path(self) / "taglist.json"
        with tag_fp.open("r", encoding='utf-8') as tagses:
            self.TAGLIST = json.load(tagses)
Пример #16
0
 async def upload(self, ctx, folder=None):
     """Upload website files"""
     attachments = ctx.message.attachments
     if len(attachments) == 0:
         await ctx.send("No file uploaded, please upload something.")
         return
     if folder is None:
         for attachment in attachments:
             filepath = bundled_data_path(self) / attachment.filename
             await attachment.save(f"{filepath}")
     else:
         folder = bundled_data_path(self) / folder
         if not os.path.isdir(folder):
             os.makedirs(folder, exist_ok=True)
         for attachment in attachments:
             filepath = folder / attachment.filename
             await attachment.save(f"{filepath}")
     await ctx.send("New files uploaded!")
Пример #17
0
    async def add_fp_gun(self,
                         ctx,
                         prpt: Optional[float] = 1.75,
                         url: ImageFinder = None,
                         margin_x: int = 0,
                         margin_y: int = 0,
                         *,
                         mirrored: bool = False):
        if prpt <= 0:
            return await ctx.send(
                "**Proportion invalide** • La valeur de proportion doit être supérieure à 0."
            )

        if url is None:
            url = await ImageFinder().search_for_images(ctx)
        msg = await ctx.message.channel.send(
            "⏳ Patientez pendant la préparation de votre image")

        async with ctx.typing():
            url = url[0]
            filename = urlsplit(url).path.rsplit('/')[-1]
            filepath = str(self.temp / filename)
            try:
                await self.download(url, filepath)
            except:
                await ctx.send(
                    "**Téléchargement échoué** • Réessayez d'une autre façon")
            else:
                gun = bundled_data_path(self) / "GunWM.png"
                try:
                    task = self.paste_image(filepath,
                                            filepath,
                                            str(gun),
                                            scale=prpt,
                                            margin=(margin_x, margin_y),
                                            mirror=mirrored,
                                            position='bottom_right'
                                            if not mirrored else 'bottom_left')
                except:
                    os.remove(filepath)
                    logger.error("Impossible de faire gun_right/gun_left",
                                 exc_info=True)
                    return await ctx.send(
                        "**Erreur** • Impossible de créer l'image demandée.")

                file = discord.File(task)
                try:
                    await ctx.send(file=file)
                except:
                    await ctx.send(
                        "**Impossible** • Je n'ai pas réussi à upload l'image (probablement trop lourde)"
                    )
                    logger.error(msg="GUN : Impossible d'upload l'image",
                                 exc_info=True)
                os.remove(filepath)
            finally:
                await msg.delete()
Пример #18
0
    async def _theme_heist(self, ctx, theme):
        """Sets the theme for heist"""
        theme = theme.title()
        guild = ctx.guild

        if not os.path.exists(
                str(bundled_data_path(self)) + "/{}.txt".format(theme)):
            themes = [
                os.path.join(x).replace('.txt', '')
                for x in os.listdir(str(bundled_data_path(self)))
                if x.endswith(".txt")
            ]
            msg = ("I could not find a theme with that name. Available Themes:"
                   "```\n{}```".format('\n'.join(themes)))
        else:
            msg = await self.thief.theme_loader(guild, theme)

        await ctx.send(msg)
Пример #19
0
    def __init__(self, bot_instance: bot):
        super().__init__()

        self.bot = bot_instance

        data_dir = data_manager.bundled_data_path(self)
        self.alot = (data_dir / "ALOT.png").read_bytes()

        self.bot.add_listener(self.alot_event_handler, "on_message")
Пример #20
0
    async def cmd3(self, ctx):
        def check(m):
            return m.channel.id == ctx.channel.id and ctx.author.id == ctx.message.author.id

        await ctx.send("Email Address?")
        email = await ctx.bot.wait_for("message", check=check)

        await ctx.send("First Name?")
        firstname = await ctx.bot.wait_for("message", check=check)

        await ctx.send("Last Name?")
        lastname = await ctx.bot.wait_for("message", check=check)

        await ctx.send("Pirate Name?")
        piratename = await ctx.bot.wait_for("message", check=check)

        await ctx.send("Phone Number?")
        phonenumber = await ctx.bot.wait_for("message", check=check)

        msg1 = await ctx.send("Do you have an Emergency Contact? Y/N")
        start_adding_reactions(msg1, ReactionPredicate.YES_OR_NO_EMOJIS)

        pred = ReactionPredicate.yes_or_no(msg1, ctx.author)
        await ctx.bot.wait_for("reaction_add", check=pred)
        if pred.result is True:
            # User responded with tick
            await ctx.send("Emergency Contact Name?")
            emgname = await ctx.bot.wait_for("message", check=check)

            await ctx.send("Emergency Contact Phone Number?")
            emgphone = await ctx.bot.wait_for("message", check=check)

            await ctx.send("Emergency Contact Relationship?")
            emgrelation = await ctx.bot.wait_for("message", check=check)

        # Begin posting data to Spreedsheet
        scope = [
            'https://spreadsheets.google.com/feeds',
            'https://www.googleapis.com/auth/drive'
        ]
        file_path = bundled_data_path(self) / 'client_secret.json'
        creds = ServiceAccountCredentials.from_json_keyfile_name(
            file_path, scope)
        client = gspread.authorize(creds)

        sheet = client.open("DragonBot Tester").sheet1
        index = 2
        now = datetime.now()
        ts = int(datetime.timestamp(now))

        row = [
            datetime.utcfromtimestamp(ts).strftime('%m/%d/%Y %H:%M:%S'),
            email.content, firstname.content, lastname.content,
            piratename.content, phonenumber.content
        ]
        sheet.insert_row(row, index)
Пример #21
0
    def __init__(self, bot):
        # self.config = Config.get_conf(
        #     self, 1_310_527_007, force_registration=True)

        # self.RULES = open("./rules.md", "r").read()
        rules_fp = bundled_data_path(self) / "rules.md"
        self.RULES = rules_fp.open("r").read()

        info_fp = bundled_data_path(self) / "info.md"
        self.INFO = info_fp.open("r").read()

        roles_fp = bundled_data_path(self) / "roles.md"
        self.ROLES = roles_fp.open("r").read()

        invite_fp = bundled_data_path(self) / "invite.md"
        self.INVITE = invite_fp.open("r").read()

        self.session = aiohttp.ClientSession()
        self.bg_loop_task: Optional[asyncio.Task] = None
Пример #22
0
    def __init__(self, bot_instance):
        super().__init__()
        self.bot: bot = bot_instance
        self.whois = self.bot.get_cog("WhoIs")

        data_dir = data_manager.bundled_data_path(self)
        self.yandere_quotes = (data_dir /
                               "yandere_quotes.txt").read_text().split('\n')

        self.bot.add_listener(self.randomly_spoop, "on_message")
Пример #23
0
 async def play_audio(self, voice_client, channel, filename: str):
     if not filename.endswith('.mp3'):
         filename += '.mp3'
     source = FFmpegPCMAudio(str(bundled_data_path(self) / filename))
     if voice_client is None or (channel.id != voice_client.channel.id):
         vc = await channel.connect()
     else:
         vc = channel.guild.voice_client
     vc.play(source)
     return vc
Пример #24
0
 async def create_card(self, ctx, author, name: str, date):
     MemberRanks = [x.name for x in author.roles]
     finalrank = [x for x in MemberRanks if x in self.cardlist.keys()]
     card_loc = "template/{}.png".format(self.cardlist[finalrank[-1]])
     img_loc = str(bundled_data_path(self) / card_loc)
     img = Image.open(img_loc)
     draw = ImageDraw.Draw(img)
     font_loc = str(bundled_data_path(self) / "template/BebasNeue.TTF")
     font = ImageFont.truetype(font_loc, 24)
     msg = name
     draw.text((650, 183), msg, (44, 44, 44), font=font)
     msg = author.top_role.name
     draw.text((651, 253), msg, (44, 44, 44), font=font)
     msg = date
     draw.text((650, 323), msg, (44, 44, 44), font=font)
     filename = "users/" + str(author.id) + ".png"
     img.save(str(bundled_data_path(self) / filename))
     image = discord.File(str(bundled_data_path(self) / filename))
     return image
Пример #25
0
 async def _themelist_heist(self, ctx):
     """Lists available themes for heist."""
     themes = [
         os.path.join(x).replace('.txt', '')
         for x in os.listdir(str(bundled_data_path(self)))
         if x.endswith(".txt")
     ]
     if len(themes) > 30:
         themes = themes[:30]
     await ctx.send("Available Themes:```\n{}```".format('\n'.join(themes)))
Пример #26
0
 def __init__(self, bot):
     self.bot = bot
     self.config = Config.get_conf(self, identifier=7345167902)
     self.config.register_guild(fp=str(
         bundled_data_path(self) / 'words.txt'),
                                doEdit=True)
     self.man = [('    ___    \n'
                  '   |   |   \n'
                  '   |   O   \n'
                  '   |       \n'
                  '   |       \n'
                  '   |       \n'
                  '   |       \n'),
                 ('    ___    \n'
                  '   |   |   \n'
                  '   |   O   \n'
                  '   |   |   \n'
                  '   |   |   \n'
                  '   |       \n'
                  '   |       \n'),
                 ('    ___    \n'
                  '   |   |   \n'
                  '   |   O   \n'
                  '   |  \\|   \n'
                  '   |   |   \n'
                  '   |       \n'
                  '   |       \n'),
                 ('    ___    \n'
                  '   |   |   \n'
                  '   |   O   \n'
                  '   |  \\|/  \n'
                  '   |   |   \n'
                  '   |       \n'
                  '   |       \n'),
                 ('    ___    \n'
                  '   |   |   \n'
                  '   |   O   \n'
                  '   |  \\|/  \n'
                  '   |   |   \n'
                  '   |  /    \n'
                  '   |       \n'),
                 ('    ___    \n'
                  '   |   |   \n'
                  '   |   O   \n'
                  '   |  \\|/  \n'
                  '   |   |   \n'
                  '   |  / \\  \n'
                  '   |       \n'),
                 ('    ___    \n'
                  '   |   |   \n'
                  '   |   X   \n'
                  '   |  \\|/  \n'
                  '   |   |   \n'
                  '   |  / \\  \n'
                  '   |       \n')]
Пример #27
0
 def __init__(self, bot):
     self.bot = bot
     self.config = Config.get_conf(self, identifier=5454514862456)
     self.loop = asyncio.get_event_loop()
     self.session = aiohttp.ClientSession(loop=self.loop)
     default_global = {"members": {}}
     self.config.register_global(**default_global)
     #thanks to nevus for code below
     self.path = str(bundled_data_path(self)) + "/cocclans.json"
     self.rules_path = str(bundled_data_path(self)) + "/rules.txt"
     self.esports_path = str(bundled_data_path(self)) + "/esports.txt"
     self.greetings_path = str(bundled_data_path(self)) + "/greetings.json"
     with open(self.path) as file:
         self.family_clans = dict(json.load(file))
     with open(self.rules_path) as file:
         self.rules_text = file.read()
     with open(self.esports_path) as file:
         self.esports_text = file.read()
     with open(self.greetings_path) as file:
         self.greetings = dict(json.load(file))
Пример #28
0
    async def _theme_heist(self, ctx, theme):
        """Sets the theme for heist"""
        theme = theme.title()
        guild = ctx.guild

        if not os.path.exists(str(bundled_data_path(self)) + f"/{theme}.txt"):
            themes = [
                os.path.join(x).replace('.txt', '')
                for x in os.listdir(str(bundled_data_path(self)))
                if x.endswith(".txt")
            ]
            theme_per_line = '\n'.join(
                themes)  # because f-string cannot have backslashes
            msg = (
                f"I could not find a theme with that name. Available Themes:"
                f"```\n{theme_per_line}```")
        else:
            msg = await self.thief.theme_loader(guild, theme)

        await ctx.send(msg)
Пример #29
0
 async def add(self, ctx):
     """Add an image to shitpost with"""
     channel = ctx.message.channel
     msg = ctx.message
     filename = "{}".format(msg.attachments[0].filename)
     directory = str(bundled_data_path(self))
     file_path = "{}/{}".format(str(directory), filename)
     async with self.session.get(msg.attachments[0].url) as resp:
         test = await resp.read()
         with open(file_path, "wb") as f:
             f.write(test)
     await ctx.send("added")
Пример #30
0
 async def _themelist_heist(self, ctx):
     """Lists available themes for heist."""
     themes = [
         os.path.join(x).replace('.txt', '')
         for x in os.listdir(str(bundled_data_path(self)))
         if x.endswith(".txt")
     ]
     if len(themes) > 30:
         themes = themes[:30]
     theme_per_line = '\n'.join(
         themes)  # because f-string cannot have backslashes
     await ctx.send(f"Available Themes:```\n{theme_per_line}```")