skip to Main Content

So, I created a minigame bot on telegram. The bot just contains a fishing game, and it’s already running. I want if a user fishes and gets a fish, the fish will be stored in a database. So the user can see what he got while fishing. Does this is require SQL?

I haven’t tried anything, because I don’t understand about storing data in python. If there is a tutorial related to this, please share it in the comments. Thank you

2

Answers


  1. Using a txt file as database is a terrible idea, go with SQL

    Login or Signup to reply.
  2. You can use anything to store user data, including text files.

    The simplest approaches to storing data can be serializing a dictionary to JSON with the builtin json module:

    DATABASE = 'database.json'  # (name or extension don't actually matter)
    
    import json
    
    # loading
    with open(DATABASE, 'r', encoding='utf-8') as fd:
        user_data = json.load(fd)
    
    user_data[1234] = 5  # pretend user 1234 scored 5 points
    
    # saving
    with open(DATABASE, 'w', encoding='utf-8') as fd:
        json.dump(user_data, fd)
    

    This would only support simple data-types. If you need to store custom classes, as long as you don’t upgrade your Python version, you can use the built-in pickle module:

    DATABASE = 'database.pickle'  # (name or extension don't actually matter)
    
    import pickle
    
    # loading
    with open(DATABASE, 'rb') as fd:
        user_data = pickle.load(fd)
    
    user_data[1234] = 5  # pretend user 1234 scored 5 points
    
    # saving
    with open(DATABASE, 'wb') as fd:
        pickle.dump(user_data, fd)
    

    Whether this is a good idea or not depends on how many users you expect your bot to have. If it’s even a hundred, these approaches will work just fine. If it’s in the thousands, perhaps you could use separate files per user, and still be okay. If it’s more than that, then yes, using any database, including the built-in sqlite3 module, would be a better idea. There are many modules for different database engines, but using SQLite is often enough (and there are also libraries that make using SQLite easier).

    Telethon itself uses the sqlite3 module to store the authorization key, and a cache for users it has seen. It’s not recommended to reuse that same file for your own needs though. It’s better to create your own database file if you choose to use sqlite3.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search