Example #1
0
def app_mentioned(event_data):
    channel = event_data["event"]["channel"]
    text = event_data["event"]["text"]

    if text[13:] == 'command':
        message = _crawl_command(text)
        slack_web_client.chat_postMessage(channel=channel, text="명령어 목록")
    elif text[13:14] == "g":
        message = _crawl_guide(text)
        print(message)
        slack_web_client.chat_postMessage(channel=channel,
                                          blocks=extract_json(message))
    elif text[13:14] == "c":
        messageBlock = _crawl_champion(text)
        slack_web_client.chat_postMessage(channel=channel,
                                          blocks=extract_json(messageBlock))
    elif text[13:14] == "s":
        message = _crawl_synergies(text)
        slack_web_client.chat_postMessage(
            channel=channel,
            # text=message
            blocks=extract_json(message))
    else:
        message = _crawl_else()
        print(message)
        slack_web_client.chat_postMessage(channel=channel,
                                          blocks=extract_json(message))
Example #2
0
    def to_dict(self) -> dict:
        as_dict = super().to_dict()
        as_dict['options'] = extract_json(self.options)

        if self.confirm is not None:
            as_dict["confirm"] = extract_json(self.confirm)

        if self.initial_option is not None:
            as_dict['initial_option'] = extract_json(self.initial_option)

        return as_dict
Example #3
0
def app_mentioned(event_data):
    channel = event_data["event"]["channel"]
    text = event_data["event"]["text"]
    user_di = event_data["event"]["user"]
    user_id = 'C:/Users/student/PycharmProjects/untitled/db/'+user_di+'.txt'
    uu='<@'+user_di+'>'
    if 'admin' in text:
        keywords = uu
    elif 'help' in text:
        keywords = "앱 초기 실행은 @Mavely 을 mention\n정보 기입은 성별/나이/키/몸무게  *ex:남자/24/176/65 * 형식으로 기입\n음식 칼로리 검색은 *검색/음식명*\n먹은 음식 계산은 *음식/음식명*\n운동 관련 유튜브 영상 시청은 *운동/?*\n하루 권장 칼로리 안넘기도록 주의하세요!"

    elif "운동" in text:
        keywords = getExercise(text)
    elif "검색" in text:
        food = text.split('/')[1]
        keywords = findFood(food)
        slack_web_client.chat_postMessage(
            channel=channel,
            blocks=extract_json(keywords)
        )
        return
    elif re.search(r"남자|여자", text):
        keywords = "네 "+uu+"회원님~~\n회원님께서는 하루 권장 칼로리가 " + "*"+str(setBaseUser(
            text, user_id))+"*" + " 이네요~\n이 이상 드시면 이 이상 드시면 살이 디룩디룩 찔테니 절--대 넘기시면 안됩니다!!\n앞으로는 음식먹기 전에 저한테 항상 검사를 맡아야 합니다!"
    elif "음식" in text:
        food = text.split('/')[1]
        keywords = eatFood(food,user_id,uu)
        slack_web_client.chat_postMessage(
            channel=channel,
            blocks=extract_json(keywords)
        )
        return
    elif len(text) == 12:
        keywords = intro(uu)
        slack_web_client.chat_postMessage(
            channel=channel,
            blocks=extract_json(keywords)
        )
        return
    else:
        keywords = joke(text)
        slack_web_client.chat_postMessage(
            channel=channel,
            blocks=extract_json(keywords)
        )
        return

    slack_web_client.chat_postMessage(
        channel=channel,
        text=keywords
    )
    return
Example #4
0
    def to_dict(self) -> dict:
        json = super().to_dict()

        if isinstance(self.options[0], OptionGroup):
            json["option_groups"] = extract_json(self.options, "block")
        else:
            json["options"] = extract_json(self.options)

        if self.initial_options is not None:
            json["initial_options"] = extract_json(self.initial_options,
                                                   "block")

        return json
