Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

write a readme for github. code: import telebot import json import os from config import…

  1. User

    write a readme for github.

    code: 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()

    draft: Telegram Text Adventure Game Bot Python Telegram Bot API License

    A simple Telegram bot that demonstrates a text-based adventure game. Players make choices by clicking on buttons, leading them through different story paths.

    Features Interactive demo game with multiple steps Simple text-based storytelling Users can restart the game at any time Ability to go back one step in the story Easily customizable story through a JSON file Setup and Installation Prerequisites Python 3.6 or higher A Telegram account A Telegram bot token from BotFather Installation Steps Clone the Repository

    git clone https://github.com/yourusername/telegram-text-adventure-bot.git cd telegram-text-adventure-bot Create a Virtual Environment It's recommended to use a virtual environment to manage dependencies:

    python3 -m venv venv source venv/bin/activate # On Windows use venv\Scripts\activate Install Dependencies Install the required packages using pip:

    pip install -r requirements.txt Configure the Bot Replace 'YOUR_BOT_TOKEN' in bot.py with your actual bot token:

    BOT_TOKEN = 'YOUR_ACTUAL_BOT_TOKEN' Run the Bot Start the bot by running:

    python bot.py Interact with the Bot Open Telegram, find your bot by its username, and start a conversation. Use /start to begin the game. Usage /start - Begin the game /restart - Restart the game from the beginning /back - Go back one step in the story Customization Editing the Story The game story is stored in game_data.json. You can modify this file to create your own story. The structure is as follows:

    "state_name": { "text": "The text shown to the user at this state.", "buttons": { "Button Label": "next_state_name" } } state_name: A unique identifier for each state in the game. text: The narrative text displayed to the player at this state. buttons: A dictionary of buttons and the states they lead to. Adding New States To add new parts to the story:

    Define a new state in game_data.json with its text and buttons. Reference the new state in the buttons of an existing state. Multi-language Support To support multiple languages:

    Create separate JSON files for each language (e.g., game_data_en.json, game_data_es.json). Load the appropriate file based on user preference or locale. Additional Improvements Here are some ideas for enhancing the bot:

    State Persistence: Save user states to a database to maintain history even if the bot restarts. Inline Keyboards: Use inline keyboards for a more polished user interface. Dynamic Content: Allow users to input text, making the game more interactive. Error Logging: Implement logging to track errors and user interactions. Unit Testing: Add tests to ensure the bot functions correctly.

  2. Assistant
    # Telegram Text Adventure Game Bot
    
    A simple Telegram bot that offers a text-based adventure game experience. Players make choices by clicking on buttons, navigating through different story paths. Easily customizable and extensible to create your own unique adventures.
    
    ## Table of Contents
    
    - [Features](#features)
    - [Prerequisites](#prerequisites)
    - [Installation](#installation)
    - [Configuration](#configuration)
    - [Running the Bot](#running-the-bot)
    - [Usage](#usage)
    - [Customization](#customization)
    - [Ideas for Improvement](#ideas-for-improvement)
    - [Contributing](#contributing)
    - [License](#license)
    
    ## Features
    
    - **Interactive Storytelling**: Navigate through the adventure by making choices via Telegram buttons.
    - **Customizable Storyline**: Easily modify the story through a JSON file.
    - **User-Friendly Commands**:
      - `/start` - Begin the game
      - `/restart` - Restart the game from the beginning
      - `/back` - Go back one step in the story
    - **State Management**: Keeps track of user progress, allowing players to restart or backtrack.
    - **Logging**: Logs user interactions for monitoring and debugging.
    - **Extensible**: Designed to be easily expanded with additional features like multi-language support or dynamic content.
    
    ## Prerequisites
    
    - **Python**: Version 3.6 or higher
    - **Telegram Account**: To interact with the bot
    - **Telegram Bot Token**: Obtainable from [BotFather](https://t.me/BotFather)
    
    ## Installation
    
    ### 1. Clone the Repository
    
    ```bash
    git clone https://github.com/yourusername/telegram-text-adventure-bot.git
    cd telegram-text-adventure-bot
    

    2. Create a Virtual Environment

    It's recommended to use a virtual environment to manage dependencies:

    python3 -m venv venv
    source venv/bin/activate  # On Windows use `venv\Scripts\activate`
    

    3. Install Dependencies

    Install the required Python packages using pip:

    pip install -r requirements.txt
    

    Configuration

    1. Create a config.py File

    Create a config.py file in the project root directory with the following content:

    BOT_TOKEN = 'YOUR_ACTUAL_BOT_TOKEN'
    ADMIN_ID = YOUR_TELEGRAM_USER_ID
    LOGGING_LEVEL = 1  # 0: No logging, 1: Minimal logging, 2: Detailed logging
    
    • BOT_TOKEN: Replace 'YOUR_ACTUAL_BOT_TOKEN' with the token you received from BotFather.
    • ADMIN_ID: Replace YOUR_TELEGRAM_USER_ID with your Telegram user ID to receive logs. You can find your user ID by messaging @userinfobot on Telegram.
    • LOGGING_LEVEL:
      • 0: No logging.
      • 1: Minimal logging (e.g., start and end commands).
      • 2: Detailed logging (all user inputs).

    2. Prepare the Story Data

    Ensure that the texts.json file is present in the project directory. This file contains the game's storyline and choices. An example structure:

    {
      "start": {
        "text": "Welcome to the adventure! Do you go left or right?",
        "buttons": {
          "Left": "left_path",
          "Right": "right_path"
        }
      },
      "left_path": {
        "text": "You took the left path and encountered a river. Do you swim across or build a raft?",
        "buttons": {
          "Swim": "swim_river",
          "Build": "build_raft"
        }
      },
      "right_path": {
        "text": "You took the right path and found a treasure chest. Do you open it or leave it?",
        "buttons": {
          "Open": "open_chest",
          "Leave": "leave_chest"
        }
      }
      // Add more states as needed
    }
    

    Running the Bot

    Start the bot by running the following command:

    python bot.py
    

    The bot will begin polling for messages. Ensure that the texts.json and config.py files are correctly set up before running.

    Usage

    Interact with your bot on Telegram using the following commands:

    • /start - Begin the game
    • /restart - Restart the game from the beginning
    • /back - Go back one step in the story
    • /stop - (Optional) Gracefully stop the bot (requires implementation)

    Example Interaction:

    1. User: /start
    2. Bot: "Welcome to the adventure! Do you go left or right?" with "Left" and "Right" buttons.
    3. User: Clicks "Left"
    4. Bot: "You took the left path and encountered a river. Do you swim across or build a raft?" with "Swim" and "Build" buttons.
    5. And so on...

    Customization

    Editing the Story

    The game's story is stored in texts.json. You can modify this file to create your own narrative. The structure for each state is as follows:

    "state_name": {
      "text": "The narrative text displayed to the player at this state.",
      "buttons": {
        "Button Label": "next_state_name"
      }
    }
    
    • state_name: A unique identifier for each state in the game.
    • text: The message displayed to the player.
    • buttons: A dictionary where each key is the label of a button, and the value is the state_name it leads to.

    Adding New States

    1. Define a New State: Add a new entry in texts.json.

      "new_state": {
        "text": "Your new story segment here.",
        "buttons": {
          "Choice 1": "next_state_1",
          "Choice 2": "next_state_2"
        }
      }
      
    2. Reference the New State: In an existing state, add a button that points to the new state.

      "existing_state": {
        "text": "Existing story text.",
        "buttons": {
          "New Choice": "new_state",
          // Other choices
        }
      }
      

    Multi-language Support

    To support multiple languages:

    1. Create Separate JSON Files: For each language, create a separate JSON file (e.g., texts_en.json, texts_es.json).

    2. Load Based on User Preference: Modify the bot to detect or allow users to select their preferred language and load the corresponding JSON file.

    Enhancements

    Consider implementing the following features to improve the bot:

    • State Persistence: Use a database to save user states, ensuring continuity even if the bot restarts.
    • Inline Keyboards: Replace reply keyboards with inline keyboards for a more polished user interface.
    • Dynamic Content: Allow users to input text to make the game more interactive and personalized.
    • Advanced Logging: Implement comprehensive logging to monitor errors and user interactions effectively.
    • Unit Testing: Add tests to ensure all functionalities work as expected.

    Ideas for Improvement

    • Deploy to Cloud Platforms: Host the bot on platforms like Heroku, AWS, or Google Cloud for better accessibility.
    • User Profiles: Maintain user profiles to track progress, preferences, or achievements.
    • Rich Media Integration: Incorporate images, videos, or audio to enhance storytelling.
    • Branching Narratives: Develop more complex storylines with multiple branching paths and endings.

    Contributing

    Contributions are welcome! Follow these steps to contribute:

    1. Fork the Repository

    2. Create a Feature Branch

      git checkout -b feature/YourFeatureName
      
    3. Commit Your Changes

      git commit -m "Add your message"
      
    4. Push to the Branch

      git push origin feature/YourFeatureName
      
    5. Open a Pull Request

    Ensure that your contributions adhere to the project's coding standards and include appropriate documentation.

    License

    This project is licensed under the MIT License.


    Enjoy your adventure! If you encounter any issues or have suggestions, feel free to open an issue or submit a pull request.

    
    ---
    
    **Notes:**
    
    1. **Consistency in File Names**: Ensure that the JSON file mentioned in the code (`texts.json`) matches the name used in the README.
    
    2. **Requirements File**: Create a `requirements.txt` with the necessary dependencies. Based on the code, at least `pyTelegramBotAPI` is required. Example:
    
        ```text
        pyTelegramBotAPI==4.12.0
        ```
    
    3. **Bot Commands**: The README lists `/stop` as an optional command. If implemented, include details; otherwise, remove it from the Usage section.
    
    4. **State History Handling**: The provided code has an inconsistency with `user_states` handling state history. Consider reviewing and testing the `get_user_state_history` and `send_message_with_buttons` functions to ensure they work as intended.
    
    5. **Error Handling**: Ensure that the bot gracefully handles errors, such as missing states or JSON parsing issues.
    
    6. **Security**: Never commit `config.py` with actual credentials to the repository. Consider adding it to `.gitignore` and provide a `config.example.py` as a template.
    
    7. **Testing**: Before deploying, thoroughly test all commands and story paths to ensure a smooth user experience.