Example #1
0
def handle_join(event):
    line_bot_api.reply_message(event.reply_token, [
        TextSendMessage(
            text="Terima Kasih telah memasukkan " + namaBot.capitalize() +
            " dalam chat ini ;D\nJika kalian membutuhkan bantuanku, panggil saja :)"
        ),
        TextSendMessage(
            text='Agar dapat menggunakan fitur-fitur yang ada, harus add ' +
            namaBot.capitalize() + ' sebagai teman dulu yak ;D',
            quick_reply=QuickReply(items=[
                QuickReplyButton(action=MessageAction(
                    label=namaBot.capitalize(), text=namaBot.capitalize()))
            ]))
    ])
    if isinstance(event.source, SourceGroup):
        ruang = event.source.sender_id
    elif isinstance(event.source, SourceRoom):
        ruang = event.source.room_id

    db.child(event.source.type).child(ruang).set(time.time())
    try:
        jumlah = db.child(event.source.type).get().val()["total"]
        db.child(event.source.type).child("total").update(jumlah + 1)
    except:
        db.child(event.source.type).child("total").set(1)
Example #2
0
def handle_follow(event):
    line_bot_api.reply_message(event.reply_token, [
        TextSendMessage(
            text='Terima kasih telah menambahkan ' + namaBot +
            ' sebagai teman ;D\n' + namaBot +
            ' akan membantu kamu ketika kamu ingin bermain, cek film bioskop, download film, dan download youtube ;)\nKak '
            + line_bot_api.get_profile(event.source.user_id).display_name +
            ' bisa mematikan notifikasi jika ' + namaBot + ' mengganggu :('),
        TextSendMessage(text='Panggil saja namaku jika kamu ingin ditemani ;D',
                        quick_reply=QuickReply(items=[
                            QuickReplyButton(action=MessageAction(
                                label='Panggil', text=namaBot.capitalize()))
                        ]))
    ])
    data = {
        'nama': line_bot_api.get_profile(event.source.user_id).display_name,
        'foto': line_bot_api.get_profile(event.source.user_id).picture_url,
        'status':
        line_bot_api.get_profile(event.source.user_id).status_message,
        'waktu_add': time.time()
    }
    db.child("pengguna").child(event.source.user_id).set(data)
    try:
        jumlah = db.child("pengguna").get().val()["total"]
        db.child("pengguna").child("total").update(jumlah + 1)
    except:
        db.child("pengguna").child("total").set(1)
Example #3
0
        def stimey(total_seconds):
            try:

                MINUTE = 60
                HOUR = MINUTE * 60
                DAY = HOUR * 24

                days = int(total_seconds / DAY)
                hours = int((total_seconds % DAY) / HOUR)
                minutes = int((total_seconds % HOUR) / MINUTE)
                seconds = int(total_seconds % MINUTE)

                string = list()
                if days > 0:
                    string.append(str(days) + " hari")
                if hours > 0:
                    string.append(str(hours) + " jam")
                if minutes > 0:
                    string.append(str(minutes) + " menit")
                if seconds > 0:
                    string.append(str(seconds) + " detik")
                else:
                    if len(string) == 0: string.append("0 detik")
                if len(string) > 1:
                    return ", ".join(string[:-1]) + ", dan " + string[-1]
                else:
                    return ", ".join(string)

            except Exception as e:
                try:
                    et, ev, tb = sys.exc_info()
                    lineno = tb.tb_lineno
                    fn = tb.tb_frame.f_code.co_filename
                    if sender != owner:
                        line_bot_api.reply_message(event.reply_token, [
                            TextSendMessage(text='Oopps.. ' +
                                            namaBot.capitalize() +
                                            ' ada kesalahan kak :('),
                            TextSendMessage(
                                text=
                                'Tapi tenang kak, laporan kesalahan ini terkirim ke owner untuk diperbaiki ;D'
                            )
                        ])
                    line_bot_api.push_message(
                        owner,
                        TextSendMessage(
                            text="[Expectation Failed] %s Line %i - %s" %
                            (fn, lineno, str(e))))
                except:
                    line_bot_api.push_message(
                        owner,
                        TextSendMessage(
                            text="Undescribeable error detected!!"))
