Skip to content

Commit

Permalink
✨ Users can now enter custom push times for menu and lecture push
Browse files Browse the repository at this point in the history
  • Loading branch information
Mueller-Patrick committed Mar 11, 2020
1 parent a8df12d commit 21a5ab4
Show file tree
Hide file tree
Showing 8 changed files with 299 additions and 84 deletions.
9 changes: 4 additions & 5 deletions Main.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,8 @@ def __init__(self):
self.bot = bt.Bot(telegram_token=self.token, users=self.helperFunctions.getUsers(),
lectureFetcher=self.lfetcher,
memes=self.memes)
self.sentMenuToday = False
self.sentLecturesToday = False
self.askedForRatingToday = False
self.sentReturnDirectionsToday = False

self.customPushTimes = self.helperFunctions.getPreferredPushTimes()

# Configure logging
logfile = 'logs/main_application_' + datetime.now().strftime('%Y-%m-%d') + '.log'
Expand Down Expand Up @@ -62,7 +60,8 @@ def close(self):
"wantsLecturePlan": user.wantsLecturePlan,
"address": user.address,
"wantsTransportInfo": user.wantsTransportInfo,
"wantsToRateMeals": user.wantsToRateMeals
"wantsToRateMeals": user.wantsToRateMeals,
"pushTimes": user.pushTimes
}
usersList.append(toAppend)
usersJson = json.dumps(usersList, indent=4)
Expand Down
2 changes: 2 additions & 0 deletions bot/Command.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ def interpretMessage(self):
'settingstype': self.mfunctions.message_settingstype,
'settingspersonalinfo': self.mfunctions.message_settingspersonalinfo,
'settingssubscriptions': self.mfunctions.message_settingssubscriptions,
'settingstimes': self.mfunctions.message_settingstimes,
'changepersonalinfo': self.mfunctions.message_changepersonalinfo,
'changepushtime': self.mfunctions.message_changepushtime,
'newcoursepassword': self.mfunctions.message_newcoursepassword,
'coursepassword': self.mfunctions.message_coursepassword,
'raplalink': self.mfunctions.message_raplalink,
Expand Down
4 changes: 2 additions & 2 deletions bot/CommandFunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def command_whatdoyouknowaboutme(self):
("🏫 You are in the " + self.message.user.course + " course"))
else:
self.bot.sendMessage(self.message.user.chatID,
"❓ But I don't know which course you are in, so I can't send you"
"❓ But I don't know which course you are in, so I can't send you "
+ "your lecture plan :(")

def command_getmenu(self):
Expand Down Expand Up @@ -135,7 +135,7 @@ def command_settings(self):
self.bot.sendMessageWithOptions(self.message.user.chatID, 'What do you want to change?',
self.bot.generateReplyMarkup(
[['️🧍 Personal Information'], ['📲 Subscription-Settings'],
['🧨 Cancel']]))
['⏰ Push Time Settings'], ['🧨 Cancel']]))
self.message.user.expectedMessageType = 'settingstype'

def command_adminrate(self):
Expand Down
116 changes: 110 additions & 6 deletions bot/MessageFunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from maps import Directions
from menu import Rater
import logging
import re


class MessageFunctions:
Expand All @@ -30,7 +31,7 @@ def message_startname(self):
+ 'each day. If you receive the menu push, I\'ll also ask you to *rate your meal*. If you don\'t '
+ 'want that, you can opt-out in the subscription settings.\n\nTo *get the daily menu at any time*, send /getmenu. If you forgot '
+ '*what lectures you have today*, type /getlectures to get the plan again. And if you want the *public '
+ 'transport directions* now, type /getdirections.\n\n'
+ 'transport directions* now, type /getdirections.\n\n'
+ 'We all love *memes*. Type /getmeme to access all of your favorite ones.\n\n'
+ 'If you find a *bug*, report it via /reportbug.\n\nAnd because I '
+ 'respect your *privacy*, type /privacy and /whatdoyouknowaboutme to get Info about what we save '
Expand Down Expand Up @@ -216,7 +217,8 @@ def message_directionstype(self):
direc = Directions.Direction(datetime.now(), self.message.user.address, False, True)
trainPlan = direc.create_message()

