コード例 #1
0
def handle_message(event):
    """testers
    """
    if event.message.text == 'ping':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text='pong')
        )

    elif event.message.text == 'moe':
        # url = request.host_url + 'moe.m4a'
        # url = os.path.join(os.path.dirname(__file__), 'moe.m4a')
        # url = 'https://nofile.io/f/59nzWNmtAn6/moe.m4a'
        url = 'https://file.io/Jvz3hd'

        try:
            line_bot_api.reply_message(
                event.reply_token,
                AudioSendMessage(
                    original_content_url=url,
                    duration=2700
                )
            )
        except linebot.exceptions.LineBotApiError as e:
            app.logger.exception(e)
コード例 #2
0
def detect_json_array_to_new_message_array(fileName):
    ''' message_type 判斷器

        讀取指定的 json檔,解析成不同格式的 SendMessage
    '''
    with open(fileName, 'r', encoding='utf8') as f:
        jsonArray = json.load(f)
    
    newmessage_Array = []
    for jsonObject in jsonArray:
        message_type = jsonObject.get('type')
        
        if message_type == 'text':
            newmessage_Array.append(TextSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'sticker':
            newmessage_Array.append(StickerSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'image':
            newmessage_Array.append(ImageSendMessage.new_from_json_dict(jsonObject))  
        elif message_type == 'video':
            newmessage_Array.append(VideoSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'audio':
            newmessage_Array.append(AudioSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'location':
            newmessage_Array.append(LocationSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'imagemap':
            newmessage_Array.append(ImagemapSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'template':
            newmessage_Array.append(TemplateSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'flex':
            newmessage_Array.append(FlexSendMessage.new_from_json_dict(jsonObject))        

    return newmessage_Array
コード例 #3
0
 def message(event):
     text=event.message.text
     message_id=event.message.id
     
     s3 = resource('s3')
     bucket = s3.Bucket("linebot-polly")
     
     polly_client = boto3.Session(
                 aws_access_key_id=os.environ['aws_access_key_id'],                     
                 aws_secret_access_key=os.environ['aws_secret_access_key'],
                 region_name='ap-northeast-1').client('polly')
 
     response = polly_client.synthesize_speech(VoiceId='Mizuki',
                     OutputFormat='mp3', 
                     Text = text)
                     
     with closing(response["AudioStream"]) as stream:
         bucket.put_object(Key=f"{message_id}.mp3", Body=stream.read())
     
     original_content_url=f"https://linebot-polly.s3-ap-northeast-1.amazonaws.com/{message_id}.mp3"
     
     line_bot_api.reply_message(
     event.reply_token,
     AudioSendMessage(
         original_content_url=original_content_url,
         duration=5000
     ))
コード例 #4
0
def gen_msg_obj(reply_text, audio_duration=5000):
    if 'imgur' in reply_text:
        match_web = regex.search(
            r'(http|https):\/\/imgur\.com\/[a-z0-9A-Z]{7}', reply_text)
        match_jpg = regex.search(
            r'(http|https):\/\/(i|m)\.imgur\.com\/[a-z0-9A-Z]{7}\.jpg',
            reply_text)
        if match_web:
            match = match_web.group()
            imgur_url = regex.sub('http:', 'https:', match)
            print(imgur_url)
            return ImageSendMessage(original_content_url=imgur_url,
                                    preview_image_url=imgur_url)
        elif match_jpg:
            match = match_jpg.group()
            imgur_url = regex.sub('http:', 'https:', match)
            print(imgur_url)
            return ImageSendMessage(original_content_url=imgur_url,
                                    preview_image_url=imgur_url)
        else:
            return TextSendMessage(text=reply_text)
    elif 'm4a' in reply_text:
        reply_text = reply_text.replace('.m4a', '')
        m4a_url = 'https://marginalbear.ml/m4a/' + urllib.parse.quote(
            reply_text) + '.m4a'
        return AudioSendMessage(original_content_url=m4a_url,
                                duration=audio_duration)
    else:
        return TextSendMessage(text=reply_text)
コード例 #5
0
 def test_audio_message(self):
     arg = {
         'original_content_url': 'https://example.com/original.m4a',
         'duration': 60000
     }
     self.assertEqual(self.serialize_as_dict(arg, type=self.AUDIO),
                      AudioSendMessage(**arg).as_json_dict())
コード例 #6
0
def detect_json_array_to_new_message_array(fileName):
    # 開啟檔案,轉成json
    with open(fileName, 'r', encoding="utf-8") as f:
        jsonArray = json.load(f)

    # 解析json
    returnArray = []
    for jsonObject in jsonArray:

        # 讀取其用來判斷的元件
        message_type = jsonObject.get('type')

        # 轉換
        if message_type == 'text':
            returnArray.append(TextSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'imagemap':
            returnArray.append(ImagemapSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'template':
            returnArray.append(TemplateSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'image':
            returnArray.append(ImageSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'sticker':
            returnArray.append(StickerSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'audio':
            returnArray.append(AudioSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'location':
            returnArray.append(LocationSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'flex':
            returnArray.append(FlexSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'video':
            returnArray.append(FlexSendMessage.new_from_json_dict(jsonObject))

            # 回傳
    return returnArray
コード例 #7
0
def get_google_audio_message(query):
    url = get_google_audio_url(query)
    audio_send_message = AudioSendMessage(
        original_content_url=url,
        duration=len(query) * 1000 // 3  # chinese character has 3 bytes
    )
    return audio_send_message
コード例 #8
0
ファイル: func.py プロジェクト: cycyucheng1010/NQU
def sendAudio(event):
    try:
        message = AudioSendMessage(original_content_url=baseurl + '2.m4a',
                                   duration=49000)
        line_bot_api.reply_message(event.reply_token, message)
    except:
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text='發生錯誤'))
コード例 #9
0
ファイル: message.py プロジェクト: nanato12/pylinebot
 def create(
     self, quick_reply: Optional[QuickReply] = None, sender: Optional[Sender] = None
 ) -> AudioSendMessage:
     return AudioSendMessage(
         original_content_url=self.content_url,
         duration=self.duration,
         quick_reply=quick_reply,
         sender=sender,
     )
コード例 #10
0
def sendVoice(event):  #傳送聲音
    try:
        message = AudioSendMessage(
            original_content_url=baseurl + 'mario.m4a',  #聲音檔置於static資料夾
            duration=20000  #聲音長度20秒
        )
        line_bot_api.reply_message(event.reply_token, message)
    except:
        line_bot_api.reply_message(event.reply_token,TextSendMessage(text='發生錯誤!'))
コード例 #11
0
ファイル: func.py プロジェクト: peter0711/mcu-tourism
def sendVoice(event):  #傳送聲音
            try:
                  message = AudioSendMessage(
	          original_content_url='https://google-translate-proxy.herokuapp.com/api/tts?query=%27[台61線((西濱快速))] 北上157.7km指示牌看起來有點搖晃(已排除)後續排除%27&language=zh-tw',  #聲音檔置於static資料夾
                  duration=20000  #聲音長度20秒
                  ),
                  line_bot_api.reply_message(event.reply_token, message)
            except:
                line_bot_api.reply_message(event.reply_token,TextSendMessage(text='發生錯誤!'))
コード例 #12
0
ファイル: app.py プロジェクト: isudzumi/CHORD-LINER
def handle_message(event):
    response = chord_liner.get_chord(event)
    if not response:
        return {}
    line_bot_api.reply_message(
        event.reply_token,
        AudioSendMessage(
            original_content_url=response['url'],
            duration=response['duration']
        ))
コード例 #13
0
    def setUp(self):
        self.tested = LineBotApi('d42b9b5dc4df7ad44e9bddd5ee915fc7')

        self.audio_message = AudioSendMessage(
            original_content_url='https://example.com/original.m4a',
            duration=240000)

        self.message = [{
            "type": "audio",
            "originalContentUrl": "https://example.com/original.m4a",
            "duration": 240000,
        }]
コード例 #14
0
    def setUp(self):
        self.tested = LineBotApi('channel_secret')

        self.audio_message = AudioSendMessage(
            original_content_url='https://example.com/original.m4a',
            duration=240000)

        self.message = [{
            "type": "audio",
            "originalContentUrl": "https://example.com/original.m4a",
            "duration": 240000,
        }]
コード例 #15
0
def doing(event,text):
    patterns = ['你好','hi','hello','哈囉','嗨']
    r = ['教授最近好嗎','哈囉吳教授 最近很忙嗎','在做實驗室測試','這邊是中正大學','哈囉阿','帥哥 找我嗎?']
    n = random.randint(0,5)
    for pattern in patterns:
        if re.search(pattern,text.lower()):
                t =  quote(r[n])   #把中文字改成網頁的編碼格式,利用我import進來的urllib.parse模組的quote方法來幫忙我們做到
                stream_url = 'https://google-translate-proxy.herokuapp.com/api/tts?query='+t+'&language=zh-tw'
                message = AudioSendMessage(
                    original_content_url = stream_url,
                    duration=20000
                )
                line_bot_api.reply_message(event.reply_token,message)    
	    except:
コード例 #16
0
ファイル: app.py プロジェクト: oange6214/Tibame_Projects
def handle_content_message(event):
    dest_langs = get_dest_langs(event.source.user_id)

    # 接收使用者語音
    r = sr.Recognizer()
    message_content = line_bot_api.get_message_content(event.message.id)
    try:
        # 將 line 語音轉 SR 可用格式 (m4a 轉 wav)
        with tempfile.NamedTemporaryFile(delete=False) as tf:
            for chunk in message_content.iter_content():
                tf.write(chunk)
            tempfile_path = tf.name
        try:
            # 利用 ffmpeg 轉檔
            AudioSegment.converter = '../../ffmpeg.exe'  # 本機使用
            sound = AudioSegment.from_file_using_temporary_files(tempfile_path)
        except:
            AudioSegment.converter = '/app/vendor/ffmpeg/ffmpeg'  # (Heruku版)
            sound = AudioSegment.from_file_using_temporary_files(tempfile_path)
        path = os.path.splitext(tempfile_path)[0] + '.wav'
        sound.export(path, format="wav")
        with sr.AudioFile(path) as source:
            audio = r.record(source)

    except Exception as e:
        t = '音訊有問題'
        line_bot_api.reply_message(event.reply_token, TextSendMessage(text=t))
    os.remove(path)
    # 語音 轉 文字
    text = r.recognize_google(audio, language='zh-TW')

    # 翻譯處理
    trans = Translator()
    trans_text = trans.translate(text, dest=dest_langs).extra_data['translation'][0][0]
    # 文字 轉 語音
    tts = gTTS(trans_text, lang=dest_langs)
    tts_url = tts.get_urls()[0]

    # 回覆語音訊息
    line_bot_api.reply_message(
        event.reply_token,
        [
            TextSendMessage(text=trans_text),
            AudioSendMessage(
                original_content_url=tts_url,
                duration=100000
            )
        ]
    )
コード例 #17
0
 def startTranslate(self):
     if self.toLang == "None":
         return TextSendMessage(
             "Do not support this language now, please try again or type @使用說明 to understand usage"
         )
     else:
         translator = Translator(from_lang='zh-Hant', to_lang=self.toLang)
         translation = translator.translate(self.oriText)
         text = quote(translation)
         speakTime = 0.4 * len(translation)
         stream_url = 'https://google-translate-proxy.herokuapp.com/api/tts?query=' + text + '&language=' + self.toLang
         replyMessage = [
             TextSendMessage(translation),
             AudioSendMessage(stream_url, (int(speakTime) + 1) * 1000)
         ]
         return replyMessage
コード例 #18
0
def sendTranslate(event, lang, sound, mtext):  #翻譯及朗讀
    try:
        translator = Translator(from_lang="zh-Hant", to_lang=lang)
        #來源是中文,翻譯後語言為lang
        translation = translator.translate(mtext)  #進行翻譯
        text = quote(translation)
        stream_url = 'https://google-translate-proxy.herokuapp.com/api/tts?query='\
        + text + '&language=' + lang  #使用google語音API
        message = [  #若要發音需傳送文字及語音,必須使用陣列
            TextSendMessage(alt_text="文字翻譯",text = translation),#傳送翻譯後文字
            AudioSendMessage(alt_text="語音翻譯",\
                             original_content_url = stream_url,duration=20000),#傳送語音
        ]
        line_bot_api.reply_message(event.reply_token, message)
    except:
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text='發生錯誤!'))
コード例 #19
0
def textHandler(event):
    userId = event.source.user_id

    data, trackURL, previewURL, title, artist, img, album = getTrackData(event.message.text)
    print("\n\n\n")
    print(data)
    print("\n\n\n")

    flexMessage = prepareFlexMessage(data)

    lineBotApi.reply_message(
            event.reply_token,FlexSendMessage(alt_text="Here is your search result", contents=flexMessage)
            )

    if previewURL != None:
        lineBotApi.push_message(userId,AudioSendMessage(previewURL,30000))
    else:
        lineBotApi.push_message(userId,TextSendMessage(text='No Audio Preview Available'))
コード例 #20
0
def build_complex_msg(result):
    complex_msg = []
    for msg_type, msg in result:
        if msg_type == 'text':
            complex_msg.append(TextSendMessage(text=msg))
        elif msg_type == 'image':
            complex_msg.append(
                ImageSendMessage(
                    original_content_url=msg,
                    preview_image_url=msg,
                ))
        elif msg_type == 'audio':
            complex_msg.append(
                AudioSendMessage(original_content_url=msg, duration=10 * 1000))
        elif msg_type == 'flex':
            complex_msg.append(msg)
        else:
            raise ValueError(f" unknown msg_type: {msg_type}")
    return complex_msg
コード例 #21
0
def sendTranslate2(event, lang, sound, mtext):  #翻譯及朗讀
    try:
        translator = Translator(from_lang=lang,
                                to_lang="zh-Hant")  #來源是中文,翻譯後語言為lang
        translation = translator.translate(mtext[1:])  #進行翻譯
        if sound == 'yes':  #發音
            text = quote(translation)
            stream_url = 'https://google-translate-proxy.herokuapp.com/api/tts?query=' + text + '&language=' + "zh-Hant"  #使用google語音API
            message = [  #若要發音需傳送文字及語音,必須使用陣列
                TextSendMessage(  #傳送翻譯後文字
                    text=translation),
                AudioSendMessage(  #傳送語音
                    original_content_url=stream_url, duration=20000),
            ]
        else:  #不發音
            message = TextSendMessage(text=translation)
        line_bot_api.reply_message(event.reply_token, message)
    except:
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text='發生錯誤!'))
コード例 #22
0
def handle_message(event):
    msg = event.message.text
    r = "Sorry, I don't what you are talking about. "

    if "voice" in msg:
        audio_message = AudioSendMessage(
            original_content_url='https://example.com/original.m4a',
            duration=240000)
        line_bot_api.reply_message(event.reply_token, audio_message)
        return

    if "hi" in msg:
        r = "Hello"
    elif "Hi" in msg:
        r = "Hello"
    elif msg == "Did you have a meal":
        r = "No"
    elif "book" in msg:
        r = " how many people, what time"
    elif "who" in msg:
        r = " Robt"
    line_bot_api.reply_message(event.reply_token, TextSendMessage(text=r))
コード例 #23
0
def handle_image(event):
    # get user & message id
    user_id = event.source.user_id
    message_id = event.message.id
    # get image content
    message_content = line_bot_api.get_message_content(message_id)
    # write image file
    if not os.path.exists('./img/'):
        os.mkdir('./img/')
    with open('./img/%s_%s.jpg' % (user_id, message_id), 'wb') as fd:
        for chunk in message_content.iter_content():
            fd.write(chunk)
    # read local image file
    image_data = open('./img/%s_%s.jpg' % (user_id, message_id), "rb").read()
    # Using the functions implementing Azure API
    # image to text
    reply_text = image_to_text(img_data=image_data)
    # text to speech
    text_to_speech(reply_text, message_id)
    with contextlib.closing(
            wave.open('./static/audio/%s.wav' % (message_id), 'r')) as f:
        frames = f.getnframes()
        rate = f.getframerate()
        duration = 1000 * frames / float(rate)
    # search youtube video
    vids = text_to_ytsearch(reply_text)
    # reply messages
    SendMessages = list()
    SendMessages.append(TextSendMessage(text=reply_text))
    SendMessages.append(
        AudioSendMessage(original_content_url='%s/static/audio/%s.wav' %
                         (NGROK_URL, message_id),
                         duration=duration))
    if len(vids) > 0:
        for obj in vids:
            if len(SendMessages) == 5:
                break
            SendMessages.append(TextSendMessage(text=obj['video_url']))
    line_bot_api.reply_message(event.reply_token, SendMessages)
コード例 #24
0
ファイル: func.py プロジェクト: lillian417/LineBot
def sendTranslate(event, lang, sound, mtext):
    try:
        translator = Translator(from_lang="zh-Hant", to_lang=lang)
        translation = translator.translate(mtext)
        if sound =='yes':
            text = quote(translation)
            stream_url = 'https://google-translate-proxy.herokuapp.com/api/tts?query='+text+'&language='+lang
            message = [
                TextSendMessage(
                    text = translation
                ),
                AudioSendMessage(
                    original_content_url= stream_url,
                    duration=20000
                ),
            ]
        else:
            message = TextSendMessage(
                text = translation
            )
        line_bot_api.reply_message(event.reply_token,message)
    except:
        line_bot_api.reply_message(event.reply_token,TextSendMessage(text='發生錯誤!'))
コード例 #25
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: ' +
                                str(profile.status_message)),
                TextSendMessage(text='User_id: ' + event.source.user_id),
            ])
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(
                    text="Bot can't use profile API without user ID"))
    elif text == 'quota':
        quota = line_bot_api.get_message_quota()
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text='type: ' + quota.type),
            TextSendMessage(text='value: ' + str(quota.value))
        ])
    elif text == 'quota_consumption':
        quota_consumption = line_bot_api.get_message_quota_consumption()
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text='total usage: ' +
                            str(quota_consumption.total_usage)),
        ])
    elif text == 'push':
        line_bot_api.push_message(event.source.user_id, [
            TextSendMessage(text='PUSH!'),
        ])
    elif text == 'multicast':
        line_bot_api.multicast([event.source.user_id], [
            TextSendMessage(text='THIS IS A MULTICAST MESSAGE'),
        ])
    elif text == 'broadcast':
        line_bot_api.broadcast([
            TextSendMessage(text='THIS IS A BROADCAST MESSAGE'),
        ])
    elif text.startswith('broadcast '):  # broadcast 20190505
        date = text.split(' ')[1]
        print("Getting broadcast result: " + date)
        result = line_bot_api.get_message_delivery_broadcast(date)
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text='Number of sent broadcast messages: ' + date),
            TextSendMessage(text='status: ' + str(result.status)),
            TextSendMessage(text='success: ' + str(result.success)),
        ])
    elif text == 'bye':
        if isinstance(event.source, SourceGroup):
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(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,
                                       TextSendMessage(text='Leaving group'))
            line_bot_api.leave_room(event.source.room_id)
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text="Bot can't leave from 1:1 chat"))
    elif text == 'image':
        url = request.url_root + '/static/logo.png'
        app.logger.info("url=" + url)
        line_bot_api.reply_message(event.reply_token,
                                   ImageSendMessage(url, url))
    elif text == 'audio':
        line_bot_api.reply_message(
            event.reply_token,
            AudioSendMessage(
                original_content_url=
                'https://shareboxnow.com/wp-content/uploads/2020/02/test.m4a',
                duration=2000))
    elif text == 'video':
        line_bot_api.reply_message(
            event.reply_token,
            VideoSendMessage(
                original_content_url=
                'https://shareboxnow.com/wp-content/uploads/2020/02/IMG_0469.mp4',
                preview_image_url=
                'https://shareboxnow.com/wp-content/uploads/2020/02/th.jpeg'))
    elif text == 'location':
        line_bot_api.reply_message(
            event.reply_token,
            LocationSendMessage(title='我未來要爬的山!',
                                address='Himalayas',
                                latitude=28.598316,
                                longitude=83.931061))

    elif text == 'confirm':
        confirm_template = ConfirmTemplate(text='Do it?',
                                           actions=[
                                               MessageAction(label='Yes',
                                                             text='Yes!'),
                                               MessageAction(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',
            thumbnail_image_url=
            'https://logos-download.com/wp-content/uploads/2016/10/Python_logo_wordmark-700x203.png',
            actions=[
                URIAction(label='Go to line.me', uri='https://line.me'),
                PostbackAction(label='ping', data='ping'),
                PostbackAction(label='ping with text',
                               data='ping',
                               text='ping'),
                MessageAction(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',
                thumbnail_image_url=
                'https://logos-download.com/wp-content/uploads/2016/10/Python_logo_wordmark-700x203.png',
                title='fuga1',
                actions=[
                    URIAction(label='Go to line.me', uri='https://line.me'),
                    PostbackAction(label='ping', data='ping')
                ]),
            CarouselColumn(
                text='hoge2',
                thumbnail_image_url=
                'https://logos-download.com/wp-content/uploads/2016/10/Python_logo_wordmark-700x203.png',
                title='fuga2',
                actions=[
                    PostbackAction(
                        label='ping with text', data='ping', text='ping'),
                    MessageAction(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=DatetimePickerAction(label='datetime',
                                            data='datetime_postback',
                                            mode='datetime')),
            ImageCarouselColumn(
                image_url='https://via.placeholder.com/1024x1024',
                action=DatetimePickerAction(
                    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 == 'flex':
        bubble = BubbleContainer(
            direction='ltr',
            hero=ImageComponent(url='https://example.com/cafe.jpg',
                                size='full',
                                aspect_ratio='20:13',
                                aspect_mode='cover',
                                action=URIAction(uri='http://example.com',
                                                 label='label')),
            body=BoxComponent(
                layout='vertical',
                contents=[
                    # title
                    TextComponent(text='Brown Cafe', weight='bold', size='xl'),
                    # review
                    BoxComponent(
                        layout='baseline',
                        margin='md',
                        contents=[
                            IconComponent(
                                size='sm',
                                url='https://example.com/gold_star.png'),
                            IconComponent(
                                size='sm',
                                url='https://example.com/grey_star.png'),
                            IconComponent(
                                size='sm',
                                url='https://example.com/gold_star.png'),
                            IconComponent(
                                size='sm',
                                url='https://example.com/gold_star.png'),
                            IconComponent(
                                size='sm',
                                url='https://example.com/grey_star.png'),
                            TextComponent(text='4.0',
                                          size='sm',
                                          color='#999999',
                                          margin='md',
                                          flex=0)
                        ]),
                    # info
                    BoxComponent(
                        layout='vertical',
                        margin='lg',
                        spacing='sm',
                        contents=[
                            BoxComponent(
                                layout='baseline',
                                spacing='sm',
                                contents=[
                                    TextComponent(text='Place',
                                                  color='#aaaaaa',
                                                  size='sm',
                                                  flex=1),
                                    TextComponent(text='Shinjuku, Tokyo',
                                                  wrap=True,
                                                  color='#666666',
                                                  size='sm',
                                                  flex=5)
                                ],
                            ),
                            BoxComponent(
                                layout='baseline',
                                spacing='sm',
                                contents=[
                                    TextComponent(text='Time',
                                                  color='#aaaaaa',
                                                  size='sm',
                                                  flex=1),
                                    TextComponent(
                                        text="10:00 - 23:00",
                                        wrap=True,
                                        color='#666666',
                                        size='sm',
                                        flex=5,
                                    ),
                                ],
                            ),
                        ],
                    )
                ],
            ),
            footer=BoxComponent(
                layout='vertical',
                spacing='sm',
                contents=[
                    # callAction, separator, websiteAction
                    SpacerComponent(size='sm'),
                    # callAction
                    ButtonComponent(
                        style='link',
                        height='sm',
                        action=URIAction(label='CALL', uri='tel:000000'),
                    ),
                    # separator
                    SeparatorComponent(),
                    # websiteAction
                    ButtonComponent(style='link',
                                    height='sm',
                                    action=URIAction(
                                        label='WEBSITE',
                                        uri="https://example.com"))
                ]),
        )
        message = FlexSendMessage(alt_text="hello", contents=bubble)
        line_bot_api.reply_message(event.reply_token, message)
    elif text == 'flex_update_1':
        bubble_string = """
        {
          "type": "bubble",
          "body": {
            "type": "box",
            "layout": "vertical",
            "contents": [
              {
                "type": "image",
                "url": "https://scdn.line-apps.com/n/channel_devcenter/img/flexsnapshot/clip/clip3.jpg",
                "position": "relative",
                "size": "full",
                "aspectMode": "cover",
                "aspectRatio": "1:1",
                "gravity": "center"
              },
              {
                "type": "box",
                "layout": "horizontal",
                "contents": [
                  {
                    "type": "box",
                    "layout": "vertical",
                    "contents": [
                      {
                        "type": "text",
                        "text": "Brown Hotel",
                        "weight": "bold",
                        "size": "xl",
                        "color": "#ffffff"
                      },
                      {
                        "type": "box",
                        "layout": "baseline",
                        "margin": "md",
                        "contents": [
                          {
                            "type": "icon",
                            "size": "sm",
                            "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"
                          },
                          {
                            "type": "icon",
                            "size": "sm",
                            "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"
                          },
                          {
                            "type": "icon",
                            "size": "sm",
                            "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"
                          },
                          {
                            "type": "icon",
                            "size": "sm",
                            "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"
                          },
                          {
                            "type": "icon",
                            "size": "sm",
                            "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gray_star_28.png"
                          },
                          {
                            "type": "text",
                            "text": "4.0",
                            "size": "sm",
                            "color": "#d6d6d6",
                            "margin": "md",
                            "flex": 0
                          }
                        ]
                      }
                    ]
                  },
                  {
                    "type": "box",
                    "layout": "vertical",
                    "contents": [
                      {
                        "type": "text",
                        "text": "¥62,000",
                        "color": "#a9a9a9",
                        "decoration": "line-through",
                        "align": "end"
                      },
                      {
                        "type": "text",
                        "text": "¥42,000",
                        "color": "#ebebeb",
                        "size": "xl",
                        "align": "end"
                      }
                    ]
                  }
                ],
                "position": "absolute",
                "offsetBottom": "0px",
                "offsetStart": "0px",
                "offsetEnd": "0px",
                "backgroundColor": "#00000099",
                "paddingAll": "20px"
              },
              {
                "type": "box",
                "layout": "vertical",
                "contents": [
                  {
                    "type": "text",
                    "text": "SALE",
                    "color": "#ffffff"
                  }
                ],
                "position": "absolute",
                "backgroundColor": "#ff2600",
                "cornerRadius": "20px",
                "paddingAll": "5px",
                "offsetTop": "10px",
                "offsetEnd": "10px",
                "paddingStart": "10px",
                "paddingEnd": "10px"
              }
            ],
            "paddingAll": "0px"
          }
        }
        """
        message = FlexSendMessage(alt_text="hello",
                                  contents=json.loads(bubble_string))
        line_bot_api.reply_message(event.reply_token, message)
    elif text == 'quick_reply':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text='Quick reply',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(
                        action=PostbackAction(label="label1", data="ping")),
                    QuickReplyButton(
                        action=MessageAction(label="label2", text="text2")),
                    QuickReplyButton(action=DatetimePickerAction(
                        label="label3", data="data3", mode="date")),
                    QuickReplyButton(action=CameraAction(label="label4")),
                    QuickReplyButton(action=CameraRollAction(label="label5")),
                    QuickReplyButton(action=LocationAction(label="label6")),
                ])))
    elif text == 'link_token' and isinstance(event.source, SourceUser):
        link_token_response = line_bot_api.issue_link_token(
            event.source.user_id)
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text='link_token: ' +
                            link_token_response.link_token)
        ])
    elif text == 'insight_message_delivery':
        today = datetime.date.today().strftime("%Y%m%d")
        response = line_bot_api.get_insight_message_delivery(today)
        if response.status == 'ready':
            messages = [
                TextSendMessage(text='broadcast: ' + str(response.broadcast)),
                TextSendMessage(text='targeting: ' + str(response.targeting)),
            ]
        else:
            messages = [TextSendMessage(text='status: ' + response.status)]
        line_bot_api.reply_message(event.reply_token, messages)
    elif text == 'insight_followers':
        today = datetime.date.today().strftime("%Y%m%d")
        response = line_bot_api.get_insight_followers(today)
        if response.status == 'ready':
            messages = [
                TextSendMessage(text='followers: ' + str(response.followers)),
                TextSendMessage(text='targetedReaches: ' +
                                str(response.targeted_reaches)),
                TextSendMessage(text='blocks: ' + str(response.blocks)),
            ]
        else:
            messages = [TextSendMessage(text='status: ' + response.status)]
        line_bot_api.reply_message(event.reply_token, messages)
    elif text == 'insight_demographic':
        response = line_bot_api.get_insight_demographic()
        if response.available:
            messages = [
                "{gender}: {percentage}".format(gender=it.gender,
                                                percentage=it.percentage)
                for it in response.genders
            ]
        else:
            messages = [TextSendMessage(text='available: false')]
        line_bot_api.reply_message(event.reply_token, messages)
    else:
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=event.message.text))
コード例 #26
0
def handle_text_message(event):

    text = event.message.text
    inputText = event.message.text
    textArray = inputText.lower().split()
    groupId = event.source.group_id
    userId = event.source.user_id
    profile = line_bot_api.get_profile(userId)
    profile_name = profile.display_name
    profile_picture = profile.picture_url
    profile_sm = profile.status_message

    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 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

    if text == '/help':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage('Hai kak..ketik /cmd untuk menu lainnya.'))

    elif text == '/cmd':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                "Menu \n"
                "/about\n/help\n/profilku\n/bye\n/ppku\n/idku\n/samehadaku\n/sp\n"
                "/echo {teks}\n/kbbi {teks}\n/gambar {teks}\n/lokasi {teks}\n"
                "/trans {teks}\n/wiki {teks}\n/wikilang {teks}\n/lagu {teks}\n"
                "/hitung {teks}\n/cariyoutube {teks}\n/zodiak {teks}\n"))
    elif text == '/about':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage("Hai kak..nama saya Shin Chan \n"
                            "saya akan membuat obrolan kamu jadi makin seru."))
    elif ('ooh' in textArray) and ('wee' in textArray):
        ooh_wee(event, line_bot_api)

    elif 'semangatin' in textArray:
        semangat(event, line_bot_api)

    elif text[0] == '/':
        cmd = search(r'\#(\w*)\s*(.*)', text)
        if cmd.group(1) == 'gombal':
            if cmd.group(2) != '':
                txt = 'eh ' + cmd.group(2) + ',\n' + choice(list_gombal)
            else:
                txt = choice(list_gombal)
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=txt))

    elif text == '/bye':
        if (userId != 'Uf12a33117e93064e553855f6a4ce80eb'):
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text="Gak mau ah, Kamu kan bukan Abangku!"))
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text="Hai kak " + profile_name +
                                " Aku keluar dulu ya..!"))
            line_bot_api.leave_group(groupId)

    elif text == '/kbbi':
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage('Ketik /kbbi {input}'))

    elif text == '/trans':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage('Ketik /trans sc={}, to={}, {text}'))

    elif text == '/wiki':
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage('Ketik /wiki {text}'))

    elif text == '/wikilang':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage('Ketik /wikilang {language_id}'))

    elif text == '/idku':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="Hai " + profile_name +
                            ", ini adalah id kamu: " + userId))

    elif text == '/profilku':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="~ [ R E S U L T ] ~\n\n Nama: " +
                            profile_name + "\n Foto Profil: " +
                            profile_picture + "\n Pesan Status: " +
                            profile_sm))

    elif text == "/ppku":
        profile = line_bot_api.get_group_member_profile(
            event.source.group_id, event.source.user_id)
        url = profile.picture_url
        image_message = ImageSendMessage(original_content_url=url,
                                         preview_image_url=url)
        line_bot_api.reply_message(event.reply_token, image_message)

    elif '/apakah ' in text:
        rep = text.replace("/apakah ", "")
        txt = [
            "Ya", "Tidak", "Bisa Jadi", "Mungkin", "Hoax", "Coba tanya lagi"
        ]

        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=random.choice(txt)))

    elif '/gambar' in text:
        separate = text.split(" ")
        search = text.replace(separate[0] + " ", "")
        r = requests.get(
            "http://rahandiapi.herokuapp.com/imageapi?key=betakey&q={}".format(
                search))
        data = r.text
        data = json.loads(data)

        if data["result"] != []:
            items = data["result"]
            path = random.choice(items)
            a = items.index(path)
            b = len(items)

        image_message = ImageSendMessage(original_content_url=path,
                                         preview_image_url=path)

        line_bot_api.reply_message(event.reply_token, image_message)

    elif '/zodiak ' in text:
        tanggal = text.replace("/zodiak ", "")
        r = requests.get(
            'https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=siapa&tanggal='
            + tanggal)
        data = r.text
        data = json.loads(data)
        lahir = data["data"]["lahir"]
        usia = data["data"]["usia"]
        ultah = data["data"]["ultah"]
        zodiak = data["data"]["zodiak"]

        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="== I N F O R M A S I ==\n" +
                            "Date Of Birth : " + lahir + "\nAge : " + usia +
                            "\nUltah : " + ultah + "\nZodiak : " + zodiak +
                            "\n== I N F O R M A S I =="))

    elif '/lokasi' in text:
        separate = text.split(" ")
        search = text.replace(separate[0] + " ", "")
        req = requests.get("https://time.siswadi.com/pray/{}".format(search))
        data = req.text
        data = json.loads(data)
        add = data['location']['address']
        lat = data['location']['latitude']
        lon = data['location']['longitude']

        location_message = LocationSendMessage(title='Lokasi',
                                               address=add,
                                               latitude=lat,
                                               longitude=lon)

        line_bot_api.reply_message(event.reply_token, location_message)

    if 'meet?' in text:
        sticker_message = StickerSendMessage(package_id='1', sticker_id='1')

        line_bot_api.reply_message(event.reply_token, sticker_message)

    elif '/hitung' in text:
        separate = text.split(" ")
        search = text.replace(separate[0] + " ", "")
        if search == None:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(
                    text=
                    "Untuk cara menggunakan kalkulator, ketik /hitung 'nominal'\n\nContoh: /hitung (3e+2i)*(2e-3i)\n\nSelamat mencoba (((o(*゚▽゚*)o)))"
                ))
        else:
            with requests.session() as web:
                web.headers[
                    "user-agent"] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
            r = web.get("http://api.mathjs.org/v4/?expr={}".format(
                urllib2.quote(search)))
            data = r.text
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=str(data)))

    elif text == '/sp':
        start = time.time()
        elapsed_time = time.time() - start
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=format(elapsed_time)))

    elif '/cariyoutube ' in text:
        query = text.replace("/cariyoutube ", "")
        with requests.session() as s:
            s.headers['user-agent'] = 'Mozilla/5.0'
            url = 'http://www.youtube.com/results'
            params = {'search_query': query}
            r = s.get(url, params=params)
            soup = BeautifulSoup(r.content, 'html5lib')
            num = 0
            hasil = ""
            for a in soup.select('.yt-lockup-title > a[title]'):
                num += 1
                if '&list=' not in a['href']:
                    hasil += "".join(
                        (a["title"], "\nhttps://www.youtube.com" + a["href"],
                         "\n\n"))
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=hasil))

    elif '/lagu ' in text:
        query = text.replace("/lagu ", "")
        cond = query.split("|")
        search = cond[0]
        result = requests.get(
            "http://api.ntcorp.us/joox/search?q={}".format(search))
        data = result.text
        data = json.loads(data)
        if len(cond) == 1:
            num = 0
            ret_ = "╔══[ Result Music ]"
            for music in data["result"]:
                num += 1
                ret_ += "\n╠ {}. {}".format(num, music["single"])
            ret_ += "\n╚══[ Total {} Music ]".format(len(data["result"]))
            ret_ += "\n\nUntuk Melihat Details Music, silahkan gunakan command /lagu {}|「number」".format(
                search)
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=ret_))
        elif len(cond) == 2:
            num = int(cond[1])
            if num <= len(data["result"]):
                music = data["result"][num - 1]
                result = requests.get(
                    "http://api.ntcorp.us/joox/song_info?sid={}".format(
                        music["sid"]))
                data = result.text
                data = json.loads(data)
                if data["result"] != []:
                    ret_ = "╔══[ Music ]"
                    ret_ += "\n╠ Title : {}".format(data["result"]["song"])
                    ret_ += "\n╠ Album : {}".format(data["result"]["album"])
                    ret_ += "\n╠ Size : {}".format(data["result"]["size"])
                    ret_ += "\n╠ Link : {}".format(data["result"]["mp3"][0])
                    ret_ += "\n╚══[ Finish ]"
                    audio = data["result"]["m4a"][0]
                    image_message = ImageSendMessage(
                        original_content_url=data["result"]["img"],
                        preview_image_url=data["result"]["img"])
                    audio_message = AudioSendMessage(
                        original_content_url=audio, duration=240000)
                    #                   line_bot_api.reply_message(
                    #                       event.reply_token,
                    #                       TextSendMessage(text=ret_))
                    #                   return

                    line_bot_api.reply_message(event.reply_token,
                                               TextSendMessage(text=ret_))
                    return

    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('/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)))
コード例 #27
0
    def _to_channel_message(message):
        """
        Convert Minette Message object to LINE SendMessage object

        Parameters
        ----------
        response : Message
            Response message object

        Returns
        -------
        response : SendMessage
            SendMessage object for LINE Messaging API
        """
        payload = next(
            iter([
                p for p in message.payloads if p.content_type != "quick_reply"
            ]), None)
        quick_reply = next(
            iter([
                p.content for p in message.payloads
                if p.content_type == "quick_reply"
            ]), None)
        if message.type == "text":
            return TextSendMessage(text=message.text, quick_reply=quick_reply)
        elif message.type == "image":
            return ImageSendMessage(original_content_url=payload.url,
                                    preview_image_url=payload.thumb,
                                    quick_reply=quick_reply)
        elif message.type == "audio":
            return AudioSendMessage(original_content_url=payload.url,
                                    duration=payload.content["duration"],
                                    quick_reply=quick_reply)
        elif message.type == "video":
            return VideoSendMessage(original_content_url=payload.url,
                                    preview_image_url=payload.thumb,
                                    quick_reply=quick_reply)
        elif message.type == "location":
            cont = payload.content
            return LocationSendMessage(title=cont["title"],
                                       address=cont["address"],
                                       latitude=cont["latitude"],
                                       longitude=cont["longitude"],
                                       quick_reply=quick_reply)
        elif message.type == "sticker":
            return StickerSendMessage(package_id=payload.content["package_id"],
                                      sticker_id=payload.content["sticker_id"],
                                      quick_reply=quick_reply)
        elif message.type == "imagemap":
            return ImagemapSendMessage(alt_text=message.text,
                                       base_url=payload.url,
                                       base_size=payload.content["base_size"],
                                       actions=payload.content["actions"],
                                       quick_reply=quick_reply)
        elif message.type == "template":
            return TemplateSendMessage(alt_text=message.text,
                                       template=payload.content,
                                       quick_reply=quick_reply)
        elif message.type == "flex":
            return FlexSendMessage(alt_text=message.text,
                                   contents=payload.content,
                                   quick_reply=quick_reply)
        else:
            return None
コード例 #28
0
 def create_message(self):
     return AudioSendMessage(original_content_url=self.content_url,
                             duration=self.duration,
                             quick_reply=self.quick_reply)
コード例 #29
0
ファイル: app.py プロジェクト: x1001000/linebot-pytube
def message_text(event):
    for split in event.message.text.split():
        match = re.search('.*youtu.*', split)
        if match:
            url = match.group(0)
            try:
                yt = YouTube(url)
            except Exception as e:
                print('EXCEPTION:', e)
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(
                        text='You下ube被YouTube已讀。。。\n請換個網址再讓我試試。。。'))
                break
            streams = yt.streams
            video_id = yt.video_id
            print(yt.title)

            # DOWNLOAD mp4
            try:
                if streams.get_highest_resolution():
                    print(streams.get_highest_resolution().download(
                        output_path='static', filename=video_id))
                elif streams.first():
                    print(streams.first().download(output_path='static',
                                                   filename=video_id))
                else:
                    line_bot_api.reply_message(
                        event.reply_token, TextSendMessage(text='抱歉我找不到載點。。。'))
                    break
            except Exception as e:
                print('EXCEPTION:', e)
                line_bot_api.reply_message(event.reply_token,
                                           TextSendMessage(text='抱歉我似乎壞掉了。。。'))
                break

            # DOWNLOAD or EXTRACT m4a
            #video = VideoFileClip('static/YTDL.mp4')
            #audio = video.audio
            #audio.write_audiofile('static/LINE.mp3')
            #video.close()
            #audio.close()
            #text='https://youtube-dl-linebot.herokuapp.com/static/LINE.mp3'
            if streams.get_audio_only():
                print(streams.get_audio_only().download(output_path='static',
                                                        filename=video_id +
                                                        '_m4a'))
                os.system(
                    f'mv static/{video_id}_m4a.mp4 static/{video_id}.m4a')
            else:
                os.system(
                    f'ffmpeg -i static/{video_id}.mp4 -vn -c:a copy static/{video_id}.m4a'
                )

            # LINE mp4 and m4a
            try:
                line_bot_api.reply_message(event.reply_token, [
                    TextSendMessage(text='敬請手刀下載⬇⬇'),
                    VideoSendMessage(
                        original_content_url=
                        f'https://linebot-pytube.herokuapp.com/static/{video_id}.mp4',
                        preview_image_url=yt.thumbnail_url),
                    AudioSendMessage(
                        original_content_url=
                        f'https://linebot-pytube.herokuapp.com/static/{video_id}.m4a',
                        duration=yt.length * 1000)
                ])
            except Exception as e:
                print('EXCEPTION:', e)
                line_bot_api.reply_message(event.reply_token,
                                           TextSendMessage(text='奇怪再試一次。。。'))
            finally:
                break
    else:
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text='說好的YouTube呢。。。'))
コード例 #30
0
ファイル: app.py プロジェクト: rinda18/oalinebot-1
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 Aditmadzs\n"
								"Nice to meet you... \n"
								"source code: https://github.com/Aditmadzs"))
	
	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/Aditmadzs/oalinebot/blob/master/Lang.txt"))
	
	elif text == '/test':
		line_bot_api.reply_message(
				event.reply_token,
				AudioSendMessage(original_content_url='http://commondatastorage.googleapis.com/codeskulptor-assets/week7-brrring.m4a',
									duration=240000))
	
	elif text == '/manga':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("mangaku.in"))
	
	elif text == '/ig':
		line_bot_api.reply_message(
				event.reply_token,
				TextSendMessage("https://www.instagram.com/aditmadzs1"))
	
	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)))