Here is the improved code for your Telegram bot with the requested logging functionality and separation of the configuration file. The code has been designed to be template-like so that it can be shared on GitHub.
First, create a config.py file where you will store your bot token, admin ID, and logging level.
config.py
# config.py
# Replace 'YOUR_BOT_TOKEN' with your actual bot token
BOT_TOKEN = 'YOUR_BOT_TOKEN'
# Replace 'ADMIN_TELEGRAM_ID' with your Telegram ID
ADMIN_ID = 'ADMIN_TELEGRAM_ID'
# Set the logging level:
# 0 - No logging
# 1 - Log only start and end messages (with user ID and username)
# 2 - Log every user response (with user ID and username)
LOGGING_LEVEL = 1
Next, update your main bot script to include the new logging functionality.
bot.py
import telebot
import json
import os
from config import BOT_TOKEN, ADMIN_ID, LOGGING_LEVEL
bot = telebot.TeleBot(BOT_TOKEN)
user_states = {}
GAME_DATA_FILE = 'texts.json'
if os.path.exists(GAME_DATA_FILE):
with open(GAME_DATA_FILE, 'r', encoding='utf-8') as f:
game_data = json.load(f)
else:
print(f"Error: '{GAME_DATA_FILE}' not found.")
exit(1)
def log_message(message_type, user_id, username, content=''):
if LOGGING_LEVEL == 0:
return
if LOGGING_LEVEL == 1 and message_type not in ['start', 'end']:
return
log_text = f"{message_type.upper()} - User ID: {user_id}, Username: {username}"
if content:
log_text += f", Content: {content}"
bot.send_message(ADMIN_ID, log_text)
# Start command handler
@bot.message_handler(commands=['start'])
def start_message(message):
user_states[message.chat.id] = 'start'
send_message_with_buttons(message.chat.id, 'start')
log_message('start', message.chat.id, message.from_user.username)
# Message handler for button clicks and text inputs
@bot.message_handler(func=lambda message: True)
def handle_message(message):
chat_id = message.chat.id
state = user_states.get(chat_id, 'start')
user_input = message.text.strip()
log_message('input', chat_id, message.from_user.username, user_input)
if state in game_data and user_input in game_data[state]['buttons']:
next_state = game_data[state]['buttons'][user_input]
user_states[chat_id] = next_state
send_message_with_buttons(chat_id, next_state)
else:
bot.send_message(chat_id, "I don't understand that choice. Please select one of the available options.")
# Function to send messages with keyboard buttons
def send_message_with_buttons(chat_id, state):
if state in game_data:
text = game_data[state]['text']
buttons = game_data[state].get('buttons', None)
if buttons:
keyboard = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)
for button_text in buttons:
keyboard.add(telebot.types.KeyboardButton(button_text))
bot.send_message(chat_id, text, reply_markup=keyboard)
else:
# If no buttons, remove the keyboard
bot.send_message(chat_id, text, reply_markup=telebot.types.ReplyKeyboardRemove())
else:
bot.send_message(chat_id, "Oops, something went wrong...", reply_markup=telebot.types.ReplyKeyboardRemove())
# Restart command handler
@bot.message_handler(commands=['restart'])
def restart_game_command(message):
user_states[message.chat.id] = 'start'
send_message_with_buttons(message.chat.id, 'start')
log_message('restart', message.chat.id, message.from_user.username)
# Back command handler
@bot.message_handler(commands=['back'])
def go_back(message):
chat_id = message.chat.id
state_history = get_user_state_history(chat_id)
if len(state_history) > 1:
# Remove the last state to go back
state_history.pop()
# Update the user's current state
user_states[chat_id] = state_history[-1]
send_message_with_buttons(chat_id, state_history[-1])
else:
bot.send_message(chat_id, "You're already at the beginning of the game!")
# Function to get the user's state history
def get_user_state_history(chat_id):
if chat_id not in user_states:
user_states[chat_id] = 'start'
# For simplicity, we're using a list to track state history per user
# In a production environment, consider a more robust method or database
if '_history' not in user_states:
user_states['_history'] = {}
if chat_id not in user_states['_history']:
user_states['_history'][chat_id] = ['start']
return user_states['_history'][chat_id]
# Overriding send_message_with_buttons to update state history
def send_message_with_buttons(chat_id, state):
if state in game_data:
# Update user's state history
state_history = get_user_state_history(chat_id)
state_history.append(state)
user_states['_history'][chat_id] = state_history
text = game_data[state]['text']
buttons = game_data[state].get('buttons', None)
if buttons:
keyboard = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)
for button_text in buttons:
keyboard.add(telebot.types.KeyboardButton(button_text))
bot.send_message(chat_id, text, reply_markup=keyboard)
else:
# If no buttons, remove the keyboard
bot.send_message(chat_id, text, reply_markup=telebot.types.ReplyKeyboardRemove())
else:
bot.send_message(chat_id, "Oops, something went wrong...", reply_markup=telebot.types.ReplyKeyboardRemove())
bot.set_my_commands([
telebot.types.BotCommand('start', 'Start the game'),
telebot.types.BotCommand('restart', 'Restart the game'),
telebot.types.BotCommand('back', 'Go back one step')
])
# Handler for stopping the bot gracefully (e.g., /stop command)
@bot.message_handler(commands=['stop'])
def stop_bot(message):
log_message('end', message.chat.id, message.from_user.username)
bot.send_message(message.chat.id, "Thank you for playing! Goodbye.")
# Perform any cleanup here if necessary
bot.polling()
Explanation
-
Logging Functionality: A new function log_message() has been added to handle logging based on the LOGGING_LEVEL set in config.py.
- LOGGING_LEVEL 0: No logging.
- LOGGING_LEVEL 1: Logs only start (
/start command) and end (/stop command) messages with user ID and username.
- LOGGING_LEVEL 2: Logs every user input with user ID, username, and the content of the message.
-
Configuration File: The config.py file is used to store sensitive information like the bot token and the admin ID. This file should not be shared publicly.
-
Admin Notifications: The bot sends the logs as messages to the admin (specified by ADMIN_ID).
-
Commands: The bot now includes a /stop command to log when a user ends the interaction.
Instructions for Setting Up
-
Clone or Download the Repository: Get the code onto your local machine.
-
Install Dependencies: Ensure you have the pyTelegramBotAPI library installed.
pip install pyTelegramBotAPI
-
Create config.py: Create a new file named config.py in the same directory as your bot script, and add your bot token and admin ID.
# config.py
BOT_TOKEN = 'YOUR_BOT_TOKEN_HERE'
ADMIN_ID = 'YOUR_TELEGRAM_ID_HERE'
LOGGING_LEVEL = 1 # Set the desired logging level
-
Get Your Bot Token: Obtain the bot token from @BotFather on Telegram.
-
Find Your Admin Telegram ID: To find your own Telegram ID, you can send a message to @userinfobot or @GetIDsBot, and it will reply with your user ID.
-
Prepare the texts.json File: Create a texts.json file that contains your game data structured appropriately.
Example texts.json:
{
"start": {
"text": "Welcome to the quest! Choose an option:",
"buttons": {
"Option 1": "state1",
"Option 2": "state2"
}
},
"state1": {
"text": "You chose Option 1. Now, select next:",
"buttons": {
"Next": "state_end"
}
},
"state2": {
"text": "You chose Option 2. Now, select next:",
"buttons": {
"Next": "state_end"
}
},
"state_end": {
"text": "This is the end of the quest. Thank you for playing!",
"buttons": {}
}
}
-
Run the Bot: Start the bot by running the bot.py script.
python bot.py
README Instructions
Make sure to include the above instructions in your README.md file when you upload the code to GitHub. Also, remind users not to commit their config.py file to the repository to avoid exposing sensitive information.
Note: The provided code is a template and should be adjusted according to your specific requirements. Ensure that you handle exceptions and errors appropriately for a production environment.