self.bot.sendMessage(self.message.user.chatID, 'Here are the public transport directions for your way home:')
self.bot.sendMessage(self.message.user.chatID,
'Here are the public transport directions for your way home:')
self.bot.sendMessage(self.message.user.chatID, trainPlan)
except:
self.bot.sendMessage(self.message.user.chatID, (
Expand All @@ -230,7 +232,8 @@ def message_directionstype(self):
direc = Directions.Direction(datetime.now(), self.message.user.address, True, True)
trainPlan = direc.create_message()

self.bot.sendMessage(self.message.user.chatID, 'Here are the public transport directions for your way to DHBW:')
self.bot.sendMessage(self.message.user.chatID,
'Here are the public transport directions for your way to DHBW:')
self.bot.sendMessage(self.message.user.chatID, trainPlan)
except:
self.bot.sendMessage(self.message.user.chatID, (
Expand Down Expand Up @@ -280,14 +283,24 @@ def message_settingstype(self):
"Here are your Subscriptions:",
self.bot.generateReplyMarkup(options))
self.message.user.expectedMessageType = 'settingssubscriptions'
elif self.message.text == '⏰ Push Time Settings':
menuPushTime = self.message.user.pushTimes['menu']
lecturePushTime = self.message.user.pushTimes['lecture']
self.bot.sendMessageWithOptions(self.message.user.chatID,
"What push notification should come on another time? ",
self.bot.generateReplyMarkup(
[[('🍜 Menu Push (currently ' + menuPushTime + ')')],
[('🕒 Lecture Plan Push (currently ' + lecturePushTime + ')')],
['⏪ Back']]))
self.message.user.expectedMessageType = 'settingstimes'
elif self.message.text == '🧨 Cancel':
self.bot.sendMessage(self.message.user.chatID, "ALLES BLEIBT HIER WIE ES IST.")
self.message.user.expectedMessageType = ''
else:
self.bot.sendMessageWithOptions(self.message.user.chatID, "Wrong input. Please try again:",
self.bot.generateReplyMarkup(
[['️🧍 Personal Information'], ['📲 Subscription-Settings'],
['🧨 Cancel']]))
['⏰ Push Time Settings'], ['🧨 Cancel']]))

# Called when user sends the information that he wants to change his personal info
def message_settingspersonalinfo(self):
Expand Down Expand Up @@ -316,7 +329,7 @@ def message_settingspersonalinfo(self):
self.bot.sendMessageWithOptions(self.message.user.chatID, 'What do you want to change?',
self.bot.generateReplyMarkup(
[['️🧍 Personal Information'], ['📲 Subscription-Settings'],
['🧨 Cancel']]))
['⏰ Push Time Settings'], ['🧨 Cancel']]))
self.message.user.expectedMessageType = 'settingstype'
else:
self.bot.sendMessageWithOptions(self.message.user.chatID, "Wrong input. Please try again:",
Expand Down Expand Up @@ -371,7 +384,8 @@ def message_settingssubscriptions(self):
elif self.message.text == '⏪ Back':
self.bot.sendMessageWithOptions(self.message.user.chatID, 'What do you want to change?',
self.bot.generateReplyMarkup([['️🧍 Personal Information'],
['📲 Subscription-Settings'], ['🧨 Cancel']]))
['📲 Subscription-Settings'],
['⏰ Push Time Settings'], ['🧨 Cancel']]))
self.message.user.expectedMessageType = 'settingstype'
else:
# Fetch the user's subscriptions to show them the current status
Expand Down Expand Up @@ -402,6 +416,40 @@ def message_settingssubscriptions(self):
"Wrong input. Please try again:",
self.bot.generateReplyMarkup(options))