Example #5
0
def app_mentioned(event_data):
    now = time.localtime()

    got_time = "%04d/%02d/%02d %02d:%02d:%02d" % (now.tm_year, now.tm_mon,
                                                  now.tm_mday, now.tm_hour,
                                                  now.tm_min, now.tm_sec)
    print(
        '==============================================================================================='
    )
    print(' * 멘션 받은 시간 : ' + got_time + '\n * Client_Msg_ID = ' +
          event_data["event"]["client_msg_id"] + '\n * Text = ' +
          event_data["event"]["text"])
    print(
        '==============================================================================================='
    )
    print('\n\n')

    channel = event_data["event"]["channel"]
    text = event_data["event"]["text"]

    message = _crawl_movie_rank_details(text)

    new_id = event_data["event"]["client_msg_id"]

    if origin is None:
        slack_web_client.chat_postMessage(channel=channel,
                                          blocks=extract_json(message))
        return

    # 예외처리 코드
    for i in range(len(origin)):
        if origin[i] == new_id:
            return

    print('------------------------------------------------------')
    print('새로운 아이디 넣기 전 origin list : ' + str(origin))

    if len(origin) < 10:
        origin.append(new_id)
    else:
        del origin[0]
        origin.append(new_id)

    print('new_id : ' + new_id)
    print('새로운 아이디 추가 후 origin list : ' + str(origin))
    print('------------------------------------------------------')

    slack_web_client.chat_postMessage(channel=channel,
                                      blocks=extract_json(message))
Example #6
0
def app_mentioned(event_data):
    channel = event_data["event"]["channel"]
    text = event_data["event"]["text"]

    if text[13:] == 'command':
        message = _crawl_command(text)
        slack_web_client.chat_postMessage(channel=channel, text="명령어 목록")
    elif text[13:18] == "guide":
        message = _crawl_guide(text)
        # print(message)
        slack_web_client.chat_postMessage(channel=channel,
                                          blocks=extract_json(message))
    elif text[13:] == "champion":
        message = _crawl_champion(text)
        slack_web_client.chat_postMessage(
            channel=channel,
            # text=message
            text="챔피언 정보 입니다.\n" + message)
    elif text[13:] == "synergies":
        message = _crawl_synergies(text)
        slack_web_client.chat_postMessage(
            channel=channel,
            # text=message
            text="시너지 정보 입니다.")
    else:
        message = _crawl_else
        slack_web_client.chat_postMessage(channel=channel, text=message)
def app_mentioned(event_data):
    channel = event_data["event"]["channel"]
    text = event_data["event"]["text"]

    if 'music' in text:
        message = show_menu_list()
        slack_web_client.chat_postMessage(channel=channel,
                                          blocks=extract_json(message))

    elif text[-1].isdigit():

        tmp = [1, 2, 3, 4, 5]
        if int(text[-1]) in tmp:
            # 있는경우
            sel = int(text[-1])
            message_list, attachments_list = genre_crawl(sel)

            for i in range(len(message_list)):
                slack_web_client.chat_postMessage(
                    channel=channel,
                    text=message_list[i],
                    attachments=attachments_list[i])
                time.sleep(1)

        else:
            #없는경우 메세지 출력
            slack_web_client.chat_postMessage(
                channel=channel, text="`@<봇이름> music` 과 같이 멘션해주세요.")

    else:
        slack_web_client.chat_postMessage(channel=channel,
                                          text="`@<봇이름> music` 과 같이 멘션해주세요.")

    return "OK", 200
def click_Threding(click_event):
    what_event = click_event.action_id
    event_list = what_event.split('_')

    if event_list[0] == 'price':

        click_value = int(click_event.value)
        if event_list[1] == 'up':

            click_value += 0 if click_value >= 5 else 1
        else:
            click_value -= 0 if click_value <= 0 else 1

        message_blocks = make_sale_message_blocks(click_value)

    elif event_list[0] == 'tap':
        if event_list[1] == 'office':
            crawling_url = '2010100000'
        elif event_list[1] == 'gaming':
            crawling_url = '2010300000'
        else:
            crawling_url = '2010500000'

        crawling_page(crawling_url)
        message_blocks = make_sale_message_blocks(0)

    # 메시지를 채널에 올립니다
    slack_web_client.chat_postMessage(channel=click_event.channel.id,
                                      blocks=extract_json(message_blocks))
