Skip to content

Commit

Permalink
Merge remote-tracking branch 'refs/remotes/origin/master' into stable
Browse files Browse the repository at this point in the history
  • Loading branch information
derpicknicker1 committed Sep 24, 2016
2 parents 85de76e + c42f1e8 commit 530e200
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 52 deletions.
22 changes: 11 additions & 11 deletions octoprint_telegram/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,15 +195,15 @@ def handleTextMessage(self, message, chat_id, from_id):
self.main.send_msg("I do not understand you! " + self.gEmo('mistake'),chatID=chat_id)
raise ExitThisLoopException()
# check if user is allowed to execute the command
if self.isCommandAllowed(chat_id,from_id,command):
if self.isCommandAllowed(chat_id,from_id,command) and self.main.tcmd.checkState(from_id, command, parameter):
# messageRespondID is needed to send command replys only to the sender
# if message is from a group
self.main.messageResponseID = message['message']['message_id']
# Track command
if command.startswith("/"):
self.main.track_action("command/" + command[1:])
# execute command
self.main.tcmd.commandDict[command]['cmd'](chat_id=chat_id,parameter=parameter)
self.main.tcmd.commandDict[command]['cmd'](chat_id=chat_id,parameter=parameter,cmd=command)
# we dont need the messageResponseID anymore
self.main.messageResponseID = None
else:
Expand Down Expand Up @@ -250,7 +250,7 @@ def parseUserData(self, message):
self.main.chats[chat_id] = data
self.main.send_msg(self.gEmo('info') + "Now i know you. Before you can do anything, go to OctoPrint Settings and edit some rights.",chatID=chat_id)
kwargs = {'chat_id':int(chat_id)}
t.threading.Thread(target=self.main.get_usrPic, kwargs=kwargs)
t = threading.Thread(target=self.main.get_usrPic, kwargs=kwargs)
t.daemon = True
t.run()
self._logger.debug("Got new User")
Expand Down Expand Up @@ -477,17 +477,18 @@ def on_after_startup(self):
if fcut not in self.chats:
self._logger.debug("Removing pic" +fcut+".jpg")
try:
os.remove(self.get_plugin_data_folder()++"/img/user/"+f)
os.remove(self.get_plugin_data_folder()+"/img/user/"+f)
except OSError:
pass
#Update user profile photos
for key in self.chats:
try:
kwargs = {}
kwargs['chat_id'] = int(key)
t = threading.Thread(target=self.get_usrPic, kwargs=kwargs)
t.daemon = True
t.run()
if key is not 'zBOTTOMOFCHATS':
kwargs = {}
kwargs['chat_id'] = int(key)
t = threading.Thread(target=self.get_usrPic, kwargs=kwargs)
t.daemon = True
t.run()
except Exception:
pass

Expand Down Expand Up @@ -782,7 +783,7 @@ def on_event(self, event, payload, **kwargs):
if event in self.tmsg.msgCmdDict:
self._logger.debug("Got an event: " + event + " Payload: " + str(payload))
# Start event handler
self.tmsg.msgCmdDict[event](event, payload, **kwargs)
self.tmsg.startEvent(event, payload, **kwargs)
else:
# return as fast as possible
return
Expand Down Expand Up @@ -1090,7 +1091,6 @@ def track_action(self, action):
t.daemon = True
t.run()


