Beispiel #1
0
        def decorated_command(plugin_obj, data, user_data):
            parser = argparse.ArgumentParser(prog=kwargs["name"],
                                             description=kwargs["description"],
                                             usage=kwargs["usage"])

            # Dynamically add in the required and optional arguments:
            arg_type = ["required", "optional"]
            for at in arg_type:
                if kwargs.get(at):
                    for argument in kwargs[at]:
                        # If there is a list of available values, then ensure that they are added in for argparse to
                        # process properly. This can be done 1 of two ways:
                        #  1.) [Not recommended] Use argparse directly by passing in a fixed list within
                        #       `properties["choices"]`
                        #
                        #  2.) [Recommended] Add `choices` outside of `properties` where you can define where
                        #      the list of values appear within the Plugin's command config. This is
                        #      preferred, because it reflects how the command is actually configured after the plugin's
                        #      `setup()` method is run.
                        #
                        #      To make use of this properly, you need to have the help text contain: "{values}"
                        #      This will then ensure that the list of values are properly in there.
                        ##
                        if argument.get("choices"):
                            # Add the dynamic choices:
                            argument["properties"]["choices"] = plugin_obj.commands[kwargs["name"]][argument["choices"]]

                            # Fix the help text:
                            argument["properties"]["help"] = argument["properties"]["help"].format(
                                values=", ".join(plugin_obj.commands[kwargs["name"]][argument["choices"]])
                            )

                        parser.add_argument(argument["name"], **argument["properties"])

            # Remove the command from the command string:
            split_args = shlex.split(data["text"])[1:]
            try:
                args = vars(parser.parse_args(split_args))

            except SystemExit as _:
                send_info(data["channel"], format_help_text(data, user_data, **kwargs), markdown=True,
                          ephemeral_user=user_data["id"])
                return

            # Perform additional verification:
            try:
                args = perform_additional_verification(plugin_obj, args, **kwargs)
            except ParseException as pe:
                send_error(data["channel"], pe.format_proper_usage(user_data["name"]),
                           markdown=True, ephemeral_user=user_data["id"])
                return
            except Exception as e:
                send_error(data["channel"], "An exception was encountered while running validation for the input. "
                                            "The exception details are: `{}`".format(str(e)),
                           markdown=True)
                return

            # Run the next function:
            data["command_name"] = kwargs["name"]
            return func(plugin_obj, data, user_data, **args)
Beispiel #2
0
        def decorated_command(plugin_obj, data, user_data):
            parser = argparse.ArgumentParser(prog=kwargs["name"],
                                             description=kwargs["description"],
                                             usage=kwargs["usage"])

            # Dynamically add in the required and optional arguments:
            arg_type = ["required", "optional"]
            for at in arg_type:
                if kwargs.get(at):
                    for argument in kwargs[at]:
                        # If there is a list of available values, then ensure that they are added in for argparse to
                        # process properly. This can be done 1 of two ways:
                        #  1.) [Not recommended] Use argparse directly by passing in a fixed list within
                        #       `properties["choices"]`
                        #
                        #  2.) [Recommended] Add `choices` outside of `properties` where you can define where
                        #      the list of values appear within the Plugin's command config. This is
                        #      preferred, because it reflects how the command is actually configured after the plugin's
                        #      `setup()` method is run.
                        #
                        #      To make use of this properly, you need to have the help text contain: "{values}"
                        #      This will then ensure that the list of values are properly in there.
                        ##
                        if argument.get("choices"):
                            # Add the dynamic choices:
                            argument["properties"]["choices"] = plugin_obj.commands[kwargs["name"]][argument["choices"]]

                            # Fix the help text:
                            argument["properties"]["help"] = argument["properties"]["help"].format(
                                values=", ".join(plugin_obj.commands[kwargs["name"]][argument["choices"]])
                            )

                        parser.add_argument(argument["name"], **argument["properties"])

            # Remove the command from the command string:
            split_args = shlex.split(data["text"])[1:]
            try:
                args = vars(parser.parse_args(split_args))

            except SystemExit as _:
                send_info(data["channel"], format_help_text(data, user_data, **kwargs), markdown=True,
                          ephemeral_user=user_data["id"])
                return

            # Perform additional verification:
            try:
                args = perform_additional_verification(plugin_obj, args, **kwargs)
            except ParseException as pe:
                send_error(data["channel"], pe.format_proper_usage(user_data["name"]),
                           markdown=True, ephemeral_user=user_data["id"])
                return
            except Exception as e:
                send_error(data["channel"], "An exception was encountered while running validation for the input. "
                                            "The exception details are: `{}`".format(str(e)),
                           markdown=True)
                return

            # Run the next function:
            data["command_name"] = kwargs["name"]
            return func(plugin_obj, data, user_data, **args)
