Esempio n. 1
0
    def ranti_bot():
        command_text = request.data.get('text')
        command_text = command_text.split(' ')
        slack_uid = request.data.get('user_id')
        slackhelper = SlackHelper()
        slack_user_info = slackhelper.user_info(slack_uid)
        actions = Actions(slackhelper, slack_user_info)

        if command_text[0] not in allowed_commands:
            response_body = {
                'text':
                'Invalid Command Sent - `/ranti help` for available commands'
            }

        if command_text[0] == 'help':
            response_body = actions.help()

        if command_text[0] in ['my-task', 'my-tasks']:
            response_body = actions.my_tasks()

        if command_text[0] in ['show-task', 'show-tasks']:
            date = command_text[1]
            response_body = actions.show_tasks(date)

        response = jsonify(response_body)
        response.status_code = 200
        return response
Esempio n. 2
0
    def test_dialog_works(self, mock_slack_api_call):
        mock_slack_api_call.return_value = {
            "ok": "true",
        }

        slack_helper = SlackHelper()

        dialog = {
            "callback_id":
            "ryde-46e2b0",
            "title":
            "Request a Ride",
            "submit_label":
            "Request",
            "state":
            "Limo",
            "elements": [{
                "type": "text",
                "label": "Pickup Location",
                "name": "loc_origin"
            }, {
                "type": "text",
                "label": "Dropoff Location",
                "name": "loc_destination"
            }]
        }

        assert slack_helper.dialog(dialog, "12.ab").get("ok") == "true"
Esempio n. 3
0
	def send():
		slackhelper = SlackHelper()
		slackhelper.post_message('Morning, where are you located today?\nPlease write your location in one line (city, building, floor...)\nIf you need to search for a user, use his username with the @.\nThank you! :smile:', 'DN036B2PJ')
		response_body = {'text': ':)'}
		response = jsonify(response_body)
		response.status_code = 200
		return response
Esempio n. 4
0
 def __init__(self, request):
     BaseController.__init__(self, request)
     self.slackhelper = SlackHelper()
     self.menu_repo = MenuRepo()
     self.meal_repo = MealItemRepo()
     self.engagement_repo = VendorEngagementRepo()
     self.andela_service = AndelaService()
     self.vendor_rating_repo = VendorRatingRepo()
Esempio n. 5
0
	def change():
		text = request.data.get('text')
		slack_uid = request.data.get('user_id')
		slackhelper = SlackHelper()
		slack_user_info = slackhelper.user_info(slack_uid)
		user_name = slack_user_info['user']['name']
		redis_client.set(user_name.encode('utf8'), text)
		response_body = "Your location is stored succesfully as %s" % (text)
		response = jsonify(response_body)
		response.status_code = 200
		return response
Esempio n. 6
0
	def sendall():
		slackhelper = SlackHelper()
		request = slackhelper.get_users_in_channel()
		if request['ok']:
			for item in request['members']:
				print(item['id'])
				slackhelper.post_message('Morning, where are you located today?\nPlease write your location in one line (city, building, floor...)\nIf you need to search for a user, use his username with the @.\nThank you! :smile:', item['id'])
		
		response_body = {'text': ':)'}
		response = jsonify(response_body)
		response.status_code = 200
		return response
Esempio n. 7
0
    def test_find_by_email_works(self, mock_slack_api_call):
        slack_helper = SlackHelper()

        mock_slack_api_call.return_value = {
            "ok": "true",
            "user": {
                "id": "W012A3CDE",
                "name": "spengler",
                "deleted": "false",
                "is_admin": "true",
                "profile": {
                    "email": "*****@*****.**"
                }
            }
        }

        assert slack_helper.find_by_email("*****@*****.**").get(
            "ok") == "true"
        assert slack_helper.find_by_email("*****@*****.**").get("user").get(
            "id") == "W012A3CDE"
        assert slack_helper.find_by_email("*****@*****.**").get("user").get(
            "name") == "spengler"
        assert slack_helper.find_by_email("*****@*****.**").get("user").get(
            "deleted") == "false"
        assert slack_helper.find_by_email("*****@*****.**").get("user").get(
            "is_admin") == "true"
        assert slack_helper.find_by_email("*****@*****.**").get("user").get(
            "profile").get("email") == "*****@*****.**"