# Called when the user sends the information which push time he wants to change
def message_settingstimes(self):
if '🍜 Menu Push' in self.message.text:
menuPushTime = self.message.user.pushTimes['menu']
self.bot.sendMessage(self.message.user.chatID, (
"You currently receive the menu push at " + menuPushTime
+ ". To change that, send me the new time in the format *HH:MM*. Please notice that it has to be "
+ "between 00:00 and 10:59."))
self.message.user.tempParams['pushtimeToBeChanged'] = 'menu'
self.message.user.expectedMessageType = 'changepushtime'
elif '🕒 Lecture Plan Push' in self.message.text:
lecturePushTime = self.message.user.pushTimes['lecture']
self.bot.sendMessage(self.message.user.chatID, (
"You currently receive the lecture push at " + lecturePushTime
+ ". To change that, send me the new time in the format *HH:MM*. Please notice that it has to be "
+ "between 15:00 and 22:59."))
self.message.user.tempParams['pushtimeToBeChanged'] = 'lecture'
self.message.user.expectedMessageType = 'changepushtime'
elif '⏪ Back' in self.message.text:
self.bot.sendMessageWithOptions(self.message.user.chatID, "Wrong input. Please try again:",
self.bot.generateReplyMarkup(
[['️🧍 Personal Information'], ['📲 Subscription-Settings'],
['⏰ Push Time Settings'], ['🧨 Cancel']]))
self.message.user.expectedMessageType = 'settingstype'
else:
menuPushTime = self.message.user.pushTimes['menu']
lecturePushTime = self.message.user.pushTimes['lecture']
self.bot.sendMessageWithOptions(self.message.user.chatID,
"What push notification should come on another time? ",
self.bot.generateReplyMarkup(
[[('🍜 Menu Push (currently ' + menuPushTime + ')')],
[('🕒 Lecture Plan Push (currently ' + lecturePushTime + ')')],
['⏪ Back']]))

# Called when the user sends the new info about him
def message_changepersonalinfo(self):
type = self.message.user.tempParams['personalInfoToBeChanged']
Expand Down Expand Up @@ -454,6 +502,62 @@ def message_changepersonalinfo(self):
'Wrong type for changing personal info given in MessageFunctions.message_changepersonalinfo. Given type: %s',
type)

# Called when the user sends the new push time
def message_changepushtime(self):
type = self.message.user.tempParams['pushtimeToBeChanged']

#TODO: remove
print(self.message.text)

if type == 'menu':
# Possible values: 00:00 to 10:59
timeRegex = re.compile('[0-1][0-9]:[0-5][0-9]')
timeObj = timeRegex.search(self.message.text)

# A regex valid time is found and the time is valid
if timeObj is not None:
timeString = timeObj.group()
if int(timeString[:2]) <= 10:
self.message.user.pushTimes['menu'] = timeString
self.bot.sendMessage(self.message.user.chatID,
("Successfully updated your menu push time to " + timeString))
self.message.user.tempParams['pushtimeToBeChanged'] = ''
self.message.user.expectedMessageType = ''
else:
self.bot.sendMessage(self.message.user.chatID, (
"Invalid time: " + self.message.text
+ ". Please use the format HH:MM and notice that it has to be between 00:00 and 10:59"))
else:
self.bot.sendMessage(self.message.user.chatID, (
"Invalid time: " + self.message.text
+ ". Please use the format HH:MM and notice that it has to be between 00:00 and 10:59"))
elif type == 'lecture':
# Possible values: 15:00 to 22:59
timeRegex = re.compile('[1-2][0-9]:[0-5][0-9]')
timeObj = timeRegex.search(self.message.text)

# A regex valid time is found and the time is valid
if timeObj is not None:
timeString = timeObj.group()
if int(timeString[:2]) <= 22 and int(timeString[:2]) >= 15:
self.message.user.pushTimes['lecture'] = timeString
self.bot.sendMessage(self.message.user.chatID,
("Successfully updated your lecture push time to " + timeString))
self.message.user.tempParams['pushtimeToBeChanged'] = ''
self.message.user.expectedMessageType = ''
else:
self.bot.sendMessage(self.message.user.chatID, (
"Invalid time: " + self.message.text
+ ". Please use the format HH:MM and notice that it has to be between 15:00 and 22:59"))
else:
self.bot.sendMessage(self.message.user.chatID, (
"Invalid time: " + self.message.text
+ ". Please use the format HH:MM and notice that it has to be between 15:00 and 22:59"))
else:
logging.warning(
'Wrong type for changing push time given in MessageFunctions.message_changepushtime. Given type: %s',
type)