Example #4
0
def handle_postback(event):
	if isinstance(event.source, SourceGroup):
		kirim = event.source.sender_id
	elif isinstance(event.source, SourceRoom):
		kirim = event.source.room_id
	else:
		kirim = event.source.user_id
	
	sender = event.source.user_id
	
	try:
		if event.postback.data[0] == '/':
			data = event.postback.data[1:].split(" ",1)
			if len(data) > 1:
				cmd, args = data[0].lower(), data[1]
			else:
				cmd, args = data[0].lower(), ""

			if cmd == "main":
				pesan = TemplateSendMessage(
					alt_text='Kamu yakin?',
					template=ConfirmTemplate(
						text='Kamu akan diberikan beberapa soal yang berhubungan dengan film. Siapkah kamu menjawabnya?',
						actions=[
							PostbackAction(
								label='Siap',
								text='Siapp, siapa takut?',
								data='/quiz ready'
							),
							PostbackAction(
								label='Tidak',
								text='Belum, saya masih gatau apa-apa tentang film T_T',
								data='/quiz not ready'
							)
						]
					)
				)
				line_bot_api.reply_message(event.reply_token, pesan)

			elif cmd == 'nyerah':
				if kirim in playah:
					if sender in playah[kirim]["pemain"]:
						if sender in kebenaran[kirim]["nyerah"]:return
						if playah[kirim]["status"] == "mulai":
							kebenaran[kirim]["nyerah"].append(sender)
							line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Kak '+panggil(sender)+' menyerah dan tidak dapat melanjutkan permainan :('))
				else:
					try:
						nomor, tanya, waktu = soal[kirim]
					except:
						line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Kak '+panggil(sender)+' tidak dalam permainan ._.'))
						return
					data = qz.child("Quiz").child("Skor Pribadi").child(sender).get().val()
					nama = line_bot_api.get_profile(sender).display_name
					poin = data["poin"]
					try:
						gambar = line_bot_api.get_profile(sender).picture_url
					except:
						gambar = ""
					line_bot_api.reply_message(event.reply_token, hasil_akhir(nama, nomor-1, poin, gambar))
					del soal[kirim]
					del selesai[kirim]
	
			elif cmd == 'quiz':
				if args == 'ready':
					if event.source.type == 'user':
						try:
							data = qz.child("Quiz").child("Skor Pribadi").child(sender).get().val()
							poin = data["poin"]
						except:
							data = {"poin":0,"waktu":time.time()}
							qz.child("Quiz").child("Skor Pribadi").child(sender).set(data)
						pertanyaan = qz.child("Quiz").child("Pilihan").get().val()
						tanya = random.choice([i for i in pertanyaan])
						pilihan = [i for i in pertanyaan[tanya]["Jawaban"]]
						film = pertanyaan[tanya]["Film"]
						try:
							gambar = pertanyaan[tanya]["Gambar"]
						except:
							gambar = ""
						nomor = 1
						soal.update({kirim:[nomor, tanya, time.time()]})
						selesai.update({kirim:[]})
						selesai[kirim].append(tanya)
						line_bot_api.reply_message(event.reply_token, film_quiz("Pertanyaan "+str(nomor)+"/10", tanya, film, pilihan, gambar))
					else:
						line_bot_api.reply_message(event.reply_token, pemain(aturan))
						playah.update({kirim:{"status":"pending","pemain":[]}})
						t = Timer(60, cek_pemain, [kirim])
						t.start()
				else:
					line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Kabarin kalau udah siap ya kak ;D'))
			
			elif cmd == 'join':
				durasi = time.time() - float(args)
				try:
					status = playah[kirim]["status"]
				except:
					line_bot_api.reply_message(event.reply_token, mulai_permainan())
					return
				if sender in playah[kirim]["pemain"]:
					line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Kak '+panggil(sender)+' sudah memasuki permainan ._.'))
					return
				if status == 'pending':
					if durasi < 30*60: #30 menit
						playah[kirim]["pemain"].append(sender)
						try:
							main = qz.child("Quiz").child("Skor").child(kirim).child(sender).get().val()
							poin = main["poin"]
						except:
							data = {"poin":0,"waktu":time.time()}
							qz.child("Quiz").child("Skor").child(kirim).child(sender).set(data)
						line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Kak '+panggil(sender)+' telah bergabung ;D'))
						if len(playah[kirim]["pemain"]) == 5:
							line_bot_api.push_message(kirim, [
								TextSendMessage(text='5 pemain telah terkumpul ;D'), 
								TextSendMessage(text='Kalian bisa menunggu atau langsung memulai permainan'), 
								TextSendMessage(text='Ketik /mulai jika ingin memulai permainan ;)')
								]
							)
					else:
						line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Waktu untuk bergabung sudah habis kak '+panggil(sender)+' :('))
				else:
					line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Kak '+panggil(sender)+' tidak dapat bergabung karena permainan sedang berlangsung ;)'))

			elif cmd == 'jawab':
				if kirim in soal:
					nomor, tanya, waktu = soal[kirim]
					bertanya = qz.child("Quiz").child("Pilihan").get().val()
					bertanya = bertanya[tanya]
					try:
						menjawab = bertanya["Jawaban"][args]
					except:
						line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Tidak ada pilihan yang kak '+panggil(sender)+' pilih di soal ini :('))
						return
					if event.source.type == 'user':
						if menjawab == 'Benar':
							data = qz.child("Quiz").child("Skor Pribadi").child(sender).get().val()
							poin = data["poin"] + 1
							qz.child("Quiz").child("Skor Pribadi").child(sender).set({"poin":poin,"waktu":time.time()})
							pertanyaan = qz.child("Quiz").child("Pilihan").get().val()
							tanya = random.choice([i for i in pertanyaan])
							while tanya in selesai[kirim]:
								tanya = random.choice([i for i in pertanyaan])
							selesai[kirim].append(tanya)
							pilihan = [i for i in pertanyaan[tanya]["Jawaban"]]
							film = pertanyaan[tanya]["Film"]
							try:
								gambar = pertanyaan[tanya]["Gambar"]
							except:
								gambar = ""
							if nomor < 10:
								nomor = nomor + 1
								soal.update({kirim:[nomor, tanya, time.time()]})
								line_bot_api.reply_message(event.reply_token, [
									TextSendMessage(text='Kak '+panggil(sender)+' benar ;D'), 
									film_quiz("Pertanyaan "+str(nomor)+"/10", tanya, film, pilihan, gambar)
									]
								)
							else:
								data = qz.child("Quiz").child("Skor Pribadi").get().val()
								nama = line_bot_api.get_profile(sender).display_name
								poin = data[sender]["poin"]
								skorlist = {}
								for p in data:
									skornya = data[p]["poin"]
									waktu = data[p]["waktu"]
									skorlist.update({p:[skornya, waktu]})
								line_bot_api.reply_message(event.reply_token, hasil_akhir(nama, nomor, poin, skorlist))
								del soal[kirim]
								del selesai[kirim]
						else:
							data = qz.child("Quiz").child("Skor Pribadi").child(sender).get().val()
							nama = line_bot_api.get_profile(sender).display_name
							poin = data["poin"]
							try:
								gambar = line_bot_api.get_profile(sender).picture_url
							except:
								gambar = ""
							line_bot_api.reply_message(event.reply_token, [
								TextSendMessage(text='Kak '+panggil(sender)+' salah :('), 
								hasil_akhir(nama, nomor-1, poin, gambar)
								]
							)
							del soal[kirim]
							del selesai[kirim]
					else:
						main = qz.child("Quiz").child("Skor").child(kirim).child(sender).get().val()
						try:
							poin = main["poin"]
						except:
							poin = 0
						if sender not in playah[kirim]["pemain"]:return
						benar = kebenaran[kirim]["benar"]
						salah = kebenaran[kirim]["salah"]
						nyerah = kebenaran[kirim]["nyerah"]
						if sender in benar or sender in salah or sender in nyerah:return
						if menjawab == 'Benar':
							if sender not in benar or sender not in salah or sender not in nyerah:
								if len(kebenaran[kirim]["benar"]) == 0:
									poin += 5
									kebenaran[kirim]["benar"].append(sender)
									line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Kak '+panggil(sender)+' benar dan mendapatkan 5 poin. Total: '+str(poin)+' poin ;D'))
								elif len(kebenaran[kirim]["benar"]) == 1:
									poin += 3
									kebenaran[kirim]["benar"].append(sender)
									line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Kak '+panggil(sender)+' benar dan mendapatkan 3 poin. Total: '+str(poin)+' poin ;D'))
								elif len(kebenaran[kirim]["benar"]) == 2:
									poin += 1
									kebenaran[kirim]["benar"].append(sender)
									line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Kak '+panggil(sender)+' benar dan mendapatkan 1 poin. Total: '+str(poin)+' poin ;D'))
								else:
									kebenaran[kirim]["benar"].append(sender)
									line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Kak '+panggil(sender)+' benar ;)'))
						else:
							if (sender not in kebenaran[kirim]["benar"]) or (sender not in kebenaran[kirim]["salah"]) or (sender not in kebenaran[kirim]["nyerah"]):
								poin = poin - 1
								kebenaran[kirim]["salah"].append(sender)
								line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Kak '+panggil(sender)+' salah, dikurangi 1 poin. :(\nTotal: '+str(poin)+' poin.'))
						
						if nomor < 10:
							benar = len(kebenaran[kirim]["benar"])
							salah = len(kebenaran[kirim]["salah"])
							nyerah = len(kebenaran[kirim]["nyerah"])
							if (benar + salah + nyerah) == len(playah[kirim]["pemain"]):
								pertanyaan = qz.child("Quiz").child("Pilihan").get().val()
								tanya = random.choice([i for i in pertanyaan])
								pilihan = [i for i in pertanyaan[tanya]["Jawaban"]]
								film = pertanyaan[tanya]["Film"]
								try:
									gambar = pertanyaan[tanya]["Gambar"]
								except:
									gambar = ""
								nomor = nomor + 1
								soal.update({kirim:[nomor, tanya, time.time()]})
								line_bot_api.push_message(kirim, film_quiz("Pertanyaan "+str(nomor)+"/10", tanya, film, pilihan, gambar))
								nyerah = [i for i in kebenaran[kirim]["nyerah"]]
								kebenaran.update({kirim:{"benar":[],"salah":[],"nyerah":nyerah}})
								t = Timer(60, waktu_main, (nomor, kirim))
								t.start()
						else:
							skornya = qz.child("Quiz").child("Skor").child(kirim).get().val()
							skor_trakhir = {}
							for u in skornya:
								total_skor = skornya[u]["poin"] + poin
								skor_trakhir.update({u:total_skor})
							line_bot_api.reply_message(event.reply_token, skor_akhir(skor_trakhir))
							del playah[kirim]
							del kebenaran[kirim]
						data = {"poin":poin,"waktu":time.time()}
						qz.child("Quiz").child("Skor").child(kirim).child(sender).set(data)
	
	except Exception as e:
		try:
			et, ev, tb = sys.exc_info()
			lineno = tb.tb_lineno
			fn = tb.tb_frame.f_code.co_filename
			if sender != owner:
				line_bot_api.reply_message(event.reply_token, [
					TextSendMessage(text='Oopps.. '+namaBot.capitalize()+' ada kesalahan kak :('),
					TextSendMessage(text='Tapi tenang kak, laporan kesalahan ini terkirim ke owner untuk diperbaiki ;D')
					]
				)
			line_bot_api.push_message(owner, TextSendMessage(text="[Expectation Failed] %s Line %i - %s"% (fn, lineno, str(e))))
		except:
			line_bot_api.push_message(owner, TextSendMessage(text="Undescribeable error detected!!"))
Example #5
0
def handle_message(event):
    if isinstance(event.source, SourceGroup):
        kirim = event.source.sender_id
    elif isinstance(event.source, SourceRoom):
        kirim = event.source.room_id
    else:
        kirim = event.source.user_id

    sender = event.source.user_id
    text = event.message.text

    try:

        if sender in perintah:
            komando, waktu = perintah[sender]

            if komando == 'Cari film imdb':
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(text='Sebentar kak ' + panggil(sender) +
                                    ', ' + namaBot.capitalize() +
                                    ' sedang menyiapkan hasil pencarian ;)'))
                pencarian.update({text: []})
                for i in search_movie_imdb(text):
                    pencarian[text].append(i)
                hasil = pencarian[text]
                if len(hasil) > 10:
                    hasil = hasil[:9]
                    kirimin = list()
                    for r in hasil:
                        kirimin.append(r)
                    kirimin.append(
                        BubbleContainer(body=BoxComponent(
                            layout='vertical',
                            spacing='sm',
                            contents=[
                                ButtonComponent(action=PostbackAction(
                                    label='Selanjutnya',
                                    text='Selain itu?',
                                    data='/imdb ' + text.replace(' ', '+') +
                                    ' 9'),
                                                flex=1,
                                                gravity='center')
                            ])))
                    pesan = FlexSendMessage(
                        alt_text='Hasil pencarian: ' + text,
                        contents=CarouselContainer(contents=kirimin))
                else:
                    pesan = FlexSendMessage(
                        alt_text='Hasil pencarian: ' + text,
                        contents=CarouselContainer(contents=hasil))
                line_bot_api.push_message(sender, pesan)
                del perintah[sender]

        if text == 'Cek film dong':
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='Kak ' + panggil(sender) +
                                ' mau cari film apa?'))
            perintah.update({sender: ['Cari film imdb', time.time()]})

    except Exception as e:
        try:
            et, ev, tb = sys.exc_info()
            lineno = tb.tb_lineno
            fn = tb.tb_frame.f_code.co_filename
            if sender != owner:
                line_bot_api.reply_message(event.reply_token, [
                    TextSendMessage(text='Oopps.. ' + namaBot.capitalize() +
                                    ' ada kesalahan kak :('),
                    TextSendMessage(
                        text=
                        'Tapi tenang kak, laporan kesalahan ini terkirim ke owner untuk diperbaiki ;D'
                    )
                ])
            line_bot_api.push_message(
                owner,
                TextSendMessage(text="[Expectation Failed] %s Line %i - %s" %
                                (fn, lineno, str(e))))
        except:
            line_bot_api.push_message(
                owner, TextSendMessage(text="Undescribeable error detected!!"))
