Esempio n. 1
0
def handle_message(event):
    sender = event.source.user_id
    text = event.message.text
    if sender in remind_me:
        status, kalender = remind_me[sender]
        if status == 'sukses':
            tanggal, jamku = kalender.split("T")
            thn, bln, tgl = tanggal.split("-")
            tanggal = tgl + '-' + bln + '-' + thn
            data = {'tanggal': tanggal, 'jam': jamku, 'ulang': False}
            db.child("pengguna").child(sender).child("tambahan").child(
                "pengingat").child(text).set(data)
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text='Okee kak ;D'))
            sesuatu.reminder()
            del remind_me[sender]
Esempio n. 2
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)
Esempio n. 3
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)
Esempio n. 4
0
def handle_location_message(event):
    cinemaxxi.handle_location_message(event)
    if event.source.user_id in perintah:
        komando, waktu = perintah[event.source.user_id]
        if komando == "lokasi":
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='Kak ' + panggil(event.source.user_id) +
                                ' sekarang berada di ' +
                                event.message.address + ' ;)'))
            data = {
                'nama_lokasi': event.message.address,
                'latitude': event.message.latitude,
                'longitude': event.message.longitude
            }
            db.child("pengguna").child(event.source.user_id).child(
                "tambahan").child("lokasi").set(data)
            del perintah[event.source.user_id]
Esempio n. 5
0
def handle_leave(event):
    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).remove()
    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(0)
Esempio n. 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

    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!!"))
