Пример #1
0
def update_datetimepicker(event,id):
    """日付の更新用のボタンテンプレートメッセージ
    Args:
        event (linebot.models.events.MessageEvent): LINE Webhookイベントオブジェクト
        id (dict)  parse_pbd = urllib.parse.parse_qs(postback_data)
                   id=parse_pbd["reminders_id"] カルーセルメッセージオブジェクトに紐づけられたid
    """
    now_date = datetime.now(timezone('Asia/Tokyo')).strftime("%Y-%m-%dt%H:%M")
    new_datetimepicker = TemplateSendMessage(
        alt_text='時間を入力するぽん',
        template=ButtonsTemplate(
            text= '変更後の時間を入力するぽん',
            actions=[
                DatetimePickerTemplateAction(
                    label='設定',
                    data='dateupdater&reminders_id=' +str(id[0]),
                    mode='datetime',
                    initial=now_date,
                    min=now_date,
                    max='2099-12-31t23:59'
                )
            ]
        )
    )
    reply_message(event.reply_token, new_datetimepicker)
Пример #2
0
def choice_datatime(type):
    now_time = datetime.datetime.now().strftime("%Y-%m-%d")
    max_time_tmp = datetime.datetime.now()+datetime.timedelta(days=365)
    max_time = max_time_tmp.strftime("%Y-%m-%d")
    print(now_time)
    print(max_time)
    if(type == type_of_return):
        title_string = " 請選擇回國日期"
        text_string = "選擇日期"
    else:
        title_string = " 請選擇啟程日期"
        text_string = "選擇日期"
    buttons_template_message = TemplateSendMessage(
        alt_text='DatetimePicker',
        template=ButtonsTemplate(
            title=title_string,
            text=text_string,
            actions=[
                DatetimePickerTemplateAction(
                    label=title_string,
                    mode="date",
                    data=type,
                    initial=now_time,
                    max="2018-10-30",
                    min="2018-06-04"
                )
            ]
        )
    )
    return buttons_template_message
Пример #3
0
def create_datepicker(context):
    """
    datepickerオブジェクト作成method
    Args:
        context (str): 会話から受け取った予定
    Rerurns:
        linebot.models.template.TemplateSendMessage: datepickerオブジェクト
    """
    now_date = datetime.now(timezone('Asia/Tokyo')).strftime("%Y-%m-%dt%H:%M")
    date_picker = TemplateSendMessage(
        alt_text='「' + context + '」をいつ教えてほしいぽん?',
        template=ButtonsTemplate(
            text= '「' + context + '」をいつ教えてほしいぽん?\n「キャンセル」って言ってくれればやめるたぬ~',
            actions=[
                DatetimePickerTemplateAction(
                    label='設定',
                    data='createdatepicker',
                    mode='datetime',
                    initial=now_date,
                    min=now_date,
                    max='2099-12-31t23:59'
                )
            ]
        )
    )

    return date_picker
Пример #4
0
def sendDatetime(event):  #日期時間
    try:
        message = TemplateSendMessage(
            alt_text='日期時間範例',
            template=ButtonsTemplate(
                thumbnail_image_url='https://i.imgur.com/VxVB46z.jpg',
                title='日期時間示範',
                text='請選擇:',
                actions=[
                    DatetimePickerTemplateAction(
                        label="選取日期",
                        data="action=sell&mode=date",  #觸發postback事件
                        mode="date",  #選取日期
                        initial="2019-06-01",  #顯示初始日期
                        min="2019-01-01",  #最小日期
                        max="2020-12-31"  #最大日期
                    ),
                    DatetimePickerTemplateAction(
                        label="選取時間",
                        data="action=sell&mode=time",
                        mode="time",  #選取時間
                        initial="10:00",
                        min="00:00",
                        max="23:59"
                    ),
                    DatetimePickerTemplateAction(
                        label="選取日期時間",
                        data="action=sell&mode=datetime",
                        mode="datetime",  #選取日期時間
                        initial="2019-06-01T10:00",
                        min="2019-01-01T00:00",
                        max="2020-12-31T23:59"
                    )
                ]
            )
        )
        line_bot_api.reply_message(event.reply_token,message)
    except:
        line_bot_api.reply_message(event.reply_token,TextSendMessage(text='發生錯誤!'))
Пример #5
0
def sendDatetime(event, backdata):  #日期時間
    try:
        message = TemplateSendMessage(
            alt_text='日期時間選取',
            template=ButtonsTemplate(
                thumbnail_image_url=
                'https://upload.cc/i1/2020/02/23/CrfWMt.png',
                title='日期時間示範',
                text='請選擇:',
                actions=[
                    DatetimePickerTemplateAction(
                        label="選取日期",
                        data="action=sellDate&mode=date",  #觸發postback事件
                        mode="date",  #選取日期
                        initial="2020-05-01",  #顯示初始日期
                        min="2020-05-01",  #最小日期
                        max="2020-12-31"  #最大日期
                    ),
                    DatetimePickerTemplateAction(
                        label="選取時間",
                        data="action=sellDate&mode=time",
                        mode="time",  #選取時間
                        initial="10:00",
                        min="00:00",
                        max="23:59"),
                    DatetimePickerTemplateAction(
                        label="選取日期時間",
                        data="action=sellDate&mode=datetime",
                        mode="datetime",  #選取日期時間
                        initial="2020-05-01T10:00",
                        min="2020-05-01T00:00",
                        max="2020-12-31T23:59")
                ]))
        line_bot_api.reply_message(event.reply_token, message)
    except:
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text='sendDatetime發生錯誤!'))
def arrival_datepicker(destination_name):
    now_date = datetime.datetime.now().isoformat()
    regex  = re.findall(r"[0-9]{4}-[0-9]{2}-[0-9]{2}|[0-9]{2}:[0-9]{2}", now_date)
    tstr = regex[0] + "T" + regex[1]

    return FlexSendMessage("集合時間", BubbleContainer(
        size="mega",
        header=BoxComponent(
            layout="vertical",
            contents=[
                TextComponent(
                    text=destination_name,
                    align="center",
                    size="lg"
                ),
            ]),
        body=BoxComponent(
            layout="vertical",
            contents=[
                TextComponent(
                    text="集合時間を入力してください",
                    align="center",
                    size="sm"
                ),
                ButtonComponent(
                    style="link",
                    height="sm",
                    action=DatetimePickerTemplateAction(
                        label="集合時間設定",
                        data="action=buy&itemid=2&mode=datetime",
                        mode="datetime",
                        initial=tstr,
                        min=tstr,
                        max="2099-12-31T23:59"
                    )
                )
            ]
        ),
        styles=BubbleStyle(body=BlockStyle(background_color="#ffffff"))
    ))
Пример #7
0
def set_duration_message(line_bot_api, reply_token):
    # 確実に日本時間での時間を取得する
    initial_date = datetime.datetime.utcnow() + datetime.timedelta(hours=9)
    limit_date = initial_date + datetime.timedelta(days=90)
    date_picker = TemplateSendMessage(
        alt_text="終了予定日を設定",
        template=ButtonsTemplate(
            title="終了予定日",
            text="終了予定日を設定します。",
            actions=[
                DatetimePickerTemplateAction(
                    label="日付を選択",
                    data="action=set_end_day",
                    mode="date",
                    initial=get_date(initial_date +
                                     datetime.timedelta(days=30)),
                    min=get_date(initial_date),
                    max=get_date(limit_date))
            ]))
    line_bot_api.reply_message(
        reply_token,
        [TextSendMessage(text="期限を選択してください。(最大90日先まで選択可能)"), date_picker])
