Skip to content

Commit

Permalink
telegram fix
Browse files Browse the repository at this point in the history
fixed documentation
  • Loading branch information
Sebastian committed Jun 20, 2019
1 parent fa8a7e0 commit b2a9eab
Show file tree
Hide file tree
Showing 7 changed files with 513 additions and 468 deletions.
47 changes: 18 additions & 29 deletions RTOC/LoggerPlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,7 @@

class LoggerPlugin:
"""
This class is imported by any plugin written for RTOC.
It includes all functions to interact with RTOC. Every plugin must inherit this class! Your plugin must look like this:
.. code-block:
::
from RTOC.LoggerPlugin import LoggerPlugin
class Plugin(LoggerPlugin):
def __init__(self, stream=None, plot=None, event=None):
LoggerPlugin.__init__(self, stream, plot, event)
...
...
Args:
stream (method): The callback-method for the stream-method
Expand All @@ -43,7 +29,7 @@ def __init__(self, stream=None, plot=None, event=None):
def __init__(self, stream=None, plot=None, event=None, telegramBot=None, *args, **kwargs):
# Plugin setup
# self.setDeviceName()
self._deviceName = "noDevice"
self._devicename = "noDevice"
self._cb = stream
self._ev = event
self._plt = plot
Expand Down Expand Up @@ -120,7 +106,7 @@ def stream(self, y=[], snames=[], dname=None, unit=None, x=None, slist=None, sdi
if self._cb:
now = time.time()
if dname is None:
dname = self._deviceName
dname = self._devicename
if slist is None and sdict is None:
if type(y) == int or type(y) == float:
y = [y]
Expand Down Expand Up @@ -205,7 +191,7 @@ def plot(self, x=[], y=[], sname='noName', dname=None, unit='', hold='off', auto
y = x
x = list(range(len(x)))
if dname is None:
dname = self._deviceName
dname = self._devicename
if self._plt:
self._plt(x, y, sname, dname, unit, hold=hold, autoResize=autoResize)
return True
Expand Down Expand Up @@ -236,7 +222,7 @@ def event(self, text='', sname=None, dname=None, priority=0, id=None, value=None
if sname is None:
sname = "unknownEvent"
if dname is None:
dname = self._deviceName
dname = self._devicename
if self._ev:
self._ev(text, sname, dname, x, priority, value=value, id=id)
return True
Expand Down Expand Up @@ -398,7 +384,7 @@ def setDeviceName(self, devicename="noDevice"):
Returns:
None
"""
self._deviceName = devicename # Is shown in GUI
self._devicename = devicename # Is shown in GUI

def close(self):
"""
Expand Down Expand Up @@ -543,42 +529,45 @@ def __updateT(self, func):
func()
diff = (time.time() - start_time)

def telegram_send_message(self, text, onlyAdmin=False):
def telegram_send_message(self, text, priority=0, permission='write'):
"""
Sends a message to all clients (or only admins).
Args:
text (str): Text to be send to the clients.
onlyAdmin (bool): If True, only admins will get this message
priority (int): Priority to decide, which allow each client to disable notifications (0: Information, 1: Warning, 2: Error)
permission (str): Choose user-permission (blocked, read, write, admin)
"""
if self._bot is not None:
self._bot.send_message_to_all(text, onlyAdmin)
self._bot.send_message_to_all(self._devicename+': '+str(text), priority, permission)
else:
logging.warning('TelegramBot is not enabled or wrong configured! Can not send message "{}"'.format(text))

def telegram_send_photo(self, path, onlyAdmin=False):
def telegram_send_photo(self, path, priority=0, permission='write'):
"""
Sends the picture at a given path to all clients (or only admins).
Args:
path (str): Path to the picture to send.
onlyAdmin (bool): If True, only admins will get this message
priority (int): Priority to decide, which allow each client to disable notifications (0: Information, 1: Warning, 2: Error)
permission (str): Choose user-permission (blocked, read, write, admin)
"""
if self._bot is not None:
self._bot.send_photo(path, onlyAdmin)
self._bot.send_photo(path, priority, permission)
else:
logging.warning('TelegramBot is not enabled or wrong configured! Can not send photo "{}"'.format(path))

def telegram_send_document(self, path, onlyAdmin=False):
def telegram_send_document(self, path, priority=0, permission='write'):
"""
Sends any document at a given path to all clients (or only admins).
Args:
path (str): Path to the file to send.
onlyAdmin (bool): If True, only admins will get this message
priority (int): Priority to decide, which allow each client to disable notifications (0: Information, 1: Warning, 2: Error)
permission (str): Choose user-permission (blocked, read, write, admin)
"""
if self._bot is not None:
self._bot.send_document(path, onlyAdmin)
self._bot.send_document(path, priority, permission)
else:
logging.warning('TelegramBot is not enabled or wrong configured! Can not send file "{}"'.format(path))

Expand Down
6 changes: 3 additions & 3 deletions RTOC/RTLogger/plugins/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@
devicename = "test"

class Plugin(LoggerPlugin):
def __init__(self, stream=None, plot=None, event=None):
def __init__(self, *args, **kwargs):
# Plugin setup
super(Plugin, self).__init__(stream, plot, event)
super(Plugin, self).__init__(*args, **kwargs)
self.setDeviceName(devicename)
self.smallGUI = True
self._startTime = time.time()
Expand All @@ -40,7 +40,7 @@ def __updateT(self):
# self.samplerate= 1
self.stream(
y=[self.samplerate, timedelta, delay, error],
snames=['Samplerate', 'Delta', 'Delay', 'Error'],
snames=['Samplerate.a', 'Delta', 'Delay', 'Error'],
)
time.sleep(delay)

Expand Down
96 changes: 54 additions & 42 deletions RTOC/RTLogger/telegramBot.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ def check_chat_id(self, chat_id):
first_name = str(chat.first_name)
last_name = str(chat.last_name)
text = translate('RTOC', '{} {} joined {} for the first time.').format(first_name, last_name, self.logger.config['global']['name'])
self.send_message_to_all(text, onlyAdmin=True)
self.send_message_to_all(text, permission='admin')
logging.info('TELEGRAM BOT: New client connected with ID: '+str(chat_id))
if len(self.telegram_clients.keys()) == 0:
ad = 'admin'
Expand Down Expand Up @@ -187,28 +187,40 @@ def sendEvent(self, message, devicename, signalname, priority):
# except Exception:
# self.bot.send_message(chat_id=int(id), text=message)

def send_message_to_all(self, message, onlyAdmin=False):
def check_permission_and_priority(self, chat_id, priority, permission):
self.check_chat_id(chat_id)
perms = ['blocked','read','write','admin']
if priority >= self.telegram_clients[chat_id]['eventlevel']:
if permission in perms:
idx = perms.index(self.telegram_clients[chat_id]['permission'])
idx2 = perms.index(permission)
if idx >= idx2:
return True
return False


def send_message_to_all(self, message, priority=0, permission='write'):
for id in self.telegram_clients.keys():
if (onlyAdmin and self.telegram_clients[id]['permission'] == 'admin') or not onlyAdmin:
if self.check_permission_and_priority(id, priority, permission):
self.send_message(chat_id=int(id), text=message, delete=False)

def send_photo(self, path, onlyAdmin=False):
def send_photo(self, path, priority=0, permission='write'):
try:
for id in self.telegram_clients.keys():
if (onlyAdmin and self.telegram_clients[id]['permission'] == 'admin') or not onlyAdmin:
if self.check_permission_and_priority(id, priority, permission):
self.bot.send_photo(chat_id=int(id), photo=open(path, 'rb'))
except Exception as error:
text = translate('RTOC', 'Error while sending photo:\n{}').format(error)
self.send_message_to_all(text, onlyAdmin)
self.send_message_to_all(text, priority, permission)

def send_document(self, path, onlyAdmin=False):
def send_document(self, path, priority=0, permission='write'):
try:
for id in self.telegram_clients.keys():
if (onlyAdmin and self.telegram_clients[id]['permission'] == 'admin') or not onlyAdmin:
if self.check_permission_and_priority(id, priority, permission):
self.bot.send_document(chat_id=int(id), document=open(path, 'rb'))
except Exception as error:
text = translate('RTOC', 'Error while sending file:\n{}').format(error)
self.send_message_to_all(text, onlyAdmin)
self.send_message_to_all(text, priority, permission)

def connect(self):
idler = Thread(target=self.connectThread)
Expand Down Expand Up @@ -946,33 +958,7 @@ def signalsHandlerAns(self, bot, chat_id, strung):
self.signals_selected[chat_id].pop(idx)
self.send_message(chat_id=chat_id,
text=translate('RTOC', 'Signal removed from selection.'))
elif len(a) == 2: # and not self.get_telegram_client(chat_id, 'signalSubmenu', True):
if strung not in self.signals_selected[chat_id]:
sigID = self.logger.database.getSignalID(a[0], a[1])
xmin, xmax, sigLen = self.logger.database.getSignalInfo(sigID)
if xmin != None:
self.signals_selected[chat_id].append(strung)
t = self.createPlotToolTip(xmin, xmax, sigLen)
else:
self.signals_selected[chat_id].append(strung)
t = translate('RTOC', 'Empty signal')

evs = self.logger.database.getEvents(sigID)
if evs == []:
evtext = '0'
else:
evtext = str(len(evs))+translate('RTOC', '\nLatest Event:\n')
if evs[0][6] == 0:
prio = translate('RTOC', 'Information')
elif evs[0][6] == 1:
prio = translate('RTOC', 'Warning')
else:
prio = translate('RTOC', 'Error')

evtext += prio+': '
evtext += evs[0][3]+': '+ dt.datetime.fromtimestamp(evs[0][4]).strftime("%d.%m.%Y %H:%M:%S")
self.send_message(chat_id,
translate('RTOC', 'Signal selected:\n{}\nEvents: {}').format(t, evtext), ParseMode.MARKDOWN, True, False)
elif self.get_telegram_client(chat_id, 'signalSubmenu', True) and strung in self.logger.database.deviceNames():
self.signalsDeviceSubHandler(bot, chat_id, strung)
return
Expand Down Expand Up @@ -1034,8 +1020,7 @@ def signalsHandlerAns(self, bot, chat_id, strung):
self.telegram_clients[str(chat_id)]['signalSubmenu'] = True
self.saveClients()
else:
self.send_message(chat_id=chat_id,
text=translate('RTOC', 'Signal names consist of\n<Device>.<Signal>\nYour message didn\'t look that way.\n'))
self.selectSignal(bot, chat_id, strung)
self.signalsHandler(bot, chat_id, True)
return

Expand All @@ -1048,15 +1033,43 @@ def signalsDeviceSubHandler(self, bot, chat_id, device):
sname = '.'.join(signalname)
if sname not in self.signals_selected[chat_id]:
commands.append(sname)
commands = [translate('RTOC', 'All')] +commands
text = translate('RTOC', 'Signals of {}').format(device)
commands.sort()
self.sendMenuMessage(bot, chat_id, commands, text)

def signalsDeviceSubHandlerAns(self, bot, chat_id, strung):
a = strung.split('.')
if strung == self.BACKBUTTON:
self.signalsHandler(bot, chat_id, True)
return
elif strung == translate('RTOC', 'All'):
dev = self.telegram_clients[str(chat_id)]['menu'].split(':')[0]
availableSignals = self.logger.database.signalNames(devices=[dev])
for signalname in availableSignals:
sname = '.'.join(signalname)
if sname not in self.signals_selected[chat_id] and dev in sname:
self.signals_selected[chat_id].append(sname)
self.send_message(chat_id=chat_id,
text=translate('RTOC', 'All signals of {} selected.').format(dev))
else:
self.selectSignal(bot, chat_id, strung)
device = self.telegram_clients[str(chat_id)]['menu'].split(':')[0]
self.signalsDeviceSubHandler(bot, chat_id, device)

def selectSignal(self, bot, chat_id, strung):
a = strung.split('.')
if len(a)>2:
self.send_message(chat_id, translate('RTOC', 'Please rename this signal. Signals should not contain "." and ":".'))
b=['.'.join(a[:-2]),a[-1]]
self.selectSignal2(bot, chat_id, strung, b)
b=[a[0],'.'.join(a[1:])]
self.selectSignal2(bot, chat_id, strung, b)
elif len(a) == 2:
self.selectSignal2(bot, chat_id, strung, a)


def selectSignal2(self, bot, chat_id, strung, a):
a = strung.split('.')
if len(a) == 2:
if strung not in self.signals_selected[chat_id]:
sigID = self.logger.database.getSignalID(a[0], a[1])
Expand Down Expand Up @@ -1084,11 +1097,10 @@ def signalsDeviceSubHandlerAns(self, bot, chat_id, strung):
evtext += evs[0][3]+' am '+ dt.datetime.fromtimestamp(evs[0][4]).strftime("%d.%m.%Y %H:%M:%S")
self.send_message(chat_id,
translate('RTOC', 'Signal selected:\n{}\nEvents: {}').format(t, evtext), ParseMode.MARKDOWN, True, False)
return True
else:
self.send_message(chat_id=chat_id,
text=translate('RTOC', 'Signal names consist of\n<Device>.<Signal>\nYour message didn\'t look that way.\n'))
device = self.telegram_clients[str(chat_id)]['menu'].split(':')[0]
self.signalsDeviceSubHandler(bot, chat_id, device)
return False


def signalsSelectRangeHandler(self, bot, chat_id):
self.telegram_clients[str(chat_id)]['menu'] = "signalSelectRange"
Expand Down
6 changes: 3 additions & 3 deletions RTOC/RTOC_GUI/ui/rtoc.ui
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
</widget>
<widget class="QDockWidget" name="deviceWidget">
<property name="sizePolicy">
<sizepolicy hsizetype="Ignored" vsizetype="Preferred">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
Expand Down Expand Up @@ -156,7 +156,7 @@
<x>0</x>
<y>0</y>
<width>398</width>
<height>88</height>
<height>95</height>
</rect>
</property>
<property name="sizePolicy">
Expand Down Expand Up @@ -273,7 +273,7 @@
<x>0</x>
<y>0</y>
<width>400</width>
<height>98</height>
<height>96</height>
</rect>
</property>
<attribute name="label">
Expand Down
Binary file modified RTOC/locales/de_de.qm
Binary file not shown.

0 comments on commit b2a9eab

Please sign in to comment.