This repository has been archived by the owner on Nov 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.py
698 lines (621 loc) · 28.7 KB
/
parser.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
import json
import urllib
import requests
import logging
import smtplib
import traceback
import time
from os import listdir
from os.path import isfile, join
import dateutil.parser
import email
import feedparser
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from lxml import html
import ntpath
import xml.etree.ElementTree as ET
import os
import subprocess
import fritzconnection as fc
import couchdb
# google APIs authentication
from oauth2client.service_account import ServiceAccountCredentials
#from apiclient.discovery import build
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
#from apiclient.discovery import build
import datetime
from configparser import ConfigParser
class Parser:
config = ConfigParser()
config.read('config.ini')
def getPhoneList(self):
FRITZ_IP = self.config.get('main', 'FRITZ_IP')
FRITZ_USER = self.config.get('main', 'FRITZ_USER')
FRITZ_PASSWORD = self.config.get('main', 'FRITZ_PASSWORD')
result = "Master, versuche die Anrufe zu ermitteln.."
telitem = [
'Kein Call', 'Kein Call', 'Kein Call', 'Kein Call', 'Kein Call'
]
f = fc.FritzConnection(
address=FRITZ_IP,
user=FRITZ_USER,
password=FRITZ_PASSWORD)
fritz = f.call_action('X_AVM-DE_OnTel', 'GetCallList')
print("This is the URL for the callers, including session token for now: " +
fritz["NewCallListURL"])
xmlhandle = urllib.request.urlopen(fritz["NewCallListURL"])
xmlresult = xmlhandle.read()
xmlhandle.close()
root = ET.fromstring(xmlresult)
result = "Master, hier die verpassten Anrufe (letzte 5):\n"
thisCall = ""
maxResults = 4
countedresults = 0
for callerID in root.iter('Call'):
if callerID.find("Type").text == '2':
callDate = callerID.find("Date").text
inPhoneBook = callerID.find("Name").text
callerNumber = callerID.find("Caller").text
thisCall = callDate + ":\n"
if callerNumber is not None:
thisCall = thisCall + callerNumber
if inPhoneBook is not None:
thisCall = thisCall + " (" + inPhoneBook + ")"
thisCall = thisCall + "\n"
telitem[countedresults] = thisCall
result = result + thisCall
countedresults = countedresults + 1
# print countedresults
if countedresults > maxResults:
# print "break now"
break
return {'reply': result, 'tellist': telitem}
def getCalendarEvents(self):
GOOGLECALENDAR_ID = self.config.get('main', 'GOOGLECALENDAR_ID')
result = "Master, hier die folgenden Meetings..\n"
calitem = [
'Kein Termin', 'Kein Termin', 'Kein Termin', 'Kein Termin',
'Kein Termin'
]
try:
scopes = ['https://www.googleapis.com/auth/calendar']
credentials = ServiceAccountCredentials.from_json_keyfile_name(
'google-credentials.json', scopes)
cal = build('calendar', 'v3', credentials=credentials,
cache_discovery=False)
now = datetime.datetime.utcnow().isoformat(
) + 'Z' # 'Z' indicates UTC time
eventsResult = cal.events().list(
calendarId=GOOGLECALENDAR_ID,
timeMin=now,
maxResults=5,
singleEvents=True,
orderBy='startTime').execute()
calcounter = 0
for i in eventsResult['items']:
eventtime = i['start']
resulttime = ''
if 'dateTime' in eventtime:
resulttime = eventtime['dateTime']
if 'date' in eventtime:
resulttime = eventtime['date']
parsedTime = dateutil.parser.parse(
resulttime) # reformat the time
resulttime = parsedTime.strftime('%a, %d-%m, %H:%M')
result = result + resulttime + '\n' + i['summary'] + '\n'
calitem[calcounter] = resulttime + ': ' + i['summary']
calcounter = calcounter + 1
# cal.close()
return {'reply': result, 'calendarlist': calitem}
except:
logging.exception("Exception when retrieving calendar data.")
return {'reply': 'did not work', 'calendarlist': calitem}
def getKitaTraffic(self):
# check google maps for the traffic to kindergarten
GOOGLE_API_KEY = self.config.get('main', 'GOOGLE_API_KEY')
GOOGLETRAFFIC_SOURCE = self.config.get('main', 'GOOGLETRAFFIC_SOURCE')
GOOGLETRAFFIC_DESTINATION = self.config.get(
'main', 'GOOGLETRAFFIC_DESTINATION')
traffic_to = urllib.request.urlopen(
'https://maps.googleapis.com/maps/api/distancematrix/json?origins='+GOOGLETRAFFIC_SOURCE +
'&destinations='+GOOGLETRAFFIC_DESTINATION +
'&departure_time=now&mode=driving&language=de-DE&key='
+ GOOGLE_API_KEY)
traffic_back = urllib.request.urlopen(
'https://maps.googleapis.com/maps/api/distancematrix/json?origins='+GOOGLETRAFFIC_DESTINATION +
'&destinations='+GOOGLETRAFFIC_SOURCE +
'&departure_time=now&mode=driving&language=de-DE&key='
+ GOOGLE_API_KEY)
logging.info("Resulting traffic to destionation: " + str(traffic_to))
logging.info("Resulting traffic to source: " + str(traffic_back))
data_to = json.loads(traffic_to.read().decode('UTF-8'))
data_back = json.loads(traffic_back.read().decode('UTF-8'))
resultstring = "Master, hier aktueller Verkehr zur Kita: " + \
data_to['rows'][0]['elements'][0]['duration_in_traffic']['text'] + \
", Rueckweg: " + \
data_back['rows'][0]['elements'][0]['duration_in_traffic']['text']
durationValue = round(
data_to['rows'][0]['elements'][0]['duration_in_traffic']['value'])
return {
'reply':
resultstring,
'toDuration':
durationValue
}
def getFuelPrice(self):
# check fuel price in my neighbourhood
TANKEN_APIKEY = self.config.get('main', 'TANKEN_APIKEY')
TANKEN_LOCATION = self.config.get('main', 'TANKEN_LOCATION')
r = urllib.request.urlopen(
'https://creativecommons.tankerkoenig.de/json/prices.php?ids=' + TANKEN_LOCATION+'&apikey=' + TANKEN_APIKEY)
fuelprice = json.loads(r.read().decode('UTF-8'))
resultstring = ''
try:
resultstring = "Master, hier der Tankpreis E10 bei Aral: " + str(
fuelprice['prices'][TANKEN_LOCATION]
['e10'])
return {
'reply':
str(resultstring),
'fuelPrice':
str(fuelprice['prices'][TANKEN_LOCATION]
['e10'])
}
except Exception:
return {'reply': 'Fuel station is closed', 'fuelPrice': 'N/A'}
def startAlarm(self):
# this starts motion detection for a connected webcam
# clean up alarmimages
result = "Alarm wurde aktiviert.."
try:
subprocess.call(
'rm -rf /home/pi/optimat/alarmimages/*', shell=True)
# start daemon
# maybe this? on_event_end /home/guillo/bin/motion_encode_and_delete_jpgs gap 10
subprocess.call('nohup sudo motion -p pid.txt', shell=True)
self.config.set("main", "ALARM_IS_ON", "1")
result = "Alarm wurde aktiviert.."
except Exception:
logging.exception("Could not activate alarm")
result = "Alarm wurde nicht aktiviert, technischer Fehler.."
return {'reply': result}
def stopAlarm(self):
pid = '0'
with open('pid.txt', 'r') as f:
pid = f.read().replace('\n', '')
f.close()
print('Killing process motion with pid: ' + pid)
subprocess.call('sudo kill ' + pid, shell=True)
self.config.set("main", "ALARM_IS_ON", "0")
result = "Alarm wurde de-aktiviert.."
return {'reply': result}
def startEnergy(self):
# TODO change this to FritzDECT, deleted code for old switches
result = "Strom ist an.. (Lichter? Buegeleisen? Wasserkocher?)"
return {'reply': result}
def stopEnergy(self):
# TODO change this to FritzDECT, deleted code for old switches
result = "Strom ist aus.. (Lichter? Buegeleisen? Wasserkocher?)"
return {'reply': result}
def sendAlarm(self):
# TODO delete this?
resultstring = "Master, das Video wurde per eMail verschickt..."
return {'reply': resultstring}
def listFilesNAS(self, path):
# TODO, this does not work yet, because the list call returns different format/values depending on number of files
# result = 'Your files in ' + path + ' are:\n'
# filestation = FileStation(config.NAS_IP, config.NAS_USER, config.NAS_PASSWORD)
# resultdict = filestation.list('/' + path, limit=0)
# resultdict = filestation.list('/' + path, limit=0)['files'] #e.g. ourdata
# print resultdict
# for key in resultdict:
# print key['path']
# result = result + key['path'] + '\n'
return {'reply': 'todo'}
def downloadFilesNAS(self, myfile, method='download'):
NAS_IP = self.config.get('main', 'NAS_IP')
NAS_USER = self.config.get('main', 'NAS_USER')
NAS_PASSWORD = self.config.get('main', 'NAS_PASSWORD')
NAS_BASEFOLDER = self.config.get('main', 'NAS_BASEFOLDER')
authString = json.load(
urllib.request.urlopen(
'http://' + NAS_IP +
':5000/webapi/auth.cgi?api=SYNO.API.Auth&version=6&method=login&account='
+ NAS_USER + '&passwd=' + NAS_PASSWORD +
'&session=FileStation&format=sid'))
sidToken = authString['data']['sid']
downloadedFile = urllib.urlretrieve(
'http://' + NAS_IP +
':5000/webapi/entry.cgi?api=SYNO.FileStation.Download&version=2&method=download&path='+NAS_BASEFOLDER +
+ myfile + '&mode=download&_sid=' + sidToken,
'filecache/' + ntpath.basename(myfile))
# extract file from whole path
newpath = 'filecache/' + ntpath.basename(myfile)
return newpath
def sendFileViaEmail(self, myfile):
newpath = self.downloadFilesNAS(
myfile) # returns the location of the file locally
mail_user = self.config.get('main', 'MAIL_SENDER')
mail_pwd = self.config.get('main', 'MAIL_PASSWORD')
mail_to = self.config.get('main', 'MAIL_RECIPIENT')
MAIL_SERVER = self.config.get('main', 'MAIL_SERVER')
msg = MIMEMultipart()
msg['From'] = mail_user
msg['To'] = mail_to
msg['Subject'] = 'Mail from Optimat for you..'
msg.attach(MIMEText("Hello Master! Hier das File.."))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(newpath, 'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(myfile))
msg.attach(part)
mailServer = smtplib.SMTP(MAIL_SERVER, 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(mail_user, mail_pwd)
mailServer.sendmail(mail_user, mail_to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
return
def getSBahnTraffic(self):
result = "Master, versuche die Verbindungen zu suchen.."
# result.encode('utf-8')
# TODO this is harcoded to Frankfurt West
page = requests.get(
'http://reiseauskunft.bahn.de/bin/bhftafel.exe/dn?ld=15079&rt=1&input=Frankfurt(Main)West%238002042&boardType=dep&time=actual&productsFilter=00001&REQTrain_name=4&start=yes&'
)
tree = html.fromstring(page.content)
result = "Master, das sind die naechsten Verbindungen der S4 ab Westbahnhof:\n"
# TODO when this is available as DB OpenData, change to API
# TODO something is wrong with the encoding here
for x in range(0, 5):
traintime = tree.xpath(
'//*[@id="journeyRow_' + str(x) + '"]/td[1]/text()')
delay = tree.xpath(
'//*[@id="journeyRow_' + str(x) + '"]/td[6]//span/text()')
traintimestring = ''.join(traintime).encode('utf-8')
delaytimestring = ''.join(delay).encode('utf-8')
result = result + "Zug um: " + \
str(traintimestring) + " mit " + str(delaytimestring) + "\n"
return {'reply': result}
def getBitcoinBalance(self):
result = "Master, hier Ihr Kontostand in Bitcoin. Sie sind sehr reich. Nicht.\n"
result.encode('utf-8')
BLOCKIO_APIKEY = self.config.get('main', 'BLOCKIO_APIKEY')
r = urllib.request.urlopen(
'https://block.io/api/v2/get_balance/?api_key=' + BLOCKIO_APIKEY)
balance = json.loads(r.read().decode('UTF-8'))
result = result + balance['data']['available_balance'] + \
', unconfirmed: ' + balance['data']['pending_received_balance']
return {'reply': result}
def transferBitcoins(self, request):
BLOCKIO_APIKEY = self.config.get('main', 'BLOCKIO_APIKEY')
BLOCKIO_TARGETWALLET = self.config.get('main', 'BLOCKIO_TARGETWALLET')
BLOCKIO_PIN = self.config.get('main', 'BLOCKIO_PIN')
tokens = request.split(' ')
amount = str(tokens[1])
target = BLOCKIO_TARGETWALLET # hardcoded for now
transaction_result = json.load(
urllib.request.urlopen(
'https://block.io/api/v2/withdraw/?api_key=' +
BLOCKIO_APIKEY + '&amounts=' + amount +
'&to_addresses=' + target + '&pin=' + BLOCKIO_PIN))
result = 'Master, ich habe ' + amount + ' bitcoins an Ihr Konto ueberwiesen'
return {'reply': result}
def checkStatus(self, inputstatus):
# this saves the current wellbeing psycho status.
# TODO do a proper chatbot here, not if/then
result = {
'reply': 'Wie geht es Dir heute?',
'keyboard': [['Gut', 'Schlecht'], ['Ganz OK', 'Superb']]
}
if inputstatus in ['gut', 'schlecht', 'ganz ok', 'superb']:
result = {
'reply': 'Warum?',
'keyboard': [['Arbeit', 'Beziehung'],
['Familie', 'Gesundheit']]
}
if inputstatus in ['arbeit']:
result = {
'reply': 'Warum?',
'keyboard': [['Chef', 'Kollegen'], ['Kunde', 'Inhalt']]
}
if inputstatus in ['beziehung']:
result = {
'reply': 'Warum?',
'keyboard': [['Erlebnis', 'Event'], ['Streit', 'Partner']]
}
if inputstatus in ['familie']:
result = {
'reply':
'Warum?',
'keyboard': [['Kinder', 'Verwandschaft'],
['Eltern', 'Schwiegereltern']]
}
if inputstatus in ['gesundheit']:
result = {
'reply': 'Warum?',
'keyboard': [['Schlapp', 'Fieber'],
['Arztbesuch', 'Uebelkeit']]
}
return result
def saveStatus(self, inputstatus):
# this saves the current psycho status to a local couchdb
COUCHDB_SERVER = self.config.get('main', 'COUCHDB_SERVER')
server = couchdb.Server(
url='http://' + COUCHDB_SERVER + ':5984/')
db = server['feely']
db.save({'status': inputstatus, 'timestamp': time.time()})
return {'reply': 'Danke, viel Erfolg heute noch'}
def checkWeather(self):
OPENWEATHER_APIKEY = self.config.get('main', 'OPENWEATHER_APIKEY')
OPENWEATHER_LOCATIONID = self.config.get(
'main', 'OPENWEATHER_LOCATIONID')
r = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?id=' +
OPENWEATHER_LOCATIONID+'&APPID=' + OPENWEATHER_APIKEY + '&units=metric')
temperature = json.loads(r.read().decode('UTF-8'))
t = temperature['main']['temp']
resultstring = 'Master, Temperatur ist bei ' + str(
t) + ' Grad Celsius'
return {'reply': resultstring, 'onlyTemp': str(t)}
def checkWeatherForecast(self):
# TODO this doesn't work on the chatbot yet, only dashboard?
OPENWEATHER_APIKEY = self.config.get('main', 'OPENWEATHER_APIKEY')
OPENWEATHER_LOCATIONID = self.config.get(
'main', 'OPENWEATHER_LOCATIONID')
r = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/forecast?id=' +
OPENWEATHER_LOCATIONID+'&APPID=' + OPENWEATHER_APIKEY + '&units=metric')
completeforecast = json.loads(r.read().decode('UTF-8'))
# print 'Forecast: ' + json.dumps(completeforecast)
forecast = []
for n in range(0, 7):
# print 'getting time..' + str(completeforecast['list'][n]['dt'])
time = datetime.datetime.fromtimestamp(
completeforecast['list'][n]['dt'])
temperature = completeforecast['list'][n]['main']['temp']
# print 'getting icon....' + str(completeforecast['list'][n])
icon = 'http://openweathermap.org/img/w/' + \
completeforecast['list'][n]['weather'][0]['icon'] + '.png'
# print 'Got time ' + str(time) + ' and forecast ' + str(temperature) + ' and icon ' + str(icon)
forecast.append((time.strftime('%H:%M'), str(int(temperature)),
str(icon)))
resultstring = 'Master, Temperatur in Koenigstein ist bei Grad Celsius'
return {'reply': resultstring, 'onlyForecast': forecast}
def checkNews(self):
try:
logging.info('Check news started...')
f = feedparser.parse(
'http://www.spiegel.de/schlagzeilen/tops/index.rss')
logging.info('Executed rss feed parse')
# collect headlines
newsitem = [
'No headlines right now..', 'No headlines right now..',
'No headlines right now..', 'No headlines right now..',
'No headlines right now..'
]
logging.info('Iterating over news')
for n in range(0, 5):
if 'title' in f.entries[n]:
logging.info('This is the news:' + f.entries[n]['title'])
newsitem[n] = f.entries[n]['title']
else:
logging.info(
'This is the broken RSS feed: %s', f.entries[n])
resultstring = 'Master, hier sind die aktuellen News von Spiegel Online:\n' + '\n'.join(
newsitem)
logging.info(
'Executed rss feed parse ,this is the result' + resultstring)
except Exception as e:
logging.error(traceback.format_exc())
return {'reply': resultstring, 'newslist': newsitem}
def getMotd(self):
try:
f = open("motd.txt", "r+")
logging.info("Setting a new topic")
result = f.readline()
f.close()
return {'reply': [result], 'motd': [result]}
except Exception:
logging.exception("Could not read message of the day from file")
return {'reply': 'Keine neue Nachricht', 'motd': "Keine neue Nachricht"}
def saveMotd(self, inputmessage):
try:
f = open("motd.txt", "w+")
logging.info("Setting a new topic")
f.write(inputmessage)
f.close()
return {'reply': "Saved motd: " + inputmessage, 'motd': [inputmessage]}
except Exception:
logging.exception("Save Topic went wrong")
def getCorona(self):
try:
r = urllib.request.urlopen(
'https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=GEN%20%3D%20%27HOCHTAUNUSKREIS%27&outFields=*&outSR=4326&f=json')
out = json.loads(r.read().decode('UTF-8'))
corona_hochtaunus = int(
round(out['features'][0]['attributes']['cases7_per_100k']))
r = urllib.request.urlopen(
'https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=GEN%20%3D%20%27FRANKFURT%20AM%20MAIN%27&outFields=*&outSR=4326&f=json')
out = json.loads(r.read().decode('UTF-8'))
corona_ffm = int(
round(out['features'][0]['attributes']['cases7_per_100k']))
r = urllib.request.urlopen(
'https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/Coronaf%C3%A4lle_in_den_Bundesl%C3%A4ndern/FeatureServer/0/query?where=LAN_ew_GEN%20%3D%20%27HESSEN%27&outFields=LAN_ew_EWZ,OBJECTID,Fallzahl,Aktualisierung,AGS_TXT,GlobalID,faelle_100000_EW,Shape__Area,Shape__Length,Death,cases7_bl_per_100k,OBJECTID_1,LAN_ew_GEN&returnGeometry=false&outSR=4326&f=json')
out = json.loads(r.read().decode('UTF-8'))
corona_hessen = int(
round(out['features'][0]['attributes']['cases7_bl_per_100k']))
return {'reply': "Corona data: " + "tbd", 'corona': [corona_hochtaunus, corona_ffm, corona_hessen]}
except Exception:
logging.exception("Save Topic went wrong")
def saveRandomMotd(self):
try:
f = open("motd.txt", "w+")
logging.info("Setting a new topic")
r = urllib.request.urlopen('http://quotes.rest/qod.json')
out = json.loads(r.read().decode('UTF-8'))
quote = out['contents']['quotes'][0]['quote'] + \
", " + out['contents']['quotes'][0]['author']
f.write(quote)
f.close()
return {'reply': "Saved motd: " + quote, 'motd': [quote]}
except Exception:
logging.exception("Save Topic went wrong")
def triggerFunction(self):
FUNCTION_URL = self.config.get('main', 'FUNCTION_URL')
try:
logging.info("Executing function")
r = urllib.request.urlopen(FUNCTION_URL)
return {'reply': 'Done'}
except Exception:
logging.exception("Save Topic went wrong")
def updateDashboard(self, displayFuel=False):
try:
logging.info("Update the dashboard..")
# initial data before the API call
dashdata = {
'traffic': '16m',
'fuel': '1.45',
'temperature': '18 C',
'miner': '50 C'
}
dashdata['tel'] = [
'Telefon A', 'Telefon B', 'Telefon C', 'Telefon D', 'Telefon E'
]
dashdata['news'] = ['News1', 'News2', 'News C', 'News D', 'News E']
dashdata['calendar'] = [
'Cal 1', 'Cal 2', 'Cal C', 'Cal D', 'Cal E'
]
dashdata['forecast'] = [('t', '12', 'ico')]
dashdata['miner'] = '0'
dashdata['reward'] = '0'
dashdata['motd'] = 'Nachricht des Tages'
dashdata['corona'] = '00'
# retrieved real data starts here:
logging.info("Getting Kita traffic..")
traffic = self.getKitaTraffic()
dashdata['traffic'] = str(
round(float(traffic['toDuration']) / 60)) + 'min'
logging.info("Getting Weather..")
weather = self.checkWeather()
dashdata['temperature'] = str(
int(round(float(weather['onlyTemp'])))) + ' C'
# logging.info("Logging temperatur for dashboard: " +
# dashdata['temperature'])
logging.info("Getting Weather forecast..")
forecast = self.checkWeatherForecast()
dashdata['forecast'] = forecast['onlyForecast']
logging.info("Getting News..")
news = self.checkNews(
)['newslist'] # news = list of news items from Spiegel online feed
dashdata['news'] = news
logging.info("Getting Phone List..")
tel = self.getPhoneList()['tellist']
dashdata['tel'] = tel
logging.info("Getting Calendar events..")
cal = self.getCalendarEvents()
dashdata['calendar'] = cal['calendarlist']
logging.info("Getting fuel price..")
fuel = self.getFuelPrice()
dashdata['fuel'] = str(fuel['fuelPrice']) + 'EUR'
logging.info("Getting MOTD..")
motd = self.getMotd()
dashdata['motd'] = motd['motd']
logging.info("Getting Corona numbers..")
corona = self.getCorona()
dashdata['corona'] = corona['corona']
# TODO this could be routed to any dashboard, not only the local one
logging.info("Posting all to dashboard..")
print(requests.post(
'http://localhost:5000/dashboard', json=dashdata))
except Exception as e:
print('Ohoh, something went wrong when updating the dashboard...')
print(e)
def parseInput(self, request):
# default reply if none of the keywords was used
result = {'reply': "Master, ich weiss nicht was Du meinst!"}
logging.info("Got request: " + str(request))
# send a message to the dashboard
if request.lower().find("thema") >= 0:
inputmessage = request[6:]
result = self.saveMotd(inputmessage)
# is it a file to be emailed from my NAS
if str.lower(request).find("send") >= 0:
print("file detected...")
myfile = request[5:]
self.sendFileViaEmail(myfile)
result = "eMail wurde verschickt, viel Spass damit!"
# is it a directory to be listed?
if request.find("list") >= 0:
path = request[5:]
result = self.listFilesNAS(path)
# file operations require case sensitivity, therefore insensitivity to the command comes here:
request = str.lower(request)
# is it some traffic information?
if request == ("verkehr kita"):
result = self.getKitaTraffic()
# calendar?
if request == ("kalender"):
result = self.getCalendarEvents()
# is it the delay of the SBahn information?
if request == ("sbahn"):
result = self.getSBahnTraffic()
# do we want last callers from fritz box?
if request == ("telefon"):
result = self.getPhoneList()
# Current fuel price
if request == ("tanken"):
result = self.getFuelPrice()
# someone in the house? video alarm
if request == ("alarm"):
result = self.sendAlarm()
# starting webcam
if request == ("alarm on"):
result = self.startAlarm()
# stopping webcam
if request == ("alarm off"):
result = self.stopAlarm()
# starting lights
if request == ("strom an"):
result = self.startEnergy()
# stopping lights
if request == ("strom aus"):
result = self.stopEnergy()
# get bitcon wallet status
if request == ("konto"):
result = self.getBitcoinBalance()
# send bitcon tos
if 'transfer' in request:
result = self.transferBitcoins(request)
# how are you doing
if request == ("status"):
result = self.checkStatus('status')
# how are you doing
# wetter
if request == ("wetter"):
result = self.checkWeather()
# spiegel online news
if request == ("news"):
result = self.checkNews()
# save status, TODO make this configurable
if request in [
'gut', 'schlecht', 'ganz ok', 'superb', 'arbeit', 'chef',
'kollegen', 'kunde', 'inhalt', 'beziehung', 'erlebnis',
'event', 'streit', 'partner', 'familie', 'kinder',
'verwandschaft', 'eltern', 'schwiegereltern', 'gesundheit',
'schlapp', 'fieber', 'arztbesuch', 'uebelkeit'
]:
self.saveStatus(request)
result = self.checkStatus(request)
return result