Example #9
0
def app_mentioned(event_data):
    channel = event_data["event"]["channel"]
    text = event_data["event"]["text"]
    # timeEvent = event_data["event_time"]      #   타임이벤트 발생 조건을 변경해 listening 반응을 제어

    ## 챗봇이 받은 메시지 파싱 ##
    split = []
    split = text.split(">")
    splitText = split[1]

    ## 초기 블록 생성 ##
    my_blocks = []
    contentBlockTmp = SectionBlock(text="`****d*원하시는 날짜의 메뉴를 골라줭~!~!엉*****` ")
    button_actions = ActionsBlock(elements=[
        ButtonElement(text="어제", action_id="yesterday", value="0"),
        ButtonElement(text="오늘", style="danger", action_id="today", value="1"),
        ButtonElement(text="내일", action_id="tomorrow", value="2"),
        ButtonElement(text="모레",
                      style="primary",
                      action_id="theDayAfterTomorrow",
                      value="3"),
    ])
    my_blocks.append(contentBlockTmp)
    my_blocks.append(button_actions)

    ## Post message to Chatbot ##
    slackWebClient_toChatbotPostMsg(channel, extract_json(my_blocks))
Example #10
0
 def select_host_from_dynamic_list(_rqst):
     return {
         'options': extract_json([
             Option(label=val, value=val)
             for val in ('lx5e1234', 'lx5w1234', 'lx5e4552')
         ])
     }
Example #11
0
def app_mentioned(event_data):

    print('app_mentioned event data:', event_data)
    channel = event_data["event"]["channel"]
    text = event_data["event"]["text"]
    client_msg_id = event_data["event"]["client_msg_id"]

    keyword = ""
    for key in text.strip().split()[1:]:
        keyword += (str(key)) + ' '

    print('client message id:', client_msg_id)
    if client_msg_id not in prev_client_msg_id:
        prev_client_msg_id[client_msg_id] = 1
    else:
        print('=' * 50, 'PLEASE NO RETRY', '=' * 50)
        resp = make_response('no-retry', 200)
        resp.headers["X-Slack-No-Retry"] = 1
        return resp

    # 입력한 텍스트에서 검색 키워드와 가격대를 뽑아냅니다.
    # 중고거래 사이트를 크롤링하여 가격대가 비슷한 상품을 찾아옵니다.
    message_blocks = first_message(keyword)

    # 메시지를 채널에 올립니다
    slack_web_client.chat_postMessage(channel=channel,
                                      blocks=extract_json(message_blocks))
Example #12
0
def app_mentioned(event_data):
    channel = event_data["event"]["channel"]
    text = event_data["event"]["text"]
    # user_id = event_data["event"]["user"]
    # 연령대별은 연령대
    # 섹션은 날짜, 카테고리 검색 조건 설정
    text_matach = text.split(" ")
    # message_blocks = []
    if text_matach[1] in MATCHING and not text_matach[
            1] == "오늘" and not text_matach[1] == "어제":
        print("pass")
        slack_web_client.chat_postMessage(channel=channel,
                                          text="요청한  *" + text_matach[1] +
                                          "* 뉴스입니다.\n")
    else:
        if len(text_matach) <= 2:
            slack_web_client.chat_postMessage(
                channel=channel,
                text=
                "`@<봇이름> YYYYmmdd(오늘까지) 카테고리(정치,시사,IT,세계,사회문화)`와 같이 멘션해주세요\n 혹은 `@<봇이름> 연령대(10대,20대,30대,40대,50대,60대)` 와 같이 멘션해주세요"
            )
            return 0
        if not text_matach[2] in MATCHING:
            slack_web_client.chat_postMessage(
                channel=channel,
                text=
                "`@<봇이름> YYYYmmdd(오늘까지) 카테고리(정치,시사,IT,세계,사회문화)`와 같이 멘션해주세요\n 혹은 `@<봇이름> 연령대(10대,20대,30대,40대,50대,60대)` 와 같이 멘션해주세요"
            )
            return 0
        else:
            if text_matach[1] == "오늘":
                text_matach[1] = datetime.now().strftime("%Y%m%d")
                text = text.replace('오늘', text_matach[1])
            elif text_matach[1] == "어제":
                text_matach[1] = (datetime.now() -
                                  timedelta(days=1)).strftime("%Y%m%d")
                text = text.replace('어제', text_matach[1])
            print(text)
            now = int(datetime.now().strftime("%Y%m%d"))
            new_date = datetime.strptime(text_matach[1], '%Y%m%d')

            if int(new_date.strftime("%Y%m%d")) > now:
                slack_web_client.chat_postMessage(
                    channel=channel,
                    text=
                    "`@<봇이름> YYYYmmdd(오늘까지) 카테고리(정치,시사,IT,세계,사회문화)`와 같이 멘션해주세요\n 혹은 `@<봇이름> 연령대(10대,20대,30대,40대,50대,60대)` 와 같이 멘션해주세요"
                )
                return 0
            slack_web_client.chat_postMessage(
                channel=channel,
                text="요청한 " + text.split(" ")[1] + " *" + text.split(" ")[2] +
                "* 뉴스입니다.\n")

    message = _crawl(text)

    slack_web_client.chat_postMessage(channel=channel,
                                      blocks=extract_json(message))

    return 0
