Esempio n. 1
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", "English", "Tafsir"],
         ["Previous", "Random", "Next"]],
        resize_keyboard=True)

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

    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
Esempio n. 2
0
def quran_api():
    if request.method == "POST":
        quran = Quran()
        data = request.get_json()
        if data:
            if data["type"] == "select":
                data = data.get("data")
                if data:
                    surah = data.get("surah")
                    ayat = data.get("ayat")
                    return jsonify(quran.select(surah, ayat))
                else:
                    return jsonify(
                        dict(success=False,
                             message="gagal, param data tidak ada"))
            elif data["type"] == "surah":
                data = data.get("data")
                if data:
                    surah = data.get("surah")
                    return jsonify(quran.surah(surah))
                else:
                    return jsonify(
                        dict(success=False,
                             message="gagal, param data tidak ada"))
            elif data["type"] == "specify":
                data = data.get("data")
                if data:
                    surah = data.get("surah")
                    start = data.get("start")
                    end = data.get("end")
                    return jsonify(quran.specify(surah, start=start, end=end))
                else:
                    return jsonify(
                        dict(success=False,
                             message="gagal, param data tidak ada"))
            else:
                return jsonify(status=False, message=None)
        else:
            return jsonify(status=False, message=None)
    return render_template("api.html", path="api", title="API Quran")
Esempio n. 3
0
def serve(bot, data):
    global update_id

    def send_quran(s, a, quran_type, chat_id, 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:  # weird Telegram update with only an update_id
            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

        # "special:quran_type"
        special_state = quran_type.split(":")

        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>")
            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"]
            elif command == "feedback":
                text = ("Jazak Allahu khayran! Your feedback is highly "
                        "appreciated and will help us improve our services. "
                        "Your next message will be sent to the developers. "
                        "Send /cancel to cancel.")
                save_user(chat_id, (s, a, "feedback:" + quran_type))
            elif command == "cancel":
                text = ("Cancelled.")
                if len(special_state) > 1:
                    save_user(chat_id, (s, a, special_state[1]))
            else:
                text = None  # "Invalid command"
            if text:
                bot.send_message(chat_id=chat_id, text=text, parse_mode="HTML")
                continue

        if len(special_state) > 1:
            if special_state[0] == "feedback":
                with open("feedback.txt", "a") as f:
                    f.write("%d: %s\n" % (chat_id, message))
                text = "Feedback saved 😊"
                bot.send_message(chat_id=chat_id, text=text)
                save_user(chat_id, (s, a, special_state[1]))
                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()
Esempio n. 4
0
###

import requests as rq

from quran import Quran

# res = quran.get_recitations()
# res = quran.get_translations()
# res = quran.get_languages(language='ur')
# res = quran.get_tafsirs()
# res = quran.get_chapters(6, language="ur")
# res = quran.get_verses(6, recitation=1, translations=21, language="en", text_type="words")
# res = quran.get_verse(6, 6)
# res = quran.get_juzs()

qur = Quran()


def test_get_recitations():
    assert qur.get_recitations() == rq.get(
        "http://api.quran.com:3000/api/v3/options/recitations").json()


def test_get_translations():
    assert qur.get_translations() == rq.get(
        "http://api.quran.com:3000/api/v3/options/translations").json()


def test_get_languages():
    assert qur.get_languages(language='ur') == rq.get(
        "http://api.quran.com:3000/api/v3/options/languages?language=bn").json(
Esempio n. 5
0
from quran import Quran
import time
from twitter import Twitter
from media import Media

# Changed english quran to indonesian quran

md = Media()
tw = Twitter()
quran = Quran()
surahs = quran.fetch_surah_data()

def start():
    while True:
        try:
            md.download_image()
            data = quran.get_ayah()
            surah_name = surahs[data["index_surah"]-1]["name"]
            print("Surah name is "+str(surah_name))
            ayah_text = data["ayah"]["text"]
            ayah_index = data["ayah"]["index"]
            print("Ayah ke "+str(ayah_index)+ " and isi "+ str(ayah_text))
            tweet_candidate = ayah_text + " [" + surah_name + " : " + str(ayah_index) + "]"
            if len(tweet_candidate) < 280:
                tw.api.update_status(tweet_candidate)
            else:
                md.process_image(ayah_text, surah_name, ayah_index)
                tw.post_tweet_with_media()

            time.sleep(14400)
        except Exception as ex:
Esempio n. 6
0
def serve(bot, update_id, data):
    interface = telegram.ReplyKeyboardMarkup(
        [["Arabic", "Audio", "English", "Tafsir"], ["Previous", "Random", "Next"]], resize_keyboard=True
    )

    def send_quran(s, a, quran_type, chat_id, reply_markup=None):
        if not (0 < s < 115 and 0 < a <= Quran.surah_lengths[s]):
            bot.sendMessage(chat_id=chat_id, text="Ayah does not exist!")
            return
        elif quran_type in ("english", "tafsir"):
            text = data[quran_type].getAyah(s, a)
            bot.sendMessage(chat_id=chat_id, text=text, reply_markup=reply_markup)
        elif quran_type == "arabic":
            bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO)
            image = "quran_images/" + str(s) + "_" + str(a) + ".png"
            upload_file(image, quran_type, chat_id=chat_id, caption="Quran %d:%d" % (s, a), reply_markup=reply_markup)
        elif quran_type == "audio":
            bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.UPLOAD_AUDIO)
            audio = "Husary/" + str(s).zfill(3) + str(a).zfill(3) + ".mp3"
            upload_file(
                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])

    def upload_file(filename, quran_type, **kwargs):
        def upload(f):
            if quran_type == "arabic":
                v = bot.sendPhoto(photo=f, **kwargs)["photo"][-1]["file_id"]
            elif quran_type == "audio":
                v = bot.sendAudio(audio=f, **kwargs)["audio"]["file_id"]
            save_file(filename, v)

        def upload_from_disk():
            with open(filename, "rb") as f:
                upload(f)

        f = get_file(filename)
        if f is not None:
            try:
                upload(f)
            except telegram.TelegramError as e:
                if "file_id" in e.message:
                    upload_from_disk()
                else:
                    raise e
        else:
            upload_from_disk()

    for update in bot.getUpdates(offset=update_id, timeout=10):
        chat_id = update.message.chat_id
        update_id = update.update_id + 1
        message = update.message.text.encode("utf-8").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: %s" % (chat_id, message))

        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:"
                    " 2 255. Then I respond with that ayah from the Noble "
                    "Quran. Or type: random."
                )
            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 the bot is available at: "
                    "https://github.com/rahiel/BismillahBot."
                )
            else:
                text = "Invalid command"
            bot.sendMessage(chat_id=chat_id, text=text)
            continue

        match = re.match("(\d+)[ :\-;.,]*(\d*)", message)
        if match is not None:
            s = int(match.group(1))
            a = int(match.group(2)) if match.group(2) else 1
            send_quran(s, a, quran_type, chat_id, reply_markup=interface)
        elif message in ("english", "tafsir", "audio", "arabic"):
            send_quran(s, a, message, chat_id)
        elif message in ("next", "previous", "random"):
            if message == "next":
                s, a = Quran.getNextAyah(s, a)
            elif message == "previous":
                s, a = Quran.getPreviousAyah(s, a)
            elif message == "random":
                s, a = Quran.getRandomAyah()
            send_quran(s, a, quran_type, chat_id)

    sys.stdout.flush()
    return update_id
Esempio n. 7
0
def serve(bot, data):
    global update_id

    def send_quran(s, a, quran_type, chat_id, reply_markup=None):
        if quran_type in ("english", "tafsir"):
            text = data[quran_type].getAyah(s, a)
            bot.sendMessage(chat_id=chat_id, text=text[:MAX_MESSAGE_LENGTH],
                            reply_markup=reply_markup)
        elif quran_type == "arabic":
            bot.sendChatAction(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.sendChatAction(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.getUpdates(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"].getAyah(s, a)
                tafsir = data["tafsir"].getAyah(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.answerInlineQuery(inline_query_id=query_id, cache_time=cache_time, results=results)
            continue

        if not update.message:  # weird Telegram update with only an update_id
            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

        # "special:quran_type"
        special_state = quran_type.split(':')

        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 Noble "
                        "Quran. Type /index to see all Surahs or try /random. "
                        "I'm available in any chat on Telegram, just type: <b>@BismillahBot</b>")
            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"]
            elif command == "feedback":
                text = ("Jazak Allahu khayran! Your feedback is highly "
                        "appreciated and will help us improve our services. "
                        "Your next message will be sent to the developers. "
                        "Send /cancel to cancel.")
                save_user(chat_id, (s, a, "feedback:" + quran_type))
            elif command == "cancel":
                text = ("Cancelled.")
                if len(special_state) > 1:
                    save_user(chat_id, (s, a, special_state[1]))
            else:
                text = None  # "Invalid command"
            if text:
                bot.sendMessage(chat_id=chat_id, text=text, parse_mode="HTML")
                continue

        if len(special_state) > 1:
            if special_state[0] == "feedback":
                with open("feedback.txt", 'a') as f:
                    f.write("%d: %s\n" % (chat_id, message))
                text = "Feedback saved 😊"
                bot.sendMessage(chat_id=chat_id, text=text)
                save_user(chat_id, (s, a, special_state[1]))
                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.getNextAyah(s, a)
            elif message == "previous":
                s, a = Quran.getPreviousAyah(s, a)
            elif message in ("random", "/random"):
                s, a = Quran.getRandomAyah()
            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.sendMessage(chat_id=chat_id, text="Ayah does not exist!")

    sys.stdout.flush()