コード例 #1
0
def lambda_handler(event, context):
    print event
    query_string = event['params']['querystring']

    code = query_string['code']
    state = query_string['state']

    payload = {'client_id': conf.CLIENT_ID, 'client_secret': conf.CLIENT_SECRET, 'code': code}
    response = bopbot_util.send_request_to_slack(url=conf.OAUTH_ACCESS, parameter=payload)
    print response

    if not response:
        print 'send request failed'
        raise Exception("Bad Request")

    if type(response) == str:
        response = json.loads(response)

    try:
        access_token = response['access_token']
        team_id = response['team_id']
        team_name = response['team_name']
        user_id = response['user_id']
        bot_dict = response['bot']
        bot_id = bot_dict['bot_user_id']
        bot_token = bot_dict['bot_access_token']
    except KeyError, e:
        print e
        print 'Response: %s' % response
        raise Exception("Bad Request: %s" % e)
コード例 #2
0
def install_im_open(bot_token):
    payload = {'token': bot_token, 'exclude_archived': 1}
    url = 'https://slack.com/api/channels.list'

    response = bopbot_util.send_request_to_slack(url=url, parameter=payload)
    if not response:
        print 'Get slack channel list failed'
        return

    # response = json.loads(response)

    try:
        channels = response['channels']
        for channel in channels:
            if channel['is_general']:
                channel_id = channel['id']
                url = 'https://slack.com/api/channels.info'
                payload = {'token': bot_token, 'channel': channel_id}
                response = bopbot_util.send_request_to_slack(url=url, parameter=payload)

                if not response:
                    return

                # response = json.loads(response)

                channel = response['channel']
                members = channel['members']

                params = []
                url = 'https://slack.com/api/im.open'
                for member in members:
                    payload = {'token': bot_token, 'user': member}
                    param = (url, payload)
                    params.append(param)

                return bopbot_util.send_request_with_multiprocessing_pool(4, params)
    except Exception, e:
        print 'IM open failed %s' % e
コード例 #3
0
def clicked_simple_demo_more_options(user_id, bot_token):
    """
    :param user_id:
    :param bot_token:
    :return:
    """
    payload = bopbot_util.get_dict_for_slack_post_request(
        token=bot_token,
        channel=user_id,
        as_user='******',
    )
    payload.update(
        make_tutorial_restaurant_list(callback_id='simple_demo_send_the_poll',
                                      phrase_key='tutorial_4',
                                      is_title=False))

    return bopbot_util.send_request_to_slack(url=conf.CHAT_POST_MESSAGE,
                                             parameter=payload)
コード例 #4
0
def clicked_simple_demo_send_the_poll(user_id, bot_token):
    """

    :param user_id:
    :param bot_token:
    :return:
    """
    user_table = conf.aws_dynamo_db.Table(conf.USER_STATUS_TABLE)
    user_table.put_item(Item={'User_id': user_id})

    phrase = bopbot_util.get_phrase('tutorial_5')
    payload = bopbot_util.get_dict_for_slack_post_request(token=bot_token,
                                                          channel=user_id,
                                                          as_user='******',
                                                          text=phrase)
    payload.update({'mrkdwn': 'true'})

    return bopbot_util.send_request_to_slack(url=conf.CHAT_POST_MESSAGE,
                                             parameter=payload)
コード例 #5
0
def clicked_send_the_poll_button(bot_token, user_id):
    phrase = bopbot_util.get_phrase('invite')
    item = user_table.get_item_from_table(key={'User_id': user_id})
    if 'Current_list' not in item:
        return

    user_table.update_item_to_table(key={'User_id': user_id},
                                    attribute_updates={
                                        'Status': {
                                            'Action': 'PUT',
                                            'Value': 'wte_invitation'
                                        }
                                    })

    payload = bopbot_util.get_dict_for_slack_post_request(token=bot_token,
                                                          channel=user_id,
                                                          text=phrase)
    return bopbot_util.send_request_to_slack(url=conf.CHAT_POST_MESSAGE,
                                             parameter=payload)
コード例 #6
0
def send_start_demo_message(user_id, bot_token):
    """
    :rtype: object
    :param user_id:
    :param bot_token:
    :return:
    """
    try:
        user_table = conf.aws_dynamo_db.Table(conf.USER_STATUS_TABLE)
        user_table.put_item(Item={'User_id': user_id, 'Status': 'tutorial'})

        callback_id = 'simple_demo_start'
        button = bopbot_util.interactive_buttons[callback_id][0]
        action = {
            'name': button,
            'text': button,
            'type': 'button',
            'value': button
        }

        attachments = [
            bopbot_util.make_im_button_attachment(text='#Simple demo',
                                                  callback_id=callback_id,
                                                  actions=[action])
        ]

        attachments = json.dumps(attachments)

        phrase = bopbot_util.get_phrase('tutorial_1')

        payload = bopbot_util.get_dict_for_slack_post_request(
            token=bot_token,
            channel=user_id,
            text=phrase,
            attachments=attachments,
            as_user='******')

        return bopbot_util.send_request_to_slack(url=conf.CHAT_POST_MESSAGE,
                                                 parameter=payload)
    except Exception, e:
        print e
        return
コード例 #7
0
def clicked_simple_demo_start(team_id, user_id, bot_token):
    """
    :param team_id:
    :param user_id:
    :param bot_token:
    :return:
    """
    payload = bopbot_util.get_dict_for_slack_post_request(token=bot_token,
                                                          channel=user_id,
                                                          as_user='******')

    team_table = conf.aws_dynamo_db.Table(conf.SLACK_TEAM_TABLE)
    response = team_table.get_item(Key={
        'Team_id': team_id,
        'User_id': user_id
    })
    item = response['Item']

    if 'Access_token' in item:
        payload.update(
            make_tutorial_restaurant_list('simple_demo_more_options',
                                          'tutorial_3'))
    else:
        phrase = bopbot_util.get_phrase('tutorial_auth')
        attachments = [{
            'title':
            'Authorization',
            'title_link':
            'https://slack.com/oauth/authorize?scope=bot,channels:write,im:write,im:history,reminders:write&state=%s&client_id=%s'
            % ('tutorial', conf.CLIENT_ID)
        }]
        attachments = json.dumps(attachments)

        payload.update({'text': phrase, 'attachments': attachments})

    return bopbot_util.send_request_to_slack(url=conf.CHAT_POST_MESSAGE,
                                             parameter=payload)
コード例 #8
0
        if menu_name == bopbot_util.interactive_buttons[callback][0]:
            user_table.put_item_to_table(item={
                'User_id': user_id,
                'Channel_id': channel_id,
                'Status': 'reminder'
            })

            phrase = bopbot_util.get_phrase('reminder_add')
            payload = {
                'token': bot_token,
                'channel': channel,
                'as_user': '******',
                'text': phrase
            }
            response = bopbot_util.send_request_to_slack(
                url=conf.CHAT_POST_MESSAGE, parameter=payload)
            print 'reminder response %s' % response
            return response
        elif menu_name == bopbot_util.interactive_buttons[callback][1]:
            user_table.put_item_to_table(item={'User_id': user_id})
            payload = bopbot_util.make_archive_payload(bot_token=bot_token,
                                                       user_id=user_id,
                                                       channel=channel_id)
            return bopbot_util.send_request_to_slack(
                url=conf.CHAT_POST_MESSAGE, parameter=payload)

    elif callback == 'archive_channel':
        if menu_name == bopbot_util.interactive_buttons[callback][0]:
            #archive
            channel_id = str(actions[0]['value'])
