Skip to content

Commit 072bf1b

Browse files
Merge pull request #3 from FlyingFathead/timestamping
`v0.7613` - Improved timestamps on multiple timezones
2 parents 018f745 + 0333ed4 commit 072bf1b

File tree

4 files changed

+141
-21
lines changed

4 files changed

+141
-21
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,10 @@ If you run into any issues, consult the logs or reach out on the repository's [I
240240
---
241241

242242
# Changelog
243+
- v0.7613 - Improved timestamps on multiple timezones
244+
- Added a separate module to `src/timedate_handler.py` to assist the model
245+
- => Datetime stamps now in separate system messages
246+
- => More TZ-aware dates and times
243247
- v0.7611 - Parsing hotfix for notifications
244248
- v0.761 - **Timed notifications / user reminders**
245249
- Brand-new feature: users can set timed reminders (alerts) by requesting reminders that the bot stores in an SQLite database. A separate poller picks them up as soon as they are due, and the bot automatically notifies the user on set times.

src/main.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
# Multi-API Telegram Bot (Powered by ChatKeke)
2-
#
2+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
33
# by FlyingFathead ~*~ https://github.com/FlyingFathead
44
# ghostcode: ChaosWhisperer
5-
#
65
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
76
# https://github.com/FlyingFathead/TelegramBot-OpenAI-API
87
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
9-
#
108
# version of this program
11-
version_number = "0.7612"
9+
version_number = "0.7613"
1210

1311
# Add the project root directory to Python's path
1412
import sys
@@ -215,7 +213,10 @@ def load_config(self):
215213
'SystemInstructions',
216214
'You are an OpenAI API-based chatbot on Telegram.'
217215
)
218-
self.system_instructions = f"[Bot's current model: {self.model}] {default_system_msg}"
216+
217+
# # // skip current model info
218+
# self.system_instructions = f"[Bot's current model: {self.model}] {default_system_msg}"
219+
self.system_instructions = f"[Instructions] {default_system_msg}"
219220

220221
self.start_command_response = self.config.get(
221222
'StartCommandResponse',

src/text_message_handler.py

Lines changed: 44 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,13 @@
2929
from telegram.constants import ChatAction
3030
from telegram.error import TimedOut
3131

32+
# time & date handling
33+
from timedate_handler import (
34+
get_ordinal_suffix,
35+
get_english_timestamp_str,
36+
get_finnish_timestamp_str
37+
)
38+
3239
# reminder handling
3340
from reminder_handler import handle_add_reminder, handle_delete_reminder, handle_edit_reminder, handle_view_reminders
3441

@@ -259,16 +266,31 @@ async def handle_message(bot, update: Update, context: CallbackContext, logger)
259266
# Debug: Print before token limit checks
260267
bot.logger.info(f"[Debug] is_no_limit: {is_no_limit}, user_token_count: {user_token_count}, max_tokens_config: {max_tokens_config}")
261268

262-
# get date & time for timestamps
269+
# ~~~~~~~~~~~~~~~
270+
# Make timestamp
271+
# ~~~~~~~~~~~~~~~
263272
now_utc = datetime.datetime.utcnow()
264-
current_time = now_utc
265-
# utc_timestamp = now_utc.strftime("%Y-%m-%d %H:%M:%S UTC")
266-
267-
# display abbreviated
268-
utc_timestamp = now_utc.strftime("%Y-%m-%d %H:%M:%S %a UTC")
269273

274+
# We'll keep this for session timeout comparisons
275+
current_time = now_utc
270276
day_of_week = now_utc.strftime("%A")
271-
user_message_with_timestamp = f"[{utc_timestamp}] {user_message}"
277+
system_timestamp = now_utc.strftime("%Y-%m-%d %H:%M:%S UTC")
278+
279+
english_line = get_english_timestamp_str(now_utc)
280+
finnish_line = get_finnish_timestamp_str(now_utc)
281+
282+
# Combine them however you like, e.g.:
283+
#
284+
# Monday, April 9th, 2025 | Time (UTC): 12:34:56
285+
# maanantai, 9. huhtikuuta 2025, klo 15:34:56 Suomen aikaa
286+
#
287+
current_timestamp_str = f"{english_line}\n{finnish_line}"
288+
289+
# We'll put that into a system message
290+
timestamp_system_msg = {
291+
"role": "system",
292+
"content": current_timestamp_str
293+
}
272294

273295
# Add the user's tokens to the total usage (JSON style)
274296
bot.total_token_usage += user_token_count
@@ -316,12 +338,24 @@ async def handle_message(bot, update: Update, context: CallbackContext, logger)
316338
# Initialize chat_history as an empty list if it doesn't exist
317339
chat_history = context.chat_data.get('chat_history', [])
318340

341+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~
342+
# Insert the new system msg
343+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~
344+
# logger info on the appended system message
345+
logger.info(f"Inserting timestamp system message: {current_timestamp_str}")
346+
347+
chat_history.append(timestamp_system_msg)
348+
319349
# Append the new user message to the chat history
320-
chat_history.append({"role": "user", "content": user_message_with_timestamp})
350+
chat_history.append({"role": "user", "content": user_message})
321351

322352
# Prepare the conversation history to send to the OpenAI API
323-
system_timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
324-
system_message = {"role": "system", "content": f"System time+date: {system_timestamp}, {day_of_week}): {bot.system_instructions}"}
353+
354+
# # // old method that included the timestamp in the original system message
355+
# system_timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
356+
# system_message = {"role": "system", "content": f"System time+date: {system_timestamp}, {day_of_week}): {bot.system_instructions}"}
357+
358+
system_message = {"role": "system", "content": f"Instructions: {bot.system_instructions}"}
325359

326360
chat_history_with_system_message = [system_message] + chat_history
327361

@@ -1319,12 +1353,6 @@ async def handle_message(bot, update: Update, context: CallbackContext, logger)
13191353
model_info=model_info
13201354
)
13211355

1322-
# # Log the bot's response
1323-
# bot.log_message(
1324-
# message_type='Bot',
1325-
# message=bot_reply,
1326-
# )
1327-
13281356
# # # send the response
13291357
# # await context.bot.send_message(
13301358
# # chat_id=chat_id,

src/timedate_handler.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# timedate_handler.py
2+
import datetime
3+
import pytz
4+
5+
# Maps English day names from strftime() -> Finnish
6+
fi_days = {
7+
"Monday": "maanantai",
8+
"Tuesday": "tiistai",
9+
"Wednesday": "keskiviikko",
10+
"Thursday": "torstai",
11+
"Friday": "perjantai",
12+
"Saturday": "lauantai",
13+
"Sunday": "sunnuntai"
14+
}
15+
16+
# Maps English month names -> Finnish “month in the partitive case” for typical date usage
17+
fi_months = {
18+
"January": "tammikuuta",
19+
"February": "helmikuuta",
20+
"March": "maaliskuuta",
21+
"April": "huhtikuuta",
22+
"May": "toukokuuta",
23+
"June": "kesäkuuta",
24+
"July": "heinäkuuta",
25+
"August": "elokuuta",
26+
"September": "syyskuuta",
27+
"October": "lokakuuta",
28+
"November": "marraskuuta",
29+
"December": "joulukuuta"
30+
}
31+
32+
def get_ordinal_suffix(day_num: int) -> str:
33+
"""
34+
Returns the English ordinal suffix for a given day of the month, e.g.
35+
1->"1st", 2->"2nd", 3->"3rd", 4->"4th", etc.
36+
"""
37+
if 11 <= (day_num % 100) <= 13:
38+
return "th"
39+
elif day_num % 10 == 1:
40+
return "st"
41+
elif day_num % 10 == 2:
42+
return "nd"
43+
elif day_num % 10 == 3:
44+
return "rd"
45+
else:
46+
return "th"
47+
48+
def get_english_timestamp_str(now_utc: datetime.datetime) -> str:
49+
"""
50+
Returns an English-formatted date/time string, e.g.:
51+
'Monday, April 9th, 2025 | Time (UTC): 12:34:56'
52+
"""
53+
day_of_week_eng = now_utc.strftime("%A") # e.g. "Monday"
54+
month_name_eng = now_utc.strftime("%B") # e.g. "April"
55+
day_num = int(now_utc.strftime("%d"))
56+
year_str = now_utc.strftime("%Y")
57+
suffix = get_ordinal_suffix(day_num)
58+
date_str = f"{month_name_eng} {day_num}{suffix}, {year_str}"
59+
time_str = now_utc.strftime("%H:%M:%S") # "12:34:56"
60+
61+
return f"{day_of_week_eng}, {date_str} | Time (UTC): {time_str}"
62+
63+
def get_finnish_timestamp_str(now_utc: datetime.datetime) -> str:
64+
"""
65+
Returns a Finnish-formatted date/time string. For example:
66+
'maanantai, 9. huhtikuuta 2025, klo 15:34:56 Suomen aikaa'
67+
68+
(Adjust as you like for Finnish grammar.)
69+
"""
70+
helsinki_tz = pytz.timezone("Europe/Helsinki")
71+
now_fin = now_utc.astimezone(helsinki_tz)
72+
73+
weekday_eng = now_fin.strftime("%A") # e.g. "Monday"
74+
day_of_week_fi = fi_days.get(weekday_eng, weekday_eng)
75+
76+
month_eng = now_fin.strftime("%B") # e.g. "April"
77+
month_fi = fi_months.get(month_eng, month_eng)
78+
79+
day_num = int(now_fin.strftime("%d")) # e.g. 9
80+
year_str = now_fin.strftime("%Y") # e.g. "2025"
81+
82+
# For Finnish style we might do e.g. "9. huhtikuuta 2025"
83+
date_str_fi = f"{day_num}. {month_fi} {year_str}"
84+
85+
time_str_fi = now_fin.strftime("%H:%M:%S") # "15:34:56"
86+
# For instance: "maanantai, 9. huhtikuuta 2025, klo 15:34:56 Suomen aikaa"
87+
return f"{day_of_week_fi}, {date_str_fi}, klo {time_str_fi} Suomen aikaa"

0 commit comments

Comments
 (0)