77import dynaconfig
88import 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
1515logging .basicConfig (
1616 format = "%(asctime)s - %(levelname)s - %(message)s" , level = logging .INFO
1717)
18+ logging .basicConfig (
19+ format = "%(asctime)s - %(levelname)s - %(message)s" , level = logging .WARNING
20+ )
1821logging .basicConfig (
1922 format = "%(asctime)s - %(levelname)s - %(message)s" , level = logging .ERROR
2023)
2124
2225
23- API_TOKEN = dynaconfig .settings ["API_TOKEN" ]
26+ API_TOKEN = dynaconfig .settings ["TELEGRAM" ][ " API_TOKEN" ]
2427API_URL = f"https://api.telegram.org/bot{ API_TOKEN } /sendMessage"
25- CHAT_ID = dynaconfig .settings ["CHAT_ID" ]
28+ CHAT_ID = dynaconfig .settings ["TELEGRAM" ][ " CHAT_ID" ]
2629
2730
2831def send_news_to_telegram (message ):
@@ -46,14 +49,21 @@ def send_news_to_telegram(message):
4649
4750
4851if __name__ == "__main__" :
49- data_from_db = news_db .create_connection (news_db .DB_FILE )
52+ db_connection = news_db .create_connection (news_db .DB_FILE )
5053 while True :
51- time .sleep (1 )
52- current_time = datetime .now ().strftime ("%H:%M" )
53- if TIME_TO_SEND_START < current_time < TIME_TO_SEND_END :
54- logging .info (f"Time: { current_time } . Time to send has come !" )
55- for news in news_db .send_all_news (data_from_db ):
56- send_news_to_telegram (news )
57- time .sleep (300 )
54+ if db_connection :
55+ time .sleep (1 )
56+ current_time = datetime .now ().strftime ("%H:%M" )
57+ if TIME_TO_SEND_START < current_time < TIME_TO_SEND_END :
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 )
66+ else :
67+ logging .info ("Still waiting to send." )
5868 else :
59- logging .info ( f"Time: { current_time } . Still waiting to send. " )
69+ logging .error ( "Connection to db is not exist ! " )
0 commit comments