Example #1
0
async def audio(chat: Chat, match):
    log(chat)
    surah = int(match.group(1))
    if not (1 <= surah <= 114):
        return chat.send_text("Surah does not exist!")
    await chat.send_chat_action("upload_audio")

    directory = "Mahmoud_Khalil_Al-Hussary_(Updated2)(MP3_Quran)/"
    multiple = {  # surahs in multiple audio tracks
        2: 4,
        3: 3,
        4: 3,
        5: 2,
        6: 2,
        7: 2,
        9: 2,
        10: 2,
        11: 2,
        12: 2,
        16: 2
    }

    if surah in multiple:
        filenames = [
            directory + str(surah).zfill(3) + "_" + str(i) + ".mp3"
            for i in range(1, multiple[surah] + 1)
        ]
        multi = True
    else:
        filenames = [directory + str(surah).zfill(3) + ".mp3"]
        multi = False
    performer = "Shaykh Mahmoud Khalil al-Husary"
    title = "Quran {} {}".format(surah, Quran.get_surah_name(surah))

    for (i, filename) in enumerate(filenames):
        if multi:
            title = "Quran {} {} (part {}/{})".format(
                surah, Quran.get_surah_name(surah), i + 1, len(filenames))
        file_id = await get_file(filename)
        if file_id:
            try:
                response = await chat.send_audio(file_id,
                                                 performer=performer,
                                                 title=title)
            except Exception as e:
                if "file_id" in str(e) or "file identifier" in str(e):
                    with open(filename, "rb") as f:
                        response = await chat.send_audio(f,
                                                         performer=performer,
                                                         title=title)
                else:
                    raise (e)
        else:
            with open(filename, "rb") as f:
                response = await chat.send_audio(f,
                                                 performer=performer,
                                                 title=title)

        file_id = response["result"]["audio"]["file_id"]
        await save_file(filename, file_id)
Example #2
0
def main():
    global update_id
    bot = telegram.Bot(token=TOKEN)

    try:
        update_id = bot.get_updates()[0].update_id
    except IndexError:
        update_id = None

    interface = telegram.ReplyKeyboardMarkup(
        [["Arabic", "Audio", "Indonesia", "Tafsir"],
         ["Sebelumnya", "Acak", "Berikutnya"]],
        resize_keyboard=True)

    data = {
        "indonesia": Quran("translation"),
        "tafsir": Quran("tafsir"),
        "index": make_index(),
        "interface": interface
    }
    data["default_query_results"] = get_default_query_results(data["indonesia"])

    while True:
        try:
            serve(bot, data)
        except NetworkError:
            sleep(1)
        except Unauthorized:  # user has removed or blocked the bot
            update_id += 1
        except TelegramError as e:
            if "Invalid server response" in str(e):
                sleep(3)
            else:
                raise e
Example #3
0
def get_default_query_results(quran: Quran):
    results = []
    ayat = [
        (13, 28), (33, 56), (2, 62), (10, 31), (17, 36), (5, 32), (39, 9), (17, 44), (28, 88), (17, 84), (33, 6),
        (7, 57), (3, 7), (2, 255), (63, 9), (57, 20), (49, 12), (16, 125), (24, 35), (73, 8), (4, 103)
    ]
    for s, a in ayat:
        ayah = "%d:%d" % (s, a)
        indonesia = quran.get_ayah(s, a)
        results.append(InlineQueryResultArticle(
            ayah + "def", title=ayah,
            description=indonesia[:120],
            input_message_content=InputTextMessageContent(indonesia))
        )
    return results
