예제 #1
0
def remove_user(bot, update):
    try:
        uid = update.message.from_user.id
        print(db_interface.user_exist(uid))
        if db_interface.user_exist(uid):
            delete_result = db_interface.delete_user(uid)
            message_array = []
            if delete_result.deleted_count == 1:
                message_array.append(
                    f"Details for {uid} has been removed from the database\n"
                )
                message_array.append("You can now register again using /register")
            else:
                message_array.append(
                    "An Unknown error has occured! Kindly inform @fatalityx"
                )
            message = "".join(message_array)
            update.message.reply_text(message, parse_mode="Markdown")
        else:
            message_array = [
                f"Unable to find your telegram ID {uid} in the database!\n"
            ]
            message_array.append("Are you sure you didn't mean to register instead?")
            message = "".join(message_array)
            update.message.reply_text(message, parse_mode="Markdown")
    except Exception as e:
        print(str(e))  # To be changed.
        return ConversationHandler.END
예제 #2
0
def toggle_night(bot, update):
    uid = update.message.from_user.id
    config = Configuration()
    try:
        if db_interface.user_exist(uid):
            if db_interface.toggle_alert(uid, False):
                message = "Nightly alert has been sucessfully *enabled*!"
            else:
                message = "Nightly alert has been sucessfully *disabled*!"
            update.message.reply_text(message, parse_mode="Markdown")
        else:
            message_array = ["You are not registered!\n"]
            message_array.append("Would you like to register using /register?")
            message = "".join(message_array)
            update.message.reply_text(message, parse_mode="Markdown")
    except Exception as e:
        local = arrow.utcnow().to("Asia/Singapore")
        local_time = local.format("YYYY-MM-DD HH:mm:ss ZZ")
        bot.send_message(chat_id=config.ERROR_CHANNEL,
                         text=f"An error occured at {local_time}")
        bot.send_message(
            chat_id=config.ERROR_CHANNEL,
            text=f"The error was: {traceback.format_exc()}",
        )
        bot.send_message(
            chat_id=config.ERROR_CHANNEL,
            text=
            f"This message was triggered in nightly reminder toggle. Triggered by: {uid}",
        )
예제 #3
0
def get_today(bot, update):
    uid = update.message.from_user.id
    config = Configuration()

    try:
        if db_interface.user_exist(uid):
            current_date = datetime.now(pytz.timezone("Asia/Singapore")).date()
            # sets time to midnight.
            current_date = datetime.combine(current_date, time())
            # gets a list of IndividualClassStructure objects.
            classes_list = db_interface.get_current_class(
                uid, current_date, current_date)
            # sorts by start time
            classes_list.sort(key=lambda x: x.start_time)
            lsd = db_interface.get_last_sync_date(uid)

            mt = MessageTimetable(None, lsd)
            for c in classes_list:
                mt.add_class_list(c.class_numeric_day, c)
            formatted_message = mt.get_today()

            update.message.reply_text(
                formatted_message,
                disable_web_page_preview=True,
                quote=True,
                parse_mode="Markdown",
            )

        else:
            message_array = [
                f"Unable to find telegram ID {uid} in our database\n"
            ]
            message_array.append(
                "Kindly register using /register before attempting to retrieve a timetable."
            )
            message = "".join(message_array)
            update.message.reply_text(message, parse_mode="Markdown")

    except Exception as e:
        print(str(e))
        local = arrow.utcnow().to("Asia/Singapore")
        local_time = local.format("YYYY-MM-DD HH:mm:ss ZZ")
        bot.send_message(chat_id=config.ERROR_CHANNEL,
                         text=f"An error occured at {local_time}")
        bot.send_message(
            chat_id=config.ERROR_CHANNEL,
            text=f"The error was: {traceback.format_exc()}",
        )
        bot.send_message(
            chat_id=config.ERROR_CHANNEL,
            text=f"This message was triggered in get today timetable by {uid}.",
        )
예제 #4
0
def start_register(bot, update):
    """
    Kickstarts registeration process. Gets name and 
    subsequently passes it to the next handler in process.
    """
    try:
        config = Configuration()
        # gets the telegram ID
        tg_id = update.message.from_user.id
        # Checks the database for the user ID
        message_array = []
        if not db_interface.user_exist(tg_id):
            r = config.REDIS_INSTANCE
            if not r.get(tg_id):
                message_array.append(
                    "Hi! Let's get started by registering with this bot\n"
                )
                message_array.append(
                    "❇️By using this bot, you hereby declare that you have read the documentation and disclaimer on github.\n"
                )
                message_array.append(
                    "❇️*As such, you release the author from any responsibilities of events incurred by the usage of this bot*\n"
                )
                message_array.append(
                    "❇️At any point of time during this process, you can stop the bot by typing /cancel\n"
                )
                message_array.append("Now, can I have your *name*?")
                message = "".join(message_array)
                update.message.reply_text(message, parse_mode="Markdown")
                # instructs the chatbox to move to the next method.
                return NAME
            else:
                message_array.append("You are already enqueued!\n")
                message_array.append(
                    "If you are encountering issues, please pm @fatalityx directly."
                )
                message = "".join(message_array)
                update.message.reply_text(message, parse_mode="Markdown")
                return ConversationHandler.END
        else:
            message_array.append("You are already registered!\n")
            message_array.append(
                "If you have forgotten your application key, please use /forget to clear your information and re-register."
            )
            message = "".join(message_array)
            update.message.reply_text(message, parse_mode="Markdown")
            return ConversationHandler.END

    except Exception as e:
        print(str(e))  # To be changed.
        return ConversationHandler.END
