-
Notifications
You must be signed in to change notification settings - Fork 0
/
telebot.py
286 lines (244 loc) · 9.63 KB
/
telebot.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
import csv, requests, json, telepot, sys, os, time, datetime, subprocess, psutil, RPi.GPIO as GPIO
from telepot.loop import MessageLoop
from pprint import pprint
# Variablen aus der Config holen
from config import apikey
from config import grant
from config import owner
from config import botcall
from config import prozesse
from config import dmrid
logfile = "botlog.txt"
userfile = "users.csv"
grantfehler = "tztztz ... Du darfst das nicht!"
mmdvmaufruf = "sudo systemctl start mmdvmhost.service"
dmrgwaufruf = "sudo systemctl start dmrgateway.service"
svxaufruf = "sudo systemctl start svxlink"
svxstop = "sudo systemctl stop svxlink"
link341 = "sudo sh /home/pi/remote/link341.sh"
link951 = "sudo sh /home/pi/remote/link951.sh"
#mmdvmaufruf = "/usr/bin/screen /home/pi/MMDVMHost/MMDVMHost /home/pi/MMDVMHost/MMDVM-DB0ASE.ini"
#dmrgwaufruf = "/usr/bin/screen /home/pi/DMRGateway/DMRGateway /home/pi/DMRGateway/DMRGateway-DB0ASE.ini"
# GPIO Settings
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
# Loggingfunktion
def botlog(logtext):
file = open(logfile, "a+")
file.write(time.strftime("%d.%m. %H:%M:%S") + ": " + logtext + '\n')
file.close()
# Funktion zur Information des/der Botowner
def ownerinfo(msg,owner):
for x in owner:
try:
bot.sendMessage(x,msg)
except:
print("Benachrichtigung Owner ging schief")
# Lasthearedfunktion DMR
def lastheared(suchstring):
if suchstring == '':
suchstring = "received RF voice header"
else:
suchstring = "received RF voice header from " +suchstring
heared = []
dateiname = "/var/log/mmdvm/MMDVM-"+(time.strftime("%Y-%m-%d"))+".log"
file = open(dateiname, "r")
for line in file:
if line.find(suchstring) > 1:
string = (line.rstrip())
string = string.split(" ")
heared.append(string)
file.close()
if not heared:
return "Bis jetzt hat noch keiner Gefunkt :-( ..."
else:
return heared[-1][2] + " " + heared[-1][4] + " " + heared[-1][5] + " " + heared[-1][11] + " " + heared[-1][13] + " " + heared[-1][14]
# Prozesskiller
def prockiller(prozess):
os.system('pkill '+prozess)
# Funktion zum Abruf der Abbonierten TG
def talkgroups():
r = requests.get("http://api.brandmeister.network/v1.0/repeater/?action=profile&q=" + dmrid)
try:
data = r.json()
tgs = 'Talkgroups:'
for tg in data['staticSubscriptions']:
tgs += "\n" + str(tg['talkgroup']) + " im TS" + str(tg['slot'])
for tg in data['clusters']:
tgs += "\n" + str(tg['talkgroup']) + " im TS" + str(tg['slot']) + " (" + str(tg['extTalkgroup']) + ")"
if tgs == 'Talkgroups:':
tgs = "Keine Talkgroups statisch geschaltet."
except:
print("Abruf der Talkgroups ging schief....")
r.close()
return tgs
# Funktion zum Testen, ob ein Prozess läuft
def prozesschecker(prozess):
proc = ([p.info for p in psutil.process_iter(attrs=['pid','name']) if prozess in p.info['name']])
if proc != []:
status = "Aktiv"
else:
status = "Nicht Aktiv"
return status
def handle(msg):
content_type, chat_type, chat_id = telepot.glance(msg)
#print(content_type, chat_type, chat_id)
#pprint(msg)
vorname = msg['from']['first_name']
username = msg['from']['username']
id = msg['from']['id']
msg['text'] = msg['text'].lower()
# print(msg['text'])
if msg['text'] in ["/start","/start start", "start", "hallo", "Hallo", "Hi", "Start"]:
bot.sendMessage(chat_id, "Herzlich willkommen bei " + botcall + " " + vorname + "!" + \
"\nUm Hilfe zu erhalten, schreib /hilfe. Informationen und Hinweise bitte an @dj1jay.")
elif msg['text'] in ["/hilfe", "hilfe"]:
hilfetext = "Informationen und Kommandos:\n/status Gibt den Status des Repeaters aus\n/hilfe Hilfetext mit der" \
" Liste der Kommandos\n/tg Listet die in DMR geschalteten TG auf\n/lheared Gibt aus, wer als letztes lokal gehört wurde."\
"\n/lastthr Letzte Relaisstation im ThüringenLink? \n/lastata Letzte Relais Station im Relaisverbund Berlin\n/lastecho letzte Echolink Station bei DB0FTS"
if id in grant:
hilfetext += "\n\n/killmmdvm Stoppt MMDVM\n/startmmdvm Startet MMDVM\n/killdmrgw Stoppt das DMRGateway\n/startdmrgw Startet DMRGateway" \
"\n/killsvx Beende Svxlink\n/startsvx Starte Svxlink\n/switchthr Relaisverbund Wechseln nach Thüringen\n/switchata Relaisverbund Wechseln nach Berlin"\
"\n/lhecho Letzte Station Echolink \n/txan Schaltet den Sender an\n/txaus Schaltet den Sender aus\n/rxan Schaltet den RX ein" \
"\n/rxaus Schaltet den RX an\n/reboot start den Rechner neu"
bot.sendMessage(chat_id,botcall + " " + hilfetext)
elif msg['text'] in ["/tg"]:
bot.sendMessage(chat_id, talkgroups())
elif "/lheared" in msg['text']:
if msg['text'] == "/lheared":
heared = lastheared('')
bot.sendMessage(chat_id,heared)
else:
suche = msg['text'].split(" ")
heared = lastheared(suche[1].upper())
bot.sendMessage(chat_id,heared)
elif msg['text'] in ["/killmmdvm"]:
if id in grant:
prockiller("MMDVMHost")
bot.sendMessage(chat_id,"Beende MMDVM...")
else:
bot.sendMessage(chat_id,grantfehler)
elif msg['text'] in ["/startmmdvm"]:
if id in grant:
os.system(mmdvmaufruf)
bot.sendMessage(chat_id,"Starte MMDVM")
else:
bot.sendMessage(chat_id,grantfehler)
elif msg['text'] in ["/killdmrgw"]:
if id in grant:
prockiller("DMRGateway")
bot.sendMessage(chat_id,"Beende DMRGateway...")
else:
bot.sendMessage(chat_id,grantfehler)
elif msg['text'] in ["/startdmrgw"]:
if id in grant:
os.system(dmrgwaufruf)
bot.sendMessage(chat_id,"Starte DMRGateway")
else:
bot.sendMessage(chat_id,grantfehler)
elif msg['text'] in ["/killsvx"]:
if id in grant:
os.system(svxstop)
bot.sendMessage(chat_id,"Beende SvxLink...")
else:
bot.sendMessage(chat_id,grantfehler)
elif msg['text'] in ["/startsvx"]:
if id in grant:
os.system(svxaufruf)
bot.sendMessage(chat_id,"Starte SvxLink")
else:
bot.sendMessage(chat_id,grantfehler)
## Svxlink Log
elif msg['text'] in ["/lastthr"]:
lhthr = subprocess.check_output('grep "THR_Logic: Talker" /var/log/svxlink.log | tail -1 | cut -d: -f6', shell=True)
bot.sendMessage(chat_id,"Zuletzt gehört im ThüringenLink:" + lhthr)
##
elif msg['text'] in ["/lastata"]:
lhata = subprocess.check_output('grep "ATA_Logic: Talker" /var/log/svxlink.log | tail -1 | cut -d: -f6', shell=True)
bot.sendMessage(chat_id,"Zuletzt gehört im Verbund Berlin:" + lhata)
elif msg['text'] in ["/lastecho"]:
lhecho = subprocess.check_output('grep "EchoLink QSO state changed to CONNECTED" /var/log/svxlink.log | tail -1 | cut -d: -f4', shell=True)
bot.sendMessage(chat_id,"Zuletzt per Echolink:" + lhecho)
elif msg['text'] in ["/switchata"]:
if id in grant:
os.system(link951)
bot.sendMessage(chat_id,"Wechsel zum Relaisverbund Berlin")
else:
bot.sendMessage(chat_id,grantfehler)
elif msg['text'] in ["/switchthr"]:
if id in grant:
os.system(link341)
bot.sendMessage(chat_id,"Wechsel zum Relaisverbund ThüringenLink")
else:
bot.sendMessage(chat_id,grantfehler)
###
elif msg['text'] in ["/status"]:
status = ''
# Eingänge lesen
if GPIO.input(13) == GPIO.HIGH:
status += "TX ist aus\n"
else:
status += "TX is an\n"
if GPIO.input(15) == GPIO.HIGH:
status += "RX ist aus"
else:
status += "RX ist an"
# Laufende Prozesse testen
for proc in prozesse:
status += "\n" + proc + " " + prozesschecker(proc)
## Temperaturen
# CPU-Temperaturen auslesen
tFile = open('/sys/class/thermal/thermal_zone0/temp')
temp = float(tFile.read())
tempC = temp/1000
status += "\nCPU Temperatur " + str(tempC)
bot.sendMessage(chat_id, status)
elif msg['text'] in ["/txaus"]:
if id in grant:
GPIO.output(13, GPIO.HIGH)
bot.sendMessage(chat_id,"Sender ist aus!")
else:
bot.sendMessage(chat_id,grantfehler)
elif msg['text'] in ["/txan"]:
if id in grant:
GPIO.output(13, GPIO.LOW)
bot.sendMessage(chat_id,"Sender ist wieder an!")
else:
bot.sendMessage(chat_id,grantfehler)
elif msg['text'] in ["/rxaus"]:
if id in grant:
GPIO.output(15, GPIO.HIGH)
bot.sendMessage(chat_id,"Empfang ist aus!")
else:
bot.sendMessage(chat_id,grantfehler)
elif msg['text'] in ["/rxan"]:
if id in grant:
GPIO.output(15, GPIO.LOW)
bot.sendMessage(chat_id,"Empfang ist wieder an!")
else:
bot.sendMessage(chat_id,grantfehler)
elif msg['text'] in ["/reboot"]:
if id in grant:
bot.sendMessage(chat_id,"Starte das System neu.")
os.system('sudo shutdown -r now')
else:
bot.sendMessage(chat_id,grantfehler)
else:
bot.sendMessage(chat_id, 'Mit "' + msg['text'] + '" kann ich nichts anfangen, '+ vorname + "!\nEine Liste der Befehle bekommst du mit /hilfe.")
bot = telepot.Bot(apikey)
try:
ownerinfo("Ich bin wieder da...",owner)
MessageLoop(bot,handle).run_as_thread()
except:
print("Irgendwas stimmt mit dem Bot nicht....")
try:
while 1:
time.sleep(10)
except:
print("Und Tschüss....")
ownerinfo("Der Bot wird beendet...",owner)
# GPIO.cleanup()