Beispiel #3
0
    def authenticate(self, data, user_data, **kwargs):
        send_info(data["channel"], "🎟 @{}: Sending a Duo notification to your device. You must approve!"
                  .format(user_data["name"]), markdown=True, ephemeral_user=user_data["id"])

        try:
            result = self._perform_auth(user_data)
        except InvalidDuoResponseError as idre:
            send_error(data["channel"], "💀 @{}: There was a problem communicating with Duo. Got this status: {}. "
                                        "Aborting..."
                       .format(user_data["name"], str(idre)), markdown=True)
            return False

        except CantDuoUserError as _:
            send_error(data["channel"], "💀 @{}: I can't Duo authenticate you. Please consult with your identity team."
                                        " Aborting..."
                       .format(user_data["name"]), markdown=True)
            return False

        except Exception as e:
            send_error(data["channel"], "💀 @{}: I encountered some issue with Duo... Here are the details: ```{}```"
                       .format(user_data["name"], str(e)), markdown=True)
            return False

        if not result:
            send_error(data["channel"], "💀 @{}: Your Duo request was rejected. Aborting..."
                       .format(user_data["name"]), markdown=True, thread=data["ts"])
            return False

        # All Good:
        send_success(data["channel"], "🎸 @{}: Duo approved! Completing request..."
                     .format(user_data["name"]), markdown=True, ephemeral_user=user_data["id"])
        return True
Beispiel #4
0
    def listachat(self, data, user_data, history, for_user):

        session = DBSession()
        today = datetime.date.today()

        if history < 1:
            send_error(data['channel'],
                       "Non non non, history doit être > 1 <@{0}> ;)".format(
                           user_data['id']),
                       markdown=True)
            return

        user = None
        if for_user:
            user = self.get_db_user(session, for_user)

            if not user:
                send_error(data['channel'], 'Erreur zjaifnazgoizangoiazg')

        delta = datetime.timedelta(days=history)
        start_date = today - delta

        query = session.query(Expense).filter(Expense.date >= start_date)
        if user:
            query = query.filter(Expense.user_id == user.id)

        expenses = query.all()

        outputs = []
        if not expenses:
            if user:
                outputs.append(
                    "Pas d'achat dans les {0} derniers jours pour {1}.".format(
                        history, user.name))
            else:
                outputs.append(
                    "Pas d'achat dans les {0} derniers jours.".format(history))
        else:
            if user:
                outputs.append(
                    "Liste des achats depuis {0} jours par {1} :".format(
                        history, user.name))
            else:
                outputs.append(
                    "Liste des achats depuis {0} jours :".format(history))
            for expense in expenses:
                if user:
                    text = "- Le {0} : {1} €".format(expense.date,
                                                     expense.amount)
                else:
                    text = "- {0}, le {1} : {2} €".format(
                        expense.user.name, expense.date, expense.amount)
                if expense.description:
                    text += " pour {0}".format(expense.description)
                outputs.append(text)
        send_info(data['channel'],
                  text='\n'.join(outputs),
                  markdown=True,
                  thread=data["ts"])
Beispiel #5
0
def print_help(data):
    text = "I support the following commands:\n"

    for txt in HELP_TEXT:
        text += txt

    text += "`!Help` - This command."
    send_info(data["channel"], text, markdown=True)
def print_help(data):
    text = "I support the following commands:\n"

    for txt in HELP_TEXT:
        text += txt

    text += "`!Help` - This command."

    send_info(data["channel"], text, markdown=True)
def test_send_info(slack_client, markdown):
    from hubcommander.bot_components.slack_comm import send_info, WORKING_COLOR
    attachment = {"text": "ʕ•ᴥ•ʔ", "color": WORKING_COLOR}

    if markdown:
        attachment["mrkdwn_in"] = ["text"]

    send_info("some_channel", attachment["text"], markdown)

    actually_said("some_channel", [attachment], slack_client)