Пример #8
0
def handle_message(event):
    text = event.message.text
    if 'こんにちは' in text:
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text='Hello World'))
    elif '日付' in text:
        date_picker = TemplateSendMessage(
            alt_text='予定日を設定',
            template=ButtonsTemplate(text='予定日を設定',
                                     title='YYYY-MM-dd',
                                     actions=[
                                         DatetimePickerTemplateAction(
                                             label='設定',
                                             data='action=buy&itemid=1',
                                             mode='date',
                                             initial='2017-04-01',
                                             min='2017-04-01',
                                             max='2099-12-31')
                                     ]))
    else:
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text='「' + text + '」って何?'))
Пример #9
0
def handle_text_message(event):
    text = event.message.text

    if text == 'profile':
        if isinstance(event.source, SourceUser):
            profile = line_bot_api.get_profile(event.source.user_id)
            line_bot_api.reply_message(
                event.reply_token, [
                    TextSendMessage(
                        text='Display name: ' + profile.display_name
                    ),
                    TextSendMessage(
                        text='Status message: ' + profile.status_message
                    )
                ]
            )
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextMessage(text="Bot can't use profile API without user ID"))
    elif text == 'bye':
        if isinstance(event.source, SourceGroup):
            line_bot_api.reply_message(
                event.reply_token, TextMessage(text='Leaving group'))
            line_bot_api.leave_group(event.source.group_id)
        elif isinstance(event.source, SourceRoom):
            line_bot_api.reply_message(
                event.reply_token, TextMessage(text='Leaving group'))
            line_bot_api.leave_room(event.source.room_id)
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextMessage(text="Bot can't leave from 1:1 chat"))
    elif text == 'confirm':
        confirm_template = ConfirmTemplate(text='Do it?', actions=[
            MessageTemplateAction(label='Yes', text='Yes!'),
            MessageTemplateAction(label='No', text='No!'),
        ])
        template_message = TemplateSendMessage(
            alt_text='Confirm alt text', template=confirm_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'buttons':
        buttons_template = ButtonsTemplate(
            title='My buttons sample', text='Hello, my buttons', actions=[
                URITemplateAction(
                    label='Go to line.me', uri='https://line.me'),
                PostbackTemplateAction(label='ping', data='ping'),
                PostbackTemplateAction(
                    label='ping with text', data='ping',
                    text='ping'),
                MessageTemplateAction(label='Translate Rice', text='米')
            ])
        template_message = TemplateSendMessage(
            alt_text='Buttons alt text', template=buttons_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'carousel':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(text='hoge1', title='fuga1', actions=[
                URITemplateAction(
                    label='Go to line.me', uri='https://line.me'),
                PostbackTemplateAction(label='ping', data='ping')
            ]),
            CarouselColumn(text='hoge2', title='fuga2', actions=[
                PostbackTemplateAction(
                    label='ping with text', data='ping',
                    text='ping'),
                MessageTemplateAction(label='Translate Rice', text='米')
            ]),
        ])
        template_message = TemplateSendMessage(
            alt_text='Carousel alt text', template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'image_carousel':
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
                                action=DatetimePickerTemplateAction(label='datetime',
                                                                    data='datetime_postback',
                                                                    mode='datetime')),
            ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
                                action=DatetimePickerTemplateAction(label='date',
                                                                    data='date_postback',
                                                                    mode='date'))
        ])
        template_message = TemplateSendMessage(
            alt_text='ImageCarousel alt text', template=image_carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'imagemap':
        pass
    else:
        line_bot_api.reply_message(
            event.reply_token, TextSendMessage(text=event.message.text))
Пример #10
0
    def setUp(self):
        self.tested = LineBotApi('d42b9b5dc4df7ad44e9bddd5ee915fc7')

        self.button_template_message = TemplateSendMessage(
            alt_text='Buttons template',
            template=ButtonsTemplate(
                thumbnail_image_url='https://example.com/image.jpg',
                title='Menu',
                text='Please select',
                actions=[
                    PostbackTemplateAction(label='postback',
                                           text='postback text',
                                           data='action=buy&itemid=1'),
                    MessageTemplateAction(label='message',
                                          text='message text'),
                    URITemplateAction(label='uri', uri='http://example.com/')
                ]))

        self.button_message = [{
            "type": "template",
            "altText": "Buttons template",
            "template": {
                "type":
                "buttons",
                "thumbnailImageUrl":
                "https://example.com/image.jpg",
                "imageAspectRatio":
                None,
                "imageSize":
                None,
                "imageBackgroundColor":
                None,
                "title":
                "Menu",
                "text":
                "Please select",
                "actions": [{
                    "type": "postback",
                    "label": "postback",
                    "text": "postback text",
                    "data": "action=buy&itemid=1"
                }, {
                    "type": "message",
                    "label": "message",
                    "text": "message text"
                }, {
                    "type": "uri",
                    "label": "uri",
                    "uri": "http://example.com/"
                }]
            }
        }]

        self.confirm_template_message = TemplateSendMessage(
            alt_text='Confirm template',
            template=ConfirmTemplate(
                text='Are you sure?',
                actions=[
                    PostbackTemplateAction(label='postback',
                                           text='postback text',
                                           data='action=buy&itemid=1'),
                    MessageTemplateAction(label='message', text='message text')
                ]))

        self.confirm_message = [{
            "type": "template",
            "altText": "Confirm template",
            "template": {
                "type":
                "confirm",
                "text":
                "Are you sure?",
                "actions": [{
                    "type": "postback",
                    "label": "postback",
                    "text": "postback text",
                    "data": "action=buy&itemid=1"
                }, {
                    "type": "message",
                    "label": "message",
                    "text": "message text"
                }]
            }
        }]

        self.carousel_template_message = TemplateSendMessage(
            alt_text='Carousel template',
            template=CarouselTemplate(columns=[
                CarouselColumn(
                    thumbnail_image_url='https://example.com'
                    '/item1.jpg',
                    title='this is menu1',
                    text='description1',
                    actions=[
                        PostbackTemplateAction(label='postback1',
                                               text='postback text1',
                                               data='action=buy&itemid=1'),
                        MessageTemplateAction(label='message1',
                                              text='message text1'),
                        URITemplateAction(label='uri1',
                                          uri='http://example.com/1')
                    ]),
                CarouselColumn(
                    thumbnail_image_url='https://example.com'
                    '/item2.jpg',
                    image_background_color='#000000',
                    title='this is menu2',
                    text='description2',
                    actions=[
                        PostbackTemplateAction(label='postback2',
                                               text='postback text2',
                                               data='action=buy&itemid=2'),
                        MessageTemplateAction(label='message2',
                                              text='message text2'),
                        URITemplateAction(label='uri2',
                                          uri='http://example.com/2')
                    ]),
                CarouselColumn(
                    thumbnail_image_url='https://example.com'
                    '/item3.jpg',
                    title='this is menu3',
                    text='description3',
                    actions=[
                        DatetimePickerTemplateAction(
                            label="datetime picker date",
                            data="action=sell&itemid=2&mode=date",
                            mode="date",
                            initial="2013-04-01",
                            min="2011-06-23",
                            max="2017-09-08"),
                        DatetimePickerTemplateAction(
                            label="datetime picker time",
                            data="action=sell&itemid=2&mode=time",
                            mode="time",
                            initial="10:00",
                            min="00:00",
                            max="23:59"),
                        DatetimePickerTemplateAction(
                            label="datetime picker datetime",
                            data="action=sell&itemid=2&mode=datetime",
                            mode="datetime",
                            initial="2013-04-01T10:00",
                            min="2011-06-23T00:00",
                            max="2017-09-08T23:59")
                    ])
            ]))

        self.carousel_message = [{
            "type": "template",
            "altText": "Carousel template",
            "template": {
                "type":
                "carousel",
                "columns": [{
                    "thumbnailImageUrl":
                    "https://example.com/item1.jpg",
                    "imageBackgroundColor":
                    None,
                    "title":
                    "this is menu1",
                    "text":
                    "description1",
                    "actions": [{
                        "type": "postback",
                        "label": "postback1",
                        "text": "postback text1",
                        "data": "action=buy&itemid=1"
                    }, {
                        "type": "message",
                        "label": "message1",
                        "text": "message text1"
                    }, {
                        "type": "uri",
                        "label": "uri1",
                        "uri": "http://example.com/1"
                    }]
                }, {
                    "thumbnailImageUrl":
                    "https://example.com/item2.jpg",
                    "imageBackgroundColor":
                    "#000000",
                    "title":
                    "this is menu2",
                    "text":
                    "description2",
                    "actions": [{
                        "type": "postback",
                        "label": "postback2",
                        "text": "postback text2",
                        "data": "action=buy&itemid=2"
                    }, {
                        "type": "message",
                        "label": "message2",
                        "text": "message text2"
                    }, {
                        "type": "uri",
                        "label": "uri2",
                        "uri": "http://example.com/2"
                    }]
                }, {
                    "thumbnailImageUrl":
                    "https://example.com/item3.jpg",
                    "imageBackgroundColor":
                    None,
                    "title":
                    "this is menu3",
                    "text":
                    "description3",
                    "actions": [{
                        "type": "datetimepicker",
                        "label": "datetime picker date",
                        "data": "action=sell&itemid=2&mode=date",
                        "mode": "date",
                        "initial": "2013-04-01",
                        "min": "2011-06-23",
                        "max": "2017-09-08"
                    }, {
                        "type": "datetimepicker",
                        "label": "datetime picker time",
                        "data": "action=sell&itemid=2&mode=time",
                        "mode": "time",
                        "initial": "10:00",
                        "min": "00:00",
                        "max": "23:59"
                    }, {
                        "type": "datetimepicker",
                        "label": "datetime picker datetime",
                        "data": "action=sell&itemid=2&mode=datetime",
                        "mode": "datetime",
                        "initial": "2013-04-01T10:00",
                        "min": "2011-06-23T00:00",
                        "max": "2017-09-08T23:59"
                    }]
                }],
                "imageAspectRatio":
                None,
                "imageSize":
                None
            }
        }]

        self.image_carousel_template_message = TemplateSendMessage(
            alt_text='Image carousel template',
            template=ImageCarouselTemplate(columns=[
                ImageCarouselColumn(image_url='https://example.com/'
                                    'item1.jpg',
                                    action=PostbackTemplateAction(
                                        label='postback1',
                                        data='action=buy&itemid=1')),
                ImageCarouselColumn(
                    image_url='https://example.com'
                    '/item2.jpg',
                    action=MessageTemplateAction(label='message2',
                                                 text='message text2')),
                ImageCarouselColumn(image_url='https://example.com/'
                                    'item3.jpg',
                                    action=URITemplateAction(
                                        label='uri1',
                                        uri='https://example.com/1'))
            ]))

        self.image_carousel_message = [{
            "type": "template",
            "altText": "Image carousel template",
            "template": {
                "type":
                "image_carousel",
                "columns": [{
                    "imageUrl": "https://example.com/item1.jpg",
                    "action": {
                        "type": "postback",
                        "label": "postback1",
                        "data": "action=buy&itemid=1",
                        "text": None
                    }
                }, {
                    "imageUrl": "https://example.com/item2.jpg",
                    "action": {
                        "type": "message",
                        "label": "message2",
                        "text": "message text2"
                    }
                }, {
                    "imageUrl": "https://example.com/item3.jpg",
                    "action": {
                        "type": "uri",
                        "label": "uri1",
                        "uri": "https://example.com/1"
                    }
                }]
            }
        }]
Пример #11
0
def handle_text_message(event):

	text=event.message.text
	
	if isinstance(event.source, SourceGroup):
		subject = line_bot_api.get_group_member_profile(event.source.group_id,
														event.source.user_id)
		set_id = event.source.group_id
	elif isinstance(event.source, SourceRoom):
		subject = line_bot_api.get_room_member_profile(event.source.room_id,
                                                   event.source.user_id)
		set_id = event.source.room_id
	else:
		subject = line_bot_api.get_profile(event.source.user_id)
		set_id = event.source.user_id
	
	def split1(text):
		return text.split('/wolfram ', 1)[-1]
		
	def split2(text):
		return text.split('/kbbi ', 1)[-1]
		
	def split3(text):
		return text.split('/echo ', 1)[-1]

	def split4(text):
		return text.split('/wolframs ', 1)[-1]
	
	def split5(text):
		return text.split('/trans ', 1)[-1]
	
	def split6(text):
		return text.split('/wiki ', 1)[-1]
	
	def split7(text):
		return text.split('/wikilang ', 1)[-1]
		
	def split8(text):
		return text.split('/urban ', 1)[-1]

	def split9(text):
		return text.split('/ox ', 1)[-1]
		
	def ox(keyword):
		oxdict_appid = ('7dff6c56')
		oxdict_key = ('41b55bba54078e9fb9f587f1b978121f')
		
		word = quote(keyword)
		url = ('https://od-api.oxforddictionaries.com:443/api/v1/entries/en/{}'.format(word))
		req = requests.get(url, headers={'app_id': oxdict_appid, 'app_key': oxdict_key})
		if "No entry available" in req.text:
			return 'No entry available for "{}".'.format(word)

		req = req.json()
		result = ''
		i = 0
		for each_result in req['results']:
			for each_lexEntry in each_result['lexicalEntries']:
				for each_entry in each_lexEntry['entries']:
					for each_sense in each_entry['senses']:
						if 'crossReferenceMarkers' in each_sense:
							search = 'crossReferenceMarkers'
						else:
							search = 'definitions'
						for each_def in each_sense[search]:
							i += 1
							result += '\n{}. {}'.format(i, each_def)

		if i == 1:
			result = 'Definition of {}:\n'.format(keyword) + result[4:]
		else:
			result = 'Definitions of {}:'.format(keyword) + result
		return result

	
	def wolfram(query):
		wolfram_appid = ('83L4JP-TWUV8VV7J7')

		url = 'https://api.wolframalpha.com/v2/result?i={}&appid={}'
		return requests.get(url.format(quote(query), wolfram_appid)).text
		
	def wolframs(query):
		wolfram_appid = ('83L4JP-TWUV8VV7J7')

		url = 'https://api.wolframalpha.com/v2/simple?i={}&appid={}'
		return url.format(quote(query), wolfram_appid)
	
	def trans(word):
		sc = 'en'
		to = 'id'
		
		if word[0:].lower().strip().startswith('sc='):
			sc = word.split(', ', 1)[0]
			sc = sc.split('sc=', 1)[-1]
			word = word.split(', ', 1)[1]
	
		if word[0:].lower().strip().startswith('to='):
			to = word.split(', ', 1)[0]
			to = to.split('to=', 1)[-1]
			word = word.split(', ', 1)[1]
			
		if word[0:].lower().strip().startswith('sc='):
			sc = word.split(', ', 1)[0]
			sc = sc.split('sc=', 1)[-1]
			word = word.split(', ', 1)[1]
			
		return translator.translate(word, src=sc, dest=to).text
		
	def wiki_get(keyword, set_id, trim=True):
    
		try:
			wikipedia.set_lang(wiki_settings[set_id])
		except KeyError:
			wikipedia.set_lang('en')

		try:
			result = wikipedia.summary(keyword)

		except wikipedia.exceptions.DisambiguationError:
			articles = wikipedia.search(keyword)
			result = "{} disambiguation:".format(keyword)
			for item in articles:
				result += "\n{}".format(item)
		except wikipedia.exceptions.PageError:
			result = "{} not found!".format(keyword)

		else:
			if trim:
				result = result[:2000]
				if not result.endswith('.'):
					result = result[:result.rfind('.')+1]
		return result
		
	def wiki_lang(lang, set_id):
    
		langs_dict = wikipedia.languages()
		if lang in langs_dict.keys():
			wiki_settings[set_id] = lang
			return ("Language has been changed to {} successfully."
					.format(langs_dict[lang]))

		return ("{} not available!\n"
				"See meta.wikimedia.org/wiki/List_of_Wikipedias for "
				"a list of available languages, and use the prefix "
				"in the Wiki column to set the language."
				.format(lang))	
	
	def find_kbbi(keyword, ex=True):

		try:
			entry = KBBI(keyword)
		except KBBI.TidakDitemukan as e:
			result = str(e)
		else:
			result = "Definisi {}:\n".format(keyword)
			if ex:
				result += '\n'.join(entry.arti_contoh)
			else:
				result += str(entry)
		return result
	
	def urban(keyword, ex=True):
		
		try:
			entry = udtop(keyword)
		except (TypeError, AttributeError, udtop.TermNotFound) :
			result = "{} definition not found in urbandictionary.".format(keyword)
		else:
			result = "{} definition:\n".format(keyword)
			if ex:
				result += str(entry)
			else:
				result += entry.definition
		return result
	
	if text == '/help':
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage('I will be here for you'))
	
	elif text == '/leave':
		if isinstance(event.source, SourceGroup):
			line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('I am leaving the group...'))
			line_bot_api.leave_group(event.source.group_id)
		
		elif isinstance(event.source, SourceRoom):
			line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('I am leaving the group...'))
			line_bot_api.leave_room(event.source.room_id)
			
		else:
			line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('>_< cannot do...'))
	
	elif text == '/about':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("Hello, my name is Reika \n"
								"Nice to meet you... \n"
								"source code: https://github.com/Vetrix/ZERO"))
	
	elif text == '/cmd':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("Without parameters: \n"
								"/about, /help, /profile, /leave, /lang \n"
								"/confirm, /buttons, /search image, \n"
								"/manga, /dots, /track, /bet \n"
								"/image_carousel, /imagemap \n"
								"\n"
								"With parameters: \n"
								"/echo, /kbbi, /wolfram, /wolframs, \n"
								"/trans, /wiki, /wikilang, /urban, /ox"))
	
	elif text == '/lang':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("Language for translation see here \n"
								"https://github.com/Vetrix/ZERO/blob/master/Lang.txt"))
	
	elif text == '/manga':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("mangaku.in"))
	
	elif text == '/dots':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("https://www.instagram.com/dotaindonesia2/"))
	
	elif text == '/track':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("http://dota2.prizetrac.kr/international2018"))
	
	elif text == '/bet':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("dota2.com/predictions"))
	
	elif text == '/search image':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("Try this up \n"
								"https://reverse.photos/"))
	
	elif text == '/profile':
		if isinstance(event.source, SourceGroup):
			try:
				profile = line_bot_api.get_group_member_profile(event.source.group_id, event.source.user_id)
				result = ("Display name: " + profile.display_name + "\n" +
						  "Profile picture: " + profile.picture_url + "\n" +
						  "User_ID: " + profile.user_id)
			except LineBotApiError:
				pass	
			line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage(result))
			
		
		elif isinstance(event.source, SourceRoom):
			try:
				profile = line_bot_api.get_room_member_profile(event.source.room_id, event.source.user_id)
				result = ("Display name: " + profile.display_name + "\n" +
						  "Profile picture: " + profile.picture_url + "\n" +
						  "User_ID: " + profile.user_id)
			except LineBotApiError:
				pass	
			line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage(result))
			
				
		else:
			try:
				profile = line_bot_api.get_profile(event.source.user_id)
				result = ("Display name: " + profile.display_name + "\n" +
						  "Profile picture: " + profile.picture_url + "\n" +
						  "User_ID: " + profile.user_id)
				if profile.status_message:
					result += "\n" + "Status message: " + profile.status_message
			except LineBotApiError:
				pass
			line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage(result))
	
	elif text=='/kbbi':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('command /kbbi {input}'))
	
	elif text=='/urban':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('command /urban {input}'))
	
	elif text=='/ox':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('command /ox {input}'))
	
	elif text=='/wolfram':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('command /wolfram {input}'))
				
	elif text=='/trans':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('command /trans sc={}, to={}, {text}'))
	
	elif text=='/wiki':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('command /wiki {text}'))
				
	elif text=='/wikilang':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage('command /wikilang {language_id}'))
	
	elif text == '/confirm':
		confirm_template = ConfirmTemplate(text='Do it?', actions=[
			MessageTemplateAction(label='Yes', text='Yes!'),
			MessageTemplateAction(label='No', text='No!'),
			])
		template_message = TemplateSendMessage(
			alt_text='Confirm alt text', template=confirm_template)
		line_bot_api.reply_message(event.reply_token, template_message)
	
	elif text == '/buttons':
		buttons_template = ButtonsTemplate(
			title='My buttons sample', text='Hello, my buttons', actions=[
				URITemplateAction(
					label='Go to line.me', uri='https://line.me'),
				PostbackTemplateAction(label='ping', data='ping'),
				PostbackTemplateAction(
					label='ping with text', data='ping',
					text='ping'),
				MessageTemplateAction(label='Translate Rice', text='米')
			])
		template_message = TemplateSendMessage(
			alt_text='Buttons alt text', template=buttons_template)
		line_bot_api.reply_message(event.reply_token, template_message)
	
	elif text == '/image_carousel':
		image_carousel_template = ImageCarouselTemplate(columns=[
			ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
								action=DatetimePickerTemplateAction(label='datetime',
																	data='datetime_postback',
																	mode='datetime')),
			ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
								action=DatetimePickerTemplateAction(label='date',
																	data='date_postback',
																	mode='date'))
		])
		template_message = TemplateSendMessage(
			alt_text='ImageCarousel alt text', template=image_carousel_template)
		line_bot_api.reply_message(event.reply_token, template_message)
		
	elif text == '/imagemap':
		pass
	
	elif text[0:].lower().strip().startswith('/wolfram '):
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage(wolfram(split1(text))))
			
	elif text[0:].lower().strip().startswith('/wolframs '):
		line_bot_api.reply_message(
			event.reply_token,
			ImageSendMessage(original_content_url= wolframs(split4(text)),
								preview_image_url= wolframs(split4(text))))

	elif text[0:].lower().strip().startswith('/kbbi '):
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage(find_kbbi(split2(text))))
			
	elif text[0:].lower().strip().startswith('/urban '):
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage(urban(split8(text))))
			
	elif text[0:].lower().strip().startswith('/ox '):
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage(ox(split9(text))))
			
	elif text[0:].lower().strip().startswith('/echo ') :
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage(split3(text)))
			
	elif text[0:].lower().strip().startswith('/trans ') :
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage(trans(split5(text))))
	
	elif text[0:].lower().strip().startswith('/wiki ') :
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage(wiki_get(split6(text), set_id=set_id)))
			
	elif text[0:].lower().strip().startswith('/wikilang ') :
		line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage(wiki_lang(split7(text), set_id=set_id)))
