alles,was sich so angesammelt hat

This commit is contained in:
hubobel 2017-12-01 18:51:46 +01:00
parent 9ea4115722
commit 82d39233eb
38 changed files with 1720 additions and 0 deletions

11
.idea/HubobelsPython.iml generated Normal file
View file

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TestRunnerService">
<option name="PROJECT_TEST_RUNNER" value="Unittests" />
</component>
</module>

4
.idea/misc.xml generated Normal file
View file

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6.1 (/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6)" project-jdk-type="Python SDK" />
</project>

8
.idea/modules.xml generated Normal file
View file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/HubobelsPython.iml" filepath="$PROJECT_DIR$/.idea/HubobelsPython.iml" />
</modules>
</component>
</project>

BIN
Dienstag.pdf Normal file

Binary file not shown.

17
IFTT.py Normal file
View file

@ -0,0 +1,17 @@
import urllib.request
import requests
import datetime
datum = datetime.datetime.now().strftime("%H:%M")
print("Choose your third string.")
c = eval(input())
#email_alert(c)
url1 = "https://maker.ifttt.com/trigger/iCloud/with/key/foLJhy361EqeESdkssI-J?value1="
url2 = "&value2="
url = url1 + c + url2 + datum
print(url)
requests.get("https://maker.ifttt.com/trigger/iCloud/with/key/foLJhy361EqeESdkssI-J?value1=test_final&value2=12:05")
requests.get(url)

73
Kodi_Class 2.py Normal file
View file

@ -0,0 +1,73 @@
import urllib.request
class kodi():
def __init__(self,url="10.0.1.102"):
self.kodiurl="http://"+url+"/jsonrpc?request=%7B%22jsonrpc%22:%20%222.0%22,%20%22method%22:%20%22Player.GetItem%22,%20%22params%22:%20%7B%20%22properties%22:%20%5B%22title%22,%20%22album%22,%20%22artist%22,%20%22season%22,%20%22episode%22,%20%22duration%22,%20%22showtitle%22,%20%22tvshowid%22,%20%22thumbnail%22,%20%22file%22,%20%22fanart%22,%20%22streamdetails%22%5D,%20%22playerid%22:%201%20%7D,%20%22id%22:%20%22VideoGetItem%22%7D"
self.jsonString = self.JSON_holen
@property
def JSON_holen(self):
try:
antwort = urllib.request.urlopen(self.kodiurl)
b = (antwort.read())
self.jsonString = b.decode("utf-8")
return self.jsonString
except:
return None
def Suchen_nach(self, suchstring, json=""):
if json=="":
self.jsonString=self.JSON_holen
else:
self.jsonString=json
start = len(suchstring) + 3
ende = len(self.jsonString)
position = self.jsonString.find("\"" + suchstring, 46,ende)
if position > 0:
position2 = self.jsonString.find(",\"", position,ende)
wert = (self.jsonString[position + start:position2])
x = 0
while wert.isalnum() is False and x < 2:
wert = wert.strip("\"}][{")
x = x + 1
return wert
return None
def kodiitem(self, koditems=None):
if koditems is None:
koditems = {'episode': "", 'label': "", 'season': "", 'showtitle': "", 'type': "", 'title': ""}
a = self.JSON_holen
if a != None:
for i in koditems:
string = self.Suchen_nach(i, a)
if type(string)==str:
string = string.replace("ä", "ae").replace("Ä", "Ae").replace("ö", "oe").replace("Ö", "oe").replace(
"ü", "ue").replace("Ü", "Ue").replace(" ", "_").replace("-1","").replace("_"," ")
elif string == None:
string =""
koditems[i] = string
if "type" in koditems == "episode":
if len("season" in koditems) == 1:
koditems["season"] = "S0" + koditems["season"]
else:
koditems["season"] = "S" + koditems["season"]
if len(koditems["episode"]) == 1:
koditems["episode"] = "E0" + koditems["episode"]
else:
koditems["episode"] = "E" + koditems["episode"]
if "type" in koditems:
test = self.Suchen_nach("label", a)
if koditems["type"] =="unknown" and test !="":
koditems["type"]="Stream"
return koditems
items = {"episode": "","width": "","duration":"","type":""}
sz = kodi("10.0.1.101")
wz = kodi("10.0.1.102")
print((sz.kodiitem()))
print((sz.JSON_holen))
print((wz.kodiitem()))
print((wz.JSON_holen))

68
Liste.py Normal file
View file