Beispiel #8
0
    def cancelmanger(self, data, user_data, for_user):
        session = DBSession()

        day = self.get_db_day(session)
        if not day:
            day = Day(date=datetime.date.today())
            session.add(day)
            session.commit()

        outputs = []

        if for_user:
            user = self.get_db_user(session, for_user)
        else:
            user = self.get_db_user(session, user_data['name'])

        if not user:
            send_error(data['channel'],
                       'Erreur zjaifnazgoizangoiazg',
                       thread=data["ts"])

        presence = session.query(Presence).filter(
            Presence.user_id == user.id, Presence.day_id == day.id).first()
        if not presence:
            if for_user:
                outputs.append(
                    "@{0} n'étais pas inscrit, pas de soucis <@{1}> !".format(
                        user.name, user_data['id']))
            else:
                outputs.append(
                    "Tu n'étais pas inscrit, pas de soucis <@{0}> !".format(
                        user_data['id']))
        else:
            session.query(Presence).filter_by(id=presence.id).delete()
            session.commit()
            if for_user:
                outputs.append("J'ai supprimé l'inscription de @{0}.".format(
                    user.name))
            else:
                outputs.append(
                    "J'ai supprimé ta demande <@{0}>, dommage ça allait être trop bon !"
                    .format(user_data['id']))

            outputs.append("Si besoin tu !Manger à nouveau :)")
        send_info(data['channel'],
                  text='\n'.join(outputs),
                  markdown=True,
                  ephemeral_user=user_data["id"])
        data['text'] = '!QuiMange'
        self.quimange(data, user_data)
Beispiel #9
0
    def authenticate(self, data, user_data, **kwargs):
        send_info(
            data["channel"],
            "🎟 @{}: Sending a Duo notification to your device. You must approve!"
            .format(user_data["name"]),
            markdown=True,
            ephemeral_user=user_data["id"])

        try:
            result = self._perform_auth(user_data)
        except InvalidDuoResponseError as idre:
            send_error(
                data["channel"],
                "💀 @{}: There was a problem communicating with Duo. Got this status: {}. "
                "Aborting...".format(user_data["name"], str(idre)),
                markdown=True)
            return False

        except CantDuoUserError as _:
            send_error(
                data["channel"],
                "💀 @{}: I can't Duo authenticate you. Please consult with your identity team."
                " Aborting...".format(user_data["name"]),
                markdown=True)
            return False

        except Exception as e:
            send_error(
                data["channel"],
                "💀 @{}: I encountered some issue with Duo... Here are the details: ```{}```"
                .format(user_data["name"], str(e)),
                markdown=True)
            return False

        if not result:
            send_error(
                data["channel"],
                "💀 @{}: Your Duo request was rejected. Aborting...".format(
                    user_data["name"]),
                markdown=True,
                thread=data["ts"])
            return False

        # All Good:
        send_success(data["channel"],
                     "🎸 @{}: Duo approved! Completing request...".format(
                         user_data["name"]),
                     markdown=True,
                     ephemeral_user=user_data["id"])
        return True
Beispiel #10
0
    def list_org_command(data):
        """
        The "!ListTravisOrgs" command. Lists all organizations that have Travis CI enabled.
        :param data:
        :return:
        """
        headers = ["Alias", "Organization"]
        rows = []
        for org in ORGS.items():
            rows.append([org[0].lower(), org[0]])
            for alias in org[1]["aliases"]:
                rows.append([alias, org[0]])

        send_info(data["channel"], "Travis CI is enabled on the following orgs:\n"
                                   "```{}```".format(tabulate(rows, headers=headers)), markdown=True, thread=data["ts"])
Beispiel #11
0
    def achat(self, data, user_data, amount, description):

        session = DBSession()
        today = datetime.date.today()
        user = self.get_db_user(session, user_data['name'])

        expense = Expense(user_id=user.id,
                          amount=amount,
                          description=description)
        session.add(expense)
        session.commit()

        send_info(data['channel'],
                  text='Achat enregistré !',
                  markdown=True,
                  thread=data["ts"])
Beispiel #12
0
    def list_org_command(data):
        """
        The "!ListTravisOrgs" command. Lists all organizations that have Travis CI enabled.
        :param data:
        :return:
        """
        headers = ["Alias", "Organization"]
        rows = []
        for org in ORGS.items():
            rows.append([org[0].lower(), org[0]])
            for alias in org[1]["aliases"]:
                rows.append([alias, org[0]])

        send_info(data["channel"],
                  "Travis CI is enabled on the following orgs:\n"
                  "```{}```".format(tabulate(rows, headers=headers)),
                  markdown=True)
