Beispiel #1
0
    async def facebook(self, command):
        if command == 'get_started':
            # send_message = [
            #     Message(
            #         attachment=ImageAttachment(
            #             url=BRICK_DEFAULT_IMAGE
            #         )
            #     ),
            #     Message(
            #         text='geniecontents에서 제공하는 "띠별 오늘의 운세 서비스"에요.'
            #     )
            # ]
            send_message = [
                Message(attachment=TemplateAttachment(payload=GenericTemplate(
                    elements=[
                        Element(
                            image_url=BRICK_DEFAULT_IMAGE,
                            title='띠별 오늘의 운세 서비스',
                            subtitle='geniecontents에서 제공하는 "띠별 오늘의 운세 서비스"에요.')
                    ])))
            ]
            await self.fb.send_messages(send_message)
            await self.brick_db.save()
        elif command == 'final':
            input_data = await self.brick_db.get()
            num = input_data['store'][0]['value']
            now = datetime.datetime.today()
            res = requests.get(
                url=
                'https://www.geniecontents.com/fortune/internal/v1/daily?birthYear=%s&targetYear=%s&targetMonth=%s&targetDay=%s'
                % (num, now.year, now.month, now.day))
            try:
                parsed_result = res.json()
                parsed_result.update(parsed_result['list'][0])
                send_message = [
                    Message(text='조회된 결과에요'),
                    Message(attachment=ImageAttachment(
                        url='https:%s' % parsed_result['animalImgUrl'])),
                    Message(
                        text=
                        '출생년도 : {year}\n운세 : {summary}\n자세한 내용 : {description}'
                        .format(**parsed_result),
                        quick_replies=QuickReply(quick_reply_items=[
                            QuickReplyTextItem(
                                title='다른 운세검색',
                                payload='brick|luck|get_started')
                        ]))
                ]
            except:
                send_message = [Message(text='조회된 결과가 없습니다.')]

            await self.brick_db.delete()
            await self.fb.send_messages(send_message)
        return None
Beispiel #2
0
 async def facebook(self, command):
     if command == 'get_started':
         send_message = [
             Message(
                 attachment=ImageAttachment(
                     url=BRICK_DEFAULT_IMAGE
                 )
             ),
             Message(
                 text='안녕하세요. 장소 테스트입니다.'
             ),
             Message(
                 text='현재위치를 보내주세요.',
                 quick_replies=QuickReply(
                     quick_reply_items=[
                         QuickReplyLocationItem()
                     ]
                 )
             )
         ]
         await self.fb.send_messages(send_message)
     return None
Beispiel #3
0
    async def facebook(self, command):
        if command == 'get_started':
            send_message = [
                Message(
                    attachment=ImageAttachment(
                        url=BRICK_DEFAULT_IMAGE[1]
                    )
                ),
                Message(
                    text='블루핵에서 제공하는 "메일보내기 서비스"예요.'
                ),
                Message(
                    attachment=TemplateAttachment(
                        payload=GenericTemplate(
                            elements=[
                                Element(title='메일전송',
                                        subtitle='챗봇에서 메일을 보낼 수 있어요',
                                        buttons=[
                                            PostBackButton(
                                                title='메일보내기',
                                                payload='brick|mailer|show_data'
                                            )
                                        ])
                            ]
                        )
                    )
                )
            ]
            await self.fb.send_messages(send_message)
        elif command == 'show_data':
            await self.brick_db.save()
        elif command == 'cancel':
            await self.brick_db.delete()
            await self.fb.send_message(
                message=Message(
                    text='메일 보내기를 취소했어요.',
                    quick_replies=QuickReply(
                        quick_reply_items=[
                            QuickReplyTextItem(
                                title='새 메일보내기',
                                payload='brick|mailer|show_data'
                            )
                        ]
                    )
                ))
        elif command == 'final':
            input_data = await self.brick_db.get()
            msg = MIMEText(input_data['store'][2]['value'])
            msg['Subject'] = '%s로부터 이메일입니다.' % input_data['store'][0]['value']
            msg['To'] = input_data['store'][1]['value']
            self.smtp.ehlo()
            self.smtp.starttls()
            self.smtp.login(self.sender_email, self.sender_password)
            self.smtp.sendmail(self.sender_email, input_data['store'][1]['value'], msg.as_string())
            await self.fb.send_message(
                message=Message(
                    text='메일 보내기가 완료되었어요.',
                    quick_replies=QuickReply(
                        quick_reply_items=[
                            QuickReplyTextItem(
                                title='연속하여 메일보내기',
                                payload='brick|mailer|show_data'
                            )
                        ]
                    )
                ))

        return None