@ -0,0 +1,68 @@
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import os
pfad = os.path.dirname(__file__)
def Nachricht(fradress, toadress, bccs, sub, attach):
fromaddr = fradress
toaddr = toadress
fobj = open(pfad + "/mpg/pass.txt")
passw = []
for line in fobj:
a = line.rstrip()
passw.append(a)
fobj.close()
pwd = passw[0]
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = sub
body = 'Hello World again and again and again'
msg.attach(MIMEText(body, 'plain'))
for each in attach:
filename = each
attachment = open(pfad + '/mpg/'+each, 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename= %s' % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, pwd)
text = msg.as_string()
server.sendmail(fromaddr, bccs, text)
server.quit()
return
fradress='carsten.richter77@gmail.com'
toadress='carsten.richter77@gmail.com'
sub='das ist der finale Standalonetest'
anhang = ['adressen.txt','heute.pdf']
fobj = open(pfad + "/mpg/adressen.txt")
bcc = []
for line in fobj:
a = line.rstrip()
bcc.append(a)
fobj.close()
Nachricht (fradress,toadress,bcc,sub,anhang)

BIN
Montag.pdf Normal file

Binary file not shown.

4
README 2.md Normal file
View file

@ -0,0 +1,4 @@
# mrRSS
ein RSS Reader
es folgt bald mehr

58
README.md Normal file
View file

@ -0,0 +1,58 @@
# mpgScanner
holt die Vertretungspläne vom Schulserver und verschickt diese, sollten Aktualisierungen vorliegen, dann per Mail und/oder Telegram-Messenger an beliebige viele
Empfänger (via Blindcopy, BCC),in Abhänigkeit davon, ob gerade Ferien oder ein Feiertag sind.
Für Nutzer der Hausautomation "Homematic": Es wird eine Systemvariable "Ferien" automatisch auf "True" bzw "False" gesetzt, wenn man dies möchte.
Zusätzlich werden einmal pro Tag ein "Zitat des Tages" angegeben.
Beim Versand der PDF werden die jeweils aktuelle Temperatur,Luftfeuchte und der Wolkenstatus mitangegeben. Ein zufällig ausgewählter "Chuck-Norris-Fact" runden das ganze dann ab.
# Installation
Das File downloaden und in einen beliebigen Ordner, in welchem man natürlich Schreibrechte besitzen muss, stecken.
Nach dem ersten Start wird automatisch eine Datei pass.json im gleichen Verzeichniss erstellt und die Anwendung beendet sich selbst.
Nun müssen folgende Angaben innerhalb dieser 'pass.json' gemacht werden:
* "gmail_pass":Passwort für den eigenen G-Mail Account (wird zum Versenden der PDF´s benötigt)
* "gmail_user":eigene Emailadresse des für die versendung zuständigen Accounts
* "Land":Europäisches Kürzel für den eignen Wohnort (z.Bsp. RP für RheinlandPfalz)
* "TOKEN":der Usertoken des Telegrammessengers (optional)
* "Chat_ID":Chat_ID des Telegrammessengers (optional)
* "ccu_ip":IP der CCU-Zentrale der Hausautomation 'Homematic' (optional)
* "wetter_API": der API-Key von wunderground.com
* "wetter_Ort": die ID der verwendeten Wetterstation
Weiterhin muss auf dem ausführenden System die Pythonbiliothek "pyTelegramBotAPI" installiert sein (wenn man Telegram nutzen möchte, sonst wird diese Funktion automatisch deaktiviert:
* sollte pip noch nicht installiert sein: "sudo apt-get installe python3-pip"
* pip3 install pyTelegramBotAPI
Bsp. für eine leere pass.json, wie sie automatisch nach dem ersten Start angelegt wird:
{
"Chat_ID": "",
"Land": "rp",
"TOKEN": "",
"ccu_ip": "",
"gmail_pass": "",
"gmail_user": "",
"mpg_pass": "",
"mpg_user": ""
}
# Benutzung
Das Programm wird am besten über einen Cronjob periodisch aufgerufen, z.Bsp. Stündlich, immer zur halben Stunde, im Zeitraum von 7 bis 15 Uhr, an den Werk(Schul-)tagen Montag bis Freitag.
Eintrag in der crontab sollte dann in etwa so ausschauen (Pfad zum Script bitte anpassen):
30 7-15 * * 1-5 python3 /home/carsten/Scripts/mpgScanner.py
# Disclaimer
Diese Software benutz den Zugang zum Schulserver des Max-Planck-Gymnasiums in Ludwigshafen (http://www.mpglu.de/aktuelles/vertretungsplan.html), um dort die Vertretungspläne für den aktuellen und den darauf folgenden Schultag zu laden. Für die Feier- und Ferientagsdaten wird die API von smartnoob.de (https://robin.meis.space/2014/04/15/ferien-feiertag-api-fuer-deutschland/) benutz. Vielen Dank für die Bereitstellung der Daten.
Für das "Zitat des Tages Feature" nutze ich die API von https://taeglicheszit.at
Um die aktuelle Temperatur/Luftfeuchtigkeit und "Bedeckung" anzuzeigen, greife ich auf die API von http://www.wunderground.com zurück.
Der Chuck-Norris-Fact wird von meiner eigenen API (api.hubobel.de/facts) bereitgestellt.
[![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.me/Hubobel)

98
REST_API.log Normal file
View file

@ -0,0 +1,98 @@
[2017-Nov-11 18:32] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-11 18:32] 127.0.0.1 GET http /facts? 200 OK
[2017-Nov-11 18:34] 127.0.0.1 GET http /? 200 OK
[2017-Nov-11 18:38] 127.0.0.1 GET http /? 200 OK
[2017-Nov-11 18:38] 127.0.0.1 GET http /? 200 OK
[2017-Nov-11 18:38] 127.0.0.1 GET http /? 200 OK
[2017-Nov-11 18:38] 127.0.0.1 GET http /facts? 200 OK
[2017-Nov-11 18:38] 127.0.0.1 GET http /facts/? 404 NOT FOUND
[2017-Nov-11 18:38] 127.0.0.1 GET http /facts/12? 200 OK
[2017-Nov-11 18:38] 127.0.0.1 GET http /facts/12? 200 OK
[2017-Nov-11 18:38] 127.0.0.1 GET http /facts/12? 200 OK
[2017-Nov-11 18:38] 127.0.0.1 GET http /facts/? 404 NOT FOUND
[2017-Nov-11 18:42] 127.0.0.1 GET http /facts/? 404 NOT FOUND
[2017-Nov-11 18:42] 127.0.0.1 GET http /facts? 200 OK
[2017-Nov-11 18:42] 127.0.0.1 GET http /? 200 OK
[2017-Nov-11 18:42] 127.0.0.1 GET http /? 200 OK
[2017-Nov-11 18:42] 127.0.0.1 GET http /? 200 OK
[2017-Nov-11 18:42] 127.0.0.1 GET http /facts? 200 OK
[2017-Nov-11 18:42] 127.0.0.1 GET http /facts? 200 OK
[2017-Nov-11 18:42] 127.0.0.1 GET http /facts/? 404 NOT FOUND
[2017-Nov-11 18:43] 127.0.0.1 GET http /facts/12? 200 OK
[2017-Nov-11 18:44] 127.0.0.1 GET http /facts/12? 200 OK
[2017-Nov-11 18:45] 127.0.0.1 GET http /facts/12? 200 OK
[2017-Nov-11 18:45] 127.0.0.1 GET http /facts/12? 200 OK
[2017-Nov-11 18:45] 127.0.0.1 GET http /facts/13? 200 OK
[2017-Nov-11 18:45] 127.0.0.1 GET http /facts/? 404 NOT FOUND
[2017-Nov-11 18:46] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-11 18:46] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-11 18:46] 127.0.0.1 GET http /facts/? 404 NOT FOUND
[2017-Nov-11 18:46] 127.0.0.1 GET http /facts/10? 200 OK
[2017-Nov-11 18:46] 127.0.0.1 GET http /facts/10? 200 OK
[2017-Nov-11 18:46] 127.0.0.1 GET http /facts/? 404 NOT FOUND
[2017-Nov-11 18:46] 127.0.0.1 GET http /facts/85? 200 OK
[2017-Nov-11 18:46] 127.0.0.1 GET http /facts/89? 200 OK
[2017-Nov-11 18:47] 127.0.0.1 GET http /facts/? 404 NOT FOUND
[2017-Nov-11 18:47] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-11 18:47] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-11 18:47] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-11 18:47] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-11 18:47] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-11 18:47] 127.0.0.1 GET http /facts/? 404 NOT FOUND
[2017-Nov-11 18:47] 127.0.0.1 GET http /facts? 200 OK
[2017-Nov-11 18:47] 127.0.0.1 GET http /? 200 OK
[2017-Nov-11 18:47] 127.0.0.1 GET http /? 200 OK
[2017-Nov-11 21:48] 81.169.144.135 GET http /facts/9999? 200 OK[2017-Nov-12 10:30] 127.0.0.1 GET http /? 200 OK
[2017-Nov-12 10:31] 127.0.0.1 GET http /? 200 OK
[2017-Nov-12 10:31] 127.0.0.1 GET http /? 200 OK
[2017-Nov-12 10:31] 127.0.0.1 GET http /? 200 OK
[2017-Nov-14 17:16] 127.0.0.1 GET http /? 200 OK
[2017-Nov-14 17:16] 127.0.0.1 GET http /? 200 OK
[2017-Nov-14 17:16] 127.0.0.1 GET http /facts? 200 OK
[2017-Nov-14 17:16] 127.0.0.1 GET http /facts? 200 OK
[2017-Nov-14 17:17] 127.0.0.1 GET http /facts/? 404 NOT FOUND
[2017-Nov-14 17:17] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-14 17:17] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-14 17:17] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-14 17:17] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-14 17:17] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-14 17:18] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-14 17:18] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-14 17:18] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-14 17:18] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-14 17:18] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-14 17:19] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-14 17:19] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-14 17:24] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-14 17:24] 127.0.0.1 GET http /facts/? 404 NOT FOUND
[2017-Nov-14 17:24] 127.0.0.1 GET http /facts/10? 200 OK
[2017-Nov-14 17:24] 127.0.0.1 GET http /facts/10? 200 OK
[2017-Nov-14 17:25] 127.0.0.1 GET http /facts/10? 200 OK
[2017-Nov-14 17:25] 127.0.0.1 GET http /facts/12? 200 OK
[2017-Nov-14 17:25] 127.0.0.1 GET http /facts/12? 200 OK
[2017-Nov-14 17:25] 127.0.0.1 GET http /facts/12? 200 OK
[2017-Nov-14 17:25] 127.0.0.1 GET http /facts/? 404 NOT FOUND
[2017-Nov-14 17:25] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-14 17:25] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-14 17:25] 127.0.0.1 GET http /facts/9999? 200 OK
[2017-Nov-14 17:25] 127.0.0.1 GET http /facts/? 404 NOT FOUND
[2017-Nov-14 17:25] 127.0.0.1 GET http /facts/89? 200 OK
[2017-Nov-14 17:25] 127.0.0.1 GET http /facts/86? 200 OK
[2017-Nov-14 17:33] 127.0.0.1 GET http /facts? 200 OK
[2017-Nov-14 17:33] 127.0.0.1 GET http /facts? 200 OK
[2017-Nov-14 17:34] 127.0.0.1 GET http /facts/? 404 NOT FOUND
[2017-Nov-14 17:34] 127.0.0.1 GET http /facts/15? 200 OK
[2017-Nov-14 17:34] 127.0.0.1 GET http /facts/15? 200 OK
[2017-Nov-14 17:55] 127.0.0.1 GET http /? 200 OK
[2017-Nov-14 17:55] 127.0.0.1 GET http /facts? 200 OK
[2017-Nov-14 17:55] 127.0.0.1 GET http /facts? 200 OK
[2017-Nov-14 17:55] 127.0.0.1 GET http /facts/? 404 NOT FOUND
[2017-Nov-14 17:55] 127.0.0.1 GET http /facts/12? 200 OK
[2017-Nov-14 17:55] 127.0.0.1 GET http /facts/19? 200 OK
[2017-Nov-14 18:43] 127.0.0.1 GET http /facts/19? 200 OK
[2017-Nov-14 18:43] 127.0.0.1 GET http /facts/? 404 NOT FOUND
[2017-Nov-14 18:43] 127.0.0.1 GET http /facts? 200 OK
[2017-Nov-14 18:44] 127.0.0.1 GET http /? 200 OK
[2017-Nov-14 18:44] 127.0.0.1 GET http /? 200 OK
[2017-Nov-14 18:45] 127.0.0.1 GET http /? 200 OK
[2017-Nov-14 18:46] 127.0.0.1 GET http /? 200 OK

66
REST_API.py Normal file
View file

@ -0,0 +1,66 @@
import os
import random
from flask import Flask, jsonify
import bs4 as bs
import urllib.request
app = Flask(__name__)
fact=[]
pfad = os.path.dirname(__file__)
chuck_file= open(pfad + '/mpg/chuck.rtf','r')
for line in chuck_file:
fact.append(line)
chuck_file.close()
ran=random.randint(1,len(fact)-1)
fakt={}
a=0
for i in fact:
fakt[a]=i
a =a +1
@app.route('/')
def index():
return "Hello, World!"
@app.route('/facts', methods=['GET'])
def get_tasks():
return jsonify({'facts': fakt})
@app.route('/lotto', methods=['GET'])
def get_lotto():
sauce = urllib.request.urlopen('http://www.lottotip-check.de').read()
soup = bs.BeautifulSoup(sauce, 'html.parser')
table = soup.find_all('table')
row = []
test = []
for i in table:
table_rows = i.find_all('tr')
for tr in table_rows:
# print(tr)
td = tr.find_all('td')
if td != []:
row = [i.text for i in td]
# print(row)
th = tr.find_all('th')
sz = [i.text for i in th]
# print(sz)
date = 'Ziehung vom: ' + str(sz[0])
sz = 'Superzahl: ' + str(sz[1])
row.append(sz)
row.insert(0, date)
test.extend(row)
test[14] = 'Superzahl: ' + test[14]
test = test[0:24]
Mit = {test[0]: test[1:8]}
EUR = {test[8]: test[9:16]}
Sam = {test[16]: test[17:24]}
return jsonify(test)
@app.route('/facts/<int:task_id>', methods=['GET'])
def get_task(task_id):
if len(fact)-1<task_id:
return jsonify({'error':"Auch Chuck Norris Witze sind begrenzt"})
return jsonify({'fact': fact[task_id]})
if __name__ == '__main__':
app.run(host='0.0.0.0')