Пример #12
0
def handle_text_message(event):
    text = event.message.text

    if text == 'profile':
        if isinstance(event.source, SourceUser):
            profile = line_bot_api.get_profile(event.source.user_id)
            line_bot_api.reply_message(
                event.reply_token, [
                    TextSendMessage(
                        text='Display Name: ' + profile.display_name
                    ),
                    TextSendMessage(
                        text='Status : ' + profile.status_message
                    )
                ]
            )
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextMessage(text="Bot can't use profile API without user ID"))
            
    elif text == 'bye':
        if isinstance(event.source, SourceGroup):
            line_bot_api.reply_message(
                event.reply_token,
                TextMessage(text='I\'ll be back ....'))
            text_message = TextSendMessage(text='testers!')
            line_bot_api.leave_group(event.source.group_id)
        elif isinstance(event.source, SourceRoom):
            line_bot_api.reply_message(
                event.reply_token, TextMessage(text='Fine'))
            line_bot_api.leave_room(event.source.room_id)
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextMessage(text="Leave me yourself"))
            
    elif text == 'confirm':
        confirm_template = ConfirmTemplate(text='Do it?', actions=[
            MessageTemplateAction(label='Yes', text='Yes!'),
            MessageTemplateAction(label='No', text='No!'),
        ])
        template_message = TemplateSendMessage(
            alt_text='''YoRHa's Request''', template=confirm_template)
        line_bot_api.reply_message(event.reply_token, template_message)