Beispiel #4
0
    async def facebook(self, command):
        if command == 'get_started':
            # send_message = [
            #     Message(
            #         attachment=ImageAttachment(
            #             url=BRICK_DEFAULT_IMAGE
            #         )
            #     ),
            #     Message(
            #         text='외교부에서 제공하는 "해외국가정보 서비스"에요.'
            #     )
            # ]
            send_message = [
                Message(attachment=TemplateAttachment(payload=GenericTemplate(
                    elements=[
                        Element(image_url=BRICK_DEFAULT_IMAGE,
                                title='해외국가정보 서비스',
                                subtitle='외교부에서 제공하는 "해외국가정보 서비스"에요.')
                    ])))
            ]
            await self.fb.send_messages(send_message)
            await self.brick_db.save()
        elif command == 'final':
            input_data = await self.brick_db.get()
            country = input_data['store'][0]['value']

            res = requests.get(
                url=
                'http://apis.data.go.kr/1262000/CountryBasicService/getCountryBasicList?serviceKey=%s&numOfRows=10&pageSize=10&pageNo=1&startPage=1&countryName=%s'
                % (input_data['data']['api_key'],
                   urllib.parse.quote_plus(country)))
            items = get_items_from_xml(res)

            if type(items) is dict:
                if items.get('code', '00') == '99' or items.get('code',
                                                                '00') == '30':
                    send_message = [
                        Message(
                            text=
                            'chatbrick 홈페이지에 올바르지 않은 API key를 입력했어요. 다시 한번 확인해주세요.',
                        )
                    ]
                else:
                    send_message = [Message(text=UNKNOWN_ERROR_MSG)]
            else:
                if len(items) == 0:
                    send_message = [
                        Message(text='조회된 결과가 없습니다.',
                                quick_replies=QuickReply(quick_reply_items=[
                                    QuickReplyTextItem(
                                        title='다른 국가검색',
                                        payload='brick|country|get_started')
                                ]))
                    ]
                else:
                    items[0]['basic'] = remove_html_tag(items[0]['basic'])
                    send_message = [
                        Message(attachment=ImageAttachment(
                            url=download_and_save_image(items[0]['imgUrl']))),
                        Message(
                            text=
                            '{continent}\n*{countryName}({countryEnName})*\n{basic}'
                            .format(**items[0]),
                            quick_replies=QuickReply(quick_reply_items=[
                                QuickReplyTextItem(
                                    title='다른 국가검색',
                                    payload='brick|country|get_started')
                            ]))
                    ]

            await self.brick_db.delete()
            await self.fb.send_messages(send_message)
        return None
    def make_the_bricks_for_facebook(self):
        designer_brick = []

        # get_started (1.1, 1.2)
        designer_brick.append(FacebookBrick(brick_type='postback', value='get_started', actions=[
            FacebookGeneralAction(message=Message(text=self.data['custom_settings']['get_started'])),
            FacebookGeneralAction(message=Message(
                attachment=TemplateAttachment(
                    payload=ListTemplate(top_element_style='LARGE',
                                         elements=[Element(title=self.data['basic']['name'],
                                                           image_url=self.data['basic']['profile_image'],
                                                           buttons=[PostBackButton(payload='VIEW_PROFILE',
                                                                                   title='View')]),
                                                   Element(title='Portfolio',
                                                           subtitle='%s님의 포트폴리오를 보고 싶은가요?' % self.data['basic']['name'],
                                                           buttons=[
                                                               PostBackButton(payload='VIEW_PORTFOLIO',
                                                                              title='View')]),
                                                   Element(title='Contact',
                                                           subtitle='%s님에게 이메일을 보내고 싶은가요?' % self.data['basic'][
                                                               'name'],
                                                           buttons=[PostBackButton(payload='CONTACT',
                                                                                   title='View')])
                                                   ]
                                         )
                )
            )
            )
        ]
                                            )
                              )
        # Profile(1) / 2
        designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_PROFILE', actions=[
            FacebookGeneralAction(message=Message(
                attachment=TemplateAttachment(
                    payload=GenericTemplate(elements=[
                        Element(title=self.data['basic']['name'],
                                subtitle='{special}\n{residence}'.format(**self.data['basic']),
                                image_url=self.data['basic']['profile_image'],
                                buttons=[
                                    PostBackButton(title='Work', payload='VIEW_USERS_WORK'),
                                    PostBackButton(title='Specialties', payload='VIEW_USERS_SPECIALTIES'),
                                    PostBackButton(title='Summary', payload='VIEW_USERS_SUMMARY'),
                                ],
                                default_action={
                                    'type': 'web_url',
                                    'url': self.data['basic']['social'],
                                    'webview_height_ratio': 'tall'
                                }
                                )
                    ])
                )
            ))
        ]))

        # Work / 2.1.1
        if self.data.get('work', False) and len(self.data['work']):
            work_element = [
                Element(title='Work',
                        subtitle='%s님의 경력 사항입니다.' % self.data['basic']['name'],
                        image_url=WORK_IMAGE_URL)
            ]

            for work in self.data['work']:
                if work['name'].strip() == '':
                    raise RuntimeError('경력의 근무 회사의 이름이 없어요.')

                work_element.append(Element(title=work['name'], subtitle='{period}\n{field}'.format(**work)))

            designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_USERS_WORK', actions=[
                FacebookGeneralAction(message=Message(
                    attachment=TemplateAttachment(
                        payload=ListTemplate(elements=work_element, top_element_style='LARGE', buttons=[
                            PostBackButton(title='Menu', payload='get_started')
                        ])
                    )
                ))
            ]))
        else:
            designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_USERS_WORK', actions=[
                FacebookGeneralAction(message=Message(text='%s님이 아직 Work 항목을 입력하지 않았습니다.' % self.data['basic']['name']))
            ]))

        # Specialties / 2.1.2
        if self.data.get('specialties', False) and len(self.data['specialties']):
            special_element = [
                Element(title='Specialties',
                        subtitle='%s님의 보유기술 및 능력입니다.' % self.data['basic']['name'],
                        image_url=SPECIALTIES_IMAGE_URL)
            ]

            for special in self.data['specialties']:
                if special['name'].strip() == '':
                    raise RuntimeError('보유 기술의 이름이 없어요.')

                if special['detail'].strip() == '':
                    raise RuntimeError('보유 기술의 설명이 없어요.')

                special_element.append(Element(title=special['name'], subtitle=special['detail']))

            designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_USERS_SPECIALTIES', actions=[
                FacebookGeneralAction(message=Message(
                    attachment=TemplateAttachment(
                        payload=ListTemplate(elements=special_element, top_element_style='LARGE', buttons=[
                            PostBackButton(title='Menu', payload='get_started')
                        ])
                    )
                ))
            ]))
        else:
            designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_USERS_SPECIALTIES', actions=[
                FacebookGeneralAction(
                    message=Message(text='%s님이 아직 Specialties 항목을 입력하지 않았습니다.' % self.data['basic']['name']))
            ]))

        # Summary / 2.1.3
        if self.data.get('summary', False) and self.data['summary'].strip() != '':
            designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_USERS_SUMMARY', actions=[
                FacebookGeneralAction(message=Message(
                    attachment=ImageAttachment(url=SUMMARY_IMAGE_URL)
                )),
                FacebookGeneralAction(message=Message(
                    text=self.data['summary']
                ))
            ]))
        else:
            designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_USERS_SUMMARY', actions=[
                FacebookGeneralAction(
                    message=Message(text='%s님이 아직 Summary 항목을 입력하지 않았습니다.' % self.data['basic']['name']))
            ]))

        # Contact / 4
        if self.data['basic'].get('email', False) and self.data['basic']['email'].strip() != '':
            designer_brick.append(FacebookBrick(brick_type='postback', value='CONTACT', actions=[
                FacebookGeneralAction(message=Message(
                    attachment=TemplateAttachment(
                        payload=GenericTemplate(elements=[
                            Element(title='Contact',
                                    subtitle='자세한 문의는 아래의 메일보내기 버튼을 이용해주세요.',
                                    image_url=CONTACT_IMAGE_URL,
                                    buttons=[
                                        PostBackButton(title='Send E-Mail',
                                                       payload='SEND_EMAIL_TO_USER')
                                    ]
                                    )
                        ])
                    )
                ))
            ]))
        else:
            designer_brick.append(FacebookBrick(brick_type='postback', value='CONTACT', actions=[
                FacebookGeneralAction(
                    message=Message(text='%s님이 아직 이메일을 입력하지 않았습니다.' % self.data['basic']['name']))
            ]))

        if self.data.get('portfolio', False) and len(self.data['portfolio']):
            temp_element = []

            for portfolio in self.data['portfolio'][:10]:
                temp_element.append(Element(title=portfolio['title'],
                                            subtitle=portfolio['sub_title'],
                                            image_url=portfolio['image_url'],
                                            buttons=[
                                                UrlButton(title='View', url=portfolio['url'])
                                            ]
                                            ))

            designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_PORTFOLIO', actions=[
                FacebookGeneralAction(message=Message(
                    attachment=TemplateAttachment(
                        payload=GenericTemplate(elements=temp_element)
                    )
                ))
            ]))
        else:
            designer_brick.append(FacebookBrick(brick_type='postback', value='VIEW_PORTFOLIO', actions=[
                FacebookGeneralAction(
                    message=Message(text='%s님이 아직 Portfolio 항목을 입력하지 않았습니다.' % self.data['basic']['name']))
            ]))

        designer_brick.append(FacebookBrick(brick_type='postback', value='SEND_EMAIL_TO_USER',
                                            actions=[
                                                FacebookBrickAction(
                                                    brick_id='mailerforset',
                                                    data={
                                                        'to': self.data['basic']['email'].strip()
                                                    }
                                                )
                                            ]))

        return designer_brick