# Called when the user sends the new password for a course
def message_newcoursepassword(self):
password = self.message.text
Expand Down
4 changes: 4 additions & 0 deletions bot/User.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@ def __init__(self, chatID):
self.address = ''
self.wantsTransportInfo = False
self.wantsToRateMeals = True
self.pushTimes = {
'menu': '06:00',
'lecture': '18:00'
}
4 changes: 2 additions & 2 deletions lecturePlan/LectureFetcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,9 @@ def getFormattedLectures(self, courseName, dayString):
beginTime = str(lecture.start)[11:16]
endTime = str(lecture.end)[11:16]
if retString != '': # To skip the first item in the list
retString += ('\n' + beginTime + '-' + endTime + ': *' + lecture.summary + '*')
retString += ('\n' + beginTime + ' - ' + endTime + ': *' + lecture.summary + '*')
else: # The first element doesnt need a line break at the start
retString += (beginTime + '-' + endTime + ': *' + lecture.summary + '*')
retString += (beginTime + ' - ' + endTime + ': *' + lecture.summary + '*')

return retString

Expand Down
35 changes: 22 additions & 13 deletions mainHelpers/AsyncLoops.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ async def mainLoop(self):

async def pushLoop(self):
while True:
await asyncio.sleep(29)
await asyncio.sleep(31)
now = datetime.now()
timeString = now.strftime("%H:%M")
weekday = now.weekday()
Expand All @@ -45,29 +45,34 @@ async def pushLoop(self):
sendPlanToday = False

# run daily at 06:00 for all users that want the menu
if str(timeString) == '06:00' and not self.main.sentMenuToday and canteenOpen:
self.main.sentMenuToday = True
if str(timeString) == '06:00' and canteenOpen:
logging.info('Sending menu')
self.helpers.sendMenu()
elif str(timeString) == '18:00' and not self.main.sentLecturesToday and sendPlanToday:
self.main.sentLecturesToday = True
elif str(timeString) == '18:00' and sendPlanToday:
logging.info('Sending lecture plans')
self.helpers.sendLectures()
elif str(timeString) == '14:30' and not self.main.askedForRatingToday and canteenOpen:
self.main.askedForRatingToday = True
elif str(timeString) == '14:30' and canteenOpen:
logging.info('Sending menu rating requests')
self.helpers.sendMenuRating()
elif str(timeString) == '10:00' and not self.main.sentReturnDirectionsToday:
self.main.sentReturnDirectionsToday = True
elif str(timeString) == '10:00':
logging.info('Sending return directions')
self.helpers.sendReturnDirections()
# Reset the boolean to send the menu for today again.
# Do this only if seconds < 30 because otherwise it would happen twice.
elif timeString == '23:59' and int(datetime.now().strftime('%S')) < 30:
logging.info('Resetting variables and writing usage stats')
logging.info('Writing usage stats')
self.helpers.writeUsageStats(True)
self.main.sentMenuToday = False
self.main.sentLecturesToday = False

# Run all the custom push times
if timeString in list(self.main.customPushTimes):
for pushPreference in self.main.customPushTimes[timeString]:
if pushPreference[0] == 'menu':
self.helpers.sendMenu(True, pushPreference[1])
elif pushPreference[0] == 'lecture':
self.helpers.sendLectures(True, pushPreference[1])
else:
logging.warning('AsyncLoops.pushLoop(): Tried to send custom push with unknown type %s',
pushPreference[0])

# Check if it should stop
if self.main.bot.tellMainToClose:
Expand Down Expand Up @@ -95,7 +100,8 @@ async def saveLoop(self):
"wantsLecturePlan": user.wantsLecturePlan,
"address": user.address,
"wantsTransportInfo": user.wantsTransportInfo,
"wantsToRateMeals": user.wantsToRateMeals
"wantsToRateMeals": user.wantsToRateMeals,
"pushTimes": user.pushTimes
}
usersList.append(toAppend)
usersJson = json.dumps(usersList, indent=4)
Expand All @@ -110,6 +116,9 @@ async def saveLoop(self):
# save usage stats
self.helpers.writeUsageStats(False)

# Also reload the custom push times in case something changed
self.main.customPushTimes = self.helpers.getPreferredPushTimes()

logging.info('Saved all preferences')

# Check if it should stop
Expand Down
Loading

0 comments on commit 21a5ab4

Please sign in to comment.