コード例 #1
0
ファイル: bot_information.py プロジェクト: scvdss/Lisency
 async def on_message(self, message):
     # If bot is mentioned in message (both in guild and DM) show it's prefix
     if message.mentions and not message.author.bot and self.bot.user in message.mentions:
         if message.guild is None:
             prefix = self.bot.config["default_prefix"]
             msg = f"My prefix here is **{prefix}**"
             await message.channel.send(embed=info(msg, None))
         else:
             prefix = await self.bot.main_db.get_guild_prefix(
                 message.guild.id)
             msg = f"My prefix in this guild is **{prefix}**"
             await message.channel.send(embed=info(msg, message.guild.me))
コード例 #2
0
    async def ping(self, ctx):
        """
        Show bot ping.

        First value is REST API latency.
        Second value is Discord Gateway latency.
        """
        before = time.monotonic()
        message = await ctx.send(embed=info("Pong", ctx.me))
        ping = (time.monotonic() - before) * 1000
        content = (f":ping_pong:   |   {int(ping)}ms\n"
                   f":timer:   |   {self.bot.latency * 1000:.0f}ms")
        await message.edit(embed=info(content, ctx.me, title="Results:"))
コード例 #3
0
ファイル: help.py プロジェクト: albertopoljak/Licensy
 async def faq(self, ctx):
     """Show common Q/A about bot and its usage."""
     bot_faq = (
         f"You can find it on [Github.]({self.github_faq})\n\n"
         "Please let me know which features/improvements you want so I can focus on those.\n"
         f"Type `{ctx.prefix}support` for invite to support server."
     )
     await ctx.send(embed=info(bot_faq, ctx.me, title="FAQ"))
コード例 #4
0
ファイル: bot_information.py プロジェクト: scvdss/Lisency
    async def invite(self, ctx):
        """
        Shows bot invite link.

        """
        invite_link = self._get_bot_invite_link()
        description = f"Use this **[invite link]({invite_link})** to invite me."
        await ctx.send(embed=info(description, ctx.me, title="Invite me :)"))
コード例 #5
0
ファイル: bot_information.py プロジェクト: scvdss/Lisency
    async def support_server(self, ctx):
        """
        Shows invite to the support server.

        """
        description = (
            f"Join **[support server]({self.bot.config['support_channel_invite']})** "
            f"for questions, suggestions and support.")
        await ctx.send(embed=info(description, ctx.me, title="Ask away!"))
コード例 #6
0
ファイル: games.py プロジェクト: scvdss/Lisency
    async def giveaway(self, ctx, duration_minutes: positive_integer,
                       channel: discord.TextChannel):
        if duration_minutes > 1440:
            await ctx.send(embed=failure("Maximum duration is 24h!"),
                           delete_after=5)
            return

        description = "React to this message to enter the giveaway and a chance to win license!"
        event_title = "Giveaway!"
        emoji = "🎉"
        message = await channel.send(
            embed=info(description, ctx.me, title=event_title))
        await message.add_reaction(emoji)

        await asyncio.sleep(duration_minutes * 60)

        try:
            done_message = await channel.fetch_message(message.id)
        except NotFound:
            logger.info(
                f"Event message deleted! Event canceled! Guild:{ctx.guild.id} {ctx.guild.name}, "
                f"channel: {channel.id} {channel.name}")
            return

        for reaction in done_message.reactions:
            if str(reaction.emoji) == emoji:
                choices = []
                async for user in reaction.users():
                    if not user.bot:
                        choices.append(user)
                if choices:
                    winner = random.choice(choices)
                    edit_description = f"Giveaway has finished,\n{winner.mention} has won the raffle!"
                    await message.edit(
                        embed=info(edit_description, ctx.me, title=event_title)
                    )
                    await channel.send(f"{winner.mention} has won the raffle.",
                                       delete_after=10)
                else:
                    edit_description = "Giveaway has finished, no one reacted :("
                    await message.edit(
                        embed=info(edit_description, ctx.me, title=event_title)
                    )
            break
コード例 #7
0
    async def role_hierarchy(self, ctx):
        """Shows role hierarchy in guild and highlights top role which bot can currently manage."""
        roles = []
        for role in reversed(ctx.guild.roles):
            if role == ctx.me.top_role:
                roles.append(f"{role.name} : {role.id} (mine top role)")
            else:
                roles.append(f"{role.name} : {role.id}")

        await ctx.send(embed=info("\n".join(roles), None))