Example #6
0
def handle_postback(event):
    if isinstance(event.source, SourceGroup):
        kirim = event.source.sender_id
    elif isinstance(event.source, SourceRoom):
        kirim = event.source.room_id
    else:
        kirim = event.source.user_id
    sender = event.source.user_id
    try:

        if event.postback.data[0] == '/':
            data = event.postback.data[1:].split(" ", 1)
            if len(data) > 1:
                cmd, args = data[0].lower(), data[1]
            else:
                cmd, args = data[0].lower(), ""

            if cmd == 'imdb':
                cari, nomor = args.split(" ")
                cari = cari.replace('+', ' ')
                batas = int(nomor) + 10
                hasil = pencarian[cari]
                jhasil = len(hasil) - int(nomor)
                res = list()
                if jhasil > 10:
                    for i in hasil[int(nomor) + 1:batas]:
                        res.append(i)
                    res.append(
                        BubbleContainer(body=BoxComponent(
                            layout='vertical',
                            spacing='sm',
                            contents=[
                                ButtonComponent(action=PostbackAction(
                                    label='Selanjutnya',
                                    text='Selain itu?',
                                    data='/imdb ' + cari.replace(' ', '+') +
                                    ' ' + str(batas)),
                                                flex=1,
                                                gravity='center')
                            ])))
                    hasil = res
                else:
                    hasil = hasil[int(nomor) + 1:]

                pesan = FlexSendMessage(
                    alt_text='Hasil pencarian: ' + cari,
                    contents=CarouselContainer(contents=hasil))
                line_bot_api.reply_message(event.reply_token, pesan)

    except Exception as e:
        try:
            et, ev, tb = sys.exc_info()
            lineno = tb.tb_lineno
            fn = tb.tb_frame.f_code.co_filename
            if sender != owner:
                line_bot_api.reply_message(event.reply_token, [
                    TextSendMessage(text='Oopps.. ' + namaBot.capitalize() +
                                    ' ada kesalahan kak :('),
                    TextSendMessage(
                        text=
                        'Tapi tenang kak, laporan kesalahan ini terkirim ke owner untuk diperbaiki ;D'
                    )
                ])
            line_bot_api.push_message(
                owner,
                TextSendMessage(text="[Expectation Failed] %s Line %i - %s" %
                                (fn, lineno, str(e))))
        except:
            line_bot_api.push_message(
                owner, TextSendMessage(text="Undescribeable error detected!!"))
Example #7
0
def handle_postback(event):
    if isinstance(event.source, SourceGroup):
        kirim = event.source.sender_id
    elif isinstance(event.source, SourceRoom):
        kirim = event.source.room_id
    else:
        kirim = event.source.user_id

    try:

        if event.postback.data[0] == '/':
            data = event.postback.data[1:].split(" ", 1)
            if len(data) > 1:
                cmd, args = data[0].lower(), data[1]
            else:
                cmd, args = data[0].lower(), ""

            if cmd == 'cek_bioskop':
                line_bot_api.reply_message(event.reply_token, tayang(args))

            elif cmd == 'cek_film_bioskop':
                line_bot_api.reply_message(event.reply_token, info_film(args))

            elif cmd == 'reminder':
                jamku, judul, bioskop, tanggalku = args.split(" ")
                judul = judul.replace("+", " ")
                bioskop = bioskop.replace("+", " ")
                jam, menit = jamku.split(":")
                tgl, bln, thn = tanggalku.split("-")

                x = datetime.today()
                if int(thn) <= x.year:
                    if int(bln) <= x.month:
                        if int(tgl) <= x.day:
                            if int(jam) <= x.hour:
                                if int(menit) <= x.minute:
                                    line_bot_api.reply_message(
                                        event.reply_token,
                                        TextSendMessage(
                                            text='Waktunya sudah lewat kak :(')
                                    )
                                    return

                if x.hour < int(jam):
                    ingat_jam = int(jam)
                    ingat_menit = int(menit) - 30
                    if ingat_menit < 0:
                        ingat_jam = int(jam) - 1
                        ingat_menit = abs(ingat_menit)
                    r = x.replace(hour=x.hour + (ingat_jam - x.hour),
                                  minute=x.minute + (ingat_menit - x.minute))
                    delta_b = r - x
                    detik = delta_b.seconds + 1
                    b = Timer(detik, ingetin30,
                              (event.source.user_id, jamku, judul, bioskop))
                    b.start()

                y = x.replace(hour=x.hour + (int(jam) - x.hour),
                              minute=x.minute + (int(menit) - x.minute))
                delta_t = y - x
                secs = delta_t.seconds + 1
                t = Timer(secs, ingetin,
                          (event.source.user_id, jamku, judul, bioskop))
                t.start()
                line_bot_api.reply_message(event.reply_token,
                                           TextSendMessage('Okee kak ;D'))
                data = {'tanggal': tanggalku, 'jam': jamku, 'ulang': False}
                db.child("pengguna").child(
                    event.source.user_id).child("tambahan").child(
                        "pengingat").child('Nonton ' + judul.capitalize() +
                                           ' di ' + bioskop).set(data)

    except Exception as e:
        try:
            et, ev, tb = sys.exc_info()
            lineno = tb.tb_lineno
            fn = tb.tb_frame.f_code.co_filename
            if sender != owner:
                line_bot_api.reply_message(event.reply_token, [
                    TextSendMessage(text='Oopps.. ' + namaBot.capitalize() +
                                    ' ada kesalahan kak :('),
                    TextSendMessage(
                        text=
                        'Tapi tenang kak, laporan kesalahan ini terkirim ke owner untuk diperbaiki ;D'
                    )
                ])
            line_bot_api.push_message(
                owner,
                TextSendMessage(text="[Expectation Failed] %s Line %i - %s" %
                                (fn, lineno, str(e))))
        except:
            line_bot_api.push_message(
                owner, TextSendMessage(text="Undescribeable error detected!!"))