##    elif text == 'view profiles' :
##        profile = line_bot_api.get_group_member_profile(group_id, user_id)
##        line_bot_api.reply_message(event.reply_token, TextSendMessage(text=profile.display_name))
##        line_bot_api.reply_message(event.reply_token, TextSendMessage(text=profile.user_id))
##        line_bot_api.reply_message(event.reply_token, TextSendMessage(text=profile.picture_url))
    elif (text.split())[0] == 'sendto' :
        lineID = (text.split())[1]
        message = (text.split())[2]
        try:
            target = client._client.findContactByUserid(lineID)
            c = LineContact(client, target)
            c.sendMessage(message)
        except:
            line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Error'))
            
    elif text == 'buttons':
        buttons_template = ButtonsTemplate(
            title='My buttons sample', text='Hello, my buttons', actions=[
                URITemplateAction(
                    label='Go to line.me', uri='https://line.me'),
                PostbackTemplateAction(label='ping', data='ping'),
                PostbackTemplateAction(
                    label='ping with text', data='ping',
                    text='ping'),
                MessageTemplateAction(label='Translate Rice', text='米')
            ])
        template_message = TemplateSendMessage(
            alt_text='''YoRHa's Request''', template=buttons_template)
        line_bot_api.reply_message(event.reply_token, template_message)
        
    elif text == 'carousel':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(text='hoge1', title='fuga1', actions=[
                URITemplateAction(
                    label='Go to line.me', uri='https://line.me'),
                PostbackTemplateAction(label='ping', data='ping')
            ]),
            CarouselColumn(text='hoge2', title='fuga2', actions=[
                PostbackTemplateAction(
                    label='ping with text', data='ping',
                    text='ping'),
                MessageTemplateAction(label='Translate Rice', text='米')
            ]),
        ])
        template_message = TemplateSendMessage(
            alt_text='Carousel alt text', template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'image_carousel':
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
                                action=DatetimePickerTemplateAction(label='datetime',
                                                                    data='datetime_postback',
                                                                    mode='datetime')),
            ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
                                action=DatetimePickerTemplateAction(label='date',
                                                                    data='date_postback',
                                                                    mode='date'))
        ])
        template_message = TemplateSendMessage(
            alt_text='ImageCarousel alt text', template=image_carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'imagemap':
        pass
    elif text == '7 First Kisses':
        toString = '''
[SEVEN FIRST KISSES]
Link Sharing by 9S

Episode 1 : https://www.youtube.com/watch?v=PUBrXIikG9k
Episode 2 : https://www.youtube.com/watch?v=_3n3aapyn3g
Episode 3 : https://www.youtube.com/watch?v=xl6FE4xBx7Y
Episode 4 : https://www.youtube.com/watch?v=dAr8bxgHhvo
Episode 5 : https://www.youtube.com/watch?v=fzoQJSAYvLY
Episode 6 : https://www.youtube.com/watch?v=-wkXXkFPcJ4
Episode 7 : https://www.youtube.com/watch?v=qXGf2VAHw28
Episode 8 : https://www.youtube.com/watch?v=jv37Kt5u8WI

~ End at Eps 8 ~'''
        line_bot_api.reply_message(event.reply_token, TextSendMessage(text=toString))        
    elif text == 'YoRHa' :
        line_bot_api.reply_message(event.reply_token, TextSendMessage(text='For the Glory of Mankind'))
    elif text == '@emi[L]' :
        line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Summoned...'))
    elif text.lower() == ('hai' or 'hello' or 'pagi' or 'pagii' or 'malam' or 'siang') or ('selamat' in text.lower()) :
        line_bot_api.reply_message(event.reply_token, TextSendMessage(text=text + 'juga :D'))
    elif text == 'info' :
        line_bot_api.reply_message(event.reply_token, TextSendMessage(text='still in development, here\'s some command :\n \
                                                                      profile\n\
                                                                      bye\n\
                                                                      confirm (RAW)\n\
                                                                      sendto (ERROR)\n\
                                                                      buttons (RAW)\n\
                                                                      carousel (RAW) \n\
                                                                      image_carousel (RAW) \n\
                                                                      imagemap (RAW) \n\
                                                                      YoRHa \n\
                                                                      @emi[L] \n\
                                                                      info (Untested'))
Пример #13
0
def handle_text_message(event):
    text = event.message.text
    if "/stalk " in text.lower():
        user = text.lower().replace("/stalk ", "")
        r = request.get('http://api.secold.com/instagram/stalk/' + user +
                        '/postlimit/6')
        data = r.text
        data = json.loads(data)
        if data['results'] != []:
            line_bot_api.reply_message(event.reply_token, [
                TextSendMessage(
                    text=
                    "Failed, User mungkin di private atau post kurang dari 6")
            ])
        else:
            image_carousel_template = ImageCarouselTemplate(columns=[
                ImageCarouselColumn(image_url=data['results'][0]['url'],
                                    actions=URITemplateAction(
                                        label='Save',
                                        url=data['results'][0]['url'])),
                ImageCarouselColumn(image_url=data['results'][1]['url'],
                                    actions=URITemplateAction(
                                        label='Save',
                                        url=data['results'][1]['url'])),
                ImageCarouselColumn(image_url=data['results'][2]['url'],
                                    actions=URITemplateAction(
                                        label='Save',
                                        url=data['results'][2]['url']))
            ])
            template_message = TemplateSendMessage(
                alt_text='Stalk ig', template=image_carousel_template)
            line_bot_api.reply_message(event.reply_token, template_message)

    elif "/ig " in text.lower():
        username = text.lower().replace('/ig ', '')
        path = 'http://rahandiapi.herokuapp.com/instainfo/' + username + '?key=betakey'
        r = requests.get(path)
        data = r.json()
        line_bot_api.reply_message(
            event.reply_token,
            [TextSendMessage(text='\nNama : ' + str(data['result']['name']))])

    elif text == '/bye':
        if isinstance(event.source, SourceGroup):
            line_bot_api.reply_message(
                event.reply_token,
                TextMessage(text='Owner : http://line.me/ti/p/~bali999'))
            line_bot_api.leave_group(event.source.group_id)
        elif isinstance(event.source, SourceRoom):
            line_bot_api.reply_message(
                event.reply_token,
                TextMessage(text='Owner : http://line.me/ti/p/~bali999'))
            line_bot_api.leave_room(event.source.room_id)
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextMessage(text="Bot can't leave from 1:1 chat"))
    elif text == 'confirm':
        confirm_template = ConfirmTemplate(
            text='Do it?',
            actions=[
                MessageTemplateAction(label='Yes', text='Yes!'),
                MessageTemplateAction(label='No', text='No!'),
            ])
        template_message = TemplateSendMessage(alt_text='Confirm alt text',
                                               template=confirm_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == '/buttons':
        buttons_template = ButtonsTemplate(
            title='List Pr',
            text='Klik salah satu',
            actions=[
                URITemplateAction(label='Go to line.me',
                                  uri='https://line.me'),
                PostbackTemplateAction(label='ping', data='ping'),
                PostbackTemplateAction(label='ping with text',
                                       data='ping',
                                       text='ping'),
                MessageTemplateAction(label='Translate Rice', text='米')
            ])
        template_message = TemplateSendMessage(alt_text='Buttons alt text',
                                               template=buttons_template)
        line_bot_api.reply_message(event.reply_token, template_message)

    elif text == 'carousel':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(text='hoge1',
                           title='fuga1',
                           actions=[
                               URITemplateAction(label='Go to line.me',
                                                 uri='https://line.me'),
                               PostbackTemplateAction(label='ping',
                                                      data='ping')
                           ]),
            CarouselColumn(
                text='hoge2',
                title='fuga2',
                actions=[
                    PostbackTemplateAction(
                        label='ping with text', data='ping', text='ping'),
                    MessageTemplateAction(label='Translate Rice', text='米')
                ]),
        ])
        template_message = TemplateSendMessage(alt_text='Carousel alt text',
                                               template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)

    elif text == 'Pr':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(
                text='Klik salah satu',
                title='List PR',
                thumbnail_image_url='https://i.imgur.com/zWJqolN.jpg',
                actions=[
                    PostbackTemplateAction(label='Pkn', data='pkn'),
                    PostbackTemplateAction(label='Kimia', data='kimia'),
                ]),
            CarouselColumn(
                text='Klik salah satu',
                title='List PR',
                thumbnail_image_url='https://i.imgur.com/zWJqolN.jpg',
                actions=[
                    PostbackTemplateAction(label='Bhs.Bali', data='bali'),
                    PostbackTemplateAction(label='Agama', data='agama'),
                ]),
            CarouselColumn(
                text='Klik salah satu',
                title='List PR',
                thumbnail_image_url='https://i.imgur.com/zWJqolN.jpg',
                actions=[
                    PostbackTemplateAction(label='Kwu', data='kwu'),
                    PostbackTemplateAction(label='Ips', data='ips'),
                ]),
            CarouselColumn(
                text='Klik salah satu',
                title='List PR',
                thumbnail_image_url='https://i.imgur.com/zWJqolN.jpg',
                actions=[
                    PostbackTemplateAction(label='Fisika', data='fisika'),
                    PostbackTemplateAction(label='Matematika', data='matik'),
                ]),
            CarouselColumn(
                text='Klik salah satu',
                title='List PR',
                thumbnail_image_url='https://i.imgur.com/zWJqolN.jpg',
                actions=[
                    PostbackTemplateAction(label='Kkpi', data='kkpi'),
                    MessageTemplateAction(label='Ipa', text='Pr ipa')
                ]),
            CarouselColumn(
                text='Klik salah satu',
                title='List PR',
                thumbnail_image_url='https://i.imgur.com/zWJqolN.jpg',
                actions=[
                    PostbackTemplateAction(label='English', data='inggris'),
                    PostbackTemplateAction(label='Seni Budaya', data='senbud')
                ]),
            CarouselColumn(
                text='Klik salah satu',
                title='List PR',
                thumbnail_image_url='https://i.imgur.com/zWJqolN.jpg',
                actions=[
                    PostbackTemplateAction(label='Budi pekerti', data='budi'),
                    PostbackTemplateAction(label='Bhs.Indonesia', data='indo')
                ]),
        ])
        template_message = TemplateSendMessage(alt_text='Carousel alt text',
                                               template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)

    elif text == 'Jadwal':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(
                text='Klik salah satu',
                title='Jadwal',
                thumbnail_image_url='https://i.imgur.com/2dZuLj8.jpg',
                actions=[
                    PostbackTemplateAction(label='Senin', data='senin'),
                    PostbackTemplateAction(label='Selasa', data='selasa'),
                    PostbackTemplateAction(label='Rabu', data='rabu')
                ]),
            CarouselColumn(
                text='Klik salah satu',
                title='Jadwal',
                thumbnail_image_url='https://i.imgur.com/8yVTyeg.jpg',
                actions=[
                    PostbackTemplateAction(label='Kamis', data='kamis'),
                    PostbackTemplateAction(label='Jumat', data='jumat'),
                    PostbackTemplateAction(label='Sabtu', data='sabtu')
                ]),
        ])
        template_message = TemplateSendMessage(alt_text='Carousel alt text',
                                               template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)

    elif text == 'Bantuan':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(
                text='Klik salah satu',
                title='Jadwal',
                thumbnail_image_url='https://i.imgur.com/mMi5Umy.jpg',
                actions=[
                    PostbackTemplateAction(label='Jadwal', data='jadwal')
                ]),
            CarouselColumn(
                text='Klik salah satu',
                title='List PR',
                thumbnail_image_url='https://i.imgur.com/RXHhM4U.jpg',
                actions=[PostbackTemplateAction(label='List PR', data='pr')]),
            CarouselColumn(
                text='Klik salah satu',
                title='Jadwal UAS',
                thumbnail_image_url='https://i.imgur.com/BxbJ52i.jpg',
                actions=[
                    MessageTemplateAction(label='Jadwal UAS',
                                          text='/jadwal uas')
                ])
        ])
        template_message = TemplateSendMessage(alt_text='Bantuan',
                                               template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)

    elif text == 'tekno':
        databerita = listBerita("http://tekno.kompas.com/business")
        daftarberita = databerita.daftarBerita()
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(
                text=daftarberita[acak[0]]['judul'],
                actions=[
                    PostbackTemplateAction(label="Ringkas",
                                           data=daftarberita[acak[0]]['link'],
                                           text='ringkas'),
                    URITemplateAction(label='Baca berita asli',
                                      uri=daftarberita[acak[0]]['link'])
                ]),
            CarouselColumn(
                text=daftarberita[acak[1]]['judul'],
                actions=[
                    PostbackTemplateAction(label="Ringkas",
                                           data=daftarberita[acak[1]]['link'],
                                           text='ringkas'),
                    URITemplateAction(label='Baca berita asli',
                                      uri=daftarberita[acak[1]]['link'])
                ]),
            CarouselColumn(
                text=daftarberita[acak[2]]['judul'],
                actions=[
                    PostbackTemplateAction(label="Ringkas",
                                           data=daftarberita[acak[2]]['link'],
                                           text='ringkas'),
                    URITemplateAction(label='Baca berita asli',
                                      uri=daftarberita[acak[2]]['link'])
                ]),
            CarouselColumn(
                text=daftarberita[acak[3]]['judul'],
                actions=[
                    PostbackTemplateAction(label="Ringkas",
                                           data=daftarberita[acak[3]]['link'],
                                           text='ringkas'),
                    URITemplateAction(label='Baca berita asli',
                                      uri=daftarberita[acak[3]]['link'])
                ])
        ])
        template_message = TemplateSendMessage(alt_text='Daftar Berita Tekno',
                                               template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'bisnis':
        databerita = listBerita("http://bisniskeuangan.kompas.com/bisnis")
        daftarberita = databerita.daftarBerita()
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(
                text=daftarberita[acak[0]]['judul'],
                actions=[
                    PostbackTemplateAction(label="Ringkas",
                                           data=daftarberita[acak[0]]['link'],
                                           text='ringkas'),
                    URITemplateAction(label='Baca berita asli',
                                      uri=daftarberita[acak[0]]['link'])
                ]),
            CarouselColumn(
                text=daftarberita[acak[1]]['judul'],
                actions=[
                    PostbackTemplateAction(label="Ringkas",
                                           data=daftarberita[acak[1]]['link'],
                                           text='ringkas'),
                    URITemplateAction(label='Baca berita asli',
                                      uri=daftarberita[acak[1]]['link'])
                ]),
            CarouselColumn(
                text=daftarberita[acak[2]]['judul'],
                actions=[
                    PostbackTemplateAction(label="Ringkas",
                                           data=daftarberita[acak[2]]['link'],
                                           text='ringkas'),
                    URITemplateAction(label='Baca berita asli',
                                      uri=daftarberita[acak[2]]['link'])
                ]),
            CarouselColumn(
                text=daftarberita[acak[3]]['judul'],
                actions=[
                    PostbackTemplateAction(label="Ringkas",
                                           data=daftarberita[acak[3]]['link'],
                                           text='ringkas'),
                    URITemplateAction(label='Baca berita asli',
                                      uri=daftarberita[acak[3]]['link'])
                ])
        ])
        template_message = TemplateSendMessage(alt_text='Daftar Berita Bisnis',
                                               template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'otomotif':
        databerita = listBerita("http://otomotif.kompas.com/news")
        daftarberita = databerita.daftarBerita()
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(
                text=daftarberita[acak[0]]['judul'],
                actions=[
                    PostbackTemplateAction(label="Ringkas",
                                           data=daftarberita[acak[0]]['link'],
                                           text='ringkas'),
                    URITemplateAction(label='Baca berita asli',
                                      uri=daftarberita[acak[0]]['link'])
                ]),
            CarouselColumn(
                text=daftarberita[acak[1]]['judul'],
                actions=[
                    PostbackTemplateAction(label="Ringkas",
                                           data=daftarberita[acak[1]]['link'],
                                           text='ringkas'),
                    URITemplateAction(label='Baca berita asli',
                                      uri=daftarberita[acak[1]]['link'])
                ]),
            CarouselColumn(
                text=daftarberita[acak[2]]['judul'],
                actions=[
                    PostbackTemplateAction(label="Ringkas",
                                           data=daftarberita[acak[2]]['link'],
                                           text='ringkas'),
                    URITemplateAction(label='Baca berita asli',
                                      uri=daftarberita[acak[2]]['link'])
                ]),
            CarouselColumn(
                text=daftarberita[acak[3]]['judul'],
                actions=[
                    PostbackTemplateAction(label="Ringkas",
                                           data=daftarberita[acak[3]]['link'],
                                           text='ringkas'),
                    URITemplateAction(label='Baca berita asli',
                                      uri=daftarberita[acak[3]]['link'])
                ])
        ])
        template_message = TemplateSendMessage(
            alt_text='Daftar Berita Otomotif', template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)

    elif text == 'About':
        buttons_template = ButtonsTemplate(
            text='Main Developer',
            title='Bali Tenaya',
            thumbnail_image_url='https://i.imgur.com/cltOVPI.jpg',
            actions=[
                URITemplateAction(
                    label='instagram',
                    uri='https://www.instagram.com/tenaya_bali/'),
                URITemplateAction(label='Twitter',
                                  uri='https://www.twitter.com/tenaya_bali/')
            ])
        template_message = TemplateSendMessage(alt_text='About',
                                               template=buttons_template)
        line_bot_api.reply_message(event.reply_token, template_message)

    elif text == 'image_carousel':
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(
                image_url='https://via.placeholder.com/1024x1024',
                action=DatetimePickerTemplateAction(label='datetime',
                                                    data='datetime_postback',
                                                    mode='datetime')),
            ImageCarouselColumn(
                image_url='https://via.placeholder.com/1024x1024',
                action=DatetimePickerTemplateAction(
                    label='date', data='date_postback', mode='date'))
        ])
        template_message = TemplateSendMessage(
            alt_text='ImageCarousel alt text',
            template=image_carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
Пример #14
0
def ask_question_states(event):
    now = datetime.now()
    train_type = ""
    qs = current_app.session.query(TRA_QuestionState).filter_by(expired=False) \
        .filter_by(user=event.source.user_id)
    if hasattr(event.source, "group_id"):
        qs = qs.filter_by(group=event.source.group_id)
    try:
        qs = qs.one()
        train_type = "TRA"
    except NoResultFound:
        pass
    except MultipleResultsFound:
        for i in qs.all():
            i.expired = True

    if not train_type:
        qs = current_app.session.query(THSR_QuestionState).filter_by(expired=False) \
            .filter_by(user=event.source.user_id)
        try:
            qs = qs.one()
            train_type = "THSR"
        except NoResultFound:
            return None
        except MultipleResultsFound:
            for i in qs.all():
                i.expired = True
            return None

    message = None
    if not qs.departure_station:
        if train_type == "TRA":
            res = match_TRA_station_name(event.message.text)
        else:
            res = match_THSR_station_name(event.message.text)
        if res:
            qs.departure_station = res
            message = TextSendMessage(text="請輸入目的站")
    elif not qs.destination_station:
        if train_type == "TRA":
            res = match_TRA_station_name(event.message.text)
        else:
            res = match_THSR_station_name(event.message.text)
        if res and res != qs.departure_station:
            qs.destination_station = res
            title = '請選擇搭乘時間: {0} → {1}'.format(qs.departure_station,
                                                qs.destination_station)
            message = TemplateSendMessage(alt_text='請選擇搭乘時間',
                                          template=ButtonsTemplate(
                                              title=title,
                                              text='點擊選擇',
                                              actions=[
                                                  DatetimePickerTemplateAction(
                                                      label='搭乘時間',
                                                      data='datetime_postback',
                                                      mode='datetime'),
                                              ]))
        elif res == qs.departure_station:
            message = create_error_text_message(
                text="輸入的目的站與起程站皆是{0},請重新輸入有效目的站".format(res))
    elif isinstance(
            event,
            PostbackEvent) and qs.departure_station and qs.destination_station:
        try:
            dt = event.postback.params["datetime"]
            dt = datetime.strptime(dt, "%Y-%m-%dT%H:%M")
            qs.departure_time = dt
            if qs.group:
                current_app.linebot.push_message(
                    qs.group, TextSendMessage(text="搜尋中..."))
            else:
                current_app.linebot.push_message(
                    qs.user, TextSendMessage(text="搜尋中..."))
            if train_type == "TRA":
                suitable_trains = request_TRA_matching_train(qs)
            else:
                suitable_trains = request_THSR_matching_train(qs)
            actions = [
                DatetimePickerTemplateAction(label='更換搭乘時間',
                                             data='datetime_postback',
                                             mode='datetime'),
                MessageTemplateAction(label='新的搜尋', text='T')
            ]
            if not suitable_trains:
                text = "無適合班次"
            elif train_type == "TRA":
                text = "車次   車種      開車         抵達\n"
                fmt = "{0:0>4}  {1:^2}     {2}       {3}\n"
                count = 0
                for _l in suitable_trains:
                    text = text + fmt.format(
                        _l[0].train.train_no, _l[0].train.train_type,
                        _l[1].departure_time.strftime("%H:%M"),
                        _l[2].arrival_time.strftime("%H:%M"))
                    count += 1
                    # Total word number of a post is limited
                    if len(text) > 125:
                        break
                if len(suitable_trains) > count:
                    actions.insert(
                        0, MessageTemplateAction(label='列出更多', text='列出更多'))
            else:
                text = "車次     開車時間    抵達時間\n".format(qs.departure_station,
                                                      qs.destination_station)
                fmt = "{0:0>4}       {1}          {2}\n"
                count = 0
                for _l in suitable_trains:
                    text = text + fmt.format(
                        _l[0].train.train_no,
                        _l[1].departure_time.strftime("%H:%M"),
                        _l[2].arrival_time.strftime("%H:%M"))
                    count += 1
                    if len(text) > 125:
                        break
                if len(suitable_trains) > count:
                    actions.insert(
                        0, MessageTemplateAction(label='列出更多', text='列出更多'))
            message = TemplateSendMessage(
                alt_text='搜尋結果: {0} → {1}'.format(qs.departure_station,
                                                  qs.destination_station),
                template=ButtonsTemplate(text=text, actions=actions))
        except KeyError:
            pass
    elif event.message.text == "列出更多" and qs.departure_station and qs.destination_station and qs.departure_time:
        if qs.group:
            current_app.linebot.push_message(qs.group,
                                             TextSendMessage(text="搜尋中..."))
        else:
            current_app.linebot.push_message(qs.user,
                                             TextSendMessage(text="搜尋中..."))
        if train_type == "TRA":
            suitable_trains = request_TRA_matching_train(qs)
        else:
            suitable_trains = request_THSR_matching_train(qs)
        if not suitable_trains:
            text = "無適合班次"
        elif train_type == "TRA":
            text = "適合班次如下  {0} → {1} \n" \
                   "車次   車種  開車時間  抵達時間\n".format(qs.departure_station, qs.destination_station)
            fmt = "{0:0>4}  {1:^2}     {2}        {3}\n"
            for _l in suitable_trains:
                text = text + fmt.format(
                    _l[0].train.train_no, _l[0].train.train_type,
                    _l[1].departure_time.strftime("%H:%M"),
                    _l[2].arrival_time.strftime("%H:%M"))
                if len(text) > 1000:
                    text = text + "More..."
                    break
        else:
            text = "適合班次如下  {0} → {1} \n" \
                   "車次     開車時間    抵達時間\n".format(qs.departure_station, qs.destination_station)
            fmt = "{0:0>4}       {1}          {2}\n"
            for _l in suitable_trains:
                text = text + fmt.format(
                    _l[0].train.train_no,
                    _l[1].departure_time.strftime("%H:%M"),
                    _l[2].arrival_time.strftime("%H:%M"))
                if len(text) > 1000:
                    text = text + "More..."
                    break
        message = TextSendMessage(text=text)
    if message:
        qs.update = now
    return message
Пример #15
0
         ]),
         CarouselColumn(text='Arabian egg', title='2', actions=[
             PostbackTemplateAction(
                 label='ping with text', data='ping',
                 text='ping'),
             MessageTemplateAction(label='Translate Rice', text='米')
         ]),
     ])
     template_message = TemplateSendMessage(
         alt_text='Choose which one to replace.', template=carousel_template)
     line_bot_api.reply_message(event.reply_token, template_message)
 elif text == '1':
     image_carousel_template = ImageCarouselTemplate(columns=[
         ImageCarouselColumn(image_url='https://www.theurbanlist.com/content/article/wysiwyg/three-williams-eggs.png',
                             action=DatetimePickerTemplateAction(label='datetime',
                                                                 data='datetime_postback',
                                                                 mode='datetime')),
         ImageCarouselColumn(image_url='https://www.fritzmag.com.au/wp-content/uploads/2016/12/Get-Your-Googie-On-With-South-Australian-Eggs-2.jpg',
                             action=DatetimePickerTemplateAction(label='date',
                                                                 data='date_postback',
                                                                 mode='date'))
     ])
     template_message = TemplateSendMessage(
         alt_text='ImageCarousel alt text', template=image_carousel_template)
     line_bot_api.reply_message(event.reply_token, template_message)
 elif text == '2':
     image_carousel_template = ImageCarouselTemplate(columns=[
         ImageCarouselColumn(image_url='https://www.theurbanlist.com/content/article/wysiwyg/three-williams-eggs.png',
                             action=DatetimePickerTemplateAction(label='datetime',
                                                                 data='datetime_postback',
                                                                 mode='datetime')),
Пример #16
0
def handle_text_message(event):
    if (event.message.text.lower() == "nilai"):
        # jika tombol nilai ditekan
        # fungsi yang akan dilakukan ditulis dibawah ini
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text='Nilai dari mata kuliah apa yang ingin ditampilkan?'))
        menuNilai = CarouselTemplate(columns=[
            CarouselColumn(
                title='AI',
                text='Inteligensi Buatan',
                defaultAction=MessageAction(label='Lihat Nilai', text='AI'),
                actions=[MessageAction(label='Lihat Nilai', text='AI')]),
            CarouselColumn(
                title='Jarkom',
                text='Jaringan Komputer',
                defaultAction=MessageAction(label='Lihat Nilai',
                                            text='Jarkom'),
                actions=[MessageAction(label='Lihat Nilai', text='Jarkom')]),
            CarouselColumn(
                title='IMK',
                text='Interaksi Manusia Komputer',
                defaultAction=MessageAction(label='Lihat Nilai', text='IMK'),
                actions=[MessageAction(label='Lihat Nilai', text='IMK')]),
            CarouselColumn(
                title='MPPL',
                text='Manajemen Proyek Perangkat Lunak',
                defaultAction=MessageAction(label='Lihat Nilai', text='MPPL'),
                actions=[MessageAction(label='Lihat Nilai', text='MPPL')]),
            CarouselColumn(
                title='WBD',
                text='Web-Based Development',
                defaultAction=MessageAction(label='Lihat Nilai', text='WBD'),
                actions=[MessageAction(label='Lihat Nilai', text='WBD')]),
            CarouselColumn(
                title='MBD',
                text='Manajemen Basis Data',
                defaultAction=MessageAction(label='Lihat Nilai', text='MBD'),
                actions=[MessageAction(label='Lihat Nilai', text='MBD')])
        ])
        messageNilai = TemplateSendMessage(alt_text='Tampilkan Nilai',
                                           template=menuNilai)
        line_bot_api.reply_message(event.reply_token, messageNilai)
    elif (event.message.text.lower() == "ai"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Inteligensi Buatan\n' \
        '== KUIS == \n' \
        'Kuis 1 : 75 \n' \
        'Kuis 2 : 88 \n' \
        '== TUGAS == \n' \
        'Tucil 1 : 100 \n' \
        'Tubes 1 : 100 \n' \
        '== UJIAN == \n' \
        'UTS : 99'))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text='Selamat! Kamu benar-benar bersinar dalam mata kuliah ini!'
            ))
    elif (event.message.text.lower() == "jarkom"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Jaringan Komputer\n' \
        '== KUIS == \n' \
        'Kuis 1 : 90 \n' \
        'Kuis 2 : 101 \n' \
        'Kuis 3 : 85 \n' \
        'Kuis 4 : 95 \n' \
        'Kuis 5 : 90'))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text=
                'Kuis dadakan bukan menjadi penghalang untuk kamu terus berkembang!'
            ))
    elif (event.message.text.lower() == "imk"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Interaksi Manusia Komputer\n' \
        '== KUIS == \n' \
        'Kuis 1 : 45 \n' \
        'Kuis 2 : 60 \n' \
        'Kuis 3 : 75 \n' \
        'Kuis 4 : 70 \n' \
        'Kuis 5 : 90 \n' \
        '== TUGAS == \n' \
        'Tugas 1 : 95 \n' \
        'Tugas 2 : 85 \n' \
        'Tugas 3 : 80 \n' \
        'Tugas 4 : 90 \n' \
        'Tugas 5 : 95'))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text='Nilai kuismu kian hari kian membaik! Pertahankanlah!'))
    elif (event.message.text.lower() == "mppl"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Manajemen Proyek Perangkat Lunak\n' \
        '== TUGAS == \n' \
        'Tugas 1 : 88 \n' \
        'Tugas 2 : 88 \n' \
        'Tugas 3 : 88 \n' \
        'Tugas 4 : 87 \n' \
        'Tugas 5 : 88 \n' \
        '== UJIAN == \n' \
        'UTS : 54'))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text=
                'Masih ada kesempatan untuk meraih nilai yang lebih tinggi di UAS nanti. Semangat!'
            ))
    elif (event.message.text.lower() == "wbd"):
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                'Nilai tidak ditemukan untuk mata kuliah Web-based Development.'
            ))
    elif (event.message.text.lower() == "mbd"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Manajemen Basis Data\n' \
        '== KUIS == \n' \
        'Kuis 1 : 45 \n' \
        'Kuis 2 : 60 \n' \
        '== TUGAS == \n' \
        'Tugas 1 : 95 \n' \
        '== UJIAN == \n' \
        'UTS : 67'))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text=
                'Jangan biarkan soal beranak itu melunturkan semangatmu! Kamu masih memiliki kesempatan untuk memperbaiki nilaimu. Berjuanglah!'
            ))
    elif (event.message.text.lower() == "to-do list"):
        # jika tombol to-do list ditekan
        # fungsi yang akan dilakukan ditulis dibawah ini
        toDoListMenu = ButtonsTemplate(
            title='To-do List Menu',
            text='Pilih salah satu',
            thumbnail_image_url=
            'https://raw.githubusercontent.com/alvinlimassa/upi-bot/todolist/Image/todolist.png?token=AZu-_q7EbEcr2o4ChRGwXOrzCXqetxNcks5b7p25wA%3D%3D',
            actions=[
                MessageAction(label='Tampilkan Semua',
                              text='Tampilkan Semua To-do List'),
                DatetimePickerTemplateAction(label='Pilih tanggal',
                                             data='datetime_postback',
                                             mode='date'),
                MessageAction(label='Tambah To-do List',
                              text='Tambah To-do List')
            ])
        toDoListMessage = TemplateSendMessage(alt_text='To do List Menu',
                                              template=toDoListMenu)
        line_bot_api.reply_message(event.reply_token, toDoListMessage)
    elif (event.message.text.lower() == "tampilkan semua to-do list"):
        # jika user meminta menampilkan semua to-do list
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Berikut ini adalah To-Do List anda : \n' \
        'Senin, 12 November 2018 : \n' \
        '- 07.00 - 09.00 = AI \n' \
        '- 09.00 - 11.00 = IMK \n' \
        '- PR IMK (Deadline 10.00)\n' \
        'Selasa, 13 November 2018 : \n' \
        '- 07.00 - 09.00 = WBD\n' \
        '- 09.00 - 11.00 = JARKOM'))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text=
                'Tekan/ ketik Selanjutnya untuk menampilkan to-do list berikutnya',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(action=MessageAction(
                        label='Selanjutnya', text='to-do list lanjut')),
                ])))
    elif (event.message.text.lower() == "to-do list lanjut"):
        # jika user meminta menampilkan Lanjutan To-do list
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Berikut ini adalah To-Do List anda : \n' \
        'Rabu, 14 November 2018 : \n' \
        '- 07.00 - 08.00 = IMK \n' \
        '- 08.00 - 10.00 = AI \n' \
        'Kamis, 15 November 2018 : \n' \
        '- 07.00 - 09.00 = WBD\n' \
        '- 09.00 - 11.00 = JARKOM'))
    elif (event.message.text.lower() == "tambah to-do list"):
        # jika user ingin menambahkan jadwal
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                'Untuk menambahkan To-do List gunakan perintah = add: <judul to-do list>'
            ))
    elif (event.message.text.lower() == "referensi"):
        # jika tombol referensi ditekan
        # fungsi yang akan dilakukan ditulis dibawah ini
        temp = [
            MessageAction(label=x.split(" ")[1],
                          text=x.split(" ")[0] + " " +
                          " ".join(x.split(" ")[2:])) for x in matkul_list
        ]
        matkulMenu = CarouselTemplate(columns=[
            CarouselColumn(
                title=x.label, text=x.text, defaultAction=x, actions=[x])
            for x in temp
        ])
        matkulMessage = TemplateSendMessage(alt_text='Daftar mata kuliah',
                                            template=matkulMenu)
        line_bot_api.reply_message(event.reply_token, matkulMessage)
    elif (event.message.text.lower() ==
          "if3110 pengembangan aplikasi berbasis web"):
        # referensi wbd
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Referensi IF3110 Pengembangan Aplikasi Berbasis Web\n\n' \
        '1. Web Technologies: A Computer Science Perspec4ve, Jeffrey C. Jackson, Pren4ce Hall, 2007\n\n' \
        '2. Developing Large Web Applica4ons: Producing Code That Can Grow and Thrive, Kyle Loudon, O\'Reilly Media, Inc., 2010\n\n' \
        '3. HTML5: Up and Running, Mark Pilgrim, O\'Reilly Media, Inc., 2010\n\n' \
        '4. The Java EE 6 Tutorial: Basic Concepts, Eric Jendrock & Ian Evans & Devika Gollapudi & Kim Haase & Chinmayee Srivathsa, Pren4ce Hall, 2010\n\n' \
        '5. JavaScript: The Defini4ve Guide, David Flanagan, O\'Reilly Media, 2011'))
    elif (event.message.text.lower() == "if3130 jaringan komputer"):
        # referensi jarkom
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Referensi IF3130 Jaringan Komputer\n\n' \
        '1. Computer Networks: A Systems Approach (4th Edition) by Larry Peterson and Bruce Davie. Morgan Kaufmann, 2007.\n\n' \
        '2. Lin, Y.-D. Computer Networks: An Open Source Approach McGraw Hills, 2011\n\n' \
        '3. Tanenbaum, Andrew, “Computer Networks”, 4th Ed. Prentice Hall, 2003\n\n' \
        '4. Stallings, William, “Data & Computer Communications”, Prentice Hall, 2002'))
    elif (event.message.text.lower() == "if3140 manajemen basis data"):
        # referensi mbd
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Referensi IF3140 Manajemen Basis Data\n\n' \
        '1. Silberschatz, H.F. Korth, S. Sudarshan, ‘Database System Concepts’, McGraw-Hill (Pustaka Utama)\n\n' \
        '2. J.A. Hoffer, M.B. Prescott, F.R. McFadden, ‘Modern Database Management’, Pearson Prentice Hall (Pendukung)\n\n' \
        '3. C.J. Date, ‘An Introduction to Database System’, Addison Wesley (Pendukung)'))
    elif (event.message.text.lower() ==
          "if3150 manajemen proyek perangkat lunak"):
        # referensi mppl
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Referensi IF3150 Manajemen Proyek Perangkat Lunak\n\n' \
        '1. Information Technology Project Management 8th Edition, Kathy Schwalbe, Thomson Course Technology, 2015\n\n' \
        '2. A Guide to the Project Management Body of Knowledge, ANSI-PMI, 2008\n\n' \
        '3. Software Project, Steve McConnel, Microsoft Press, 1998\n\n' \
        '4. Project Management Professional Study Guide, Kim Heldman, Sybex, 2004\n\n' \
        '5. Wysocki, Robert K. Effective project management: traditional, agile, extreme. John Wiley & Sons, 2011'))
    elif (event.message.text.lower() == "if3151 interaksi manusia dan komputer"
          ):
        # referensi wbd
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Referensi IF3151 Interaksi Manusia dan Komputer\n\n' \
        '1. Interaction Design - Beyond Human-Computer Interaction, Jenny Preece et al., John Wiley & Sons'))
    elif (event.message.text.lower() == "if3170 intelegensi buatan"):
        # referensi wbd
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Referensi IF3110 Pengembangan Aplikasi Berbasis Web\n\n' \
        '1. Stuart J Russell & Peter Norvig, Artificial Intelligence: A Modern Approach, 3rd Edition, Prentice-Hall International, Inc, 2010\n\n' \
        '2. Tom Mitchell, Machine Learning, 1999\n\n' \
        '3. MIT OpenCourseWare Website: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/'))
    elif (event.message.text.lower() == "presensi"):
        # jika tombol presensi ditekan
        # fungsi yang akan dilakukan ditulis dibawah ini
        presensiMenu = ButtonsTemplate(
            title='Pilih Jenis Presensi',
            text='Pilih salah satu',
            actions=[
                MessageAction(label='Semua Mata Kuliah',
                              text='presensi-semua'),
                MessageAction(label='Spesific Mata Kuliah',
                              text='presensi-spesific'),
            ])
        presensiMessage = TemplateSendMessage(alt_text='Presensi Menu',
                                              template=presensiMenu)
        line_bot_api.reply_message(event.reply_token, presensiMessage)

    elif (event.message.text.lower() == "presensi-semua"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('PRESENSI \n' \
        '============================\n' \
        'Jaringan Komputer : 20%\n'\
        'Manajemen Basis Data : 100%\n'\
        'Manajemen Proyek Perangkat Lunak : 80%\n'\
        'Interaksi Manusia Komputer : 100%\n'\
        'Web-Based Development : 80%\n'\
        'Intelegensi Buatan : 100%\n'\
        ))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text=
                'Semangat untuk jaringan komputernya, jangan menghilang seperti ninja :)'
            ))
    elif (event.message.text.lower() == "presensi-spesific"):
        # jika tombol presensi ditekan
        # fungsi yang akan dilakukan ditulis dibawah ini
        menuSpesific = CarouselTemplate(columns=[
            CarouselColumn(title='IF3170',
                           text='Inteligensi Buatan',
                           defaultAction=MessageAction(label='Lihat presensi',
                                                       text='presensi-IF3170'),
                           actions=[
                               MessageAction(label='Lihat presensi',
                                             text='presensi-IF3170')
                           ]),
            CarouselColumn(title='IF3130',
                           text='Jaringan Komputer',
                           defaultAction=MessageAction(label='Lihat presensi',
                                                       text='presensi-IF3130'),
                           actions=[
                               MessageAction(label='Lihat presensi',
                                             text='presensi-IF3130')
                           ]),
            CarouselColumn(title='IF3151',
                           text='Interaksi Manusia Komputer',
                           defaultAction=MessageAction(label='Lihat presensi',
                                                       text='presensi-IF3151'),
                           actions=[
                               MessageAction(label='Lihat presensi',
                                             text='presensi-IF3151')
                           ]),
            CarouselColumn(title='IF3150',
                           text='Manajemen Proyek Perangkat Lunak',
                           defaultAction=MessageAction(label='Lihat presensi',
                                                       text='presensi-IF3150'),
                           actions=[
                               MessageAction(label='Lihat presensi',
                                             text='presensi-IF3150')
                           ]),
            CarouselColumn(title='IF3110',
                           text='Web-Based Development',
                           defaultAction=MessageAction(label='Lihat presensi',
                                                       text='presensi-IF3110'),
                           actions=[
                               MessageAction(label='Lihat presensi',
                                             text='presensi-IF3110')
                           ]),
            CarouselColumn(title='IF3140',
                           text='Manajemen Basis Data',
                           defaultAction=MessageAction(label='Lihat presensi',
                                                       text='presensi-IF3140'),
                           actions=[
                               MessageAction(label='Lihat presensi',
                                             text='presensi-IF3140')
                           ])
        ])
        messageSpesific = TemplateSendMessage(alt_text='Tampilkan Nilai',
                                              template=menuSpesific)
        line_bot_api.reply_message(event.reply_token, messageSpesific)

    elif (event.message.text.lower() == "presensi-if3130"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('PRESENSI \n' \
        '============================\n' \
        'Jaringan Komputer : 20%\n'\
        'Jumlah Pertemuan : 20\n'\
        'Pertemuan tidak masuk : 3-18\n'\
        ))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(text='Semangat untuk kelas jarkomnya !!! '))

    elif (event.message.text.lower() == "presensi-if3140"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('PRESENSI \n' \
        '============================\n' \
        'Manajemen Basis Data : 100%\n'\
        'Jumlah Pertemuan : 20\n'\
        'Pertemuan tidak masuk : -\n'\
        ))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(text='Mantap sudah bagus !!!, Pertahankan !!!'))
    elif (event.message.text.lower() == "presensi-if3170"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('PRESENSI \n' \
        '============================\n' \
        'Intelegensi Buatan : 100%\n'\
        'Jumlah Pertemuan : 20\n'\
        'Pertemuan tidak masuk : -\n'\
        ))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(text='Mantap sudah bagus !!!, Pertahankan !!!'))
    elif (event.message.text.lower() == "presensi-if3150"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('PRESENSI \n' \
        '============================\n' \
        'Manajemen Proyek Perangkat Lunak : 80%\n'\
        'Jumlah Pertemuan : 20\n'\
        'Pertemuan tidak masuk : 19,20\n'\
        ))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text=
                'Absen masih aman, namun jatahmu sudah habis :( . Jangan bolos lagi !!!'
            ))
    elif (event.message.text.lower() == "presensi-if3151"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('PRESENSI \n' \
        '============================\n' \
        'Interaksi Manusia Komputer : 100%\n'\
        'Jumlah Pertemuan : 20\n'\
        'Pertemuan tidak masuk : -\n'\
        ))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(text='Mantap sudah bagus !!!, Pertahankan !!!'))
    elif (event.message.text.lower() == "presensi-if3110"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('PRESENSI \n' \
        '============================\n' \
        'Web-Based Development : 80%\n'\
        'Jumlah Pertemuan : 20\n'\
        'Pertemuan tidak masuk : 19,20\n'\
        ))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text=
                'Absen masih aman, namun jatahmu sudah habis :( . Jangan bolos lagi !!!'
            ))
    elif (event.message.text.lower() == "aturan"):
        # jika tombol aturan ditekan
        # fungsi yang akan dilakukan ditulis dibawah ini
        aturanMenu = ButtonsTemplate(
            title='Prosedur dan Regulasi ITB',
            text='Pilih salah satu',
            actions=[
                MessageAction(label='Jadwal TU', text='Jadwal TU Kantor'),
                MessageAction(label='Pinjam Labtek V', text='Pinjam Labtek V'),
                MessageAction(label='KTM Hilang', text='KTM Hilang'),
                MessageAction(label='Transkrip', text='Permintaan Transkrip')
            ])
        aturanMessage = TemplateSendMessage(alt_text='Menu aturan',
                                            template=aturanMenu)
        line_bot_api.reply_message(event.reply_token, aturanMessage)
    elif (event.message.text.lower() == "jadwal tu kantor"):
        # jadwal buka TU dan kantor
        line_bot_api.reply_message(event.reply_token, TextSendMessage('JADWAL BUKA TU DAN KANTOR \n' \
        '============================\n' \
        '\n' \
        'TU STEI \n' \
        '07.00 - 12.00  13.00 - 15.00 \n' \
        'LK ITB \n' \
        '07.00 - 12.00  13.00 - 16.30 \n' \
        'SP ITB\n' \
        '08.00 - 12.00  13.00 - 16.30'))
    elif (event.message.text.lower() == "pinjam labtek v"):
        # prosedur peminjaman ruangan labtek V
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Prosedur Peminjaman Ruangan Labtek V \n' \
        '================================ \n' \
        '\n' \
        'Prasyarat: \n' \
        '1. Biaya fotokopi Rp500,00 \n' \
        '\n' \
        'Prosedur: \n' \
        '1. Datang ke TU Lab Labtek V lantai 4 pada jam kerja\n' \
        '2. Isi surat peminjaman ruangan\n' \
        '3. Bawa surat peminjaman ke SP STEI Labtek VIII lantai 2 pada jam kerja\n'
        '4. Datang kembali ke SP STEI setelah 1 hari\n'
        '5. Ambil surat dan fotokopi 3 lembar\n'
        '6. Beri surat ke TU Lab dan dapur Labtek V lantai 4'))
    elif (event.message.text.lower() == "permintaan transkrip"):
        # prosedur permintaan transkrip
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Prosedur Permintaan Transkrip \n' \
        '========================= \n' \
        '\n' \
        'Prasyarat: \n' \
        '1. Biaya fotokopi Rp1.000,00 \n' \
        '2. Bolpoin\n' \
        '\n' \
        'Prosedur: \n' \
        '1. Datang ke TU STEI Labtek V lantai 2 pada jam kerja\n' \
        '2. Isi lembar permintaan surat\n' \
        '3. Kembalikan lembar ke TU\n' \
        '4. Datang kembali ke TU STEI setelah 3 hari\n' \
        '5. Ambil transkrip asli dan fotokopi 5 lembar\n' \
        '6. Bawa hasil fotokopi ke TU untuk dilegalisasi'))
    elif (event.message.text.lower() == "ktm hilang"):
        # prosedur permintaan KTM baru
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Prosedur Penggantian KTM Hilang \n' \
        '============================ \n' \
        '\n' \
        'Prasyarat: \n' \
        '1. Surat keterangan hilang dari TU \n' \
        '2. Foto untuk KTM baru (digital)\n' \
        '3. Biaya penggantian Rp30.000,00\n' \
        '\n' \
        'Prosedur: \n' \
        '1. Datang ke Annex ITB dengan membawa prasyarat\n' \
        '2. Upload foto dan isi data di web sesuai dengan pemberitahuan\n' \
        '3. Ambil KTM baru di gedung CRCS pada waktu yang telah diberitahukan'))
    elif (event.message.text.lower() == "soal"):
        # jika tombol soal ditekan
        # fungsi yang akan dilakukan ditulis dibawah ini
        line_bot_api.push_message(event.source.user_id,
                                  TextSendMessage(text='Pilih Mata Kuliah'))
        menuQuiz = CarouselTemplate(columns=[
            CarouselColumn(
                title='AI',
                text='Inteligensi Buatan',
                defaultAction=MessageAction(label='Latihan', text='quiz-AI'),
                actions=[MessageAction(label='Latihan', text='quiz-AI')]),
            CarouselColumn(
                title='Jarkom',
                text='Jaringan Komputer',
                defaultAction=MessageAction(label='Latihan',
                                            text='quiz-Jarkom'),
                actions=[MessageAction(label='Latihan', text='quiz-Jarkom')])
        ])
        messageQuiz = TemplateSendMessage(alt_text='Tampilkan Nilai',
                                          template=menuQuiz)
        line_bot_api.reply_message(event.reply_token, messageQuiz)
    elif (event.message.text.lower() == "quiz-ai"):
        menuQuiz = CarouselTemplate(columns=[
            CarouselColumn(title='Bab 1',
                           text='Pengenalan AI',
                           defaultAction=MessageAction(label='Mulai Quiz',
                                                       text='quiz-pengenalan'),
                           actions=[
                               MessageAction(label='Mulai Quiz',
                                             text='quiz-pengenalan')
                           ]),
            CarouselColumn(title='Bab 2',
                           text='Learning',
                           defaultAction=MessageAction(label='Mulai Quiz',
                                                       text='quiz-learning'),
                           actions=[
                               MessageAction(label='Mulai Quiz',
                                             text='quiz-learning')
                           ])
        ])
        messageQuiz = TemplateSendMessage(alt_text='Tampilkan Nilai',
                                          template=menuQuiz)
        line_bot_api.reply_message(event.reply_token, messageQuiz)

    elif (event.message.text.lower() == "quiz-pengenalan"):
        # jika tombol aturan ditekan
        # fungsi yang akan dilakukan ditulis dibawah ini
        aturanMenu = ButtonsTemplate(
            title='Pengenalan',
            text='Mana yang bukan pendekatan AI?',
            actions=[
                MessageAction(label='Thinking Humanlly', text='TH'),
                MessageAction(label='Thinking Animally ', text='TA'),
                MessageAction(label='Acting Humanlly', text='AH'),
                MessageAction(label='Acting Rationally', text='AR')
            ])
        aturanMessage = TemplateSendMessage(alt_text='To do List Menu',
                                            template=aturanMenu)
        line_bot_api.reply_message(event.reply_token, aturanMessage)
    elif (event.message.text.lower() == "th"
          or event.message.text.lower() == "ah"
          or event.message.text.lower() == "ar"):
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text='Persentase Kebenaran: 0%\n Ayo semangat ngerjainnya!'))
    elif (event.message.text.lower() == "ta"):
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text='Persentase Kebenaran: 100%\n Alhamdulillah bener semua'))
    else:
        inputTextA = event.message.text.lower().split(": ")
        inputTextB = event.message.text.lower().split(" :")
        inputTextC = event.message.text.lower().split(":")
        inputTextD = event.message.text.lower().split(" ")
        if (inputTextA[0] == "add" or inputTextA[0] == "referensi"):
            inputText = inputTextA
        elif (inputTextB[0] == "add" or inputTextB[0] == "referensi"):
            inputText = inputTextB
        elif (inputTextC[0] == "add" or inputTextC[0] == "referensi"):
            inputText = inputTextC
        elif (inputTextD[0] == "add" or inputTextD[0] == "referensi"):
            inputText = inputTextD
        else:
            inputText = []
        if (inputText[0] == "add"):
            # fungsi untuk menambahkan to-do list
            global toDoListString
            toDoListString = 'Judul To-do List : ' + inputText[1]
            addToDoListMenu = ButtonsTemplate(
                title='Add To Do List',
                text=toDoListString,
                actions=[
                    DatetimePickerTemplateAction(
                        label='Pilih tanggal',
                        data='todolist_datetime_postback',
                        mode='datetime')
                ])
            addToDoListMessage = TemplateSendMessage(
                alt_text='To do List Menu', template=addToDoListMenu)
            line_bot_api.reply_message(event.reply_token, addToDoListMessage)
        elif (inputText[0] == "referensi"):
            # fungsi untuk mencari referensi dengan keyword mata kuliah
            temp = [
                MessageAction(label=x.split(" ")[1],
                              text=x.split(" ")[0] + " " +
                              " ".join(x.split(" ")[2:])) for x in matkul_list
                if inputText[1].lower() in x.lower()
            ]
            if (temp):
                matkulMenu = CarouselTemplate(columns=[
                    CarouselColumn(title=x.label,
                                   text=x.text,
                                   defaultAction=x,
                                   actions=[x]) for x in temp
                ])
                matkulMessage = TemplateSendMessage(
                    alt_text='Daftar mata kuliah', template=matkulMenu)
                line_bot_api.reply_message(event.reply_token, matkulMessage)
            else:
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage('Tidak ditemukan mata kuliah terkait ' +
                                    '\'' + inputText[1] + '\''))
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(
                    "Maaf, kami tidak mengerti permintaan anda harap cek kembali input anda"
                ))
