mirror of
https://github.com/aljazceru/chatgpt-telegram-bot.git
synced 2025-12-20 06:05:12 +01:00
refactored language to bot_language
"language" seems to be reserved on some systems for the actual system language
This commit is contained in:
@@ -72,7 +72,7 @@ def main():
|
||||
'token_price': float(os.environ.get('TOKEN_PRICE', 0.002)),
|
||||
'image_prices': [float(i) for i in os.environ.get('IMAGE_PRICES',"0.016,0.018,0.02").split(",")],
|
||||
'transcription_price': float(os.environ.get('TOKEN_PRICE', 0.006)),
|
||||
'language': os.environ.get('LANGUAGE', 'en')
|
||||
'bot_language': os.environ.get('BOT_LANGUAGE', 'en')
|
||||
}
|
||||
|
||||
# Setup and run ChatGPT and Telegram bot
|
||||
|
||||
@@ -20,15 +20,15 @@ from usage_tracker import UsageTracker
|
||||
with open('translations.json', 'r', encoding='utf-8') as f:
|
||||
translations = json.load(f)
|
||||
|
||||
def localized_text(key, language):
|
||||
def localized_text(key, bot_language):
|
||||
"""
|
||||
Return translated text for a key in specified language.
|
||||
Return translated text for a key in specified bot_language.
|
||||
Keys and translations can be found in the translations.json.
|
||||
"""
|
||||
try:
|
||||
return translations[language][key]
|
||||
return translations[bot_language][key]
|
||||
except KeyError:
|
||||
logging.warning(f"No translation available for language code '{language}' and key '{key}'")
|
||||
logging.warning(f"No translation available for bot_language code '{bot_language}' and key '{key}'")
|
||||
# Fallback to English if the translation is not available
|
||||
if key in translations['en']:
|
||||
return translations['en'][key]
|
||||
@@ -69,19 +69,19 @@ class ChatGPTTelegramBot:
|
||||
"""
|
||||
self.config = config
|
||||
self.openai = openai
|
||||
language = self.config['language']
|
||||
bot_language = self.config['bot_language']
|
||||
self.commands = [
|
||||
BotCommand(command='help', description=localized_text('help_description', language)),
|
||||
BotCommand(command='reset', description=localized_text('reset_description', language)),
|
||||
BotCommand(command='image', description=localized_text('image_description', language)),
|
||||
BotCommand(command='stats', description=localized_text('stats_description', language)),
|
||||
BotCommand(command='resend', description=localized_text('resend_description', language))
|
||||
BotCommand(command='help', description=localized_text('help_description', bot_language)),
|
||||
BotCommand(command='reset', description=localized_text('reset_description', bot_language)),
|
||||
BotCommand(command='image', description=localized_text('image_description', bot_language)),
|
||||
BotCommand(command='stats', description=localized_text('stats_description', bot_language)),
|
||||
BotCommand(command='resend', description=localized_text('resend_description', bot_language))
|
||||
]
|
||||
self.group_commands = [
|
||||
BotCommand(command='chat', description=localized_text('chat_description', language))
|
||||
BotCommand(command='chat', description=localized_text('chat_description', bot_language))
|
||||
] + self.commands
|
||||
self.disallowed_message = localized_text('disallowed', language)
|
||||
self.budget_limit_message = localized_text('budget_limit', language)
|
||||
self.disallowed_message = localized_text('disallowed', bot_language)
|
||||
self.budget_limit_message = localized_text('budget_limit', bot_language)
|
||||
self.usage = {}
|
||||
self.last_message = {}
|
||||
|
||||
@@ -91,15 +91,15 @@ class ChatGPTTelegramBot:
|
||||
"""
|
||||
commands = self.group_commands if self.is_group_chat(update) else self.commands
|
||||
commands_description = [f'/{command.command} - {command.description}' for command in commands]
|
||||
language = self.config['language']
|
||||
bot_language = self.config['bot_language']
|
||||
help_text = (
|
||||
localized_text('help_text', language)[0] +
|
||||
localized_text('help_text', bot_language)[0] +
|
||||
'\n\n' +
|
||||
'\n'.join(commands_description) +
|
||||
'\n\n' +
|
||||
localized_text('help_text', language)[1] +
|
||||
localized_text('help_text', bot_language)[1] +
|
||||
'\n\n' +
|
||||
localized_text('help_text', language)[2]
|
||||
localized_text('help_text', bot_language)[2]
|
||||
)
|
||||
await update.message.reply_text(help_text, disable_web_page_preview=True)
|
||||
|
||||
@@ -130,38 +130,38 @@ class ChatGPTTelegramBot:
|
||||
chat_id = update.effective_chat.id
|
||||
chat_messages, chat_token_length = self.openai.get_conversation_stats(chat_id)
|
||||
remaining_budget = self.get_remaining_budget(update)
|
||||
language = self.config['language']
|
||||
bot_language = self.config['bot_language']
|
||||
text_current_conversation = (
|
||||
f"*{localized_text('stats_conversation', language)[0]}*:\n"
|
||||
f"{chat_messages} {localized_text('stats_conversation', language)[1]}.\n"
|
||||
f"{chat_token_length} {localized_text('stats_conversation', language)[2]}.\n"
|
||||
f"*{localized_text('stats_conversation', bot_language)[0]}*:\n"
|
||||
f"{chat_messages} {localized_text('stats_conversation', bot_language)[1]}.\n"
|
||||
f"{chat_token_length} {localized_text('stats_conversation', bot_language)[2]}.\n"
|
||||
f"----------------------------\n"
|
||||
)
|
||||
text_today = (
|
||||
f"*{localized_text('usage_today', language)}*\n"
|
||||
f"{tokens_today} {localized_text('stats_tokens', language)}\n"
|
||||
f"{images_today} {localized_text('stats_images', language)}\n"
|
||||
f"{transcribe_minutes_today} {localized_text('stats_transcribe', language)[0]} "
|
||||
f"{transcribe_seconds_today} {localized_text('stats_transcribe', language)[1]}\n"
|
||||
f"{localized_text('stats_total', language)}{current_cost['cost_today']:.2f}\n"
|
||||
f"*{localized_text('usage_today', bot_language)}*\n"
|
||||
f"{tokens_today} {localized_text('stats_tokens', bot_language)}\n"
|
||||
f"{images_today} {localized_text('stats_images', bot_language)}\n"
|
||||
f"{transcribe_minutes_today} {localized_text('stats_transcribe', bot_language)[0]} "
|
||||
f"{transcribe_seconds_today} {localized_text('stats_transcribe', bot_language)[1]}\n"
|
||||
f"{localized_text('stats_total', bot_language)}{current_cost['cost_today']:.2f}\n"
|
||||
f"----------------------------\n"
|
||||
)
|
||||
text_month = (
|
||||
f"*{localized_text('usage_month', language)}*\n"
|
||||
f"{tokens_month} {localized_text('stats_tokens', language)}\n"
|
||||
f"{images_month} {localized_text('stats_images', language)}\n"
|
||||
f"{transcribe_minutes_month} {localized_text('stats_transcribe', language)[0]} "
|
||||
f"{transcribe_seconds_month} {localized_text('stats_transcribe', language)[1]}\n"
|
||||
f"{localized_text('stats_total', language)}{current_cost['cost_month']:.2f}"
|
||||
f"*{localized_text('usage_month', bot_language)}*\n"
|
||||
f"{tokens_month} {localized_text('stats_tokens', bot_language)}\n"
|
||||
f"{images_month} {localized_text('stats_images', bot_language)}\n"
|
||||
f"{transcribe_minutes_month} {localized_text('stats_transcribe', bot_language)[0]} "
|
||||
f"{transcribe_seconds_month} {localized_text('stats_transcribe', bot_language)[1]}\n"
|
||||
f"{localized_text('stats_total', bot_language)}{current_cost['cost_month']:.2f}"
|
||||
)
|
||||
# text_budget filled with conditional content
|
||||
text_budget = "\n\n"
|
||||
budget_period =self.config['budget_period']
|
||||
if remaining_budget < float('inf'):
|
||||
text_budget += f"{localized_text('stats_budget', language)} {localized_text(budget_period, language)}: ${remaining_budget:.2f}.\n"
|
||||
text_budget += f"{localized_text('stats_budget', bot_language)} {localized_text(budget_period, bot_language)}: ${remaining_budget:.2f}.\n"
|
||||
# add OpenAI account information for admin request
|
||||
if self.is_admin(update):
|
||||
text_budget += f"{localized_text('stats_openai', language)}{self.openai.get_billing_current_month():.2f}."
|
||||
text_budget += f"{localized_text('stats_openai', bot_language)}{self.openai.get_billing_current_month():.2f}."
|
||||
|
||||
usage_text = text_current_conversation + text_today + text_month + text_budget
|
||||
await update.message.reply_text(usage_text, parse_mode=constants.ParseMode.MARKDOWN)
|
||||
@@ -180,7 +180,7 @@ class ChatGPTTelegramBot:
|
||||
if chat_id not in self.last_message:
|
||||
logging.warning(f'User {update.message.from_user.name} (id: {update.message.from_user.id})'
|
||||
f' does not have anything to resend')
|
||||
await context.bot.send_message(chat_id=chat_id, text=localized_text('resend_failed', self.config['language']))
|
||||
await context.bot.send_message(chat_id=chat_id, text=localized_text('resend_failed', self.config['bot_language']))
|
||||
return
|
||||
|
||||
# Update message text, clear self.last_message and send the request to prompt
|
||||
@@ -207,7 +207,7 @@ class ChatGPTTelegramBot:
|
||||
chat_id = update.effective_chat.id
|
||||
reset_content = message_text(update.message)
|
||||
self.openai.reset_chat_history(chat_id=chat_id, content=reset_content)
|
||||
await context.bot.send_message(chat_id=chat_id, text=localized_text('reset_done', self.config['language']))
|
||||
await context.bot.send_message(chat_id=chat_id, text=localized_text('reset_done', self.config['bot_language']))
|
||||
|
||||
async def image(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""
|
||||
@@ -219,7 +219,7 @@ class ChatGPTTelegramBot:
|
||||
chat_id = update.effective_chat.id
|
||||
image_query = message_text(update.message)
|
||||
if image_query == '':
|
||||
await context.bot.send_message(chat_id=chat_id, text=localized_text('image_no_prompt', self.config['language']))
|
||||
await context.bot.send_message(chat_id=chat_id, text=localized_text('image_no_prompt', self.config['bot_language']))
|
||||
return
|
||||
|
||||
logging.info(f'New image generation request received from user {update.message.from_user.name} '
|
||||
@@ -245,7 +245,7 @@ class ChatGPTTelegramBot:
|
||||
await context.bot.send_message(
|
||||
chat_id=chat_id,
|
||||
reply_to_message_id=self.get_reply_to_message_id(update),
|
||||
text=f"{localized_text('image_no_prompt', self.config['language'])}: {str(e)}",
|
||||
text=f"{localized_text('image_no_prompt', self.config['bot_language'])}: {str(e)}",
|
||||
parse_mode=constants.ParseMode.MARKDOWN
|
||||
)
|
||||
|
||||
@@ -267,7 +267,7 @@ class ChatGPTTelegramBot:
|
||||
|
||||
async def _execute():
|
||||
filename_mp3 = f'{filename}.mp3'
|
||||
language = self.config['language']
|
||||
bot_language = self.config['bot_language']
|
||||
try:
|
||||
media_file = await context.bot.get_file(update.message.effective_attachment.file_id)
|
||||
await media_file.download_to_drive(filename)
|
||||
@@ -276,7 +276,7 @@ class ChatGPTTelegramBot:
|
||||
await context.bot.send_message(
|
||||
chat_id=chat_id,
|
||||
reply_to_message_id=self.get_reply_to_message_id(update),
|
||||
text=f"{localized_text('media_download_fail', language)[0]}: {str(e)}. {localized_text('media_download_fail', language)[1]}",
|
||||
text=f"{localized_text('media_download_fail', bot_language)[0]}: {str(e)}. {localized_text('media_download_fail', bot_language)[1]}",
|
||||
parse_mode=constants.ParseMode.MARKDOWN
|
||||
)
|
||||
return
|
||||
@@ -293,7 +293,7 @@ class ChatGPTTelegramBot:
|
||||
await context.bot.send_message(
|
||||
chat_id=update.effective_chat.id,
|
||||
reply_to_message_id=self.get_reply_to_message_id(update),
|
||||
text=localized_text('media_type_fail', language)
|
||||
text=localized_text('media_type_fail', bot_language)
|
||||
)
|
||||
if os.path.exists(filename):
|
||||
os.remove(filename)
|
||||
@@ -321,7 +321,7 @@ class ChatGPTTelegramBot:
|
||||
if self.config['voice_reply_transcript']:
|
||||
|
||||
# Split into chunks of 4096 characters (Telegram's message limit)
|
||||
transcript_output = f"_{localized_text('transcript', language)}:_\n\"{transcript}\""
|
||||
transcript_output = f"_{localized_text('transcript', bot_language)}:_\n\"{transcript}\""
|
||||
chunks = self.split_into_chunks(transcript_output)
|
||||
|
||||
for index, transcript_chunk in enumerate(chunks):
|
||||
@@ -342,7 +342,7 @@ class ChatGPTTelegramBot:
|
||||
self.usage["guests"].add_chat_tokens(total_tokens, self.config['token_price'])
|
||||
|
||||
# Split into chunks of 4096 characters (Telegram's message limit)
|
||||
transcript_output = f"_{localized_text('transcript', language)}:_\n\"{transcript}\"\n\n_{localized_text('answer', language)}:_\n{response}"
|
||||
transcript_output = f"_{localized_text('transcript', bot_language)}:_\n\"{transcript}\"\n\n_{localized_text('answer', bot_language)}:_\n{response}"
|
||||
chunks = self.split_into_chunks(transcript_output)
|
||||
|
||||
for index, transcript_chunk in enumerate(chunks):
|
||||
@@ -358,7 +358,7 @@ class ChatGPTTelegramBot:
|
||||
await context.bot.send_message(
|
||||
chat_id=chat_id,
|
||||
reply_to_message_id=self.get_reply_to_message_id(update),
|
||||
text=f"{localized_text('transcribe_fail', language)}: {str(e)}",
|
||||
text=f"{localized_text('transcribe_fail', bot_language)}: {str(e)}",
|
||||
parse_mode=constants.ParseMode.MARKDOWN
|
||||
)
|
||||
finally:
|
||||
@@ -519,7 +519,7 @@ class ChatGPTTelegramBot:
|
||||
await context.bot.send_message(
|
||||
chat_id=chat_id,
|
||||
reply_to_message_id=self.get_reply_to_message_id(update),
|
||||
text=f"{localized_text('chat_fail', self.config['language'])} {str(e)}",
|
||||
text=f"{localized_text('chat_fail', self.config['bot_language'])} {str(e)}",
|
||||
parse_mode=constants.ParseMode.MARKDOWN
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user