Example #8
0
def handle_message(event):
    try:

        if isinstance(event.source, SourceGroup):
            kirim = event.source.sender_id
        elif isinstance(event.source, SourceRoom):
            kirim = event.source.room_id
        else:
            kirim = event.source.user_id

        sender = event.source.user_id

        text = event.message.text

        # MENGAMBIL INPUTAN PENGGUNA
        if sender in perintah:
            komando, waktu = perintah[sender]

            # MENAMPILKAN BIOSKOP DI KOTA
            if komando == "Cek bioskop":
                try:
                    cinema = cinema21.Cinema21()
                    kota = text.lower()
                    for y in cinema.cities()[0]:
                        if kota == y[1].lower():
                            kode = y[0]
                    terdekat = cinema.city_cinemas(kode)
                    premiere = terdekat[0]
                    xxi = terdekat[1]
                    imax = terdekat[2]
                    res = list()

                    if len(premiere) > 0:
                        for film in premiere:
                            bioskop = film[4]
                            kode = film[0]
                            keterangan = film[6].replace('\r', '')
                            res.append(
                                BubbleContainer(
                                    header=BoxComponent(
                                        layout='vertical',
                                        contents=[
                                            TextComponent(text=bioskop,
                                                          size='lg',
                                                          align='center',
                                                          weight='bold',
                                                          color='#f4f4f4',
                                                          wrap=True)
                                        ]),
                                    hero=ImageComponent(
                                        url=
                                        'https://i.postimg.cc/28r8Vsnt/premiere.png',
                                        size='full',
                                        aspect_ratio='3:1',
                                        aspect_mode='cover'),
                                    body=BoxComponent(layout='vertical',
                                                      contents=[
                                                          TextComponent(
                                                              text=keterangan,
                                                              margin='lg',
                                                              size='sm',
                                                              align='center',
                                                              color='#e4e4e4',
                                                              wrap=True)
                                                      ]),
                                    footer=BoxComponent(
                                        layout='horizontal',
                                        contents=[
                                            ButtonComponent(
                                                action=PostbackAction(
                                                    text='Mau liat film di ' +
                                                    bioskop.capitalize() +
                                                    ' dong',
                                                    label='Lihat Film',
                                                    data='/cek_bioskop ' +
                                                    kode),
                                                color='#860000',
                                                style='primary')
                                        ]),
                                    styles=BubbleStyle(
                                        header=BlockStyle(
                                            background_color='#000000'),
                                        body=BlockStyle(
                                            background_color='#000000'),
                                        footer=BlockStyle(
                                            background_color='#000000'))))

                    if len(xxi) > 0:
                        for film in xxi:
                            bioskop = film[4]
                            kode = film[0]
                            keterangan = film[6].replace('\r', '')
                            res.append(
                                BubbleContainer(
                                    header=BoxComponent(
                                        layout='vertical',
                                        contents=[
                                            TextComponent(text=bioskop,
                                                          size='lg',
                                                          align='center',
                                                          weight='bold',
                                                          color='#f4f4f4',
                                                          wrap=True)
                                        ]),
                                    hero=ImageComponent(
                                        url=
                                        'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTiTQHHaE05tNJ7cNhMbE6DmB0EXBHe0HnbRULKt0YpG9-uc5v5',
                                        size='full',
                                        aspect_ratio='3:1',
                                        aspect_mode='cover'),
                                    body=BoxComponent(layout='vertical',
                                                      contents=[
                                                          TextComponent(
                                                              text=keterangan,
                                                              margin='lg',
                                                              size='sm',
                                                              align='center',
                                                              color='#e4e4e4',
                                                              wrap=True)
                                                      ]),
                                    footer=BoxComponent(
                                        layout='horizontal',
                                        contents=[
                                            ButtonComponent(
                                                action=PostbackAction(
                                                    text='Mau liat film di ' +
                                                    bioskop.capitalize() +
                                                    ' dong',
                                                    label='Lihat Film',
                                                    data='/cek_bioskop ' +
                                                    kode),
                                                color='#860000',
                                                style='primary')
                                        ]),
                                    styles=BubbleStyle(
                                        header=BlockStyle(
                                            background_color='#000000'),
                                        body=BlockStyle(
                                            background_color='#000000'),
                                        footer=BlockStyle(
                                            background_color='#000000'))))
                    if len(imax) > 0:
                        for film in imax:
                            bioskop = film[4]
                            kode = film[0]
                            keterangan = film[6].replace('\r', '')
                            res.append(
                                BubbleContainer(
                                    header=BoxComponent(
                                        layout='vertical',
                                        contents=[
                                            TextComponent(text=bioskop,
                                                          size='lg',
                                                          align='center',
                                                          weight='bold',
                                                          color='#f4f4f4',
                                                          wrap=True)
                                        ]),
                                    hero=ImageComponent(
                                        url=
                                        'https://i.postimg.cc/nLY3cQxg/imax.png',
                                        size='full',
                                        aspect_ratio='3:1',
                                        aspect_mode='cover'),
                                    body=BoxComponent(layout='vertical',
                                                      contents=[
                                                          TextComponent(
                                                              text=keterangan,
                                                              margin='lg',
                                                              size='sm',
                                                              align='center',
                                                              color='#e4e4e4',
                                                              wrap=True)
                                                      ]),
                                    footer=BoxComponent(
                                        layout='horizontal',
                                        contents=[
                                            ButtonComponent(
                                                action=PostbackAction(
                                                    text='Mau liat film di ' +
                                                    bioskop.capitalize() +
                                                    ' dong',
                                                    label='Lihat Film',
                                                    data='/cek_bioskop ' +
                                                    kode),
                                                color='#860000',
                                                style='primary')
                                        ]),
                                    styles=BubbleStyle(
                                        header=BlockStyle(
                                            background_color='#000000'),
                                        body=BlockStyle(
                                            background_color='#000000'),
                                        footer=BlockStyle(
                                            background_color='#000000'))))
                    hasil = FlexSendMessage(
                        alt_text="Bioskop di " + text,
                        contents=CarouselContainer(contents=res))
                    line_bot_api.reply_message(event.reply_token, hasil)
                except Exception as e:
                    try:
                        et, ev, tb = sys.exc_info()
                        lineno = tb.tb_lineno
                        fn = tb.tb_frame.f_code.co_filename
                        if sender != owner:
                            line_bot_api.reply_message(event.reply_token, [
                                TextSendMessage(text='Oopps.. ' +
                                                namaBot.capitalize() +
                                                ' ada kesalahan kak :('),
                                TextSendMessage(
                                    text=
                                    'Tapi tenang kak, laporan kesalahan ini terkirim ke owner untuk diperbaiki ;D'
                                )
                            ])
                        line_bot_api.push_message(
                            owner,
                            TextSendMessage(
                                text="[Expectation Failed] %s Line %i - %s" %
                                (fn, lineno, str(e))))
                    except:
                        line_bot_api.push_message(
                            owner,
                            TextSendMessage(
                                text="Undescribeable error detected!!"))
                del perintah[sender]

        # CHAT BIASA
        if text == "Cek film bioskop":
            data = db.child("pengguna").get().val()[sender]
            try:
                lokasi = data["tambahan"]["lokasi"]
                lat = lokasi["latitude"]
                lng = lokasi["longitude"]
                line_bot_api.push_message(kirim, bioskop_terdekat(lat, lng))
            except:
                perintah.update(
                    {sender: ['Cek bioskop terdekat',
                              time.time()]})
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(text="Share lokasi dulu kak " +
                                    panggil(sender) +
                                    ", nanti kucarikan bioskop terdekat ;)",
                                    quick_reply=QuickReply(items=[
                                        QuickReplyButton(action=LocationAction(
                                            label='Share lokasi'))
                                    ])))

    except Exception as e:
        try:
            et, ev, tb = sys.exc_info()
            lineno = tb.tb_lineno
            fn = tb.tb_frame.f_code.co_filename
            if sender != owner:
                line_bot_api.reply_message(event.reply_token, [
                    TextSendMessage(text='Oopps.. ' + namaBot.capitalize() +
                                    ' ada kesalahan kak :('),
                    TextSendMessage(
                        text=
                        'Tapi tenang kak, laporan kesalahan ini terkirim ke owner untuk diperbaiki ;D'
                    )
                ])
            line_bot_api.push_message(
                owner,
                TextSendMessage(text="[Expectation Failed] %s Line %i - %s" %
                                (fn, lineno, str(e))))
        except:
            line_bot_api.push_message(
                owner, TextSendMessage(text="Undescribeable error detected!!"))