163
REST_APIv2.py Normal file
View file

@ -0,0 +1,163 @@
import random
from flask import Flask, jsonify,make_response
import pymysql
import bs4 as bs
import urllib.request
app = Flask(__name__)
def Lotto():
sauce = urllib.request.urlopen('http://www.lottotip-check.de').read()
soup = bs.BeautifulSoup(sauce, 'html.parser')
# print(soup.prettify())
table = soup.find_all('table')
row = []
ZahlenAll = []
ZahlenMittwoch = {'Datum': '', 'Z1': '', 'Z2': '', 'Z3': '', 'Z4': '', 'Z5': '', 'Z6': '', 'Superzahl': '',
'Spiel77': '', 'Super6': ''}
ZahlenSamstag = {'Datum': '', 'Z1': '', 'Z2': '', 'Z3': '', 'Z4': '', 'Z5': '', 'Z6': '', 'Superzahl': '',
'Spiel77': '', 'Super6': ''}
ZahlenEuro = {'Datum': '', 'Z1': '', 'Z2': '', 'Z3': '', 'Z4': '', 'Z5': '', 'Superzahl1': '', 'Superzahl2': ''}
for i in table:
table_rows = i.find_all('tr')
for tr in table_rows:
# print(tr)
td = tr.find_all('td')
if td != []:
row = [i.text for i in td]
# print(row)
th = tr.find_all('th')
sz = [i.text for i in th]
# print(len(sz))
if len(sz) == 5:
row.append(str(sz[2]))
row.append(str(sz[3]))
date = 'Ziehung vom: ' + str(sz[0])
sz = str(sz[1])
row.append(sz)
row.insert(0, date)
ZahlenAll.extend(row)
a = 0
while a <= 5:
a = a + 1
ZahlenMittwoch['Z' + str(a)] = int(ZahlenAll[a])
ZahlenMittwoch['Datum'] = ZahlenAll[0]
ZahlenMittwoch['Superzahl'] = int(ZahlenAll[9])
ZahlenMittwoch['Super6'] = int(ZahlenAll[8])
ZahlenMittwoch['Spiel77'] = int(ZahlenAll[7])
print(ZahlenMittwoch)
a = 0
while a <= 5:
a = a + 1
ZahlenSamstag['Z' + str(a)] = int(ZahlenAll[a + 18])
ZahlenSamstag['Datum'] = ZahlenAll[18]
ZahlenSamstag['Superzahl'] = int(ZahlenAll[27])
ZahlenSamstag['Super6'] = int(ZahlenAll[26])
ZahlenSamstag['Spiel77'] = int(ZahlenAll[25])
print(ZahlenSamstag)
a = 0
while a <= 4:
a = a + 1
ZahlenEuro['Z' + str(a)] = int(ZahlenAll[a + 10])
ZahlenEuro['Datum'] = ZahlenAll[10]
ZahlenEuro['Superzahl2'] = int(ZahlenAll[17])
ZahlenEuro['Superzahl1'] = int(ZahlenAll[16])
print(ZahlenEuro)
return ZahlenMittwoch,ZahlenEuro,ZahlenSamstag
@app.route('/lotto', methods=['GET'])
def get_lotto():
Mit,EUR,Sam=Lotto()
return jsonify('alle Angaben ohne Gewaehr:',Mit,EUR,Sam)
@app.route('/lotto/Samstag', methods=['GET'])
def get_lottoSam():
Mit,EUR,Sam=Lotto()
return jsonify('alle Angaben ohne Gewaehr:',Sam)
@app.route('/lotto/Mittwoch', methods=['GET'])
def get_lottoMit():
Mit,EUR,Sam=Lotto()
return jsonify('alle Angaben ohne Gewaehr:',Mit)
@app.route('/lotto/Euro', methods=['GET'])
def get_lottoEur():
Mit,EUR,Sam=Lotto()
return jsonify('alle Angaben ohne Gewaehr:',EUR)
def Update():
connection = pymysql.connect(db="hubobel",
user="hubobel",
passwd="polier2003",
host='10.0.1.59',charset='utf8')
cursor = connection.cursor()
sql="SELECT * FROM facts"
resp=cursor.execute(sql)
x=cursor.fetchall()
fact=dict(x)
cursor.close()
connection.close()
a=len(fact)
return fact,a
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Nicht unterstuetzt'}), 404)
@app.route('/')
def index():
fact,a = Update()
fact={
'GET:api.hubobel.de/facts.....':'Uebersicht ueber alle verfuegbaren Facts mit ihrer ID',
'GET: api.hubobel.de/facts/<ID>.....':'JSON des abgefragten Facts',
'GET: api.hubobel.de/facts/zufall.....':'ein zufaellig ausgewaehlter Fact wird im JSON zurueck gegeben',
'facts':a,
'GET: api.hubobel.de/lotto....':'Liefert die letzten Zahlen von Mittwochs-, Euro- und Samstagslotto',
'GET: api.hubobel.de/lotto/Mittwoch.....':'Liefert die letzten Mottwochszahlen',
'GET: api.hubobel.de/lotto/Euro.....':'Liefert die letzten Eurojackpotzahlen',
'GET: api.hubobel.de/lotto/Samstag.....':'Liefert die letzten Samstagszahlen'}
return jsonify({'eine REST-API von hubobel.de Methoden/Funktionen':fact})
@app.route('/facts', methods=['GET'])
def get_tasks():
fact, a = Update()
return jsonify({'facts': fact})
@app.route('/facts/<int:task_id>', methods=['GET'])
def get_task(task_id):
connection = pymysql.connect(db="hubobel",
user="hubobel",
passwd="polier2003",
host='10.0.1.59', charset='utf8')
cursor = connection.cursor()
sql = "SELECT * FROM facts ORDER BY nr DESC"
resp = cursor.execute(sql)
x = int(resp)
if x<task_id:
return jsonify({'error':"Auch Chuck Norris FACTS sind begrenzt"})
sql_q = "SELECT * FROM facts WHERE nr like '" + str(task_id) + "'"
cursor.execute(sql_q)
resp = cursor.fetchall()
resp = (resp[0][1])
cursor.close()
connection.close()
return jsonify({'fact': resp})
@app.route('/zufall', methods=['GET'])
def zufall():
connection = pymysql.connect(db="hubobel",
user="hubobel",
passwd="polier2003",
host='10.0.1.59', charset='utf8')
cursor = connection.cursor()
sql = "SELECT * FROM facts ORDER BY nr DESC"
resp = cursor.execute(sql)
x = int(resp)
ran = random.randint(1, x)
print(x, ran)
sql_q = "SELECT * FROM facts WHERE nr like '" + str(ran) + "'"
resp = cursor.execute(sql_q)
resp = cursor.fetchall()
resp = (resp[0][1])
cursor.close()
connection.close()
return jsonify({ran: resp})
if __name__ == '__main__':
app.run(host='0.0.0.0')

74
Rest_API.bak Normal file
View file

@ -0,0 +1,74 @@
import random
from flask import Flask, jsonify,make_response
import pymysql
app = Flask(__name__)
def Update():
connection = pymysql.connect(db="hubobel",
user="hubobel",
passwd="polier2003",
host='10.0.1.59',charset='utf8')
cursor = connection.cursor()
sql="SELECT * FROM facts"
resp=cursor.execute(sql)
x=cursor.fetchall()
fact=dict(x)
cursor.close()
connection.close()
a=len(fact)
return fact,a
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Nicht unterstuetzt'}), 404)
@app.route('/')
def index():
fact,a = Update()
fact={
'POST:api.hubobel.de/facts.....':'Uebersicht ueber alle verfuegbaren Facts mit ihrer ID',
'POST: api.hubobel.de/facts/<ID>.....':'JSON des abgefragten Facts',
'POST: api.hubobel.de/facts/9999.....':'ein zufaellig ausgewaehlter Fact wird im JSON zurueck gegeben',
'facts':a}
return jsonify({'eine REST-API von hubobel.de Methoden/Funktionen':fact})
@app.route('/facts', methods=['GET'])
def get_tasks():
fact, a = Update()
return jsonify({'facts': fact})
@app.route('/facts/<int:task_id>', methods=['GET'])
def get_task(task_id):
connection = pymysql.connect(db="hubobel",
user="hubobel",
passwd="polier2003",
host='10.0.1.59', charset='utf8')
cursor = connection.cursor()
sql = "SELECT * FROM facts ORDER BY nr DESC"
resp = cursor.execute(sql)
x = int(resp)
if x<task_id:
return jsonify({'error':"Auch Chuck Norris FACTS sind begrenzt"})
sql_q = "SELECT * FROM facts WHERE nr like '" + str(task_id) + "'"
cursor.execute(sql_q)
resp = cursor.fetchall()
resp = (resp[0][1])
cursor.close()
connection.close()
return jsonify({'fact': resp})
@app.route('/zufall', methods=['GET'])
def zufall():
connection = pymysql.connect(db="hubobel",
user="hubobel",
passwd="polier2003",
host='10.0.1.59', charset='utf8')
cursor = connection.cursor()
sql = "SELECT * FROM facts ORDER BY nr DESC"
resp = cursor.execute(sql)
x = int(resp)
ran = random.randint(1, x)
print(x, ran)
sql_q = "SELECT * FROM facts WHERE nr like '" + str(ran) + "'"
resp = cursor.execute(sql_q)
resp = cursor.fetchall()
resp = (resp[0][1])
cursor.close()
connection.close()
return jsonify({ran: resp})
if __name__ == '__main__':
app.run(host='0.0.0.0')

