Skip to content

Commit f877874

Browse files
committed
timestamp fixes & notification adjustments
1 parent 78658fe commit f877874

10 files changed

+101
-23
lines changed

.catgitinclude

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,5 @@ src/modules.py
88
src/text_message_handler.py
99
src/utils.py
1010
config/config.ini
11+
src/reminder_poller.py
12+
src/reminder_handler.py

src/api_get_stock_prices.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from datetime import datetime
1616

1717
# Configure logging
18-
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
18+
# logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
1919

2020
# Utility function to get API key
2121
def get_api_key():

src/api_get_stock_prices_alphavantage.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from datetime import datetime
1616

1717
# Configure logging
18-
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
18+
# logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
1919

2020
# Utility function to get API key
2121
def get_api_key():

src/api_get_stock_prices_yfinance.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from datetime import datetime
1414

1515
# Configure logging
16-
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
16+
# logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
1717

1818
# Search for stock symbol (Using yfinance for direct data fetching)
1919
async def search_stock_symbol(keyword):

src/api_key.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from config_paths import CONFIG_PATH, API_TOKEN_PATH # Import the centralized CONFIG_PATH
99

1010
# Set up basic logging
11-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
11+
# logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
1212

1313
# Flag to enable or disable fallback to environment variable if the key is not found in the file
1414
ENABLE_KEY_READING_FALLBACK = True

src/bot_token.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from config_paths import CONFIG_PATH, TOKEN_FILE_PATH
99

1010
# Set up basic logging configuration
11-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[logging.StreamHandler(sys.stdout)])
11+
# logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[logging.StreamHandler(sys.stdout)])
1212

1313
class BotTokenError(Exception):
1414
"""Custom exception for bot token retrieval failures."""