def route_hook(self, server_routes, *args, **kwargs):
from octoprint.server.util.tornado import LargeResponseHandler, UrlProxyHandler, path_validation_factory
from octoprint.util import is_hidden_path
Expand Down
45 changes: 26 additions & 19 deletions octoprint_telegram/telegramCommands.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,22 @@ class TCMD():
def __init__(self, main):
self.main = main
self.gEmo = self.main.gEmo
self.tmpSysCmd = {}
self.stateList = {}
self._logger = main._logger.getChild("TCMD")
self.commandDict = {
gettext("Yes"): {'cmd': self.cmdYes, 'bind_none': True},
gettext("Cancel"): {'cmd': self.cmdNo, 'bind_none': True},
gettext("No"): {'cmd': self.cmdNo,'bind_none': True},
gettext("Change height"): {'cmd': self.cmdChgHeight, 'bind_cmd': '/settings'},
(self.gEmo('enter') + gettext(" Enter height")): {'cmd': self.cmdSetHeight, 'bind_cmd': '/settings'},
gettext(" Enter height"): {'cmd': self.cmdSetHeight, 'bind_cmd': '/settings'},
gettext("Change time"): {'cmd': self.cmdChgTime, 'bind_cmd': '/settings'},
(self.gEmo('enter') + gettext(" Enter time")): {'cmd': self.cmdSetTime, 'bind_cmd': '/settings'},
gettext(" Enter time"): {'cmd': self.cmdSetTime, 'bind_cmd': '/settings'},
gettext("Start print"): {'cmd': self.cmdStartPrint, 'bind_cmd': '/print'},
gettext("Stop print"): {'cmd': self.cmdHalt, 'bind_cmd': '/print'},
gettext("Don't print"): {'cmd': self.cmdDontPrint, 'bind_cmd': '/print'},
gettext("Do System Command"): {'cmd': self.cmdSysRun, 'bind_cmd': '/sys'},
gettext("Change height"): {'cmd': self.cmdChgHeight, 'bind_cmd': '/settings', 'lastState': '/settings'},
(self.gEmo('enter') + gettext(" Enter height")): {'cmd': self.cmdSetHeight, 'bind_cmd': '/settings', 'lastState': gettext("Change height")},
gettext(" Enter height"): {'cmd': self.cmdSetHeight, 'bind_cmd': '/settings', 'lastState': gettext("Change height")},
gettext("Change time"): {'cmd': self.cmdChgTime, 'bind_cmd': '/settings', 'lastState': '/settings'},
(self.gEmo('enter') + gettext(" Enter time")): {'cmd': self.cmdSetTime, 'bind_cmd': '/settings', 'lastState': gettext("Change time")},
gettext(" Enter time"): {'cmd': self.cmdSetTime, 'bind_cmd': '/settings', 'lastState': gettext("Change time")},
gettext("Start print"): {'cmd': self.cmdStartPrint, 'bind_cmd': '/print', 'lastState': '/print_'},
gettext("Stop print"): {'cmd': self.cmdHalt, 'bind_cmd': '/abort', 'lastState': '/abort'},
gettext("Don't print"): {'cmd': self.cmdDontPrint, 'bind_cmd': '/print', 'lastState': '/print_'},
gettext("Do System Command"): {'cmd': self.cmdSysRun, 'bind_cmd': '/sys', 'lastState': '/sys_'},
'/print_': {'cmd': self.cmdRunPrint, 'bind_cmd': '/print'},
'/test': {'cmd': self.cmdTest},
'/status': {'cmd': self.cmdStatus},
Expand All @@ -48,12 +48,22 @@ def __init__(self, main):
'/ctrl_': {'cmd': self.cmdCtrlRun, 'bind_cmd': '/ctrl'}
}

def checkState(self, chat_id, cmd, parameter = ""):
if not chat_id in self.stateList:
self.stateList[chat_id] = ["",""]
ret = True
if 'lastState' in self.commandDict[cmd]:
if self.commandDict[cmd]['lastState'] != self.stateList[chat_id][0]:
ret = False
self.stateList[chat_id][0] = cmd
if parameter is not None and parameter is not "":
self.stateList[chat_id][1] = parameter
return ret

def cmdYes(self,chat_id,**kwargs):
self.main.send_msg(gettext("Alright."),chatID=chat_id)

def cmdNo(self,chat_id,**kwargs):
if chat_id in self.tmpSysCmd:
del self.tmpSysCmd[chat_id]
self.main.send_msg(gettext("Maybe next time."),chatID=chat_id)

def cmdTest(self,chat_id,**kwargs):
Expand All @@ -76,7 +86,7 @@ def cmdSettings(self,chat_id,**kwargs):
def cmdChgHeight(self,chat_id,**kwargs):
self.main.send_msg(self.gEmo('enter') + " " + gettext("Enter height"), force_reply=True,chatID=chat_id)

def cmdSetHeight(self,chat_id,parameter,**kwargs):
def cmdSetHeight(self,chat_id,parameter,**kwargs):
self.main._settings.set_float(['notification_height'], parameter, force=True)
self.main.send_msg(self.gEmo('height') + gettext(" Notification height is now %(height)fmm.", height=self.main._settings.get_float(['notification_height'])),chatID=chat_id)

Expand Down Expand Up @@ -169,21 +179,18 @@ def cmdSys(self,chat_id,**kwargs):

def cmdSysReq(self,chat_id,parameter,**kwargs):
if parameter is None or parameter is "":
kwargs['cmd'] = "/sys"
self.cmdSys(chat_id, **kwargs)
return
actions = self.main._settings.global_get(['system','actions'])
command = next((d for d in actions if 'action' in d and self.hashMe(d['action'], 6) == parameter) , False)
if command :
self.tmpSysCmd.update({chat_id: parameter})
self.main.send_msg(self.gEmo('question') + " Really execute "+command['name']+"?",responses=[gettext("Do System Command"), gettext("Cancel")],chatID=chat_id)
return
self.main.send_msg(self.gEmo('warning') + " Sorry, i don't know this System Command.",chatID=chat_id)

def cmdSysRun(self,chat_id,**kwargs):
if chat_id not in self.tmpSysCmd:
return
parameter = self.tmpSysCmd[chat_id]
del self.tmpSysCmd[chat_id]
parameter = self.stateList[chat_id][1]
actions = self.main._settings.global_get(['system','actions'])
action = next((i for i in actions if self.hashMe(i['action'], 6) == parameter), False)
### The following is taken from OctoPrint/src/octoprint/server/api/__init__.py -> performSystemAction()
Expand Down
35 changes: 14 additions & 21 deletions octoprint_telegram/telegramNotifications.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,19 +84,16 @@ def __init__(self, main):
'StatusPrinting': self.msgStatusPrinting
}

