Esempio n. 1
0
def _connect(teamId, bot_token, data):

    timeoutThread = threading.Thread(target=_timeout, args=(teamId, ))
    timeoutThread.start()

    global isRemainTime

    sc = SlackClient(bot_token)
    if sc.rtm_connect():
        print("connected! : " + teamId)

        redis_manager.redis_client.hset('rtm_status_' + teamId, 'status',
                                        SOCKET_STATUS_CONNECTED)
        redis_manager.redis_client.hset('rtm_status_' + teamId, 'expire_time',
                                        time.time() + SOCKET_EXPIRE_TIME)

        worker.delay(data)

        while isRemainTime:
            response = sc.rtm_read()

            if len(response) == 0:
                continue

            # response는 배열로, 여러개가 담겨올수 있음
            for data in response:
                print(data)

                try:
                    if data['type'] == "message" and 'subtype' not in data:
                        if data['text'][0] == '/':
                            continue
                        data['team_id'] = data['team']
                        status_channel = redis_manager.redis_client.get(
                            "status_" + data["channel"])

                        # 게임이 플레이중이라면
                        if status_channel == static.GAME_STATE_PLAYING:
                            print('playing')
                            worker.delay(data)

                except Exception as e:
                    print('error ' + str(e))

        print("socket disconnected")
        redis_manager.redis_client.hset('rtm_status_' + teamId, 'status',
                                        SOCKET_STATUS_IDLE)
        print("kill pid : " + str(os.getpid()))
        #os.kill(os.getpid(), 9)
        sys.exit(1)
    else:
        print("connection failed!")

        redis_manager.redis_client.hset('rtm_status_' + teamId, 'status',
                                        SOCKET_STATUS_RECONNECTING)

        time.sleep(3)
        _connect(teamId, bot_token, data)

    return 0
Esempio n. 2
0
def slack_game_start():

    # TODO : 요청이 들어온 채널의 redis status 체크해서 게임이 이미 시작했으면 게임 플레이를 안하도록 수정 필요
    payload = request.get_data().decode()
    app.logger.info(payload)
    data = {}

    teamId = request.form.get('team_id')
    teamLang = util.get_team_lang(teamId)

    data['team_id'] = request.form.get('team_id')
    data['channel'] = request.form.get('channel_id')
    data['text'] = static.GAME_COMMAND_START
    data['user'] = request.form.get('user_id')
    data['mode'] = "normal"
    redis_manager.redis_client.set(
        'game_mode_' + request.form.get('channel_id'), "normal")

    game_state = redis_manager.redis_client.get("status_" + data['channel'])
    app.logger.info(game_state)

    if game_state == None or game_state == static.GAME_STATE_IDLE:
        # 현재 채널 상태 설정
        redis_manager.redis_client.set("status_" + data["channel"],
                                       static.GAME_STATE_LOADING)

        app.logger.info("rtm status : " +
                        str(rtm_manager.is_socket_opened(teamId)))
        if rtm_manager.is_socket_opened(teamId) != static.SOCKET_STATUS_IDLE:
            redis_manager.redis_client.hset(
                'rtm_status_' + teamId, 'expire_time',
                time.time() + static.SOCKET_EXPIRE_TIME)
            redis_manager.redis_client.set("status_" + data["channel"],
                                           static.GAME_STATE_LOADING),

            print('start')
            worker.delay(data)
        else:
            rtm_manager.open_new_socket(teamId, data)

        response = Response(
            json.dumps({
                'response_type': 'in_channel',
                'text': ''
            }))
        response.headers['Content-type'] = 'application/json'
        return response
    else:

        response = Response(
            json.dumps({
                'response_type':
                'in_channel',
                'text':
                static.getText(static.CODE_TEXT_ALREADY_STARTED, teamLang),
                'as_user':
                '******'
            }))
        response.headers['Content-type'] = 'application/json'
        return response