src/custom_functions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ async def observe_chat():
186186
},
187187
'reminder_text': {
188188
'type': 'string',
189-
'description': "Text of the reminder. Required for 'add', optional for 'edit'."
189+
'description': "Text of the reminder, in the user's requested language. You can be a bit creative, like: 'Hey! You asked me to remind you... etc, emojis and basic Telegram HTML formatting is allowed.'. Required for 'add', optional for 'edit'."
190190
},
191191
'due_time_utc': {
192192
'type': 'string',

src/main.py

Lines changed: 91 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
99
#
1010
# version of this program
11-
version_number = "0.76"
11+
version_number = "0.761"
1212

1313
# Add the project root directory to Python's path
1414
import sys
@@ -71,16 +71,67 @@
7171
from voice_message_handler import handle_voice_message
7272
from token_usage_visualization import generate_usage_chart
7373

74-
# Call the startup message function
75-
utils.print_startup_message(version_number)
76-
77-
# # Keep the root logger at INFO with a timestamp format
78-
# logging.basicConfig(
79-
# format='[%(asctime)s] %(name)s - %(levelname)s - %(message)s',
80-
# level=logging.INFO
81-
# )
74+
# force our basic logging
75+
logging.basicConfig(
76+
level=logging.INFO,
77+
format='[%(asctime)s] %(name)s - %(levelname)s - %(message)s',
78+
stream=sys.stdout,
79+
force=True, # <--- THIS forcibly removes existing handlers
80+
)
8281

83-
logger = logging.getLogger(__name__)
82+
def setup_logging(chat_logging_enabled: bool):
83+
"""
84+
Set up all logging (console & file handlers, chat logger, etc.) exactly once.
85+
"""
86+
root_logger = logging.getLogger()
87+
root_logger.setLevel(logging.INFO)
88+
89+
# Avoid double-adding a StreamHandler if it’s already there
90+
if not any(isinstance(h, logging.StreamHandler) for h in root_logger.handlers):
91+
console_formatter = logging.Formatter('[%(asctime)s] %(name)s - %(levelname)s - %(message)s')
92+
console_handler = logging.StreamHandler(sys.stdout)
93+
console_handler.setLevel(logging.INFO)
94+
console_handler.setFormatter(console_formatter)
95+
root_logger.addHandler(console_handler)
96+
97+
# Add a rotating file handler for the "main" bot log if desired
98+
# (If you don't want a file log, remove this block.)
99+
file_formatter = logging.Formatter('[%(asctime)s] %(name)s - %(levelname)s - %(message)s')
100+
file_handler = RotatingFileHandler(
101+
LOG_FILE_PATH,
102+
maxBytes=1_048_576, # e.g. ~1MB
103+
backupCount=5
104+
)
105+
file_handler.setLevel(logging.INFO)
106+
file_handler.setFormatter(file_formatter)
107+
root_logger.addHandler(file_handler)
108+
109+
# Optionally set up a separate "ChatLogger" if chat_logging_enabled is True
110+
if chat_logging_enabled:
111+
chat_logger = logging.getLogger('ChatLogger')
112+
chat_logger.setLevel(logging.INFO)
113+
chat_logger.propagate = False # We do not want double logs in root if we’re writing to separate files
114+
115+
# Clear existing handlers to avoid duplicates on restarts
116+
if chat_logger.hasHandlers():
117+
chat_logger.handlers.clear()
118+
119+
chat_file_handler = RotatingFileHandler(
120+
CHAT_LOG_FILE_PATH,
121+
maxBytes=CHAT_LOG_MAX_SIZE,
122+
backupCount=5
123+
)
124+
# You can keep a simpler format if you want:
125+
chat_file_formatter = logging.Formatter('%(asctime)s - %(message)s')
126+
chat_file_handler.setFormatter(chat_file_formatter)
127+
chat_logger.addHandler(chat_file_handler)
128+
129+
# If you also want the chat logs to appear in console, attach the same console_handler or a new one:
130+
# (comment out if you only want them in the file)
131+
chat_console_handler = logging.StreamHandler(sys.stdout)
132+
chat_console_handler.setLevel(logging.INFO)
133+
chat_console_handler.setFormatter(file_formatter) # reuse the same format
134+
chat_logger.addHandler(chat_console_handler)
84135

85136
# Initialize the tokenizer globally
86137
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
@@ -95,10 +146,20 @@ def __init__(self):
95146
self.load_config()
96147

97148
# Initialize logging
98-
self.initialize_logging()
149+
# self.initialize_logging()
99150

100151
# Initialize chat logging if enabled
101-
self.initialize_chat_logging()
152+
# self.initialize_chat_logging()
153+
154+
# REMOVED the calls to self.initialize_logging() or self.initialize_chat_logging()
155+
# Because we do that in main() before constructing TelegramBot.
156+
157+
self.logger = logging.getLogger('TelegramBotLogger')
158+
self.logger.info("Initializing TelegramBot...")
159+
160+
# The rest is mostly unchanged:
161+
self.reminders_enabled = self._parser.getboolean('Reminders', 'EnableReminders', fallback=False)
162+
self.logger.info(f"Reminders Enabled according to config: {self.reminders_enabled}")
102163

103164
# Assign self.logger after initializing logging
104165
self.logger = logging.getLogger('TelegramBotLogger')
@@ -224,7 +285,7 @@ def initialize_logging(self):
224285
# TelegramBotLogger
225286
telegram_logger = logging.getLogger('TelegramBotLogger')
226287
telegram_logger.setLevel(logging.INFO)
227-
telegram_logger.propagate = False # PREVENT PROPAGATION
288+
telegram_logger.propagate = True # True to enable propagation, False to disable it
228289

229290
# Clear existing handlers if any exist (safety measure)
230291
if telegram_logger.hasHandlers():
@@ -254,7 +315,7 @@ def initialize_chat_logging(self):
254315
if self.chat_logging_enabled:
255316
chat_logger = logging.getLogger('ChatLogger')
256317
chat_logger.setLevel(logging.INFO)
257-
chat_logger.propagate = False # PREVENT PROPAGATION
318+
chat_logger.propagate = True # set True to keep, False to disable
258319

259320
# Clear existing handlers if any exist (safety measure)
260321
if chat_logger.hasHandlers():
@@ -472,6 +533,21 @@ def run(self):
472533

473534
application.run_polling()
474535

475-
if __name__ == '__main__':
536+
def main():
537+
# 1) Read config
538+
config = configparser.ConfigParser()
539+
config.read(CONFIG_PATH)
540+
chat_logging_enabled = config['DEFAULT'].getboolean('ChatLoggingEnabled', False)
541+
542+
# 2) Actually call our logging setup
543+
setup_logging(chat_logging_enabled=chat_logging_enabled)
544+
545+
# 3) Print startup banner
546+
utils.print_startup_message(version_number)
547+
548+
# 4) Now create & run the bot
476549
bot = TelegramBot()
477550
bot.run()
551+
552+
if __name__ == '__main__':
553+
main()

src/rss_parser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
DEFAULT_MAX_ENTRIES = 20
2828

2929
# Configure logging
30-
logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(message)s')
30+
# logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(message)s')
3131

3232
# print term width horizontal line
3333
def print_horizontal_line(character='-'):

src/url_handler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
# Configure logging
2020
logger = logging.getLogger(__name__)
21-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
21+
# logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
2222

2323
# Helper function to format duration from seconds to H:M:S
2424
def format_duration(duration):

0 commit comments

Comments
 (0)