Example #9
0
def handle_location_message(event):
    if isinstance(event.source, SourceGroup):
        kirim = event.source.sender_id
    elif isinstance(event.source, SourceRoom):
        kirim = event.source.room_id
    else:
        kirim = event.source.user_id

    sender = event.source.user_id

    # MENGAMBIL INPUTAN PENGGUNA
    if sender in perintah:
        komando, waktu = perintah[sender]

        # MENAMPILKAN BIOSKOP TERDEKAT
        if komando == "Cek bioskop terdekat":
            try:
                line_bot_api.reply_message(
                    event.reply_token,
                    bioskop_terdekat(event.message.latitude,
                                     event.message.longitude))
                data = {
                    'nama_lokasi': event.message.address,
                    'latitude': event.message.latitude,
                    'longitude': event.message.longitude
                }
                db.child("pengguna").child(sender).child("tambahan").child(
                    "lokasi").set(data)
                del perintah[sender]
            except:
                try:
                    balasCepat = list()
                    cinema = cinema21.Cinema21()
                    for y in cinema.cities()[0]:
                        balasCepat.append(
                            QuickReplyButton(
                                action=MessageAction(label=y[1].capitalize(),
                                                     text=y[1].capitalize())))
                    line_bot_api.reply_message(event.reply_token, [
                        TextSendMessage(
                            text=namaBot.capitalize() +
                            ' tidak dapat menemukan bioskop terdekat kak :('),
                        TextSendMessage(
                            text='Kakak sekarang di kota apa?',
                            quick_reply=QuickReply(items=balasCepat[:13]))
                    ])
                    del perintah[sender]
                    perintah.update({sender: ["Cek bioskop", time.time()]})
                except Exception as e:
                    try:
                        et, ev, tb = sys.exc_info()
                        lineno = tb.tb_lineno
                        fn = tb.tb_frame.f_code.co_filename
                        if sender != owner:
                            line_bot_api.reply_message(event.reply_token, [
                                TextSendMessage(text='Oopps.. ' +
                                                namaBot.capitalize() +
                                                ' ada kesalahan kak :('),
                                TextSendMessage(
                                    text=
                                    'Tapi tenang kak, laporan kesalahan ini terkirim ke owner untuk diperbaiki ;D'
                                )
                            ])
                        line_bot_api.push_message(
                            owner,
                            TextSendMessage(
                                text="[Expectation Failed] %s Line %i - %s" %
                                (fn, lineno, str(e))))
                    except:
                        line_bot_api.push_message(
                            owner,
                            TextSendMessage(
                                text="Undescribeable error detected!!"))
Example #10
0
def handle_postback(event):
    if isinstance(event.source, SourceGroup):
        kirim = event.source.sender_id
    elif isinstance(event.source, SourceRoom):
        kirim = event.source.room_id
    else:
        kirim = event.source.user_id

    try:

        if event.postback.data == 'test':
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text="Test berhasil"))

        if event.postback.data[0] == '/':
            data = event.postback.data[1:].split(" ", 1)
            if len(data) > 1:
                cmd, args = data[0].lower(), data[1]
            else:
                cmd, args = data[0].lower(), ""

            if cmd == 'ytdownload':
                thumbnails, link = args.split(' ')
                download_ini = download(thumbnails, link)
                line_bot_api.reply_message(event.reply_token, download_ini)

            elif cmd == 'yt':
                data = args.split(" ", 1)
                if len(data) > 1:
                    mau, cari = data[0], data[1]
                else:
                    mau, cari = data[0], ""

                if mau == 'iya':
                    perintah.update(
                        {event.source.user_id: ['Cari lagi',
                                                time.time()]})
                    try:
                        del videos[cari.replace('+', ' ')]
                    except:
                        pass

                elif mau == 'tidak':
                    line_bot_api.reply_message(
                        event.reply_token,
                        TextSendMessage(text="Terima kasih ;)"))
                    try:
                        del videos[cari.replace('+', ' ')]
                    except:
                        pass

                else:
                    cari, nomor = args.split(" ")
                    try:
                        video = videos[cari.replace('+', ' ')]
                        batas = int(nomor) + 9
                    except:
                        videos.update({cari: []})
                        for i in youtube(cari):
                            videos[cari].append(i)
                        video = videos[cari.replace('+', ' ')]
                        batas = 19
                    jvideo = 50 - int(nomor)
                    res = list()
                    if jvideo > 10:
                        for i in video[int(nomor) + 1:batas]:
                            res.append(i)
                        res.append(
                            BubbleContainer(body=BoxComponent(
                                layout='vertical',
                                spacing='sm',
                                contents=[
                                    ButtonComponent(action=PostbackAction(
                                        label='Selanjutnya',
                                        text='Selain itu?',
                                        data='/yt ' + cari + ' ' + str(batas)),
                                                    flex=1,
                                                    gravity='center')
                                ])))
                        video = res
                    else:
                        video = video[int(nomor) + 1:]
                    line_bot_api.reply_message(event.reply_token, [
                        FlexSendMessage(
                            alt_text='Hasil pencarian: ' + cari,
                            contents=CarouselContainer(contents=video)),
                        TemplateSendMessage(
                            alt_text='Mau cari video lagi?',
                            template=ConfirmTemplate(
                                text='Mau cari video lagi?',
                                actions=[
                                    PostbackAction(label='Iya',
                                                   text='Iya',
                                                   data='/yt iya ' + cari),
                                    PostbackAction(label='Tidak',
                                                   text='Tidak',
                                                   data='/yt tidak ' + cari)
                                ]))
                    ])

    except Exception as e:
        try:
            et, ev, tb = sys.exc_info()
            lineno = tb.tb_lineno
            fn = tb.tb_frame.f_code.co_filename
            if sender != owner:
                line_bot_api.reply_message(event.reply_token, [
                    TextSendMessage(text='Oopps.. ' + namaBot.capitalize() +
                                    ' ada kesalahan kak :('),
                    TextSendMessage(
                        text=
                        'Tapi tenang kak, laporan kesalahan ini terkirim ke owner untuk diperbaiki ;D'
                    )
                ])
            line_bot_api.push_message(
                owner,
                TextSendMessage(text="[Expectation Failed] %s Line %i - %s" %
                                (fn, lineno, str(e))))
        except:
            line_bot_api.push_message(
                owner, TextSendMessage(text="Undescribeable error detected!!"))
Example #11
0
def handle_message(event):
    try:

        if isinstance(event.source, SourceGroup):
            kirim = event.source.sender_id
        elif isinstance(event.source, SourceRoom):
            kirim = event.source.room_id
        else:
            kirim = event.source.user_id

        sender = event.source.user_id

        def balas(args):
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=args))

        def cbalas(args):
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(
                    text=args,
                    quick_reply=[
                        QuickReplyButton(action=MessageAction(
                            label="YouTube Search", text="YouTube")),
                        QuickReplyButton(action=MessageAction(
                            label="Google Image Search", text="Google Image"))
                    ]))

        def message(args):
            line_bot_api.push_message(kirim, TextSendMessage(text=args))

        def cmessage(args):
            line_bot_api.push_message(
                kirim,
                TextSendMessage(
                    text=args,
                    quick_reply=[
                        QuickReplyButton(action=MessageAction(
                            label="YouTube Search", text="YouTube")),
                        QuickReplyButton(action=MessageAction(
                            label="Google Image Search", text="Google Image"))
                    ]))

        def img(args):
            line_bot_api.push_message(
                kirim,
                ImageSendMessage(original_content_url=args,
                                 preview_image_url=args))

        text = event.message.text

        if sender in perintah:
            komando, waktu = perintah[sender]

            if komando == "Mau nonton YouTube":
                try:
                    line_bot_api.reply_message(
                        event.reply_token,
                        TextSendMessage(text='Tunggu sebentar ya kak ' +
                                        panggil(sender) + ', ' +
                                        namaBot.capitalize() +
                                        ' sedang mengumpulkan data.. ;)'))
                    videos.update({text: []})
                    for i in youtube(text):
                        videos[text].append(i)
                    hasil = videos[text][:9]
                    cari = text.split()
                    res = list()
                    for i in hasil:
                        res.append(i)
                    res.append(
                        BubbleContainer(body=BoxComponent(
                            layout='vertical',
                            spacing='sm',
                            contents=[
                                ButtonComponent(action=PostbackAction(
                                    label='Selanjutnya',
                                    text='Selain itu?',
                                    data='/yt ' + '+'.join(cari) + ' 9'),
                                                flex=1,
                                                gravity='center')
                            ])))
                    line_bot_api.push_message(kirim, [
                        FlexSendMessage(
                            alt_text='Hasil pencarian: ' + text,
                            contents=CarouselContainer(contents=res)),
                        TemplateSendMessage(
                            alt_text='Mau cari video lagi?',
                            template=ConfirmTemplate(
                                text='Mau cari video lagi?',
                                actions=[
                                    PostbackAction(label='Iya',
                                                   text='Iya',
                                                   data='/yt iya ' + text),
                                    PostbackAction(label='Tidak',
                                                   text='Tidak',
                                                   data='/yt tidak ' + text)
                                ]))
                    ])
                except Exception as e:
                    try:
                        et, ev, tb = sys.exc_info()
                        lineno = tb.tb_lineno
                        fn = tb.tb_frame.f_code.co_filename
                        if sender != owner:
                            line_bot_api.reply_message(event.reply_token, [
                                TextSendMessage(text='Oopps.. ' +
                                                namaBot.capitalize() +
                                                ' ada kesalahan kak :('),
                                TextSendMessage(
                                    text=
                                    'Tapi tenang kak, laporan kesalahan ini terkirim ke owner untuk diperbaiki ;D'
                                )
                            ])
                        line_bot_api.push_message(
                            owner,
                            TextSendMessage(
                                text="[Expectation Failed] %s Line %i - %s" %
                                (fn, lineno, str(e))))
                    except:
                        line_bot_api.push_message(
                            owner,
                            TextSendMessage(
                                text="Undescribeable error detected!!"))
                del perintah[sender]

            elif komando == 'Cari lagi':
                perintah.update({sender: ['Mau nonton YouTube', time.time()]})
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(text='Mau cari apa di YouTube?'))

            elif komando == "Google Image":
                try:
                    line_bot_api.reply_message(event.reply_token, gis(text))
                except Exception as e:
                    try:
                        et, ev, tb = sys.exc_info()
                        lineno = tb.tb_lineno
                        fn = tb.tb_frame.f_code.co_filename
                        if sender != owner:
                            line_bot_api.reply_message(event.reply_token, [
                                TextSendMessage(text='Oopps.. ' +
                                                namaBot.capitalize() +
                                                ' ada kesalahan kak :('),
                                TextSendMessage(
                                    text=
                                    'Tapi tenang kak, laporan kesalahan ini terkirim ke owner untuk diperbaiki ;D'
                                )
                            ])
                        line_bot_api.push_message(
                            owner,
                            TextSendMessage(
                                text="[Expectation Failed] %s Line %i - %s" %
                                (fn, lineno, str(e))))
                    except:
                        line_bot_api.push_message(
                            owner,
                            TextSendMessage(
                                text="Undescribeable error detected!!"))
                del perintah[sender]

        elif text == "Mau nonton YouTube":
            perintah.update({sender: [text, time.time()]})
            balas("Mau cari apa di YouTube?")

        elif text == "=cmds" or text.lower() == "perintah":
            buttons_template = TemplateSendMessage(
                alt_text='Perintah-perintah',
                template=ButtonsTemplate(
                    title='PERINTAH',
                    text="Ini pilihan perintah yang bisa kamu pakai",
                    actions=[
                        MessageTemplateAction(label='Youtube Search',
                                              text='YouTube'),
                        MessageTemplateAction(label='Google Image Search',
                                              text='Google Image'),
                        MessageTemplateAction(label='Owner', text='Owner')
                    ]))
            line_bot_api.reply_message(event.reply_token, buttons_template)

        elif text[0] == "=" or "rion" in text:
            data = text[1:].split(" ", 1)
            if len(data) > 1:
                cmd, args = data[0].lower(), data[1]
            else:
                cmd, args = data[0].lower(), ""

            ############ COMMAND STARTS HERE ############

            if cmd == "yt":
                if args == "":
                    balas("Type =yt <your keyword> to search a youtube video.")
                    return
                try:
                    line_bot_api.reply_message(event.reply_token,
                                               youtube(args))
                except:
                    cbalas(args + " tidak ketemu di youtube :<")

            elif cmd == "gis":
                try:
                    if args == "":
                        balas("Type =gis <your keyword> to search an image.")
                        return
                    line_bot_api.reply_message(event.reply_token, gis(args))
                except Exception as e:
                    try:
                        et, ev, tb = sys.exc_info()
                        lineno = tb.tb_lineno
                        fn = tb.tb_frame.f_code.co_filename
                        if sender != owner:
                            line_bot_api.reply_message(event.reply_token, [
                                TextSendMessage(text='Oopps.. ' +
                                                namaBot.capitalize() +
                                                ' ada kesalahan kak :('),
                                TextSendMessage(
                                    text=
                                    'Tapi tenang kak, laporan kesalahan ini terkirim ke owner untuk diperbaiki ;D'
                                )
                            ])
                        line_bot_api.push_message(
                            owner,
                            TextSendMessage(
                                text="[Expectation Failed] %s Line %i - %s" %
                                (fn, lineno, str(e))))
                    except:
                        line_bot_api.push_message(
                            owner,
                            TextSendMessage(
                                text="Undescribeable error detected!!"))

    except LineBotApiError as e:
        print(e.status_code)
        print(e.error.message)
        print(e.error.details)
