Skip to content

Commit d73493f

Browse files
committed
Refactor settings; update logic when db is empty; fixing logging and exceptions
1 parent daba456 commit d73493f

3 files changed

Lines changed: 49 additions & 42 deletions

File tree

datapath.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@
77
import dynaconfig
88
import news_db
99

10-
# Time range for sending messages
11-
TIME_TO_SEND_START = datetime.now().replace(hour=10, minute=00).strftime("%H:%M")
12-
TIME_TO_SEND_END = datetime.now().replace(hour=20, minute=00).strftime("%H:%M")
10+
# Time range for sending messages loaded from settings.toml
11+
TIME_TO_SEND_START = dynaconfig.settings["TIMINIGS"]["TIME_TO_SEND_START"]
12+
TIME_TO_SEND_END = dynaconfig.settings["TIMINIGS"]["TIME_TO_SEND_END"]
1313

1414
# Logging
1515
logging.basicConfig(
@@ -23,9 +23,9 @@
2323
)
2424

2525

26-
API_TOKEN = dynaconfig.settings["API_TOKEN"]
26+
API_TOKEN = dynaconfig.settings["TELEGRAM"]["API_TOKEN"]
2727
API_URL = f"https://api.telegram.org/bot{API_TOKEN}/sendMessage"
28-
CHAT_ID = dynaconfig.settings["CHAT_ID"]
28+
CHAT_ID = dynaconfig.settings["TELEGRAM"]["CHAT_ID"]
2929

3030

3131
def send_news_to_telegram(message):
@@ -49,17 +49,21 @@ def send_news_to_telegram(message):
4949

5050

5151
if __name__ == "__main__":
52-
data_from_db = news_db.create_connection(news_db.DB_FILE)
52+
db_connection = news_db.create_connection(news_db.DB_FILE)
5353
while True:
54-
if data_from_db:
54+
if db_connection:
5555
time.sleep(1)
5656
current_time = datetime.now().strftime("%H:%M")
5757
if TIME_TO_SEND_START < current_time < TIME_TO_SEND_END:
58-
logging.info(f"Time: {current_time}. Time to send has come !")
59-
for news in news_db.send_all_news(data_from_db):
60-
send_news_to_telegram(news)
61-
time.sleep(300)
58+
logging.info("Time to send has come !")
59+
data_from_db = news_db.send_all_news(db_connection)
60+
if len(data_from_db) == 0:
61+
logging.warning("Database is empty !")
62+
else:
63+
for news in data_from_db:
64+
send_news_to_telegram(news)
65+
time.sleep(300)
6266
else:
63-
logging.info(f"Time: {current_time}. Still waiting to send.")
67+
logging.info("Still waiting to send.")
6468
else:
65-
logging.warning("Looks like database is empty.")
69+
logging.error("Connection to db is not exist !")

news_db.py

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@
77

88
import dynaconfig
99

10-
TIME_TO_PURGE = "00:00"
11-
12-
DB_FILE = Path(f"{dynaconfig.settings['DB_NAME']}")
10+
# Timing and db name loaded from settings.toml
11+
TIME_TO_PURGE = dynaconfig.settings["TIMINIGS"]["TIME_TO_PURGE"]
12+
DB_FILE = Path(f"{dynaconfig.settings['DB']['DB_NAME']}")
1313

1414
# SQL queries
1515
CREATE_TABLE_SQL = """
@@ -121,19 +121,20 @@ def delete_all_news(conn):
121121

122122

123123
if __name__ == "__main__":
124-
conn = create_connection(DB_FILE)
125-
if DB_FILE.exists():
126-
create_table(conn, CREATE_TABLE_SQL)
127-
128-
while True:
129-
CURRENT_TIME = datetime.now().strftime("%H:%M")
130-
time.sleep(1)
131-
if conn is not None:
132-
send_all_news(conn)
133-
if CURRENT_TIME == TIME_TO_PURGE:
134-
logging.info(f"Time: {CURRENT_TIME}. Time to purge has come !")
135-
delete_all_news(conn)
136-
else:
137-
logging.info(f"Time: {CURRENT_TIME}. Still waiting for purging.")
138-
else:
139-
logging.error("Error! Cannot create the database connection.")
124+
try:
125+
conn = create_connection(DB_FILE)
126+
if DB_FILE.exists():
127+
create_table(conn, CREATE_TABLE_SQL)
128+
129+
while True:
130+
CURRENT_TIME = datetime.now().strftime("%H:%M")
131+
time.sleep(1)
132+
if conn is not None:
133+
send_all_news(conn)
134+
if CURRENT_TIME == TIME_TO_PURGE:
135+
logging.info("Time to purge has come !")
136+
delete_all_news(conn)
137+
else:
138+
logging.info("Still waiting for purging.")
139+
except sqlite3.Error as sql_err:
140+
logging.error(f"Cannot create the database connection. Error: {sql_err}")

truth_seeker.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,14 @@
77
import dynaconfig
88
import news_db
99

10-
# Load variables from settings.toml
11-
API_KEY = dynaconfig.settings["API_KEY"]
12-
QUERY = dynaconfig.settings["QUERY"]
10+
# News API params loaded from settings.toml
11+
API_KEY = dynaconfig.settings["NEWS_API"]["API_KEY"]
12+
QUERY = dynaconfig.settings["NEWS_API"]["QUERY"]
13+
LANGUAGE = dynaconfig.settings["NEWS_API"]["LANGUAGE"]
14+
TIME_TO_SEARCH = dynaconfig.settings["TIMINGS"]["TIME_TO_SEARCH"]
1315

1416
newsapi = NewsApiClient(api_key=API_KEY)
1517

16-
TIME_TO_SEARCH = "11:10"
17-
1818

1919
# Logging
2020
logging.basicConfig(
@@ -37,10 +37,12 @@ def fetch_info() -> dict:
3737
# Use to get news from yesterday to current time
3838
yesterday = date.today() - timedelta(days=1)
3939
try:
40+
logging.info(
41+
f"Searching for {QUERY}; most popular; from: {yesterday}; language: {LANGUAGE}"
42+
)
4043
result = newsapi.get_everything(
41-
q=QUERY, sort_by="popularity", from_param=yesterday
44+
q=QUERY, sort_by="popularity", from_param=yesterday, language=LANGUAGE
4245
)
43-
logging.info(f"Searching for {QUERY}")
4446
return result
4547
except ConnectionError as con_err:
4648
logging.error(con_err)
@@ -74,7 +76,7 @@ def load_to_db(fetch_info: dict):
7476
tuple(article_list),
7577
)
7678
else:
77-
logging.warning("Empty response from API.")
79+
logging.warning("Empty response from News API.")
7880
raise IndexError
7981

8082

@@ -84,10 +86,10 @@ def load_to_db(fetch_info: dict):
8486
time.sleep(1)
8587
# Pull too much info
8688
if CURRENT_TIME == TIME_TO_SEARCH:
87-
logging.info(f"Time: {CURRENT_TIME}. Time to search has come !")
89+
logging.info("Time to search has come !")
8890
try:
8991
load_to_db(fetch_info())
9092
except BaseException as base_err:
9193
logging.error(base_err)
9294
else:
93-
logging.info(f"Time: {CURRENT_TIME}. Still waiting for searching.")
95+
logging.info("Still waiting for searching.")

0 commit comments

Comments
 (0)