def get(cls): logger = HenriqueLogger.func_level2logger(cls.get, logging.DEBUG) sender_name = request.args.get(cls.Data.Field.SENDER_NAME) text_in = request.args.get(cls.Data.Field.TEXT) newline = request.args.get(cls.Data.Field.NEWLINE) logger.debug({"sender_name":sender_name, "text_in":text_in, "newline":newline}) if not HenriqueCommand.text2is_query(text_in): return None chatroom = ChatroomKakaotalk.chatroom() Chatroom.chatrooms2upsert([chatroom]) channel_user = ChannelUserKakaotalk.sender_name2channel_user(sender_name) ChannelUser.channel_users2upsert([channel_user]) packet = {KhalaPacket.Field.TEXT: text_in, KhalaPacket.Field.CHATROOM: Chatroom.chatroom2codename(chatroom), KhalaPacket.Field.CHANNEL_USER: ChannelUser.channel_user2codename(channel_user), KhalaPacket.Field.SENDER_NAME: sender_name, } logger.debug({"packet": packet,}) text_response = HenriquePacket.packet2response(packet) if not text_response: return None if cls.packet2skip_response(packet): # run packet but do not respond return None text_out = newline.join(text_response.splitlines()) if newline else text_response return text_out, 200
def test_01(self): Chatroom.chatrooms2upsert([ChatroomKakaotalk.chatroom()]) sender_name = "iris" channel_user_codename = ChannelUserKakaotalk.sender_name2codename( sender_name) ChannelUser.channel_users2upsert( [ChannelUserKakaotalk.sender_name2channel_user(sender_name)]) # collection = ChannelUserCollection.collection() # collection.delete_one({ChannelUser.Field.CODENAME: channel_user_codename}) packet = { KhalaPacket.Field.TEXT: "?price 사탕무 리스본 120ㅅ", KhalaPacket.Field.CHATROOM: KakaotalkUWOChatroom.codename(), KhalaPacket.Field.CHANNEL_USER: channel_user_codename, KhalaPacket.Field.SENDER_NAME: sender_name, } PriceSkill.packet2response(packet) collection = ChannelUserCollection.collection() channel_user_doc = MongoDBTool.bson2json( collection.find_one( {ChannelUser.Field.CODENAME: channel_user_codename})) hyp = MongoDBTool.doc2id_excluded(channel_user_doc, ) ref = { 'channel': 'kakaotalk_uwo', 'codename': 'kakaotalk_uwo.iris', 'alias': 'iris' } # pprint(hyp) self.assertEqual(hyp, ref)
def price_lang2text(cls, price, lang): logger = HenriqueLogger.func_level2logger(cls.price_lang2text, logging.DEBUG) if price is None: return cls.lang2text_idk(lang) rate = MarketpriceDoc.price2rate(price) trend = MarketpriceDoc.price2trend(price) # raise Exception({"price":price}) channel_user_codename = MarketpriceDoc.price2channel_user(price) channel_user = l_singleton2obj( ChannelUser.codenames2channel_users([channel_user_codename])) logger.debug({"price": price, "channel_user": channel_user}) # raise Exception({"price":price}) created_at = MarketpriceDoc.price2created_at( price) or MarketpriceDoc.created_at_backoff() td = datetime.now(tz=pytz.utc) - created_at str_timedelta = HenriqueDatetime.timedelta_lang2str(td, lang) arrow = Trend.trend2arrow(trend) text_out_base = format_str("{}{} @ {}", str(rate), arrow, str_timedelta) if td >= HenriqueDatetime.Constant.TIMEDELTA_OUTDATED: return text_out_base user_alias = ChannelUser.channel_user2alias(channel_user) str_user_alias = "[by {}]".format(user_alias) text_out = " ".join([text_out_base, str_user_alias]) return text_out
def test_04(self): cls = self.__class__ Chatroom.chatrooms2upsert([ChatroomKakaotalk.chatroom()]) sender_name = "iris" channel_user_codename = ChannelUserKakaotalk.sender_name2codename( sender_name) ChannelUser.channel_users2upsert( [ChannelUserKakaotalk.sender_name2channel_user(sender_name)]) # now_utc = datetime.now(pytz.utc) packet = { KhalaPacket.Field.TEXT: "?남만", KhalaPacket.Field.CHATROOM: KakaotalkUWOChatroom.codename(), KhalaPacket.Field.CHANNEL_USER: channel_user_codename, KhalaPacket.Field.SENDER_NAME: sender_name, } response = NanbanSkill.packet2response(packet) hyp = response.splitlines()[0] # utc_nanban = now_utc + NanbanTimedelta.period() # tz = pytz.timezone("Asia/Seoul") # now_tz = DatetimeTool.astimezone(now_utc, tz) # now_nanban = DatetimeTool.astimezone(utc_nanban, tz) ref = """[남만시각] 글로벌서버""" # pprint(response) self.assertEqual(hyp, ref)
def test_05(self): Chatroom.chatrooms2upsert([ChatroomKakaotalk.chatroom()]) ServerDoc.codenames2delete([Server.Codename.MARIS]) sender_name = "iris" channel_user_codename = ChannelUserKakaotalk.sender_name2codename( sender_name) ChannelUser.channel_users2upsert( [ChannelUserKakaotalk.sender_name2channel_user(sender_name)]) # now_utc = datetime.now(pytz.utc) packet = { KhalaPacket.Field.TEXT: "?남만 +2분", KhalaPacket.Field.CHATROOM: KakaotalkUWOChatroom.codename(), KhalaPacket.Field.CHANNEL_USER: channel_user_codename, KhalaPacket.Field.SENDER_NAME: sender_name, } with self.assertRaises(HenriqueCommandError) as context: NanbanSkill.packet2response(packet) self.assertEquals( """[남만시각] 이전에 설정된 남만 시각이 없어서 +/-로 남만 시각을 조정할 수 없어요.""", str(context.exception)) if HenriqueEnv.env() == HenriqueEnv.Value.LOCAL: return # cannot test here because LOCAL has different settings hyp = HenriquePacket.packet2response(packet) ref = "[남만시각] 이전에 설정된 남만 시각이 없어서 +/-로 남만 시각을 조정할 수 없어요." # pprint(hyp) self.assertEqual(hyp, ref)
def test_06(self): Chatroom.chatrooms2upsert([ChatroomKakaotalk.chatroom()]) sender_name = "iris" channel_user_codename = ChannelUserKakaotalk.sender_name2codename(sender_name) ChannelUser.channel_users2upsert([ChannelUserKakaotalk.sender_name2channel_user(sender_name)]) # server = "maris" # ports = ["Lisbon"] # tradegoods = ["Sugar Beet"] # # MarketpriceDoc.server_ports_tradegoods2delete(server, ports, tradegoods) # channel = Channel.Codename.KAKAOTALK_UWO_UWO # discord packet = {KhalaPacket.Field.TEXT: "?시세 사탕무 : 말세80ㅎ; 사사리75ㅎ; 시라130ㅅ;", KhalaPacket.Field.CHATROOM: KakaotalkUWOChatroom.codename(), KhalaPacket.Field.CHANNEL_USER: channel_user_codename, KhalaPacket.Field.SENDER_NAME: sender_name, } hyp_01 = PriceSkill.packet2response(packet) ref_01 = """[사탕무] 시세 시라쿠사 130↗ @ 방금전 [by iris] 마르세이유 80↘ @ 방금전 [by iris] 사사리 75↘ @ 방금전 [by iris]""" # pprint(hyp_01) self.assertEqual(hyp_01, ref_01)
def test_02(self): chatroom = { 'channel': 'discord', 'codename': 'discord-471024213159837696', 'locale': 'ko-KR' } Chatroom.chatrooms2upsert([chatroom]) channel_user = { 'channel': 'discord', 'codename': 'discord-340205035558535169', 'alias': 'yeri' } ChannelUser.channel_users2upsert([channel_user]) packet = { 'text': '?ㅎㄱ 육두구', 'chatroom': 'discord-471024213159837696', 'channel_user': '******', 'sender_name': 'yeri', } hyp = HenriquePacket.packet2response(packet) ref = """[항구] 육두구 취급항 - 룬, 암보이나""" # pprint(hyp) self.assertEqual(hyp, ref)
async def on_message(cls, message): from henrique.main.singleton.khala.henrique_khala import HenriquePacket from khala.singleton.messenger.discord.internal.packet_discord import PacketDiscord from khala.singleton.messenger.discord.internal.chatroom_discord import ChatroomDiscord from henrique.main.singleton.khala.henrique_khala import HenriqueCommand logger = KhalaLogger.func_level2logger(cls.on_message, logging.DEBUG) client = cls.client() text_in = message.content logger.debug({"message": message, }) if DiscordTool.user_message2is_author(client.user, message): return if not HenriqueCommand.text2is_query(text_in): return Chatroom.chatrooms2upsert([ChatroomDiscord.message2chatroom(message)]) ChannelUser.channel_users2upsert([ChannelUserDiscord.message2channel_user(message)]) packet = PacketDiscord.message2packet(message) logger.debug({"packet": packet, }) text_out = HenriquePacket.packet2response(packet) await message.channel.send(text_out)
def test_05(self): Chatroom.chatrooms2upsert([ChatroomKakaotalk.chatroom()]) sender_name = "iris" channel_user_codename = ChannelUserKakaotalk.sender_name2codename(sender_name) ChannelUser.channel_users2upsert([ChannelUserKakaotalk.sender_name2channel_user(sender_name)]) dt_now = datetime.now(pytz.utc) port = "Lisbon" tradegood = "Sugar Beet" server = Server.Codename.MARIS # channel_user = '******' def insert_docs(): collection = MarketpriceCollection.collection() doc_old = {MarketpriceDoc.Field.CREATED_AT: dt_now - timedelta(hours=10), MarketpriceDoc.Field.PORT: "Lisbon", MarketpriceDoc.Field.TRADEGOOD: tradegood, MarketpriceDoc.Field.RATE: 120, MarketpriceDoc.Field.TREND: Trend.Value.RISE, MarketpriceDoc.Field.SERVER: server, MarketpriceDoc.Field.CHANNEL_USER: channel_user_codename, } doc_new = {MarketpriceDoc.Field.CREATED_AT: dt_now, MarketpriceDoc.Field.PORT: "Seville", MarketpriceDoc.Field.TRADEGOOD: tradegood, MarketpriceDoc.Field.RATE: 60, MarketpriceDoc.Field.TREND: Trend.Value.RISE, MarketpriceDoc.Field.SERVER: server, MarketpriceDoc.Field.CHANNEL_USER: channel_user_codename, } collection.insert_many([doc_old, doc_new]) MarketpriceDoc.server_ports_tradegoods2delete(server, [port], [tradegood]) insert_docs() packet = {KhalaPacket.Field.TEXT: "?price 리스본,세비야 사탕무", KhalaPacket.Field.CHATROOM: KakaotalkUWOChatroom.codename(), KhalaPacket.Field.CHANNEL_USER: channel_user_codename, KhalaPacket.Field.SENDER_NAME: sender_name, } hyp = NORM_LIST(PriceSkill.packet2rowsblocks(packet)) ref = [('[사탕무] 시세', ['세비야', '리스본'])] # pprint(hyp) self.assertEqual(hyp, ref)
def test_06(self): logger = HenriqueLogger.func_level2logger(self.test_06, logging.DEBUG) Chatroom.chatrooms2upsert([ChatroomKakaotalk.chatroom()]) ServerDoc.codenames2delete([Server.Codename.MARIS]) sender_name = "iris" channel_user_codename = ChannelUserKakaotalk.sender_name2codename( sender_name) ChannelUser.channel_users2upsert( [ChannelUserKakaotalk.sender_name2channel_user(sender_name)]) tz = pytz.timezone("Asia/Seoul") now_tz = DatetimeTool.datetime2truncate_seconds(datetime.now(tz)) # hour = (now_tz + timedelta(seconds=3600)).hour packet1 = { KhalaPacket.Field.TEXT: "?남만 {}".format(now_tz.strftime("%I:%M %p")), KhalaPacket.Field.CHATROOM: KakaotalkUWOChatroom.codename(), KhalaPacket.Field.CHANNEL_USER: channel_user_codename, KhalaPacket.Field.SENDER_NAME: sender_name, } NanbanSkill.packet2response(packet1) packet2 = { KhalaPacket.Field.TEXT: "?남만 +2분 1초", KhalaPacket.Field.CHATROOM: KakaotalkUWOChatroom.codename(), KhalaPacket.Field.CHANNEL_USER: channel_user_codename, KhalaPacket.Field.SENDER_NAME: sender_name, } NanbanSkill.packet2response(packet2) doc = ServerDoc.codename2doc(Server.Codename.MARIS) dt_nanban = DatetimeTool.astimezone( ServerNanban.nanban2datetime(ServerDoc.doc2nanban(doc)), tz) logger.debug({ "now_tz": now_tz, "dt_nanban": dt_nanban, 'now_tz.strftime("%I:%M %p")': now_tz.strftime("%I:%M %p"), }) ref = (now_tz + timedelta(seconds=2 * 60 + 1)).timetz() self.assertEquals(dt_nanban.timetz(), ref)
def test_03(self): logger = HenriqueLogger.func_level2logger(self.test_02, logging.DEBUG) Chatroom.chatrooms2upsert([ChatroomKakaotalk.chatroom()]) sender_name = "iris" channel_user_codename = ChannelUserKakaotalk.sender_name2codename( sender_name) ChannelUser.channel_users2upsert( [ChannelUserKakaotalk.sender_name2channel_user(sender_name)]) now_seoul = datetime.now( tz=pytz.timezone(HenriqueLocale.lang2tzdb("ko"))) dt_target = now_seoul - timedelta(seconds=3 * 60) text = "?남만 {}".format(dt_target.strftime("%I:%M %p").lstrip("0")) logger.debug({ "text": text, "now_seoul": now_seoul, }) packet = { KhalaPacket.Field.TEXT: text, KhalaPacket.Field.CHATROOM: KakaotalkUWOChatroom.codename(), KhalaPacket.Field.CHANNEL_USER: channel_user_codename, KhalaPacket.Field.SENDER_NAME: sender_name, } response = NanbanSkill.packet2response(packet) # pprint(text) # pprint(response) response_lines = response.splitlines() span = ( len("다음 남만 시각: "), len("다음 남만 시각: 3:58:00 PM (KST) "), ) hyp = SpanTool.list_span2sublist(response_lines[2], span).strip() dt_nanban = dt_target + NanbanTimedelta.period() ref = dt_nanban.strftime("%I:%M:00 %p (KST)").lstrip("0") self.assertEqual( hyp, ref, )
def test_01(self): Chatroom.chatrooms2upsert([ChatroomKakaotalk.chatroom()]) sender_name = "iris" channel_user_codename = ChannelUserKakaotalk.sender_name2codename(sender_name) ChannelUser.channel_users2upsert([ChannelUserKakaotalk.sender_name2channel_user(sender_name)]) packet = {KhalaPacket.Field.CHANNEL_USER: channel_user_codename, KhalaPacket.Field.SENDER_NAME: sender_name, KhalaPacket.Field.TEXT: "?price 리스본 육두구", KhalaPacket.Field.CHATROOM: KakaotalkUWOChatroom.codename(), } hyp = NORM_LIST(PriceSkill.packet2rowsblocks(packet)) ref = [('[리스본] 시세', ['육두구'])] # pprint(hyp) self.assertEqual(hyp, ref)
def test_02(self): Chatroom.chatrooms2upsert([ChatroomKakaotalk.chatroom()]) sender_name = "iris" channel_user_codename = ChannelUserKakaotalk.sender_name2codename(sender_name) ChannelUser.channel_users2upsert([ChannelUserKakaotalk.sender_name2channel_user(sender_name)]) packet = {KhalaPacket.Field.CHANNEL_USER: channel_user_codename, KhalaPacket.Field.SENDER_NAME: sender_name, KhalaPacket.Field.TEXT: "?price 리스본 세비야 육두구 메이스", KhalaPacket.Field.CHATROOM: KakaotalkUWOChatroom.codename(), } hyp = NORM_SET(PriceSkill.packet2rowsblocks(packet)) ref = [('[육두구] 시세', {'세비야', '리스본'}), ('[메이스] 시세', {'세비야', '리스본'}), ] # pprint({"hyp":hyp}) self.assertEqual(hyp, ref)
def test_07(self): Chatroom.chatrooms2upsert([ChatroomKakaotalk.chatroom()]) sender_name = "iris" channel_user_codename = ChannelUserKakaotalk.sender_name2codename(sender_name) ChannelUser.channel_users2upsert([ChannelUserKakaotalk.sender_name2channel_user(sender_name)]) packet = {KhalaPacket.Field.CHANNEL_USER: channel_user_codename, KhalaPacket.Field.SENDER_NAME: sender_name, KhalaPacket.Field.TEXT: "?price 리스본 육두구", KhalaPacket.Field.CHATROOM: KakaotalkUWOChatroom.codename(), } hyp = PriceSkill.packet2response(packet) ref = """[사탕무] 시세 시라쿠사 130↗ @ 방금전 [by iris] 마르세이유 80↘ @ 방금전 [by iris] 사사리 75↘ @ 방금전 [by iris]""" # pprint(hyp) self.assertEqual(hyp, ref)
def test_04(self): Chatroom.chatrooms2upsert([ChatroomKakaotalk.chatroom()]) sender_name = "iris" channel_user_codename = ChannelUserKakaotalk.sender_name2codename(sender_name) ChannelUser.channel_users2upsert([ChannelUserKakaotalk.sender_name2channel_user(sender_name)]) server = "maris" ports = ["Lisbon"] tradegoods = ["Sugar Beet"] MarketpriceDoc.server_ports_tradegoods2delete(server, ports, tradegoods) # channel = Channel.Codename.KAKAOTALK_UWO_UWO # discord packet = {KhalaPacket.Field.TEXT: "?price 사탕무 리스본 120ㅅ", KhalaPacket.Field.CHATROOM: KakaotalkUWOChatroom.codename(), KhalaPacket.Field.CHANNEL_USER: channel_user_codename, KhalaPacket.Field.SENDER_NAME: sender_name, } hyp_01 = PriceSkill.packet2response(packet) ref_01 = """[사탕무] 시세 리스본 120↗ @ 방금전 [by iris]""" #pprint({"hyp_01": hyp_01}) self.assertEqual(hyp_01, ref_01) price_list_latest = MarketpriceDoc.ports_tradegoods2price_list_latest(server, ports, tradegoods) hyp_02 = lmap(MarketpriceDoc.doc2norm_unittest, price_list_latest) ref_02 = [{'port': 'Lisbon', 'rate': 120, 'tradegood': 'Sugar Beet', 'server': 'maris', 'trend': 'rise', 'channel_user': '******', }] # pprint({"hyp_02": hyp_02}) self.assertEqual(hyp_02, ref_02)
def codenames2docs(cls, codenames): collection = ChannelUserCollection.collection() query = {ChannelUser.Field.CODENAME: {"$in": codenames}} cursor = collection.find(query) h_codename2doc = merge_dicts( [{ ChannelUser.channel_user2codename(doc): doc } for doc in map(MongoDBTool.bson2json, cursor)], vwrite=vwrite_no_duplicate_key) doc_list = lmap(h_codename2doc.get, codenames) return doc_list
def test_02(self): Chatroom.chatrooms2upsert([ChatroomKakaotalk.chatroom()]) sender_name = "iris" channel_user_codename = ChannelUserKakaotalk.sender_name2codename( sender_name) ChannelUser.channel_users2upsert( [ChannelUserKakaotalk.sender_name2channel_user(sender_name)]) packet = { KhalaPacket.Field.TEXT: "?누구 iris", KhalaPacket.Field.CHATROOM: KakaotalkUWOChatroom.codename(), KhalaPacket.Field.CHANNEL_USER: channel_user_codename, KhalaPacket.Field.SENDER_NAME: sender_name, } response = WhoSkill.packet2response(packet) # pprint(response) self.assertGreaterEqual(len(response.splitlines()), 3) self.assertEqual(response.splitlines()[0], "[유저] iris(아리)")
def tuple2pair(cls, t): logger = HenriqueLogger.func_level2logger(cls.tuple2pair, logging.DEBUG) def chatuser_uuid2channel_user(chatuser_uuid, alias=None): if not chatuser_uuid: return None row = ChatuserTable.uuid2row(chatuser_uuid) if not row: logger.debug({"chatuser_uuid":chatuser_uuid}) return None channel_user = ChatuserTable.row2channel_user(row, alias=alias) return channel_user j_postgres = t[PortTradegoodStateTable.index_json()] sender_name = j_postgres.get("sender_name") created_at = DatetimeTool.fromisoformat(j_postgres["created_at"]) port_name_en = PortTradegoodStateTable.tuple2port_name_en(t) port = cls.name_en2port(port_name_en) tradegood_name_en = PortTradegoodStateTable.tuple2tradegood_name_en(t) tradegood = cls.name_en2tradegood(tradegood_name_en) rate = PortTradegoodStateTable.tuple2rate(t) trend = PortTradegoodStateTable.tuple2trend(t) chatuser_uuid = PortTradegoodStateTable.tuple2chatuser_uuid(t) channel_user = chatuser_uuid2channel_user(chatuser_uuid, alias=sender_name) channel_user_code = ChannelUser.channel_user2codename(channel_user) if channel_user else None server_alias = str2lower(jdown(j_postgres, ["server", "name"])) # logger.debug({"server_alias":server_alias}) server = Server.alias_lang2server(server_alias, "ko") assert_true(server,server_alias) marketprice = {MarketpriceDoc.Field.CREATED_AT: created_at, MarketpriceDoc.Field.PORT: Port.port2codename(port), MarketpriceDoc.Field.TRADEGOOD: Tradegood.tradegood2codename(tradegood), MarketpriceDoc.Field.RATE: rate, MarketpriceDoc.Field.TREND: trend, MarketpriceDoc.Field.CHANNEL_USER: channel_user_code, MarketpriceDoc.Field.SERVER: Server.server2codename(server), } return marketprice, channel_user
def test_03(self): Chatroom.chatrooms2upsert([ChatroomKakaotalk.chatroom()]) sender_name = "iris" channel_user_codename = ChannelUserKakaotalk.sender_name2codename(sender_name) ChannelUser.channel_users2upsert([ChannelUserKakaotalk.sender_name2channel_user(sender_name)]) packet = {KhalaPacket.Field.CHANNEL_USER: channel_user_codename, KhalaPacket.Field.SENDER_NAME: sender_name, KhalaPacket.Field.TEXT: "?price 육메 이베", KhalaPacket.Field.CHATROOM: KakaotalkUWOChatroom.codename(), } hyp = NORM_SET(PriceSkill.packet2rowsblocks(packet)) ref = [('[육두구] 시세', {'바르셀로나', '발렌시아', "히혼", "팔마", "빌바오", "세비야", "말라가", "사그레스", "리스본", "세우타", "파루", "라스팔마스", "마데이라", "비아나두카스텔루", "몽펠리에", "카사블랑카", "포르투", }), ('[메이스] 시세', {'바르셀로나', '발렌시아', "히혼", "팔마", "빌바오", "세비야", "말라가", "사그레스", "리스본", "세우타", "파루", "라스팔마스", "마데이라", "비아나두카스텔루", "몽펠리에", "카사블랑카", "포르투", }), ] # pprint({"hyp": hyp}) self.assertEqual(hyp, ref)
def sender_name2codename(cls, sender_name): return ChannelUser.channel_suffix2codename( Channel.Codename.KAKAOTALK_UWO, sender_name)
def id2codename(cls, id_str): return ChannelUser.channel_suffix2codename(Channel.Codename.DISCORD, id_str)
def _docs2cache(cls, docs): logger = KhalaLogger.func_level2logger(cls._docs2cache, logging.DEBUG) for doc in docs: codename = ChannelUser.channel_user2codename(doc) CacheManager.add2cache(cls.codenames2docs, doc, args=[codename])
def doc2pair(channel_user): cond = {ChannelUser.Field.CODENAME: ChannelUser.channel_user2codename(channel_user)} return cond, channel_user