Exemple #1
0
class InvitePlug(Plugin):

    def load(self, config):
        self.invite_db = InviteDatabase()
        self.db = Database("InvitePlug")
        self.logger = getLogger("InvitePlug")
        super().load(config)
        self.logger.info("Finished loading invite plugin")

    @Plugin.listen("GuildMemberAdd")
    def on_member(self, event):
        if self.invite_db.already_joined(event):
            self.logger.info("User {0} has rejoined the server".format(event.user.id))
        else:
            for invite in self.invite_db:
                try:
                    invite_obj = event.client.api.invites_get(invite['invite_code'])
                    print(invite_obj.uses, "/", invite_obj.max_uses)
                except APIException:
                    self.logger.info("Invite revoked! Rewarding accordingly")
                    self.db.create_user(event.user)
                    invited = self.db.find_user(event.user.id)
                    inviter = self.db.find_user(invite['user_id'])
                    invited.bepis += 20
                    inviter.bepis += 30
                    event.client.api.channels_messages_create(
                        GENERAL_CHANNEL,
                        "Thanks for inviting <@{0}>, <@{1}>. You've earned 30 bepis and"
                        " <@{1}> earned 20 for using the referral link".format(invited.user_id, inviter.user_id)
                    )
                    self.invite_db.remove_invite(invite['invite_code'])
                    self.logger.info("Removed invite and rewarded users")
                    break
            else:
                self.db.create_user(event.user)
            self.logger.info("Created account for User {0}".format(event.user.id))

    @Plugin.command("invite")
    @ensure_profile
    def create_invite(self, event, user):
        invite = self.invite_db.invites.find_one({"user_id": user.user_id})
        if invite:
            invite_code = invite['invite_code']
        else:
            invite = event.msg.channel.create_invite(
                max_age=0,
                max_uses=1,
                unique=True
            )
            invite_code = invite.code
            self.invite_db.register_invite(invite_code, user.user_id)
        event.msg.reply("There! Here's your referral link. Whenever a person joins with this link, you'll get 30 bepis"
                        "and they'll get 20. Make sure to get a new link after inviting someone! https://discord.gg/"
                        + invite_code)