Example #13
0
    def handle_select_request(self, rqst: OptionSelectRequest):
        """

        Parameters
        ----------
        rqst

        Returns
        -------

        Notes
        -----
            https://api.slack.com/reference/block-kit/composition-objects#option_group
        """
        event = rqst.block_id

        callback = first(self.ic.select.listeners(event))
        if not callback:
            msg = f"No handler for ext selector event: {event}"
            self.log.error(msg)
            return

        cal_sig = signature(callback)
        if len(cal_sig.parameters) == 1:
            return callback(rqst)

        action = ActionEvent(type=rqst.rqst_type,
                             id=rqst.action_id,
                             value=rqst.value,
                             data={})

        # invoke the callback to retrieve the list of Option or OptionGroup
        # items.  Ensure that the callback did return what we expect, and then
        # return the requird Dict back to api.slack.com

        res_list = callback(rqst, action)
        if not res_list:
            emsg = f'Missing return from select {action.value}, callback: {event}'
            self.log.info(emsg)
            return {'options': []}

        if not isinstance(res_list, List):
            emsg = (
                f'Unexpected return, not list, from select {action.value}, callback: {event}.  '
                f'Got {type(res_list)} instead')
            self.log.error(emsg)
            raise SlackAppTKError(emsg, rqst, res_list)

        first_res = first(res_list)
        if isinstance(first_res, swc_objs.Option):
            res_type = 'options'
        elif isinstance(first_res, swc_objs.OptionGroup):
            res_type = 'option_groups'
        else:
            emsg = f'Unknown return type from select callback: {type(first_res)}'
            self.log.error(emsg)
            raise SlackAppTKError(emsg, rqst, res_list)

        return {res_type: extract_json(res_list)}
Example #14
0
def app_mentioned(event_data):
    channel = event_data["event"]["channel"]
    text = event_data["event"]["text"]
    message_block = _crawl(text)
    slack_web_client.chat_postMessage(
        channel=channel,
        blocks=extract_json(message_block)
    )
Example #15
0
    def to_dict(self) -> dict:
        self.validate_json()

        fields = {
            "type": self._type,
            "title": extract_json(self._title),
            "blocks": extract_json(self._blocks),
            "close": extract_json(self._close),
            "submit": extract_json(self._submit),
            "private_metadata": self._private_metadata,
            "callback_id": self._callback_id,
            "clear_on_close": self._clear_on_close,
            "notify_on_close": self._notify_on_close,
            "external_id": self._external_id,
        }

        return {k: v for k, v in fields.items() if v is not None}
def send_multi_line(channel, text_list):
    block = SectionBlock(
        text='\n'.join(text_list)
    )
    my_blocks = [block]
    slack_web_client.chat_postMessage(
        channel=channel,
        blocks=extract_json(my_blocks),
    )
Example #17
0
def app_mentioned(event_data):
    channel = event_data["event"]["channel"]
    text = event_data["event"]["text"]
    for i in range(12):
        message = _crawl_music_chart(text, i)
        message2 = crawl_image_in_url(text, i)
        slack_web_client.chat_postMessage(channel=channel,
                                          blocks=extract_json(message2))
        slack_web_client.chat_postMessage(channel=channel, text=message)