예제 #5
0
def get_ics(bot, update):
    print("Get ICS method called")
    config = Configuration()
    is_callback = False
    if not update.message:
        uid = update.callback_query.from_user.id
        is_callback = True
    else:
        uid = update.message.from_user.id
    try:
        if db_interface.user_exist(uid):
            print("DB Interface exists")
            filepath = f"./ics/{uid}.ics"
            # Gets a list of classes
            classes_list = db_interface.get_all_classes(uid)
            print(classes_list)
            ics_model = ICSParser(classes_list)
            ics_model.convert_to_event()
            with open(filepath, "w") as f:
                f.writelines(ics_model.calendar)

            # sends the message
            bot.send_document(chat_id=uid, document=open(filepath, "rb"))
        else:
            message_array = [
                f"Unable to find telegram ID {uid} in our database\n"
            ]
            message_array.append(
                "Kindly register using /register before attempting to retrieve a timetable."
            )
            message = "".join(message_array)
            update.message.reply_text(message, parse_mode="Markdown")

    except Exception as e:
        print(str(e))
        local = arrow.utcnow().to("Asia/Singapore")
        local_time = local.format("YYYY-MM-DD HH:mm:ss ZZ")
        bot.send_message(chat_id=config.ERROR_CHANNEL,
                         text=f"An error occured at {local_time}")
        bot.send_message(
            chat_id=config.ERROR_CHANNEL,
            text=f"The error was: {traceback.format_exc()}",
        )
        bot.send_message(
            chat_id=config.ERROR_CHANNEL,
            text=f"This message was triggered in get timetable by {uid}.",
        )
예제 #6
0
def update(bot, update):
    """
    confirms that the update is meant to be handled.
    """
    config = Configuration()
    try:
        uid = update.message.from_user.id
        if not db_interface.user_exist(uid):
            update.message.reply_text("You are not registered! Please register first")
            return ConversationHandler.END
        r = config.REDIS_INSTANCE
        if r.get(uid):
            update.message.reply_text("You are already enqueued in the queue!")
            return ConversationHandler.END
        message_array = ["Do you want to update your timetable?\n"]
        message_array.append("❇️This will erase *all* previous timetable schedules\n")
        message_array.append("❇️Please reply with a yes or no\n")
        message_array.append("❇️To exit this state, please use /cancel\n")
        message = "".join(message_array)
        update.message.reply_text(message, parse_mode="Markdown")
        return ENTERKEY

    except Exception as e:
        local = arrow.utcnow().to("Asia/Singapore")
        local_time = local.format("YYYY-MM-DD HH:mm:ss ZZ")
        bot.send_message(
            chat_id=config.ERROR_CHANNEL, text=f"An error occured at {local_time}"
        )
        bot.send_message(
            chat_id=config.ERROR_CHANNEL,
            text=f"The error was: {traceback.format_exc()}",
        )
        bot.send_message(
            chat_id=config.ERROR_CHANNEL,
            text=f"This message was triggered in get timetable by {uid}.",
        )
        return ConversationHandler.END
예제 #7
0
def get_timetable(bot, update):
    config = Configuration()
    is_callback = False
    if not update.message:
        uid = update.callback_query.from_user.id
        is_callback = True
    else:
        uid = update.message.from_user.id
    try:
        if db_interface.user_exist(uid):
            # if its not a callback type:
            if not is_callback:
                current_date = date.today()
                # sets time to midnight.
                current_date = datetime.combine(current_date, time())
            else:  # if it is a callback
                query = update.callback_query
                current_date = datetime.strptime(query.data[2:], "%b%d%Y")

            start_date = current_date - timedelta(days=current_date.weekday())
            end_date = start_date + timedelta(days=6)

            # gets a list of IndividualClassStructure objects.
            classes_list = db_interface.get_current_class(
                uid, start_date, end_date)
            # sorts by start time
            classes_list.sort(key=lambda x: x.start_time)
            lsd = db_interface.get_last_sync_date(uid)

            # prepares the message timetable object
            cur_week = datetime.strftime(
                (current_date - timedelta(days=current_date.weekday())),
                "%b %d %Y")
            print(cur_week)
            mt = MessageTimetable(cur_week, lsd)
            for c in classes_list:
                mt.add_class_list(c.class_numeric_day, c)
            formatted_message = mt.get_message()

            # prepares the keyboard.
            reply_kb = get_keyboard(uid, current_date, start_date, end_date)
            reply_markup = InlineKeyboardMarkup(reply_kb)
            # sends the message
            if is_callback:
                bot.edit_message_text(
                    text=formatted_message,
                    chat_id=update.callback_query.message.chat_id,
                    message_id=update.callback_query.message.message_id,
                    disable_web_page_preview=True,
                    reply_markup=reply_markup,
                    parse_mode="Markdown",
                )
            else:
                update.message.reply_text(
                    formatted_message,
                    reply_markup=reply_markup,
                    disable_web_page_preview=True,
                    quote=True,
                    parse_mode="Markdown",
                )
        else:
            message_array = [
                f"Unable to find telegram ID {uid} in our database\n"
            ]
            message_array.append(
                "Kindly register using /register before attempting to retrieve a timetable."
            )
            message = "".join(message_array)
            update.message.reply_text(message, parse_mode="Markdown")

    except Exception as e:
        print(str(e))
        local = arrow.utcnow().to("Asia/Singapore")
        local_time = local.format("YYYY-MM-DD HH:mm:ss ZZ")
        bot.send_message(chat_id=config.ERROR_CHANNEL,
                         text=f"An error occured at {local_time}")
        bot.send_message(
            chat_id=config.ERROR_CHANNEL,
            text=f"The error was: {traceback.format_exc()}",
        )
        bot.send_message(
            chat_id=config.ERROR_CHANNEL,
            text=f"This message was triggered in get timetable by {uid}.",
        )