Example #12
0
def handle_message(event):
	if isinstance(event.source, SourceGroup):
		kirim = event.source.sender_id
	elif isinstance(event.source, SourceRoom):
		kirim = event.source.room_id
	else:
		kirim = event.source.user_id
	
	sender = event.source.user_id
	profil = line_bot_api.get_profile(sender)
	text = event.message.text
	
	try:

		if kirim in perintah:
			komando, waktu = perintah[kirim]
			durasi = time.time() - waktu
			if durasi > 60:
				del perintah[kirim]
				return

			if komando == "Iya, mau nyari film":
				film = download_film(text)
				res = list()
				if len(film) > 10:
					for i in film[:9]:
						res.append(i)
					res.append(
						BubbleContainer(
							body=BoxComponent(
								layout='vertical',
								spacing='sm',
								contents=[
									ButtonComponent(
										action=PostbackAction(
											label='Selanjutnya',
											text='Selain itu?',
											data='/next_download '+text+' '+kirim+' 9'
										),
										flex=1,
										gravity='center'
									)
								]
							)
						)
					)
				else:
					res = film
				hasil = FlexSendMessage(
					alt_text='Hasil pencarian: '+text.capitalize(),
					contents=CarouselContainer(
						contents=res
					)
				)
				line_bot_api.reply_message(event.reply_token, [
					TextSendMessage(text=namaBot.capitalize()+' dapat ini kak '+profil.display_name), 
					hasil
					]
				)
				del perintah[sender]

		if text == "Iya, mau nyari film":
			perintah.update({sender:[text, time.time()]})
			line_bot_api.reply_message(event.reply_token, TextSendMessage(text="Mau cari film apa?"))

		elif text == "Gada sih, cuma mau lihat-lihat film aja":
			perintah.update({sender:[text, time.time()]})

		elif text == "Mau download film":
			konfirmasi = BubbleContainer(
				direction='ltr',
				header=BoxComponent(
					layout='vertical',
					contents=[
						TextComponent(
							text='Ada film yang ingin kamu cari?',
							align='center'
						)
					]
				),
				footer=BoxComponent(
					layout='horizontal',
					contents=[
						BoxComponent(
							layout='horizontal',
							spacing='sm',
							contents=[
								ButtonComponent(
									action=MessageAction(
										label='Iya',
										text='Iya, mau nyari film'
									),
									style='primary'
								),
								ButtonComponent(
									action=MessageAction(
										label='Tidak',
										text='Gada sih, cuma mau lihat-lihat film aja'
									),
									style='secondary'
								)
							]
						)
					]
				)
			)
			line_bot_api.reply_message(event.reply_token, FlexSendMessage(alt_text='Kamu mau apa?',contents=konfirmasi))


	except Exception as e:
		try:
			et, ev, tb = sys.exc_info()
			lineno = tb.tb_lineno
			fn = tb.tb_frame.f_code.co_filename
			if sender != owner:
				line_bot_api.reply_message(event.reply_token, [
					TextSendMessage(text='Oopps.. '+namaBot.capitalize()+' ada kesalahan kak :('),
					TextSendMessage(text='Tapi tenang kak, laporan kesalahan ini terkirim ke owner untuk diperbaiki ;D')
					]
				)
			line_bot_api.push_message(owner, TextSendMessage(text="[Expectation Failed] %s Line %i - %s"% (fn, lineno, str(e))))
		except:
			line_bot_api.push_message(owner, TextSendMessage(text="Undescribeable error detected!!"))