コード例 #9
0
        print response

        if 'Item' in response:
            item = response['Item']
            if 'Status' in item and item['Status'] == 'tutorial':
                bopbot_tutorial.clicked_simple_demo_start(team_id=team_id, user_id=user_id, bot_token=bot_token)

    elif state == 'install':
        install_im_open(bot_token=bot_token)
        response = bopbot_tutorial.send_start_demo_message(user_id=user_id, bot_token=bot_token)
        print 'app install %s' % response

    else:
        phrase = bopbot_util.get_phrase('main_auth_success')
        payload = bopbot_util.get_dict_for_slack_post_request(token=bot_token, channel=user_id, text=phrase)
        bopbot_util.send_request_to_slack(url=conf.CHAT_POST_MESSAGE, parameter=payload)

        payload = {
            'team_id': team_id,
            'event': {
                'channel': user_id,
                'user': user_id,
                'ts': state,
                'text': 'what to eat'
            }
        }

        conf.aws_sns.publish(
            TopicArn=conf.aws_sns_event_arn,
            Message=json.dumps({'default': json.dumps(payload)}),
            MessageStructure='json'
コード例 #10
0
def complete_poll_event(response, message_ts, channel_id, channel_name,
                        bot_token, user_id):
    # poll 메시지 업데이트. 버튼들 제거.
    attachments = response['message']['attachments']
    update_attachments = list()
    for attachment in attachments:
        if 'actions' not in attachment:
            update_attachments.append(attachment)

    update_attachments = json.dumps(update_attachments)
    payload = {
        'token': bot_token,
        'ts': message_ts,
        'channel': response['channel'],
        'text': response['message']['text'],
        'attachments': update_attachments
    }
    bopbot_util.send_request_to_slack(url='https://slack.com/api/chat.update',
                                      parameter=payload)

    button_actions = attachments[len(attachments) - 1]['actions']

    result = get_decision_from_button_list(message_ts, button_actions)

    decision_list = result['Decision']
    vote_result_attachments = result['Attachments']
    user_id_list = result['Users']

    vote_result_attachments = json.dumps(vote_result_attachments)

    payload = {
        "token": str(bot_token),
        "channel": channel_id,
        "as_user": "******",
        'text': 'Result',
        'attachments': vote_result_attachments
    }
    print bopbot_util.send_request_to_slack(url=conf.CHAT_POST_MESSAGE,
                                            parameter=payload)

    # joke
    if len(user_id_list) == 0:
        phrase = bopbot_util.get_phrase('poll_joke')

        payload = {
            "token": str(bot_token),
            "channel": channel_id,
            "as_user": "******",
            'text': phrase
        }
        print bopbot_util.send_request_to_slack(url=conf.CHAT_POST_MESSAGE,
                                                parameter=payload)

    else:
        index = randint(0, len(decision_list) - 1)
        decision = decision_list[index]
        location = decision['Location']
        yelp_id = decision['Yelp_id']
        name = '*' + decision['Name'] + '*'

        if len(decision_list) > 1:
            phrase = bopbot_util.get_phrase('poll_tied')
            text = phrase % (len(decision_list), name)
        else:
            phrase = bopbot_util.get_phrase('poll_result')
            text = phrase % name
        print text

        restaurant_table = conf.aws_dynamo_db.Table(conf.RESTAURANT_TABLE)

        item = restaurant_table.get_item(Key={
            'Location': location,
            'Yelp_id': yelp_id
        })['Item']

        channel_table = BopBotDatabase(table=conf.CHANNEL_POLL_TABLE)
        channel_table.update_item_to_table(
            key={'Channel_id': channel_id},
            attribute_updates={
                'Location': {
                    'Action': 'PUT',
                    'Value': item['Location'].encode('utf8')
                },
                'User_id': {
                    'Action': 'PUT',
                    'Value': user_id
                },
                'Yelp_id': {
                    'Action': 'PUT',
                    'Value': item['Yelp_id'].encode('utf8')
                },
                'lat': {
                    'Action': 'PUT',
                    'Value': item['location']['coordinate']['lat']
                },
                'lng': {
                    'Action': 'PUT',
                    'Value': item['location']['coordinate']['lng']
                },
                'Message_ts': {
                    'Action': 'PUT',
                    'Value': message_ts
                }
            })
        restaurant_attachment = bopbot_util.make_restaurant_list_attachments(
            [item])
        restaurant_attachment = json.dumps(restaurant_attachment)

        payload = {
            'token': bot_token,
            'channel': channel_id,
            'as_user': '******',
            'text': text,
            'attachments': restaurant_attachment
        }
        print bopbot_util.send_request_to_slack(url=conf.CHAT_POST_MESSAGE,
                                                parameter=payload)

        phrase = bopbot_util.get_phrase('reminder_1')
        text = phrase % name
        payload = {
            "token": bot_token,
            "channel": user_id,
            "as_user": "******",
            'text': text
        }

        reminder_param = {
            'channel': channel_id,
            'channel_name': channel_name,
            'decision': name
        }
        reminder_param = json.dumps(reminder_param)

        actions = []
        for button in bopbot_util.interactive_buttons['reminder_menu']:
            action = bopbot_util.make_im_button(name=button,
                                                text=button,
                                                value=reminder_param)
            actions.append(action)

        reminder_attachments = [
            bopbot_util.make_im_button_attachment(callback_id='reminder_menu',
                                                  actions=actions)
        ]
        reminder_attachments = json.dumps(reminder_attachments)
        payload.update({'attachments': reminder_attachments})
        bopbot_util.send_request_to_slack(url=conf.CHAT_POST_MESSAGE,
                                          parameter=payload)

    return response