Esempio n. 3
0
def slack_game_exit():
    payload = request.get_data().decode()
    app.logger.info(payload)
    data = {}
    data['team_id'] = request.form.get('team_id')
    data['channel'] = request.form.get('channel_id')
    data['text'] = static.GAME_COMMAND_EXIT
    data['user'] = request.form.get('user_id')

    worker.delay(data)

    response = Response(json.dumps({
        'response_type': 'in_channel',
        'text': ''
    }))
    response.headers['Content-type'] = 'application/json'
    return response
Esempio n. 4
0
def slack_game_kok():
    payload = request.get_data().decode()
    app.logger.info(payload)
    data = {}
    data['team_id'] = request.form.get('team_id')
    data['channel'] = request.form.get('channel_id')
    data['text'] = static.GAME_COMMAND_KOK
    data['user'] = request.form.get('user_id')

    teamId = request.form.get('team_id')
    teamLang = util.get_team_lang(teamId)

    if redis_manager.redis_client.get('kokstatus_' + data["channel"]) == "1":

        response = Response(
            json.dumps({
                'response_type':
                'in_channel',
                'text':
                static.getText(static.CODE_TEXT_ALREADY_STARTED, teamLang)
            }))
        response.headers['Content-type'] = 'application/json'
    else:

        if rtm_manager.is_socket_opened(teamId) != static.SOCKET_STATUS_IDLE:
            redis_manager.redis_client.hset(
                'rtm_status_' + teamId, 'expire_time',
                time.time() + static.SOCKET_EXPIRE_TIME)
            redis_manager.redis_client.set("status_" + data["channel"],
                                           static.GAME_STATE_LOADING),

            redis_manager.redis_client.set('kokstatus_' + data["channel"], "1")
            print('start')
            worker.delay(data)
        else:
            rtm_manager.open_new_socket(teamId, data)

        response = Response(
            json.dumps({
                'response_type': 'in_channel',
                'text': ''
            }))
        response.headers['Content-type'] = 'application/json'
    return response
Esempio n. 5
0
def slack_event():
    payload = request.get_data().decode()
    data = json.loads(payload)

    app.logger.info(data)
    print("event : " + str(data))
    return 'hello'
    worker.delay(eventData)

    response = {}
    response['ok'] = 'True'

    if data['type'] == 'url_verification':
        response['challenge'] = data['challenge']

    elif data['type'] == 'event_callback':
        # worker.delay(data['event'])
        eventData = data['event']
        #eventData에 팀 아이디 추
        eventData["team_id"] = data['team_id']

        if eventData['type'] == "message" and 'subtype' not in data[
                'event'] and 'text' in data['event']:

            status_channel = redis_manager.redis_client.get(
                "status_" + eventData["channel"])
            # redis_manager.redis_client.set("status_" + eventData["channel"], static.GAME_STATE_IDLE)
            # app.logger.info('status_channel => '+ㄴㅅstatic.GAME_STATE_IDLE)

            # 강제종료 명령을 최우선으로 처리함
            if eventData["text"] == static.GAME_COMMAND_EXIT:
                app.logger.info('.exit')
                worker.delay(eventData)
                return (json.dumps(response))
            # 게임이 플레이중이라면
            if status_channel == static.GAME_STATE_PLAYING:
                if eventData["text"][0] == ".":
                    return (json.dumps(response))
                app.logger.info('playing')
                worker.delay(eventData)

            # 게임 플레이중이 아니라면
            elif status_channel == static.GAME_STATE_IDLE or status_channel == None:
                app.logger.info('commend')
                if eventData["text"] == static.GAME_COMMAND_START:
                    app.logger.info('.start')
                    worker.delay(eventData)
                elif eventData["text"] == static.GAME_COMMAND_SCORE:
                    app.logger.info('.rank')
                    worker.delay(eventData)
                elif eventData["text"] == static.GAME_COMMAND_MY_RANK:
                    app.logger.info('.myrank')
                    worker.delay(eventData)
                elif eventData["type"] == "channel_joined":
                    app.logger.info('others')
                    worker.delay(eventData)
    app.logger.info(json.dumps(response))
    return json.dumps(response)