Пример #17
0
                                 PostbackTemplateAction(label='時代力量',
                                                        data='時代力量'),
                                 PostbackTemplateAction(label='無黨籍',
                                                        data='無黨籍')
                             ]))
######################################################
time_buttons_template_message = TemplateSendMessage(
    alt_text='Buttons template',
    template=ButtonsTemplate(
        thumbnail_image_url=Webhook_URL + '/static/images/time',
        title='請選擇時間區間',
        text='Please select',
        actions=[
            DatetimePickerTemplateAction(label="開始時間",
                                         data="輸入結束時間",
                                         mode="date",
                                         initial="2017-08-01",
                                         min="2017-01-01",
                                         max="2017-12-31"),
            DatetimePickerTemplateAction(label="結束時間",
                                         data="輸入想查詢的『政治人名』或『政黨』",
                                         mode="date",
                                         initial="2017-08-01",
                                         min="2017-01-01",
                                         max="2017-12-31"),
        ]))
######################################################


def response(event):
    if "你好" in event.message.text:
        line_bot_api.reply_message(event.reply_token,
Пример #18
0
def handle_text_message(event):
    text = event.message.text
    cancel_message = 'type "cancel" to cancel search'
    if text == 'profile':
        if isinstance(event.source, SourceUser):
            profile = line_bot_api.get_profile(event.source.user_id)
            line_bot_api.reply_message(
                event.reply_token, [
                    TextSendMessage(
                        text='Display name: ' + profile.display_name
                    ),
                    TextSendMessage(
                        text='Status message: ' + profile.status_message
                    )
                ]
            )
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextMessage(text="Bot can't use profile API without user ID"))
    elif text == 'bye':
        if isinstance(event.source, SourceGroup):
            line_bot_api.reply_message(
                event.reply_token, TextMessage(text='Leaving group'))
            line_bot_api.leave_group(event.source.group_id)
        elif isinstance(event.source, SourceRoom):
            line_bot_api.reply_message(
                event.reply_token, TextMessage(text='Leaving group'))
            line_bot_api.leave_room(event.source.room_id)
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextMessage(text="Bot can't leave from 1:1 chat"))
    elif text == 'confirm':
        confirm_template = ConfirmTemplate(text='Do it?', actions=[
            MessageTemplateAction(label='Yes', text='Yes!'),
            MessageTemplateAction(label='No', text='No!'),
        ])
        template_message = TemplateSendMessage(
            alt_text='Confirm alt text', template=confirm_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'buttons':
        buttons_template = ButtonsTemplate(
            title='My buttons sample', text='Hello, my buttons', actions=[
                URITemplateAction(
                    label='Go to line.me', uri='https://line.me'),
                PostbackTemplateAction(label='ping', data='ping'),
                PostbackTemplateAction(
                    label='ping with text', data='ping',
                    text='ping'),
                MessageTemplateAction(label='Translate Rice', text='米')
            ])
        template_message = TemplateSendMessage(
            alt_text='Buttons alt text', template=buttons_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'carousel':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(text='hoge1', title='fuga1', actions=[
                URITemplateAction(
                    label='Go to line.me', uri='https://line.me'),
                PostbackTemplateAction(label='ping', data='ping')
            ]),
            CarouselColumn(text='hoge2', title='fuga2', actions=[
                PostbackTemplateAction(
                    label='ping with text', data='ping',
                    text='ping'),
                MessageTemplateAction(label='Translate Rice', text='米')
            ]),
        ])
        template_message = TemplateSendMessage(
            alt_text='Carousel alt text', template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'image_carousel':
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
                                action=DatetimePickerTemplateAction(label='datetime',
                                                                    data='datetime_postback',
                                                                    mode='datetime')),
            ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
                                action=DatetimePickerTemplateAction(label='date',
                                                                    data='date_postback',
                                                                    mode='date'))
        ])
        template_message = TemplateSendMessage(
            alt_text='ImageCarousel alt text', template=image_carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'imagemap':
        pass
    elif text == 'Find egg':
        #Actionnya masih gak ngerti gimana caranya actionnya text Category: Arabian aja
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(image_url='https://www.theurbanlist.com/content/article/wysiwyg/three-williams-eggs.png',
                                action=PostbackTemplateAction(label='Arabian egg\nRp 25.000,00',data='arabian-egg')),
            ImageCarouselColumn(image_url='https://www.fritzmag.com.au/wp-content/uploads/2016/12/Get-Your-Googie-On-With-South-Australian-Eggs-2.jpg',
                                action=DatetimePickerTemplateAction(label='Australian egg\nRp 25.000,00',
                                                                    data='australian-egg'))
        ])
        template_message = TemplateSendMessage(
            alt_text='ImageCarousel alt text', template=image_carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'cancel':
        line_bot_api.reply_message(
            event.reply_token,
            TextMessage(text="Welcome..."))
    elif text == 'Category: Arabian':
        #Belum bisa actionnya juga
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(image_url='https://www.theurbanlist.com/content/article/wysiwyg/three-williams-eggs.png',
                                action=DatetimePickerTemplateAction(label='date',
                                                                    data='date_postback',
                                                                    mode='date')),
        ])
        template_message = TemplateSendMessage(
            alt_text='ImageCarousel alt text', template=image_carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'Choose Arabian egg':
        message = 'Arabian egg\n\nPrice: Rp. 25,000.00\nStore location: Yogya karapitan (Bandung)\nCondition: Good\n\nTo buy this product type "Buy Arabian egg"'
        line_bot_api.reply_message(
            event.reply_token, TextSendMessage(text=message))
    elif text == 'Findstore Yogya':
        message = 'Search result for "Yogya"\n1. Yogya Karapitan\n2. Yogya Riau Junction\n3. Yogya Sunda\n4. Yogya Minimarket\n\nType number to choose shope e.g: 1 to choose Yogya Karapitan'
        line_bot_api.reply_message(
            event.reply_token, TextSendMessage(text=message))
    elif text == '1':
        message = 'You choose Yogya Karapitan\n\nTo search products, type "Find <product name>\n\nTo view other instructions type "help"'
        line_bot_api.reply_message(
            event.reply_token, TextSendMessage(text=message))
    elif text == 'list transactions':
        #Actionnya belum bisa nanti actionnya ke view transaction 15022 aja
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(image_url='https://www.theurbanlist.com/content/article/wysiwyg/three-williams-eggs.png',
                                action=DatetimePickerTemplateAction(label='date',
                                                                    data='date_postback',
                                                                    mode='date')),
            ImageCarouselColumn(image_url='https://www.fritzmag.com.au/wp-content/uploads/2016/12/Get-Your-Googie-On-With-South-Australian-Eggs-2.jpg',
                                action=DatetimePickerTemplateAction(label='date',
                                                                    data='date_postback',
                                                                    mode='date'))
        ])
        template_message = TemplateSendMessage(
            alt_text='ImageCarousel alt text', template=image_carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'view transaction 15022':
        #Edit aja gambarnya + actionnya juga + labelnya juga masih dummy ini
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(image_url='https://www.theurbanlist.com/content/article/wysiwyg/three-williams-eggs.png',
                                action=DatetimePickerTemplateAction(label='date',
                                                                    data='date_postback',
                                                                    mode='date')),
        ])
    elif text == 'Compare':
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(image_url='https://www.theurbanlist.com/content/article/wysiwyg/three-williams-eggs.png',
                                action=DatetimePickerTemplateAction(label='datetime',
                                                                    data='datetime_postback',
                                                                    mode='datetime')),
            ImageCarouselColumn(image_url='https://www.fritzmag.com.au/wp-content/uploads/2016/12/Get-Your-Googie-On-With-South-Australian-Eggs-2.jpg',
                                action=DatetimePickerTemplateAction(label='date',
                                                                    data='date_postback',
                                                                    mode='date'))
        ])
        template_message = TemplateSendMessage(
            alt_text='Choose one of these products to compare with <current_product>', template=image_carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'Display all':
        line_bot_api.reply_message(
            event.reply_token,
            TextMessage(text="Arabian egg vs Mysterious egg\n\nShell:\nSpike shell vs Smooth shell\n\nShape:\nRound shape vs Oval shape\n\nSize:10inch vs 18inch\n\nColor:\nRed vs Cream.\n\nMysterious egg's exclusive properties:\nDoes not break when thrown with a force.\nIs not known if it's an actual egg.\n\nAustralian egg's exclusive properties:\n-"))
    elif text == 'Change':
		carousel_template = CarouselTemplate(columns=[
            CarouselColumn(text='Mysterious egg', title='1', actions=[
                URITemplateAction(
                    label='Go to line.me', uri='https://line.me'),
                PostbackTemplateAction(label='ping', data='ping')
            ]),
            CarouselColumn(text='Arabian egg', title='2', actions=[
                PostbackTemplateAction(
                    label='ping with text', data='ping',
                    text='ping'),
                MessageTemplateAction(label='Translate Rice', text='米')
            ]),
        ])
        template_message = TemplateSendMessage(
            alt_text='Choose which one to replace.', template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
Пример #19
0
def handle_message(event):
    if event.message.text != "":
        auth_json_path = 'google_sheet.json'
        gss_scopes = ['https://spreadsheets.google.com/feeds']
        gss_client = google_sheet.auth_gss_client(auth_json_path, gss_scopes)
        spreadsheet_key = '1Q4hWEVjTB-rdc7HAi_Yc_cF4uymjfPHe70Cc36fLHyM'
        the_id = event.source.user_id
        profile = line_bot_api.get_profile(the_id)
        user_name = profile.display_name
        message = event.message.text
        google_sheet.user_log(gss_client, spreadsheet_key, the_id, user_name,
                              message)

    if event.message.text == '強制輸入':
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(
                image_url='https://upload.cc/i1/2018/05/31/d6Skxh.png',
                action=DatetimePickerTemplateAction(
                    label='點我選最近一次經期日期', data='update', mode='date'))
        ])
        template_message = TemplateSendMessage(
            alt_text='第一次輸入月經', template=image_carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
        return 0

    elif event.message.text in ('hi', 'Hi', 'HI', 'hello', '你好', '哈囉', '嗨'):
        profile = line_bot_api.get_profile(event.source.user_id)
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text='Hi hi ' + profile.display_name + '\n' +
                            '輸入"menu"來玩吧!\n( ━☞´◔‿ゝ◔`)━☞')
        ])

    elif event.message.text == 'id':
        line_bot_api.reply_message(
            event.reply_token,
            [TextSendMessage(text='id: ' + event.source.user_id)])

    elif event.message.text == '瘦腿':
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(
                text=
                'https://www.youtube.com/watch?v=3X1PL7ym04I&list=PL2T5-4ENPUpIkpC0oGj6r-dLLluOeSeUn&index=2&t=1s'
            ),
            TextSendMessage(
                text=
                'https://www.youtube.com/watch?v=Rr8CEyQ3-5k&index=2&list=PL2T5-4ENPUpIkpC0oGj6r-dLLluOeSeUn'
            )
        ])
        return 0

    elif event.message.text == '蝴蝶袖':
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(
                text='https://www.youtube.com/watch?v=C8oSs8qf_7g'),
            TextSendMessage(text='https://www.youtube.com/watch?v=Fh0WLIFQVdk')
        ])
        return 0

    elif event.message.text == '瘦肚子':
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(
                text='https://www.youtube.com/watch?v=dzFs1eA6DV8'),
            TextSendMessage(text='https://www.youtube.com/watch?v=qT9aYCk5fmI')
        ])
        return 0

    elif event.message.text == '激烈一點':
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(
                text='https://www.youtube.com/watch?v=40Gd7pOF0L8'),
            TextSendMessage(text='https://www.youtube.com/watch?v=ByLnybm0M88')
        ])
        return 0

    elif event.message.text in ('豐胸運動', '豐胸'):
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(
                text='https://www.youtube.com/watch?v=eBcZ22nUV_k'),
            TextSendMessage(text='https://www.youtube.com/watch?v=2HfEp3fpO9I')
        ])
        return 0

    elif event.message.text in ('那個來'):
        message = TextSendMessage(text='那個來怎麼辦呢')
        line_bot_api.reply_message(event.reply_token, message)
    elif event.message.text in ('沒來'):
        message = TextSendMessage(text='阿賀!!!??')
        line_bot_api.reply_message(event.reply_token, message)
    elif event.message.text in ('避孕'):
        message = TextSendMessage(text='怎麼避孕呢')
        line_bot_api.reply_message(event.reply_token, message)

    elif event.message.text in ('睡前瘦身', '減肥'):
        buttons_template = TemplateSendMessage(
            alt_text='睡前瘦身 template',
            template=ButtonsTemplate(
                title='想瘦哪兒',
                text='請選擇',
                thumbnail_image_url=
                'https://upload.cc/i1/2018/05/31/42AKh7.png',
                actions=[
                    MessageTemplateAction(label='瘦腿', text='瘦腿'),
                    MessageTemplateAction(label='蝴蝶袖', text='蝴蝶袖'),
                    MessageTemplateAction(label='瘦肚子', text='瘦肚子'),
                    MessageTemplateAction(label='激烈一點', text='激烈一點')
                ]))
        line_bot_api.reply_message(event.reply_token, buttons_template)
        return 0

    elif event.message.text in ('看帥哥', '看猛男'):
        message = TemplateSendMessage(
            alt_text='menu template',
            template=ImageCarouselTemplate(columns=[
                ImageCarouselColumn(
                    image_url='https://upload.cc/i1/2018/05/28/0BqKvb.png',
                    action=MessageTemplateAction(
                        label='減肥',
                        text='減肥',
                    )),
                ImageCarouselColumn(
                    image_url='https://upload.cc/i1/2018/05/27/cm2Gua.png',
                    action=MessageTemplateAction(
                        label='豐胸',
                        text='豐胸',
                    )),
                ImageCarouselColumn(
                    image_url='https://upload.cc/i1/2018/05/27/rMB73X.png',
                    action=MessageTemplateAction(
                        label='減肥',
                        text='減肥',
                    )),
                ImageCarouselColumn(
                    image_url='https://upload.cc/i1/2018/05/27/O0VTrv.png',
                    action=MessageTemplateAction(
                        label='豐胸',
                        text='豐胸',
                    )),
                ImageCarouselColumn(
                    image_url='https://upload.cc/i1/2018/05/27/onFG3Y.png',
                    action=MessageTemplateAction(
                        label='減肥',
                        text='減肥',
                    ))
            ]))
        line_bot_api.reply_message(event.reply_token, message)
        return 0

    elif event.message.text in ('看正妹', '看美女'):
        message = TemplateSendMessage(
            alt_text='menu template',
            template=ImageCarouselTemplate(columns=[
                ImageCarouselColumn(
                    image_url='https://upload.cc/i1/2018/05/27/ZzRxic.png',
                    action=MessageTemplateAction(
                        label='豐胸',
                        text='豐胸',
                    )),
                ImageCarouselColumn(
                    image_url='https://upload.cc/i1/2018/05/27/1A0gEe.png',
                    action=MessageTemplateAction(
                        label='減肥',
                        text='減肥',
                    )),
                ImageCarouselColumn(
                    image_url='https://upload.cc/i1/2018/05/27/XrYx1e.png',
                    action=MessageTemplateAction(
                        label='減肥',
                        text='減肥',
                    )),
                ImageCarouselColumn(
                    image_url='https://upload.cc/i1/2018/05/27/ltEiag.png',
                    action=MessageTemplateAction(
                        label='豐胸',
                        text='豐胸',
                    )),
                ImageCarouselColumn(
                    image_url='https://upload.cc/i1/2018/05/27/3YHWAq.png',
                    action=MessageTemplateAction(
                        label='減肥',
                        text='減肥',
                    ))
            ]))
        line_bot_api.reply_message(event.reply_token, message)
        return 0

    elif event.message.text in ('激勵', '看圖'):
        message = TemplateSendMessage(
            alt_text='Confirm template',
            template=ConfirmTemplate(text='看看別人,勉勵自己。來帖帥哥還是正妹?',
                                     actions=[
                                         MessageTemplateAction(
                                             label='看帥哥',
                                             text='看帥哥',
                                         ),
                                         MessageTemplateAction(label='看美女',
                                                               text='看美女')
                                     ]))
        line_bot_api.reply_message(event.reply_token, message)
        return 0

    elif event.message.text in ('update', 'Update', '更新日期', '輸入經期', '姨媽來了'):
        message = TemplateSendMessage(
            alt_text='確認輸入經期 template',
            template=ConfirmTemplate(
                text='要更新經期嗎?舊的紀錄會洗掉唷~',
                actions=[
                    MessageTemplateAction(label='我要輸入(๑ÒωÓ๑)', text='強制輸入'),
                    MessageTemplateAction(label='算了(´ー`)σ', text='上一次')
                ]))
        line_bot_api.reply_message(event.reply_token, message)
        return 0

    elif event.message.text in ('menu', 'Menu', '目錄', '姨媽'):
        message = TemplateSendMessage(
            alt_text='menu template',
            template=ImageCarouselTemplate(columns=[
                ImageCarouselColumn(
                    image_url='https://upload.cc/i1/2018/05/31/y6OWHi.png',
                    action=MessageTemplateAction(
                        label='算一下日期',
                        text='查詢',
                    )),
                ImageCarouselColumn(
                    image_url='https://upload.cc/i1/2018/05/31/eDdQMh.png',
                    action=MessageTemplateAction(
                        label='減肥',
                        text='減肥',
                    )),
                ImageCarouselColumn(
                    image_url='https://upload.cc/i1/2018/05/31/PXF1rR.png',
                    action=MessageTemplateAction(
                        label='豐胸',
                        text='豐胸',
                    )),
                ImageCarouselColumn(
                    image_url='https://upload.cc/i1/2018/05/31/1OWHVP.png',
                    action=MessageTemplateAction(
                        label='激勵',
                        text='激勵',
                    )),
                ImageCarouselColumn(
                    image_url='https://upload.cc/i1/2018/05/28/knXNB3.png',
                    action=PostbackTemplateAction(
                        Label='聯絡姨媽',
                        text='聯絡姨媽',
                        data='contact_me',
                    ))
            ]))
        line_bot_api.reply_message(event.reply_token, message)
        return 0

    elif event.message.text in ('聯絡姨媽', '姨媽是誰', '找姨媽'):
        message = TemplateSendMessage(
            alt_text='姨媽的聯絡方式',
            template=ButtonsTemplate(
                thumbnail_image_url=
                'https://upload.cc/i1/2018/05/28/Qtp3hR.png',
                title='這裡找姨媽',
                text='喜歡請按讚',
                actions=[
                    URITemplateAction(
                        label='Facebook',
                        uri='https://www.facebook.com/anna.yaping'),
                    URITemplateAction(
                        label='Instagram',
                        uri='https://www.instagram.com/anna_yaping/')
                ]))
        line_bot_api.reply_message(event.reply_token, message)

    elif event.message.text in ('上一次'):
        the_id = event.source.user_id
        profile = line_bot_api.get_profile(the_id)
        user_name = profile.display_name
        content = cal_period.next_period(the_id, user_name, '上一次')

        if content == 0:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='你還沒有輸入最近的一次月經日期歐~請輸入"update"來記錄吧!!'))
        else:
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=content))

    elif event.message.text in ('下一次'):
        the_id = event.source.user_id
        profile = line_bot_api.get_profile(the_id)
        user_name = profile.display_name
        content = cal_period.next_period(the_id, user_name, '下一次')

        if content == 0:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='你還沒有輸入最近的一次月經日期歐~請輸入"update"來記錄吧!!'))
        else:
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=content))

    elif event.message.text in ('黃金瘦身期', '瘦身期'):
        the_id = event.source.user_id
        profile = line_bot_api.get_profile(the_id)
        user_name = profile.display_name
        content = cal_period.next_period(the_id, user_name, '瘦身')

        if content == 0:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='你還沒有輸入最近的一次月經日期歐~請輸入"update"來記錄吧!!'))
        else:
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=content))

    elif event.message.text in ('黃金豐胸期', '豐胸期'):
        the_id = event.source.user_id
        profile = line_bot_api.get_profile(the_id)
        user_name = profile.display_name
        content = cal_period.next_period(the_id, user_name, '豐胸')

        if content == 0:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='你還沒有輸入最近的一次月經日期歐~請輸入"update"來記錄吧!!'))
        else:
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=content))

    elif event.message.text in ('全部', '查全部', '全部都來'):
        the_id = event.source.user_id
        profile = line_bot_api.get_profile(the_id)
        user_name = profile.display_name
        content = cal_period.next_period(the_id, user_name, 'all')

        if content == 0:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='你還沒有輸入最近的一次月經日期歐~請輸入"update"來記錄吧!!'))
        else:
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=content))

    elif event.message.text in ('危險', '危險期', '非安全期'):
        the_id = event.source.user_id
        profile = line_bot_api.get_profile(the_id)
        user_name = profile.display_name
        content = cal_period.next_period(the_id, user_name, '危險')

        if content == 0:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='你還沒有輸入最近的一次月經日期歐~請輸入"update"來記錄吧!!'))
        else:
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=content))

    elif event.message.text in ('經期相關', '查詢經期相關問題'):
        the_id = event.source.user_id
        profile = line_bot_api.get_profile(the_id)
        user_name = profile.display_name
        content = cal_period.next_period(the_id, user_name, '經期相關')

        if content == 0:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='你還沒有輸入最近的一次月經日期歐~請輸入"update"來記錄吧!!'))
        else:
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=content))

    elif event.message.text in ("查", "查詢"):
        buttons_template = TemplateSendMessage(
            alt_text='查詢 template',
            template=ButtonsTemplate(
                title='查什麼呢',
                text='要查什麼呢?',
                thumbnail_image_url=
                'https://upload.cc/i1/2018/05/31/DVwFRg.png',
                actions=[
                    MessageTemplateAction(label='查詢經期相關日期', text='經期相關'),
                    MessageTemplateAction(label='黃金瘦身期', text='黃金瘦身期'),
                    MessageTemplateAction(label='黃金豐胸期', text='黃金豐胸期'),
                    MessageTemplateAction(label='全部都來', text='查全部')
                ]))
        line_bot_api.reply_message(event.reply_token, buttons_template)
        return 0

    else:
        message = TextSendMessage(text=event.message.text)
        line_bot_api.reply_message(event.reply_token, message)