Help to sort out the json error -
C:\Users\123\AppData\Local\Programs\Python\Python38>python C:\main_3.py
Traceback (most recent call last):
File "C:\main_3.py", line 10, in <module>
data = json.load(file)
File "C:\Users\123\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\123\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\123\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\123\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
C:\Users\123\AppData\Local\Programs\Python\Python38>
Perhaps this error is due to an empty file - ping_data.json? In this case, I do not know how to prepare this file for the first launch.
Telegram bot. The point of the program is to ping hosts and keep a record of the status of the last check, and in case of program crashes and startup, all the results of the last check must be read from the file.
Complete code
import telebot
from pythonping import ping
import time
import yaml
from libs.host import address
import json
ping_data = dict()
with open('C:\ping_data.json') as file:
data = json.load(file)
def init():
global bot, userid, interval
interval = 30
with open('C:\config2.yaml', encoding="utf-8") as f:
try:
docs = yaml.load_all(f, Loader=yaml.FullLoader)
for doc in docs:
for k, v in doc.items():
if k == "botkey":
bot = telebot.TeleBot(v)
elif k == "userid":
userid = v
elif k == "hosts":
set_hosts(v)
elif k == "interval":
interval = int(v)
except yaml.YAMLError as exc:
print(exc)
def set_hosts(hosts):
"""
Здесь парсим список хостов и передаем их в массив
"""
global hosts_list
hosts_list = []
for item in hosts:
ac = item.split(":")
hosts_list.append(address(ac[0], ac[1]))
def send_message(message):
"""
Посылаем сообщение пользователю
"""
bot.send_message(userid, message)
def ping_host(address):
status = ping_url(address.address)
if data['address.address'] != status:
ping_data['address.address'] = status
send_message(( "! " if status is None else "+ " if status else "- ") + address.comment)
def ping_url(url):
"""
Пинг хоста. Response list - это ответ библиотеки ping. По умолчанию она
посылает четыре пакета. Если хотя бы один пинг успешен, хост активен
"""
try:
response_list = ping(url, timeout=5, verbose = True)
except:
return None
return sum(1 for x in response_list if x.success) > 0
def main():
"""
Бесконечный цикл, который пингует сервисы один за другим.
"""
init()
while True:
for host in hosts_list:
ping_host(host)
with open('C:\ping_data.json','w') as file:
json.dump(ping_data, file, indent=2)
time.sleep(interval)
if __name__ == '__main__':
main()
The contents of the config2.yaml file for example.
botkey: ***********************************
userid: -**********
interval: 60
hosts:
- "google.com:Google.ru"
- "ya.ru:Yandex.ru"
- "mail.ru:Mail.ru"
- "rambler.ru:Rambler.ru"