Beispiel #6
0
    def make_the_bricks(self):
        designer_brick = []
        hackathon_name = self.data['basic']['name']

        # get_started (1, 2) - 참가 신청 날짜 일 때,
        designer_brick.append(
            FacebookBrick(brick_type='postback', value='get_started', condition=[
                {
                    'type': 'date_between',
                    'data': {
                        'start_date': self.data['date']['application_period']['start'],
                        'end_data': self.data['date']['application_period']['end']
                    }
                }
            ],
                          actions=[
                              FacebookGeneralAction(message=Message(
                                  text=self.data['custom_settings']['get_started']
                              )),
                              FacebookGeneralAction(message=Message(
                                  attachment=TemplateAttachment(
                                      payload=GenericTemplate(elements=[
                                          Element(title='%s 안내' % hackathon_name,
                                                  image_url=self.data['basic']['poster_image'],
                                                  subtitle='%s에 대한 안내정보에요.' % hackathon_name,
                                                  buttons=[
                                                      PostBackButton(title='일정 및 장소안내',
                                                                     payload='VIEW_SCHEDULE_AND_PLACE'),
                                                      PostBackButton(title='참가요건',
                                                                     payload='VIEW_REQUIREMENTS'),
                                                      PostBackButton(title='시상 및 참가혜택',
                                                                     payload='VIEW_PRIZE_AND_BENEFIT')
                                                  ]),
                                          Element(title='%s 참가신청' % hackathon_name,
                                                  image_url=WORK_IMAGE_URL,
                                                  subtitle='우리 함께 %s에 참가해요.' % hackathon_name,
                                                  buttons=[
                                                      UrlButton(title='참가 신청하기', url=self.data['application']['url'])
                                                  ]),
                                          Element(image_url=WORK_IMAGE_URL,
                                                  title='문의',
                                                  subtitle='%s에 대해 궁금하신점을 말씀해주세요' % hackathon_name,
                                                  buttons=[
                                                      PostBackButton(title='문의하기', payload='CONTACT')
                                                  ]),
                                          Element(image_url=WORK_IMAGE_URL,
                                                  title='주최/주관/후원 정보',
                                                  subtitle='%s의 주최/주관/후원 정보에요.' % hackathon_name,
                                                  buttons=[
                                                      PostBackButton(title='보기', payload='VIEW_SPONSOR')
                                                  ])
                                      ])
                                  )
                              ))
                          ])
        )

        # get_started (1, 2) - 참가 신청 날짜가 아닐 때,
        designer_brick.append(
            FacebookBrick(brick_type='postback', value='get_started', condition=[
                {
                    'type': 'date_not_between',
                    'data': {
                        'start_date': self.data['date']['application_period']['start'],
                        'end_data': self.data['date']['application_period']['end']
                    }
                }
            ],
                          actions=[
                              FacebookGeneralAction(message=Message(
                                  text=self.data['custom_settings']['get_started']
                              )),
                              FacebookGeneralAction(message=Message(
                                  attachment=TemplateAttachment(
                                      payload=GenericTemplate(elements=[
                                          Element(title='%s 안내' % hackathon_name,
                                                  image_url=self.data['basic']['poster_image'],
                                                  subtitle='%s에 대한 안내정보에요.' % hackathon_name,
                                                  buttons=[
                                                      PostBackButton(title='일정 및 장소안내',
                                                                     payload='VIEW_SCHEDULE_AND_PLACE'),
                                                      PostBackButton(title='참가요건',
                                                                     payload='VIEW_REQUIREMENTS'),
                                                      PostBackButton(title='시상 및 참가혜택',
                                                                     payload='VIEW_PRIZE_AND_BENEFIT')
                                                  ]),
                                          Element(title='%s 참가신청' % hackathon_name,
                                                  image_url=WORK_IMAGE_URL,
                                                  subtitle='우리 함께 %s에 참가해요.' % hackathon_name
                                                  ),
                                          Element(image_url=WORK_IMAGE_URL,
                                                  title='문의',
                                                  subtitle='%s에 대해 궁금하신점을 말씀해주세요' % hackathon_name,
                                                  buttons=[
                                                      PostBackButton(title='문의하기', payload='CONTACT')
                                                  ]),
                                          Element(image_url=WORK_IMAGE_URL,
                                                  title='주최/주관/후원 정보',
                                                  subtitle='%s의 주최/주관/후원 정보에요.' % hackathon_name,
                                                  buttons=[
                                                      PostBackButton(title='보기', payload='VIEW_SPONSOR')
                                                  ])
                                      ])
                                  )
                              ))
                          ])
        )

        # 일정 및 장소안내 / 3.1
        place_button = [
            PostBackButton(title='본행사 장소보기',
                           payload='VIEW_PLACE_OF_MAIN_MEETING')
        ]

        if self.data['place'].get('pre-meeting', False):
            place_button.insert(0, PostBackButton(title='사전일정 장소보기',
                                                  payload='VIEW_PLACE_OF_PRE_MEETING'))

        designer_brick.append(
            FacebookBrick(
                brick_type='postback',
                value='VIEW_SCHEDULE_AND_PLACE',
                actions=[
                    FacebookGeneralAction(
                        message=Message(
                            attachment=TemplateAttachment(
                                payload=GenericTemplate(
                                    elements=[
                                        Element(image_url=WORK_IMAGE_URL,
                                                title='%s의 진행 일정정보에요.' % hackathon_name,
                                                buttons=[
                                                    # 4
                                                    PostBackButton(title='일정보기',
                                                                   payload='VIEW_SCHEDULE')
                                                ]),
                                        Element(image_url=WORK_IMAGE_URL,
                                                title='%s이 진행되는 장소에요.' % hackathon_name,
                                                buttons=place_button)
                                    ]
                                )
                            )
                        )
                    )
                ]
            )
        )

        # 일정안내(1) / 4
        schedule_action = [
            FacebookGeneralAction(
                message=Message(
                    attachment=ImageAttachment(
                        url=self.data['basic']['poster_image']
                    )
                )
            ),
            FacebookGeneralAction(
                message=Message(
                    text='참가 신청 일정\n%s ~ %s' % (self.data['date']['application_period']['start'],
                                                self.data['date']['application_period']['end'])
                )
            )
        ]

        if self.data['contents'].get('pre-meeting', False):
            schedule_action.insert(1, FacebookGeneralAction(
                message=Message(
                    text='사전일정\n:%s\n사전일정 내용\n:%s' % (self.data['date']['pre-meeting'],
                                                      self.data['contents']['pre-meeting'])
                )
            ))

        now_date = dateutil.parser.parse(self.data['date']['main-meeting']['start'])
        for idx, content in enumerate(self.data['contents']['main-meeting']):
            if (idx+1) == len(self.data['contents']['main-meeting']):
                schedule_action.append(
                    FacebookGeneralAction(
                        message=Message(
                            attachment=TemplateAttachment(
                                payload=ButtonTemplate(
                                    text='본행사 %d년 %d월 %d일\n%s' % (now_date.year, now_date.month, now_date.day, content),
                                    buttons=[
                                        UrlButton(title='참가신청하기', url=self.data['application']['url'])
                                    ]
                                )
                            )
                        )
                    )
                )
            else:
                schedule_action.append(
                    FacebookGeneralAction(
                        message=Message(
                            text='본행사 %d년 %d월 %d일\n%s' % (now_date.year, now_date.month, now_date.day, content)
                        )
                    )
                )

            now_date = now_date + datetime.timedelta(days=1)

        designer_brick.append(
            FacebookBrick(
                brick_type='postback',
                value='VIEW_SCHEDULE',
                actions=schedule_action
            )
        )

        # 사전일정 장소안내 / 5
        if self.data['place'].get('pre-meeting', False):
            designer_brick.append(
                FacebookBrick(
                    brick_type='postback',
                    value='VIEW_PLACE_OF_PRE_MEETING',
                    actions=[
                        FacebookGeneralAction(
                            message=Message(
                                attachment=TemplateAttachment(
                                    payload=ButtonTemplate(
                                        text='{name}\n{address}'.format(**self.data['place']['pre-meeting']),
                                        buttons=[
                                            UrlButton(
                                                title='지도보기',
                                                url=self.data['place']['pre-meeting']['url']
                                            )
                                        ]
                                    )
                                )
                            )
                        )
                    ]
                )
            )

        # 본행사 장소안내 / 6
        if self.data['place'].get('main-meeting', False):
            designer_brick.append(
                FacebookBrick(
                    brick_type='postback',
                    value='VIEW_PLACE_OF_MAIN_MEETING',
                    actions=[
                        FacebookGeneralAction(
                            message=Message(
                                attachment=TemplateAttachment(
                                    payload=ButtonTemplate(
                                        text='{name}\n{address}'.format(**self.data['place']['main-meeting']),
                                        buttons=[
                                            UrlButton(
                                                title='지도보기',
                                                url=self.data['place']['main-meeting']['url']
                                            )
                                        ]
                                    )
                                )
                            )
                        )
                    ]
                )
            )

        # 참여요건 / 7
        designer_brick.append(
            FacebookBrick(
                brick_type='postback',
                value='VIEW_REQUIREMENTS',
                actions=[
                    FacebookGeneralAction(
                        message=Message(
                            text=self.data['application']['requirements']
                        )
                    ),
                    FacebookGeneralAction(
                        message=Message(
                            attachment=TemplateAttachment(
                                payload=ButtonTemplate(
                                    text=self.data['application']['preparation'],
                                    buttons=[
                                        UrlButton(title='참가신청하기', url=self.data['application']['url'])
                                    ]
                                )
                            )
                        )
                    )
                ]
            )
        )

        # 시상 및 참가혜택 / 8
        prize_text = '시상\n======================\n'
        for prize in self.data['prize']:
            prize_text += '{name} / {desc} / {benefit}\n'.format(**prize)

        designer_brick.append(
            FacebookBrick(
                brick_type='postback',
                value='VIEW_PRIZE_AND_BENEFIT',
                actions=[
                    FacebookGeneralAction(
                        message=Message(
                            text=prize_text
                        )
                    ),
                    FacebookGeneralAction(
                        message=Message(
                            attachment=TemplateAttachment(
                                payload=ButtonTemplate(
                                    text=self.data['benefit_of_participant'],
                                    buttons=[
                                        UrlButton(title='참가신청하기', url=self.data['application']['url'])
                                    ]
                                )
                            )
                        )
                    )
                ]
            )
        )

        # 문의하기 / 10
        designer_brick.append(
            FacebookBrick(
                brick_type='postback',
                value='CONTACT',
                actions=[
                    FacebookGeneralAction(
                        message=Message(
                            text='문의사항은 아래의 메일 / 전화를 이용해주세요.\n{email}\n{tel}'.format(**self.data['basic'])
                        )
                    )
                ]
            )
        )

        # 주최/주관/후원정보 / 11
        sponsor_text = []

        thanks = self.data['thanks']

        if thanks.get('hoster', False):
            if thanks['hoster'].strip() != '':
                sponsor_text.append('주최\n:%s' % thanks['hoster'])

        if thanks.get('organizer', False):
            if thanks['organizer'].strip() != '':
                sponsor_text.append('주관\n:%s' % thanks['organizer'])

        if thanks.get('sponsor', False):
            if thanks['sponsor'].strip() != '':
                sponsor_text.append('협찬\n:%s' % thanks['sponsor'])

        designer_brick.append(
            FacebookBrick(
                brick_type='postback',
                value='VIEW_SPONSOR',
                actions=[
                    FacebookGeneralAction(
                        message=Message(
                            attachment=ImageAttachment(url=WORK_IMAGE_URL)
                        )
                    ),
                    FacebookGeneralAction(
                        message=Message(
                            text='\n\n'.join(sponsor_text)
                        )
                    )
                ]
            )
        )

        return designer_brick