Beispiel #13
0
    def cuisiner(self, data, user_data):

        session = DBSession()

        day = self.get_db_day(session)
        if not day:
            day = Day(date=datetime.date.today())
            session.add(day)
            session.commit()

        outputs = []

        user = self.get_db_user(session, user_data['name'])

        if not user:
            send_error(data['channel'],
                       'Erreur il faut ```python manage.py sync``` d\'abort !',
                       thread=data["ts"])

        presence = session.query(Presence).filter(
            Presence.user_id == user.id, Presence.day_id == day.id).first()

        if not presence:
            presence = Presence(user_id=user.id, day_id=day.id, cook=1)
            session.add(presence)
            session.commit()

            outputs.append(
                "J'ai pris en compte le fait que tu cuisinais aujourd'hui")

        else:
            presence.cook = 1
            session.add(presence)
            session.commit()

            outputs.append(
                "J'ai pris en compte le fait que tu cuisinais aujourd'hui")
        send_info(data['channel'],
                  text='\n'.join(outputs),
                  markdown=True,
                  ephemeral_user=user_data["id"])
        data['text'] = '!QuiMange'
        self.quimange(data, user_data)
Beispiel #14
0
    def mealprice(self, data, user_data):
        session = DBSession()

        total_expenses = 0.0
        expenses = session.query(Expense).all()
        for expense in expenses:
            total_expenses += expense.amount

        total_presences = 0
        presences = session.query(Presence).all()
        for presence in presences:
            total_presences += presence.meals

        average_price = total_expenses / total_presences

        outputs = []
        outputs.append("Total des dépenses : {0} €".format(total_expenses))
        outputs.append("Total de repas : {0}".format(total_presences))
        outputs.append("Prix moyen d'un repas : {0} €".format(average_price))

        send_info(data['channel'], text='\n'.join(outputs), markdown=True)
Beispiel #15
0
    def quimange(self, data, user_data):
        outputs = []
        session = DBSession()

        day = self.get_db_day(session)
        if not day:
            day = Day(date=datetime.date.today())
            session.add(day)
            session.commit()

        presences = session.query(Presence).filter(
            Presence.day_id == day.id).all()
        if not presences:
            outputs.append("Personne d'inscrit aujourd'hui, sniff :(")
        else:
            total = 0
            for presence in presences:
                user = presence.user
                total += presence.meals
                guest = presence.meals - 1
                if guest > 0:
                    outputs.append("{0} avec {1} invités".format(
                        user.name, guest))
                else:
                    outputs.append(user.name)
                if presence.cook == 1:
                    outputs.append("C'est {0} qui cuisinera".format(user.name))
            if total > 1:
                outputs.insert(0,
                               "Ce midi, {0} personnes mangent:".format(total))
            else:
                outputs.insert(
                    0, "Ce midi, {0} personne mange, bravo à elle !!".format(
                        total))

        send_info(data['channel'], text='\n'.join(outputs), markdown=True)
Beispiel #16
0
    def cancelcuisiner(self, data, user_data):
        session = DBSession()

        day = self.get_db_day(session)
        if not day:
            day = Day(date=datetime.date.today())
            session.add(day)
            session.commit()

        outputs = []

        user = self.get_db_user(session, user_data['name'])

        if not user:
            send_error(data['channel'],
                       'Erreur zjaifnazgoizangoiazg',
                       thread=data["ts"])

        presence = session.query(Presence).filter(
            Presence.user_id == user.id, Presence.day_id == day.id).first()
        if not presence:
            outputs.append(
                "Tu n'étais pas inscrit, pas de soucis <@{0}> !".format(
                    user_data['id']))
        else:
            presence.cook = 0
            session.add(presence)
            session.commit()
            outputs.append("J'ai supprimé le fait que tu avais cuisiné")

        send_info(data['channel'],
                  text='\n'.join(outputs),
                  markdown=True,
                  ephemeral_user=user_data["id"])
        data['text'] = '!QuiMange'
        self.quimange(data, user_data)
Beispiel #17
0
 def repeat_thread_command(self, data, user_data, text):
     new_text = data['text'].split(' ', 1)[1]
     send_info(data["channel"], new_text, markdown=True, thread=data["ts"])
Beispiel #18
0
    def mybalance(self, data, user_data, history, for_user):
        today = datetime.date.today()

        session = DBSession()
        if history < 1:
            send_error(data['channel'],
                       "Non non non, history doit être > 1 <@{0}> ;)".format(
                           user_data['id']),
                       markdown=True)
            return

        if for_user:
            user = self.get_db_user(session, for_user)
        else:
            user = self.get_db_user(session, user_data['name'])

        if not user:
            send_error(data['channel'], 'Erreur zjaifnazgoizangoiazg')

        delta = datetime.timedelta(days=history)
        start_date = today - delta

        expenses = session.query(Expense).filter(
            Expense.user_id == user.id, Expense.date >= start_date).all()

        outputs = []
        if not expenses:
            outputs.append(
                "Pas d'achat dans les {0} derniers jours pour {1}".format(
                    history, user.name))
        else:
            if for_user:
                outputs.append(
                    "Liste des achats depuis {0} jours par {1} :".format(
                        history, user.name))
            else:
                outputs.append(
                    "Liste de tes achats depuis {0} jours :".format(history))
            for expense in expenses:
                text = "- Le {0} : {1} €".format(expense.date, expense.amount)
                if expense.description:
                    text += " pour {0}".format(expense.description)
                outputs.append(text)

        presences = session.query(Presence).filter(
            Presence.user_id == user.id).join(Day).filter(
                Day.date >= start_date).all()

        if not presences:
            outputs.append(
                "Pas de repas compatibilisé dans les {0} derniers jours pour {1}"
                .format(history, user.name))
        else:
            if for_user:
                outputs.append(
                    "Liste des repas depuis {0} jours de {1} :".format(
                        history, user.name))
            else:
                outputs.append(
                    "Liste de tes repas depuis {0} jours :".format(history))
            for presence in presences:
                text = "- Le {0} : {1} repas à {2} €".format(
                    presence.day.date, presence.meals, presence.day.price)
                outputs.append(text)

        if for_user:
            outputs.append(
                "Du coup, en tout, voici la balance de {0} : {1} €".format(
                    user.name, user.balance))
        else:
            outputs.append("Du coup, en tout, voici ta balance : {0} €".format(
                user.balance))

        send_info(data['channel'],
                  text='\n'.join(outputs),
                  markdown=True,
                  thread=data["ts"])
Beispiel #19
0
    def enable_travis_command(self, data, user_data, org, repo):
        """
        Enables Travis CI on a repository within the organization.

        Command is as follows: !enabletravis <organization> <repo>
        :param repo:
        :param org:
        :param user_data:
        :param data:
        :return:
        """
        from hubcommander.command_plugins.enabled_plugins import COMMAND_PLUGINS
        github_plugin = COMMAND_PLUGINS["github"]

        # Output that we are doing work:
        send_info(data["channel"], "@{}: Working, Please wait...".format(user_data["name"]), thread=data["ts"])

        # Get the repo information from GitHub:
        try:
            repo_result = github_plugin.check_gh_for_existing_repo(repo, org)

            if not repo_result:
                send_error(data["channel"],
                           "@{}: This repository does not exist in {}!".format(user_data["name"], org),
                           thread=data["ts"])
                return

        except Exception as e:
            send_error(data["channel"],
                       "@{}: I encountered a problem:\n\n{}".format(user_data["name"], e), thread=data["ts"])
            return

        which = "pro" if repo_result["private"] else "public"

        try:
            # Sync with Travis CI so that it knows about the repo:
            send_info(data["channel"], ":skull: Need to sync Travis CI with GitHub. Please wait...", thread=data["ts"])
            self.sync_with_travis(which)

            send_info(data["channel"], ":guitar: Synced! Going to enable Travis CI on the repo now...",
                      thread=data["ts"])

            travis_data = self.look_for_repo(which, repo_result)
            if not travis_data:
                send_error(data["channel"], "@{}: Couldn't find the repo in Travis for some reason...\n\n".format(
                    user_data["name"]), thread=data["ts"])
                return

            # Is it already enabled?
            if travis_data["active"]:
                send_success(data["channel"],
                             "@{}: Travis CI is already enabled on {}/{}.\n\n".format(
                                 user_data["name"], org, repo), thread=data["ts"])
                return

            # Enable it:
            self.enable_travis_on_repo(which, repo_result)

        except Exception as e:
            send_error(data["channel"],
                       "@{}: I encountered a problem communicating with Travis CI:\n\n{}".format(user_data["name"], e),
                       thread=data["ts"])
            return

        message = "@{}: Travis CI has been enabled on {}/{}.\n\n".format(user_data["name"], org, repo)
        send_success(data["channel"], message, thread=data["ts"])
Beispiel #20
0
 def repeat_command(self, data, user_data, text):
     new_text = data['text'].split(' ', 1)[1]
     send_info(data["channel"],
               new_text,
               markdown=True,
               ephemeral_user=user_data["id"])
Beispiel #21
0
    def enable_travis_command(self, data, user_data):
        """
        Enables Travis CI on a repository within the organization.

        Command is as follows: !enabletravis <organization> <repo>
        :param data:
        :return:
        """
        from hubcommander.command_plugins.enabled_plugins import GITHUB_PLUGIN
        try:
            parser = argparse.ArgumentParser()
            parser.add_argument('org', type=str)
            parser.add_argument('repo', type=str)

            args, unknown = parser.parse_known_args(
                args=preformat_args(data["text"]))
            if len(unknown) > 0:
                raise SystemExit()

            args = vars(args)

            repo_to_set = extract_repo_name(args["repo"])

            # Check that we can use this org:
            real_org = GITHUB_PLUGIN.org_lookup[args["org"]][0]

        except KeyError as _:
            send_error(
                data["channel"],
                '@{}: Invalid orgname sent in.  Run `!ListOrgs` to see the valid orgs.'
                .format(user_data["name"]),
                markdown=True)
            return

        except SystemExit as _:
            send_info(
                data["channel"],
                "@{}: `!EnableTravis` usage is:\n```!EnableTravis <Organization> <Repo>"
                "```\nNo special characters or spaces in the variables. "
                "Run `!ListOrgs` to see the list of GitHub Organizations that I manage."
                .format(user_data["name"]),
                markdown=True)
            return

        # Auth?
        if self.commands["!EnableTravis"].get("auth"):
            if not self.commands["!EnableTravis"]["auth"][
                    "plugin"].authenticate(
                        data, user_data, **
                        self.commands["!EnableTravis"]["auth"]["kwargs"]):
                return

        # Output that we are doing work:
        send_info(data["channel"],
                  "@{}: Working, Please wait...".format(user_data["name"]))

        # Get the repo information from GitHub:
        try:
            repo_result = GITHUB_PLUGIN.check_gh_for_existing_repo(
                repo_to_set, real_org)

            if not repo_result:
                send_error(
                    data["channel"],
                    "@{}: This repository does not exist in {}!".format(
                        user_data["name"], real_org))
                return

        except Exception as e:
            send_error(
                data["channel"], "@{}: I encountered a problem:\n\n{}".format(
                    user_data["name"], e))
            return

        which = "pro" if repo_result["private"] else "public"

        try:
            # Check that the repo even exists:
            send_info(
                data["channel"],
                ":skull: Need to sync Travis CI with GitHub. Please wait...")
            self.sync_with_travis(which)

            send_info(
                data["channel"],
                ":guitar: Synced! Going to enable Travis CI on the repo now..."
            )

            travis_data = self.look_for_repo(which, repo_result)
            if not travis_data:
                send_error(
                    data["channel"],
                    "@{}: Couldn't find the repo in Travis for some reason...\n\n"
                    .format(user_data["name"]))
                return

            # Is it already enabled?
            if travis_data["active"]:
                send_success(
                    data["channel"],
                    "@{}: Travis CI is already enabled on {}/{}.\n\n".format(
                        user_data["name"], real_org, repo_to_set))
                return

            # Enable it:
            self.enable_travis_on_repo(which, repo_result)

        except Exception as e:
            send_error(
                data["channel"],
                "@{}: I encountered a problem communicating with Travis CI:\n\n{}"
                .format(user_data["name"], e))
            return

        message = "@{}: Travis CI has been enabled on {}/{}.\n\n".format(
            user_data["name"], real_org, repo_to_set)
        send_success(data["channel"], message)
Beispiel #22
0
    def manger(self, data, user_data, guest, for_user):

        session = DBSession()
        if guest < 0:
            send_error(
                data['channel'],
                "Touche à ton cul avec ton nombre négatif <@{0}> ;)".format(
                    user_data['id']),
                markdown=True,
                thread=data["ts"])
            return

        day = self.get_db_day(session)
        if not day:
            day = Day(date=datetime.date.today())
            session.add(day)
            session.commit()

        outputs = []

        if for_user:
            user = self.get_db_user(session, for_user)
            from_user = self.get_db_user(session, user_data['name'])
        else:
            user = self.get_db_user(session, user_data['name'])

        if not user:
            send_error(data['channel'],
                       'Erreur il faut ```python manage.py sync``` d\'abort !',
                       thread=data["ts"])

        presence = session.query(Presence).filter(
            Presence.user_id == user.id, Presence.day_id == day.id).first()

        if not presence:
            presence = Presence(user_id=user.id,
                                day_id=day.id,
                                meals=guest + 1)
            session.add(presence)
            session.commit()

            if for_user:
                outputs.append(
                    "Demande enregistrée par <@{0}> pour <@{1}>".format(
                        from_user.slackid, user.slackid))
                if guest > 0:
                    outputs.append("Je compterai {0} part(s)".format(guest +
                                                                     1))
            else:
                outputs.append("J'ai pris en compte ta demande <@{0}>".format(
                    user_data['id']))
                if guest > 0:
                    outputs.append(
                        "Je te compterai {0} part ce jour".format(guest + 1))
        else:
            if presence.meals != guest + 1:
                presence.meals = guest + 1
                session.add(presence)
                session.commit()

                if for_user:
                    if guest > 0:
                        outputs.append(
                            "Demande modifiée par <@{0}> pour <@{1}>, {2} invité(s) rajoutés"
                            .format(from_user.slackid, user.slackid, guest))
                    else:
                        outputs.append(
                            "Demande modifiée par <@{0}> pour <@{1}>, les invités ont été supprimés"
                            .format(from_user.slackid, user.slackid, guest))
                else:
                    if guest > 0:
                        outputs.append(
                            "J'ai modifié ta demande, et rajouté {0} invité(s) <@{1}>"
                            .format(guest, user.slackid))
                    else:
                        outputs.append(
                            "J'ai modifié ta demande, et enlevé les invités <@{1}>"
                            .format(guest, user.slackid))
            else:
                if for_user:
                    outputs.append(
                        "Rien n'a changé, <@{0}> était déjà inscrit <@{1}> :)".
                        format(user.slackid, from_user.slackid))
                else:
                    outputs.append(
                        "Rien n'a changé, tu étais déjà inscrit <@{0}> :)".
                        format(user.slackid))

        outputs.append(
            "Si besoin tu peux !CancelManger ou !Manger avec des invités :)")
        if for_user:
            send_info(data['channel'],
                      text='\n'.join(outputs),
                      markdown=True,
                      ephemeral_user=user.slackid)
            send_info(data['channel'],
                      text='\n'.join(outputs),
                      markdown=True,
                      ephemeral_user=from_user.slackid)
        else:
            send_info(data['channel'],
                      text='\n'.join(outputs),
                      markdown=True,
                      ephemeral_user=user_data["id"])
        data['text'] = '!QuiMange'
        self.quimange(data, user_data)
Beispiel #23
0
    def enable_travis_command(self, data, user_data, org, repo):
        """
        Enables Travis CI on a repository within the organization.

        Command is as follows: !enabletravis <organization> <repo>
        :param repo:
        :param org:
        :param user_data:
        :param data:
        :return:
        """
        from hubcommander.command_plugins.enabled_plugins import COMMAND_PLUGINS
        github_plugin = COMMAND_PLUGINS["github"]

        # Output that we are doing work:
        send_info(data["channel"],
                  "@{}: Working, Please wait...".format(user_data["name"]))

        # Get the repo information from GitHub:
        try:
            repo_result = github_plugin.check_gh_for_existing_repo(repo, org)

            if not repo_result:
                send_error(
                    data["channel"],
                    "@{}: This repository does not exist in {}!".format(
                        user_data["name"], org))
                return

        except Exception as e:
            send_error(
                data["channel"], "@{}: I encountered a problem:\n\n{}".format(
                    user_data["name"], e))
            return

        which = "pro" if repo_result["private"] else "public"

        try:
            # Sync with Travis CI so that it knows about the repo:
            send_info(
                data["channel"],
                ":skull: Need to sync Travis CI with GitHub. Please wait...")
            self.sync_with_travis(which)

            send_info(
                data["channel"],
                ":guitar: Synced! Going to enable Travis CI on the repo now..."
            )

            travis_data = self.look_for_repo(which, repo_result)
            if not travis_data:
                send_error(
                    data["channel"],
                    "@{}: Couldn't find the repo in Travis for some reason...\n\n"
                    .format(user_data["name"]))
                return

            # Is it already enabled?
            if travis_data["active"]:
                send_success(
                    data["channel"],
                    "@{}: Travis CI is already enabled on {}/{}.\n\n".format(
                        user_data["name"], org, repo))
                return

            # Enable it:
            self.enable_travis_on_repo(which, repo_result)

        except Exception as e:
            send_error(
                data["channel"],
                "@{}: I encountered a problem communicating with Travis CI:\n\n{}"
                .format(user_data["name"], e))
            return

        message = "@{}: Travis CI has been enabled on {}/{}.\n\n".format(
            user_data["name"], org, repo)
        send_success(data["channel"], message)
Beispiel #24
0
 def repeat_thread_command(self, data, user_data, text):
     new_text = data['text'].split(' ', 1)[1]
     send_info(data["channel"], new_text, markdown=True, thread=data["ts"])
Beispiel #25
0
 def repeat_command(self, data, user_data, text):
     new_text = data['text'].split(' ', 1)[1]
     send_info(data["channel"], new_text, markdown=True, ephemeral_user=user_data["id"])
Beispiel #26
0
 def repeat_command(self, data):
     new_text = data['text'].split(' ', 1)[1]
     send_info(data["channel"], new_text, markdown=True)
Beispiel #27
0
    def balance(self, data, user_data):
        session = DBSession()
        users = (session.query(User).filter(User.status == 1).all())
        outputs = []
        outputs.append('Voici l\'état des compte chez Louise :')
        real_users = []
        for user in users:
            real_users.append({'name': user.name, 'balance': user.balance})

        total_balance = 0.0
        for user in sorted(real_users, key=lambda x: x['balance']):
            user_balance = float(user['balance'])
            total_balance += user_balance
            if abs(user_balance) > 1:
                outputs.append('{0} : balance à {1:.2f}'.format(
                    user['name'], user_balance))
        outputs.append('\nTotal balance : {0:.2f}'.format(total_balance))
        send_info(data['channel'], text='\n'.join(outputs))


        query  = session.query(User.name, User.status, User.id.label('id'), func.sum(Presence.cook).label('sum_cook'))\
            .filter(User.status == 1)\
            .join(Presence, User.id == Presence.user_id).filter(Presence.cook.isnot(None)).group_by(User.name)
        users = query.all()

        outputs = []
        #outputs.append('Qui a cuisiné et pour combien de personnes ?')
        id_user = 0

        outputs.append('```')
        outputs.append(
            '|      Nom    | Repas cuisiné | Repas mangé| RC / RM |')
        outputs.append(
            '|-------------|---------------|------------|---------|')
        for user in users:
            # Skip old user
            if not user.status:
                continue
            days = session.query(
                Presence.day_id).filter(Presence.cook == 1).filter(
                    Presence.user_id == user.id).group_by(
                        Presence.day_id).subquery()  # days where he cooked
            cooked = session.query(
                Presence.user_id,
                func.sum(Presence.meals).label('sum_cooked')).filter(
                    Presence.day_id.in_(days)).first(
                    )  #sum_cooked Number of person that he cooked for
            if cooked is None:
                cooked = 0
            else:
                cooked = str(
                    cooked[1]
                )  #cooked arrive avec le format suivant [(10, 2)] , donc [(user_id, sum_cooked)]

            eat = session.query(func.count(Presence.cook)).filter(
                Presence.cook.isnot(None)).filter(
                    Presence.user_id ==
                    user.id).first()  # Number of days he eated

            try:
                rapport = round(int(cooked) / int(eat[0]), 2)
            except ValueError:
                rapport = 0

            outputs.append('|{:13}|{:15}|{:12}|{:9}|'.format(
                user.name, cooked, eat[0], rapport))

        outputs.append('```')
        send_info(data['channel'], text='\n'.join(outputs), markdown=True)