def app_mentioned(event_data):
    channel = event_data["event"]["channel"]
    text = event_data["event"]["text"]
    mentioned_url = '2010100000'
    crawling_page(mentioned_url)
    massage_block = make_sale_message_blocks(0)

    slack_web_client.chat_postMessage(channel=channel,
                                      blocks=extract_json(massage_block))
Example #19
0
 def send(self, channel: Union[Channel, str], text: str, **kwargs):
     channel_id = id_for_channel(channel)
     if 'attachments' in kwargs and kwargs['attachments'] is not None:
         kwargs['attachments'] = extract_json(kwargs['attachments'])
     if 'blocks' in kwargs and kwargs['blocks'] is not None:
         kwargs['blocks'] = extract_json(kwargs['blocks'])
     if 'ephemeral_user' in kwargs and kwargs['ephemeral_user'] is not None:
         ephemeral_user_id = id_for_user(kwargs['ephemeral_user'])
         del kwargs['ephemeral_user']
         return LowLevelSlackClient.get_instance(
         ).web_client.chat_postEphemeral(channel=channel_id,
                                         user=ephemeral_user_id,
                                         text=text,
                                         **kwargs)
     else:
         return LowLevelSlackClient.get_instance(
         ).web_client.chat_postMessage(channel=channel_id,
                                       text=text,
                                       **kwargs)
Example #20
0
def on_button_click():
    # 버튼 클릭은 SlackEventsApi에서 처리해주지 않으므로 직접 처리합니다
    payload = request.values["payload"]
    click_event = MessageInteractiveEvent(json.loads(payload))

    func_Name = click_event.action_id
    user_input = click_event.value

    print('block id type:', type(func_Name))
    # 다른 가격대로 다시 크롤링합니다.
    if func_Name == '0':
        message_blocks = make_sale_message_blocks(user_input)
        slack_web_client.chat_postMessage(channel=click_event.channel.id,
                                          blocks=extract_json(message_blocks))
    elif func_Name == '1':
        message_blocks = make_hotel_message_blocks(user_input)
        if message_blocks == -1:
            slack_web_client.chat_postMessage(channel=click_event.channel.id,
                                              text=u"*검색결과가 없습니다.. 다시 입력해주세요*")
        else:
            slack_web_client.chat_postMessage(
                channel=click_event.channel.id,
                blocks=extract_json(message_blocks))
    elif func_Name == '2':
        message = _crawl_find_map(user_input)
        if message == -1:
            slack_web_client.chat_postMessage(
                channel=click_event.channel.id,
                text=u"띄워쓰기를 다시 하거나 좀 더 상세한 주소를 입력해 주세요.")
        else:
            slack_web_client.chat_postMessage(channel=click_event.channel.id,
                                              blocks=extract_json(message))
    elif func_Name in ["한식", "중식", "양식", "술집"]:
        message_blocks = make_sale_message_blocks(
            str(user_input) + " " + str(func_Name))
        slack_web_client.chat_postMessage(channel=click_event.channel.id,
                                          blocks=extract_json(message_blocks))

    # 메시지를 채널에 올립니다

    # Slack에게 클릭 이벤트를 확인했다고 알려줍니다
    return "OK", 200
Example #21
0
 def test_from_single_json_object(self):
     single_json_object = PlainTextObject.from_str("foo")
     output = extract_json(single_json_object)
     expected = {
         "result": {
             "type": "plain_text",
             "text": "foo",
             "emoji": True
         }
     }
     self.assertDictEqual(expected, {"result": output})
Example #22
0
def app_mentioned(event_data):
    channel = event_data["event"]["channel"]
    text = event_data["event"]["text"]

    message = _crawl_city_chart(text)
    block = _image_extraction(text)

    slack_web_client.chat_postMessage(channel=channel, text=message)

    slack_web_client.chat_postMessage(channel=channel,
                                      blocks=extract_json(block))
Example #23
0
def app_mentioned(event_data):
    channel = event_data["event"]["channel"]
    text = event_data["event"]["text"]

    # if text == '<@UL9K54M32>':
    #     keywords = '아가리'
    # else:
    #     keywords = _chat_with_mybot(text)
    slack_web_client.chat_postMessage(channel=channel,
                                      blocks=extract_json(
                                          [block1, block1, block2]))
Example #24
0
 def test_from_list_of_json_objects(self):
     json_objects = [
         PlainTextObject(text="foo"),
         MarkdownTextObject(text="bar"),
     ]
     output = extract_json(json_objects)
     expected = {"result": [
         {"type": "plain_text", "text": "foo", "emoji": True},
         {"type": "mrkdwn", "text": "bar", "verbatim": False},
     ]}
     self.assertDictEqual(expected, {"result": output})
Example #25
0
def app_mentioned(event_data):
    channel = event_data["event"]["channel"]
    text = event_data["event"]["text"]

    message = _crawl(text)

    if message == []:
        message = [SectionBlock(fields=["검색된 레시피가 없거나 오류입니다."])]

    slack_web_client.chat_postMessage(channel=channel,
                                      blocks=extract_json(message))
Example #26
0
def main(rqst: Union[InteractiveMessageRequest, CommandRequest]) -> None:

    block_id = cmd.prog + '.main.button'

    # create a Slack message that will be used to respond to the User's
    # interaction which was the invocation of the /demo command.

    resp = Response(rqst)

    # -------------------------------------------------------------------------
    # define the button callback handler to send a response back to the
    # User telling the time when they pressed the button
    # -------------------------------------------------------------------------

    @rqst.app.ic.block_action.on(block_id)
    def on_button(btn_rqst: BlockActionRequest,
                  btn_action: ActionEvent):

        btn_resp = Response(btn_rqst)

        btn_resp.send_response(text=(
            f"At timestamp `{btn_action.data['action_ts']}`, "
            f"you pressed: *{btn_action.value.title()}*")
        )

    # -------------------------------------------------------------------------
    # create a message to send to the User that has two buttons; and when
    # they click either one, the above callback will be executed.
    # -------------------------------------------------------------------------

    user_id = rqst.user_id

    resp['blocks'] = extract_json([
        SectionBlock(text=MarkdownTextObject(text=f'Hi there <@{user_id}>!')),
        DividerBlock(),
        ActionsBlock(
            block_id=block_id,
            elements=[
                ButtonElement(
                    text='Press for Bad', style='danger',
                    action_id=f'{block_id}.bad',
                    value='bad'),
                ButtonElement(
                    text='Press for Good', style="primary",
                    action_id=f'{block_id}.good',
                    value='good')
            ]

        ),
        DividerBlock()
    ])

    resp.send()
Example #27
0
    def to_dict(self) -> dict:
        as_dict = super().to_dict()

        as_dict['element'] = extract_json(self.element)
        pto_dfs = PlainTextObject.direct_from_string

        as_dict['label'] = pto_dfs(self.label)

        if 'hint' in as_dict:
            as_dict['hint'] = pto_dfs(self.hint)

        return as_dict
Example #28
0
def _papago(text):
    new_text=text.split(",")
    idx = 0
    try:
        idx = trans.index(new_text[0])
    except:
        pass
    # idx = trans.

    if trans[idx] in text:
        # text = "ko_to_en, 나는 학교에 버스도 타고, 지하철도 타고, 비행기도 탄다."
        # new_text = ['ko_to_en','나는 학교에 버스도 타고','지하철도 타고','비행기도 탄다.',]
        # idx = 0

        # new_new_text = "나는 학교에 버스도 타고, 지하철도 타고, 비행기도 탄다."
        new_new_text= ",".join(new_text[1:])

        encText = urllib.parse.quote(new_new_text)
        data = "source=" +trans[idx][:2] + "&target="+trans[idx][-2:] + "&text=" + encText
        url = "https://openapi.naver.com/v1/papago/n2mt"
        request = urllib.request.Request(url)
        request.add_header("X-Naver-Client-Id",client_id)
        request.add_header("X-Naver-Client-Secret",client_secret)
        response = urllib.request.urlopen(request, data=data.encode("utf-8"))
        rescode = response.getcode()
        if(rescode==200):
            response_body = response.read()
            return (response_body.decode('utf-8')[152:].split("\"")[0].replace(", @UKZKYKWUS.", ""))
        else:
            return ("Error Code:" + rescode)
    elif 'help' in text:
        block1 = SectionBlock(
        text="`@ko_to_en` : 한국어->영어"+"\n"+"`@en_to_ko` : 영어->한국어"+"\n"+
        "`@ko_to_ja` : 한국어->일어"+"\n"+
        "`@ko_to_ja` : 한국어->일어"+"\n"+"`@ko_to_vi` : 한국어->베트남어"+"\n"+
        "`@ko_to_fr` : 한국어->프랑스어"+"\n"+
        "`@ko_to_es` : 한국어->스페인어"+"\n"+
        "`@ko_to_id` : 한국어->인도네시아어"+"\n"+
        "`@ko_to_th` : 한국어->태국어"+"\n"+
        "`@ko_to_ru` : 한국어->러시아어"+"\n"+
        "`@en_to_ja` : 영어->일본어"
        )
        block2 = SectionBlock(
        text="`@<명령어>, <문장>` 의 형태로 멘션해주세요."
        )

        my_blocks = [block1,block2]
        slack_web_client.chat_postMessage(
        channel="#ssafy",
        blocks=extract_json(my_blocks)
)
    else:
        return "`@<봇이름> help` 와 같이 멘션해주세요."