Beispiel #7
0
    async def facebook(self, command):
        if command == 'get_started':
            send_message = [
                Message(
                    attachment=ImageAttachment(
                        url=BRICK_DEFAULT_IMAGE
                    )
                ),
                Message(
                    text='경찰청에서 제공하는 "습득물조회 서비스"에요. 분류/지역/기간으로 조회기능과 위치기반으로 조회 기능을 제공해요.'
                ),
                Message(
                    attachment=TemplateAttachment(
                        payload=GenericTemplate(
                            elements=[
                                Element(
                                    image_url='https://www.chatbrick.io/api/static/brick/img_brick_02_002.png',
                                    title='분류/지역/기간으로 조회',
                                    subtitle='습득한 물품에 대한 분류, 지역, 기간 정보를 조회할 수 있어요.',
                                    buttons=[
                                        PostBackButton(
                                            title='조회하기',
                                            payload='brick|lostnfound|Menu1'
                                        )
                                    ]
                                ),
                                Element(
                                    image_url='https://www.chatbrick.io/api/static/brick/img_brick_02_002.png',
                                    title='위치기반으로 조회',
                                    subtitle='현재 위치주소와 근처에 위치한 지구대의 습득물 정보를 조회 할 수 있어요.',
                                    buttons=[
                                        PostBackButton(
                                            title='조회하기',
                                            payload='brick|lostnfound|Menu2'
                                        )
                                    ]
                                )
                            ]
                        )
                    )
                )
            ]
            await self.fb.send_messages(send_message)
            await self.brick_db.save(show_msg=False)
        elif command == 'Menu1':
            pass
        elif command == 'final':
            input_data = await self.brick_db.get()
            keyword = input_data['store'][0]['value']
            to = datetime.datetime.today()
            today = '%d-%02d-%02d' % (to.year, to.month, to.day)
            res = requests.get(
                url='http://openapi.mpm.go.kr/openapi/service/RetrievePblinsttEmpmnInfoService/getList?serviceKey=%s&pageNo=1&startPage=1&numOfRows=20&pageSize=20&Pblanc_ty=e01&Begin_de=%s&Sort_order=1&Kwrd=%s' % (
                    input_data['data']['api_key'], today, keyword))

            items = get_items_from_xml(res)

            if len(items) == 0:
                send_message = [
                    Message(
                        text='조회된 결과가 없습니다.',
                        quick_replies=QuickReply(
                            quick_reply_items=[
                                QuickReplyTextItem(
                                    title='다른 키워드검색',
                                    payload='brick|public_jobs|get_started'
                                )
                            ]
                        )
                    )
                ]
            else:
                sending_message = []
                for item in items:
                    sending_message.append('*{title}*\n{deptName}\n{regdate} ~ {enddate}'.format(**item))
                send_message = [
                    Message(
                        text='조회된 결과에요'
                    ),
                    Message(
                        text='\n\n'.join(sending_message),
                        quick_replies=QuickReply(
                            quick_reply_items=[
                                QuickReplyTextItem(
                                    title='다른 키워드검색',
                                    payload='brick|public_jobs|get_started'
                                )
                            ]
                        )
                    )
                ]

            await self.brick_db.delete()
            await self.fb.send_messages(send_message)
        return None