Esempio n. 8
0
    def test_post_message_works(self, mock_slack_api_call):
        mock_slack_api_call.return_value = {
            "ok": "true",
            "channel": "Eat",
            "message": "Hi"
        }

        slack_helper = SlackHelper()

        assert slack_helper.post_message(message="Hi",
                                         channel="Roger").get("ok") == "true"
        assert slack_helper.post_message(
            message="Hi", channel="Roger").get("channel") == "Eat"
        assert slack_helper.post_message(
            message="Hi", channel="Roger").get("message") == "Hi"
Esempio n. 9
0
    def test_update_message_works(self, mock_slack_api_call):
        mock_slack_api_call.return_value = {
            "ok": "true",
            "channel": "Eat",
            "text": "Hi again"
        }

        slack_helper = SlackHelper()

        assert slack_helper.update_message(
            msg="Hi", recipient="Roger").get("ok") == "true"
        assert slack_helper.update_message(
            msg="Hi", recipient="Roger").get("channel") == "Eat"
        assert slack_helper.update_message(
            msg="Hi", recipient="Roger").get("text") == "Hi again"
Esempio n. 10
0
    def dbdo():
        command_text = request.data.get('text')
        command_text = command_text.split(' ', 2)
        slack_uid = request.data.get('user_id')
        slackhelper = SlackHelper()
        actions = Actions(slackhelper, slack_uid)

        if command_text[0] not in allowed_commands:
            response_body = {
                'text':
                'Invalid Command Sent - `/dbdo help` for available commands'
            }

        if command_text[0] == 'help':
            response_body = actions.help()

        if command_text[0] in ['database', 'instance']:
            get_db = Database()
            get_db.__enter__()
            info_type = command_text[0]
            response_body = get_db.get_db_info(info_type)

        if command_text[0] == 'oug-city':
            set_city = Database()
            set_city.__enter__()
            name_in = command_text[1]
            city_in = command_text[2]
            response_body = set_city.oug_city(name_in, city_in)

        response = response_body
        return response
Esempio n. 11
0
    def getIpFile():
        ''' Get the command from the post request '''
        command_text = request.data.get('text')
        command_text = command_text.split(' ')
        ''' SlackHelper class instance '''
        slackhelper = SlackHelper()
        ''' Actions instance '''
        actions = Actions(slackhelper)

        ''' Check if provided command is present in the allowed command or not. '''
        if command_text[0] not in allowed_commands:
            response_body = {
                'text': 'Invalid Command. Try /vustat help for available commands'}

        ''' If the command is help, call help function from the actions class '''
        if command_text[0] == 'help':
            response_body = actions.ipfile_help()

        ''' If the command is new, call the ipfile_new function from the action class '''
        if command_text[0] == 'new':
            response_body = actions.ipfile_new()

        ''' Prepare the response, add the response code, and return the object '''
        response = jsonify(response_body)
        response.status_code = 200
        return response
Esempio n. 12
0
	def hackabot():
		command_text = request.data.get('text')
		command_text = command_text.split(' ')
		slack_uid = request.data.get('user_id')
		slackhelper = SlackHelper()
		slack_user_info = slackhelper.user_info(slack_uid)
		actions = Actions(slackhelper, slack_user_info)

		if command_text[0] not in allowed_commands:
			response_body = {'text': 'Invalid Command Sent - `/hackabot help` for available commands'}

		if command_text[0] == 'help':
			response_body = actions.help()

		response = jsonify(response_body)
		response.status_code = 200
		return response
Esempio n. 13
0
    def test_update_message_works(self, mock_slack_api_call):
        mock_slack_api_call.return_value = {
            "ok": "true",
            "channel": "Eat",
            "text": "Hi again"
        }

        slack_helper = SlackHelper()

        assert slack_helper.update_message(
            message="Hi", channel="Roger",
            ts="1405894322.002768").get("ok") == "true"
        assert slack_helper.update_message(
            message="Hi", channel="Roger",
            ts="1405894322.002768").get("channel") == "Eat"
        assert slack_helper.update_message(
            message="Hi", channel="Roger",
            ts="1405894322.002768").get("text") == "Hi again"
Esempio n. 14
0
    def bootcamp_machinelearning():
        HELPER = 'Invalid Command Sent - `/bootcamp_ml help` for available commands'
        response_body = {'text': HELPER}

        command_text = request.data.get('text')
        if command_text is not None:

            command_text = command_text.split(' ')

            slack_uid = request.data.get('user_id')
            slackhelper = SlackHelper()
            slack_user_info = slackhelper.user_info(slack_uid)
            actions = Actions(slackhelper, slack_user_info, bootcamp="ML")

            if command_text[0] not in allowed_commands:
                response_body = {'text': HELPER}

            if command_text[0] == 'register':
                response_body = {'text': actions.register()}

            if command_text[0] == 'unregister':
                response_body = {'text': actions.unregister()}

            if command_text[0] == 'subject':
                response_body = {'text': actions.subject(command_text)}

            if command_text[0] == 'correct':
                response_body = {'text': actions.correction(command_text)}

            if command_text[0] == 'info':
                response_body = {'text': actions.info()}

            if command_text[0] == 'help':
                response_body = {'text': actions.help()}

        response = jsonify(response_body)
        response.status_code = 200
        return response