31
SQL.py Normal file
View file

@ -0,0 +1,31 @@
import pymysql
connection = pymysql.connect(db="hubobel",
user="hubobel",
passwd="polier2003",
host='10.0.1.59',charset='utf8')
cursor = connection.cursor()
try:
cursor.execute("""CREATE TABLE facts (
nr INTEGER, fact TEXT)""")
except:
print ('weiter')
sql="SELECT * FROM facts ORDER BY nr DESC"
resp=cursor.execute(sql)
x=int(resp)+1
updatecount=0
with open('api/chuck.txt', 'r') as fp:
for line in fp:
line=line.replace('\n','')
sql = "INSERT INTO `facts`(`nr`, `fact`) VALUES ('"+str(x)+"','"+line+"')"
sql_q = "SELECT * FROM facts WHERE fact like '%" + line + "%'"
resp = cursor.execute(sql_q)
if resp == 0:
cursor.execute(sql)
x=x+1
updatecount=updatecount+1
connection.commit()
cursor.close()
connection.close()
print('Es wurden '+str(updatecount)+' neue Einträge der Datenbank hinzugefügt.')

40
Soundtouch 2.py Normal file
View file

@ -0,0 +1,40 @@
import urllib.request
class soundtouch():
def __init__(self):
self.url="http://10.0.1.27:8090/"
def Webaufruf(self,befehl):
try:
self.urli=self.url+befehl
antwort = urllib.request.urlopen(self.urli)
b = (antwort.read())
self.xmlString = b.decode("utf-8")
return self.xmlString
except:
return None
def now_playing(self):
return self.Webaufruf("now_playing")
return antwort
def info(self):
return self.Webaufruf("info")
def sources(self):
return self.Webaufruf("sources")
def presets(self):
return self.Webaufruf("presets")
def volume(self):
return self.Webaufruf("volume")
def suche (self,suchstring):
string = self.info()
anfang = string.find("<"+suchstring+">") + len("<"+suchstring+">")
ende = string.find("</"+suchstring+">")
if ende != -1:
return string[anfang:ende]
else:
return None
bose=soundtouch()
print((bose.info()))
print((bose.presets()))
print((bose.volume()))
print((bose.now_playing()))
print((bose.suche("softwareVersion")))

83
chuck.rtf Normal file
View file

@ -0,0 +1,83 @@
Chuck Norris hat einen Grizzlyba?ren Vorleger in seinem Zimmer. Der Ba?r ist nicht tot, er hat nur Angst sich zu bewegen.
Chuck Norris la?uft die 100m in einer Sekunde. Er kennt eine Abku?rzung.
Chuck Norris ist eigentlich schon vor 10 Jahren gestorben. Der Tod hatte bisher nur noch nicht den Mut, es ihm zu sagen
Noch wa?hrend Alexander Bell das Telefon erfand, hatte er bereits 3 Anrufe in Abwesenheit.
Chuck Norris schla?ft bei Licht. Nicht weil er Angst vor der Dunkelheit hat, sondern weil die Dunkelheit Angst vor ihm hat.
Chuck Norris hat alle Farben erfunden. Au?er Rosa! Tom Cruise hat Rosa erfunden.
Angst vor Spinnen ist Arachnophobie, Angst vor engen Ra?umen ist Klaustrophobie, Angst vor Chuck Norris nennt man Logik.
Chuck Norris lo?scht einen Gro?brand mit Lo?schpapier ...
Einige Leute tragen Superman Schlafanzu?ge. Superman tra?gt Chuck Norris Schlafanzu?ge.
Chuck Norris vergisst nie. Er kann sich sogar an morgen erinnern ...
Chuck Norris hat bis zur Unendlichkeit geza?hlt ... 2-mal.
Chuck Norris frankiert Briefe mit seinem Passfoto.
Wenn kleine Kinder ins Bett gehen, schauen sie vorher ob Monster unterm Bett sind. Wenn Monster ins Bett gehen, schauen sie vorher, ob Chuck Norris unterm Bett ist.
Chuck Norris war Kamikazepilot - Zwo?lf mal!
Am siebten Tag machte Gott eine Pause, weil Chuck Norris seine Ruhe haben wollte.
Chuck Norris denkt nicht, er wei?.
Chuck Norris kann ein Feuer entfachen, indem er zwei Eiswu?rfel aneinander reibt.
Chuck Norris kennt den Vornamen von Sokrates.
Chuck Norris wei? wo der Pfeffer wa?chst.
Chuck Norris mag keine Pommes, die Pommes mo?gen Chuck Norris!
Chuck Norris 'Hand ist die einzige Hand, die einen Royal Flash schlagen kann.
Chuck Norris kann in der Ecke eines kreisrunden Raums sitzen.
Chuck Norris liest keine Bu?cher: er starrt sie so lange an, bis sie ihm freiwillig sagen was er wissen will.
Chuck Norris kann schneller stehen als du rennen kannst.
Selbst Chuck Norris kann nicht unter Wasser atmen. Er macht es trotzdem.
Chuck Norris geht zur Sonntagsmesse am Dienstag.
Chuck Norris kann Drehtu?ren zuschlagen!
Legenden leben ewig. Chuck Norris lebt la?nger.
Chuck Norris kann schwarze Filzstifte nach Farbe sortieren.
Das Auto von Chuck Norris braucht kein Benzin, es fa?hrt aus Respekt.
Chuck Norris ist so cool, dass es hinter ihm schneit!
Chuck Norris schla?ft nicht. Er wartet.
Es gibt keine Evolutionstheorie. Nur eine Liste von Kreaturen denen Chuck Norris erlaubt hat zu leben.
Chuck Norris tra?gt keine Uhr. Er entscheidet wie spa?t es ist!
Chuck Norris hat beim Schwimmen Amerika entdeckt.
Chuck Norris zersto?rte das Periodensystem, weil Chuck Norris nur das Element der U?berraschung anerkennt.
Wenn Sie Chuck Norris in Scrabble buchstabieren, haben Sie gewonnen. Ein fu?r alle Mal.
Chuck Norris kann 141 Zeichen twittern!
Manche Menschen ko?nnen viele Liegestu?tze - Chuck Norris kann alle.
Chuck Norris ist so cool, dass die Schafe ihn za?hlen, wenn er ins Bett geht.
Chuck Norris kann einen Stuhl mit einem einzigen Arm hochheben - auf dem er selbst sitzt!
Urspru?nglich war Chuck Norris fu?r die Rolle des Terminators vorgesehen. Regisseur James Cameron entschied sich jedoch dagegen, einen Dokumentar-Film zu drehen.
Chuck Norris wurde gestern geblitzt - beim Einparken.
Chuck Norris hat als Kind auch Sandburgen gebaut. Wir kennen sie heute als Pyramiden.
Chuck Norris feiert seinen 7 Geburtstag nicht. Sein Geburtstag feiert ihn!
Chuck Norris hat keine Freunde. Er hat Fans!
Wie trinkt Chuck Norris aus dem Wasserhahn? Natu?rlich auf ex!
Als Gott la?chelte, lachte Chuck Norris bereits herzhaft.
Chuck Norris kann den Konjunktiv Futur II bilden!
Chuck Norris la?uft bei Super Mario nach links.
Chuck Norris hat mehr Kreditkarten als Max Mustermann.
Chuck Norris und MacGyver ko?nnen beide mit einer Lupe Feuer machen. Chuck Norris kann das aber auch bei absoluter Dunkelheit.
Chuck Norris wirft auch nach 20 Uhr Altglas ein.
Chuck Norris wei? mit Sicherheit, dass Duplo nicht die la?ngste Praline der Welt ist.
Chuck Norris verzichtet auf seine Rechte - seine Linke ist sowieso schneller ...
Chuck Norris kann auch per Email eine Briefbombe schicken!
Chuck Norris wa?hlt nicht falsche die Nummer. Du gehst an das falsche Telefon.
Chuck Norris war einmal in eine Messerstecherei verwickelt. Das Messer hat verloren.
Chuck Norris kann durch Null teilen!
Wenn Chuck Norris dividiert, dann bleibt kein Rest.
Gott sprach: "Es werde Licht!" Chuck Norris antwortete: "Sag bitte!"
Chuck Norris kann u?ber seinen Schatten springen ...
Wenn der Butzemann jede Nacht schlafen geht, schaut er in seinem Kleiderschrank nach Chuck Norris.
Geister sitzen um das Lagerfeuer und erza?hlen Chuck Norris Geschichten.
Chuck Norris kann Strg+Alt+Entf gleichzeitig mit einem Finger dru?cken ... Die NSA ist nun dem Untergang geweiht, weil nichts und niemand Chuck Norris u?berwacht und u?berlebt.
Chuck Norris wurde einmal von einer Klapperschlange gebissen ...... Nach drei Tagen voller Schmerzen und Qualen ...... starb die Klapperschlange.
Chuck Norris sucht nicht bei Google - Google fragt Chuck Norris ...
Chuck Norris kann M&Ms alphabetisch sortieren.
Chuck Norris kann den toten Winkel zum Leben erwecken.
Sido hat mal gefragt, wer eigentlich dieser Chuck Norris ist. Seit dem tra?gt Sido eine Maske.
Chuck Norris hat den Niagara Fall gelo?st.
Chuck Norris ist der Einzige, der die Zeit wirklich totschlagen kann ...
Chuck Norris ist so cool, dass er eine "Fu?nf Minuten Terrine" in drei?ig Sekunden zubereiten kann.
Chuck Noris kann ohne eine einzige Frage zu beantworten ein Sandwich bei Subway bestellen.
Chuck Norris kann Zwiebeln zum Weinen bringen.
Chuck Norris kann Frauen die Abseitsregel erkla?ren ...
Chuck Norris kennt die letzte Ziffer von Pi.
Wenn Chuck Norris puzzeln will, kauft er sich eine Tu?te Paniermehl und baut die Semmeln wieder zusammen.
Nur Chuck Norris kann sehen wer auf Deinem Profil war!
Chuck Norris sucht nicht, er findet.
Chuck Norris hat einmal Russisches Roulette mit einem komplett geladenen Colt gespielt und gewonnen!
Chuck Norris spielt eine halbe Stunde PlayStation in 20 Minuten.
Chuck Norris hat nur vor einem Angst: Carsten (Hubobel) Richter.