Beispiel #8
0
    def make_the_bricks(self):
        designer_brick = []
        # get_started (1.1, 1.2)
        designer_brick.append(
            FacebookBrick(
                brick_type='postback',
                value='get_started',
                actions=[
                    FacebookGeneralAction(message=Message(
                        text=self.data['custom_settings']['get_started'])),
                    FacebookGeneralAction(message=Message(
                        attachment=TemplateAttachment(payload=ListTemplate(
                            top_element_style='LARGE',
                            elements=[
                                Element(title=self.data['basic']['name'],
                                        image_url=self.data['basic']
                                        ['profile_image'],
                                        buttons=[
                                            PostBackButton(
                                                payload='VIEW_PROFILE',
                                                title='View')
                                        ]),
                                Element(title='Portfolio',
                                        subtitle='%s님의 포트폴리오를 보고 싶은가요?' %
                                        self.data['basic']['name'],
                                        buttons=[
                                            PostBackButton(
                                                payload='VIEW_PORTFOLIO',
                                                title='View')
                                        ]),
                                Element(title='Contact',
                                        subtitle='%s님에게 이메일을 보내고 싶은가요?' %
                                        self.data['basic']['name'],
                                        buttons=[
                                            PostBackButton(payload='CONTACT',
                                                           title='View')
                                        ])
                            ]))))
                ]))
        # Profile(1) / 2
        designer_brick.append(
            FacebookBrick(
                brick_type='postback',
                value='VIEW_PROFILE',
                actions=[
                    FacebookGeneralAction(message=Message(
                        attachment=TemplateAttachment(payload=GenericTemplate(
                            elements=[
                                Element(
                                    title=self.data['basic']['name'],
                                    subtitle='{special}\n{residence}'.format(
                                        **self.data['basic']),
                                    image_url=self.data['basic']
                                    ['profile_image'],
                                    buttons=[
                                        PostBackButton(
                                            title='Work',
                                            payload='VIEW_USERS_WORK'),
                                        PostBackButton(
                                            title='Specialties',
                                            payload='VIEW_USERS_SPECIALTIES'),
                                        PostBackButton(
                                            title='Summary',
                                            payload='VIEW_USERS_SUMMARY'),
                                    ],
                                    default_action={
                                        'type': 'web_url',
                                        'url': self.data['basic']['social'],
                                        'webview_height_ratio': 'tall'
                                    })
                            ]))))
                ]))

        # Work / 2.1.1
        if len(self.data['work']):
            work_element = [
                Element(title='Work',
                        subtitle='%s님의 경력 사항입니다.' % self.data['basic']['name'],
                        image_url=WORK_IMAGE_URL)
            ]

            for work in self.data['work']:
                work_element.append(
                    Element(title=work['name'],
                            subtitle='{period}\n{field}'.format(**work)))

            designer_brick.append(
                FacebookBrick(
                    brick_type='postback',
                    value='VIEW_USERS_WORK',
                    actions=[
                        FacebookGeneralAction(message=Message(
                            attachment=TemplateAttachment(payload=ListTemplate(
                                elements=work_element,
                                top_element_style='LARGE',
                                buttons=[
                                    PostBackButton(title='Menu',
                                                   payload='get_started')
                                ]))))
                    ]))
        else:
            designer_brick.append(
                FacebookBrick(brick_type='postback',
                              value='VIEW_USERS_WORK',
                              actions=[
                                  FacebookGeneralAction(message=Message(
                                      text='%s님이 아직 Work 항목을 입력하지 않았습니다.' %
                                      self.data['basic']['name']))
                              ]))

        # Specialties / 2.1.2
        if len(self.data['specialties']):
            special_element = [
                Element(title='Specialties',
                        subtitle='%s님의 보유기술 및 능력입니다.' %
                        self.data['basic']['name'],
                        image_url=SPECIALTIES_IMAGE_URL)
            ]

            for special in self.data['specialties']:
                special_element.append(
                    Element(title=special['name'], subtitle=special['detail']))

            designer_brick.append(
                FacebookBrick(
                    brick_type='postback',
                    value='VIEW_USERS_SPECIALTIES',
                    actions=[
                        FacebookGeneralAction(message=Message(
                            attachment=TemplateAttachment(payload=ListTemplate(
                                elements=special_element,
                                top_element_style='LARGE',
                                buttons=[
                                    PostBackButton(title='Menu',
                                                   payload='get_started')
                                ]))))
                    ]))
        else:
            designer_brick.append(
                FacebookBrick(
                    brick_type='postback',
                    value='VIEW_USERS_SPECIALTIES',
                    actions=[
                        FacebookGeneralAction(message=Message(
                            text='%s님이 아직 Specialties 항목을 입력하지 않았습니다.' %
                            self.data['basic']['name']))
                    ]))

        # Summary / 2.1.3
        if self.data['summary']:
            designer_brick.append(
                FacebookBrick(brick_type='postback',
                              value='VIEW_USERS_SUMMARY',
                              actions=[
                                  FacebookGeneralAction(message=Message(
                                      attachment=ImageAttachment(
                                          url=SUMMARY_IMAGE_URL))),
                                  FacebookGeneralAction(message=Message(
                                      text=self.data['summary']))
                              ]))
        else:
            designer_brick.append(
                FacebookBrick(brick_type='postback',
                              value='VIEW_USERS_SUMMARY',
                              actions=[
                                  FacebookGeneralAction(message=Message(
                                      text='%s님이 아직 Summary 항목을 입력하지 않았습니다.' %
                                      self.data['basic']['name']))
                              ]))

        # Contact / 4
        if self.data['basic'].get('email', False):
            designer_brick.append(
                FacebookBrick(
                    brick_type='postback',
                    value='CONTACT',
                    actions=[
                        FacebookGeneralAction(message=Message(
                            attachment=TemplateAttachment(
                                payload=GenericTemplate(elements=[
                                    Element(
                                        title='Contact',
                                        subtitle=
                                        '자세한 문의는 아래의 메일보내기 버튼을 이용해주세요.',
                                        image_url=CONTACT_IMAGE_URL,
                                        buttons=[
                                            PostBackButton(
                                                title='Send E-Mail',
                                                payload='SEND_EMAIL_TO_USER')
                                        ])
                                ]))))
                    ]))
        else:
            designer_brick.append(
                FacebookBrick(brick_type='postback',
                              value='CONTACT',
                              actions=[
                                  FacebookGeneralAction(message=Message(
                                      text='%s님이 아직 이메일을 입력하지 않았습니다.' %
                                      self.data['basic']['name']))
                              ]))

        if self.data.get('portfolio', False) and self.data['portfolio']:
            temp_element = []

            for portfolio in self.data['portfolio'][:10]:
                res = requests.get(portfolio,
                                   headers={
                                       'User-Agent':
                                       'TelegramBot (like TwitterBot)',
                                       'Accept': 'text/html'
                                   })

                soup = BeautifulSoup(res.text, 'lxml')

                temp_element.append(
                    Element(title=soup.find('meta', {
                        'property': 'og:title'
                    }).get('content'),
                            subtitle=soup.find('meta', {
                                'property': 'og:description'
                            }).get('content'),
                            image_url=soup.find('meta', {
                                'property': 'og:image'
                            }).get('content'),
                            buttons=[UrlButton(title='View', url=portfolio)]))

            designer_brick.append(
                FacebookBrick(brick_type='postback',
                              value='VIEW_PORTFOLIO',
                              actions=[
                                  FacebookGeneralAction(message=Message(
                                      attachment=TemplateAttachment(
                                          payload=GenericTemplate(
                                              elements=temp_element))))
                              ]))
        else:
            designer_brick.append(
                FacebookBrick(
                    brick_type='postback',
                    value='VIEW_PORTFOLIO',
                    actions=[
                        FacebookGeneralAction(message=Message(
                            text='%s님이 아직 Portfolio 항목을 입력하지 않았습니다.' %
                            self.data['basic']['name']))
                    ]))

        designer_brick.append(
            FacebookBrick(
                brick_type='postback',
                value='SEND_EMAIL_TO_USER',
                actions=[FacebookBrickAction(brick_id='mailer', data=[])]))

        return designer_brick