Example #4
0
def serve(bot, data):
    global update_id

    def send_quran(s: int, a: int, quran_type: str, chat_id: int, reply_markup=None):
        if quran_type in ("indonesia", "tafsir"):
            text = data[quran_type].get_ayah(s, a)
            bot.send_message(chat_id=chat_id, text=text[:MAX_MESSAGE_LENGTH],
                             reply_markup=reply_markup)
        elif quran_type == "arabic":
            bot.send_chat_action(chat_id=chat_id,
                                 action=telegram.ChatAction.UPLOAD_PHOTO)
            image = get_image_filename(s, a)
            send_file(bot, image, quran_type, chat_id=chat_id,
                      caption="Quran %d:%d" % (s, a),
                      reply_markup=reply_markup)
        elif quran_type == "audio":
            bot.send_chat_action(chat_id=chat_id,
                                 action=telegram.ChatAction.UPLOAD_AUDIO)
            audio = get_audio_filename(s, a)
            send_file(bot, audio, quran_type, chat_id=chat_id,
                      performer="Shaykh Mahmoud Khalil al-Husary",
                      title="Quran %d:%d" % (s, a),
                      reply_markup=reply_markup)
        save_user(chat_id, (s, a, quran_type))

    for update in bot.get_updates(offset=update_id, timeout=10):
        update_id = update.update_id + 1

        if update.inline_query:
            query_id = update.inline_query.id
            query = update.inline_query.query
            results = []
            cache_time = 66 * (60 ** 2 * 24)
            s, a = parse_ayah(query)
            if s is not None and Quran.exists(s, a):
                ayah = "%d:%d" % (s, a)
                indonesia = data["indonesia"].get_ayah(s, a)
                tafsir = data["tafsir"].get_ayah(s, a)
                results.append(InlineQueryResultArticle(
                    ayah + "indonesia", title="Indonesia",
                    description=indonesia[:120],
                    input_message_content=InputTextMessageContent(indonesia))
                )
                results.append(InlineQueryResultArticle(
                    ayah + "tafsir", title="Tafsir",
                    description=tafsir[:120],
                    input_message_content=InputTextMessageContent(tafsir))
                )
            else:
                results = data["default_query_results"]
            bot.answer_inline_query(inline_query_id=query_id, cache_time=cache_time, results=results)
            continue

        if not update.message or not update.message.text:  # updates without text
            continue

        chat_id = update.message.chat_id
        message = update.message.text.lower()
        state = get_user(chat_id)
        if state is not None:
            s, a, quran_type = state
        else:
            s, a, quran_type = 1, 1, "indonesia"

        print("%d:%.3f:%s" % (chat_id, time(), message.replace("\n", " ")))

        if chat_id < 0:
            continue            # bot should not be in a group

        if message.startswith("/"):
            command = message[1:]
            if command in ("start", "help"):
                text = ("Kirimkan saya nomor surah dan ayat, misalnya:"
                        " <b>2:255</b>. Lalu saya menanggapi dengan ayat itu dari Kitab Suci "
                        "Al-Qur'an. Ketik /index untuk melihat semua surat atau mencoba /acak. "
                        "Saya tersedia di obrolan apa pun di Telegram, cukup ketik: <b>@BismillahIDBot</b>\n\n"
                        "Untuk trek audio Surah lengkap, bicara ke @AudioQuranBot.")
            elif command == "about":
                text = ("Terjemahan Bahasa Indonesia oleh Departemen Agama Indonesia di "
                        "tanzil.net/trans/. Audio di baca oleh "
                        "Shaykh Mahmoud Khalil al-Husary dari everyayah.com. "
                        "Tafsirnya adalah Tafsir al-Jalalayn berasal dari altafsir.com."
                        "Kode sumber BismillahIDBot tersedia di: "
                        "https://github.com/AyraHikari/BismillahBot.")
            elif command == "index":
                text = data["index"]
            else:
                text = None  # "Invalid command"

            if text:
                bot.send_message(chat_id=chat_id, text=text, parse_mode="HTML")
                continue

        if message in ("indonesia", "tafsir", "audio", "arabic"):
            send_quran(s, a, message, chat_id)
            continue
        elif message in ("berikutnya", "sebelumnya", "acak", "/acak"):
            if message == "berikutnya":
                s, a = Quran.get_next_ayah(s, a)
            elif message == "sebelumnya":
                s, a = Quran.get_previous_ayah(s, a)
            elif message in ("acak", "/acak"):
                s, a = Quran.get_random_ayah()
            send_quran(s, a, quran_type, chat_id)
            continue

        s, a = parse_ayah(message)
        if s:
            if Quran.exists(s, a):
                send_quran(s, a, quran_type, chat_id, reply_markup=data["interface"])
            else:
                bot.send_message(chat_id=chat_id, text="Ayah does not exist!")

    sys.stdout.flush()
