Skip to content

Commit 71d375f

Browse files
committed
v0.7613 - timestamping to system msgs
1 parent 018f745 commit 71d375f

File tree

3 files changed

+137
-16
lines changed

3 files changed

+137
-16
lines changed

src/main.py

Lines changed: 2 additions & 4 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

src/text_message_handler.py

Lines changed: 48 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import json
1616
import asyncio
1717
import openai
18+
from datetime import datetime, timezone
1819

1920
import utils
2021
from utils import holiday_replacements
@@ -29,6 +30,13 @@
2930
from telegram.constants import ChatAction
3031
from telegram.error import TimedOut
3132

33+
# time & date handling
34+
from timedate_handler import (
35+
get_ordinal_suffix,
36+
get_english_timestamp_str,
37+
get_finnish_timestamp_str
38+
)
39+
3240
# reminder handling
3341
from reminder_handler import handle_add_reminder, handle_delete_reminder, handle_edit_reminder, handle_view_reminders
3442

@@ -142,8 +150,9 @@ def pick_model_auto_switch(bot):
142150
if not DB_INITIALIZED_SUCCESSFULLY or not DB_PATH:
143151
logging.warning("DB not initialized or path missing — can't auto-switch, fallback to default model.")
144152
return True
145-
146-
usage_date = datetime.datetime.utcnow().strftime('%Y-%m-%d')
153+
# // old method
154+
# usage_date = datetime.datetime.utcnow().strftime('%Y-%m-%d')
155+
usage_date = datetime.now(timezone.utc).strftime('%Y-%m-%d')
147156
daily_usage = _get_daily_usage_sync(DB_PATH, usage_date)
148157
if not daily_usage:
149158
daily_premium_tokens, daily_fallback_tokens = (0, 0)
@@ -259,16 +268,31 @@ async def handle_message(bot, update: Update, context: CallbackContext, logger)
259268
# Debug: Print before token limit checks
260269
bot.logger.info(f"[Debug] is_no_limit: {is_no_limit}, user_token_count: {user_token_count}, max_tokens_config: {max_tokens_config}")
261270

262-
# get date & time for timestamps
271+
# ~~~~~~~~~~~~~~~
272+
# Make timestamp
273+
# ~~~~~~~~~~~~~~~
263274
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")
269275

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

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

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

322354
# 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}"}
355+
356+
# # // old method that included the timestamp in the original system message
357+
# system_timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
358+
# system_message = {"role": "system", "content": f"System time+date: {system_timestamp}, {day_of_week}): {bot.system_instructions}"}
359+
360+
system_message = {"role": "system", "content": f"Instructions: {bot.system_instructions}"}
325361

326362
chat_history_with_system_message = [system_message] + chat_history
327363

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)