Skip to content

Commit

Permalink
Merge pull request #352 from giloser/master
Browse files Browse the repository at this point in the history
V1.6.5
  • Loading branch information
giloser authored Mar 23, 2021
2 parents f309f37 + afe9102 commit dddb992
Show file tree
Hide file tree
Showing 8 changed files with 588 additions and 71 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
This plugin integrates Telegram Messenger with Octoprint. It sends messages (with photos if available) on print start, end and failure. Also it sends messages during the print at configurable intervals. That way you don't have to remember to regularly have a look at the printing process.
Also, you can control Octoprint via messages (settings, start a print and much more). Send `/status` to get the current printer status or `/abort` to abort the current print. Send `/help` for a list of all recognized commands. You may also use this bot in groups.

**Latest release: [1.6.4](https://github.com/fabianonline/OctoPrint-Telegram/releases)**
**Latest release: [1.6.5](https://github.com/fabianonline/OctoPrint-Telegram/releases)**

<!-- omit in toc -->
## Contents
Expand Down
220 changes: 164 additions & 56 deletions octoprint_telegram/__init__.py

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions octoprint_telegram/emojiDict.py
Original file line number Diff line number Diff line change
Expand Up @@ -856,4 +856,6 @@
'smiling cat face with open mouth': '\U0001f63a',
'shutdown' : '\U0001F4A4',
'film frame' : '\U0001F39E',
'ice cube' : '\U0001F9CA',
'freezing face' : '\U0001F976',
}
2 changes: 2 additions & 0 deletions octoprint_telegram/static/js/telegram.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ $(function() {
self.varInfoDialog = undefined;
self.emoInfoDialog = undefined;
self.mupInfoDialog = undefined;
self.timeInfoDialog = undefined;
self.currChatID = "Unknown";
self.currChatTitle = ko.observable("Unknown");
self.bind_cmd = {};
Expand Down Expand Up @@ -571,6 +572,7 @@ $(function() {
self.varInfoDialog = $('#settings-telegramDialogVarInfo');
self.emoInfoDialog = $('#settings-telegramDialogEmoInfo');
self.mupInfoDialog = $('#settings-telegramDialogMupInfo');
self.timeInfoDialog = $('#settings-telegramDialogTimeInfo');
$('.teleEmojiImg').each( function(){
$(this).attr('src','/plugin/telegram/static/img/'+$(this).attr('id')+".png")
});
Expand Down
107 changes: 104 additions & 3 deletions octoprint_telegram/telegramCommands.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
import requests
import base64
from flask_babel import gettext
from subprocess import Popen, PIPE
#from subprocess import Popen, PIPE
import subprocess
from .telegramNotifications import telegramMsgDict

################################################################################################################
Expand All @@ -27,6 +28,7 @@ def __init__(self, main):
self.conSettingsTemp = []
self.dirHashDict = {}
self.tmpFileHash = ""
self._spoolManagerPluginImplementation = None
self.port = self.main._settings.global_get(["server","port"])
self.commandDict = {
"Yes": {'cmd': self.cmdYes, 'bind_none': True},
Expand Down Expand Up @@ -303,14 +305,14 @@ def cmdSettings(self,chat_id,from_id,cmd,parameter):
return
else:
if self.main._settings.get_boolean(["send_gif"]):
gif_txt = "Desactivate gif"
gif_txt = "Deactivate gif"
gif_emo = self.gEmo('check')
else:
gif_txt = "Activate gif"
gif_emo = self.gEmo('error')

if self.main._settings.get_boolean(["multicam"]):
multicam_txt = "Desactivate management of multicam"
multicam_txt = "Deactivate management of multicam"
multicam_emo = self.gEmo('check')
else:
multicam_txt = "Activate mangement of multicam"
Expand Down Expand Up @@ -1244,6 +1246,105 @@ def cmdFilament(self,chat_id,from_id,cmd,parameter):
keys.append([[self.main.emojis['cross mark']+gettext(" Close"),"No"]])
msg_id=self.main.getUpdateMsgId(chat_id) if parameter == "back" else ""
self.main.send_msg(message,chatID=chat_id,responses=keys,msg_id=msg_id)
elif self.main._plugin_manager.get_plugin("SpoolManager",True):
if parameter and parameter != "back":
self._logger.info("Parameter received for filament: %s" % parameter)
params = parameter.split('_')
apikey = self.main._settings.global_get(['api','key'])
errorText = ""
if params[0] == "spools":
try:

if self._spoolManagerPluginImplementation == None:
self._spoolManagerPluginImplementation = self.main._plugin_manager.get_plugin("SpoolManager",True)
message ="SpoolManager: "+str(self._spoolManagerPluginImplementation.SpoolManagerAPI.load_allSpools())
#selectedSpool = self._spoolManagerPluginImplementation.filamentManager.loadSelectedSpool()
#allSpool = self._spoolManagerPluginImplementation.filamentManager.load_allSpools
#message ="selectedSpool= " +str(selectedSpool) + "\nallSpool=" +str(allSpool)

# resp = requests.get("http://localhost:" + str(self.port) + "/plugin/spoolmanager/loadSpoolsByQuery?="+query)
# resp2 = requests.get("http://localhost:" + str(self.port) + "/plugin/filamentmanager/selections?apikey="+apikey)
# if (resp.status_code != 200):
# errorText = resp.text
# resp = resp.json()
# resp2 = resp2.json()
# self._logger.info("Spools: %s" % resp["spools"])
# message = self.gEmo('info') + " Available filament spools are:\n"
# for spool in resp["spools"]:
# weight = spool["weight"]
# used = spool["used"]
# percent = int(100 - (used / weight * 100))
# message += str(spool["profile"]["vendor"]) + " " + str(spool["name"]) + " " + str(spool["profile"]["material"]) + " [" + str(percent) + "%]\n"
# for selection in resp2["selections"]:
# if selection["tool"] == 0:
# message += "\n\nCurrently selected: " + str(selection["spool"]["profile"]["vendor"]) + " " + str(selection["spool"]["name"]) + " " + str(selection["spool"]["profile"]["material"])
msg_id=self.main.getUpdateMsgId(chat_id)
self.main.send_msg(message,chatID=chat_id,msg_id = msg_id,inline=False)
except ValueError:
message = self.gEmo('mistake')+" Error getting spools. Are you sure, you have installed the Spool Manager Plugin?"
if (errorText != ""):
message += "\nError text: " + str(errorText)
msg_id=self.main.getUpdateMsgId(chat_id)
self.main.send_msg(message,chatID=chat_id,msg_id = msg_id,inline=False)
if params[0] == "changeSpool":
self._logger.info("Command to change spool: %s" % params)
if len(params) > 1:
self._logger.info("Changing to spool: %s" % params[1])
try:
payload = {"selection": {"spool": {"id": params[1]},"tool": 0}}
self._logger.info("Payload: %s" % payload)
resp = requests.patch("http://localhost:" + str(self.port) + "/plugin/filamentmanager/selections/0?apikey="+apikey, json=payload, headers={'Content-Type': 'application/json'})
if (resp.status_code != 200):
errorText = resp.text
self._logger.info("Response: %s" % resp)
resp = resp.json()
message = self.gEmo('check') + " Selected spool is now: " + str(resp["selection"]["spool"]["profile"]["vendor"]) + " " + str(resp["selection"]["spool"]["name"]) + " " + str(resp["selection"]["spool"]["profile"]["material"])
msg_id=self.main.getUpdateMsgId(chat_id)
self.main.send_msg(message,chatID=chat_id,msg_id = msg_id,inline=False)
except ValueError:
message = self.gEmo('mistake')+" Error changing spool"
if (errorText != ""):
message += "\nError text: " + str(errorText)
msg_id=self.main.getUpdateMsgId(chat_id)
self.main.send_msg(message,chatID=chat_id,msg_id = msg_id,inline=False)
else:
self._logger.info("Asking for spool")
try:
resp = requests.get("http://localhost:" + str(self.port) + "/plugin/filamentmanager/spools?apikey="+apikey)
if (resp.status_code != 200):
errorText = resp.text
resp = resp.json()
message = self.gEmo('question') + " which filament spool do you want to select?"
keys = []
tmpKeys = []
i = 1
for spool in resp["spools"]:
self._logger.info("Appending spool: %s" % spool)
tmpKeys.append([str(spool["profile"]["vendor"]) + " " + str(spool['name']) + " " + str(spool["profile"]["material"]) ,"/filament_changeSpool_" + str(spool['id'])])
if i%2 == 0:
keys.append(tmpKeys)
tmpKeys = []
i += 1
if len(tmpKeys) > 0:
keys.append(tmpKeys)
keys.append([[self.main.emojis['cross mark']+gettext(" Close"),"No"]])
msg_id=self.main.getUpdateMsgId(chat_id)
self._logger.info("Sending message")
self.main.send_msg(message,chatID=chat_id,responses=keys,msg_id=msg_id)
except ValueError:
message = self.gEmo('mistake')+" Error changing spool"
if (errorText != ""):
message += "\nError text: " + str(errorText)
msg_id=self.main.getUpdateMsgId(chat_id)
self.main.send_msg(message,chatID=chat_id,msg_id = msg_id,inline=False)
else:
message = self.gEmo('info') + " The following Filament Manager commands are known."
keys = []
keys.append([["Show spools","/filament_spools"]])
keys.append([["Change spool","/filament_changeSpool"]])
keys.append([[self.main.emojis['cross mark']+gettext(" Close"),"No"]])
msg_id=self.main.getUpdateMsgId(chat_id) if parameter == "back" else ""
self.main.send_msg(message,chatID=chat_id,responses=keys,msg_id=msg_id)
else:
message = self.gEmo('warning') + " No filament manager plugin installed."
msg_id=self.main.getUpdateMsgId(chat_id) if parameter == "back" else ""
Expand Down
48 changes: 44 additions & 4 deletions octoprint_telegram/telegramNotifications.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def is_in_python_2_7():
'markup': "off"
},
'gCode_M600' : {
'text': "{emo:warning} " + gettext("Color change requested Second try.\nBed {bed_temp}/{bed_target}, Extruder {e1_temp}/{e1_target}."),
'text': "{emo:warning} " + gettext("Color change requested.\nBed {bed_temp}/{bed_target}, Extruder {e1_temp}/{e1_target}."),
'image': True,
'silent': False,
'gif': False,
Expand All @@ -126,15 +126,46 @@ def is_in_python_2_7():
'combined' : True,
'markup': "off"
},
'Connected' : {
'text': "{emo:link symbol} " + gettext("Printer Connected"),
'image': False,
'silent': False,
'gif': False,
'combined': True,
'markup': "off"
},
'Disconnected' : {
'text': "{emo:broken heart} " + gettext("Printer Disconnected"),
'image': False,
'silent': False,
'gif': False,
'combined': True,
'markup': "off"
},
'Home' : {
'text': "{emo:house building} " + gettext("Printer received home command \nBed {bed_temp}/{bed_target}, Extruder {e1_temp}/{e1_target}"),
'image': True,
'silent': False,
'gif': False,
'combined': True,
'markup': "off"
},
'Alert' : {
'text': "{emo:bell} " + gettext("Printer received alert command \nBed {bed_temp}/{bed_target}, Extruder {e1_temp}/{e1_target}"),
'image': True,
'silent': False,
'gif': False,
'combined': True,
'markup': "off"
},
'UserNotif' : {
'text': "{emo:waving hand sign} " + gettext("User Notification {UserNotif_Text}"),
'image': True,
'silent': False,
'gif': False,
'combined': True,
'markup': "off"
}

},
}

# class to handle emojis on notifigation message format
Expand Down Expand Up @@ -179,7 +210,11 @@ def __init__(self, main):
'gCode_M600': self.msgColorChangeRequested,
'Error': self.msgPrinterError,
'MovieDone': self.msgMovieDone,
'UserNotif': self.msgUserNotif
'UserNotif': self.msgUserNotif,
'Connected':self.msgConnected,
'Disconnected':self.msgConnected,
'Alert':self.msgConnected,
'Home':self.msgConnected,
}

def startEvent(self, event, payload, **kwargs):
Expand Down Expand Up @@ -255,6 +290,11 @@ def msgUserNotif(self,payload, **kwargs):
payload = {}
self._sendNotification(payload, **kwargs)

def msgConnected(self,payload, **kwargs):
if payload is None:
payload = {}
self._sendNotification(payload, **kwargs)

def _sendNotification(self, payload, **kwargs):
try:
status = self.main._printer.get_current_data()
Expand Down
Loading

0 comments on commit dddb992

Please sign in to comment.