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.1 KiB

A bot in the shell (with timer)

In [2]:
import time

def get_reply(message):
    if "hello" in message:
        reply = "oh hello!"
    else:
        reply = None

    return reply
    
while True:
    
    # --- start timer ---
    starttime = time.time()
    # -------------------
    
    message = input(">>>")
    if message == "exit":
        break
    
    reply = get_reply(message)
    
    if reply: 
        print("<<<", reply)
        # --- check timer ---
        timer = round((time.time() - starttime), 2)
        print(f"It took you { timer } seconds to respond.")
        # -------------------
    else:
        print("<<<", "What did you say?")
<<< oh hello!
It took you 3.66 seconds to respond.
<<< oh hello!
It took you 3.04 seconds to respond.
<<< What did you say?
<<< What did you say?
<<< oh hello!
It took you 1.13 seconds to respond.
<<< oh hello!
It took you 1.5 seconds to respond.
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-2-3b07a8a8f0dd> in <module>
     15     # -------------------
     16 
---> 17     message = input(">>>")
     18     if message == "exit":
     19         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 [ ]: