コード例 #1
0
    def __init__(self, client, lang, logger, db, cursor):
        self.client = client
        self.lang = lang
        self.logger = logger

        self.db = db
        self.cursor = cursor
        self.edit = EditLocale(db, cursor)
        self.util = Util(client, db, cursor)
コード例 #2
0
    def __init__(self, client, lang, logger, db, cursor):

        self.client = client
        self.lang = lang
        self.logger = logger

        self.db = db
        self.cursor = cursor

        self.io = IO(cfg, client, db, cursor)
        self.util = Util(client, db, cursor)
        self.list = EditList(db, cursor)
        self.mark = Mark(db, cursor)
コード例 #3
0
    def __init__(self, client, logger, db, cursor):
        self.client = client
        self.logger = logger
        self.db = db
        self.cursor = cursor

        self.util = Util(client, db, cursor)
コード例 #4
0
class User(commands.Cog):

    def __init__(self, client, lang, logger, db, cursor):

        self.client = client
        self.lang = lang
        self.logger = logger

        self.db = db
        self.cursor = cursor

        self.io = IO(cfg, client, db, cursor)
        self.util = Util(client, db, cursor)
        self.list = EditList(db, cursor)
        self.mark = Mark(db, cursor)

    @commands.command(hidden=False, description="[number] slots the author of the message in the slot")
    @commands.cooldown(1, 0.5, commands.BucketType.channel)
    @commands.guild_only()
    async def slot(self, ctx, num=""):
        channel = ctx.message.channel
        channel_author = self.util.get_channel_author(channel)

        game = (channel.name.split("-"))[-1]
        author = ctx.message.author
        backup = ctx.guild.get_member(cfg['backup'])

        if game in cfg["games"].keys() and not (
                cfg["games"][game]["role"] in [x.id for x in ctx.message.author.roles]):

            # Instructor-Message
            instructor = []
            for elem in cfg["games"][game]["instructor"]:
                buffer = ctx.guild.get_member(int(elem))
                if buffer:
                    instructor.append(buffer)
                    await buffer.send(
                        self.lang["slot"]["new_user"]["instructor"].format(author, author.display_name, channel.name,
                                                                           num))

            if not instructor:
                instructor.append(ctx.guild.get_member(cfg['backup']))
                await instructor[0].send(
                    self.lang["slot"]["new_user"]["instructor"].format(author, author.display_name, channel.name, num))

            # User-Message
            if "welcome-msg" in cfg['games'][game].keys() and cfg['games'][game]['welcome-msg'] != "":
                await author.send(
                    cfg['games'][game]['welcome-msg'].format(cfg["games"][game]["name"],
                                                             " oder ".join([x.display_name for x in instructor]),
                                                             cfg["games"][game]["name"]).replace('\\n', '\n'))
            # Assign-Rule
            await author.add_roles(ctx.guild.get_role(cfg["games"][game]["beginner-role"]))

            if "strict" in cfg["games"][game].keys() and cfg["games"][game]["strict"]:
                # Channel-Message
                await channel_author.send(
                    self.lang["slot"]["new_user"]["channel"].format(author, author.display_name, channel.name, num))

                await ctx.message.delete()
                return

        if num:
            if self.list.slotEvent(channel, author.id, num, user_displayname=author.display_name):
                await self.io.writeEvent(channel)

                await author.send(
                    self.lang["slot"]["slot"]["success"]["user"].format('/'.join(ctx.channel.name.split('-')[:-1])))
                try:
                    await channel_author.send(
                        self.lang["slot"]["slot"]["success"]["channel_author"].format(author,
                                                                                      ctx.message.author.display_name,
                                                                                      channel.name, num))
                    await backup.send(self.lang["slot"]["slot"]["success"]["channel_author"].format(author,
                                                                                                    ctx.message.author.display_name,
                                                                                                    channel.name, num))
                except:
                    pass

                log = "User: "******"\t"
                log += "Channel:" + str(ctx.message.channel).ljust(20) + "\t"
                log += "Command: " + str(ctx.message.content).ljust(20) + "\t"
                self.logger.debug(log)

            else:
                await channel.send(author.mention + " " + self.lang["slot"]["slot"]["error"]["general"]["channel"],
                                   delete_after=5)

        else:
            await channel.send(
                ctx.message.author.mention + " " + self.lang["slot"]["slot"]["error"]["number_missing"]["channel"],
                delete_after=5)

        await ctx.message.delete()

    @commands.command(hidden=False, description="unslot the author of the message")
    @commands.cooldown(1, 0.5, commands.BucketType.channel)
    @commands.guild_only()
    async def unslot(self, ctx):
        channel = ctx.message.channel

        channel_author = self.util.get_channel_author(channel)

        backup = ctx.guild.get_member(cfg['backup'])
        index = self.list.unslotEvent(channel, ctx.message.author.id)
        if index:
            await self.io.writeEvent(channel)
            await ctx.message.author.send(
                self.lang["unslot"]["success"]["user"].format('/'.join(ctx.channel.name.split('-')[:-1])))
            if str(datetime.date.today()) == "-".join(channel.name.split("-")[:-1]):
                try:
                    await channel_author.send(
                        self.lang["unslot"]["success"]["channel_author_date"].format(ctx.message.author,
                                                                                     ctx.message.author.display_name,
                                                                                     channel.name, index))
                    await backup.send(self.lang["unslot"]["success"]["channel_author"].format(ctx.message.author,
                                                                                              ctx.message.author.display_name,
                                                                                              channel.name, index))
                except:
                    pass
            else:

                try:
                    await channel_author.send(
                        self.lang["unslot"]["success"]["channel_author"].format(ctx.message.author,
                                                                                ctx.message.author.display_name,
                                                                                channel.name,
                                                                                index))
                    await backup.send(self.lang["unslot"]["success"]["channel_author"].format(ctx.message.author,
                                                                                              ctx.message.author.display_name,
                                                                                              channel.name, index))

                except:
                    pass

            log = "User: "******"\t"
            log += "Channel:" + str(ctx.message.channel).ljust(20) + "\t"
            log += "Command: " + str(ctx.message.content).ljust(20) + "\t"
            self.logger.debug(log)

            await ctx.message.delete()
        else:
            await channel.send(ctx.message.author.mention + " " + self.lang["unslot"]["error"]["general"]["channel"],
                               delete_after=5)
            await ctx.message.delete()

    @commands.command(hidden=False, description="[type] adds an mark to the user in the slotlist")
    @commands.cooldown(1, 0.5, commands.BucketType.channel)
    @commands.guild_only()
    async def mark(self, ctx):
        channel = ctx.message.channel
        user = ctx.message.author

        args = ctx.message.content.split(" ")[1:]
        if len(args) == 0:
            await channel.send(
                ctx.message.author.mention + " " + self.lang["mark"]["error"]["args"],
                delete_after=5)
            await ctx.message.delete()
            return

        emoji_name = " ".join(args)
        if emoji_name in cfg['marks'].keys():
            if self.mark.addMark(user.id, channel.id, emoji_name):
                await self.io.writeEvent(channel)
                await channel.send(
                    ctx.message.author.mention + " " + self.lang["mark"]["suc"],
                    delete_after=5)
            else:
                await channel.send(
                    ctx.message.author.mention + " " + self.lang["mark"]["error"]["duplicate"],
                    delete_after=5)
        else:
            await channel.send(
                ctx.message.author.mention + " " + self.lang["mark"]["error"]["typeNotFound"],
                delete_after=5)

        await ctx.message.delete()

    @commands.command(hidden=False, description="[type] adds an mark to the user in the slotlist")
    @commands.cooldown(1, 0.5, commands.BucketType.channel)
    @commands.guild_only()
    async def unmark(self, ctx):
        channel = ctx.message.channel
        user = ctx.message.author

        args = ctx.message.content.split(" ")[1:]
        if len(args) == 0:
            await channel.send(
                ctx.message.author.mention + " " + self.lang["unmark"]["error"]["args"],
                delete_after=5)
            await ctx.message.delete()
            return

        emoji_name = " ".join(args)
        if emoji_name in cfg['marks'].keys():
            if self.mark.removeMark(user.id, channel.id, emoji_name):
                await self.io.writeEvent(channel)
                await channel.send(
                    ctx.message.author.mention + " " + self.lang["unmark"]["suc"],
                    delete_after=5)
            else:
                await channel.send(
                    ctx.message.author.mention + " " + self.lang["unmark"]["error"]["duplicate"],
                    delete_after=5)
        else:
            await channel.send(
                ctx.message.author.mention + " " + self.lang["unmark"]["error"]["typeNotFound"],
                delete_after=5)

        await ctx.message.delete()

    @commands.command()
    async def help(self, ctx):
        output = "My commands are:\n```yaml\n"

        for element in self.client.commands:
            if element != help and not element.hidden:
                output += f"{element}:".ljust(20) + f"{element.description}\n"

        if cfg['role'] in [x.name for x in ctx.message.author.roles]:
            output += "\n#Admin Commands:\n"
            for element in self.client.commands:
                if element != help and element.hidden:
                    output += f"{element}:".ljust(20) + f"{element.description}\n"

        output += "```"

        await ctx.message.author.send(output)
        await ctx.message.delete()