コード例 #8
0
    async def member_data(self, ctx, member: discord.Member = None):
        """
        Shows active subscriptions of member.
        Sends result in DMs

        """

        if member is None:
            member = ctx.author
        else:
            # If called member is the same as author allow him to see since it's himself
            if ctx.author == member:
                pass
            # We require admin permissions if you want to see other members data
            elif not ctx.author.guild_permissions.administrator:
                await ctx.send(embed=failure(
                    "You need administrator permission to see other members data."
                ))
                return

        table = texttable.Texttable(max_width=90)
        table.set_cols_dtype(["t", "t"])
        table.set_cols_align(["c", "c"])
        header = ("Licensed role", "Expiration date")
        table.add_row(header)

        all_active = await self.bot.main_db.get_member_data(
            ctx.guild.id, member.id)
        if not all_active:
            await ctx.send(
                embed=failure(f"Nothing to show for {member.mention}."))
            return

        for entry in all_active:
            # Entry is in form ("license_id", "expiration_date)
            try:
                role = ctx.guild.get_role(int(entry[0]))
                table.add_row((role.name, entry[1]))
            except (ValueError, AttributeError):
                # Just in case if error in case role is None (deleted from guild) just show IDs from database
                table.add_row(entry)

        local_time = get_current_time()
        title = (
            f"Server local time: {local_time}\n\n"
            f"{member.name} active subscriptions in guild '{ctx.guild.name}':\n\n"
        )

        await ctx.send(embed=info("Sent in Dms!", ctx.me), delete_after=5)
        await Paginator.paginate(self.bot,
                                 ctx.author,
                                 ctx.author,
                                 table.draw(),
                                 title=title,
                                 prefix="```DNS\n")
コード例 #9
0
ファイル: help.py プロジェクト: albertopoljak/Licensy
 async def quickstart(self, ctx):
     """Shortly explains first time bot usage."""
     description = f"See Github [quickstart link]({self.github_bot_quick_start})."
     await ctx.send(embed=info(description, ctx.me, title="Quickstart :)"))
