카카오톡 플러스친구 스마트채팅 만들기 5 - 식당 선택 & 결과 보기
사용자가 식당 목록 버튼을 선택하면 /message로 전달됩니다. 이를 처리하여 결과를 보여줍니다.
식당 선택
class Message(Resource):
#...생략...
def post(self):
select = Select(self.args)
if self.content == Const.BTN_SELECT_LUNCH:
return select.show_restaurant_list()
# 사용자 입력처리
user = fs.collection(Const.COL_USER).document(self.user_key).get()
user_state = user.get(Const.FIELD_STATE)
if user_state == Const.STATE_SELECT_RESTAURANT:
return select.restaurant_selected()
# default
return Util.show_start_menu()
먼저 정의한 버튼인지 확인합니다. 목록에 없으면 사용자계정에서 상태정보를 읽습니다.
# 사용자 입력처리
user = fs.collection(Const.COL_USER).document(self.user_key).get()
user_state = user.get(Const.FIELD_STATE)
해당 상태에 맞도록 처리합니다. 식당 선택 상태 였으므로, select.restaurant_selected()
함수를 호출하여 처리합니다.
class Select(Args):
def restaurant_selected(self):
user = fs.collection(Const.COL_USER).document(self.user_key).get()
user_group = user.get(Const.FIELD_GROUP)
today = Util.get_day_str()
fs.collection(Const.COL_SELECT).document(user_group).collection(Const.COL_TODAY).document(today).update({
self.user_key: self.content
}, firestore.CreateIfMissingOption(True))
msg = '[{}] 을(를) 선택하였습니다'.format(self.content)
try:
ref = fs.collection(Const.COL_GROUP).document(user_group).get()
restaurants = ref._data.get(Const.FIELD_RESTAURANT)
target = restaurants.get(self.content)
img_src = target.get(Const.FIELD_IMG_SRC)
except:
img_src = None
return Util.show_start_menu(msg, img_src)
사용자의 그룹정보를 얻습니다.
오늘 날짜 정보를 얻습니다. 타임존을 Asia/Seoul
로 설정합니다.
from datetime import datetime, timedelta
import pytz
class Util:
@classmethod
def get_day_str(cls, days=0):
tz = pytz.timezone('Asia/Seoul')
now = datetime.now(tz) + timedelta(days=days)
day_str = now.strftime('%Y.%m.%d')
return day_str
먼저 선택한 정보를 데이터를 입력합니다.
fs.collection(Const.COL_SELECT).document(user_group).collection(Const.COL_TODAY).document(today).update({
self.user_key: self.content
}, firestore.CreateIfMissingOption(True))
다음과 같은 형태로 저장합니다.
select - 그룹 - today - 날짜 - { 사용자키 : 선택식당 }
실데이터를 적용하면 다음과 같습니다.
select - 연구소 - today - 2018.05.01 - { JOcneAEi_23 : '북촌손만두' }
선택한 식당에 이미지 정보가 있는지 확인합니다. 있으면 사용자 선택 결과에 이미지를 같이 보내줍니다.
ref = fs.collection(Const.COL_GROUP).document(user_group).get()
restaurants = ref._data.get(Const.FIELD_RESTAURANT)
target = restaurants.get(self.content)
img_src = target.get(Const.FIELD_IMG_SRC)
return Util.show_start_menu(msg, img_src)
결과 보기
#결과 보기
버튼을 누른 경우를 처리합니다.
코드는 추가된 부분만 작성하도록 하겠습니다.
class Message(Resource):
def post(self):
select = Select(self.args)
result = Result(self.args)
if self.content == Const.BTN_SELECT_LUNCH:
return select.show_restaurant_list()
elif self.content == Const.BTN_SEE_RESULT:
return result.show_result()
result.show_result() 를 구현합니다.
# events/result.py
import operator
from conf.const import Const
from conf.firebaseInit import fs
from conf.util import Util
from events.args import Args
from events.select import Select
class Result(Args):
def show_result(self):
try:
# 해당 그룹에서 가장 많이 나온 순서대로 보여준다.
user = fs.collection(Const.COL_USER).document(self.user_key).get()
user_group = user.get(Const.FIELD_GROUP)
except:
print('Not Found User Group')
return Select(self.args).show_group_list()
today = Util.get_day_str()
today_format = '[{}]'.format(today)
msg_list = [today_format]
result_dict = {}
try:
result = fs.collection(Const.COL_SELECT).document(user_group).collection(Const.COL_TODAY).document(today).get()
for user_key, restaurant in result._data.items():
if restaurant in result_dict:
result_dict[restaurant] += 1
else:
result_dict[restaurant] = 1
sorted_list = sorted(result_dict.items(), key=operator.itemgetter(1))
sorted_list.reverse()
for item in sorted_list:
title = item[0]
count = item[1]
msg_list.append('{}명 : {}'.format(count, title))
except:
print('Error')
msg_list.append('아직 아무도 선택하지 않았습니다.')
rst = {
"message": {
"text": '\n'.join(msg_list)
},
"keyboard": {
"type": "buttons",
"buttons": Const.DEFAULT_KEYBOARD
}
}
return Util.send_response(rst)
먼저 그룹을 확인합니다. 해당 그룹의 그룹원들이 오늘 선택한 내용을 확인해서 많이 나온 순서대로 정렬하여 결과를 보여줍니다.
같은 그룹에 있는 사람들이 점심 식당을 선택하고, 가장 많이 선택된 식당을 보여주는 카카오톡 플러스친구 입니다. 소스 파일은 이곳에서 확인할 수 있습니다.
'Programming > Python' 카테고리의 다른 글
카카오톡 플러스친구 스마트채팅 만들기 7 - 설정 & 그룹 설정 (0) | 2018.05.09 |
---|---|
카카오톡 플러스친구 스마트채팅 만들기 6 - 식당 추가 & 식당 삭제 (0) | 2018.05.08 |
카카오톡 플러스친구 스마트채팅 만들기 4 - 식당 목록 전달 (0) | 2018.05.06 |
카카오톡 플러스친구 스마트채팅 만들기 3 - 데이터 베이스(firestore) (0) | 2018.05.05 |
카카오톡 플러스친구 스마트채팅 만들기 2 - 구조 설계 (0) | 2018.05.04 |
댓글