Example #5
0
def serve(bot, data):
    global update_id

    def send_quran(s: int,
                   a: int,
                   quran_type: str,
                   chat_id: int,
                   reply_markup=None):
        if quran_type in ("english", "tafsir"):
            text = data[quran_type].get_ayah(s, a)
            bot.send_message(chat_id=chat_id,
                             text=text[:MAX_MESSAGE_LENGTH],
                             reply_markup=reply_markup)
        elif quran_type == "arabic":
            bot.send_chat_action(chat_id=chat_id,
                                 action=telegram.ChatAction.UPLOAD_PHOTO)
            image = get_image_filename(s, a)
            send_file(bot,
                      image,
                      quran_type,
                      chat_id=chat_id,
                      caption="Quran %d:%d" % (s, a),
                      reply_markup=reply_markup)
        elif quran_type == "audio":
            bot.send_chat_action(chat_id=chat_id,
                                 action=telegram.ChatAction.UPLOAD_AUDIO)
            audio = get_audio_filename(s, a)
            send_file(bot,
                      audio,
                      quran_type,
                      chat_id=chat_id,
                      performer="Shaykh Mahmoud Khalil al-Husary",
                      title="Quran %d:%d" % (s, a),
                      reply_markup=reply_markup)
        save_user(chat_id, (s, a, quran_type))

    for update in bot.get_updates(offset=update_id, timeout=10):
        update_id = update.update_id + 1

        if update.inline_query:
            query_id = update.inline_query.id
            query = update.inline_query.query
            results = []
            cache_time = 66 * (60**2 * 24)
            s, a = parse_ayah(query)
            if s is not None and Quran.exists(s, a):
                ayah = "%d:%d" % (s, a)
                english = data["english"].get_ayah(s, a)
                tafsir = data["tafsir"].get_ayah(s, a)
                results.append(
                    InlineQueryResultArticle(
                        ayah + "english",
                        title="English",
                        description=english[:120],
                        input_message_content=InputTextMessageContent(
                            english)))
                results.append(
                    InlineQueryResultArticle(
                        ayah + "tafsir",
                        title="Tafsir",
                        description=tafsir[:120],
                        input_message_content=InputTextMessageContent(tafsir)))
            else:
                results = data["default_query_results"]
            bot.answer_inline_query(inline_query_id=query_id,
                                    cache_time=cache_time,
                                    results=results)
            continue

        if not update.message or not update.message.text:  # updates without text
            continue

        chat_id = update.message.chat_id
        message = update.message.text.lower()
        state = get_user(chat_id)
        if state is not None:
            s, a, quran_type = state
        else:
            s, a, quran_type = 1, 1, "english"

        print("%d:%.3f:%s" % (chat_id, time(), message.replace("\n", " ")))

        if chat_id < 0:
            continue  # bot should not be in a group

        if message.startswith("/"):
            command = message[1:]
            if command in ("start", "help"):
                text = (
                    "Send me the numbers of a surah and ayah, for example:"
                    " <b>2:255</b>. Then I respond with that ayah from the Holy "
                    "Quran. Type /index to see all Surahs or try /random. "
                    "I'm available in any chat on Telegram, just type: <b>@BismillahBot</b>\n\n"
                    "For audio tracks of complete Surahs, talk to @AudioQuranBot."
                )
            elif command == "about":
                text = ("The English translation is by Imam Ahmed Raza from "
                        "tanzil.net/trans/. The audio is a recitation by "
                        "Shaykh Mahmoud Khalil al-Husary from everyayah.com. "
                        "The tafsir is Tafsir al-Jalalayn from altafsir.com."
                        "The source code of BismillahBot is available at: "
                        "https://github.com/rahiel/BismillahBot.")
            elif command == "index":
                text = data["index"]
            else:
                text = None  # "Invalid command"

            if text:
                bot.send_message(chat_id=chat_id, text=text, parse_mode="HTML")
                continue

        if message in ("english", "tafsir", "audio", "arabic"):
            send_quran(s, a, message, chat_id)
            continue
        elif message in ("next", "previous", "random", "/random"):
            if message == "next":
                s, a = Quran.get_next_ayah(s, a)
            elif message == "previous":
                s, a = Quran.get_previous_ayah(s, a)
            elif message in ("random", "/random"):
                s, a = Quran.get_random_ayah()
            send_quran(s, a, quran_type, chat_id)
            continue

        s, a = parse_ayah(message)
        if s:
            if Quran.exists(s, a):
                send_quran(s,
                           a,
                           quran_type,
                           chat_id,
                           reply_markup=data["interface"])
            else:
                bot.send_message(chat_id=chat_id, text="Ayah does not exist!")

    sys.stdout.flush()