def parent_login(bot, update, user_data): """ user_data dict contains ``Student_ID`` key from :py:func:`credentials`. Extracts DOB from ``update.message.text`` and checks validity using :py:func:`misbot.mis_utils.check_parent_login` before adding it to database. Finally, sends a message to the user requesting them to start using ``/attendance`` or ``/itinerary`` commands. """ DOB = update.message.text Student_ID = user_data['Student_ID'] chatID = update.message.chat_id if not check_parent_login(Student_ID, DOB): messageContent = textwrap.dedent(""" Looks like your Date of Birth details are incorrect! Give it one more shot. Send DOB in the below format: `DD/MM/YYYY` """) bot.sendMessage(chat_id=update.message.chat_id, text=messageContent, parse_mode='markdown') return new_user = Student_ID[3:-4].title() db_session.query(Chat).filter(Chat.chatID == chatID).update({'DOB': DOB}) db_session.commit() logger.info("New Registration! Username: {}".format((Student_ID))) messageContent = "Welcome {}!\nStart by checking your /attendance or /itinerary".format(new_user) bot.sendMessage(chat_id=update.message.chat_id, text=messageContent, parse_mode='markdown') return ConversationHandler.END
def input_target(bot, update): """If the user reply is a int/float and between 1-99, stores the figure as the new attendance target. :param bot: Telegram Bot object :type bot: telegram.bot.Bot :param update: Telegram Update object :type update: telegram.update.Update :return: ConversationHandler.END :rtype: int """ try: target_figure = float(update.message.text) except ValueError: bot.sendMessage(chat_id=update.message.chat_id, text="You must send a number between 1-99.") return if not 1 <= target_figure <= 99: bot.sendMessage(chat_id=update.message.chat_id, text="You must send a number between 1-99.") return db_session.query(Misc).filter( Misc.chatID == update.message.chat_id).update( {'attendance_target': target_figure}) db_session.commit() messageContent = "Your attendance target has been set to {}%.".format( target_figure) username = get_user_info(update.message.chat_id)['PID'] logger.info("Set attendance target for {} to {}%".format( username, target_figure)) bot.sendMessage(chat_id=update.message.chat_id, text=messageContent) return ConversationHandler.END
def confirm_revert(bot, update, user_data): """If Yes, revert the specified message for all users and send a summary of the operation to admin. :param bot: Telegram Bot object :type bot: telegram.bot.Bot :param update: Telegram Update object :type update: telegram.update.Update :param user_data: Conversation data :type user_data: dict """ reply_markup = ReplyKeyboardRemove() if update.message.text == "Yes": try: notification_message = PushMessage.query.filter( PushMessage.uuid == user_data['uuid']).first().text except AttributeError: bot.sendMessage(chat_id=update.message.chat_id, text="Unknown UUID. Try again.", reply_markup=reply_markup) return ConversationHandler.END notifications = PushNotification.query.filter(and_(PushNotification.message_uuid == user_data['uuid'],\ PushNotification.sent == True)) user_list = [notification.chatID for notification in notifications] message_ids = [ notification.message_id for notification in notifications ] time_taken = delete_threaded(message_ids, user_list) notification_message_short = textwrap.shorten(notification_message, width=20, placeholder='...') stats_message = textwrap.dedent(""" Deleted the notification: ``` {} ``` {} messages deleted in {:.2f}secs. """.format(notification_message_short, len(message_ids), time_taken)) bot.sendMessage(chat_id=update.message.chat_id, text=stats_message, parse_mode='markdown', reply_markup=reply_markup) db_session.query(PushMessage).filter( PushMessage.uuid == user_data['uuid']).update({'deleted': True}) db_session.commit() return ConversationHandler.END elif update.message.text == "No" or update.message.text == "/cancel": bot.sendMessage(chat_id=update.message.chat_id, text="Revert Aborted!", reply_markup=reply_markup) return ConversationHandler.END return
def clean_attendance_records(): """Delete all lectures and practical records from the DB. To be used at the beginning of a new semester so that ``/bunk`` command doesn't display lectures of previous semester(s). :return: Number of records deleted from Lecture and Practical tables. :rtype: tuple """ lecture_records = db_session.query(Lecture).delete() practical_records = db_session.query(Practical).delete() db_session.commit() return lecture_records, practical_records
def update_target(bot, update): """Takes the sent figure and sets it as new attendance target. :param bot: Telegram Bot object :type bot: telegram.bot.Bot :param update: Telegram Update object :type update: telegram.update.Update :return: ConversationHandler.END :rtype: int """ user_reply = update.message.text if user_reply == '/cancel': bot.sendMessage(chat_id=update.message.chat_id, text="As you wish! The operation is cancelled!") return ConversationHandler.END try: new_target = int(user_reply) except ValueError: bot.sendMessage(chat_id=update.message.chat_id, text="You must send a number between 1-99.") return if not 1 <= new_target <= 99: bot.sendMessage(chat_id=update.message.chat_id, text="You must send a number between 1-99.") return old_target = get_misc_record(update.message.chat_id).attendance_target db_session.query(Misc).filter( Misc.chatID == update.message.chat_id).update( {'attendance_target': new_target}) db_session.commit() username = get_user_info(update.message.chat_id)['PID'] logger.info("Modified attendance target for {} to {}%".format( username, new_target)) new_target_message = "Your attendance target has been updated to {}%!".format( new_target) bot.sendMessage(chat_id=update.message.chat_id, text=new_target_message) mp.track(username, 'Edit Attendance Target', { 'new_target': new_target, 'old_target': old_target }) return ConversationHandler.END
def bunk_lecture(n, tot_lec, chatID): init_db() record = db_session.query(Attendance).filter( Attendance.chatID == chatID).first() attended = record.total_lec_attended conducted = record.total_lec_conducted result = (((int(attended) + int(tot_lec)) - int(n)) / (int(conducted) + tot_lec)) * 100 return round(result, 2) #Round up to 2 decimals.
def delete(bot, update): """Delete a user's credentials if they wish to stop using the bot or update them.""" chatID = update.message.chat_id user_details = db_session.query(Chat).filter(Chat.chatID == chatID).first() #Pull user's username from the DB username = user_details.PID logger.info("Deleting user credentials for {}!".format(username)) Chat.query.filter(Chat.chatID == chatID).delete() #Delete the user's record referenced by their ChatID db_session.commit() #Save changes messageContent = "Your credentials have been deleted, {}\nHope to see you back soon.".format(username[3:-4].title()) bot.sendMessage(chat_id=update.message.chat_id, text=messageContent)
def until80(chatID): init_db() record = db_session.query(Attendance).filter( Attendance.chatID == chatID).first() attended = record.total_lec_attended conducted = record.total_lec_conducted x = Symbol('x') expr = Eq((((int(attended) + x) / (int(conducted) + x)) * 100), 80) soln = solveset(expr, x) return next(iter(soln)) # Extracting the integer from singleton set soln.
def process_item(self, item, spider): #Initiate DB init_db() if not Attendance.query.filter( Attendance.chatID == spider.chatID).first(): record = Attendance( total_lec_attended=item['total_lec_attended'], total_lec_conducted=item['total_lec_conducted'], chatID=spider.chatID) db_session.add(record) db_session.commit() else: db_session.query(Attendance).filter(Attendance.chatID == spider.chatID).\ update({'total_lec_attended': item['total_lec_attended'], 'total_lec_conducted':item['total_lec_conducted']}) db_session.commit() return item
def process_item(self, item, spider): if not isinstance(item, Practicals): return item #Do nothing for Lectures Items (NOT Practicals) if not Practical.query.filter( and_(Practical.chatID == spider.chatID, Practical.name == item['subject'])).first(): record = Practical(name=item['subject'], chatID=spider.chatID, attended=item['attended'], conducted=item['conducted']) db_session.add(record) db_session.commit() else: db_session.query(Practical).filter(and_(Practical.chatID == spider.chatID, Practical.name == item['subject'])).\ update({'attended': item['attended'], 'conducted':item['conducted']}) db_session.commit() return item
def delete(bot, update): """Delete a user's credentials if they wish to stop using the bot.""" chatID = update.message.chat_id if not Chat.query.filter(Chat.chatID == chatID).first(): bot.sendMessage(chat_id=update.message.chat_id, text="Unregistered!") return user_details = db_session.query(Chat).filter( Chat.chatID == chatID).first() #Pull user's username from the DB username = user_details.PID logger.info("Deleting user credentials for %s!" % (username)) Chat.query.filter(Chat.chatID == chatID).delete( ) #Delete the user's record referenced by their ChatID db_session.commit() #Save changes bot.sendMessage(chat_id=update.message.chat_id, text="Your credentials have been deleted, %s\nHope to see you back soon." \ % (username[3:-4].title()))