Skip to content

Commit b2a9eab

Browse files
author
Sebastian
committed
telegram fix
fixed documentation
1 parent fa8a7e0 commit b2a9eab

File tree

7 files changed

+513
-468
lines changed

7 files changed

+513
-468
lines changed

RTOC/LoggerPlugin.py

Lines changed: 18 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -18,21 +18,7 @@
1818

1919
class LoggerPlugin:
2020
"""
21-
This class is imported by any plugin written for RTOC.
22-
23-
It includes all functions to interact with RTOC. Every plugin must inherit this class! Your plugin must look like this:
24-
25-
.. code-block:
26-
27-
::
28-
29-
from RTOC.LoggerPlugin import LoggerPlugin
30-
31-
class Plugin(LoggerPlugin):
32-
def __init__(self, stream=None, plot=None, event=None):
33-
LoggerPlugin.__init__(self, stream, plot, event)
34-
...
35-
...
21+
3622
3723
Args:
3824
stream (method): The callback-method for the stream-method
@@ -43,7 +29,7 @@ def __init__(self, stream=None, plot=None, event=None):
4329
def __init__(self, stream=None, plot=None, event=None, telegramBot=None, *args, **kwargs):
4430
# Plugin setup
4531
# self.setDeviceName()
46-
self._deviceName = "noDevice"
32+
self._devicename = "noDevice"
4733
self._cb = stream
4834
self._ev = event
4935
self._plt = plot
@@ -120,7 +106,7 @@ def stream(self, y=[], snames=[], dname=None, unit=None, x=None, slist=None, sdi
120106
if self._cb:
121107
now = time.time()
122108
if dname is None:
123-
dname = self._deviceName
109+
dname = self._devicename
124110
if slist is None and sdict is None:
125111
if type(y) == int or type(y) == float:
126112
y = [y]
@@ -205,7 +191,7 @@ def plot(self, x=[], y=[], sname='noName', dname=None, unit='', hold='off', auto
205191
y = x
206192
x = list(range(len(x)))
207193
if dname is None:
208-
dname = self._deviceName
194+
dname = self._devicename
209195
if self._plt:
210196
self._plt(x, y, sname, dname, unit, hold=hold, autoResize=autoResize)
211197
return True
@@ -236,7 +222,7 @@ def event(self, text='', sname=None, dname=None, priority=0, id=None, value=None
236222
if sname is None:
237223
sname = "unknownEvent"
238224
if dname is None:
239-
dname = self._deviceName
225+
dname = self._devicename
240226
if self._ev:
241227
self._ev(text, sname, dname, x, priority, value=value, id=id)
242228
return True
@@ -398,7 +384,7 @@ def setDeviceName(self, devicename="noDevice"):
398384
Returns:
399385
None
400386
"""
401-
self._deviceName = devicename # Is shown in GUI
387+
self._devicename = devicename # Is shown in GUI
402388

403389
def close(self):
404390
"""
@@ -543,42 +529,45 @@ def __updateT(self, func):
543529
func()
544530
diff = (time.time() - start_time)
545531

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

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

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

RTOC/RTLogger/plugins/test.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@
1313
devicename = "test"
1414

1515
class Plugin(LoggerPlugin):
16-
def __init__(self, stream=None, plot=None, event=None):
16+
def __init__(self, *args, **kwargs):
1717
# Plugin setup
18-
super(Plugin, self).__init__(stream, plot, event)
18+
super(Plugin, self).__init__(*args, **kwargs)
1919
self.setDeviceName(devicename)
2020
self.smallGUI = True
2121
self._startTime = time.time()
@@ -40,7 +40,7 @@ def __updateT(self):
4040
# self.samplerate= 1
4141
self.stream(
4242
y=[self.samplerate, timedelta, delay, error],
43-
snames=['Samplerate', 'Delta', 'Delay', 'Error'],
43+
snames=['Samplerate.a', 'Delta', 'Delay', 'Error'],
4444
)
4545
time.sleep(delay)
4646

RTOC/RTLogger/telegramBot.py

Lines changed: 54 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def check_chat_id(self, chat_id):
134134
first_name = str(chat.first_name)
135135
last_name = str(chat.last_name)
136136
text = translate('RTOC', '{} {} joined {} for the first time.').format(first_name, last_name, self.logger.config['global']['name'])
137-
self.send_message_to_all(text, onlyAdmin=True)
137+
self.send_message_to_all(text, permission='admin')
138138
logging.info('TELEGRAM BOT: New client connected with ID: '+str(chat_id))
139139
if len(self.telegram_clients.keys()) == 0:
140140
ad = 'admin'
@@ -187,28 +187,40 @@ def sendEvent(self, message, devicename, signalname, priority):
187187
# except Exception:
188188
# self.bot.send_message(chat_id=int(id), text=message)
189189

190-
def send_message_to_all(self, message, onlyAdmin=False):
190+
def check_permission_and_priority(self, chat_id, priority, permission):
191+
self.check_chat_id(chat_id)
192+
perms = ['blocked','read','write','admin']
193+
if priority >= self.telegram_clients[chat_id]['eventlevel']:
194+
if permission in perms:
195+
idx = perms.index(self.telegram_clients[chat_id]['permission'])
196+
idx2 = perms.index(permission)
197+
if idx >= idx2:
198+
return True
199+
return False
200+
201+
202+
def send_message_to_all(self, message, priority=0, permission='write'):
191203
for id in self.telegram_clients.keys():
192-
if (onlyAdmin and self.telegram_clients[id]['permission'] == 'admin') or not onlyAdmin:
204+
if self.check_permission_and_priority(id, priority, permission):
193205
self.send_message(chat_id=int(id), text=message, delete=False)
194206

195-
def send_photo(self, path, onlyAdmin=False):
207+
def send_photo(self, path, priority=0, permission='write'):
196208
try:
197209
for id in self.telegram_clients.keys():
198-
if (onlyAdmin and self.telegram_clients[id]['permission'] == 'admin') or not onlyAdmin:
210+
if self.check_permission_and_priority(id, priority, permission):
199211
self.bot.send_photo(chat_id=int(id), photo=open(path, 'rb'))
200212
except Exception as error:
201213
text = translate('RTOC', 'Error while sending photo:\n{}').format(error)
202-
self.send_message_to_all(text, onlyAdmin)
214+
self.send_message_to_all(text, priority, permission)
203215

204-
def send_document(self, path, onlyAdmin=False):
216+
def send_document(self, path, priority=0, permission='write'):
205217
try:
206218
for id in self.telegram_clients.keys():
207-
if (onlyAdmin and self.telegram_clients[id]['permission'] == 'admin') or not onlyAdmin:
219+
if self.check_permission_and_priority(id, priority, permission):
208220
self.bot.send_document(chat_id=int(id), document=open(path, 'rb'))
209221
except Exception as error:
210222
text = translate('RTOC', 'Error while sending file:\n{}').format(error)
211-
self.send_message_to_all(text, onlyAdmin)
223+
self.send_message_to_all(text, priority, permission)
212224

213225
def connect(self):
214226
idler = Thread(target=self.connectThread)
@@ -946,33 +958,7 @@ def signalsHandlerAns(self, bot, chat_id, strung):
946958
self.signals_selected[chat_id].pop(idx)
947959
self.send_message(chat_id=chat_id,
948960
text=translate('RTOC', 'Signal removed from selection.'))
949-
elif len(a) == 2: # and not self.get_telegram_client(chat_id, 'signalSubmenu', True):
950-
if strung not in self.signals_selected[chat_id]:
951-
sigID = self.logger.database.getSignalID(a[0], a[1])
952-
xmin, xmax, sigLen = self.logger.database.getSignalInfo(sigID)
953-
if xmin != None:
954-
self.signals_selected[chat_id].append(strung)
955-
t = self.createPlotToolTip(xmin, xmax, sigLen)
956-
else:
957-
self.signals_selected[chat_id].append(strung)
958-
t = translate('RTOC', 'Empty signal')
959-
960-
evs = self.logger.database.getEvents(sigID)
961-
if evs == []:
962-
evtext = '0'
963-
else:
964-
evtext = str(len(evs))+translate('RTOC', '\nLatest Event:\n')
965-
if evs[0][6] == 0:
966-
prio = translate('RTOC', 'Information')
967-
elif evs[0][6] == 1:
968-
prio = translate('RTOC', 'Warning')
969-
else:
970-
prio = translate('RTOC', 'Error')
971961

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

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

10551041
def signalsDeviceSubHandlerAns(self, bot, chat_id, strung):
1056-
a = strung.split('.')
10571042
if strung == self.BACKBUTTON:
10581043
self.signalsHandler(bot, chat_id, True)
10591044
return
1045+
elif strung == translate('RTOC', 'All'):
1046+
dev = self.telegram_clients[str(chat_id)]['menu'].split(':')[0]
1047+
availableSignals = self.logger.database.signalNames(devices=[dev])
1048+
for signalname in availableSignals:
1049+
sname = '.'.join(signalname)
1050+
if sname not in self.signals_selected[chat_id] and dev in sname:
1051+
self.signals_selected[chat_id].append(sname)
1052+
self.send_message(chat_id=chat_id,
1053+
text=translate('RTOC', 'All signals of {} selected.').format(dev))
1054+
else:
1055+
self.selectSignal(bot, chat_id, strung)
1056+
device = self.telegram_clients[str(chat_id)]['menu'].split(':')[0]
1057+
self.signalsDeviceSubHandler(bot, chat_id, device)
1058+
1059+
def selectSignal(self, bot, chat_id, strung):
1060+
a = strung.split('.')
1061+
if len(a)>2:
1062+
self.send_message(chat_id, translate('RTOC', 'Please rename this signal. Signals should not contain "." and ":".'))
1063+
b=['.'.join(a[:-2]),a[-1]]
1064+
self.selectSignal2(bot, chat_id, strung, b)
1065+
b=[a[0],'.'.join(a[1:])]
1066+
self.selectSignal2(bot, chat_id, strung, b)
1067+
elif len(a) == 2:
1068+
self.selectSignal2(bot, chat_id, strung, a)
1069+
1070+
1071+
def selectSignal2(self, bot, chat_id, strung, a):
1072+
a = strung.split('.')
10601073
if len(a) == 2:
10611074
if strung not in self.signals_selected[chat_id]:
10621075
sigID = self.logger.database.getSignalID(a[0], a[1])
@@ -1084,11 +1097,10 @@ def signalsDeviceSubHandlerAns(self, bot, chat_id, strung):
10841097
evtext += evs[0][3]+' am '+ dt.datetime.fromtimestamp(evs[0][4]).strftime("%d.%m.%Y %H:%M:%S")
10851098
self.send_message(chat_id,
10861099
translate('RTOC', 'Signal selected:\n{}\nEvents: {}').format(t, evtext), ParseMode.MARKDOWN, True, False)
1100+
return True
10871101
else:
1088-
self.send_message(chat_id=chat_id,
1089-
text=translate('RTOC', 'Signal names consist of\n<Device>.<Signal>\nYour message didn\'t look that way.\n'))
1090-
device = self.telegram_clients[str(chat_id)]['menu'].split(':')[0]
1091-
self.signalsDeviceSubHandler(bot, chat_id, device)
1102+
return False
1103+
10921104

10931105
def signalsSelectRangeHandler(self, bot, chat_id):
10941106
self.telegram_clients[str(chat_id)]['menu'] = "signalSelectRange"

RTOC/RTOC_GUI/ui/rtoc.ui

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
</widget>
3939
<widget class="QDockWidget" name="deviceWidget">
4040
<property name="sizePolicy">
41-
<sizepolicy hsizetype="Ignored" vsizetype="Preferred">
41+
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
4242
<horstretch>0</horstretch>
4343
<verstretch>0</verstretch>
4444
</sizepolicy>
@@ -156,7 +156,7 @@
156156
<x>0</x>
157157
<y>0</y>
158158
<width>398</width>
159-
<height>88</height>
159+
<height>95</height>
160160
</rect>
161161
</property>
162162
<property name="sizePolicy">
@@ -273,7 +273,7 @@
273273
<x>0</x>
274274
<y>0</y>
275275
<width>400</width>
276-
<height>98</height>
276+
<height>96</height>
277277
</rect>
278278
</property>
279279
<attribute name="label">

RTOC/locales/de_de.qm

516 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)