You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

7.5 KiB

A bot in the shell (with memory)

This bot has one extra feature: it can save information to a database. The database is a JSON file.

In [17]:
import os
import json

# --- database functions ---
def write_db(this_db):
    with open(db_filename, 'w+') as f:
        f.write(json.dumps(this_db, indent=4, sort_keys=True))
            
def load_db():
    # Create the database when it does not exist yet
    if not os.path.exists(db_filename):
        new_db = {}
        write_db(new_db)
    with open(db_filename, 'r') as f:
        db = json.loads(f.read())
    
    return db

def read_db(key):
    if key in db:
        return db[key]
    else:
        return None

def update_db(key, value):
    db[key] = value
    write_db(db)
# -------------------------

def get_reply(message):
    if "hello" in message:
        reply = "oh hello!"
    # --- database example ---    
    if "count" in message:
        # First check if there is a counter already,
        # and if not, make one
        if read_db("count") == None:
            current_count = update_db("count", 0)
        current_count = read_db("count")            
        new_count = current_count + 1
        update_db("count", new_count)
        reply = new_count
    # ------------------------
    else:
        reply = None
        
    return reply

# --- database settings ---
db_filename = 'shell-bot.json'
db = load_db()
# -------------------------

while True:
    message = input(">>>")
    if message == "exit":
        break
    
    reply = get_reply(message)
    
    if reply: 
        print("<<<", reply)
    else:
        print("<<<", "What did you say?")
<<< 6
<<< What did you say?
<<< 7
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-17-72e501df7c33> in <module>
     50 
     51 while True:
---> 52     message = input(">>>")
     53     if message == "exit":
     54         break

~/.local/lib/python3.7/site-packages/ipykernel/kernelbase.py in raw_input(self, prompt)
    861             self._parent_ident,
    862             self._parent_header,
--> 863             password=False,
    864         )
    865 

~/.local/lib/python3.7/site-packages/ipykernel/kernelbase.py in _input_request(self, prompt, ident, parent, password)
    902             except KeyboardInterrupt:
    903                 # re-raise KeyboardInterrupt, to truncate traceback
--> 904                 raise KeyboardInterrupt("Interrupted by user") from None
    905             except Exception as e:
    906                 self.log.warning("Invalid Message:", exc_info=True)

KeyboardInterrupt: Interrupted by user

Run the bot from a terminal

You can also save this code as a .py script, and run it from the terminal.

  1. Make a new file and save it as a .py script
  2. Open a new terminal
  3. Navigate to the folder where you saved your .py script
  4. Run your bot: $ python3 YOURFILENAME.py
In [ ]: