Exemplo n.º 1
0
 async def remove_role_on_reaction(self, target, member, channel, guild):
     role = discord.utils.get(guild.roles, name=target)
     if role is not None:
         if role in member.roles:
             if acl.get_perms(member.id, member.top_role, role.id,
                              guild.roles):
                 await member.remove_roles(role)
             else:
                 bot_room = self.bot.get_channel(Config.bot_room)
                 await bot_room.send(
                     Messages.role_remove_denied.format(
                         user=utils.generate_mention(member.id),
                         role=role.name))
     else:
         try:
             channel = discord.utils.get(guild.channels, id=int(target))
         except ValueError:
             channel = None
         if channel is None:
             channel = discord.utils.get(guild.channels,
                                         name=target[1:].lower())
         if channel is None:
             return
         perms = acl.get_perms(member.id, member.top_role, channel.id,
                               guild.roles)
         if perms:
             await channel.set_permissions(member,
                                           read_messages=None,
                                           send_messages=None)
         else:
             bot_room = self.bot.get_channel(Config.bot_room)
             await bot_room.send(
                 Messages.role_remove_denied.format(
                     user=utils.generate_mention(member.id),
                     role=channel.name))
Exemplo n.º 2
0
 async def get_join_role_data(self, message):
     input_string = message.content
     input_string = input_string.replace(" - ", " ")
     input_string = input_string.replace(": ", " ")
     input_string = input_string.replace("**", "")
     output = []
     try:
         input_string = (input_string[input_string.index('\n') + 1:]
                         .rstrip().split('\n'))
     except ValueError:
         await message.channel.send(
             Messages.role_format
             .format(user=utils.generate_mention(
                 message.author.id)
             )
         )
         return output
     for line in input_string:
         try:
             emoji = next(filter(lamda x: x[0] in UNICODE_EMOJI or x[0] == '<', line.split()))
             line = [line[:line.index(emoji)], emoji]
             output.append(line)
         except:
             await message.channel.send(
                 Messages.role_invalid_line
                 .format(user=utils.generate_mention(
                     message.author.id),
                     line=line[0]
                 )
             )
     return output
Exemplo n.º 3
0
 async def get_join_role_data(self, message):
     input_string = message.content
     input_string = input_string.replace("**", "")
     try:
         if input_string.startswith(Config.role_string):
             input_string = input_string[input_string.index('\n') + 1:]
         input_string = input_string.rstrip().split('\n')
     except ValueError:
         await message.channel.send(
             Messages.role_format.format(
                 user=utils.generate_mention(message.author.id)))
         return None
     output = []
     for line in input_string:
         try:
             out = line.split(" - ", 1)[0].split()
             out = [out[1], out[0]]
             output.append(out)
         except:
             await message.channel.send(
                 Messages.role_invalid_line.format(
                     user=utils.generate_mention(message.author.id),
                     line=line))
     for line in output:
         if "<#" in line[0]:
             line[0] = line[0].replace("<#", "")
             line[0] = line[0].replace(">", "")
             try:
                 line[0] = int(line[0])
             except:
                 await message.channel.send(
                     Messages.role_invalid_line.format(
                         user=utils.generate_mention(message.author.id),
                         line=line[0]))
     return output
Exemplo n.º 4
0
 async def message_role_reactions(self, message, data):
     if message.channel.type is not discord.ChannelType.text:
         await message.channel.send(Messages.role_not_on_server)
         guild = self.bot.get_guild(Config.guild_id)
     else:
         guild = message.guild
     for line in data:
         not_role = discord.utils.get(guild.roles, name=line[0]) is None
         if isinstance(line[0], int) or line[0].isdigit():
             not_channel = discord.utils.get(guild.channels,
                                             id=int(line[0])) is None
         else:
             not_channel = line[0][0] != "#" or\
                 discord.utils.get(guild.channels,
                                   name=line[0][1:].lower()) is None
         if not_role and not_channel:
             await message.channel.send(
                 Messages.role_not_role.format(user=utils.generate_mention(
                     message.author.id),
                                               not_role=line[0]))
         else:
             try:
                 await message.add_reaction(line[1])
             except discord.errors.HTTPException:
                 await message.channel.send(
                     Messages.role_invalid_emote.format(
                         user=utils.generate_mention(message.author.id),
                         not_emote=line[1],
                         role=line[0]))
Exemplo n.º 5
0
 async def acl(self, ctx, *args):
     if self.mod is None:
         guild = self.bot.get_guild(config.guild_id)
         self.mod = discord.utils.get(guild.roles, name="Mod")
     if self.mod in ctx.author.roles:
         if not len(args):
             await ctx.send(
                 messages.acl_help.format(
                     user=utils.generate_mention(ctx.author.id)))
             return
         if args[0] == 'add':
             await acl.handle_add(ctx, args[1:])
         elif args[0] == 'del':
             await acl.handle_del(ctx, args[1:])
         elif args[0] == 'edit':
             await acl.handle_edit(ctx, args[1:])
         elif args[0] == 'list':
             await acl.handle_list(ctx, args[1:])
         else:
             await ctx.send(
                 messages.acl_help.format(
                     user=utils.generate_mention(ctx.author.id)))
             return
     else:
         await ctx.send(
             messages.missing_perms.format(
                 user=utils.generate_mention(ctx.author.id)))
         return
Exemplo n.º 6
0
async def print_output(bot, channel, system, parsed_memory, parsed_semaphores,
                       parsed_files, parsed_processes):
    if parsed_memory != dict():
        await insult_login(
            parsed_memory,
            "Sdílenou paměť nechává nějaký {} co není na serveru.",
            "{} máš na {} {} sdílené paměti, ztracené průměrně {} minut, ty prase.",
            bot, channel, system)

    if parsed_semaphores != dict():
        await insult_login(
            parsed_semaphores, "Semafory nechává nějaký {} co není na serveru",
            "{} máš na {} {} semaforů, ležících tam průměrně {} minut, ty prase.",
            bot, channel, system)

    if parsed_files != dict():
        for login, array in parsed_files.copy().items():
            user = session.query(Permit). \
                filter(Permit.login == login).one_or_none()
            login_not_in_name = array[1]
            array = array[0]
            count = len(array)
            avg_time = sum(array) // count

            person = session.query(Valid_person). \
                filter(Valid_person.login == login).one_or_none()

            if "BIT" not in person.year and "FEKT" not in person.year:
                if login in parsed_files:
                    parsed_files.pop(login)
                continue

            if user is None:
                await bot.send(
                    channel, "Soubory semaforu nechává nějaký " + login +
                    " co není na serveru.")
            else:
                await bot.send(
                    channel,
                    utils.generate_mention(user.discord_ID) + " máš na " +
                    system + "(/dev/shm) " + str(count) + " souborů semaforu.")
                if avg_time > 9:
                    await bot.send(
                        channel, "Leží ti tam průměrně už " + str(avg_time) +
                        " minut, ty prase.")
                if login_not_in_name:
                    await bot.send(
                        channel, "Nemáš v názvu tvůj login, takže můžeš" +
                        " mit kolize s ostatními, ty prase.")

    if parsed_processes != dict():
        await insult_login(
            parsed_processes, "Nějakého {} co není na serveru.",
            "{} máš na {} {} procesů, běžících průměrně {} minut, ty prase",
            bot, channel, system)

    if (parsed_memory == dict() and parsed_semaphores == dict()
            and parsed_processes == dict() and parsed_files == dict()):
        await bot.send(
            channel, "Na " + system + " uklizeno <:HYPERS:493154327318233088>")
Exemplo n.º 7
0
    async def on_command_error(self, ctx, error):
        # The local handlers so far only catch bad arguments so we still
        # want to print the rest
        if isinstance(error, commands.BadArgument) and\
           hasattr(ctx.command, 'on_error'):
            return

        if isinstance(error, commands.CommandNotFound):
            if not ctx.message.content.startswith('!'):
                await ctx.send(messages.no_such_command)
            return
        elif isinstance(error, commands.CommandOnCooldown):
            await ctx.send(messages.spamming.format(
                user=utils.generate_mention(ctx.author.id)
                ))
        else:
            output = 'Ignoring exception in command {}:\n'.format(ctx.command)
            output += ''.join(traceback.format_exception(type(error),
                                                         error,
                                                         error.__traceback__))
            channel = self.bot.get_channel(config.bot_dev_channel)
            print(output)
            output = list(output[0 + i: 1900 + i] for i in range(0, len(output), 1900))
            if channel is not None:
                for message in output:
                    await channel.send("```\n" + message + "\n```")
Exemplo n.º 8
0
 async def log_verify_fail(self, message: discord.Message, phase: str):
     embed = discord.Embed(title="Neúspěšný pokus o verify", color=0xeee657)
     embed.add_field(name="User", value=utils.generate_mention(message.author.id))
     embed.add_field(name='Verify phase', value=phase)
     embed.add_field(name="Message", value=message.content, inline=False)
     channel = self.bot.get_channel(Config.log_channel)
     await channel.send(embed=embed)
Exemplo n.º 9
0
 async def botroom_check(self, message):
     room = await self.get_room(message)
     if room is not None and room.id not in config.allowed_channels:
         await message.channel.send(
             messages.bot_room_redirect.format(
                 utils.generate_mention(message.author.id),
                 config.bot_room))
Exemplo n.º 10
0
 async def pick(self, ctx, *args):
     """"Pick an option"""
     option = rng.pick_option(' '.join(args))
     if option:
         await ctx.send("{} {}".format(
             option, utils.generate_mention(ctx.author.id)))
     await self.check.botroom_check(ctx.message)
Exemplo n.º 11
0
    async def get_logins_user(self, ctx, login):
        result = session.query(Permit).\
            filter(Permit.login == login).one_or_none()

        if result is None:
            await ctx.send("Neni na serveru prej")
        else:
            await ctx.send(utils.generate_mention(result.discord_ID))
Exemplo n.º 12
0
    def karma_giving_get(self, author):
        k = self.repo.get_karma(author.id, "give")

        return msg.karma_given.format(user=utils.generate_mention(author.id),
                                      karma_pos=str(k[0]),
                                      karma_pos_pos=str(k[2]),
                                      karma_neg=str(k[1]),
                                      karma_neg_pos=str(k[3]))
Exemplo n.º 13
0
 async def send_masstag_messages(self, ctx, prefix, target_ids):
     message = prefix
     for index in range(len(target_ids)):
         # 35 sounds like a safe amount of tags per message
         if index % 35 == 0 and index:
             await ctx.send(message)
             message = prefix
         message += utils.generate_mention(target_ids[index])
         message += " "
     await ctx.send(message)
     return
Exemplo n.º 14
0
async def pull(ctx):
    if ctx.author.id == config.admin_id:
        try:
            utils.git_pull()
            await ctx.send("Git pulled")
        except:
            await ctx.send("Git pull error")
    else:
        await ctx.send(
            messages.insufficient_rights.format(
                user=utils.generate_mention(ctx.author.id)))
Exemplo n.º 15
0
async def reload(ctx, extension):
    if ctx.author.id == config.admin_id:
        try:
            bot.reload_extension(f'cogs.{extension}')
            await ctx.send(f'{extension} reloaded')
        except:
            await ctx.send("reloading error")
    else:
        await ctx.send(
            messages.insufficient_rights.format(
                user=utils.generate_mention(ctx.author.id)))
Exemplo n.º 16
0
    async def handle_list(self, ctx, args):
        if not len(args) or len(args) > 2:
            await ctx.send(
                messages.acl_help.format(
                    user=utils.generate_mention(ctx.author.id)))
            return

        if args[0] == "group":
            await self.list_group(ctx, args[1:])
        elif args[0] == "rule":
            await self.list_rule(ctx, args[1:])
        elif args[0] == "role":
            await self.list_role(ctx, args[1:])
        elif args[0] == "user":
            await self.list_user(ctx, args[1:])
        else:
            await ctx.send(
                messages.acl_help.format(
                    user=utils.generate_mention(ctx.author.id)))
            return
Exemplo n.º 17
0
    async def handle_del(self, ctx, args):
        if not len(args):
            await ctx.send(
                messages.acl_help.format(
                    user=utils.generate_mention(ctx.author.id)))
            return

        if args[0] == "group" and len(args) == 2:
            await self.del_group(ctx, args[1])
        elif args[0] == "rule" and len(args) == 2:
            await self.del_rule(ctx, args[1])
        elif args[0] == "role" and len(args) == 2:
            await self.del_role(ctx, args[1])
        elif args[0] == "user" and len(args) == 2:
            await self.del_user(ctx, args[1])
        else:
            await ctx.send(
                messages.acl_help.format(
                    user=utils.generate_mention(ctx.author.id)))
            return
Exemplo n.º 18
0
    async def handle_edit(self, ctx, args):
        if not len(args):
            await ctx.send(
                messages.acl_help.format(
                    user=utils.generate_mention(ctx.author.id)))
            return

        if args[0] == "group" and 3 <= len(args) <= 4:
            await self.edit_group(ctx, args[1:])
        elif args[0] == "rule" and len(args) == 3:
            await self.edit_rule(ctx, args[1:])
        elif args[0] == "role" and len(args) == 4:
            await self.edit_role(ctx, args[1:])
        elif args[0] == "user" and len(args) == 4:
            await self.edit_user(ctx, args[1:])
        else:
            await ctx.send(
                messages.acl_help.format(
                    user=utils.generate_mention(ctx.author.id)))
            return
Exemplo n.º 19
0
 async def add_role_on_reaction(self, role, member, channel, guild):
     role = discord.utils.get(guild.roles,
                              name=role)
     max_role = discord.utils.get(guild.roles,
                                  name="Rubbergod")
     if role is not None:
         if role < max_role:
             await member.add_roles(role)
         else:
             await channel.send(Messages.role_add_denied
                                .format(user=utils.generate_mention(
                                    member.id), role=role.name))
Exemplo n.º 20
0
    async def dod(self, ctx):
        # Check if the user doesn't have the verify role
        if not await self.has_role(ctx.author, config.verification_role):
            embed = disnake.Embed(title="DOD verify", color=0xeee657)
            embed.add_field(name="User",
                            value=utils.generate_mention(ctx.author.id))
            channel = self.bot.get_channel(config.log_channel)
            await channel.send(embed=embed)
            try:
                # Get server verify role
                verify = disnake.utils.get(ctx.message.guild.roles,
                                           name=config.verification_role)
                DOD = disnake.utils.get(ctx.message.guild.roles, name="DOD")
                host = disnake.utils.get(ctx.message.guild.roles, name="Host")
                zajemce = disnake.utils.get(ctx.message.guild.roles,
                                            name="ZajemceoStudium")
                member = ctx.author
            except AttributeError:
                # jsme v PM
                guild = self.bot.get_guild(config.guild_id)
                verify = disnake.utils.get(guild.roles,
                                           name=config.verification_role)
                DOD = disnake.utils.get(guild.roles, name="DOD")
                host = disnake.utils.get(guild.roles, name="Host")
                zajemce = disnake.utils.get(guild.roles,
                                            name="ZajemceoStudium")
                member = guild.get_member(ctx.author.id)

            await member.add_roles(verify)
            await member.add_roles(DOD)
            await member.add_roles(host)
            await member.add_roles(zajemce)

            await member.send(
                utils.fill_message("verify_verify_success",
                                   user=ctx.author.id))

            await member.send(Messages.verify_post_verify_info)

            if ctx.message.channel.type is not disnake.ChannelType.private:
                await ctx.message.channel.send(
                    utils.fill_message("verify_verify_success",
                                       user=ctx.author.id))
        else:
            await ctx.send(
                utils.fill_message("verify_already_verified",
                                   user=ctx.author.id,
                                   admin=config.admin_ids[0]))
        try:
            await ctx.message.delete()
        except disnake.errors.Forbidden:
            return
Exemplo n.º 21
0
 def karma_get(self, author, target=None):
     if target is None:
         target = author
     k = self.repo.get_karma(target.id)
     return msg.karma.format(user=utils.generate_mention(
                             author.id),
                             karma=k.karma.value,
                             order=k.karma.position,
                             target=target.display_name,
                             karma_pos=k.positive.value,
                             karma_pos_order=k.positive.position,
                             karma_neg=k.negative.value,
                             karma_neg_order=k.negative.position)
Exemplo n.º 22
0
 async def message_role_reactions(self, message, data):
     if message.channel.type is not discord.ChannelType.text:
         await message.channel.send(Messages.role_not_on_server)
         guild = self.bot.get_guild(Config.guild_id)
     else:
         guild = message.guild
     for line in data:
         if (discord.utils.get(guild.roles,
                               name=line[0]) is None):
             await message.channel.send(
                 Messages.role_not_role
                 .format(user=utils.generate_mention(
                     message.author.id),
                     not_role=line[0]))
         else:
             try:
                 await message.add_reaction(line[1])
             except discord.errors.HTTPException:
                 await message.channel.send(
                     Messages.role_invalid_line
                     .format(user=utils.generate_mention(
                         message.author.id),
                         not_emote=line[1], role=line[0]))
Exemplo n.º 23
0
    async def get_logins_user(self, ctx, login):
        result = session.query(Permit).\
            filter(Permit.login == login).one_or_none()

        if result is None:
            person = session.query(Valid_person).\
                filter(Valid_person.login == login).one_or_none()
            if person is None:
                await ctx.send("Uživatel není v databázi možných loginů.")
            else:
                await ctx.send(("Login: `{p.login}`\nJméno: `{p.name}`\n"
                                "Ročník: `{p.year}`\nNení na serveru."
                                ).format(p=person))
        else:
            await ctx.send(utils.generate_mention(result.discord_ID))