Exemple #2
0
class ShopPlug(Plugin):
    def load(self, config):
        self.db = Database("ShopPlug")
        self.logger = getLogger("ShopPlug")
        self.shibes = {}
        super().load(config)
        self.logger.info("Finished loading ShopPlug")

    @Plugin.listen("Ready")
    def on_ready(self, event):
        client = event.guilds[0].client
        shibe_channel = client.api.channels_get(SHIBE_CHANNEL)
        for msg in shibe_channel.messages:
            split_msg = msg.content.split(' ')
            _, name = split_msg[0], ' '.join(split_msg[1:])
            if "⭐" in name:
                value = 1000
            elif "🌟" in name:
                value = 10000
            elif "💫" in name:
                continue
            else:
                value = 20
            self.shibes[name] = value
        self.shibes = sorted(self.shibes.items(), key=lambda x: x[1])
        self.shibes.reverse()
        self.logger.info("Finished loading {0} shibes".format(len(
            self.shibes)))

    @Plugin.command("bepis", "[other_user:str]")
    @ensure_profile
    @ensure_other
    def get_bepis(self, event, user, other_user=None):
        if other_user:
            other_db = self.db.find_user(other_user.user.id)
            event.msg.reply("{1} has **{0}** bepis".format(
                other_db.bepis, other_user.user.username))
        else:
            event.msg.reply("You have **{0}** bepis".format(user.bepis))
        self.logger.info("User {0} is making it rain".format(user.user_id))

    @Plugin.command("sell", "<shibe_index:int>")
    @ensure_profile
    @ensure_index
    def sell_shibe(self, event, user, shibe, shibe_index: int):
        if "⭐" in shibe[0]:
            user.bepis += 1000
        elif "🌟" in shibe[0]:
            user.bepis += 10000
        elif "💫" in shibe[0]:
            user.bepis += 1000000
        else:
            user.bepis += 10
        event.msg.reply("Thanks for the {0}, you now have {1} bepis".format(
            shibe[0], user.bepis))
        index = user.shibes.index(shibe)
        user.remove_shibe(index)

    @Plugin.command("shop", "[page:int]")
    def show_shop(self, event, page: int = 1):
        if page not in range(1, (len(self.shibes) // 20) + 2):
            return event.msg.reply(
                "Invalid page number, choose a page from 1 to {0}".format(
                    (len(self.shibes) // 20) + 1))

        embed = MessageEmbed()
        embed.title = "The Shibe Shop!"
        embed.description = "\n".join(
            map(
                lambda x: "{0}): Selling {1} for {2}".format(
                    x[0] + ((page - 1) * 20) + 1, x[1][0], x[1][1]),
                enumerate(self.shibes[20 * (page - 1):page * 20])))
        embed.color = 0xFFFDD0
        embed.set_footer(
            text="Like what you see? Buy something! page {0}/{1}".format(
                page, (len(self.shibes) // 20) + 1))
        event.msg.reply(embed=embed)

    @Plugin.command("buy shibe", "<shop_index:int>")
    @ensure_profile
    def buy_shop(self, event, user, shop_index: int):
        try:
            buy_shibe = self.shibes[shop_index - 1]
        except IndexError:
            return event.msg.reply(
                "Invalid shop index, check !shop again to see if you typed it right."
            )
        if user.bepis < buy_shibe[1]:
            return event.msg.reply(
                "Sorry, but you need {0} more bepis".format(buy_shibe[1] -
                                                            user.bepis))
        user.bepis -= buy_shibe[1]
        user.add_shibe(buy_shibe[0])
        event.msg.reply("Thanks for shopping! here's your **{0}**".format(
            buy_shibe[0]))
        self.logger.info("User {0} bought a {1}".format(
            user.user_id, buy_shibe[0]))

    @Plugin.command("donate", "<other_user:str>, <amount:int>")
    @ensure_profile
    @ensure_other
    def donate_bepis(self, event, user, other_user, amount: int):
        if user.bepis < amount:
            return event.msg.reply(
                "You don't have enough bepis to donate that amount")
        elif amount < 1:
            return event.msg.reply("You can't just *give* them no money!")
        db_user = self.db.find_user(other_user.user.id)
        user.bepis -= amount
        db_user.bepis += amount
        event.msg.reply("Done! {0} make sure to say 'Thank you'.".format(
            other_user.user.mention))

    @Plugin.command("flip", "<amount:int>")
    @ensure_profile
    def flip_bepis(self, event, user, amount: int):
        if user.bepis < amount:
            return event.msg.reply(
                "You don't have enough bepis to bet that amount")
        elif amount < 1:
            return event.msg.reply("What? You can't bet nothing!")

        if randint(0, 1):
            user.bepis += amount
            event.msg.reply("Contratz! You won! You now have {0} bepis".format(
                user.bepis))
        else:
            user.bepis -= amount
            event.msg.reply("Oh no, you lost... You now have {0} bepis".format(
                user.bepis))
Exemple #3
0
class BattlePlug(Plugin):

    def load(self, config):
        self.db = Database("BattlePlug")
        self.shibes = {}
        self.logger = getLogger("BattlePlug")
        super().load(config)
        self.logger.info("Finished loading")

    @Plugin.listen("Ready")
    def on_ready(self, event):
        client = event.guilds[0].client
        shibe_channel = client.api.channels_get(SHIBE_CHANNEL)
        for msg in shibe_channel.messages:
            split_msg = msg.content.split(' ')
            url, name = split_msg[0], ' '.join(split_msg[1:])
            self.shibes[name] = url
        self.logger.info("Finished loading {0} shibes".format(len(self.shibes.keys())))

    @Plugin.command("battle", "<other_user:str> <shibe_index:int>")
    @ensure_profile
    @ensure_index
    @ensure_other
    @limit_channel(*COMMAND_OUTLAWS, alternative_channel_id=REDIRECT_CHANNEL)
    def start_battle(self, event, user, shibe, other_user, shibe_index: int):
        if user.user_id == other_user.user.id:
            return event.msg.reply("You can't battle yourself. That defeats the purpose.")

        event.msg.reply("Hey {0}! <@{1}> has challenged you to a duel! Type !accept if you accept,"
                        " or !decline if you decline.".format(other_user.user.mention, user.user_id))
        other_status = None

        def cond(event):
            nonlocal other_status
            if event.content.startswith("!accept"):
                other_status = True
            elif event.content.startswith("!decline"):
                other_status = False
            else:
                return False
            return True

        result = self.wait_for_event("MessageCreate", conditional=cond,
                                     channel__id=event.msg.channel.id, author__id=other_user.user.id)
        try:
            result.get(timeout=30.0)
        except timeout.Timeout:
            return event.msg.reply("Sorry, but your opponent didn't reply in time. Try someone else!")
        if not other_status:
            return event.msg.reply("Well, that's too bad. I bet you're just scared.")
        event.msg.reply("Alright! And what shibe will you be using {0}? (provide an index, see !inv)"
                        .format(other_user.user.mention))

        def cond(event):
            if event.content.isnumeric():
                return True
            return False

        result = self.wait_for_event("MessageCreate", conditional=cond,
                                     channel__id=event.msg.channel.id,  author__id=other_user.user.id)
        try:
            number = int(result.get(timeout=30.0).content)
        except timeout.Timeout:
            return event.msg.reply("Sorry, but your opponent didn't reply in time. Try someone else!")

        other_user_db = self.db.find_user(other_user.user.id)
        if not other_user_db:
            return event.msg.reply("Sorry, that shibe doesn't exist. Why don't you check again another time?")
        try:
            other_shibe = other_user_db.shibes[number - 1]
        except IndexError:
            return event.msg.reply("Sorry, that shibe doesn't exist. Why don't you check again another time?")
        event.msg.reply("Alright, let's DUEL! (This may take a bit, please be patient :wink:)")

        main_shibe_image = self.shibes[shibe[0]]
        other_shibe_image = self.shibes[other_shibe[0]]
        main_resp = requests.get(main_shibe_image)
        main_image = BytesIO(main_resp.content)
        other_resp = requests.get(other_shibe_image)
        other_image = BytesIO(other_resp.content)
        background = Image.open("imgs/background.jpg")
        main_image = Image.open(main_image).resize((240, 200))
        background.paste(main_image, (500, 250))
        other_image = Image.open(other_image).resize((150, 150))
        background.paste(other_image, (1200, 300))

        main_health, other_health, turn, last_msg = 100, 100, random.randint(0, 1), None
        while main_health > 0 and other_health > 0:
            send_background = background.copy()
            draw_background = ImageDraw.Draw(send_background)
            draw_background.rectangle([(500, 150), (500 + (main_health * 3), 175)], fill=ImageColor.getrgb("green"))
            draw_background.rectangle([(1200, 200), (1200 + (other_health * 3), 175)], fill=ImageColor.getrgb("green"))

            upload_file = BytesIO()
            send_background.save(upload_file, format="png")
            upload_file.seek(0)
            if last_msg:
                new_msg = event.msg.reply(battle_msg, attachments=[("battle.png", upload_file)])
                last_msg.delete()
                last_msg = new_msg
            else:
                last_msg = event.msg.reply("Let's BEGIN!", attachments=[("battle.png", upload_file)])

            if turn % 2:
                main_health -= random.randint(20, 60)
                battle_msg = random.choice(BATTLE_MSGS).format(other_user_db.user_id, other_shibe[0], shibe[0])
            else:
                other_health -= random.randint(15, 50)
                battle_msg = random.choice(BATTLE_MSGS)
                battle_msg = battle_msg.format(user.user_id, shibe[0], other_shibe[0])
            turn += 1

            sleep(1)

        if main_health <= 0:
            main_health, msg = 0, other_user.user.mention + " won! You get <@{0}>'s {1}".format(user.user_id, shibe[0])
        else:
            other_health, msg = 0, "<@{0}> won! You get {1}'s {2}"\
                .format(user.user_id, other_user.user.mention, other_shibe[0])

        send_background = background.copy()
        draw_background = ImageDraw.Draw(send_background)
        draw_background.rectangle([(500, 150), (500 + (main_health * 3), 175)], fill=ImageColor.getrgb("green"))
        draw_background.rectangle([(1200, 200), (1200 + (other_health * 3), 175)], fill=ImageColor.getrgb("green"))

        upload_file = BytesIO()
        send_background.save(upload_file, format="png")
        upload_file.seek(0)
        event.msg.reply(msg, attachments=[("battle.png", upload_file)])
        last_msg.delete()

        if not main_health:
            user.remove_shibe(shibe_index - 1)
            other_user_db.add_shibe(shibe[0])
        else:
            other_user_db.remove_shibe(number - 1)
            user.add_shibe(other_shibe[0])

    @Plugin.command("bestfren")
    def best_friend(self, event):
        person = random.choice([self.shibes["Jack Shibe"], self.shibes["Para Shibe"]])
        resp = requests.get(person)
        file = BytesIO(resp.content)
        event.msg.reply(attachments=[("bestfriend.png", file)])
Exemple #4
0
class ShibeUpdatePlug(Plugin):

    def load(self, config):
        self.db = Database("ShibeUpdatePlug")
        self.logger = getLogger("ShibeUpdatePlug")
        self.shibes = {}
        super().load(config)
        self.logger.info("Finished loading ShibeUpdatePlug")

    @Plugin.listen("Ready")
    def on_ready(self, event):
        client = event.guilds[0].client
        shibe_channel = client.api.channels_get(SHIBE_CHANNEL)
        for msg in shibe_channel.messages:
            split_msg = msg.content.split(' ')
            url, name = split_msg[0], ' '.join(split_msg[1:])
            self.shibes[name] = url
        self.logger.info("Finished loading {0} shibes".format(len(self.shibes.keys())))

    @Plugin.command("catch")
    @ensure_profile
    @limit_channel(*COMMAND_OUTLAWS, alternative_channel_id=REDIRECT_CHANNEL)
    def catch_chibe(self, event, user):
        diff = datetime.now() - user.last_daily
        if diff >= timedelta(hours=3):
            while True:
                name, url = choice(tuple(self.shibes.items()))
                if "⭐" in name:
                    if randint(1, 100) != 1:
                        continue
                elif "🌟" in name:
                    if randint(1, 500) != 1:
                        continue
                elif "💫" in name:
                    if randint(1, 1000) != 1:
                        continue

                resp = requests.get(url)
                file = BytesIO(resp.content)
                file.seek(0)
                event.msg.reply("You found a **{0}**".format(name), attachments=[(name + ".png", file)])
                user.add_shibe(name)
                user.last_daily = datetime.now()
                self.logger.info("User {0} caught a {1}".format(user.user_id, name))
                break
        else:
            hours, minutes, seconds = map(lambda x: int(float(x)), str(diff).split(':'))
            print(hours, minutes, seconds)
            return event.msg.reply(
                "Sorry, you still have to wait {0} hours, {1} minutes, and {2} seconds."
                .format(2 - hours, 59 - minutes, 59 - seconds))

    @Plugin.command("inv", "[page:int]")
    @ensure_profile
    @limit_channel(*COMMAND_OUTLAWS, alternative_channel_id=REDIRECT_CHANNEL)
    def list_shibes(self, event, user, page: int=1):
        if not user.shibes:
            event.msg.reply("You don't have any shibes. Type !catch to find one.")
        else:
            if page < 1:
                return event.msg.reply("Sorry, you'll need to choose a positive number")
            selected = user.shibes[20 * (page - 1):page * 20]
            if not selected:
                return event.msg.reply("Sorry, but that page doesn't exist")

            embed = MessageEmbed()
            embed.title = event.msg.author.username + "'s shibes"
            embed.description = "\n".join(map(lambda x: "{0}): {1} x {2}"
                                              .format(user.shibes.index(x) + 1, x[0], x[1]), selected))
            embed.color = 0x0ddb93
            embed.set_footer(text="Nice shibes! page {0}/{1}".format(page, (len(user.shibes) // 20) + 1))
            event.msg.reply(embed=embed)
            self.logger.info("User {0} is counting his shibe".format(user.user_id))

    @Plugin.command("trade", "<other_user:str> <shibe_index:int>")
    @ensure_profile
    @ensure_index
    @ensure_other
    def trade_shibe(self, event, user, shibe, other_user, shibe_index: int):
        if other_user.user.id == user.user_id:
            return event.msg.reply("You can't trade with yourself, that's silly. Don't do silly things.")
        other_profile = self.db.find_user(other_user.user.id)
        other_profile.add_shibe(shibe[0])
        user.remove_shibe(shibe_index - 1)
        self.logger.info("Finished trade for {0}: {1} -> {2}"
                         .format(shibe[0], event.msg.author.username, other_user.user.username))
        event.msg.reply("Done! Enjoy your shibes!")

    @Plugin.command("release", "<shibe_index:int>")
    @ensure_profile
    @ensure_index
    def release_shibe(self, event, user, shibe, shibe_index: int):
        user.remove_shibe(shibe_index - 1)
        event.msg.reply("Now there's one more {0} in the wild".format(shibe[0]))
        self.logger.info("User {0} released their {1}".format(user.user_id, shibe[0]))

    @Plugin.command("reload catch")
    @admin_only
    def reload_shibes(self, event):
        client = event.msg.client
        shibe_channel = client.api.channels_get(SHIBE_CHANNEL)
        self.shibes = {}
        for msg in shibe_channel.messages:
            split_msg = msg.content.split(' ')
            url, name = split_msg[0], ' '.join(split_msg[1:])
            self.shibes[name] = url
        self.logger.info("Finished reloading {0} shibes".format(len(self.shibes.keys())))
        event.msg.reply("Finished reloading shibes. {0} catchable shibes.".format(len(self.shibes.keys())))
Exemple #5
0
class PowerupPlug(Plugin):
    def load(self, config):
        self.db = Database("PowerupPlug")
        self.logger = getLogger("PowerupPlug")
        super().load(config)
        self.logger.info("Finished loading PowerupPlug")

    @Plugin.command("powerups")
    def show_powerup_shop(self, event):
        embed = MessageEmbed()
        embed.title = "Powerup Shop"
        embed.description = "\n\n".join(
            map(
                lambda x: "{3}) **{0}** | *{1} bepis*\n***{2}***".format(
                    x[1][1], x[1][2], x[1][3], x[0]),
                enumerate(POWERUP_FRAMES)))
        embed.color = 0xFDB813
        embed.set_footer(
            text=
            "Don't forget, Battle Hardended Shibes doesn't need to be activated, and Sneaky Trap "
            "requires a mention for it's target when activating.")
        event.msg.reply(
            "If you buy something, use !activate <ID> when you're ready to use it.",
            embed=embed)

    @Plugin.command("buy powerup", "<power_index:int>")
    @ensure_profile
    def buy_powerup(self, event, user, power_index: int):
        real_index = power_index - 1
        if real_index < 0 or real_index > len(POWERUP_FRAMES) - 1:
            return event.msg.reply("Sorry, but that powerup does not exist")
        power = POWERUP_FRAMES[real_index]
        if user.bepis < power[2]:
            return event.msg.reply(
                "Sorry, but you don't have enough bepis to buy that.")
        user.bepis -= power[2]
        user.add_powerup(power[0], power[1])

    @Plugin.command("activate", "<power_index:int> [other_user:str]")
    @ensure_profile
    @ensure_other
    def start_powerup(self, event, user, power_index: int, other_user=None):
        real_index = power_index - 1
        if real_index < 0 or real_index > len(user.powerups) - 1:
            return event.msg.reply("Sorry, but you don't have that powerup.")
        power = user.powerups.pop(real_index)
        if power[1] is not None:
            return event.msg.reply("Sorry, but this powerup is already active")
        if power[0] == "Dazzling Shibe":
            power[1] = 5
        elif power[0] == "Sneaky Trap":
            if not other_user:
                return event.msg.reply(
                    "You must mention the target person, that you're trapping."
                )
            db_other = self.db.find_user(other_user.id)
            db_other.add_powerup(("TRAPPED", db_other.user_id))
            power[1] = True
        user.powerups.insert(real_index, power)
        self.db.profiles.update_one({"user_id": user.user_id},
                                    {"$set": {
                                        "powerups": user.powerups
                                    }})

    @Plugin.command("abilities")
    @ensure_profile
    def show_powerups(self, event, user):
        parsed_powers = []
        for power in user.powerups:
            if type(power[1]) is datetime:
                if datetime.now() - power[1] < timedelta(days=1):
                    diff = datetime.now() - power[1]
                    h, m, s = map(int, str(diff).split(':'))
                    parsed_powers.append(
                        "{0}, Active, {1}h {2}m and {3}s left.".format(
                            power[0], h, m, s))
            elif type(power[1]) is int:
                pass  # WIP
            parsed_powers.append()
Exemple #6
0
class AdminPlug(Plugin):
    def load(self, config):
        self.db = Database("AdminPlug")
        self.code_db = CodeDatabase()
        self.logger = getLogger("AdminPlug")
        self.shibes = {}
        super().load(config)
        self.logger.info("Finished loading AdminPlug")

    @Plugin.listen("Ready")
    def on_ready(self, event):
        client = event.guilds[0].client
        for channel_id in (SHIBE_CHANNEL, UNCATCHABLE_CHANNEL):
            shibe_channel = client.api.channels_get(channel_id)
            for msg in shibe_channel.messages:
                split_msg = msg.content.split(' ')
                url, name = split_msg[0], ' '.join(split_msg[1:])
                self.shibes[name] = url
        self.logger.info("Finished loading {0} shibes".format(
            len(self.shibes.keys())))

    @Plugin.command("set shibe",
                    "<other_user:str> <amount:int> <shibe_name:str...>")
    @ensure_other
    @admin_only
    def set_shibe(self, event, other_user, shibe_name, amount):
        if shibe_name not in self.shibes:
            return event.msg.reply(
                "Sorry, but that shibe doesn't exist (caps sensitive)")
        other_user_db = self.db.find_user(other_user.user.id)
        other_user_db.add_shibe(shibe_name, amount)
        event.msg.reply("Set {0}'s {1} count to {2}".format(
            other_user.user.mention, shibe_name, amount))
        self.logger.info("Set {0}'s {1} count to {2}".format(
            other_user.user.id, shibe_name, amount))

    @Plugin.command("set bepis", "<other_user:str> <amount:int>")
    @ensure_other
    @admin_only
    def set_bepis(self, event, other_user, amount: int):
        other_user_db = self.db.find_user(other_user.user.id)
        other_user_db.bepis = amount
        event.msg.reply("Set {0}'s bepis to {1}".format(
            other_user.user.mention, amount))
        self.logger.info("Set {0}'s bepis to {1}".format(
            other_user.user.id, amount))

    @Plugin.command("gencode", "<shibe_name:str...>")
    @admin_only
    def create_code(self, event, shibe_name: str):
        if shibe_name not in self.shibes:
            return event.msg.reply("Cannot find shibe: " + shibe_name)
        code = self.code_db.create_code(shibe_name)
        event.msg.reply("Done! The code is " + code)

    @Plugin.command("redeem", "<code:str>")
    @ensure_profile
    def redeem_code(self, event, user, code: str):
        found = self.code_db.activate_code(code)
        if found:
            user.add_shibe(found)
            resp = requests.get(self.shibes[found])
            file = BytesIO(resp.content)
            file.seek(0)
            event.msg.reply("That code was worth a **{}**".format(found),
                            attachments=[(found + ".png", file)])
        else:
            event.msg.reply("Sorry, but that code is invalid.")

    @Plugin.command("eval", "<code:str...>")
    @ensure_profile
    def eval_code(self, event, user, code: str):
        if event.msg.author.id == BOT_OWNER:
            try:
                client = event.command.plugin.client
                returns = str(
                    eval(
                        code, {
                            "event": event,
                            "self": self,
                            "user": user,
                            'client': client
                        }))
                if len(returns) > 1994:
                    while len(returns) > 1994:
                        to_send = '```' + returns[1994:] + '```'
                        returns = returns[1994:]
                        event.msg.reply(to_send)
                    event.msg.reply('```' + returns + '```')
                else:
                    event.msg.reply('```' + returns + '```')
            except Exception as e:
                returns = '```' + '\n'.join(format_exception_only(type(e),
                                                                  e)) + '```'
                event.msg.reply(returns)
        else:
            event.msg.reply("Did you really think I'd let you do that?")

    @Plugin.command("reload admin")
    def reload_admin(self, event):
        client = event.command.plugin.client
        for channel_id in (SHIBE_CHANNEL, UNCATCHABLE_CHANNEL):
            shibe_channel = client.api.channels_get(channel_id)
            for msg in shibe_channel.messages:
                split_msg = msg.content.split(' ')
                url, name = split_msg[0], ' '.join(split_msg[1:])
                self.shibes[name] = url
        self.logger.info("Finished loading {0} shibes".format(
            len(self.shibes.keys())))
        event.msg.reply(
            "Finished reloading shibes. {0} shibes in total.".format(
                len(self.shibes.keys())))

    # I'm sure you're probobly wondering
    # why the show command is in the admin plugin
    # and that's a great question.
    # So, due to the design of how loading shibes works
    # each plug has it's own copy of shibes
    # the admin plug however, also loads the uncatchable shibes, while shibe_update doesn't.
    # This means that if the show command was where it was supposed to be, it couldn't show uncatchable shibes.
    # As I'm writing this, I've also just realized that I need to load uncatchables for the battle plug.

    @Plugin.command("show", "<shibe_index:int>")
    @ensure_profile
    @ensure_index
    def show_shibe(self, event, user, shibe, shibe_index: int):
        for name, url in self.shibes.items():
            if name == shibe[0]:
                break
        resp = requests.get(url)
        file = BytesIO(resp.content)
        file.seek(0)
        event.msg.reply("Here's your **{0}**".format(shibe[0]),
                        attachments=[(shibe[0] + ".png", file)])
        self.logger.info("User {0} is bragging about his {1}".format(
            user.user_id, shibe[0]))

    @Plugin.listen("GuildMemberAdd")
    def on_join(self, member):
        if (datetime.now() - datetime.utcfromtimestamp(
            ((int(member.user.id) >> 22) + 1420070400000) / 1000)).days < 2:
            member.ban()
Exemple #7
0
class AdminPlug(Plugin):
    def load(self, config):
        self.db = Database("AdminPlug")
        self.code_db = CodeDatabase()
        self.logger = getLogger("AdminPlug")
        self.shibes = {}
        super().load(config)
        self.logger.info("Finished loading AdminPlug")

    @Plugin.listen("Ready")
    def on_ready(self, event):
        client = event.guilds[0].client
        shibe_channel = client.api.channels_get(SHIBE_CHANNEL)
        for msg in shibe_channel.messages:
            split_msg = msg.content.split(' ')
            url, name = split_msg[0], ' '.join(split_msg[1:])
            self.shibes[name] = url
        self.logger.info("Finished loading {0} shibes".format(
            len(self.shibes.keys())))

    @Plugin.command("set shibe",
                    "<other_user:str> <amount:int> <shibe_name:str...>")
    @ensure_other
    @admin_only
    def set_shibe(self, event, other_user, shibe_name, amount):
        if shibe_name not in self.shibes:
            return event.msg.reply(
                "Sorry, but that shibe doesn't exist (caps sensitive)")
        other_user_db = self.db.find_user(other_user.user.id)
        other_user_db.add_shibe(shibe_name, amount)
        event.msg.reply("Set {0}'s {1} count to {2}".format(
            other_user.user.mention, shibe_name, amount))
        self.logger.info("Set {0}'s {1} count to {2}".format(
            other_user.user.id, shibe_name, amount))

    @Plugin.command("set bepis", "<other_user:str> <amount:int>")
    @ensure_other
    @admin_only
    def set_bepis(self, event, other_user, amount: int):
        other_user_db = self.db.find_user(other_user.user.id)
        other_user_db.bepis = amount
        event.msg.reply("Set {0}'s bepis to {1}".format(
            other_user.user.mention, amount))
        self.logger.info("Set {0}'s bepis to {1}".format(
            other_user.user.id, amount))

    @Plugin.command("gencode", "<shibe_name:str...>")
    @admin_only
    def create_code(self, event, shibe_name: str):
        if shibe_name not in self.shibes:
            return event.msg.reply("Cannot find shibe: " + shibe_name)
        code = self.code_db.create_code(shibe_name)
        event.msg.reply("Done! The code is " + code)

    @Plugin.command("redeem", "<code:str>")
    @ensure_profile
    def redeem_code(self, event, user, code: str):
        found = self.code_db.activate_code(code)
        if found:
            user.add_shibe(found)
            resp = requests.get(self.shibes[found])
            file = BytesIO(resp.content)
            file.seek(0)
            event.msg.reply("That code was worth a **{}**".format(found),
                            attachments=[(found + ".png", file)])
        else:
            event.msg.reply("Sorry, but that code is invalid.")
Exemple #8
0
class ShopPlug(Plugin):
    def load(self, config):
        self.db = Database("ShopPlug")
        self.lottery = LotteryDatabase()
        self.logger = getLogger("ShopPlug")
        self.shibes = {}
        super().load(config)

        self.logger.info("Finished loading ShopPlug")

    def start_lottery(self, client, delay=0):
        gevent.sleep(delay)
        tickets = []
        users = self.lottery.get_users()
        current_lottery = self.lottery.get_event()
        if current_lottery:
            for user in users:
                for _ in range(user['amount']):
                    tickets.append(user["user_id"])
            if not tickets:
                client.api.channels_messages_create(
                    LOTTERY_CHANNEL,
                    "No one bought tickets, so we have no winners.")
            winner = choice(tickets)
            client.api.channels_messages_create(
                LOTTERY_CHANNEL,
                "<@&{2}> And the winner is... <@{0}>! Contrats, {1} "
                "bepis has been added to your account.".format(
                    winner, current_lottery["value"], LOTTERY_ROLE))
            bepis_user = self.db.find_user(winner)
            bepis_user.bepis += current_lottery["value"]
            guild = client.api.guilds_get(SHIBE_GUILD)
            for member in guild.members.values():
                if LOTTERY_ROLE in member.roles:
                    member.remove_role(LOTTERY_ROLE)

        next_value = randint(100, 200)
        self.lottery.start_lottery(next_value)
        new_lottery = self.lottery.get_event()
        client.api.channels_messages_create(
            LOTTERY_CHANNEL,
            "A new lottery has started! Buy tickets with !ticket to "
            "win the ***{0}*** bepis prize! Ends in 12 hours.".format(
                new_lottery['value']))
        gevent.spawn_later(new_lottery['length'], self.start_lottery, client)

    @Plugin.listen("Ready")
    def on_ready(self, event):
        client = event.guilds[0].client
        shibe_channel = client.api.channels_get(SHIBE_CHANNEL)
        self.shibes = {}
        for msg in shibe_channel.messages:
            split_msg = msg.content.split(' ')
            _, name = split_msg[0], ' '.join(split_msg[1:])
            if "⭐" in name:
                value = 1000
            elif "🌟" in name:
                value = 10000
            elif "💫" in name:
                continue
            else:
                value = 20
            self.shibes[name] = value
        self.shibes = sorted(self.shibes.items(), key=lambda x: x[1])
        self.shibes.reverse()
        self.logger.info("Finished loading {0} shibes".format(len(
            self.shibes)))

        current_lottery = self.lottery.get_event()
        if current_lottery:
            delay = datetime.now() - timedelta(
                seconds=current_lottery['length'])
            if delay >= current_lottery['start_time']:
                self.start_lottery(client)
            else:
                wait = current_lottery['start_time'] - delay
                self.start_lottery(client, wait.seconds)
        else:
            self.start_lottery(client)

    @Plugin.command("bepis", "[other_user:str]")
    @ensure_profile
    @ensure_other
    def get_bepis(self, event, user, other_user=None):
        if other_user:
            other_db = self.db.find_user(other_user.user.id)
            event.msg.reply("{1} has **{0}** bepis".format(
                other_db.bepis, other_user.user.username))
        else:
            event.msg.reply("You have **{0}** bepis".format(user.bepis))
        self.logger.info("User {0} is making it rain".format(user.user_id))

    @Plugin.command("sell", "<shibe_index:int>")
    @ensure_profile
    @ensure_index
    def sell_shibe(self, event, user, shibe, shibe_index: int):
        if "⭐" in shibe[0]:
            user.bepis += 1000
        elif "🌟" in shibe[0]:
            user.bepis += 10000
        elif "💫" in shibe[0]:
            user.bepis += 1000000
        else:
            user.bepis += 10
        event.msg.reply("Thanks for the {0}, you now have {1} bepis".format(
            shibe[0], user.bepis))
        index = user.shibes.index(shibe)
        user.remove_shibe(index)

    @Plugin.command("shop", "[page:int]")
    def show_shop(self, event, page: int = 1):
        if page not in range(1, (len(self.shibes) // 20) + 2):
            return event.msg.reply(
                "Invalid page number, choose a page from 1 to {0}".format(
                    (len(self.shibes) // 20) + 1))

        embed = MessageEmbed()
        embed.title = "The Shibe Shop!"
        embed.description = "\n".join(
            map(
                lambda x: "{0}): Selling {1} for {2}".format(
                    x[0] + ((page - 1) * 20) + 1, x[1][0], x[1][1]),
                enumerate(self.shibes[20 * (page - 1):page * 20])))
        embed.color = 0xFFFDD0
        embed.set_footer(
            text="Like what you see? Buy something! page {0}/{1}".format(
                page, (len(self.shibes) // 20) + 1))
        event.msg.reply(embed=embed)

    @Plugin.command("buy shibe", "<shop_index:int>")
    @ensure_profile
    def buy_shop(self, event, user, shop_index: int):
        try:
            buy_shibe = self.shibes[shop_index - 1]
        except IndexError:
            return event.msg.reply(
                "Invalid shop index, check !shop again to see if you typed it right."
            )
        if user.bepis < buy_shibe[1]:
            return event.msg.reply(
                "Sorry, but you need {0} more bepis".format(buy_shibe[1] -
                                                            user.bepis))
        user.bepis -= buy_shibe[1]
        user.add_shibe(buy_shibe[0])
        event.msg.reply("Thanks for shopping! here's your **{0}**".format(
            buy_shibe[0]))
        self.logger.info("User {0} bought a {1}".format(
            user.user_id, buy_shibe[0]))

    @Plugin.command("donate", "<other_user:str>, <amount:int>")
    @ensure_profile
    @ensure_other
    def donate_bepis(self, event, user, other_user, amount: int):
        if user.bepis < amount:
            return event.msg.reply(
                "You don't have enough bepis to donate that amount")
        elif amount < 1:
            return event.msg.reply("You can't just *give* them no money!")
        elif user.user_id == other_user.user.id:
            return event.msg.reply("No.")
        db_user = self.db.find_user(other_user.user.id)
        user.bepis -= amount
        db_user.bepis += amount
        event.msg.reply("Done! {0} make sure to say 'Thank you'.".format(
            other_user.user.mention))

    @Plugin.command("flip", "<amount:int>")
    @ensure_profile
    def flip_bepis(self, event, user, amount: int):
        if user.bepis < amount:
            return event.msg.reply(
                "You don't have enough bepis to bet that amount")
        elif amount < 1:
            return event.msg.reply("What? You can't bet nothing!")

        if randint(0, 1):
            user.bepis += amount
            event.msg.reply("Contratz! You won! You now have {0} bepis".format(
                user.bepis))
        else:
            user.bepis -= amount
            event.msg.reply("Oh no, you lost... You now have {0} bepis".format(
                user.bepis))

    @Plugin.command("ticket", "<amount:int>")
    @ensure_profile
    def buy_tickets(self, event, user, amount: int):
        current_lottery = self.lottery.get_event()
        if user.bepis < (amount * current_lottery["price"]):
            return event.msg.reply(
                "Sorry, but you don't have enough bepis for that.")
        elif amount <= 0:
            return event.msg.reply(
                "Why are you doing that, that's stupid. Don't be stupid.")
        self.lottery.add_tickets(user.user_id, amount)
        member = event.msg.guild.get_member(user.user_id)
        if LOTTERY_ROLE not in member.roles:
            member.add_role(LOTTERY_ROLE)
        user.bepis -= (amount * current_lottery['price'])
        event.msg.reply(
            "Alright! Added {0} more tickets into your account.".format(
                amount))

    @Plugin.command("reload shop")
    @admin_only
    def reload_shop(self, event):
        client = event.msg.client
        shibe_channel = client.api.channels_get(SHIBE_CHANNEL)
        self.shibes = {}
        for msg in shibe_channel.messages:
            split_msg = msg.content.split(' ')
            _, name = split_msg[0], ' '.join(split_msg[1:])
            if "⭐" in name:
                value = 1000
            elif "🌟" in name:
                value = 10000
            elif "💫" in name:
                continue
            else:
                value = 20
            self.shibes[name] = value
        self.shibes = sorted(self.shibes.items(), key=lambda x: x[1])
        self.shibes.reverse()
        self.logger.info("Finished loading {0} shibes".format(len(
            self.shibes)))
        event.msg.reply(
            "Finished reloading shibes. {0} catchable shibes.".format(
                len(self.shibes)))