93
getMailatta 2.py Normal file
View file

@ -0,0 +1,93 @@
#!/usr/bin/env python
import poplib
import email
import os
import sys
import string
import time
try:
import telebot
telegram = True
except ImportError:
print('Librarie "telebot" ist nicht installiert. Keine Verwendung von Telegram!!!')
print('Installation ueber: "pip3 install pyTelegramBotAPI"')
telegram = False
#
# attsave.py
# Check emails at PROVIDER for attachments and save them to SAVEDIR.
#
#
PROVIDER = "pop3.web.de"
USER = "debhubobel@web.de"
PASSWORD = "PL19zPL19z"
TOKEN='312534798:AAFbMjS-tfd2BiZ_j3NEZuQYKwzACMcioVo'
Chat_ID='322673713'
SAVEDIR = "/home/carsten"
if telegram:
tb = telebot.TeleBot(TOKEN)
def saveAttachment(mstring):
filenames = []
attachedcontents = []
msg = email.message_from_string(mstring)
for part in msg.walk():
fn = part.get_filename()
if fn <> None:
filenames.append(fn)
attachedcontents.append(part.get_payload(decode = True))
for i in range(len(filenames)):
fp = file(SAVEDIR + "/" + filenames[i], "wb")
fp.write(attachedcontents[i])
print 'Found and saved attachment "' + filenames[i] + '".'
if telegram:
tb.send_message(Chat_ID, 'Found and saved attachment "' + filenames[i] + '".')
fp.close()
try:
client = poplib.POP3_SSL(PROVIDER)
except:
print "Error: Provider not found."
sys.exit(1)
client.user(USER)
client.pass_(PASSWORD)
anzahl_mails = len(client.list()[1])
for i in range(anzahl_mails):
lines = client.retr(i + 1)[1]
mailstring = string.join(lines, "\n")
saveAttachment(mailstring)
poplist = client.list()
if poplist[0].startswith('+OK') :
msglist = poplist[1]
for msgspec in msglist :
# msgspec is something like "3 3941",
# msg number and size in octets
msgnum = int(msgspec.split(' ')[0])
client.dele(msgnum)
else :
None
wtag = time.strftime('%H%M')
if wtag == '1945':
for filename in os.listdir(SAVEDIR+'/added'):
print filename+' wurde erfolgreich geloescht.'
os.remove(SAVEDIR+'/added/'+filename)
if telegram:
tb.send_message(Chat_ID,filename+' wurde erfolgreich geloescht.')
client.quit()

34
gmail 2.py Normal file
View file

@ -0,0 +1,34 @@
#!/usr/bin/python
import imaplib
import re
from urllib.request import urlopen
password= 'XXXXXXX'
user= 'XXXXXXXXXX'
mark = 1 #1 = markiert alle Mails als gelesen
ip = '10.0.1.100' # IP der CCU / RaspberryMatic / YAHM
SV = 'Mail' # Name der Systemvariable vom Typ Zahl
imap_server = imaplib.IMAP4_SSL("imap.gmail.com",993)
imap_server.login(user, password)
imap_server.select('INBOX')
status, response = imap_server.status('INBOX', "(UNSEEN)")
unreadcount = response[0].split()[2]
xyz = str(unreadcount)
zahlen=re.findall('([0-9]+)', xyz)
string="".join([str(i) for i in zahlen])
url = 'http://'+ip+':8181/loksoft.exe?ret=dom.GetObject("'+SV+'").State('+string+')'
urlopen(url)
if mark == 1:
result, data = imap_server.uid('SEARCH', None, '(UNSEEN)')
uids = data[0].split()
for uid in uids:
result, data = imap_server.uid('fetch', uid, '(RFC822)')
# ------ data is manufactured
result = imap_server.uid("STORE", uid, '+FLAGS', '\\Seen')

BIN
heute.pdf Normal file

Binary file not shown.

BIN
heute1.pdf Normal file

Binary file not shown.

39
json to dic.py Normal file
View file

@ -0,0 +1,39 @@
import json
import time
import requests
def update():
with open('pass.json') as file:
jsonpass=json.load(file)
zeit = time.strftime("%s")
if 'Tag_Nummer' in jsonpass:
print (jsonpass['Tag_Nummer'])
if jsonpass['Tag_Nummer']!= zeit:
print ('update json mit '+zeit)
jsonpass['Tag_Nummer']=zeit
with open('pass.json', 'w') as fp:
json.dump(jsonpass, fp, sort_keys=True, indent=4)
return True
else:
print('kein Update')
return False
else:
jsonpass['Tag_Nummer']=''
with open('pass.json', 'w') as fp:
json.dump(jsonpass, fp, sort_keys=True, indent=4)
if update():
print ('Neuer Tag, neues Gluck!')
url_zitat = 'https://taeglicheszit.at/zitat-api.php?format=json'
resp_zitat = requests.get(url_zitat)
data_zitat = resp_zitat.json()
#with open(pfad + '/mpg/json_ferien.data', 'w') as outfile:
#json.dump(data_ferien, outfile)
else:
print ('im Westen nix neues')
url_zitat = 'https://taeglicheszit.at/zitat-api.php?format=json'
resp_zitat = requests.get(url_zitat)
data_zitat = resp_zitat.json()
print (data_zitat)

1
json_feiertage.data Normal file
View file

@ -0,0 +1 @@
{"error": 0, "jahr": "2017", "daten": [{"title": "Neujahr", "beginn": 1483225200.0, "ende": 1483311600.0}, {"title": "Karfreitag", "beginn": 1492120800.0, "ende": 1492207200.0}, {"title": "Ostermontag", "beginn": 1492380000.0, "ende": 1492466400.0}, {"title": "Tag der Arbeit", "beginn": 1493589600.0, "ende": 1493676000.0}, {"title": "Christi Himmelfahrt", "beginn": 1495663200.0, "ende": 1495749600.0}, {"title": "Pfingstmontag", "beginn": 1496613600.0, "ende": 1496700000.0}, {"title": "Fronleichnam", "beginn": 1497477600.0, "ende": 1497564000.0}, {"title": "Tag der Deutschen Einheit", "beginn": 1506981600.0, "ende": 1507068000.0}, {"title": "Reformationstag", "beginn": 1509404400.0, "ende": 1509490800.0}, {"title": "Allerheiligen", "beginn": 1509490800.0, "ende": 1509577200.0}, {"title": "1. Weihnachtsfeiertag", "beginn": 1514156400.0, "ende": 1514242800.0}, {"title": "2. Weihnachtsfeiertag", "beginn": 1514242800.0, "ende": 1514329200.0}]}

1
json_ferien.data Normal file
View file

@ -0,0 +1 @@
{"error": 0, "jahr": "2017", "daten": [{"title": "Osterferien 2017 Rheinland-Pfalz", "beginn": 1491775200.0, "ende": 1492812000.0}, {"title": "Sommerferien 2017 Rheinland-Pfalz", "beginn": 1499032800.0, "ende": 1502488800.0}, {"title": "Herbstferien 2017 Rheinland-Pfalz", "beginn": 1506895200.0, "ende": 1507932000.0}, {"title": "Weihnachtsferien 2017 Rheinland-Pfalz", "beginn": 1513897200.0, "ende": 1515538800.0}]}

BIN
morgen.pdf Normal file

Binary file not shown.

BIN
morgen1.pdf Normal file

Binary file not shown.

BIN
mpg/heute.pdf Normal file

Binary file not shown.

438
mpgScanner.py Normal file
View file

@ -0,0 +1,438 @@
import requests
import json
import time
import datetime
import os
import smtplib
import random
import shutil
try:
import telebot
telegram = True
except ImportError:
print('Librarie "telebot" ist nicht installiert. Keine Verwendung von Telegram!!!')
print('Installation über: "pip3 install pyTelegramBotAPI"')
telegram = False
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
def Download(url):
#return None
filename = pfad+'/mpg/'+url+'.pdf'
url = 'http://www.mpglu.de/vps/'+url+'.pdf'
req = requests.get(url, auth=(jsonpass['mpg_user'], jsonpass['mpg_pass']))
file = open(filename, 'wb')
for chunk in req.iter_content(100000):
file.write(chunk)
file.close()
return None
def modification_date(filename):
t = os.path.getmtime(filename)
return datetime.datetime.fromtimestamp(t)
def Nachricht(fradress, toadress, bccs=[], sub='I am ROOT',body='this comes from Hubobel', attach=[]):
fromaddr = fradress
toaddr = toadress
if bccs==[]:
bccs = toadress
pwd = jsonpass['gmail_pass']
acc = jsonpass['gmail_user']
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = sub
msg.attach(MIMEText(body, 'plain'))
for each in attach:
filename = each
attachment = open(pfad + '/mpg/'+each, 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename= %s' % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(acc, pwd)
text = msg.as_string()
server.sendmail(fromaddr, bccs, text)
server.quit()
return
def json_pass_holen(pfad):
with open(pfad+'/pass.json') as file:
passw = json.load(file)
passw['Uhrzeit'] = time.strftime("%H:%M:%S")
passw['Tag_Name'] = time.strftime('%A')
#passw['Tag_Nummer'] = time.strftime('%w')
passw['pfad']=pfad
with open(pfad+'/pass.json', 'w') as fp:
json.dump(passw, fp, sort_keys=True, indent=4)
return passw
def update():
global jsonpass
with open(pfad+'/pass.json') as file:
jsonpass=json.load(file)
if 'Tag_Nummer' in jsonpass or jsonpass['debug']=='True':
print (jsonpass['Tag_Nummer'])
if jsonpass['Tag_Nummer']!= wtag or jsonpass['debug']=="True":
print ('update json mit '+str(wtag))
jsonpass['Tag_Nummer']=str(wtag)
url_zitat = 'https://taeglicheszit.at/zitat-api.php?format=json'
resp_zitat = requests.get(url_zitat)
data_zitat = resp_zitat.json()
jsonpass['zitat']=data_zitat['zitat']
jsonpass['autor']=data_zitat['autor']
with open(pfad+'/pass.json', 'w') as fp:
json.dump(jsonpass, fp, sort_keys=True, indent=4)
return True, jsonpass
else:
print('kein Update')
return False
else:
jsonpass['Tag_Nummer']=''
with open(pfad+'/pass.json', 'w') as fp:
json.dump(jsonpass, fp, sort_keys=True, indent=4)
def Wetter():
url = 'http://api.wunderground.com/api/'+jsonpass['wetter_API']+'/conditions/lang:DL/q/Germany/pws:'+jsonpass['wetter_Ort']+'.json'
response = requests.get(url)
data_response = response.json()
temperatur=(data_response['current_observation']['temp_c'])
wetter=(data_response['current_observation']['weather'])
feuchte=(data_response['current_observation']['relative_humidity'])
if wetter=='Leichter Regen':
wetter='bedeckt und es herrscht leichter Regen....brrrrr!'
if wetter=='Regen':
wetter='voller Wolken und es regnet.'
return temperatur,wetter,feuchte
def Chuckfact():
url_zitat = 'http://api.hubobel.de/zufall'
resp_zitat = requests.get(url_zitat)
data_zitat = resp_zitat.json()
for i in data_zitat:
fact=(data_zitat[i])
return fact
def Lotto():
a = (sorted(random.sample(range(1, 49), 6)))
b = random.randrange(0, 9)
while b in a:
b = random.randrange(1, 49)
lotto = str(a) + ',Superzahl: ' + str(b)
return lotto
pfad = os.path.dirname(__file__)
mail = 0
jetzt = int(time.strftime('%j'))
tag = time.strftime('%d')
wtag = time.strftime('%w')
mailzusatz=""
ferien = False
ferien_morgen = False
feiertag = False
feiertag_morgen = False
fradress='carsten.richter77@gmail.com'
toadress='carsten@hubobel.de'
tage=['Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag','Sonntag']
wtag1=wtag
heute_name=(tage[int(wtag)-1])
if int(wtag)>=5:
wtag1=0
morgen_name=(tage[int(wtag1)])
if os.path.isfile(pfad+'/pass.json') !=True:
print('"pass.json" scheint es nicht zu geben.')
print('Ich lege eine neue Datei "pass.json" an.')
passw={"gmail_pass": "","gmail_user": "",
"mpg_user": "",
"mpg_pass": "",
"Chat_ID": "","TOKEN": "",
"ccu_ip": "","Land": "rp",
"Wochentag": ""}
print(str(passw)+ ' bitte entsprechend befüllen.')
with open(pfad+'/pass.json', 'w') as fp:
json.dump(passw, fp, sort_keys=True, indent=4)
quit()
else:
jsonpass = json_pass_holen(pfad)
if jsonpass['TOKEN']=='' or jsonpass['Chat_ID']=='':
telegram=False
if telegram:
TOKEN = jsonpass['TOKEN']
chat_id = jsonpass['Chat_ID']
tb = telebot.TeleBot(TOKEN)
if os.path.isfile(pfad+'/mpg/adressen.txt'):
fobj = open(pfad + "/mpg/adressen.txt")
bcc = []
for line in fobj:
a = line.rstrip()
bcc.append(a)
fobj.close()
if jsonpass['ccu_ip']!='':
url_ferien_ccu = 'http://'+jsonpass['ccu_ip']+'/loksoft.exe?ret=dom.GetObject("Ferien").State('
ccu = True
else:
ccu = False
if os.path.isdir(pfad+'/mpg')!= True: #prüfen, ob das UNTERverzeichniss /mpg bereits existiert
os.makedirs(pfad+'/mpg')
print ('Downloadverzeichniss bei '+pfad +' /mpg/ created!!!')
if int(tag) == 1 and int(time.strftime('%H'))== 8: #Update einmal pro Monat (Ferien)
print("It´s Update Time!!!")
url_ferien = 'http://api.smartnoob.de/ferien/v1/ferien/?bundesland=' + jsonpass['Land']
url_feiertage = 'http://api.smartnoob.de/ferien/v1/feiertage/?bundesland=' + jsonpass['Land']
resp_ferien = requests.get(url_ferien)
resp_feiertage = requests.get(url_feiertage)
data_ferien = resp_ferien.json()
data_feiertage = resp_feiertage.json()
with open(pfad + '/mpg/json_ferien.data', 'w') as outfile:
json.dump(data_ferien, outfile)
with open(pfad + '/mpg/json_feiertage.data', 'w') as outfile:
json.dump(data_feiertage, outfile)
if os.path.isfile(pfad+'/mpg/json_ferien.data')!= True: #Download der jsons, falls diese lokal nicht existieren
print('The json_xxx.datas not found, will try to download them from the API')
url_ferien = 'http://api.smartnoob.de/ferien/v1/ferien/?bundesland=' + jsonpass['Land']
url_feiertage = 'http://api.smartnoob.de/ferien/v1/feiertage/?bundesland=' + jsonpass['Land']
resp_ferien = requests.get(url_ferien)
resp_feiertage = requests.get(url_feiertage)
data_ferien = resp_ferien.json()
data_feiertage = resp_feiertage.json()
with open(pfad+'/mpg/json_ferien.data','w') as outfile:
json.dump(data_ferien, outfile)
with open(pfad+'/mpg/json_feiertage.data','w') as outfile:
json.dump(data_feiertage, outfile)
with open(pfad+'/mpg/json_ferien.data') as file:
data_ferien=json.load(file)
with open(pfad+'/mpg/json_feiertage.data') as file:
data_feiertage=json.load(file)
a= len(data_ferien['daten'])
x = 0
while x <a:
beginn = data_ferien['daten'][x]['beginn']
beginn = datetime.datetime.fromtimestamp(beginn)
beginn = int(beginn.strftime('%j'))
ende = data_ferien['daten'][x]['ende']
ende = datetime.datetime.fromtimestamp(ende)
ende = int(ende.strftime('%j'))-1
if jetzt <= ende and jetzt >= beginn:
ferien = True
if jetzt-1 == beginn:
ferien_morgen = True
if jetzt >= beginn and jetzt <= ende-1:
ferien_morgen = True
x = x+1
if ferien and ccu: #setzen der CCU Variable
try:
requests.post(url_ferien_ccu+'1)')
except:
None
if ferien == False and ccu :
try:
requests.post(url_ferien_ccu+'0)')
except:
None
a= len(data_feiertage['daten'])
x = 0
while x <a:
beginn = data_feiertage['daten'][x]['beginn']
beginn = datetime.datetime.fromtimestamp(beginn)
beginn = int(beginn.strftime('%j'))
ende = data_feiertage['daten'][x]['ende']
ende = datetime.datetime.fromtimestamp(ende)
ende = int(ende.strftime('%j'))-1
if jetzt <= ende and jetzt >= beginn:
feiertag = True
if jetzt+1 == beginn:
feiertag_morgen = True
x = x+1
print('Es sind Ferien: '+ str(ferien))
print('Es sind morgen Ferien: '+ str(ferien_morgen))
print('Es ist ein Feiertag: '+str(feiertag))
print('Es ist morgen ein Feiertag: '+str(feiertag_morgen))
if feiertag_morgen:
mailzusatz = '\n \nMorgen ist ein Feiertag.\nNeue Nachrichten erst am nächsten Werktag wieder.\nGenießt die Zeit!'
############################################################
if ferien:
print('Es sind Ferien, also lass ich euch in Ruhe')
quit()
if feiertag_morgen:
print('Morgen ist Feiertag, also gibts auch nichts, was sich lohnt, anzuschauen.')
#quit()
try:
os.rename(pfad + '/mpg/heute.pdf', pfad +'/mpg/heute1.pdf')
url = 'heute'
Download(url)
x = os.stat(pfad+'/mpg/heute.pdf')
x = x.st_size
x1 = str(x)
y = os.stat(pfad+'/mpg/heute1.pdf')
y = y.st_size
y1 = str(y)
if x != y:
mail=mail+1
else:
print("Es gibt keine neuen Mals mit 'heute'")
d = modification_date(pfad+'/mpg/heute.pdf')
d = d.strftime('%H:%M:%S')
print("heute: " + d + ' '+ x1 + ' Bytes')
d = modification_date(pfad+'/mpg/heute1.pdf')
d = d.strftime('%H:%M:%S')
print("heute1: " + d + ' '+ y1 + ' Bytes')
except FileNotFoundError:
print("File Heute.PDF not found")
print("Will try to download it from the MPG-Server")
url = 'heute'
Download(url)
try:
os.rename(pfad+'/mpg/morgen.pdf', pfad+'/mpg/morgen1.pdf')
url = 'morgen'
Download(url)
x = os.stat(pfad+'/mpg/morgen.pdf')
x = x.st_size
x1 = str(x)
y = os.stat(pfad+'/mpg/morgen1.pdf')
y = y.st_size
y1 = str(y)
if x != y:
mail = mail + 2
else:
print("Es gibt keine neuen Mails mit 'morgen'")
d= modification_date(pfad+'/mpg/morgen.pdf')
d = d.strftime('%H:%M:%S')
print("morgen: " + d + ' ' + x1 + ' Bytes')
d = modification_date(pfad+'/mpg/morgen1.pdf')
d = d.strftime('%H:%M:%S')
print("morgen1: " + d + ' ' + x1 + ' Bytes')
except FileNotFoundError:
print("File Morgen.PDF not found")
print("Will try to download it from the MPG-Server")
url = 'morgen'
Download(url)
#sub='Hier kommt der Betreff rein'
#body = 'hier der Mailtext'
#anhang = ['adressen.txt','heute.pdf','morgen.pdf']
#Nachricht (fradress,toadress,bcc,sub,body,anhang)
if mail!=0 or jsonpass['debug']=='True':
if update():
print ('Neuer Tag, neues Gluck!')
if wtag == '1':
mailzusatz = '\n \nWillkommen in der ' + str(time.strftime('%W')) + '.Kalenderwoche.' + \
'\nNicht verzagen, nur Druck formt aus Kohle einen Diamanten!' \
'\nZitat des Tages:\n'+ jsonpass['zitat']+ \
'\nAutor: ' + jsonpass['autor'] + '\n'
if wtag == '2':
mailzusatz = '\n \nDer Montag liegt hinter uns.\nAb heuteb kann es nur noch aufwärts gehen!' \
'\nViel Spass, bei allem, was ihr so treibt\n'+ \
'\nZitat des Tages:\n'+ jsonpass['zitat']+ \
"\nAutor: " + jsonpass['autor'] + '\n'
if wtag == '3':
lotto=Lotto()
mailzusatz = '\n \nHallo Mittwoch!\nIch wünsche eine schöne Wochenmitte.\nKopf hoch! ' \
+ 'Wenn ich Lotto spielen würde, dann kämen heute folgende Zahlen zum Einsatz: ' +lotto +\
'\n\nZitat des Tages:\n'+ jsonpass['zitat']+ \
"\nAutor: " + jsonpass['autor'] + '\n'
if wtag == '4':
mailzusatz = '\n \nDer Donnerstag ist bekanntlich der \'kleine Freitag\'' \
'\nNur noch einmal (!) Gas geben!\n' '\nZitat des Tages:\n'+ jsonpass['zitat']+\
'\nAutor: '+jsonpass['autor']+'\n'
if wtag == '5':
lotto=Lotto()
mailzusatz = '\n \nEs ist Freitag!\nIch wünsche ein schönes Wochenende.' \
'\nNeue Nachrichten kommen erst am Montag wieder.\n'+'Vieleicht habt ihr ja am Samstag'\
' Glück beim Lotto. Probiert doch mal diese Zahlen: '+lotto+\
'\n\nZitat des Tages:\n'+ jsonpass['zitat']+\
'\nAutor: '+jsonpass['autor']+'\n'
else:
print ('im Westen nix neues')
if jsonpass['debug']=="True":
update()
print('DEBUG_MODE')
bcc=jsonpass['debug_adress']
TOKEN = jsonpass['debug_TOKEN']
chat_id = jsonpass['debug_Chat_ID']
tb = telebot.TeleBot(TOKEN)
mailzusatz = mailzusatz + '\n \nDies ist eine Testnachricht!\nDer Versand erfolgt nur an Hubobel und schneeschieben.\n\n' \
'Zitat des Tages:\n'+ jsonpass['zitat']+'\nAutor: '+jsonpass['autor']+'\n'
if 'wetter_API' in jsonpass:
if jsonpass['wetter_API']!='':
temperatur,wetter,feuchte=Wetter()
bericht='\nAktuell haben wir geschmeidige '+str(temperatur)+' Grad Celsius bei '+str(feuchte)\
+' Luftfeuchtigkeit.\nDer Himmel ist '+str(wetter)+'.\n'
else:
bericht = 'Wie das Wetter derzeit ist? Man(n) richte seinen Blick gen Himmel oder' \
' generiere einen API-Key unter https://www.wunderground.com/signup?mode=api_signup'
else:
bericht='Wie das Wetter derzeit ist? Man(n) richte seinen Blick gen Himmel oder' \
' generiere einen API-Key unter https://www.wunderground.com/signup?mode=api_signup'
fact='\nChuck-Norris-Fact:\n'+Chuckfact()
shutil.copy(pfad+'/mpg/morgen.pdf',pfad+'/mpg/'+morgen_name+'.pdf')
if mail == 1 or jsonpass['debug']=='True':
body = 'Es gibt eine aktuelle Version des heutigen Vertretungsplanes.'+mailzusatz+bericht+fact
anhang = ['heute.pdf']
sub = 'MPG-heute aktualisiert'
if os.path.isfile(pfad + '/mpg/adressen.txt'):
Nachricht(fradress, toadress, bcc, sub, body, anhang)
print (body+' ich versende das mal an: '+str(bcc))
if telegram:
document = open(pfad+'/mpg/heute.pdf', 'rb')
tb.send_document(chat_id, document, caption='Es gibt eine aktuelle Version des heutigen Vertretungsplanes.')
tb.send_message(chat_id, mailzusatz+bericht+fact)
if mail == 2 or jsonpass['debug']=='True':
body = 'Es gibt eine aktualisierte Version des Vertretungsplanes für '+morgen_name+mailzusatz+bericht+fact
anhang = [morgen_name+'.pdf']
sub = 'MPG-morgen aktualisiert'
if os.path.isfile(pfad + '/mpg/adressen.txt'):
Nachricht(fradress, toadress, bcc, sub, body, anhang)
print (body+' ich versende das mal an: '+str(bcc))
if telegram:
document = open(pfad + '/mpg/'+morgen_name+'.pdf', 'rb')
tb.send_document(chat_id, document, caption='Es gibt eine aktualisierte Version '
'des Vertretungsplanes für '+morgen_name+'.')
tb.send_message(chat_id, mailzusatz + bericht+fact)
if mail == 3 or jsonpass['debug']=='True':
body = 'Es gibt aktualisierte Versionen der MPG-Vertretungspläne.'+mailzusatz+bericht+fact
anhang = ['heute.pdf',morgen_name+'.pdf']
sub = 'MPG-Vertretungspläne aktualisiert'
if os.path.isfile(pfad + '/mpg/adressen.txt'):
Nachricht(fradress, toadress, bcc, sub, body, anhang)
print (body+' ich versende das mal an: '+str(bcc))
if telegram:
document = open(pfad + '/mpg/heute.pdf', 'rb')
tb.send_document(chat_id, document, caption='Es gibt aktualisierte Versionen der MPG-Vertretungspläne.')
document = open(pfad + '/mpg/'+morgen_name+'.pdf', 'rb')
tb.send_document(chat_id, document)
tb.send_message(chat_id, mailzusatz + bericht+fact)

24
newsblur.py Normal file
View file

@ -0,0 +1,24 @@
import requests
import json
import time
import datetime
import os
session = requests.session()
url = 'http://www.newsblur.com/api/login'
datas = {'username':'hubobel','password':'polier2003'}
resp = session.post(url,datas)
data = resp.json()
print (data)
url = 'http://www.newsblur.com/reader/refresh_feeds'
resp = session.get(url)
data = resp.json()
print (json.dumps(data, indent=4))
print (data['id'])
url = 'http://www.newsblur.com/reader/feed/6212608'
resp = session.get(url)
data = resp.json()
print (json.dumps(data, indent=4))
print(data)

107
newsblur_api.py Normal file
View file

@ -0,0 +1,107 @@
import requests
import json
import telebot
import os
import pymysql
def laenge():
datas = '{"sid":"' + id + '","op":"getHeadlines","feed_id":-1}'
resp = requests.post(url, datas)
data = resp.json()
a=(len(data['content']))
return a
TOKEN ='312534798:AAFbMjS-tfd2BiZ_j3NEZuQYKwzACMcioVo'
chat_id ='322673713'
tb = telebot.TeleBot(TOKEN)
url = 'http://hubobel.de/tt-rss/api/'
pfad = os.path.dirname(__file__)
datas = '{"op":"login","user":"admin","password":"password"}'
resp = requests.post(url,datas)
data = resp.json()
id= str(data['content']['session_id'])
datas = '{"sid":"'+id+'","op":"getFeeds","cat_id":-4}'
resp = requests.post(url,datas)
data = resp.json()
ids=[]
gefunden=[]
laenge_start=laenge()
suchstring=[]
fobj = open(pfad+"/toFind.txt")
for line in fobj:
suchstring.append(line.rstrip())
fobj.close()
for i in data['content']:
if int(i['unread'])>0 and int(i['id'])>0:
datas = '{"sid":"'+id+'","op":"getHeadlines","feed_id":'+str(i['id'])+'}'
resp = requests.post(url,datas)
feeds = resp.json()
for headlines in feeds['content']:
if headlines['unread']:
a=0
b=len(suchstring)
if headlines['feed_id'] == '4':
article_id=str(headlines['id'])
datas = '{"sid":"' + id + '","op":"getArticle","article_id":'+article_id+'}'
resp = requests.post(url, datas)
data = resp.json()
antwort=str(data['content'][0]['content'])
connection = pymysql.connect(db="hubobel",
user="hubobel",
passwd="polier2003",
host='10.0.1.59', charset='utf8')
cursor = connection.cursor()
sql = "SELECT * FROM facts ORDER BY nr DESC"
resp = cursor.execute(sql)
x = int(resp) + 1
line = antwort.replace('<p>', '')
line = line.replace('</p>', '')
sql = "INSERT INTO `facts`(`nr`, `fact`) VALUES ('" + str(x) + "','" + line + "')"
sql_q = "SELECT * FROM facts WHERE fact like '%" + line + "%'"
resp = cursor.execute(sql_q)
if resp == 0:
resp = cursor.execute(sql)
connection.commit()
cursor.close()
connection.close()
while a<b:
if suchstring[a] in str(headlines['title']):
ids.append(headlines['id'])
if suchstring[a] not in gefunden:
gefunden.append(suchstring[a])
a=a+1
if ids != []:
idstring=str(ids)
idstring=idstring.replace('[',"")
idstring=idstring.replace(']',"")
idstring=idstring.replace(' ','')
datas = '{"sid":"'+id+'","op":"updateArticle","article_ids":"'+idstring+'","mode":1,"field":0}'
resp = requests.post(url,datas)
data = resp.json()
laenge_ende=laenge()
ergebniss=laenge_ende-laenge_start
datas = '{"sid":"'+id+'","op":"getCounters","output_mode":"c"}'
resp = requests.post(url,datas)
data = resp.json()
unreadcount=int(data['content'][3]['counter'])
if ergebniss>0:
bericht='Es gibt '+str(ergebniss)+' neue Nachrichte(n) mit den Begriffen '+str(gefunden)+\
' in deinen News!\nEs sind nun '+str(unreadcount)+' ungelesene Nachrichten in deinen News.'
tb.send_message(chat_id, bericht)

22
pass 2.json Normal file
View file

@ -0,0 +1,22 @@
{
"Chat_ID": "@mpglu",
"Land": "rp",
"TOKEN": "467241832:AAH3e0y6Fm7ig5DtConJP29GsD-zX1psNZo",
"Tag_Name": "Friday",
"Tag_Nummer": "5",
"Uhrzeit": "18:04:05",
"autor": "Justus von Liebig",
"ccu_ip": "10.0.1.100",
"debug": "True",
"debug_Chat_ID": "322673713",
"debug_TOKEN": "312534798:AAFbMjS-tfd2BiZ_j3NEZuQYKwzACMcioVo",
"debug_adress": "carsten@hubobel.de",
"gmail_pass": "PL19zPL19z",
"gmail_user": "carsten.richter77@gmail.com",
"mpg_pass": "Ing8gresk",
"mpg_user": "schueler",
"pfad": "/Users/hubobel/Documents/Python/mpgScanner",
"wetter_API": "35a8e37c649985d5",
"wetter_Ort": "ILUDWIGS227",
"zitat": "Die Wissenschaft f\u00e4ngt eigentlich erst da an interessant zu werden, wo sie aufh\u00f6rt."
}

12
pass.json Normal file
View file

@ -0,0 +1,12 @@
{
"Chat_ID": "@mpglu",
"Land": "rp",
"TOKEN": "467241832:AAH3e0y6Fm7ig5DtConJP29GsD-zX1psNZo",
"Tag_Name": "Tuesday",
"Tag_Nummer": "1508865191",
"Uhrzeit": "2",
"Wochentag": "2",
"ccu_ip": "10.0.1.100",
"gmail_pass": "PL19zPL19z",
"gmail_user": "carsten.richter77@gmail.com"
}

10
telegram.py Normal file
View file

@ -0,0 +1,10 @@
import telebot
TOKEN = '467241832:AAH3e0y6Fm7ig5DtConJP29GsD-zX1psNZo'
chat_id = '@mpglu'
text='Es gibt einen neuen Vertretungsplan.'
tb=telebot.TeleBot(TOKEN)
tb.send_message(chat_id,text)
document = open('heute.pdf','rb')
tb.send_document(chat_id, document,caption='NEUUUUU')

42
test 2.py Normal file
View file

@ -0,0 +1,42 @@
import requests
import random
def Lotto():
a = (sorted(random.sample(range(1, 49), 6)))
b = random.randrange(0, 9)
while b in a:
b = random.randrange(1, 9)
lotto = str(a) + ',Superzahl: ' + str(b)
return lotto,a,b
url_zitat = 'http://api.hubobel.de/lotto/Mittwoch'
resp_zitat = requests.get(url_zitat)
data_zitat = resp_zitat.json()
inhalt=data_zitat[1]
a=[]
count=1
while count<7:
index=str('Z'+str(count))
a.append(inhalt[index])
count=count+1
b,c,d=Lotto()
treffer=0
ergebniss=[]
superzahl=''
for i in c:
if i in a:
treffer=treffer+1
ergebniss.append(i)
if d == inhalt['Superzahl']:
superzahl=' und die Superzahl!'
print('Die aktuellen Lottozahlen der '+inhalt['Datum']+' lauten: '+str(a)+',Superzahl: '+str(inhalt['Superzahl']))
print('Sie haben getippt: '+ b)
print('Sie haben '+str(treffer)+' Richtige '+str(ergebniss)+superzahl)

12
test.py Normal file
View file

@ -0,0 +1,12 @@
import requests
from
file = open("LOTTO_ab_2017.csv", "br")
file=requests.get('http://www.lottotip-check.de')
#csv_reader = csv.reader(file, delimiter=",")
a=[]
for row in file:
print(row)
a.append(row)
file.close()
print(len(a))
print(a[len(a)-5])

61
test_2.py Normal file
View file

@ -0,0 +1,61 @@
import bs4 as bs
import urllib.request
sauce=urllib.request.urlopen('http://www.lottotip-check.de').read()
soup=bs.BeautifulSoup(sauce,'html.parser')
#print(soup.prettify())
table=soup.find_all('table')
row=[]
ZahlenAll=[]
ZahlenMittwoch={'Datum':'','Z1':'','Z2':'','Z3':'','Z4':'','Z5':'','Z6':'','Superzahl':'','Spiel77':'','Super6':''}
ZahlenSamstag={'Datum':'','Z1':'','Z2':'','Z3':'','Z4':'','Z5':'','Z6':'','Superzahl':'','Spiel77':'','Super6':''}
ZahlenEuro={'Datum':'','Z1':'','Z2':'','Z3':'','Z4':'','Z5':'','Superzahl1':'','Superzahl2':''}
for i in table:
table_rows = i.find_all('tr')
for tr in table_rows:
#print(tr)
td = tr.find_all('td')
if td != []:
row = [i.text for i in td]
#print(row)
th = tr.find_all('th')
sz = [i.text for i in th]
#print(len(sz))
if len(sz)==5:
row.append(str(sz[2]))
row.append(str(sz[3]))
date = 'Ziehung vom: ' + str(sz[0])
sz = str(sz[1])
row.append(sz)
row.insert(0, date)
ZahlenAll.extend(row)
a=0
while a<=5:
a=a+1
ZahlenMittwoch['Z'+str(a)]=int(ZahlenAll[a])
ZahlenMittwoch['Datum']=ZahlenAll[0]
ZahlenMittwoch['Superzahl']=int(ZahlenAll[9])
ZahlenMittwoch['Super6']=int(ZahlenAll[8])
ZahlenMittwoch['Spiel77']=int(ZahlenAll[7])
print(ZahlenMittwoch)
a=0
while a<=5:
a=a+1
ZahlenSamstag['Z'+str(a)]=int(ZahlenAll[a + 18])
ZahlenSamstag['Datum']=ZahlenAll[18]
ZahlenSamstag['Superzahl']=int(ZahlenAll[27])
ZahlenSamstag['Super6']=int(ZahlenAll[26])
ZahlenSamstag['Spiel77']=int(ZahlenAll[25])
print(ZahlenSamstag)
a=0
while a<=4:
a=a+1
ZahlenEuro['Z'+str(a)]=int(ZahlenAll[a + 10])
ZahlenEuro['Datum']=ZahlenAll[10]
ZahlenEuro['Superzahl2']=int(ZahlenAll[17])
ZahlenEuro['Superzahl1']=int(ZahlenAll[16])
print(ZahlenEuro)

14
toFind.txt Normal file
View file

@ -0,0 +1,14 @@
Chuck
Apple
Amazon
Gutschein
Battlefield
Star Wars
Kodi
Nolan
Dunkirk
Star Trek
iPhone
iOS
IOS
macOS

12
txt2json.py Normal file
View file

@ -0,0 +1,12 @@
chuck_file= open(pfad + '/api/chuck.txt','r',encoding='UTF-8')
for line in chuck_file:
fact.append(line.strip('\n'))
chuck_file.close()
ran=random.randint(1,len(fact)-1)
fakt={}
a=0
for i in fact:
fakt[a]=i
a =a +1
with open(pfad+'/api/chuck.json', 'w',encoding='ascii') as fp:
json.dump(fakt, fp, sort_keys=True, indent=4)