Example #13
0
def handle_message(event):
    sender = event.source.user_id
    text = event.message.text
    try:

        startTime = time.time()
        cmds.handle_message(event)
        cinemaxxi.handle_message(event)
        yify_torrent.handle_message(event)
        quiz.handle_message(event)
        notif.handle_message(event)
        imdbthing.handle_message(event)
        gid = event.source.sender_id  #get group_id
        profil = line_bot_api.get_profile(sender)
        try:
            nama = panggil(sender)  #Ini buat nama
        except:
            data = {
                'nama':
                line_bot_api.get_profile(event.source.user_id).display_name,
                'foto':
                line_bot_api.get_profile(event.source.user_id).picture_url,
                'status':
                line_bot_api.get_profile(event.source.user_id).status_message,
                'waktu_add': time.time()
            }
            db.child("pengguna").child(event.source.user_id).set(data)
        gambar = profil.picture_url  #Ini profile picture
        status = profil.status_message  #Ini status di line

        def stimey(total_seconds):
            try:

                MINUTE = 60
                HOUR = MINUTE * 60
                DAY = HOUR * 24

                days = int(total_seconds / DAY)
                hours = int((total_seconds % DAY) / HOUR)
                minutes = int((total_seconds % HOUR) / MINUTE)
                seconds = int(total_seconds % MINUTE)

                string = list()
                if days > 0:
                    string.append(str(days) + " hari")
                if hours > 0:
                    string.append(str(hours) + " jam")
                if minutes > 0:
                    string.append(str(minutes) + " menit")
                if seconds > 0:
                    string.append(str(seconds) + " detik")
                else:
                    if len(string) == 0: string.append("0 detik")
                if len(string) > 1:
                    return ", ".join(string[:-1]) + ", dan " + string[-1]
                else:
                    return ", ".join(string)

            except Exception as e:
                try:
                    et, ev, tb = sys.exc_info()
                    lineno = tb.tb_lineno
                    fn = tb.tb_frame.f_code.co_filename
                    if sender != owner:
                        line_bot_api.reply_message(event.reply_token, [
                            TextSendMessage(text='Oopps.. ' +
                                            namaBot.capitalize() +
                                            ' ada kesalahan kak :('),
                            TextSendMessage(
                                text=
                                'Tapi tenang kak, laporan kesalahan ini terkirim ke owner untuk diperbaiki ;D'
                            )
                        ])
                    line_bot_api.push_message(
                        owner,
                        TextSendMessage(
                            text="[Expectation Failed] %s Line %i - %s" %
                            (fn, lineno, str(e))))
                except:
                    line_bot_api.push_message(
                        owner,
                        TextSendMessage(
                            text="Undescribeable error detected!!"))

        if isinstance(event.source, SourceGroup):
            kirim = gid
        elif isinstance(event.source, SourceRoom):
            kirim = event.source.room_id
        else:
            kirim = sender

        def balas(args):
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=args))

        def message(args):
            line_bot_api.push_message(kirim, TextSendMessage(text=args))

        def img(args):
            line_bot_api.push_message(
                kirim,
                ImageSendMessage(original_content_url=args,
                                 preview_image_url=args))

        if sender in perintah:
            komando, waktu = perintah[sender]

            if komando == "panggilan":
                if text == "Ubah nama panggilan": return
                db.child("pengguna").child(sender).child("tambahan").child(
                    "panggilan").set(text)
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(
                        text="Mulai sekarang kakak akan kupanggil " + text +
                        " ;D"))
                del perintah[sender]

        if text.lower() == namaBot:
            pesan = FlexSendMessage(
                alt_text="Menu",
                contents=CarouselContainer(contents=[
                    BubbleContainer(
                        styles=BubbleStyle(header=BlockStyle(
                            background_color='#223e7c')),
                        header=BoxComponent(layout='vertical',
                                            contents=[
                                                TextComponent(text='MENU',
                                                              align='center',
                                                              color='#ffffff')
                                            ]),
                        body=BoxComponent(
                            layout='vertical',
                            spacing='md',
                            contents=[
                                BoxComponent(
                                    layout='horizontal',
                                    spacing='sm',
                                    contents=[
                                        BoxComponent(
                                            layout='vertical',
                                            spacing='sm',
                                            contents=[
                                                ImageComponent(
                                                    url=
                                                    'https://i.postimg.cc/k4ybdVvm/movie-icon-11.png',
                                                    align='center',
                                                    action=MessageAction(
                                                        label='Film',
                                                        text='Nonton film kuy'
                                                    )),
                                                TextComponent(text='Film',
                                                              size='xs',
                                                              align='center')
                                            ]),
                                        BoxComponent(
                                            layout='vertical',
                                            spacing='sm',
                                            contents=[
                                                ImageComponent(
                                                    url='https://goo.gl/Rtqc1r',
                                                    align='center',
                                                    action=MessageAction(
                                                        label='Drama',
                                                        text=
                                                        'Mau nonton drama nih')
                                                ),
                                                TextComponent(text='Drama',
                                                              size='xs',
                                                              align='center')
                                            ]),
                                        BoxComponent(
                                            layout='vertical',
                                            spacing='sm',
                                            contents=[
                                                ImageComponent(
                                                    url='https://goo.gl/S9GjL7',
                                                    align='center',
                                                    action=MessageAction(
                                                        label='YouTube',
                                                        text=
                                                        'Mau nonton YouTube')),
                                                TextComponent(text='YouTube',
                                                              size='xs',
                                                              align='center')
                                            ])
                                    ]),
                                BoxComponent(
                                    layout='horizontal',
                                    spacing='sm',
                                    contents=[
                                        BoxComponent(
                                            layout='vertical',
                                            spacing='sm',
                                            contents=[
                                                ImageComponent(
                                                    url=
                                                    'https://i.postimg.cc/DzD04rPf/70.png',
                                                    align='center',
                                                    action=PostbackAction(
                                                        label='Main',
                                                        text='Main kuy',
                                                        data='/main')),
                                                TextComponent(text='Permainan',
                                                              size='xs',
                                                              align='center')
                                            ]),
                                        BoxComponent(
                                            layout='vertical',
                                            spacing='sm',
                                            contents=[
                                                ImageComponent(
                                                    url=
                                                    'https://i.postimg.cc/q75v5Q3X/69.png',
                                                    align='center',
                                                    action=PostbackAction(
                                                        label='Pengingat',
                                                        text='Atur pengingat',
                                                        data='/pengingat')),
                                                TextComponent(text='Pengingat',
                                                              wrap=True,
                                                              size='xs',
                                                              align='center')
                                            ]),
                                        BoxComponent(
                                            layout='vertical',
                                            spacing='sm',
                                            contents=[
                                                ImageComponent(
                                                    url=
                                                    'https://i.postimg.cc/YqqXtBh6/settings-3-icon.png',
                                                    align='center',
                                                    action=PostbackAction(
                                                        label='Pengaturan',
                                                        text='Pengaturan',
                                                        data='/pengaturan')),
                                                TextComponent(
                                                    text='Pengaturan',
                                                    size='xs',
                                                    align='center',
                                                    wrap=True)
                                            ])
                                    ])
                            ]),
                        footer=BoxComponent(
                            layout='baseline',
                            contents=[
                                TextComponent(text='© YRP',
                                              size='xxs',
                                              align='start'),
                                TextComponent(
                                    text=namaBot.capitalize() + ' ' +
                                    os.environ.get('HEROKU_RELEASE_VERSION'),
                                    size='xxs',
                                    align='end')
                            ]))
                ]))
            line_bot_api.reply_message(
                event.reply_token,
                [TextComponent(text="Kamu ingin apa hari ini?"), pesan])

        elif text == "Nonton film kuy":
            balas("Ini aku punya beberapa fungsi kalau kak " + nama +
                  " mau nonton film ;)")
            line_bot_api.push_message(kirim, mau_nonton())

        elif namaBot in text.lower(
        ) and not text.lower() == namaBot and not sender in cmds.perintah:

            if "apa" in text.lower():
                if text.lower()[len(text) - 1] == "?":
                    balas(
                        random.choice([
                            "Ya", "Tidak", "Terkadang", "Mungkin",
                            "Coba tanya lagi", "Entah", "Hmm..."
                        ]))
                else:
                    balas("Situ bertanya?")

    #=====[ LEAVE GROUP OR ROOM ]==========
        elif 'get out' == text.lower() or 'bye' == text.lower():
            if sender != owner:
                balas("STFU!")
                return
            if isinstance(event.source, SourceGroup):
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(text='Good Bye Cruel World'))
                line_bot_api.leave_group(event.source.group_id)
            elif isinstance(event.source, SourceRoom):
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(text='Good Bye Cruel World'))
                line_bot_api.leave_room(event.source.room_id)
            else:
                line_bot_api.reply_message(event.reply_token,
                                           TextSendMessage(text="No!"))

        ################################################

        elif text.lower() == "who am i?":
            #message("You're "+nama)
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text="You're " + nama))
            line_bot_api.push_message(
                kirim,
                ImageSendMessage(original_content_url=gambar,
                                 preview_image_url=gambar))

        elif text[0] == "=":
            data = text[1:].split(" ", 1)
            if len(data) > 1:
                cmd, args = data[0].lower(), data[1]
            else:
                cmd, args = data[0].lower(), ""

            if cmd == "e":
                if sender != owner:
                    message('STFU!')
                    return
                try:
                    ret = eval(args)
                    if ret == None:
                        message("Done.")
                        return
                    message(str(ret))
                except Exception as e:
                    try:
                        et, ev, tb = sys.exc_info()
                        lineno = tb.tb_lineno
                        fn = tb.tb_frame.f_code.co_filename
                        message("[Expectation Failed] %s Line %i - %s" %
                                (fn, lineno, str(e)))
                    except:
                        message("Undescribeable error detected!!")

    #=====[ FLEX MESSAGE ]==========
        elif text == 'flex':
            bubble = BubbleContainer(
                direction='ltr',
                hero=ImageComponent(
                    url=
                    'https://i.pinimg.com/originals/0b/45/54/0b45541af3e8d77e23498c1bc8d552f6.jpg',
                    size='full',
                    aspect_ratio='20:13',
                    aspect_mode='cover',
                    action=URIAction(
                        uri='http://line.me/ti/p/~freedom_for_all',
                        label='label')),
                body=BoxComponent(
                    layout='vertical',
                    contents=[
                        # title
                        TextComponent(text='Noir', 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='Ujung Pandang, Indonesia',
                                            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=[
                        # separator
                        SeparatorComponent(),
                        # websiteAction
                        ButtonComponent(
                            style='link',
                            height='sm',
                            action=URIAction(
                                label='Noir',
                                uri="https://line.me/ti/p/~freedom_for_all"))
                    ]),
            )
            message = FlexSendMessage(alt_text="Hi there!", contents=bubble)
            line_bot_api.reply_message(event.reply_token, message)


#=======================================================================================================================
############ ERROR HANDLING ############

    except LineBotApiError as e:
        print(e.status_code)
        print(e.error.message)
        print(e.error.details)
Example #14
0
def handle_postback(event):
    cmds.handle_postback(event)
    yify_torrent.handle_postback(event)
    cinemaxxi.handle_postback(event)
    notif.handle_postback(event)
    quiz.handle_postback(event)
    imdbthing.handle_postback(event)
    sender = event.source.user_id
    if isinstance(event.source, SourceGroup):
        kirim = gid
    elif isinstance(event.source, SourceRoom):
        kirim = event.source.room_id
    else:
        kirim = sender

    try:
        if event.postback.data[0] == '/':
            data = event.postback.data[1:].split(" ", 1)
            if len(data) > 1:
                cmd, args = data[0].lower(), data[1]
            else:
                cmd, args = data[0].lower(), ""

            if cmd == "pengaturan":
                line_bot_api.reply_message(event.reply_token,
                                           pengaturan(sender))

            elif cmd == "lokasi":
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(text='Share lokasi dulu kak ' +
                                    panggil(sender) + ' ;)',
                                    quick_reply=QuickReply(items=[
                                        QuickReplyButton(action=LocationAction(
                                            label='Share lokasi'))
                                    ])))
                perintah.update({sender: ['lokasi', time.time()]})

            elif cmd == "nick":

                if args == sender:
                    gunakan = args
                else:
                    gunakan = sender

                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(text="Kak " + panggil(gunakan) +
                                    " mau dipanggil apa?"))
                perintah.update({sender: ['panggilan', time.time()]})

            elif cmd == "tanggal_lahir":

                if args == sender:
                    gunakan = args
                else:
                    gunakan = sender

                db.child("pengguna").child(gunakan).child("tambahan").child(
                    "tanggal_lahir").set(event.postback.params['date'])
                sekarang = datetime.datetime.utcfromtimestamp(time.time())
                tanggal = int(sekarang.strftime('%d'))
                bulan = int(sekarang.strftime('%m'))
                tahun = int(sekarang.strftime('%Y'))
                utahun, ubulan, utanggal = event.postback.params['date'].split(
                    '-')
                umur = tahun - int(utahun)

                if tanggal < int(utanggal):
                    if bulan < int(ubulan):
                        umur = umur - 1

                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(text="Kak " + panggil(gunakan) +
                                    " sekarang berumur " + str(umur) +
                                    " tahun ;D"))

    except Exception as e:
        try:
            et, ev, tb = sys.exc_info()
            lineno = tb.tb_lineno
            fn = tb.tb_frame.f_code.co_filename
            if sender != owner:
                line_bot_api.reply_message(event.reply_token, [
                    TextSendMessage(text='Oopps.. ' + namaBot.capitalize() +
                                    ' ada kesalahan kak :('),
                    TextSendMessage(
                        text=
                        'Tapi tenang kak, laporan kesalahan ini terkirim ke owner untuk diperbaiki ;D'
                    )
                ])
            line_bot_api.push_message(
                owner,
                TextSendMessage(text="[Expectation Failed] %s Line %i - %s" %
                                (fn, lineno, str(e))))
        except:
            line_bot_api.push_message(
                owner, TextSendMessage(text="Undescribeable error detected!!"))