コード例 #10
0
    async def activate_license(self, ctx, license, guild_id: int, role_id: int,
                               member):
        """
        :param ctx: invoked context
        :param guild_id: guild id tied to license
        :param role_id: role id tied to license
        :param license: license to add
        :param member: who to give role to. Union[User, Member] depending if called in guild or Dm
        """
        guild = self.bot.get_guild(guild_id)
        if guild is None:
            await ctx.send(embed=failure(
                "Guild tied to that license not found in bot guilds."))
            return

        if ctx.guild is not None and ctx.guild.id != guild_id:
            await ctx.send(embed=failure(
                f"That license is not for this guild! "
                f"Either redeem it in correct guild '{guild.name}' or redeem in bot DM."
            ))
            return

        # Decorator won't work in DM so have to manually check
        if not guild.me.guild_permissions.manage_roles:
            await ctx.send(embed=failure(
                f"Guild '{guild.name}' , can't assign roles - no manage roles permission."
            ))
            if ctx.guild is not None:
                # delete message but only if in guild, can't delete dm messages
                await ctx.message.delete()
            return

        # Passed member can be a user if redeem was activated in dm, so get the member
        if ctx.guild is None:
            member = guild.get_member(member.id)
            if member is None:
                await ctx.send(embed=failure(
                    "You are no longer it the guild you're trying to activate license!"
                ))
                return

        if await self.bot.main_db.is_valid_license(license, guild.id):
            # Adding role to the member requires that role object
            # First we get the role linked to the license
            role = guild.get_role(role_id)
            if role is None:
                log_error_msg = (
                    f"Can't find role {role_id} in guild {guild.id} '{guild.name}' "
                    f"from license: '{license}' member to give the role to: {member.id} '{member.name}'"
                    "\n\nProceeding to delete this invalid license from database!"
                )
                logger.critical(log_error_msg)

                msg = (
                    "Well this is awkward...\n\n"
                    "The role that was supposed to be given out by this license has been deleted from this guild!"
                    f"\n\nError message:\n\n{log_error_msg}")
                await ctx.send(embed=failure(msg))
                await self.bot.main_db.delete_license(license)
                return
            # Now before doing anything check if member already has the role
            # Beside for logic (why redeem already existing subscription?) if we don't check this we will get
            # sqlite3.IntegrityError:
            #   UNIQUE constraint failed:LICENSED_MEMBERS.MEMBER_ID,LICENSED_MEMBERS.LICENSED_ROLE_ID
            # when adding new licensed member to table LICENSED_MEMBERS if member already has the role (because in that
            # table the member id and role id is unique aka can only have uniques roles tied to member id)
            if role in member.roles:
                # We notify user that he already has the role, we also show him the expiration date
                try:
                    expiration_date = await self.bot.main_db.get_member_license_expiration_date(
                        member.id, role_id)
                except DatabaseMissingData as e:
                    # TODO print role name instead of ID (from e)
                    msg = e.message
                    msg += (
                        f"\nThe bot did not register {member.mention} in the database with that role but somehow they have it."
                        "\nThis probably means that they were manually assigned this role without using the bot license system."
                        "\nHave someone remove the role from them and call this command again."
                    )
                    await ctx.send(embed=failure(msg))
                    if ctx.guild is not None:
                        # delete message but only if in guild, can't delete dm messages
                        await ctx.message.delete()
                    return

                remaining_time = get_remaining_time(expiration_date)
                msg = (
                    f"{member.mention} already has an active subscription for the '{role.name}' role!"
                    f"\nIt's valid for another {remaining_time}")
                await ctx.send(embed=warning(msg))
                if ctx.guild is not None:
                    # delete message but only if in guild, can't delete dm messages
                    await ctx.message.delete()
                return
            # We add the role to the member, we do this before adding/removing stuff from db
            # just in case the bot doesn't have perms and throws exception (we already
            # checked for bot_has_permissions(manage_roles=True) but it can happen that bot has
            # that permission and check is passed but it's still forbidden to alter role for the
            # member because of it's role hierarchy.) -> will raise Forbidden and be caught by cmd error handler
            await member.add_roles(role, reason="Redeemed license.")
            # We add entry to db table LICENSED_MEMBERS (which we will checked periodically for expiration)
            # First we get the license duration so we can calculate expiration date
            license_duration = await self.bot.main_db.get_license_duration_hours(
                license)
            expiration_date = construct_expiration_date(license_duration)
            # In case where you successfully redeemed the role and it's still in database(not expired)
            # BUT someone manually removed the role, in that case when you try to redeem a valid license
            # for the said role you will get IntegrityError because LICENSED_ROLE_ID and MEMBER_ID have to
            # be unique (and the entry still exists in database).
            # Even when caught by remove role event leave this
            try:
                await self.bot.main_db.add_new_licensed_member(
                    member.id, guild.id, expiration_date, role_id)
            except IntegrityError:
                # We remove the database entry because when role was remove the bot was
                # probably offline and couldn't register the role remove event
                await self.bot.main_db.delete_licensed_member(
                    member.id, role_id)
                await self.bot.main_db.add_new_licensed_member(
                    member.id, guild.id, expiration_date, role_id)
                msg = (
                    f"Someone removed the role manually from {member.mention} but no worries,\n"
                    "since the license is valid we're just gonna reactivate it :)"
                )
                await ctx.send(embed=info(msg, ctx.me))

            # Remove guild license from database, so it can't be redeemed again
            await self.bot.main_db.delete_license(license)
            # Send message notifying user
            msg = f"License valid - guild '{guild.name}' adding role '{role.name}' to {member.mention} in duration of {license_duration}h"
            await ctx.send(embed=success(msg, ctx.me))
        else:
            await ctx.send(embed=failure(
                "The license key you entered is invalid/deactivated."))
コード例 #11
0
ファイル: bot_information.py プロジェクト: scvdss/Lisency
 async def donate(self, ctx):
     """
     Support development!
     """
     await ctx.send(
         embed=info(self.patreon_link, ctx.me, title="Thank you :)"))
コード例 #12
0
ファイル: bot_information.py プロジェクト: scvdss/Lisency
 async def uptime(self, ctx):
     """
     Time since boot.
     """
     await ctx.send(embed=info(self.last_boot(), ctx.me, title="Booted:"))
コード例 #13
0
ファイル: bot_information.py プロジェクト: scvdss/Lisency
 async def source(self, ctx):
     """
     Link to source code on Github.
     """
     await ctx.send(
         embed=info(self.github_source, ctx.me, title="Source code"))
コード例 #14
0
ファイル: bot_information.py プロジェクト: scvdss/Lisency
 async def vote(self, ctx):
     """
     Vote bot on top.gg (bot list).
     """
     await ctx.send(
         embed=info(self.top_gg_vote_link, ctx.me, title="Thank you."))