Esempio n. 15
0
    def imagebot():
        """
        Grabs the data sent through the slackbot and calls the webcrawler with the given information
        """
        command_text = request.data.get('text')
        command_text = command_text.split(' ')
        slackhelper = SlackHelper()
        actions = Actions(slackhelper)

        website = command_text[0]
        tag = command_text[1]
        image_details = command_text[2]

        response_body = actions.find_image(website, tag, image_details)

        response = jsonify(response_body)
        response.status_code = 200
        return response
Esempio n. 16
0
    def vustat():
        ''' if POST request has been received, gather request body data and perform related actions '''
        command_text = request.data.get('text')
        command_text = command_text.split(' ')
        ''' get SlackHelper object '''
        slackhelper = SlackHelper()
        ''' Get Actions class object '''
        actions = Actions(slackhelper)

        ''' Check if provided command is present in the allowed command or not. '''
        if command_text[0] not in allowed_commands:
            response_body = {
                'text': 'Invalid Command. Try /vustat help for available commands'}

        ''' If the command is help, call help function from the actions class '''
        if command_text[0] == 'help':
            response_body = actions.help_vu()

        ''' If the command is 'instances', call instances function from the actions class '''
        if(command_text[0] in ['instance', 'instances']):
            response_body = actions.instances()

        ''' If the command is 'restart', first we need to make sure that there is an instance name present after command
            If not provided, display error, otherwise proceed further with appropriate function call from the actions class '''
        if(command_text[0] == 'restart'):
            if(command_text[1] == '' or command_text[1] == ' '):
                response_body = {
                    'text': 'Invalid Restart Command. Command format: `/vustat restart [instance_label]`'}
            else:
                response_body = actions.restart_instance(command_text[1])

        if(command_text[0] == 'status'):
            if(command_text[1] == '' or command_text[1] == ' '):
                response_body = {
                    'text': 'Invalid Restart Command. Command format: `/vustat status [instance_label]`'}
            else:
                response_body = actions.inst_status(command_text[1])

        ''' Prepare the response, add the response code, and return the object '''
        response = jsonify(response_body)
        response.status_code = 200
        return response
Esempio n. 17
0
    def test_user_info_works(self, mock_slack_api_call):
        mock_slack_api_call.return_value = {
            "ok": "true",
            "user": {
                "id": "W012A3CDE",
                "name": "spengler",
                "deleted": "false",
                "is_admin": "true",
            }
        }

        slack_helper = SlackHelper()

        assert slack_helper.user_info("ururuirn4455").get("ok") == "true"
        assert slack_helper.user_info("ururuirn4455").get("user").get(
            "id") == "W012A3CDE"
        assert slack_helper.user_info("ururuirn4455").get("user").get(
            "name") == "spengler"
        assert slack_helper.user_info("ururuirn4455").get("user").get(
            "deleted") == "false"
        assert slack_helper.user_info("ururuirn4455").get("user").get(
            "is_admin") == "true"
Esempio n. 18
0
def main():
    slackhelper = SlackHelper()
    actions = Actions(slackhelper)
Esempio n. 19
0
from flask import current_app as app
from tabulate import tabulate
from flask_rq2 import RQ
from config import get_env
from app.utils.githelper import GitApi
from app.utils.slackhelper import SlackHelper

rq = RQ()
__slack_helper = SlackHelper()
__git_helper = GitApi()


@rq.job
def pull_request_of_given_repo(args):
    try:
        result = __git_helper.get_pull_request(args['repo'])

        if not result:
            message = app.config['NO_PULL_REQUEST'] + ' for ' + args['repo']
            __slack_helper.send_message(message, args['response_url'])
        else:
            n = 25
            """Chunk the big list into group of 20 as it would be neater to send slack message """
            message = "Hello <@" + args['user_id'] + "> \n"
            message += " *Pending Pull request in " + args['repo'] + "*\n"
            chunk_lists = chunk_list_group(result, n)

            __slack_helper.send_message(message, args['response_url'])

            for chunk_list in chunk_lists:
                message = "```\n" + tabulate(
Esempio n. 20
0
def main():
   slackhelper = SlackHelper()
   actions = Actions(slackhelper)
   actions.stay_alive()
Esempio n. 21
0
	def reaction():
		type = request.data.get('type')
		event = request.data.get('event')
		user_id = event['user']
		channel = event['channel']
		text = event['text']

		if type == 'url_verification':
			response_body = request.data.get('challenge')
		else:
			response_body = 'Hi!'
			if not user_id == bot_id:
				slackhelper = SlackHelper()
				slack_user_info = slackhelper.user_info(user_id)
				user_name = slack_user_info['user']['name']
				clean_user_name = slack_user_info['user']['profile']['real_name_normalized']
				words_to_check = [' close to ',' near ',' next to ',' beside ',' in front of ',' behind ',' on ',' in ',' at ',' on ',' top of ',' within ',' beneath ',' under ','building','bau','basel','kau','kaiseraugst','floor','home','wfh']
				
				print (text)
				if re.search("@(?!\W)", text):
					m = re.findall(r'[@]\w+', text)
					print(m)
					user = m[0]
					print('username: '******'user: '******'user']['profile']['real_name_normalized']
					location = redis_client.get(user[1:]) or 'The user hasn\'t set the location yet'
					if location == 'The user hasn\'t set the location yet':
						slackhelper.post_message(location, channel)
					else:
						slackhelper.post_message("%s:  %s" % (search_clean_user_name, location.decode('utf8')), channel)
				elif any(word.lower() in text.lower() for word in words_to_check):
					slackhelper = SlackHelper()
					print(user_name)
					redis_client.set(user_id, text)
					slackhelper.post_message('Thank you! :smile: I have recorded your location.\nHave a good day!', channel)
				elif 'list' in text:
					if len(redis_client.keys()) > 0:
						list = ''
						print(redis_client.keys())
						for user in redis_client.keys():
							print(user)
							print(slackhelper.user_info(user))
							name =  slackhelper.user_info(user)['user']['profile']['real_name_normalized']
							list = list + name + ': '+ redis_client.get(user).decode('utf8') + '\n'
						slackhelper.post_message(list, user_id)
					else:
						slackhelper.post_message('Sorry, there are no users registered', user_id)

				else:
					slackhelper.post_message('Sorry :disappointed:, I didn\'t understand your request.\n - If you want to add your location, please say in one line where are you located (city, building, floor...)\nIf you need to search for a user use his username with the @.\nThank you! :smile:', channel)

			else:
				print("nothing")
		response = jsonify(response_body)
		response.status_code = 200
		return response
Esempio n. 22
0
def main():
    slackhelper = SlackHelper()
    actions = Actions(slackhelper)
    actions.notify_channel()
Esempio n. 23
0
 def __init__(self):
     self.slack_helper = SlackHelper()
     self.git_helper = GitApi()
Esempio n. 24
0
class BotController(BaseController):
    def __init__(self, request):
        BaseController.__init__(self, request)
        self.slackhelper = SlackHelper()
        self.menu_repo = MenuRepo()
        self.meal_repo = MealItemRepo()
        self.engagement_repo = VendorEngagementRepo()
        self.andela_service = AndelaService()
        self.vendor_rating_repo = VendorRatingRepo()

    def bot(self):
        locations = LocationRepo().fetch_all()
        location_buttons = [{
            'name': 'location',
            'text': f'{location.name}',
            'type': "button",
            'value': location.id
        } for location in locations.items]

        request_buttons = [{
            "text": "",
            "callback_id": "center_selector",
            "color": "#3AA3E3",
            "attachment_type": "default",
            "actions": location_buttons
        }]

        return self.handle_response(slack_response={
            'text': f'Welcome To Andela Eats',
            'attachments': request_buttons
        })

    def interactions(self):
        request_payload, trigger_id = self.post_params('payload', 'trigger_id')
        payload = json.loads(request_payload)

        webhook_url = payload["response_url"]
        slack_id = payload['user']['id']

        if payload['type'] == 'dialog_submission':
            slack_user_info = self.slackhelper.user_info(slack_id)
            slack_user_email = slack_user_info['user']['profile']['email']

            if payload['callback_id'] == 'final_selection':

                state = payload['state'].split('_')
                menu_id = state[0]
                meal_period = state[1]
                date_booked_for = state[2]
                location_id = state[4]
                submitted_values = payload['submission']
                meal_items = [int(v) for k, v in submitted_values.items()]
                meal_items.append(MenuRepo().get(menu_id).main_meal_id)
                meal_items = [
                    meal for meal in MealItemRepo().get_meal_items_by_ids(
                        meal_items)
                ]
                channel = 'slack'

                # Retrieve User Object
                user = self.andela_service.get_user_by_email_or_id(
                    slack_user_email)
                user_id = user['id']

                order = OrderRepo().create_order(
                    user_id=user_id,
                    date_booked_for=date_booked_for,
                    meal_items=meal_items,
                    location_id=location_id,
                    menu_id=menu_id,
                    channel=channel,
                    meal_period=meal_period)

                if order:
                    slack_data = {'text': 'Booking Confirmed!'}
                    requests.post(webhook_url,
                                  data=json.dumps(slack_data),
                                  headers={'Content-Type': 'application/json'})
                else:
                    slack_data = {'text': 'Booking Failed. Please Retry'}
                    requests.post(webhook_url,
                                  data=json.dumps(slack_data),
                                  headers={'Content-Type': 'application/json'})

            if payload['callback_id'] == 'submit_rating':

                state = payload['state'].split('_')
                menu_id = state[0]
                menu = self.menu_repo.get(menu_id)
                service_date = menu.date
                rating_type = RatingType.meal
                type_id = menu.main_meal_id
                engagement_id = menu.vendor_engagement_id
                vendor_id = self.engagement_repo.get(engagement_id).vendor_id
                rating_value = payload['submission']['rating value']
                channel = 'slack'
                comment = payload['submission']['comment']

                # Retrieve User Object
                user = self.andela_service.get_user_by_email_or_id(
                    slack_user_email)
                user_id = user['id']

                rating = self.vendor_rating_repo.new_rating(
                    vendor_id, user_id, rating_value, service_date,
                    rating_type, type_id, engagement_id, channel, comment,
                    type_id)

                if rating:
                    slack_data = {'text': 'Rating Successful!'}
                    requests.post(webhook_url,
                                  data=json.dumps(slack_data),
                                  headers={'Content-Type': 'application/json'})
                else:
                    slack_data = {'text': 'Rating Failed. Please Retry'}
                    requests.post(webhook_url,
                                  data=json.dumps(slack_data),
                                  headers={'Content-Type': 'application/json'})

            return make_response('', 200)

        if payload['type'] == 'interactive_message' and payload[
                'callback_id'] == 'center_selector':
            location_id = payload['actions'][0]['value']

            location = LocationRepo().get(location_id)
            menu_start_end_on = BotController.get_menu_start_end_on(location)
            start_on = menu_start_end_on[0]
            end_on = menu_start_end_on[1]

            date_buttons = [{
                'name':
                'selected_date',
                'type':
                'button',
                'text':
                '{}, {}'.format(day.strftime('%a'), day.strftime('%b %-d')),
                'value':
                '{}_{}'.format(day.strftime('%Y-%m-%d'), location.id)
            } for day in daterange(start_on, end_on)]

            request_buttons = [{
                "text": "",
                "callback_id": "day_selector",
                "color": "#3AA3E3",
                "attachment_type": "default",
                "actions": date_buttons
            }]

            return self.handle_response(slack_response={
                'text': f'Select Date',
                'attachments': request_buttons
            })

        if payload['type'] == 'interactive_message' and payload[
                'callback_id'] == 'day_selector':
            payload_action_value = payload['actions'][0]['value']
            selected_date = payload_action_value.split('_')[0]
            location_id = payload_action_value.split('_')[1]

            period_buttons = [
                # {'name': 'meal_period', 'type': 'button', 'text': 'Breakfast',
                #  'value': 'breakfast_{}'.format(payload_action_value)},
                {
                    'name': 'meal_period',
                    'type': 'button',
                    'text': 'Lunch',
                    'value': 'lunch_{}'.format(payload_action_value)
                }
            ]

            request_buttons = [{
                "text": "",
                "callback_id": "period_selector",
                "color": "#3AA3E3",
                "attachment_type": "default",
                "actions": period_buttons
            }]

            return self.handle_response(slack_response={
                'text': f'Select Meal Period',
                'attachments': request_buttons
            })

        if payload['type'] == 'interactive_message' and payload[
                'callback_id'] == 'period_selector':
            period = payload['actions'][0]['value'].split('_')[0]
            date = payload['actions'][0]['value'].split('_')[1]
            location_id = payload['actions'][0]['value'].split('_')[2]
            actions = {
                "attachments": [{
                    "text":
                    'What do you want to do?',
                    "callback_id":
                    "action_selector",
                    "color":
                    "#3AA3E3",
                    "attachment_type":
                    "default",
                    "actions": [{
                        "name": "main meal",
                        "text": "View Menu List",
                        "type": "button",
                        "value": f'{period}_{date}_menu_{location_id}'
                    }, {
                        "name": "main meal",
                        "text": "Place order",
                        "type": "button",
                        "value": f'{period}_{date}_order_{location_id}'
                    }]
                }]
            }
            return self.handle_response(slack_response=actions)

        if payload['type'] == 'interactive_message' and payload[
                'callback_id'] == 'action_selector':
            payload_action_value = payload['actions'][0]['value']
            if payload_action_value.split('_')[2] == 'menu':
                date = payload_action_value.split('_')[1]
                period = payload_action_value.split('_')[0]
                location_id = payload_action_value.split('_')[3]
                menus = self.menu_repo.get_unpaginated(date=date,
                                                       meal_period=period,
                                                       is_deleted=False)
                if not menus:
                    #   No Menu for provided date
                    back_buttons = [{
                        'name': 'back',
                        'text': 'Back',
                        'type': "button",
                        'value': location_id
                    }]
                    request_buttons = [{
                        "text": "",
                        "callback_id": "center_selector",
                        "color": "#3AA3E3",
                        "attachment_type": "default",
                        "actions": back_buttons
                    }]
                    return self.handle_response(
                        slack_response={
                            'text':
                            f'Sorry No Menu found for Date: {date}, Meal Period: {period}',
                            'attachments': request_buttons
                        })
                text = ''

                for menu in menus:
                    side_items_list = menu.side_items.split(',')
                    protein_items_list = menu.protein_items.split(',')

                    main = self.meal_repo.get(menu.main_meal_id).name
                    sides = [
                        side.name for side in
                        self.meal_repo.get_meal_items_by_ids(side_items_list)
                    ]
                    proteins = [
                        protein.name
                        for protein in self.meal_repo.get_meal_items_by_ids(
                            protein_items_list)
                    ]
                    menu_info = f'Main meal: *{main}*\n Side items: {", ".join(sides)}\nProtein items: {", ".join(proteins)}\n\n\n'
                    text += menu_info

                meals = {
                    "text":
                    f'{period.upper()}',
                    "attachments": [{
                        "text":
                        text,
                        "callback_id":
                        "after_menu_list",
                        "color":
                        "#3AA3E3",
                        "attachment_type":
                        "default",
                        "actions": [{
                            "name":
                            "main meal",
                            "text":
                            "Rate meal",
                            "type":
                            "button",
                            "value":
                            f'{period}_{date}_rate_{location_id}_{location_id}'
                        }, {
                            "name":
                            "main meal",
                            "text":
                            "Place an order",
                            "type":
                            "button",
                            "value":
                            f'{period}_{date}_order_{location_id}_{location_id}'
                        }]
                    }]
                }
                return self.handle_response(slack_response=meals)

        if (payload['type'] == 'interactive_message'
                and payload['callback_id'] == 'action_selector'
                and payload['actions'][0]['value'].split('_')[2] == 'order'
            ) or (payload['callback_id'] == 'after_menu_list'
                  and payload['actions'][0]['value'].split('_')[2] == 'order'):
            payload_action_value = payload['actions'][0]['value']
            meal_period = payload_action_value.split('_')[0]
            selected_date = payload_action_value.split('_')[1]
            location_id = payload_action_value.split('_')[3]
            menus = self.menu_repo.get_unpaginated(date=selected_date,
                                                   meal_period=meal_period,
                                                   is_deleted=False)
            if not menus:
                #   No Menu for provided date
                back_buttons = [{
                    'name': 'back',
                    'text': 'Back',
                    'type': "button",
                    'value': location_id
                }]

                request_buttons = [{
                    "text": "",
                    "callback_id": "center_selector",
                    "color": "#3AA3E3",
                    "attachment_type": "default",
                    "actions": back_buttons
                }]
                return self.handle_response(
                    slack_response={
                        'text':
                        f'Sorry No Menu found for Date: {selected_date}, Meal Period: {meal_period}',
                        'attachments': request_buttons
                    })

            meal_buttons = [{
                'name': 'main_meal',
                'type': 'button',
                'text': f'{menu.main_meal.name}',
                'value': f'{menu.id}_{payload_action_value}'
            } for menu in menus]

            request_buttons = [{
                "text": "",
                "callback_id": "meal_action_selector",
                "color": "#3AA3E3",
                "attachment_type": "default",
                "actions": meal_buttons
            }]

            return self.handle_response(slack_response={
                'text': 'Select Main Meal',
                'attachments': request_buttons
            })

        if payload['type'] == 'interactive_message' and payload[
                'callback_id'] == 'meal_action_selector':
            payload_action_value = payload['actions'][0]['value']
            if payload_action_value.find('order') > -1:
                menu_id = payload_action_value.split('_')[0]
                menu = self.menu_repo.get(menu_id)
                slack_id = payload['user']['id']
                slack_user_info = self.slackhelper.user_info(slack_id)
                slack_user_email = slack_user_info['user']['profile']['email']
                user = self.andela_service.get_user_by_email_or_id(
                    slack_user_email)

                # check if user already has an order
                if OrderRepo().user_has_order(user['id'],
                                              menu.date.strftime('%Y-%m-%d'),
                                              menu.meal_period):
                    slack_data = {
                        'text':
                        'You already have an order for this meal period.'
                    }
                    requests.post(webhook_url,
                                  data=json.dumps(slack_data),
                                  headers={'Content-Type': 'application/json'})
                    return self.handle_response(status_code=400)
                trigger_id = payload['trigger_id']

                side_items_list = menu.side_items.split(',')
                protein_items_list = menu.protein_items.split(',')

                side_items = self.meal_repo.get_meal_items_by_ids(
                    side_items_list)
                protein_items = self.meal_repo.get_meal_items_by_ids(
                    protein_items_list)

                request_dialog_element = []

                for i in range(1, menu.allowed_side + 1):
                    request_dialog_element.append({
                        'label':
                        f'Select Side {i}',
                        'type':
                        'select',
                        'name':
                        f'side_{i}',
                        'options': [{
                            'label': f'{side.name}',
                            'value': f'{side.id}'
                        } for side in side_items]
                    })

                for i in range(1, menu.allowed_protein + 1):
                    request_dialog_element.append({
                        'label':
                        f'Select Protein {i}',
                        'type':
                        'select',
                        'name':
                        f'protein_{i}',
                        'options': [{
                            'label': f'{protein.name}',
                            'value': f'{protein.id}'
                        } for protein in protein_items]
                    })

                state = f'{payload_action_value}'
                self.create_dialog(dialog_elem=request_dialog_element,
                                   trigger_id=trigger_id,
                                   title='Select Protein & Sides',
                                   callback_id='final_selection',
                                   state=state)

                return self.handle_response(
                    slack_response={'text': 'Select Meal Protein and Sides'})

        if payload['callback_id'] == 'after_menu_list' and payload['actions'][
                0]['value'].split('_')[2] == 'rate':

            payload_action_value = payload['actions'][0]['value']
            meal_period = payload_action_value.split('_')[0]
            selected_date = payload_action_value.split('_')[1]
            location_id = payload_action_value.split('_')[2]
            menus = self.menu_repo.get_unpaginated(date=selected_date,
                                                   meal_period=meal_period,
                                                   is_deleted=False)
            if not menus:
                #   No Menu for provided date
                back_buttons = [{
                    'name': 'back',
                    'text': 'Back',
                    'type': "button",
                    'value': location_id
                }]

                request_buttons = [{
                    "text": "",
                    "callback_id": "center_selector",
                    "color": "#3AA3E3",
                    "attachment_type": "default",
                    "actions": back_buttons
                }]
                return self.handle_response(
                    slack_response={
                        'text':
                        f'Sorry No Menu found forr Date: {selected_date}, Meal Period: {meal_period}',
                        'attachments': request_buttons
                    })

            meal_buttons = [{
                'name': 'main_meal',
                'type': 'button',
                'text': f'{menu.main_meal.name}',
                'value': f'{menu.id}_{payload_action_value}'
            } for menu in menus]

            request_buttons = [{
                "text": "",
                "callback_id": "rating_selector",
                "color": "#3AA3E3",
                "attachment_type": "default",
                "actions": meal_buttons
            }]

            return self.handle_response(slack_response={
                'text': 'Select Main Meal',
                'attachments': request_buttons
            })

        if payload['callback_id'] == 'rating_selector':

            menu_id = payload['actions'][0]['value'].split('_')[0]
            menu = self.menu_repo.get(menu_id)
            trigger_id = payload['trigger_id']
            main_meal = menu.main_meal_id

            request_dialog_element = [{
                'label':
                f'Rate meal: {self.meal_repo.get(main_meal).name}',
                'type':
                'select',
                'name':
                'rating value',
                'options': [{
                    'label': f'{value}',
                    'value': f'{value}'
                } for value in range(1, 6)]
            }, {
                'label': 'Add a short comment',
                'type': 'text',
                'name': 'comment'
            }]

            state = f'{payload["actions"][0]["value"]}'
            self.create_dialog(dialog_elem=request_dialog_element,
                               trigger_id=trigger_id,
                               title='Rate a meal',
                               callback_id='submit_rating',
                               state=state)

            return self.handle_response(slack_response={'text': 'Meal rating'})

    def create_dialog(self,
                      dialog_elem,
                      trigger_id,
                      title,
                      callback_id,
                      state=None):
        dialog = {
            "title": title,
            "submit_label": "Submit",
            "callback_id": callback_id,
            "notify_on_cancel": True,
            "state": state,
            "elements": dialog_elem
        }
        return self.slackhelper.dialog(dialog=dialog, trigger_id=trigger_id)

    @staticmethod
    def get_menu_start_end_on(location):
        """This method takes a location id, and attempts to return a start date and an end date based on the conditions
        the application expects.

        Conditions:
            If current datetime is over 3PM , skip a day and return next days.
            If day is thursday and not yet 3PM, return only friday
            If current datetime is friday, saturday or sunday, return next week from monday till friday.
            If No conditions matches, return None for both dates.

        """
        start_on = end_on = None

        current_date = current_time_by_zone(location.zone)

        if current_date.strftime('%a') == 'Mon' and int(
                current_date.strftime('%H')) >= 15:
            start_on = current_date + timedelta(days=2)
            end_on = start_on + timedelta(days=2)

        elif current_date.strftime('%a') == 'Tue' and int(
                current_date.strftime('%H')) >= 15:
            start_on = current_date + timedelta(days=2)
            end_on = start_on + timedelta(days=1)

        elif current_date.strftime('%a') == 'Wed' and int(
                current_date.strftime('%H')) >= 15:
            start_on = end_on = current_date + timedelta(days=2)

        elif current_date.strftime('%a') == 'Thu' and int(
                current_date.strftime('%H')) >= 15:
            start_on = end_on = current_date + timedelta(days=4)

        else:

            start_on = current_date + timedelta(days=1)
            if current_date.strftime('%a') == 'Mon':
                end_on = start_on + timedelta(3)
            if current_date.strftime('%a') == 'Tue':
                end_on = start_on + timedelta(2)
            if current_date.strftime('%a') == 'Wed':
                end_on = start_on + timedelta(1)
            if current_date.strftime('%a') == 'Thu':
                end_on = start_on

            else:
                if current_date.strftime('%a') == 'Fri':
                    start_on = current_date + timedelta(days=3)
                    end_on = current_date + timedelta(days=7)

                if current_date.strftime('%a') == 'Sat':
                    start_on = current_date + timedelta(days=2)
                    end_on = current_date + timedelta(days=6)

                if current_date.strftime('%a') == 'Sun':
                    next_day = 1 if int(
                        current_date.strftime('%H')) < 15 else 2
                    start_on = current_date + timedelta(days=next_day)
                    end_on = current_date + timedelta(days=5)

        return tuple((start_on, end_on))
Esempio n. 25
0
    MessageTrigger(['roxy', 'roxstar'],
                   'roxstar',
                   trigger_type=TriggerType.REACTION),
    MessageTrigger(['sherpa'], 'sherpa', trigger_type=TriggerType.REACTION),
    MessageTrigger(['bean', 'coffee', 'latte', '3bs'],
                   'thosbeans',
                   trigger_type=TriggerType.REACTION),
    MessageTrigger(['lucy'], 'lucy', trigger_type=TriggerType.REACTION),
    MessageTrigger(['mischief'],
                   'lucyintheskywithdiamonds',
                   trigger_type=TriggerType.REACTION),
    MessageTrigger([':f:'], 'f', trigger_type=TriggerType.REACTION),
]

users_dict = {u.name: u for u in users}
sh = SlackHelper()


def dab_message_response(request):
    channel = request['channel']

    kwargs = dict()
    if 'thread_ts' in request:
        kwargs['thread_ts'] = request['thread_ts']

    for user in users:
        if user.reaction_type == ReactionType.ALL or user.reaction_type == ReactionType.ONLY_MENTIONS:
            if sh.name_or_mention_in_msg(request, user):
                sh.add_user_reaction(channel, request['ts'], user)

        if user.reaction_type == ReactionType.ALL or user.reaction_type == ReactionType.ONLY_FROM_USER: