-
Notifications
You must be signed in to change notification settings - Fork 1
/
RepetierBot.py
6609 lines (6211 loc) · 345 KB
/
RepetierBot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
######################################################################################################################
# Repetier-Server_Telegram_Bot
# Copyright (c) 2020 Repetier-Server_Telegram_Bot [https://github.com/DanJunior78/Repetier-Server-Telegram-Bot]
# Owner: Daniel Glock, Germany Twitter: @Daniel_Glock
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
######################################################################################################################
import __main__ as main
import gettext
presLan = gettext
_ = presLan.gettext
import logging
import sys
import os
import platform
import locale
import datetime
import time
from datetime import timedelta
import arrow # Date ISO 8601
import threading, time, signal # threading libraries
import pathlib
import copy
import shutil
from urllib.parse import urlparse
import getpass
import json
from websocket import create_connection
import requests
import imageio
from pygifsicle import optimize #pip install pygifsicle + https://eternallybored.org/misc/gifsicle/
import cv2
import telegram
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from telegram import (InlineQueryResultArticle,
InputTextMessageContent,
InlineKeyboardButton,
InlineKeyboardMarkup,
ReplyKeyboardMarkup,
Animation,
ParseMode)
from telegram.ext import (Updater,
CommandHandler,
MessageHandler,
InlineQueryHandler,
CallbackQueryHandler,
Filters,
ConversationHandler)
from telegram.error import (TelegramError,
Unauthorized,
BadRequest,
TimedOut,
ChatMigrated,
NetworkError)
SW_VERSION = "1.1.3"
CFG_VERSION = "V1.1"
BRANCH = "main"
BRANCHBUGFIX = "bugfix"
EX_DEBUG = True
LANGUAGE = "de"
# Repetier-Server
RepetierServerIP = ""
RepetierServerPort = ""
RepetierServerWebcamIP = ""
MY_REPETIER_SERVER_API_KEY = ""
MessCnt = 0
# Bot Parameters
MY_TELEGRAM_TOKEN = ""
CHATID = ""
Printer = 1
# Thread cycle time in seconds
THRDSLOW = 10
THRDSTANDBY = 5
THRDIDLE = 2
THRDACTIVE = 1
THRDNOW = 0
THRDSEND = 2
THRDRECEIVE = 0.2
THRDORDERDATA = 1
THRDBOTCOM = 1
THRDMANAGER = 1
THRDMODELMAN = 2
THRDRESTART = 10
# Bot Handler communication levels
ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN = range(10)
ELEVEN, TWELVE, THIRTEEN, FOURTEEN, FIFTEEN, SIXTEEN, SEVENTEEN, EIGHTTEEN, NINETEEN, TWENTY = range(10,20)
TWENTYONE, TWENTYTWO, TWENTYTHREE, TWENTYFOUR, TWENTYFIVE, TWENTYSIX, TWENTYSEVEN, TWENTYEIGHT, TWENTYNINE, THIRTY = range(20,30)
# Check platform
checkPlatform = platform.platform()
# Create Logfile in sub folder of program
formatter=u'(%(threadName)-10s) - %(asctime)s - %(name)s - %(levelname)s - %(message)s'
now = datetime.datetime.now()
Uhrzeit = "{:%y%m%d_%H%M%S}"
PROGRAM_FILE = main.__file__
LOGFILEFOLDER = os.path.join(os.getcwd(), 'log')
pathlib.Path(LOGFILEFOLDER).mkdir(parents=False, exist_ok=True)
BASENAME = os.path.basename(PROGRAM_FILE)
FILENAME_NO_EXTENSION = os.path.splitext(BASENAME)[0]
PROGRAM_FILE_NO_EXT = os.path.splitext(PROGRAM_FILE)[0]
FILENAME_FILE_NO_EXT_WS = FILENAME_NO_EXTENSION + "Websocket"
LOGFILENAME = os.path.join(LOGFILEFOLDER, FILENAME_NO_EXTENSION + '.log')
LOGFILENAMEWS = os.path.join(LOGFILEFOLDER, FILENAME_FILE_NO_EXT_WS + '.log')
LOGFILECONFIG = os.path.join(LOGFILEFOLDER, 'log.conf')
# Configuration and external Data
## Configuration file
FILENAME_FILE_NO_EXT_CFG = FILENAME_NO_EXTENSION
CFGFILENAME = os.path.join(os.getcwd(), FILENAME_FILE_NO_EXT_CFG + '.json')
## Video & Gifs & Pictures & Model Pictures & Fonts & Update
PNGFILEFOLDER = os.path.join(os.getcwd(), 'pic', 'png')
GIFFILEFOLDER = os.path.join(os.getcwd(), 'pic', 'gif')
VIDFILEFOLDER = os.path.join(os.getcwd(), 'vid')
MODELFILEFOLDER = os.path.join(os.getcwd(), 'mod')
FONTSFILEFOLDER = os.path.join(os.getcwd(), 'fonts')
UPDATEFILEFOLDER = os.path.join(os.getcwd(), 'update')
UPDFILENAME="rsbversion.json"
UPDBASEURL="https://raw.githubusercontent.com/DanJunior78/Repetier-Server-Telegram-Bot/"
fontSmall = ImageFont.truetype(os.path.join(FONTSFILEFOLDER, 'NCS Rogueland Slab Bold.ttf'), 16)
fontMedium = ImageFont.truetype(os.path.join(FONTSFILEFOLDER, 'NCS Rogueland Slab Bold.ttf'), 34)
### Functions
# Program datasets inits and updates
def getNewPrinterConfig(slug = "NA", name = "NA"): # Printer dataset for the bot
printerConfig = {}
printerConfig['slug'] = slug
printerConfig['name'] = name
printerConfig['extrCoolTemp'] = 40
printerConfig['extrCoolTempExtComm'] = None
printerConfig['heatbCoolTemp'] = 40
printerConfig['heatbCoolTempExtComm'] = None
printerConfig['delayTimeAfterPrintPic'] = 0 # seconds
printerConfig['AfterPrintPicCamSelect'] = None
printerConfig['zHeightPrintPic'] = 1.0
printerConfig['zHeightPrintPicCamSelect'] = None
printerConfig['timeBasedPrintPic'] = 0 # minutes
printerConfig['timeBasedPrintPicCamSelect'] = None
return printerConfig
def getServerConfig(): # Program configuration dataset for the bot, including initialization for update reason
mainConfig = {}
mainConfig['LANGUAGE'] = "en"
mainConfig['MY_REPETIER_SERVER_API_KEY'] = ""
mainConfig['RepetierServerIP'] = ""
mainConfig['RepetierServerPort'] = ""
mainConfig['RepetierServerWebcamIP'] = ""
mainConfig['MY_TELEGRAM_ID'] = ""
mainConfig['MY_TELEGRAM_TOKEN'] = ""
return mainConfig
# Language Management
def changeLang(langSel = None):
global presLan
_ = presLan.gettext
langPath = os.path.join(os.getcwd(), 'locale')
logger.info("Language file folder: %s" % langPath)
if langSel == None:
if sys.platform.startswith('win'):
if os.getenv('LANG') is None:
lang, enc = locale.getdefaultlocale()
logger.info("Language OS: %s/%s" % locale.getdefaultlocale())
os.environ['LANG'] = lang
langSel = lang
else:
os.environ['LANG'] = '%s' % langSel
if gettext.find('RepetierBot', langPath) == None:
os.environ['LANG'] = 'en'
logger.info("Changed to alternative language english")
else:
logger.info("Changed language to \"%s\"" % langSel)
presLan = gettext.translation('RepetierBot', './locale')
logger.debug("Language file information: %s" % presLan._info)
presLan.install()
_ = presLan.gettext
# Logger setup
def setup_logger(name, formatter, level, log_file):
"""To setup as many loggers as you want"""
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
fileHdl = logging.handlers.TimedRotatingFileHandler(log_file,
when="midnight",
interval=1,
backupCount=7,
encoding = "UTF-8")
fileHdl.setLevel(logging.INFO)
fileHdl.setFormatter(logging.Formatter(formatter))
fileHdl.suffix = "%Y%m%d"
#fileHdl.extMatch = re.compile(r"^\d{8}$")
logger.addHandler(fileHdl)
if EX_DEBUG == True:
strHdl = logging.StreamHandler()
strHdl.setLevel(level)
strHdl.setFormatter(logging.Formatter(formatter))
logger.addHandler(strHdl)
logger.info("Logger: %s was activated in debug mode (%s). Level: %s" % (name, EX_DEBUG, level))
return logger
# Check configuration file and if entries missing or updates required, update dataset
def checkFileImport(data):
configCheckFileVersion = CFG_VERSION
configCheckServerData = getServerConfig()
configCheckPrinterData = getNewPrinterConfig()
try:
if data['version']['CFG_VERSION'] != CFG_VERSION:
logger.critical('Config file (JSON) upgrade file from version \"%s\" to version \"%s\"' % (data['version']['CFG_VERSION'], CFG_VERSION))
data['version']['CFG_VERSION'] = CFG_VERSION
else:
logger.debug('Config file (JSON) version: %s' % (CFG_VERSION))
except:
logger.critical('Config file (JSON) version: loaded standard content \"%s\"' % (CFG_VERSION))
data['version']['CFG_VERSION'] = CFG_VERSION
for posLabel, posData in configCheckServerData.items():
try:
dataLabelValid = data['server'][posLabel]
logger.debug('Config file (JSON) entry: %s with content: %s' % (posLabel, data['server'][posLabel]))
except:
logger.critical('Config file (JSON) entry: %s loaded standard content \"%s\"' % (posLabel, configCheckServerData[posLabel]))
data['server'][posLabel] = configCheckServerData[posLabel]
try:
dataLabelValid = data['printers']
logger.debug('Config file (JSON) printers root available')
except:
data['printers'] = []
logger.critical('Config file (JSON) printers root implemented')
for i in range(0,len(data['printers'])):
for posPrinterLabel, posPrinterData in configCheckPrinterData.items():
try:
dataLabelValid = data['printers'][i][posPrinterLabel]
logger.debug('Config file (JSON) entry: %s with content: %s' % (posPrinterLabel, data['printers'][i][posPrinterLabel]))
except:
logger.critical('Config file (JSON) entry: %s loaded standard content \"%s\"' % (posPrinterLabel, configCheckPrinterData[posPrinterLabel]))
data['printers'][i][posPrinterLabel] = configCheckPrinterData[posPrinterLabel]
return data
# Read and check configuration file
def impConfig():
global LANGUAGE,MY_REPETIER_SERVER_API_KEY,RepetierServerIP
global RepetierServerPort,MY_TELEGRAM_TOKEN,CHATID
global RepetierServerWebcamIP
global LOGFILENAME,LOGFILENAMEWS,PNGFILEFOLDER,GIFFILEFOLDER,VIDFILEFOLDER
global presLan
try:
with open(CFGFILENAME) as json_file:
data = json.load(json_file)
except:
logger.error("Configuration file not found - impConfig - : %s" % CFGFILENAME)
sys.exit()
try:
if data['gui']['testSuccess'] == True:
logger.info("Repetier Server setup was done before")
else:
logger.critical("Please do Repetier Server setup before running this program!!!")
except:
logger.error("Configuration file does not contain gui/testSuccess element")
data = checkFileImport(data)
try:
if data['version']['CFG_VERSION'] == CFG_VERSION:
logger.info("Configuration file matches: %s" % CFG_VERSION)
else:
logger.error("Configuration file version conflict: %s, instead of: %s" % (data['version']['CFG_VERSION'], CFG_VERSION))
except:
logger.error("Configuration file does not contain CFG_VERSION element")
sys.exit()
serverData = data['server']
try:
LANGUAGE = serverData['LANGUAGE']
logger.info("Repetier Server language: %s" % LANGUAGE)
except:
logger.error("Configuration file does not contain LANGUAGE element")
sys.exit()
if LANGUAGE != "":
changeLang(LANGUAGE)
try:
MY_REPETIER_SERVER_API_KEY = serverData['MY_REPETIER_SERVER_API_KEY']
logger.info("API Key Repetier Server: %s" % MY_REPETIER_SERVER_API_KEY)
except:
logger.error("Configuration file does not contain MY_REPETIER_SERVER_API_KEY element")
sys.exit()
try:
RepetierServerIP = serverData['RepetierServerIP']
logger.info("Repetier Server IP: %s" % RepetierServerIP)
except:
logger.error("Configuration file does not contain RepetierServerIP element")
sys.exit()
try:
RepetierServerPort = serverData['RepetierServerPort']
logger.info("Repetier Server Port: %s" % RepetierServerPort)
except:
logger.error("Configuration file does not contain RepetierServerPort element")
sys.exit()
try:
RepetierServerWebcamIP = serverData['RepetierServerWebcamIP']
logger.info("Repetier Server Webcam IP: %s" % RepetierServerWebcamIP)
except:
logger.error("Configuration file does not contain RepetierServerWebcamIP element")
sys.exit()
if RepetierServerWebcamIP == "":
RepetierServerWebcamIP = RepetierServerIP
data['server']['RepetierServerWebcamIP'] = RepetierServerWebcamIP
try:
MY_TELEGRAM_TOKEN = serverData['MY_TELEGRAM_TOKEN']
logger.info("Telegram Token: %s" % MY_TELEGRAM_TOKEN)
except:
logger.error("Configuration file does not contain MY_TELEGRAM_TOKEN element")
sys.exit()
try:
CHATID = serverData['MY_TELEGRAM_ID']
logger.info("Administrator Telegram ID: %s" % CHATID)
except:
logger.error("Configuration file does not contain MY_TELEGRAM_ID element")
sys.exit()
try:
with open(CFGFILENAME, 'w') as outfile:
json.dump(data, outfile)
except:
logger.error("Configuration file could not be saved")
logger.info("Configuration file successfull imported: %s" % CFGFILENAME)
return data
# Telegram main external functions
def telegramSendMsg(msg, reply_markup=None, chat_id=CHATID, token=MY_TELEGRAM_TOKEN, parse_mode=telegram.ParseMode.HTML):
bot = telegram.Bot(token=token)
return bot.sendMessage(chat_id=chat_id,
text=msg,
reply_markup=reply_markup,
parse_mode=parse_mode)
def telegramSendPic(pic, caption, reply_markup=None, chat_id=CHATID, token=MY_TELEGRAM_TOKEN, parse_mode=telegram.ParseMode.HTML):
bot = telegram.Bot(token=token)
return bot.send_photo(chat_id=chat_id,
photo=open(pic, 'rb'), # .encode('utf-8')
timeout=100,
caption=caption,
reply_markup=reply_markup,
parse_mode=parse_mode)
def telegramSendAnimation(anim, caption, reply_markup=None, chat_id=CHATID, token=MY_TELEGRAM_TOKEN, parse_mode=telegram.ParseMode.HTML):
bot = telegram.Bot(token=token)
return bot.send_animation(chat_id=chat_id,
animation=open(anim, 'rb'),
timeout=100,
caption=caption,
reply_markup=reply_markup,
parse_mode=parse_mode)
def telegramSendVideo(video, caption, reply_markup=None, chat_id=CHATID, token=MY_TELEGRAM_TOKEN, parse_mode=telegram.ParseMode.HTML):
bot = telegram.Bot(token=token)
return bot.send_video(chat_id=chat_id,
video=open(video, 'rb'),
timeout=100,
supports_streaming=True,
caption=caption,
reply_markup=reply_markup,
parse_mode=parse_mode)
def telegramSendDocument(file, caption, reply_markup=None, chat_id=CHATID, token=MY_TELEGRAM_TOKEN, parse_mode=telegram.ParseMode.HTML):
bot = telegram.Bot(token=token)
return bot.sendDocument(chat_id=chat_id,
document=open(file, 'rb'),
timeout=100,
caption=caption,
reply_markup=reply_markup,
parse_mode=parse_mode)
def telegramEditMsg(msg, message_id, reply_markup=None, chat_id=CHATID, token=MY_TELEGRAM_TOKEN, parse_mode=telegram.ParseMode.HTML):
bot = telegram.Bot(token=token)
return bot.edit_message_text(chat_id=chat_id,
message_id=message_id,
text=msg,
reply_markup=reply_markup,
parse_mode=parse_mode)
def telegramEditCapt(caption, message_id, reply_markup=None, chat_id=CHATID, token=MY_TELEGRAM_TOKEN, parse_mode=telegram.ParseMode.HTML):
bot = telegram.Bot(token=token)
return bot.edit_message_caption(chat_id=chat_id,
message_id=message_id,
caption=caption,
reply_markup=reply_markup,
parse_mode=parse_mode)
def telegramEditReplyMarkup(message_id, reply_markup=None, chat_id=CHATID, token=MY_TELEGRAM_TOKEN):
bot = telegram.Bot(token=token)
return bot.edit_message_reply_markup(chat_id=chat_id,
message_id=message_id,
reply_markup=reply_markup,
timeout=60)
def telegramDelMsg(message_id, chat_id=CHATID, token=MY_TELEGRAM_TOKEN):
bot = telegram.Bot(token=token)
return bot.deleteMessage(chat_id=chat_id,
message_id=message_id)
def telegramChatAction(action, chat_id=CHATID, token=MY_TELEGRAM_TOKEN):
bot = telegram.Bot(token=token)
bot.sendChatAction(chat_id=chat_id ,
action = action)
# telegram.ChatAction.TYPING
# .FIND_LOCATION
# .RECORD_AUDIO
# .RECORD_VIDEO
# .RECORD_VIDEO_NOTE
# .UPLOAD_AUDIO
# .UPLOAD_DOCUMENT
# .UPLOAD_PHOTO
# .UPLOAD_VIDEO
# .UPLOAD_VIDEO_NOTE
# Check values for input
def isFloat(str):
try:
float(str)
except ValueError:
return False
return True
def isInt(str):
try:
int(str)
except ValueError:
return False
return True
# Format day and time (arrow) for actual prints
def getTimeDelta(deltaT = 0): # in seconds (datetime..timedelta.total_seconds())
seconds = int(deltaT)
seconds_in_day = 60 * 60 * 24
seconds_in_hour = 60 * 60
seconds_in_minute = 60
days = seconds // seconds_in_day
hours = (seconds - (days * seconds_in_day)) // seconds_in_hour
minutes = (seconds - (days * seconds_in_day) - (hours * seconds_in_hour)) // seconds_in_minute
second = seconds % 60
if second < 10:
secondStr = "0%s"%second
else:
secondStr = "%s"%second
if minutes < 10:
minutesStr = "0%s"%minutes
else:
minutesStr = "%s"%minutes
if hours < 10:
hoursStr = "0%s"%hours
else:
hoursStr = "%s"%hours
if days > 0:
message="%sd - %s:%s:%s" % (days,hoursStr,minutesStr,secondStr)
return message
elif hours > 0:
message="%s:%s:%s" % (hoursStr,minutesStr,secondStr)
return message
elif minutes > 0:
message="00:%s:%s" % (minutesStr,secondStr)
return message
else:
message="00:00:%s" % (secondStr)
return message
def getGranularity(deltaT = 0): # in seconds (datetime..timedelta.total_seconds())
seconds = int(deltaT)
seconds_in_day = 60 * 60 * 24
seconds_in_hour = 60 * 60
seconds_in_minute = 60
days = seconds // seconds_in_day
hours = (seconds - (days * seconds_in_day)) // seconds_in_hour
minutes = (seconds - (days * seconds_in_day) - (hours * seconds_in_hour)) // seconds_in_minute
second = seconds % 60
if days > 0:
granularity=["day","hour", "minute","second"]
return granularity
elif hours > 0:
granularity=["hour", "minute","second"]
return granularity
elif minutes > 0:
granularity=["minute","second"]
return granularity
else:
granularity=["second"]
return granularity
def getTimeToGo(start = 0, timeToPrint = 0):
global LANGUAGE
present = arrow.now()
present = present.replace(tzinfo='UTC')
printFinishTime = arrow.get(int(start) + int(timeToPrint))#, 'Europe/Berlin') #Europe/Berlin
timeToGo = printFinishTime - present
message = printFinishTime.humanize(present, locale=LANGUAGE, granularity=getGranularity(timeToGo.total_seconds())) # LANGUAGE # 'de'
return message
def getTimeGone(start = 0):
global LANGUAGE
present = arrow.now()
present = present.replace(tzinfo='UTC')
printStart = arrow.get(int(start))
actPrintTime = present - printStart
message = printStart.humanize(present, locale=LANGUAGE,granularity=getGranularity(actPrintTime.total_seconds()))
return message
def error_callback(update, error): # Telegram bot error handling
"""
Handle errors in the dispatcher and decide which errors are just logged and which errors are important enough to
trigger a message to the admin.
"""
try:
telegramSendMsg(_("BOT Error!!! Please try again.") + "\n %s" % error.error,reply_markup=None, chat_id=CHATID, token=MY_TELEGRAM_TOKEN)
raise error.error
except telegram.error.BadRequest:
logger.error('Bot Bad Request "%s"' % error.error)
except telegram.error.TimedOut:
logger.error('Bot TimedOut "%s"' % error.error)
except:
logger.error('Bot Error "%s"' % error.error)
def checkUserIDValid(update, chatID=CHATID):# Telegram check user ID
if update.effective_chat.id == chatID:
return True
else:
return False
# Telegram interaction functions
def build_menu(buttons,
n_cols,
header_buttons=None,
footer_buttons=None):
"""
:param buttons: a list of buttons.
:param n_cols: how many columns to show the butt,ons in
:param header_buttons: list of buttons appended to the beginning
:param footer_buttons: list of buttons added to the end
:return: the menu
"""
menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
if header_buttons:
menu.insert(0, header_buttons)
if footer_buttons:
menu.append(footer_buttons)
return InlineKeyboardMarkup(menu)
def getStartKeyboard(userKeyb = []):# Main keyboard layout at start of bot for printer
stdKeyb = []
stdKeyb.append(InlineKeyboardButton(_("End"), callback_data='End'))
reply_markup = build_menu(userKeyb,
1,
footer_buttons=stdKeyb)
return reply_markup
def getKeyboard(userKeyb = [], back = ""):# Main keyboard layout of bot for printer levels below
stdKeyb = []
stdKeyb.append(InlineKeyboardButton(_("Back"), callback_data='Back'))
stdKeyb.append(InlineKeyboardButton(_("End"), callback_data='End'))
reply_markup = build_menu(userKeyb,
2,
footer_buttons=stdKeyb)
return reply_markup
def getSpecialKeyboard(headerKeyb = [], userKeyb = [], back = ""):# Main keyboard layout of bot for printer levels below
stdKeyb = []
stdKeyb.append(InlineKeyboardButton(_("Back"), callback_data='Back'))
stdKeyb.append(InlineKeyboardButton(_("End"), callback_data='End'))
reply_markup = build_menu(userKeyb,
2,
footer_buttons=stdKeyb,
header_buttons=headerKeyb)
return reply_markup
def getMsgKeyboard():# Message keyboard add ons
userKeyb = []
msg = botThreads.getServerDataStorage(action="messages")
for message in msg:
userKeyb.append(InlineKeyboardButton(message['id'], callback_data=message['id']))
stdKeyb = []
stdKeyb.append(InlineKeyboardButton(_("End"), callback_data='End'))
reply_markup = build_menu(userKeyb,
4,
footer_buttons=stdKeyb)
return reply_markup
def checkStartKeys(slug):# Check start keyboard add ons
key = []
msg = botThreads.getServerDataStorage(action="listExternalCommands")
msg2 = botThreads.getPrinterDataStorage(slug=slug, action="getPrinterConfig")
listPrinters = botThreads.getPrinterDataStorage(slug, "listPrinter")
if msg == "Error" or msg2 == "Error" or listPrinters == "Error":
return key
if len(msg) > 0:
key.append(InlineKeyboardButton(_("ExtCommands"), callback_data='ExtCommands'))
for webcam in range(0,len(msg2['webcams'])):
key.append(InlineKeyboardButton(_('Webcam %s') % str(webcam + 1), callback_data='Webcam %s' % str(webcam + 1)))
if len(msg2['quickCommands']) > 0:
key.append(InlineKeyboardButton(_('Quick Commands'), callback_data='QuickCommands'))
if listPrinters['online'] == 1 and listPrinters['active'] == True:
key.append(InlineKeyboardButton(_('Printer'), callback_data='HandlePrinter'))
key.append(InlineKeyboardButton(_('Settings'), callback_data='Settings'))
if not botThreads.botData['server']['update']['actual']:
key.append(InlineKeyboardButton(_('Update to %s') % botThreads.botData['server']['update']['latest'], callback_data='UpdateBot'))
return key
def getLogfilesKeyboard():
key = []
for file in os.listdir(LOGFILEFOLDER):
if file.endswith(FILENAME_NO_EXTENSION + '.log'):
buf = {}
buf['filename'] = file
key.append(InlineKeyboardButton(("%s") % (buf['filename']), callback_data=buf['filename']))
key.append(InlineKeyboardButton(_("database"), callback_data='database'))
key.append(InlineKeyboardButton(_("Active Threads"), callback_data='threads'))
return key
def getRemPrinterFromBotKeyboard():
key = []
for printer in botThreads.botData['printers']:
key.append(InlineKeyboardButton(_("Remove %s") % (printer), callback_data=printer))
return key
def getRepetierBotStatsKeyboard():
key = []
for stats in botThreads.botData['server']['dataRepetier']['historySummary']:
key.append(InlineKeyboardButton(stats, callback_data=stats))
return key
def getExtCommands():# Get external commands from server
key = []
msg = botThreads.getServerDataStorage(action="listExternalCommands")
if msg == "Error":
return key
for item in msg:
key.append(InlineKeyboardButton(item['name'], callback_data=item['id']))
return key
def getExtCommandsConfirmButton(command):# Get external command OK button
key = []
msg = botThreads.getServerDataStorage(action="listExternalCommands")
if msg == "Error":
return key
for item in msg:
if item['id'] == command:
key.append(InlineKeyboardButton(_("OK"), callback_data='OK'))
return key
def getExtCommandsConfirmText(command):# Get external commands confirmation text from server
msg = botThreads.getServerDataStorage(action="listExternalCommands")
if msg == "Error":
return "Error"
for item in msg:
if item['id'] == command:
return item['confirm']
def getWebcamConfig(slug, update):# Get webcam configuration from server
queryData = update.callback_query.data
key = []
msg2 = botThreads.getPrinterDataStorage(slug=slug, action="getPrinterConfig")
if msg2 == "Error":
return key
x = int(queryData.split()[1]) - 1
if msg2['webcams'][x]['dynamicUrl'] != "":
key.append(InlineKeyboardButton(_('Send Video Camera %s') % str(x + 1), callback_data='Send Video %s' % str(x + 1))) # 'Sende Video %s' % str(webcam + 1)
if msg2['webcams'][x]['staticUrl'] != "":
key.append(InlineKeyboardButton(_('Send Gif Camera %s') % str(x + 1), callback_data='Send Gif %s' % str(x + 1)))
key.append(InlineKeyboardButton(_('Send Png Camera %s') % str(x + 1), callback_data='Send Png %s' % str(x + 1)))
return key
def getQuickCommandsButton(slug):# Get quick command configuration from server
key = []
msg2 = botThreads.getPrinterDataStorage(slug=slug, action="getPrinterConfig")
if msg2 == "Error":
loggerWS.error("Request error getPrinterConfig in getQuickCommandsButton for printer: %s" % str(slug))
return key
quickCom = msg2['quickCommands']
for item in quickCom:
key.append(InlineKeyboardButton(item['name'], callback_data=item['name']))
return key
def getSettingsButton(slug):# Get settings configuration from config file
key = []
for printer in botThreads.botData['printers']:
if printer == slug:
item = botThreads.botData['printers'][printer]['config']
key.append(InlineKeyboardButton(_("Extr. cool down: %s°C") % item['extrCoolTemp'], callback_data='Extruder Temp Limit %s' % item['extrCoolTemp']))
if item['extrCoolTempExtComm'] != None:
msg = botThreads.getServerDataStorage(action="listExternalCommands")
for msgitem in msg:
if item['extrCoolTempExtComm'] == msgitem['id']:
key.append(InlineKeyboardButton(_("ExtCom: %s") % msgitem['name'], callback_data='ExtCommand Temp Limit %d' % msgitem['id']))
else:
key.append(InlineKeyboardButton(_("ExtCom temp. dis."), callback_data='ExtCommand Temp Limit None'))
key.append(InlineKeyboardButton(_("Heatb. cool down: %s°C") % item['heatbCoolTemp'], callback_data='Heatbed Temp Limit %s' % item['heatbCoolTemp']))
if item['heatbCoolTempExtComm'] != None:
msg = botThreads.getServerDataStorage(action="listExternalCommands")
for msgitem in msg:
if item['heatbCoolTempExtComm'] == msgitem['id']:
key.append(InlineKeyboardButton(_("HeatbCom: %s") % msgitem['name'], callback_data='HeatbCommand Temp Limit %d' % msgitem['id']))
else:
key.append(InlineKeyboardButton(_("HeatbCom temp. dis."), callback_data='HeatbCommand Temp Limit None'))
key.append(InlineKeyboardButton(_("Pic after print: %ss") % item['delayTimeAfterPrintPic'], callback_data='Print after time %s' % item['delayTimeAfterPrintPic']))
if item['AfterPrintPicCamSelect'] != None:
key.append(InlineKeyboardButton(_("From Cam: %s") % str(item['AfterPrintPicCamSelect']+1), callback_data='Send Png %s' % str(item['AfterPrintPicCamSelect'])))
else:
key.append(InlineKeyboardButton(_("Pic disabled"), callback_data='Send Png None'))
key.append(InlineKeyboardButton(_("Pic after z height: %smm") % item['zHeightPrintPic'], callback_data='zHeight Value %s' % item['zHeightPrintPic']))
if item['zHeightPrintPicCamSelect'] != None:
key.append(InlineKeyboardButton(_("From Cam: %s") % str(item['zHeightPrintPicCamSelect']+1), callback_data='Send zHeight Png %s' % str(item['zHeightPrintPicCamSelect'])))
else:
key.append(InlineKeyboardButton(_("Pic disabled"), callback_data='Send zHeight Png None'))
key.append(InlineKeyboardButton(_("Pic after time: %s min") % item['timeBasedPrintPic'], callback_data='Print time based time %s' % item['timeBasedPrintPic']))
if item['timeBasedPrintPicCamSelect'] != None:
key.append(InlineKeyboardButton(_("From Cam: %s") % str(item['timeBasedPrintPicCamSelect']+1), callback_data='Send time based Png %s' % str(item['timeBasedPrintPicCamSelect'])))
else:
key.append(InlineKeyboardButton(_("Pic disabled"), callback_data='Send time based Png None'))
return key
def getExtComAndDisableButton():# Get external command buttons and disable button
key = getExtCommands()
key.append(InlineKeyboardButton(_("disable ExtCom"), callback_data='ExtCommand Temp Limit Disable'))
return key
def getAfterPrintWebcamAndDisableButton(slug):# Get webcam buttons and disable button
key = getAllWebcamsFromPrinterAfter(slug)
key.append(InlineKeyboardButton(_("disable Pic"), callback_data='Send Png None'))
return key
def getZHeightPrintWebcamAndDisableButton(slug):# Get webcam buttons and disable button
key = getAllWebcamsFromPrinterZHeight(slug)
key.append(InlineKeyboardButton(_("disable Pic"), callback_data='Send zHeight Png None'))
return key
def getTimeBasedPrintWebcamAndDisableButton(slug):# Get webcam buttons and disable button
key = getAllWebcamsFromPrinterTimeBased(slug)
key.append(InlineKeyboardButton(_("disable Pic"), callback_data='Send time based Png None'))
return key
def getAllWebcamsFromPrinterAfter(slug):# Get available webcams from server
key = []
msg2 = botThreads.getPrinterDataStorage(slug=slug, action="getPrinterConfig")
if msg2 == "Error":
return key
for x in range(0, len(msg2['webcams'])):
if msg2['webcams'][x]['staticUrl'] != "":
key.append(InlineKeyboardButton(_('Send Png Camera %s') % str(x + 1), callback_data='Send Png %s' % str(x + 1)))
return key
def getAllWebcamsFromPrinterZHeight(slug):# Get available webcams from server
key = []
msg2 = botThreads.getPrinterDataStorage(slug=slug, action="getPrinterConfig")
if msg2 == "Error":
return key
for x in range(0, len(msg2['webcams'])):
if msg2['webcams'][x]['staticUrl'] != "":
key.append(InlineKeyboardButton(_('Send Png Camera %s') % str(x + 1), callback_data='Send zHeight Png %s' % str(x + 1)))
return key
def getAllWebcamsFromPrinterTimeBased(slug):# Get available webcams from server
key = []
msg2 = botThreads.getPrinterDataStorage(slug=slug, action="getPrinterConfig")
if msg2 == "Error":
return key
for x in range(0, len(msg2['webcams'])):
if msg2['webcams'][x]['staticUrl'] != "":
key.append(InlineKeyboardButton(_('Send Png Camera %s') % str(x + 1), callback_data='Send time based Png %s' % str(x + 1)))
return key
def getOKButton():# Get OK button
key = []
key.append(InlineKeyboardButton(_("OK"), callback_data='OK'))
return key
def getStartPrintButton(slug):# Get OK button
key = []
key.append(InlineKeyboardButton(_("Printer queue"), callback_data='Queue'))
stateLists = botThreads.getPrinterDataStorage(slug, "stateList")
if stateLists != "Error":
for i in range(0,len(stateLists['fans'])):
key.append(InlineKeyboardButton((_("Fan speed") + " %d" % (i+1)), callback_data="FanSpeed %d" % i))
for i in range(0,len(stateLists['extruder'])):
key.append(InlineKeyboardButton((_("Extr temp") + " %d" % (i+1)), callback_data="ExtruderTemperature %d" % i))
for i in range(0,len(stateLists['heatedBeds'])):
key.append(InlineKeyboardButton((_("Bed temp") + " %d" % (i+1)), callback_data="BedTemperature %d" % i))
for i in range(0,len(stateLists['heatedChambers'])):
key.append(InlineKeyboardButton((_("Cham temp") + " %d" % (i+1)), callback_data="ChamberTemperature %d" % i))
return key
def getHandlePrintButton(slug):
key = []
key.append(InlineKeyboardButton(_("Flow multiplier"), callback_data='FlowMultiply'))
key.append(InlineKeyboardButton(_("Speed multiplier"), callback_data='SpeedMultiply'))
stateLists = botThreads.getPrinterDataStorage(slug, "stateList")
if stateLists != "Error":
for i in range(0,len(stateLists['fans'])):
key.append(InlineKeyboardButton((_("Fan speed") + " %d" % (i+1)), callback_data="FanSpeed %d" % i))
for i in range(0,len(stateLists['extruder'])):
key.append(InlineKeyboardButton((_("Extr temp") + " %d" % (i+1)), callback_data="ExtruderTemperature %d" % i))
for i in range(0,len(stateLists['heatedBeds'])):
key.append(InlineKeyboardButton((_("Bed temp") + " %d" % (i+1)), callback_data="BedTemperature %d" % i))
for i in range(0,len(stateLists['heatedChambers'])):
key.append(InlineKeyboardButton((_("Cham temp") + " %d" % (i+1)), callback_data="ChamberTemperature %d" % i))
key.append(InlineKeyboardButton(_("Cancel print"), callback_data='Cancel'))
return key
def getPrintQueueText(slug, pos):# Get quick command text from server
fileList = []
thumbnPos = 0
filePathModel= pathlib.Path(os.path.join(MODELFILEFOLDER, slug))
pngCounter = sum(1 for x in pathlib.Path(filePathModel).glob('*.png') if x.is_file())
for eachFileInPath in pathlib.Path(filePathModel).glob('*.png'):
printData = {}
printData['id'] = int(os.path.splitext(os.path.basename(eachFileInPath))[0])
printData['file'] = eachFileInPath
fileList.append(printData)
listModels = botThreads.getPrinterDataStorage(slug, "listModels")
message = _("Printer Queue") + ":\n"
if pngCounter == 0:
message += "<b> " + _("No files on the Server") + "...</b>"
elif pngCounter > pos + 6:
for txt in range(pos, (pos+6)):
fileInfo = fileList[txt]
for anyModel in listModels['data']:
if anyModel['id'] == fileInfo['id']:
message += "<code> %d: %s, " % (thumbnPos+1,anyModel['name']) + _("Print Time: %s") % (getTimeDelta(anyModel['printTime'])) + "</code>\n"
thumbnPos += 1
else:
amountPic = pngCounter - pos
for pic in range(pos, pngCounter):
fileInfo = fileList[pic]
for anyModel in listModels['data']:
if anyModel['id'] == fileInfo['id']:
message += "<code> %d: %s, " % (thumbnPos+1,anyModel['name']) + _("Print Time: %s") % (getTimeDelta(anyModel['printTime'])) + "</code>\n"
thumbnPos += 1
return message
def getPreviewPicSetting(preMsg):
msg = {}
msg['msgLong'] = preMsg
msg['msgShort'] = preMsg
msg['id'] = 0
msg['actPrint'] = os.path.join(MODELFILEFOLDER,'preview.jpg')
return msg
def getPrintSelectData(slug, fileID):# Get print file data
filePathModel= pathlib.Path(os.path.join(MODELFILEFOLDER, slug))
listModels = botThreads.getPrinterDataStorage(slug, "listModels")
message = "<b> " + _("Print File") + ":</b>\n"
file = ""
idInt = int(fileID)
for eachFileInList in listModels['data']:
if eachFileInList['id'] == idInt:
filePathModelName = fileID + ".png"
file = pathlib.Path(os.path.join(filePathModel, filePathModelName))
message += "<code>" + _("Print: ") + ": %s" % (eachFileInList['name']) + "</code>\n"
if eachFileInList['notes'] != "":
message += "<code>" + _("Note") + ": %s" % (eachFileInList['notes']) + "</code>\n"
message += "<code>" + _("Print Time") + ": %s" % (getTimeDelta(eachFileInList['printTime'])) + "</code>\n"
message += "<code>" + _("Filament total") + ": %.2fm" % (eachFileInList['filamentTotal']/1000) + "</code>\n"
message += "<code>" + _("Slicer") + ": %s" % (eachFileInList['slicer']) + "</code>\n"
message += "<code>" + _("Created") + ": %s" % (arrow.get(int(eachFileInList['created'])).format('DD.MM.YYYY - HH:mm')) + "</code>\n"
message += "<code>" + _("Layers") + ": %d" % (int(eachFileInList['layer'])) + "</code>\n"
message += "<code>" + _("Printed") + ": %d" % (int(eachFileInList['printed'])) + "</code>\n"
if eachFileInList['fits']:
message += "<code>" + _("Fits On Heatbed: Yes") + "</code>\n"
else:
message += "<code>" + _("Fits On Heatbed: No") + "</code>\n"
msg = {}
msg['msgLong'] = message
msg['msgShort'] = message
msg['id'] = idInt
msg['actPrint'] = file
return msg, idInt
def getPrintQueueButton(slug, pos):# Get print queue
key = []
fileList = []
thumbnPos = 0
filePathModel= pathlib.Path(os.path.join(MODELFILEFOLDER, slug))
fileBackground = os.path.join(MODELFILEFOLDER,'background.jpg') # (827, 512)
filePreview = os.path.join(MODELFILEFOLDER,'preview.jpg') # (827, 512)
pngCounter = sum(1 for x in pathlib.Path(filePathModel).glob('*.png') if x.is_file())
key = getMoveQueueButton(pngCounter, pos)
for eachFileInPath in pathlib.Path(filePathModel).glob('*.png'):
printData = {}
printData['id'] = int(os.path.splitext(os.path.basename(eachFileInPath))[0])
printData['file'] = eachFileInPath
fileList.append(printData)
listModels = botThreads.getPrinterDataStorage(slug, "listModels")
if pngCounter == 0:
preview = Image.open(fileBackground)
drawPreview = ImageDraw.Draw(preview)
drawPreview.text((50, 256),_("No files on the Server"),(0,0,0),font=fontMedium)
preview.save(filePreview)
elif pngCounter > pos + 6:
preview = Image.open(fileBackground)
for pic in range(pos, (pos+6)):
fileInfo = fileList[pic]
for anyModel in listModels['data']:
if anyModel['id'] == fileInfo['id']:
preview = addThumbnail(pic=preview,
pos=thumbnPos,
text=anyModel['name'],
picThmbFile=fileInfo['file'])
key.append(InlineKeyboardButton(anyModel['name'], callback_data=str(anyModel['id'])))
thumbnPos += 1
preview.save(filePreview)
else:
preview = Image.open(fileBackground)
amountPic = pngCounter - pos
for pic in range(pos, pngCounter):
fileInfo = fileList[pic]
for anyModel in listModels['data']:
if anyModel['id'] == fileInfo['id']:
preview = addThumbnail(pic=preview,
pos=thumbnPos,
text=anyModel['name'],
picThmbFile=fileInfo['file'],
amountPic=amountPic)
key.append(InlineKeyboardButton(anyModel['name'], callback_data=str(anyModel['id'])))
thumbnPos += 1
preview.save(filePreview)
return key
def getMoveQueueButton(pngCounter, pos):
key = []
if pos > 12:
npos = pos - 12
if npos < 0:
npos = 0
key.append(InlineKeyboardButton("<<", callback_data="<< %s" % str(npos)))
if pos > 5:
npos = pos - 6
if npos < 0:
npos = 0
key.append(InlineKeyboardButton("<", callback_data="<< %s" % str(npos)))
if pngCounter-pos > 12:
npos = pos + 12
key.append(InlineKeyboardButton(">>", callback_data=">> %s" % str(npos)))
if pngCounter-pos > 6:
npos = pos + 6
key.append(InlineKeyboardButton(">", callback_data=">> %s" % str(npos)))
return key
def getPrintSelectionButton(slug, id):# Get print queue
key = []
key.append(InlineKeyboardButton("Print", callback_data=str(id)))
return key
def setFMultiplyButton():
key = []
key.append(InlineKeyboardButton("+10", callback_data="plus10"))
key.append(InlineKeyboardButton("-10", callback_data="minus10"))
key.append(InlineKeyboardButton("+5", callback_data="plus5"))
key.append(InlineKeyboardButton("-5", callback_data="minus5"))
key.append(InlineKeyboardButton("+1", callback_data="plus1"))
key.append(InlineKeyboardButton("-1", callback_data="minus1"))
return key
def setPrintFSpeedButton(queryData):
fan = int(queryData.split()[1])
key = []
key.append(InlineKeyboardButton("100%", callback_data="100 %d" % fan))
key.append(InlineKeyboardButton("90%", callback_data="90 %d" % fan))
key.append(InlineKeyboardButton("80%", callback_data="80 %d" % fan))