def _prepMsg(self, event):
def startEvent(self, event, payload, **kwargs):
status = self.main._printer.get_current_data()
self.z = status['currentZ'] or 0.0
if 'bind_msg' in telegramMsgDict[event]:
event = telegramMsgDict[event]['bind_msg']
return event
kwargs['event'] = event
self.msgCmdDict[event](payload, **kwargs)

def msgPrinterStart_Shutdown(self, event, payload, **kwargs):
kwargs['event'] = self._prepMsg(event)
def msgPrinterStart_Shutdown(self, payload, **kwargs):
self._sendNotification(payload, **kwargs)

def msgZChange(self, event, payload, **kwargs):
kwargs['event'] = self._prepMsg(event)
def msgZChange(self, payload, **kwargs):
status = self.main._printer.get_current_data()
if not status['state']['flags']['printing'] or not self.is_notification_necessary(payload['new'], payload['old']):
return
Expand All @@ -109,40 +106,36 @@ def msgZChange(self, event, payload, **kwargs):
self.main._settings.get_int(['notification_time']))
self._sendNotification(payload, **kwargs)

def msgPrintStarted(self, event, payload, **kwargs):
kwargs['event'] = self._prepMsg(event)
def msgPrintStarted(self, payload, **kwargs):
self.last_z = 0.0
self.last_notification_time = time.time()
self._sendNotification(payload, **kwargs)

def msgPrintDone(self, event, payload, **kwargs):
kwargs['event'] = self._prepMsg(event)
def msgPrintDone(self, payload, **kwargs):
self.main.shut_up = {}
kwargs["delay"] = self.main._settings.get_int(["message_at_print_done_delay"])
self._sendNotification(payload, **kwargs)

def msgPrintFailed(self, event, payload, **kwargs):
kwargs['event'] = self._prepMsg(event)
def msgPrintFailed(self, payload, **kwargs):
self.main.shut_up = {}
self._sendNotification(payload, **kwargs)

def msgStatusPrinting(self, event, payload, **kwargs):
kwargs['event'] = self._prepMsg(event)
def msgStatusPrinting(self, payload, **kwargs):
self.track = False
self._sendNotification(payload, **kwargs)

def msgStatusNotPrinting(self, event, payload, **kwargs):
kwargs['event'] = self._prepMsg(event)
def msgStatusNotPrinting(self, payload, **kwargs):
self.track = False
self._sendNotification(payload, **kwargs)

def _sendNotification(self, payload, **kwargs):
status = self.main._printer.get_current_data()
event = kwargs['event']
kwargs['event'] = telegramMsgDict[event]['bind_msg'] if 'bind_msg' in telegramMsgDict[event] else event
kwargs['with_image'] = self.main._settings.get(['messages',str(kwargs['event']),'image'])
self._logger.debug("Printer Status" + str(status))
# define locals for string formatting
z = self.z
event = kwargs['event']
temps = self.main._printer.get_current_temperatures()
self._logger.debug("TEMPS - " + str(temps))
bed_temp = temps['bed']['actual'] if 'bed' in temps else 0.0
Expand All @@ -166,15 +159,15 @@ def _sendNotification(self, payload, **kwargs):
message = self.main._settings.get(["messages",kwargs['event'],"text"]).format(emo,**locals())
except Exception as ex:
self._logger.debug("Exception on formatting message: " + str(ex))
message = self.main.gEmo('warning') + " ERROR: I was not able to format the Notification for '"+kwargs['event']+"' properly. Please open your OctoPrint settings for " + self.main._plugin_name + " and check message settings for '" + kwargs['event'] + "'."
message = self.main.gEmo('warning') + " ERROR: I was not able to format the Notification for '"+event+"' properly. Please open your OctoPrint settings for " + self.main._plugin_name + " and check message settings for '" + event + "'."
self._logger.debug("Sending Notification: " + message)
# Do we want to send with Markup?
kwargs['markup'] = self.main._settings.get(["messages",kwargs['event'],"markup"])
# finally send MSG
self.main.send_msg(message, **kwargs)

if self.track:
self.main.track_action("notification/" + kwargs['event'])
self.main.track_action("notification/" + event)
self.track = True

# Helper to determine if notification will be send on gcode ZChange event
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
plugin_name = "OctoPrint-Telegram"

# The plugin's version. Can be overwritten within OctoPrint's internal data via __plugin_version__ in the plugin module
plugin_version = "1.3.2"
plugin_version = "1.3.3"

# The plugin's description. Can be overwritten within OctoPrint's internal data via __plugin_description__ in the plugin
# module
Expand Down

0 comments on commit 530e200

Please sign in to comment.