Esempio n. 7
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!!"))
Esempio n. 8
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!!"))
Esempio n. 9
0
def handle_postback(event):
    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 == "pengingat":
                try:
                    data = db.child("pengguna").child(sender).child(
                        "tambahan").get().val()
                    zona = data["zona_waktu"]
                    sekarang = datetime.today()
                    if sekarang.minute < 10:
                        menit = '0' + str(sekarang.minute)
                    else:
                        menit = str(sekarang.minute)
                    if sekarang.hour < 10:
                        jam = '0' + str(sekarang.hour)
                    else:
                        jam = str(sekarang.hour)
                    pesan = TemplateSendMessage(
                        alt_text='Liat pengingat atau mau nambahin pengingat?',
                        template=ButtonsTemplate(
                            title='Pengingat',
                            text='Mau cek atau nambahin pengingat?',
                            actions=[
                                PostbackAction(label='Cek Pengingat',
                                               text='Mau cek pengingat',
                                               data='/cek_pengingat'),
                                DatetimePickerAction(
                                    label='Tambah pengingat',
                                    text='Mau nambahin pengingat',
                                    data='/tambah_pengingat',
                                    mode='datetime',
                                    initial=str(sekarang.year) + '-' +
                                    str(sekarang.month) + '-' +
                                    str(sekarang.day + 1) + 't' + jam + ':' +
                                    menit,
                                    min=str(sekarang.date()) + 't' + jam +
                                    ':' + menit)
                            ]))
                    line_bot_api.reply_message(event.reply_token, pesan)
                except:
                    line_bot_api.reply_message(event.reply_token, [
                        TextSendMessage(
                            text='Kak ' + panggil(sender) +
                            ' belum menentukan zona waktu, silahkan dipilih dulu ;D'
                        ),
                        indozone()
                    ])

            elif cmd == 'zona':
                try:
                    data = db.child("pengguna").child(sender).child(
                        "tambahan").get().val()
                    sekarang = data["zona_waktu"]
                except:
                    sekarang = ""

                if not sekarang == "":
                    if args != sekarang:
                        konfirm = TemplateSendMessage(
                            alt_text='Kamu ingin mengubah zona waktu kamu?',
                            template=ConfirmTemplate(
                                text='Kamu ingin mengubah zona waktu kamu dari '
                                + sekarang + ' ke ' + args.upper() + '?',
                                actions=[
                                    PostbackAction(label='Iya',
                                                   text='Iya',
                                                   data='/ubah_zona_waktu ' +
                                                   args),
                                    PostbackAction(
                                        label='Tidak',
                                        text='Tidak',
                                        data='/ubah_zona_waktu tidak')
                                ]))
                        line_bot_api.reply_message(event.reply_token, konfirm)
                    else:
                        line_bot_api.reply_message(
                            event.reply_token,
                            TextSendMessage(text='Zona waktu kak ' +
                                            panggil(sender) + ' sudah ' +
                                            args.upper() + ' :|'))
                else:
                    db.child("pengguna").child(sender).child("tambahan").child(
                        "zona_waktu").set(args.upper())
                    line_bot_api.reply_message(
                        event.reply_token,
                        TextSendMessage(text='Zona waktu kak ' +
                                        panggil(sender) +
                                        ' berhasil diset ;D'))
                    if sender in remind_me:
                        status, kalender = remind_me[sender]
                        if status == 'pending':
                            t_timestamp = time.mktime(
                                datetime.strptime(
                                    kalender, "%Y-%m-%dT%H:%M").timetuple())
                            MENIT = 60
                            JAM = MENIT * 60
                            if args.upper() == 'WITA':
                                t_timestamp = t_timestamp + (1 * JAM)
                            elif args.upper() == 'WIT':
                                t_timestamp = t_timestamp + (2 * JAM)
                            durasi = t_timestamp - time.time()
                            if int(durasi) <= 20:
                                line_bot_api.push_message(
                                    sender, [
                                        TextSendMessage(
                                            text='Maaf kak ' +
                                            panggil(sender) +
                                            ', waktunya udah lewat :('),
                                        TextSendMessage(
                                            text='Silahkan pilih waktu lagi ;D'
                                        )
                                    ])
                                del remind_me[sender]
                            else:
                                remind_me.update(
                                    {sender: ['sukses', kalender]})
                                line_bot_api.push_message(
                                    sender,
                                    TextSendMessage(
                                        text='Kak ' + panggil(sender) +
                                        ' mau diingatkan apa pada tanggal ' +
                                        tgl + ' bulan ' + bulan(int(bln)) +
                                        ' tahun ' + thn + ' jam ' + jamku +
                                        '?'))

            elif cmd == 'zona_waktu':
                line_bot_api.reply_message(event.reply_token, indozone())

            elif cmd == 'ubah_zona_waktu':
                try:
                    sekarang = db.child("pengguna").child(sender).child(
                        "tambahan").child("zona_waktu").get().val()
                    if args != 'tidak':
                        if sekarang.lower() == args:
                            line_bot_api.reply_message(
                                event.reply_token,
                                TextSendMessage(text="Kak " + panggil(sender) +
                                                " sudah " + args.upper() +
                                                " :|"))
                        else:
                            db.child("pengguna").child(sender).child(
                                "tambahan").child("zona_waktu").update(
                                    args.upper())
                            line_bot_api.reply_message(
                                event.reply_token,
                                TextSendMessage(text='Zona waktu kak ' +
                                                panggil(sender) +
                                                ' berhasil diubah menjadi ' +
                                                args.upper() + ' ;D'))
                    else:
                        line_bot_api.reply_message(
                            event.reply_token,
                            TextSendMessage(text='Zona waktu kak ' +
                                            panggil(sender) + ' tetap ' +
                                            sekarang + ' ;D'))
                except:
                    line_bot_api.reply_message(event.reply_token, [
                        TextSendMessage(text='Kak ' + panggil(sender) +
                                        ' belum menentukan zona waktu :('),
                        TextSendMessage(
                            text='Silahkan pilih zona waktu terlebih dahulu ;D'
                        ),
                        indozone()
                    ])

            elif cmd == 'tambah_pengingat':
                kalender = event.postback.params['datetime']
                t_timestamp = time.mktime(
                    datetime.strptime(kalender, "%Y-%m-%dT%H:%M").timetuple())
                durasi = t_timestamp - time.time()
                if int(durasi) <= 0:
                    line_bot_api.reply_message(event.reply_token, [
                        TextSendMessage(text='Maaf kak ' + panggil(sender) +
                                        ', waktunya udah lewat :('),
                        TextSendMessage(text='Silahkan pilih waktu lagi ;D')
                    ])
                    return
                try:
                    status = 'sukses'
                    data = db.child("pengguna").child(sender).child(
                        "tambahan").get().val()
                    zona_waktu = data["zona_waktu"]
                    tanggal, jamku = kalender.split("T")
                    thn, bln, tgl = tanggal.split('-')
                    line_bot_api.reply_message(
                        event.reply_token,
                        TextSendMessage(text='Kak ' + panggil(sender) +
                                        ' mau diingatkan apa pada tanggal ' +
                                        tgl + ' bulan ' + bulan(int(bln)) +
                                        ' tahun ' + thn + ' jam ' + jamku +
                                        '?'))
                except:
                    status = 'pending'
                    line_bot_api.reply_message(event.reply_token, [
                        TextSendMessage(
                            text='Maaf kak, kak ' + panggil(sender) +
                            ' belum memberitahu zona waktu kakak :('),
                        TextSendMessage(text='Silahkan dipilih dulu kak ;D'),
                        indozone()
                    ])

                remind_me.update({sender: [status, kalender]})

            elif cmd == 'cek_pengingat':
                try:
                    sekarang = datetime.today()
                    if sekarang.minute < 10:
                        menit = '0' + str(sekarang.minute)
                    else:
                        menit = str(sekarang.minute)
                    if sekarang.hour < 10:
                        jam = '0' + str(sekarang.hour)
                    else:
                        jam = str(sekarang.hour)
                    kumpulan = list()
                    atur = {}
                    reminder = db.child("pengguna").child(sender).child(
                        "tambahan").child("pengingat").get().val()
                    for alarm in reminder:
                        waktu = reminder[alarm]["jam"]
                        tanggal = reminder[alarm]["tanggal"]
                        waktu_alarm = tanggal + " " + waktu
                        t_timestamp = time.mktime(
                            datetime.strptime(waktu_alarm,
                                              "%d-%m-%Y %H:%M").timetuple())
                        durasi = t_timestamp - time.time()
                        atur.update({durasi: [alarm, tanggal, waktu]})

                    tambahan = db.child("pengguna").child(sender).child(
                        "tambahan").get().val()
                    zona_waktu = tambahan["zona_waktu"]

                    diatur = [i for i in atur.keys()]
                    diatur.sort()
                    for r in diatur:
                        alarm, tanggal, waktu = atur[r]
                        kumpulan.append(
                            BoxComponent(
                                layout='baseline',
                                margin='sm',
                                contents=[
                                    TextComponent(
                                        text=reminder[alarm]["tanggal"],
                                        size='xs',
                                        align='center'),
                                    TextComponent(text=reminder[alarm]["jam"],
                                                  size='xs',
                                                  align='center'),
                                    TextComponent(text=alarm,
                                                  size='xs',
                                                  align='center',
                                                  wrap=True)
                                ]))
                    jadwal = BubbleContainer(
                        direction='ltr',
                        body=BoxComponent(
                            layout='vertical',
                            contents=[
                                TextComponent(text='PENGINGAT',
                                              align='center',
                                              weight='bold',
                                              color='#aaaaaa'),
                                SeparatorComponent(margin='md'),
                                TextComponent(
                                    text='Berikut ini pengingat kak ' +
                                    panggil(sender) + ' ;D',
                                    size='sm',
                                    align='start',
                                    gravity='top',
                                    margin='md',
                                    wrap=True),
                                BoxComponent(layout='baseline',
                                             contents=[
                                                 TextComponent(
                                                     text='Zona Waktu',
                                                     size='xs',
                                                     color='#7b7b7b'),
                                                 TextComponent(text=zona_waktu,
                                                               flex=2,
                                                               size='xs',
                                                               color='#7b7b7b')
                                             ]),
                                SeparatorComponent(margin='lg'),
                                BoxComponent(
                                    layout='vertical',
                                    margin='sm',
                                    contents=[
                                        BoxComponent(
                                            layout='baseline',
                                            contents=[
                                                TextComponent(text='Tanggal',
                                                              size='xs',
                                                              align='center',
                                                              weight='bold',
                                                              color='#939393'),
                                                TextComponent(text='Jam',
                                                              size='xs',
                                                              align='center',
                                                              weight='bold',
                                                              color='#939393'),
                                                TextComponent(text='Agenda',
                                                              size='xs',
                                                              align='center',
                                                              weight='bold',
                                                              color='#939393')
                                            ]),
                                        SeparatorComponent(margin='xs'),
                                        BoxComponent(layout='vertical',
                                                     margin='sm',
                                                     contents=kumpulan)
                                    ])
                            ]),
                        footer=BoxComponent(
                            layout='horizontal',
                            contents=[
                                ButtonComponent(action=DatetimePickerAction(
                                    label='Tambah pengingat',
                                    text='Mau nambahin pengingat',
                                    data='/tambah_pengingat',
                                    mode='datetime',
                                    initial=str(sekarang.year) + '-' +
                                    str(sekarang.month) + '-' +
                                    str(sekarang.day + 1) + 't' + jam + ':' +
                                    menit,
                                    min=str(sekarang.date()) + 't' + jam +
                                    ':' + menit),
                                                color='#ffffff',
                                                height='sm')
                            ]),
                        styles=BubbleStyle(footer=BlockStyle(
                            background_color='#00318d')))
                    kirim = FlexSendMessage(alt_text='Pengingat',
                                            contents=jadwal)
                    line_bot_api.reply_message(event.reply_token, kirim)
                except:
                    line_bot_api.reply_message(
                        event.reply_token,
                        TextSendMessage(text='Kamu tidak memiliki pengingat.'))
    except Exception as e:
        try:
            et, ev, tb = sys.exc_info()
            lineno = tb.tb_lineno
            fn = tb.tb_frame.f_code.co_filename
            line_bot_api.push_message(
                sender,
                TextSendMessage(text="[Expectation Failed] %s Line %i - %s" %
                                (fn, lineno, str(e))))
        except:
            line_bot_api.push_message(
                sender,
                TextSendMessage(text="Undescribeable error detected!!"))
Esempio n. 10
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)
Esempio n. 11
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!!"))