Moving everything to a Class

The code for this blog is version 0.3 on github

Now that i got a mostly function bot that can read from a channel and write to a channel, having random function in a script is not going to scale well it time to move this all in to a class.

The class is going to be pretty simple, all the function we had in the script will become function of the class, with just 2 new function an init function and a run function

The init function set up all the thing we need set up at run time. A connection to the database, and the connection to the slack client

class KarmaBot(object):
    def __init__(self):
        engine = create_engine('sqlite:///db.db')
        Base.metadata.bind = engine
        DBSession = sessionmaker(bind=engine)
        self.session = DBSession()

        logging.basicConfig()
        self.mychannel = 'newtest'
        self.slack_client = slack.WebClient(token=token)

The run function is our bot loop it going to do 3 things

  1. get the channel id from slack
  2. Find what the last timestamp in our database is
  3. Find out if there is any new karam to add or remove from the user
    def run(self):
        id = self.get_channel_id()
        if not id:
            sys.exit(1)
        while True:
            # Get the latest time stamp from the database so we don't run on the same message
            ts = self.get_latest_ts_from_db()
            if ts:
                print(ts.timestamp.timestamp())
            # record the latest message to the database and show the history
            history = self.add_new_ts_to_db(id, ts)
            # If there is a message we want to parse it to see if they want to add or remove karma
            if history['messages']:
                for message in history['messages']:
                    self.parse_karma(message)
            time.sleep(2)

Leave a comment

Blog at WordPress.com.

Up ↑