Exemplo n.º 24
0
 async def subject(self, ctx, subcommand=None, subject=None):
     if ctx.author.id == config.admin_id:
         if not subcommand or not subject:
             await ctx.send(messages.subject_format)
             return
         if subcommand == "add":
             self.rev.add_subject(subject)
             await ctx.send(f'Zkratka {subject} byla přidána')
         elif subcommand == "remove":
             self.rev.remove_subject(subject)
             await ctx.send(f'Zkratka {subject} byla odebrána')
         else:
             await ctx.send(messages.review_wrong_subject)
     else:
         await ctx.send(
             messages.insufficient_rights
             .format(user=utils.generate_mention(ctx.author.id)))
Exemplo n.º 25
0
    async def gen_code_and_send_mail(self, message, login, mail_postfix):
        # Generate a verification code
        code = ''.join(
            random.choices(string.ascii_uppercase + string.digits, k=20))

        email_message = Config.default_prefix + "verify "
        email_message += login + " " + code

        self.send_mail(login + mail_postfix, email_message)

        # Save the newly generated code into the database
        self.repo.save_sent_code(login, code)

        await message.channel.send(
            Messages.verify_send_success.format(user=utils.generate_mention(
                message.author.id),
                                                mail=mail_postfix))
Exemplo n.º 26
0
 def generate_number(message):
     """"Generate random number from interval"""
     string = message.content.split(" ")
     if len(string) != 3 and len(string) != 2:
         return Messages.rng_generator_format
     try:
         x = int(string[1])
         if len(string) == 3:
             y = int(string[2])
         else:
             y = 0
     except ValueError:
         return Messages.rng_generator_format_number.format(
             user=utils.generate_mention(message.author.id))
     if x > y:
         x, y = y, x  # variable values swap
     return randint(x, y)
Exemplo n.º 27
0
async def on_command_error(ctx, error):
    if isinstance(error, commands.BadArgument) and ctx.command.name == 'hug':
        return

    if isinstance(error, commands.CommandNotFound):
        if not ctx.message.content.startswith('!'):
            await ctx.send(messages.no_such_command)
        return
    elif isinstance(error, commands.CommandOnCooldown):
        await ctx.send(messages.spamming.format(
            user=utils.generate_mention(ctx.author.id)
            ))
    else:
        output = 'Ignoring exception in command {}:\n'.format(ctx.command)
        output += ''.join(traceback.format_exception(type(error),
                                                     error,
                                                     error.__traceback__))
        channel = bot.get_channel(config.log_channel_id)
        print(output)
        if channel is not None:
            await channel.send("```\n" + output + "\n```")
Exemplo n.º 28
0
    async def update_db(self, ctx):
        if ctx.author.id != config.admin_id:
            await ctx.send(
                messages.insufficient_rights.format(
                    user=utils.generate_mention(ctx.author.id)))
            return

        with open("merlin-latest", "r") as f:
            data = f.readlines()

        new_people = []
        new_logins = []

        for line in data:
            line = line.split(":")
            login = line[0]
            name = line[4].split(",", 1)[0]
            try:
                year = line[4].split(",")[1]
            except IndexError:
                continue
            new_people.append(Valid_person(login=login, year=year, name=name))
            new_logins.append(login)

        for person in new_people:
            session.merge(person)

        for person in session.query(Valid_person):
            if person.login not in new_logins:
                try:
                    # check for muni
                    int(person.login)
                    print("Muni pls")
                    person.year = "MUNI"
                except ValueError:
                    person.year = "dropout"

        session.commit()

        await ctx.send("Update databaze probehl uspesne")
Exemplo n.º 29
0
async def insult_login(parsed_items, non_user_format: str, user_format: str,
                       bot, channel, system):
    for login, array in parsed_items.copy().items():
        user = session.query(Permit).filter(
            Permit.login == login).one_or_none()
        count = len(array)
        avg_time = sum(array) // count

        person = session.query(Valid_person).filter(
            Valid_person.login == login).one_or_none()

        if "BIT" not in person.year and "FEKT" not in person.year:
            if login in parsed_items:
                parsed_items.pop(login)
            continue

        if user is None:
            await channel.send(non_user_format.format(login))
        else:
            await channel.send(
                user_format.format(utils.generate_mention(user.discord_ID),
                                   system, str(count),
                                   minutes_to_formated_time(avg_time)))
Exemplo n.º 30
0
async def hug_error(ctx, error):
    if isinstance(error, commands.BadArgument):
        await ctx.send(
            messages.member_not_found
            .format(user=utils.generate_mention(ctx.author.id)))