コード例 #5
0
class Handler(commands.Cog):
    def __init__(self, client, lang, logger, db, cursor):
        self.client = client
        self.lang = lang
        self.logger = logger

        self.db = db
        self.cursor = cursor
        self.edit = EditLocale(db, cursor)
        self.util = Util(client, db, cursor)

    async def notify(self, event, user_id, delay):
        """
            Calculates datetime for notification
                Args:
                    event(string): ID of an event
                    user_id(string): User ID
                    delay(int): delay in sec.

        """

        await asyncio.sleep(delay)

        user = self.client.get_user(int(user_id))
        if user:
            sql = "SELECT Time FROM Notify WHERE Event = %s AND User = %s"
            self.cursor.execute(sql, [event, user_id])
            result = self.cursor.fetchall()

            if not result:
                return

            now = dt.datetime.now()
            delta = (result[0][0] - now).total_seconds()

            if abs(delta) > 1200:
                return

            sql = "SELECT Name, Time FROM Event WHERE ID = %s;"
            self.cursor.execute(sql, [event])
            result = self.cursor.fetchone()

            guild = self.client.get_guild(int(cfg['guild']))
            nickname = guild.get_member(int(user_id)).display_name
            try:
                await user.send(self.lang["notify_global"]["noti"].format(
                    nickname, str(result[0]), str(result[1])))
            except discord.errors.Forbidden:
                log = "User: "******"\t"
                log += "Channel:" + str(event).ljust(20) + "\t"
                log += "Command: " + "Notify: discord.errors.Forbidden".ljust(
                    20) + "\t"
                self.logger.log(log)

    @commands.Cog.listener()
    async def on_ready(self):
        sql = "SELECT n.User, n.Time, n.Event FROM Notify n, User u \
                WHERE n.User = u.ID AND u.Notify AND n.Enabled AND n.Time >= CURDATE();"

        self.cursor.execute(sql)
        result = self.cursor.fetchall()

        for elem in result:
            now = dt.datetime.now()
            delta = (elem[1] - now).total_seconds()
            if delta > 0:
                asyncio.create_task(self.notify(elem[2], elem[0], delta))

    @commands.Cog.listener()
    async def on_guild_channel_update(self, before, after):
        if before.name != after.name:
            if (event := self.edit.getEvent(after.id)) is not None:
                author = self.util.get_channel_author(after)

                try:
                    date = [int(x) for x in after.name.split("-")[:3]]
                    date = dt.date(*date)
                except ValueError:
                    await author.send(
                        self.lang["update"]["auto"]["date_error"].format(
                            after.name))
                    return

                self.edit.updateNotify(after.id,
                                       str(event[0]) + " " + str(event[1]),
                                       str(date) + " " + str(event[1]))
                if self.edit.updateEvent(after.id, after.name, date):
                    await author.send(
                        self.lang["update"]["auto"]["success"].format(
                            after.name))
                else:
                    await author.send(
                        self.lang["update"]["auto"]["error"].format(after.name)
                    )
                    return
コード例 #6
0
ファイル: io.py プロジェクト: marcopolo88/Registration-Bot
    def __init__(self, cfg, client, db, cursor):
        self.cfg = cfg
        self.db = db
        self.cursor = cursor

        self.util = Util(client, db, cursor)