Example #29
0
def on_button_click():
    # 버튼 클릭은 SlackEventsApi에서 처리해주지 않으므로 직접 처리합니다
    payload = request.values["payload"]
    click_event = MessageInteractiveEvent(json.loads(payload))

    keyword = click_event.block_id
    dDay = int(click_event.value)

    yesterday = datetime.today().day - 1
    yttt = []
    for i in range(4):
        tmpYttt = yesterday + i
        if int(tmpYttt) < 10:
            yttt.append("0" + str(tmpYttt))
        else:
            yttt.append(str(tmpYttt))

    dateData = ""
    if dDay == 0:
        dateData = yttt[0]
    elif dDay == 1:
        dateData = yttt[1]
    if dDay == 2:
        dateData = yttt[2]
    elif dDay == 3:
        dateData = yttt[3]

    objectList = []
    objectList = crawlig(dateData)

    # 블록 처리 ##
    my_blocks = []
    for i in range(len(objectList)):
        m = objectList[i]
        titleBlockTmp = SectionBlock(text="*`\\\\\\\\\\\\\\\\\\\\\\\\\t\t" +
                                     "Day " + dateData + ". " + m.title +
                                     "\t\t///////////`*")
        imgBlockTmp = ImageBlock(
            image_url=m.img,
            alt_text="이미지가 안보이면 어쩔수 없지...",
        )
        contentBlockTmp = SectionBlock(fields=m.foods)

        my_blocks.append(titleBlockTmp)
        my_blocks.append(imgBlockTmp)
        my_blocks.append(contentBlockTmp)

    ## Post message to Chatbot ##
    slackWebClient_toChatbotPostMsg(click_event.channel.id,
                                    extract_json(my_blocks))

    # Slack에게 클릭 이벤트를 확인했다고 알려줍니다
    return "OK", 200
Example #30
0
def on_button_click():
    # 버튼 클릭은 SlackEventsApi에서 처리해주지 않으므로 직접 처리합니다
    payload = request.values["payload"]
    click_event = MessageInteractiveEvent(json.loads(payload))

    fortune = click_event.value
    user_id_ = click_event.user.id

    if(fortune == "birth"):
        message = today_fortune(user_id_)
        slack_web_client.chat_postMessage(
            channel=click_event.channel.id,
            blocks=extract_json(message)
        )
        return "OK", 200
    elif(fortune == "animal"):
        message = animal_fortune(user_id_)
        slack_web_client.chat_postMessage(
            channel=click_event.channel.id,
            blocks=extract_json(message)
        )
        return "OK", 200
    elif(fortune == "constellation"):
        message = constellation_fortune(user_id_)
        slack_web_client.chat_postMessage(
            channel=click_event.channel.id,
            blocks=extract_json(message)
        )
        return "OK", 200
    elif fortune in ["love", "money", "work", "study"]:
        message = today_fortune_detail(user_id_, fortune)
        slack_web_client.chat_postMessage(
            channel=click_event.channel.id,
            blocks=extract_json(message)
        )
        return "OK", 200

    # Slack에게 클릭 이벤트를 확인했다고 알려줍니다
    return "OK", 200