It looks like you're working on a Telegram bot that handles key generation and management. I'll help you review the code you've provided and point out potential issues and improvements.
Observations and Suggestions:
-
Undefined Variables and Functions:
-
confirm_message and markup:
- In your code snippet,
confirm_message and markup are used but not defined within the shown code. Ensure that confirm_message is properly assigned the message string you intend to send, and markup is defined with the appropriate keyboard markup before they're used.
confirm_message = f"Validity period: {validity_days} days\n\nDo you want to proceed?"
markup = telebot.types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
markup.add('Yes', 'No')
-
load_keys() and load_users():
- These functions are called in the
list_keys_command function but are not defined in the provided snippet. Make sure these functions are implemented to load data from your storage (e.g., JSON files).
def load_keys():
try:
with open('keys.json', 'r') as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return {}
def load_users():
try:
with open('users.json', 'r') as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return {}
-
Inconsistent Command Names:
-
In your response messages, you refer to the /listkeys command:
response += f"\n\n💡 Use /listkeys to view all keys and their status"
-
However, your command handler listens for /list:
@bot.message_handler(commands=['list'])
def list_keys_command(message):
-
Solution: Decide on a consistent command name and update both the handler and the messages accordingly. For example, if you choose /listkeys, update the command handler:
@bot.message_handler(commands=['listkeys'])
def list_keys_command(message):
-
Handling User Authentication:
-
You're checking if the user's username is anetjaka to restrict access:
if message.from_user.username != 'anetjaka':
bot.reply_to(message, "⛔ This command is restricted to admin use only.")
return
-
Issue: If a user doesn't have a Telegram username set, message.from_user.username might be None, leading to potential errors.
-
Solution: Use the user's Telegram ID instead, which is always present:
ADMIN_USER_ID = 123456789 # Replace with your actual Telegram user ID
if message.from_user.id != ADMIN_USER_ID:
bot.reply_to(message, "⛔ This command is restricted to admin use only.")
return
-
Date and Time Handling:
-
When parsing dates, ensure consistency and consider timezones:
expiry_date = datetime.fromisoformat(info['expires_at'])
is_expired = datetime.now() > expiry_date
-
Issue: This comparison might not be accurate if expires_at and datetime.now() are in different timezones.
-
Solution: Use timezone-aware datetime objects. Consider using the pytz library or Python's built-in timezone support (Python 3.6+).
from datetime import datetime, timezone
expiry_date = datetime.fromisoformat(info['expires_at']).astimezone(timezone.utc)
now = datetime.now(timezone.utc)
is_expired = now > expiry_date
-
Error Handling Improvements:
-
In confirm_generation, you have a broad exception handler:
except Exception as e:
bot.reply_to(message, f"An error occurred: {str(e)}",
reply_markup=telebot.types.ReplyKeyboardRemove())
-
Suggestion: Handle specific exceptions where possible to provide more precise feedback.
-
Clearing User Data:
-
After completing the operation, you delete the user's data:
del user_data[user_id]
-
Suggestion: Ensure this doesn't interfere with other operations that might be using user_data. If user_data is only used for this flow, then this is appropriate.
-
Response Formatting:
-
Enhance readability by formatting dates and separating entries clearly.
-
Example:
response += f"Key: `{key}`\n"
response += f"Status: {status}\n"
response += f"Expires: {expiry_date.strftime('%Y-%m-%d %H:%M:%S %Z')}\n"
response += f"Redeemed: {'Yes' if is_redeemed else 'No'}\n"
if is_redeemed and redeemed_by in users:
user_info = users[redeemed_by]
response += f"Redeemed By: {user_info.get('name', redeemed_by)}\n"
response += "\n" # Add a line break between entries
Remember to set parse_mode='Markdown' or parse_mode='MarkdownV2' in your bot.reply_to call to render Markdown formatting.
-
Completing the Function Definitions:
Ensure all functions are properly defined and indented. For example, make sure the confirm_generation function is aligned correctly in your code.
Revised Code Snippet:
Here's how you might revise the confirm_generation function:
def confirm_generation(message):
if message.text.lower() not in ['yes', 'no']:
bot.reply_to(message, "Please select Yes or No. Use /genkeys to start over.",
reply_markup=telebot.types.ReplyKeyboardRemove())
return
if message.text.lower() == 'no':
bot.reply_to(message, "Operation cancelled.",
reply_markup=telebot.types.ReplyKeyboardRemove())
return
user_id = message.from_user.id
if user_id not in user_data:
bot.reply_to(message, "Session expired. Please use /genkeys to start over.",
reply_markup=telebot.types.ReplyKeyboardRemove())
return
try:
num_keys = user_data[user_id]['num_keys']
validity_days = user_data[user_id]['validity_days']
new_keys = generate_keys(num_keys, validity_days)
existing_keys = load_keys() # Using the load_keys function
existing_keys.update(new_keys)
with open('keys.json', 'w') as f:
json.dump(existing_keys, f, indent=4)
response = f"✅ Successfully generated {num_keys} keys!\n\n"
response += f"🔑 Generated Keys:\n\n"
for key in new_keys.keys():
response += f"{key}\n"
response += f"\n⏳ Validity: {validity_days} days"
response += f"\n📁 Keys saved to keys.json"
response += f"\n\n💡 Use /listkeys to view all keys and their status"
del user_data[user_id]
bot.reply_to(message, response,
reply_markup=telebot.types.ReplyKeyboardRemove())
except Exception as e:
bot.reply_to(message, f"An error occurred during key generation. Please try again.",
reply_markup=telebot.types.ReplyKeyboardRemove())
# Optionally log the exception
print(f"Error in confirm_generation: {e}")
And update the command handler:
@bot.message_handler(commands=['listkeys'])
def list_keys_command(message):
ADMIN_USER_ID = 123456789 # Replace with your Telegram user ID
if message.from_user.id != ADMIN_USER_ID:
bot.reply_to(message, "⛔ This command is restricted to admin use only.")
return
keys = load_keys()
users = load_users()
if not keys:
bot.reply_to(message, "No keys found in the database.")
return
response = "🔑 *Keys Status:*\n\n"
for key, info in keys.items():
expiry_date = datetime.fromisoformat(info['expires_at']).astimezone(timezone.utc)
is_expired = datetime.now(timezone.utc) > expiry_date
is_redeemed = info.get('redeemed', False)
redeemed_by = info.get('redeemed_by', 'None')
status = "🔴 Expired" if is_expired else "🟢 Active"
if is_redeemed:
status += " (Redeemed)"
response += f"*Key:* `{key}`\n"
response += f"*Status:* {status}\n"
response += f"*Expires:* {expiry_date.strftime('%Y-%m-%d %H:%M:%S %Z')}\n"
response += f"*Redeemed:* {'Yes' if is_redeemed else 'No'}\n"
if is_redeemed and redeemed_by in users:
user_info = users[redeemed_by]
response += f"*Redeemed By:* {user_info.get('name', redeemed_by)}\n"
response += "\n"
bot.reply_to(message, response, parse_mode='Markdown')
Additional Tips:
-
Logging: Consider adding logging to your bot to track errors and user actions. This can help with debugging and monitoring.
-
User Sessions: If you have multiple user interactions, consider using a more robust session management system, possibly with a database.
-
Security: Be cautious with sensitive data. If keys are sensitive, ensure they are not exposed to unauthorized users.
-
Testing: Thoroughly test each command and interaction flow to catch any issues.
Conclusion:
By addressing these points, your bot should function more smoothly, and you'll avoid common pitfalls. If you encounter specific errors or have more questions, feel free to ask!