def IsFreeCommand(self, chat_id): try: start_date_query, end_date_query = self.str_text.split(';') except: raise err.ParseError # Call the GoogleAPI class and check isFree try: query = gc.GoogleAPI().FreeBusyQuery(start_date_query, end_date_query) isFree = gc.GoogleAPI().isFree(query) except: raise err.QueryError self.bot.sendMessage(chat_id, isFree) # Get the query's busy info if not isFree: info_busy = gc.GoogleAPI().BusyInfo(query) self.bot.sendMessage(chat_id, 'You are busy on this time interval!') self.bot.sendMessage(chat_id, "You have %d event(s) occuring between %s and %s" %(len(info_busy), start_date_query, end_date_query)) for i in range(len(info_busy)): # Ignoring timezones ignored_tz_start_busy = hc.StringParseGoogleAPI(info_busy[i]['start']).IgnoreTimeZone() ignored_tz_end_busy = hc.StringParseGoogleAPI(info_busy[i]['end']).IgnoreTimeZone() # Make these pretty start_busy_pretty = ignored_tz_start_busy.strftime('%Y-%m-%d %H:%M') end_busy_pretty = ignored_tz_end_busy.strftime('%Y-%m-%d %H:%M') # Send message to user self.bot.sendMessage(chat_id, "%d. %s until %s" %(i + 1, start_busy_pretty, end_busy_pretty)) raise err.IsNotFreeError return isFree
def AddIndexCommand(self, str_text): str_input = hc.StringParseIndex(str_text) str_input.Parse() course_name = str_input.course_name course_type = str_input.course_type index = str_input.index hc.splintergetdata().start(course_name, course_type, index)
def getUpcomingEvent(self, chat_id): num_event = int(self.str_text) self.bot.sendMessage(chat_id, 'Getting %s upcoming event(s) for you' %(num_event)) events = gc.GoogleAPI().getUpcomingEventList(num_event) event_detail_list = [] inlines_keyboard = [] for event in events: # Getting the start, end, and summary start = event['start']['dateTime'] end = event['end']['dateTime'] summary = event['summary'] # Ignoring their timezones ignore_tz_start = hc.StringParseGoogleAPI(start).IgnoreTimeZone() ignore_tz_end = hc.StringParseGoogleAPI(end).IgnoreTimeZone() # Making these pretty ignore_tz_start_pretty = ignore_tz_start.strftime('%Y-%m-%d %H:%M') ignore_tz_end_pretty = ignore_tz_end.strftime('%Y-%m-%d %H:%M') # Combining all complete_event = summary + ' (' + ignore_tz_start_pretty + ' until ' + ignore_tz_end_pretty + ')' event_detail_list.append(complete_event) # Preparing inline keyboard for event_detail in event_detail_list: inlines_keyboard.append([InlineKeyboardButton(text=event_detail, callback_data=event_detail)]) keyboard = InlineKeyboardMarkup(inline_keyboard=inlines_keyboard) # Send the message to user self.bot.sendMessage(chat_id, 'Here they are!', reply_markup=keyboard)
def PreCreateEventIndex(self, evt_list): """Description: preparation to add the event from evt_list to Google Calendar""" for i in range(len(evt_list)): event1 = evt_list[i] course_index = event1[0] course_type = event1[1] course_group = event1[2] day = event1[3] start_time = event1[4][0] end_time = event1[4][1] location = event1[5] recurrence = event1[6] first_week = db.DB().table_query(self.chat_id, first_week=True)[0] first_recess_week = db.DB().table_query(self.chat_id, first_recess_week=True)[1] # Concatenate together event_summary = " ".join([course_code, course_type]) event_desc = " ".join([course_index, course_group]) ignore_first_event = False if day != 'MO': if recurrence.count('1') != 0 or recurrence != '' or recurrence.count('1') == 0: ignore_first_event = True # Recurrence Parsing recurrenceObject = hc.StringParseGoogleAPI(recurrence) recurrence_string = recurrenceObject.ParseOccurIgnoreWeek(first_week, start_time) # CreateEventIndex gc.GoogleAPI().CreateEventIndex(self.chat_id, event_summary, location, event_desc, start_time, end_time, first_week, first_recess_week, recurrence_string, day, ignore_first_event)
def pushButtonRegister_clicked(self): if HelperClass.IsFaculty_IDTaken(self.textEdit.toPlainText()): QMessageBox.question(self, 'Faculty ID Taken!', "Faculty ID is already taken!", QMessageBox.Ok) else: cnx = mysql.connector.connect(user='******', password='******', host='localhost', database='inventory_system') cursor = cnx.cursor() query = ( "INSERT INTO faculty " "(faculty_id, first_name, last_name, middle_name, birthdate, username, password, gender_id, position_id, inventory_id) " "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)") employeeDetails = (self.textEdit.toPlainText(), self.textEdit_2.toPlainText(), self.textEdit_3.toPlainText(), self.textEdit_4.toPlainText(), date(1969, 6, 12), 'facultyDefault', 'password123', 0, 0, 0) cursor.execute(query, employeeDetails) QMessageBox.question(self, 'Success!', "Faculty Registered!", QMessageBox.Ok) cnx.commit() cursor.close() cnx.close() self.pushButtonBack_clicked()
def resolve_message(data): print(" [x] Receiving message %r" % data) analysisTask = HelperClass() decoded_csv = analysisTask.decodeCsv(data) # turn csv file into DF df = analysisTask.csvToDF(decoded_csv) logger.info('DF has been created') # do statistical overview task = TrafficOverviewStatistics() renamed_DF = task.renameColumns(df) stats = task.ALL_describe(renamed_DF) print(stats) logger.info('Statistical overview for DF has been supplied')
def pushButtonDone_clicked(self): if HelperClass.IsFaculty_IDTaken(self.editID.toPlainText( )) and self.editID.toPlainText() != str(self.faculty_ID): QMessageBox.question(self, 'Faculty ID Taken!', "Faculty ID is already taken!", QMessageBox.Ok) else: cnx = mysql.connector.connect(user='******', password='******', host='localhost', database='inventory_system') cursor = cnx.cursor() query = ( "UPDATE faculty " "SET faculty_id = %s, first_name = %s, middle_name = %s, last_name = %s " "WHERE faculty_id = %s") employeeDetails = (self.editID.toPlainText(), self.editFirst.toPlainText(), self.editMiddle.toPlainText(), self.editLast.toPlainText(), self.faculty_ID) cursor.execute(query, employeeDetails) QMessageBox.question(self, 'Success!', "Faculty Details Edited!", QMessageBox.Ok) cnx.commit() cursor.close() cnx.close() self.dialogBack = MemberDetails(self.faculty_ID) self.dialogBack.show() self.close()
def SetStudentType(self, chat_id): str_input = hc.StringParseStudentType(self.str_text) str_input.ParseInput() # print(self.str_text) course_type = str_input.course_type print(course_type) excel = db.DB() excel.update(chat_id, student_type=course_type)
def CreateEventCommand(self): str_input = hc.StringParseGoogleAPI(self.str_text) str_input.ParseEvent() event_name = str_input.event_name location = str_input.location start_date = str_input.start_date end_date = str_input.end_date # Call the GoogleAPI class and create event gc.GoogleAPI().createEvent(event_name, location, start_date, end_date)
def FreeBusyQuery(self, str_date_start, str_date_end): # str_date --> yyyy-mm-dd hh:mm # Parsing date iso_date_start = hc.StringParseGoogleAPI(str_date_start).ParseDate() iso_date_end = hc.StringParseGoogleAPI(str_date_end).ParseDate() # query details query = { 'timeMin': iso_date_start, 'timeMax': iso_date_end, 'timeZone': 'Asia/Singapore', 'items': [{ 'id': 'primary' }] } query = self.service.freebusy().query(body=query).execute() return query
def resolve_message(data): print(" [x] Receiving message %r" % data) analysisTask = HelperClass() # decode csv file decoded_csv = analysisTask.decodeCsv(data) # turn csv file into DF df = analysisTask.csvToDF(decoded_csv) logger.info('DF has been created') # do statistical overview task = TrafficFilterLargest() renamed_DF = task.renameColumns(df) filter = task.popularParkingbyID(renamed_DF) print('Print filter: ') print(filter) logger.info('Filter has been applied to the data set')
def pushButtonLogin_clicked(self): loginSuccess = HelperClass.CheckLoginCredentials( self.textUsername.toPlainText(), self.textPassword.text()) if loginSuccess: self.close() self.dialog.show() else: QMessageBox.question(self, 'Login Failed!', "Incorrect login credentials!", QMessageBox.Ok)
def FreeBusyQuery(self, str_date_start, str_date_end): # str_date --> yyyy-mm-dd hh:mm credentials = self.get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', 'v3', http=http) # Parsing date iso_date_start = hc.StringParseGoogleAPI(str_date_start).ParseDate() iso_date_end = hc.StringParseGoogleAPI(str_date_end).ParseDate() # query details query = { 'timeMin': iso_date_start, 'timeMax': iso_date_end, 'timeZone': 'Asia/Singapore', 'items': [ { 'id': 'primary' } ] } query = service.freebusy().query(body=query).execute() return query
def IsFreeCommand(self): str_input = hc.StringParseGoogleAPI(self.str_text) str_input.ParseDateRange() start_date_query = str_input.start_date end_date_query = str_input.end_date # Call the GoogleAPI class and check isFree query = gc.GoogleAPI().FreeBusyQuery(start_date_query, end_date_query) isFree = gc.GoogleAPI().isFree(query) # Get the query's busy info if not isFree: info_busy = gc.GoogleAPI().BusyInfo(query) self.start_busy = info_busy[0] self.end_busy = info_busy[1] return isFree
def resolve_message(dataOne, dataTwo): print(" [x] Receiving message %r") analysisTask = HelperClass() dataWeather = analysisTask.decodeCsv(dataOne) dfWeather = analysisTask.csvToDF(dataWeather) print('Print DF: ') print(dfWeather) analysisTask = HelperClass() dataTraffic = analysisTask.decodeCsv(dataTwo) dfTraffic = analysisTask.csvToDF(dataTraffic) print('Print DF: ') print(dfTraffic) task = TrafficWeatherJoin() weatherPrep_DF = task.weather_API_dataPrep(dfWeather) trafficPrep_DF = task.traffic_dataPrep(dfTraffic) task.mergeDatasetsNew(weatherPrep_DF, trafficPrep_DF)
def __init__(self): self.helperObj = HC.HelperClass() self.htmlstrip = mls.MLStripper() self.wordnet_lemmatizer = WordNetLemmatizer() self.coOccMatrixBody = None self.coOccMatrixTitle = None self.wordList = None self.tagsList = None self.tagsPrior = None self.baseLevel = None self.strengthAssoBody = None self.strengthAssoTitle = None self.scaledEntropyBody = None self.scaledEntropyTitle = None self.weightBody = 1.75 self.weightTitle = 0.93 self.attentionWeightBody = None self.attentionWeightTitle = None self.tagActivationWeight = None
def predictLongTermValue(self): #Step 1. Parse all the input files print(Files.InputFiles) helperObj = HC.HelperClass() for file in Files.InputFiles.keys(): try: helperObj.ParseFile(Files.InputFiles[file], file ) except: print("Error Parsing File") helperObj.PairCommentWithPosts() #Step 2. Create Question Answer Pairs questionAnswerPairs = helperObj.CreateQuestionAnswerPair() # Step 3. We have created Q/A pairs. Now we need to extract the features. hourList = [1,6,12,24] hourFeaturePair = {} for hour in hourList: helperObj.CreateLabels() featureList = helperObj.ExtractAllFeatures(hour) hourFeaturePair[hour] = featureList # Step 4: Create csv files csvGenerator = Csvgenerator.CsvGenerator(hourFeaturePair) csvGenerator.generate_standardized_data() csvGenerator.genrate_csv() c = 20 #Predict the long term value VCC.vcClassifier('LTV',8)
def __init__(self, str_text): super().__init__() self.command_list = [ '/start', '/help', '/quit', '/isfree', '/getupcomingevent', '/addevent', '/removeevent', '/getevent', '/addcourse', '/removecourse', '/getcourse', '/setstudenttype', '/addfirstweek', ] self.str_text = str_text # Updatable self._start_busy = None self._end_busy = None self.getdata = hc.splintergetdata() # property not yet added!!!
def get_event(self): """Description: Get each a list event data from the parsed HTML Return: list """ value_list = list(self.index_dictionary.values()) key_list = list(self.index_dictionary.keys()) event_list = [[] for event in range(len(value_list[0]))] # initialize list of lists ParseObject = hc.StringParseGoogleAPI(self.index_dictionary) for i in range(len(value_list[0])): # Change the time format time = self.index_dictionary['time'][i] formated_time = ParseObject.ParseDateIndex(time) self.index_dictionary['time'][i] = formated_time # Change the day format day = self.index_dictionary['day'][i] # Setting the value ParseObject.day = day # Assign it to the list self.index_dictionary['day'][i] = ParseObject.day for key in key_list: event_list[i].append(self.index_dictionary[key][i]) return event_list
def handleAPI(self, msg): content_type, self.chat_type, chat_id = telepot.glance(msg) print(content_type, self.chat_type, chat_id) # debug msg received response = self.bot.getUpdates() self.StoreChat(response) if content_type == 'text': # Convert the message to lower case msg_received = msg['text'].lower() # If the message is a valid command if BotCommand(msg_received).isValidCommand(): if msg_received == '/start': self.bot.sendMessage(chat_id, "Hi! I'm a bot that tells you your course schedule and plan your meetings! Feel free to ask me stuff :)") self.bot.sendMessage(chat_id, "If you want to know your course schedule, type in Course. If you want to plan your meetings, type in Meetings. If you want to know anything about me, just type in whatever you want and hope I understand :)") elif msg_received == '/createevent': msg_reply = "Okay send me the details in following format:" str_format = "Event Name;location;yyyy-mm-ddThh:mm;yyyy-mm-ddThh:mm" self.bot.sendMessage(chat_id, msg_reply) self.bot.sendMessage(chat_id, str_format) print(response) elif msg_received == '/addindex': msg_reply = "Sure thing. Please type your details in following format: \n" str_format = "Course Name;Course Type(Full/Part Time);Index Number" self.bot.sendMessage(chat_id,msg_reply) self.bot.sendMessage(chat_id, str_format) print(response) elif msg_received == '/quit': self.bot.sendMessage(chat_id, "Bye :(") elif msg_received == '/isfree': self.bot.sendMessage(chat_id, "Please enter the date interval using the following format: ") self.bot.sendMessage(chat_id, "YYYY-MM-DD HH:MM;YYYY-MM-DD HH:MM") else: self.bot.sendMessage(chat_id, "Command not updated!") else: # Execute the command further # Create the Command Object first BotCommandObject = BotCommand(msg['text']) # This checks if the last msg['text'] is indeed a command if self.list_update_message[-2] == '/createevent': try: BotCommandObject.CreateEventCommand() except: self.bot.sendMessage(chat_id, 'Cannot create event! Make sure to enter the correct format!') else: self.bot.sendMessage(chat_id, 'Successful!') elif self.list_update_message[-2] == '/isfree': try: isFree = BotCommandObject.IsFreeCommand() except: self.bot.sendMessage(chat_id, 'Cannot check! Make sure to enter the correct format!') else: self.bot.sendMessage(chat_id, isFree) if isFree: self.bot.sendMessage(chat_id, 'You are free on this time interval') else: start_busy = BotCommandObject.start_busy end_busy = BotCommandObject.end_busy self.bot.sendMessage(chat_id, 'You are busy on this interval!') self.bot.sendMessage(chat_id, 'You have an event from %s to %s' % (start_busy, end_busy)) elif self.list_update_message[-2] == '/addindex': self.bot.sendMessage(chat_id, 'Please wait while we process your information. This may take around a minute.\n') self.bot.sendMessage(chat_id, 'To prevent crashing, please wait until the Success message has appeared.\n') try: BotCommand().AddIndexCommand(msg['text']) except: self.bot.sendMessage(chat_id, 'Cannot add index! Make sure you have entered the correct format!') else: self.bot.sendMessage(chat_id, "Successfully added! :)") else: # Below is not a command. It only makes the bot smarter # manual emoticons ONLY :p if msg_received[0] == ':': if len(msg_received) <= 3: self.bot.sendMessage(chat_id, msg['text']) else: self.bot.sendMessage(chat_id, "What is that??? .-.") elif msg_received.find('rude') != -1: self.bot.sendMessage(chat_id, BotReply().reply_dict['rude']) # If the bot knows reply the message elif BotReply().isValidtoReply(msg_received): print(BotReply().reply_dict[msg_received]) # With name? if BotReply().isWithName(msg_received): self.bot.sendMessage(chat_id, BotReply().reply_dict[msg_received] +', ' + msg['chat']['first_name']+' !') elif msg_received == 'meetings': self.bot.sendMessage(chat_id, BotReply().reply_dict[msg_received]) inlines_keyboard = [] for i in range(len(hc.PreformattedBotInlineMarkup().days)): # print(hc.PreformattedBotInlineMarkup().days[i]) inlines_keyboard.append([InlineKeyboardButton(text=hc.PreformattedBotInlineMarkup().days[i], callback_data=hc.PreformattedBotInlineMarkup().days[i])]) # print(inlines_keyboard) keyboard = InlineKeyboardMarkup(inline_keyboard=inlines_keyboard) self.bot.sendMessage(chat_id, 'Choose a day!', reply_markup=keyboard) else: self.bot.sendMessage(chat_id, BotReply().reply_dict[msg_received]) else: self.bot.sendMessage(chat_id, "Sorry, I don't know what to reply such conversation yet. :'(")
def CreateEventIndex(self, chat_id, summary, location, desc, start_time, end_time, first_week, first_recess_week, recurrence, day, is_ignore_first_event=False): # First Instance of the course # first_event's start_time first_event_start_str = first_week + 'T' + start_time # to avoid ambiguity first_event_start_obj = datetime.datetime.strptime( first_event_start_str, '%Y-%m-%dT%H:%M:%S') first_event_start_iso = first_event_start_obj.isoformat() first_event_ugly_start = first_event_start_obj.strftime( "%Y%m%dT%H%M%S") # first_event's end_time first_event_end_str = first_week + 'T' + end_time first_event_end_obj = datetime.datetime.strptime( first_event_end_str, '%Y-%m-%dT%H:%M:%S') first_event_end_iso = first_event_end_obj.isoformat() # The recess week first_recess_week_str = first_recess_week + 'T' + start_time first_recess_week_obj = datetime.datetime.strptime( first_recess_week_str, '%Y-%m-%dT%H:%M:%S') # Ignore recess week ParseObject = hc.StringParseGoogleAPI(start_time) ignore_recess_week = ParseObject.ParseDateWeek(first_recess_week_obj) # ignore the first event ignore_first_event = "" # Comma Issues if is_ignore_first_event: if recurrence != '': ignore_first_event = ',' + first_event_ugly_start + ',' else: ignore_first_event = ',' + first_event_ugly_start else: recurrence = ',' + recurrence final_week_obj = datetime.datetime.strptime( first_week, '%Y-%m-%d') + datetime.timedelta(days=7 * 13 + 5) final_week_str = final_week_obj.strftime("%Y%m%d") # Event Details event = { 'summary': summary, 'location': location, 'description': desc, 'start': { 'dateTime': first_event_start_iso, 'timeZone': 'Asia/Singapore', }, 'end': { 'dateTime': first_event_end_iso, 'timeZone': 'Asia/Singapore', }, 'reminders': { 'useDefault': False, 'overrides': [{ 'method': 'popup', 'minutes': 60 }], }, 'recurrence': [ "EXDATE;TZID=Asia/Singapore;VALUE=DATE:" + ignore_recess_week + ignore_first_event + recurrence, "RRULE:FREQ=WEEKLY;UNTIL=" + final_week_str + ";BYDAY=" + day ] } event = self.service.events().insert(calendarId='primary', body=event).execute() print('Event created: %s' % (event.get('htmlLink'))) event_id = event['id'] print(event_id) course_code, course_type = summary.split(' ') db.DB().UpdateCourseCodeEventId(chat_id, course_code, event_id)
def AddEventCommand(self, chat_id): try: # Parsing str_input = hc.StringParseGoogleAPI(self.str_text) str_input.ParseEvent() event_name = str_input.event_name location = str_input.location start_date = str_input.start_date start_date_pretty = str_input.start_time_cantik end_date_pretty = str_input.end_time_cantik end_date = str_input.end_date except: raise err.ParseError try: # Performing queries Google = gc.GoogleAPI() query = Google.FreeBusyQuery(start_date_pretty, end_date_pretty) isFree = Google.isFree(query) info_busy = Google.BusyInfo(query) except: raise err.QueryError('Unable to perform query') # Get the query's busy info if not isFree: print("not free!") self.bot.sendMessage(chat_id, "Cannot add event!") self.bot.sendMessage(chat_id, "You have %d event(s) occuring between %s and %s" %(len(info_busy), start_date_pretty, end_date_pretty)) for i in range(len(info_busy)): # Ignoring timezones ignored_tz_start_busy = hc.StringParseGoogleAPI(info_busy[i]['start']).IgnoreTimeZone() ignored_tz_end_busy = hc.StringParseGoogleAPI(info_busy[i]['end']).IgnoreTimeZone() # Make these pretty start_busy_pretty = ignored_tz_start_busy.strftime('%Y-%m-%d %H:%M') end_busy_pretty = ignored_tz_end_busy.strftime('%Y-%m-%d %H:%M') # Send message to user self.bot.sendMessage(chat_id, "%d. %s until %s" %(i + 1, start_busy_pretty, end_busy_pretty)) # Raise the error raise err.IsNotFreeError else: # Call the GoogleAPI class and create event current_event_id = gc.GoogleAPI().createEvent(event_name, location, start_date, end_date) # load the event to the database other_event_id_dict = { current_event_id: { 'name': event_name, 'location': location, 'start': start_date_pretty, 'end': end_date_pretty } } excel = db.DB() existing_data_str = excel.table_query(chat_id, other_event_id=True)[4] if excel.isRecordExist(chat_id, other_event_id=True): existing_data_dict = json.loads(existing_data_str) other_event_id_dict.update(existing_data_dict) other_event_id_str = json.dumps(other_event_id_dict) excel.update(chat_id, other_event_id=other_event_id_str)
def on_callback_query(self, msg): query_id, chat_id, query_data = telepot.glance(msg, flavor='callback_query') print('Callback Query:', query_id, chat_id, query_data) if msg['message']['text'].find('Please choose your index below')!=-1: try: self.indexchosen = query_data BotFindIndexObject = hc.chooseindex() BotFindIndexObject.selectindex(self.indexchosen, self.parseddataindex) except: self.bot.answerCallbackQuery(query_id, text='Error! :(') self.bot.sendMessage(chat_id, 'Error occured! Please try again...') else: self.bot.answerCallbackQuery(query_id, text='Index received! :)') BotFindIndexObject = hc.chooseindex() complete_data = BotFindIndexObject.selectindex(self.indexchosen, self.parseddataindex) course_code_dict = { course_code: { 'index':self.indexchosen, 'event_id': [] } } # Check if the dictionary already exists db_check = db.DB() if db_check.isRecordExist(chat_id, course_code_event_id=True): data = db_check.table_query(chat_id, course_code_event_id=True)[3] data_dict = json.loads(data) course_code_dict.update(data_dict) if not BotCommandObject.error: # If online course is selected if complete_data['recurrence'][0].find('Online') != -1: self.bot.answerCallbackQuery(query_id, text='It is an online course!') self.bot.sendMessage(chat_id, "%s is an online course! No need to add it to your Google Calendar!" %(course_code)) self.bot.sendMessage(chat_id, self.failRecordDatabaseandCalendar) self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, "Run /addcourse to add another course (no online course, please)") self.bot.sendMessage(chat_id, "Run /removecourse to remove a course") self.bot.sendMessage(chat_id, "Run /getcourse to list all the courses you have added") else: # Initialize pre requisite before adding to Google Calendar toGoogle = IndexToGoogle(chat_id, complete_data) event_list = toGoogle.get_event() # Loads the dictionary to the database course_code_dict_str = json.dumps(course_code_dict) db.DB().update(chat_id, course_code_event_id=course_code_dict_str) try: toGoogle.PreCreateEventIndex(event_list) except: self.bot.sendMessage(chat_id, "Unknown error has occured") else: self.bot.sendMessage(chat_id, "Nice!") self.bot.sendMessage(chat_id, "%s (index %s) has been added to your Google Calendar and our database" %(course_code, query_data)) self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, "Run /addcourse to add another course") self.bot.sendMessage(chat_id, "Run /removecourse to remove a course") self.bot.sendMessage(chat_id, "Run /getcourse to list all the courses you have added") elif msg['message']['text'].find('Please click the course that you want to remove!') != -1: try: BotCommand(query_data).RemoveCourseCommand(chat_id) except: self.bot.sendMessage(chat_id, self.failRemoveDatabaseandCalendar) self.bot.answerCallbackQuery(query_id, text='Error! :(') else: self.bot.answerCallbackQuery(query_id, text='Course removed! :)') self.bot.sendMessage(chat_id, self.successRemoveDatabaseandCalendar) self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, "Run /addcourse to replace your removed course, if you wish") self.bot.sendMessage(chat_id, "Run /removecourse to remove another course") self.bot.sendMessage(chat_id, "Run /getcourse to list all the courses you have added") elif msg['message']['text'].find("Please click the event that you want to remove!") != -1: self.bot.answerCallbackQuery(query_id, text='Removing event...') try: BotCommand(query_data).RemoveEventCommand(chat_id) except: self.bot.sendMessage(chat_id, "Cannot remove event, unknown error happens!") self.bot.sendMessage(chat_id, self.failRecordDatabaseandCalendar) else: self.bot.sendMessage(chat_id, "The event %s has been removed!" %(query_data)) self.bot.sendMessage(chat_id, self.successRemoveDatabaseandCalendar) self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, "Run /removeevent to remove another event") self.bot.sendMessage(chat_id, "Run /addevent to add an event") self.bot.sendMessage(chat_id, "Run /getevent to list all events you have added") else: self.bot.answerCallbackQuery(query_id, text='Got it :)')
def handleAPI(self, msg): content_type, chat_type, chat_id = telepot.glance(msg) print(content_type, chat_type, chat_id) response = self.bot.getUpdates() self.StoreChat(response) if content_type == 'text': # Convert the message to lower case msg_received = msg['text'].lower() # If the message is a valid command if BotCommand(msg_received).isValidCommand(): # Send users a message related to the command if msg_received == '/start': self.bot.sendMessage(chat_id, "Hi, %s! Need help to be more productive? Good news, I'm here to manage your time! Feel free to ask me stuff!" %(msg['chat']['first_name'])) self.bot.sendMessage(chat_id, "*Want to know me more?* Just ask me whatever you want and hope I can understand", parse_mode='Markdown') self.bot.sendMessage(chat_id, "*Want to know what I can do?* Just run /help to see commands that I can do to help you", parse_mode='Markdown') elif msg_received == '/help': self.bot.sendMessage(chat_id, "Here is the list of commands that I can do: ") self.bot.sendMessage(chat_id, self.helpMessage, parse_mode="Markdown") elif msg_received == '/addevent': msg_reply = "Okay send me the details in following format:" str_format = "*Event Name;location;YYYY-MM-DD HH:MM;YYYY-MM-DD HH:MM*" self.bot.sendMessage(chat_id, msg_reply) self.bot.sendMessage(chat_id, str_format, parse_mode="Markdown") self.bot.sendMessage(chat_id, "*For example:*", parse_mode="Markdown") self.bot.sendMessage(chat_id, "_Party;NTU;2017-10-08 20:00;2017-10-08 22:00_", parse_mode="Markdown") print(response) elif msg_received == '/removeevent': excel = db.DB() course_code_str = excel.table_query(chat_id, other_event_id=True)[4] if not excel.isRecordExist(chat_id, other_event_id=True): self.bot.sendMessage(chat_id,"There is nothing to remove...") self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, "Run /addevent to add an event") else: course_code_dict = json.loads(course_code_str) evt_name_list = [ course_code_dict[key]['name'] + ';' + course_code_dict[key]['start'] + ';' + course_code_dict[key]['end'] for key in list(course_code_dict.keys()) ] inlines_keyboard = [] for i in evt_name_list: inlines_keyboard.append([InlineKeyboardButton(text=i, callback_data=i)]) keyboard = InlineKeyboardMarkup(inline_keyboard=inlines_keyboard) self.bot.sendMessage(chat_id, "Your events are as follows in the format: event_name;start_time;end_time") self.bot.sendMessage(chat_id, "Please click the event that you want to remove!", reply_markup=keyboard) elif msg_received == '/getevent': excel = db.DB() course_code_str = excel.table_query(chat_id, other_event_id=True)[4] if not excel.isRecordExist(chat_id, other_event_id=True): self.bot.sendMessage(chat_id, "There is no event recorded in our database!") self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, "Run /addevent to add an event") else: course_code_dict = json.loads(course_code_str) evt_name_list = [ course_code_dict[key]['name'] + ';' + course_code_dict[key]['start'] + ';' + course_code_dict[key]['end'] for key in list(course_code_dict.keys()) ] inlines_keyboard = [] for i in evt_name_list: inlines_keyboard.append([InlineKeyboardButton(text=i, callback_data=i)]) keyboard = InlineKeyboardMarkup(inline_keyboard=inlines_keyboard) self.bot.sendMessage(chat_id, "Your events are as follows in the format: \n *event_name;start_time;end_time*", parse_mode="Markdown", reply_markup=keyboard) self.bot.sendMessage(chat_id, "What you probably want do next: ") self.bot.sendMessage(chat_id, "Run /removeevent to remove an event") self.bot.sendMessage(chat_id, "Run /addevent to add an event") self.bot.sendMessage(chat_id, "Run /getevent to list all events you have added") elif msg_received == '/setstudenttype': self.bot.sendMessage(chat_id,'Are you a full time or part time student?',reply_markup=ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text="Full Time"), KeyboardButton(text="Part Time")]],one_time_keyboard=True)) elif msg_received == '/addcourse': self.bot.sendMessage(chat_id, 'Sure thing') print(response) check_db = db.DB() first_week_exist = check_db.isRecordExist(chat_id, first_week=True) first_recess_week_exist = check_db.isRecordExist(chat_id, first_recess_week=True) student_type_exist = check_db.isRecordExist(chat_id, student_type=True) is_satisfied = [first_week_exist, first_recess_week_exist, student_type_exist] if not all(is_satisfied): # any of the requirements are not satisfied self.bot.sendMessage(chat_id,'Hmm... Wait a second. You haven\'t told me enough data!') self.bot.sendMessage(chat_id,'Run /setstudenttype to set your student type, i.e. Full Time or Part Time') self.bot.sendMessage(chat_id, 'Run /addfirstweek to set your first_week and first_recess_week') self.error = 1 # explicitly telling that there is an error else: self.bot.sendMessage(chat_id, "Please type your course code below. For example, CZ1003") print(response) self.error = 0 # no error occured elif msg_received == '/removecourse': excel = db.DB() course_code_str = excel.table_query(chat_id, course_code_event_id=True)[3] if not excel.isRecordExist(chat_id, course_code_event_id=True): self.bot.sendMessage(chat_id,"There is nothing to remove...") self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, "Run /addcourse to add a course") else: course_code_dict = json.loads(course_code_str) index_list = [ key for key in list(course_code_dict.keys()) ] inlines_keyboard = [] for i in index_list: inlines_keyboard.append([InlineKeyboardButton(text=i, callback_data=i)]) keyboard = InlineKeyboardMarkup(inline_keyboard=inlines_keyboard) self.bot.sendMessage(chat_id, "Please click the course that you want to remove!",reply_markup=keyboard) elif msg_received == '/getcourse': excel = db.DB() course_code_str = excel.table_query(chat_id, course_code_event_id=True)[3] if not excel.isRecordExist(chat_id, course_code_event_id=True): self.bot.sendMessage(chat_id, "There are no indexes registered in our database!") self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, "Run /addcourse to add your index") else: course_code_dict = json.loads(course_code_str) index_list = [ key for key in list(course_code_dict.keys()) ] inlines_keyboard = [] for i in list(index_list): inlines_keyboard.append([InlineKeyboardButton(text=i, callback_data=i)]) keyboard = InlineKeyboardMarkup(inline_keyboard=inlines_keyboard) self.bot.sendMessage(chat_id, "Your course code are as follows: ", reply_markup=keyboard) self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, "Run /addcourse to add a course") self.bot.sendMessage(chat_id, "Run /removecourse to remove a course (if any)") elif msg_received == '/quit': self.bot.sendMessage(chat_id, "Bye :(") elif msg_received == '/isfree': self.bot.sendMessage(chat_id, "Please enter the date interval using the following format: ") self.bot.sendMessage(chat_id, "YYYY-MM-DD HH:MM;YYYY-MM-DD HH:MM") self.bot.sendMessage(chat_id, '*For example:* ', parse_mode="Markdown") self.bot.sendMessage(chat_id, '2017-10-09 08:00;2017-10-09 16:00', parse_mode="Markdown") elif msg_received == '/addfirstweek': self.bot.sendMessage(chat_id, "Please enter the Monday dates of your first week and first recess week using the following format: ") self.bot.sendMessage(chat_id, "*FirstWeek;FirstRecessWeek*", parse_mode="Markdown") self.bot.sendMessage(chat_id, '*For example:* ', parse_mode="Markdown") self.bot.sendMessage(chat_id, '_2017-8-14;2017-10-2_', parse_mode="Markdown") self.bot.sendMessage(chat_id, "*Notes*: _These two dates are very important. If you enter the wrong dates and add your course (i.e. by running /addcourse), consequently, your course schedule will be shifted by one or more weeks!_", parse_mode="Markdown") elif msg_received == '/getupcomingevent': self.bot.sendMessage(chat_id, 'Please enter how many upcoming events are you looking for!') keyboard=[ [ '7', '8', '9' ], [ '4', '5', '6' ], [ '1', '2', '3' ] ] reply_markup = ReplyKeyboardMarkup(keyboard=keyboard, one_time_keyboard=True) self.bot.sendMessage(chat_id, 'Press!', reply_markup=reply_markup) else: self.bot.sendMessage(chat_id, "Command not updated!") else: # Execute the command further # Create the Command Object first global BotCommandObject BotCommandObject = BotCommand(msg['text']) # to prevent crashing as it separates the variables so literally it can run parallelly # This checks if the last msg['text'] is indeed a command if len(self.list_update_message) >= 2 and self.list_update_message[-2] == '/addevent': try: BotCommandObject.AddEventCommand(chat_id) except err.ParseError: self.bot.sendMessage(chat_id, 'Cannot addevent! Make sure to enter the correct format!') self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, "Run /addevent again with the correct time format") except err.IsNotFreeError: self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, "Run /addevent to add another event with different datetime") except err.QueryError: self.bot.sendMessage(chat_id, "Your format is correct, however we cannot perform the query to your Google Account") self.bot.sendMessage(chat_id, "Chances are: ") self.bot.sendMessage(chat_id, '1. You have problems with your API keys') self.bot.sendMessage(chat_id, '2. You entered a bad date, e.g. your end time is smaller than your start time') self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, 'Resolve your API problem') self.bot.sendMessage(chat_id, 'Run /addevent again and give me a reasonable date interval') except: self.bot.sendMessage(chat_id, 'Unknown Error occured') else: self.bot.sendMessage(chat_id, self.successRecordDatabase) self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, "Run /addevent to add another event") self.bot.sendMessage(chat_id, "Run /removeevent to remove an event") self.bot.sendMessage(chat_id, "Run /getevent to list all events you have added") elif len(self.list_update_message) >= 2 and (self.list_update_message[-2] == '/setstudenttype' or self.list_update_message[-2] == '/setstudentype' or self.list_update_message[-2] == '/st'): try: BotCommandObject.SetStudentType(chat_id) except: self.bot.sendMessage(chat_id, 'Wrong format!') else: self.bot.sendMessage(chat_id, self.successRecordDatabase,reply_markup=ReplyKeyboardRemove(remove_keyboard=True)) self.bot.sendMessage(chat_id, "Have you added your first week?") self.bot.sendMessage(chat_id, "If you haven't, run /addfirstweek") self.bot.sendMessage(chat_id, "If you have, then run /addcourse straight away!") elif len(self.list_update_message) >= 2 and self.list_update_message[-2] == '/isfree': try: BotCommandObject.IsFreeCommand(chat_id) except err.ParseError: self.bot.sendMessage(chat_id, 'Cannot perform query!') self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, 'Run /isfree again with the correct date format') except err.QueryError: self.bot.sendMessage(chat_id, "Your format is correct, however we cannot perform the query to your Google Account") self.bot.sendMessage(chat_id, "Chances are: ") self.bot.sendMessage(chat_id, '1. You have problems with your API keys') self.bot.sendMessage(chat_id, '2. You entered a bad date, e.g. your end time is smaller than your start time') self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, 'Resolve your API problem') self.bot.sendMessage(chat_id, 'Run /addevent again and give me a reasonable date interval') except err.IsNotFreeError: self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, "Run /isfree again with different datetime") else: self.bot.sendMessage(chat_id, 'You are free on this time interval') self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, 'Run /addevent to add an event for this interval time') self.bot.sendMessage(chat_id, 'Run /getevent to list all events you have added') self.bot.sendMessage(chat_id, 'Run /isfree again to check for another time') elif len(self.list_update_message) >= 2 and self.list_update_message[-2] == '/addcourse' and not self.error: self.bot.sendMessage(chat_id, 'Please wait while we process your information. This may take around a minute.\n') self.bot.sendMessage(chat_id, 'To prevent crashing, please wait until the Success message has appeared.\n') try: self.indexchosen='' BotCommandObject.AddCourseCommand(chat_id) self.parseddataindex = BotCommandObject.parseddataindex except err.BrowserError: self.bot.sendMessage(chat_id, 'Cannot access the course!') self.bot.sendMessage(chat_id, 'Chances are: ') self.bot.sendMessage(chat_id, '1. You have problems with your browser driver (e.g. chromedriver for Google Chrome)') self.bot.sendMessage(chat_id, '2. You entered a course code that does not exist') self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, 'Resolve your browser problem') self.bot.sendMessage(chat_id, 'Run /addcourse and enter the correct course code') except: self.bot.sendMessage(chat_id, 'Cannot access the course! Make sure you have entered the correct format!') else: if not BotCommandObject.error: self.bot.sendMessage(chat_id, "The indexes for this course code has been successfully accessed. Please do the instructions above :)") elif len(self.list_update_message) >= 2 and self.list_update_message[-2] == '/addfirstweek': try: BotCommandObject.AddFirstWeek(chat_id) except err.IsNotMondayError: self.bot.sendMessage(chat_id, "The input date is not Monday!") self.bot.sendMessage(chat_id, self.failRecordDatabase) self.bot.sendMessage(chat_id, "Please run /addfirstweek again and enter the Monday dates of your first week and first recess week!") except err.ParseError: self.bot.sendMessage(chat_id, 'Unable to parse!') self.bot.sendMessage(chat_id, self.failRecordDatabase) self.bot.sendMessage(chat_id, self.suggestion) self.bot.sendMessage(chat_id, 'Run /addfirstweek again and enter the correct format!') else: self.bot.sendMessage(chat_id, self.successRecordDatabase) self.bot.sendMessage(chat_id, "Have you set your student type?") self.bot.sendMessage(chat_id, "If you haven't, run /setstudenttype") self.bot.sendMessage(chat_id, "If you have, run /addcourse straight away!") elif len(self.list_update_message) >= 2 and self.list_update_message[-2] == '/getupcomingevent': BotCommandObject.getUpcomingEvent(chat_id) else: # Below is not a command. It only makes the bot smarter # manual emoticons ONLY :p if msg_received[0] == ':': if len(msg_received) <= 3: self.bot.sendMessage(chat_id, msg['text']) else: self.bot.sendMessage(chat_id, "What is that??? .-.") elif msg_received.find('rude') != -1: self.bot.sendMessage(chat_id, BotReply().reply_dict['rude']) # If the bot knows reply the message elif BotReply().isValidtoReply(msg_received): print(BotReply().reply_dict[msg_received]) # With name? if BotReply().isWithName(msg_received): self.bot.sendMessage(chat_id, BotReply().reply_dict[msg_received] +', ' + msg['chat']['first_name'] + ' !') elif msg_received == 'meetings': self.bot.sendMessage(chat_id, BotReply().reply_dict[msg_received]) inlines_keyboard = [] for i in range(len(hc.PreformattedBotInlineMarkup().days)): inlines_keyboard.append([InlineKeyboardButton(text=hc.PreformattedBotInlineMarkup().days[i], callback_data=hc.PreformattedBotInlineMarkup().days[i])]) keyboard = InlineKeyboardMarkup(inline_keyboard=inlines_keyboard) self.bot.sendMessage(chat_id, 'Choose a day!', reply_markup=keyboard) else: self.bot.sendMessage(chat_id, BotReply().reply_dict[msg_received]) else: self.bot.sendMessage(chat_id, "Sorry, I don't know what to reply such conversation yet. :'(")