Close

New Website Database Code for Twitch Buttons

A project log for ATLTVHEAD

Atltvhead is a mashup of interactive art and wearable technology with a message of positivity and encouragement to let your oddities shine!

atltvheadatltvhead 03/31/2020 at 12:580 Comments

Wix stopped allowing me to  add random users to my email crm contact list. A bug, but one that seems to persist even if "fixed" on there end. So it was back to the drawing board.


Wix, does allow a database to be maintained and for the user to build an api to access different elements of one's site. So I set up my buttons to input into the database, based on mouse clicking see code:

import wixData from 'wix-data';

$w.onReady(function () {
	//TODO: write your page related code here...

});

export function B4_rainbow(event, $w) {
    //look at database and see the number of results in it. 
	wixData.query('interactions').find().then(result=>{
		let record = result.items[0]; //item with values

                // increment this by 1  
		record.b_4++; // the rainbow effect is attached to b_4 value in my database
		
                console.log(record.b_4); //let me know i've done something

                //save the new data back into the interactions database
		wixData.update('interactions', record).then((results) => {
			let item = results; //see item 
			console.log(results);
			} )
		.catch( (err) => {
			let errorMsg = err;
		} );
	});
}

Now to build the backend of my site, so I can access the values from an HTTP- request

import {ok, notFound, created, serverError} from 'wix-http-functions';
import wixData from 'wix-data';


// function to read my database, and return a json string of all the elements of my database in it. 
export function get_readInteractions(request) {
  let options = {
    "headers": {
      "Content-Type": "application/json"
    }
  };

  return wixData.query("interactions")
    .find()
    .then( (results) => {
      if(results.items.length > 0) {
        options.body = {
          "results" : results.items
		}
        return ok(options);
	  }
	})
}

 But I want a way to store my high fives I get out in person, back into my database. Luckily there is a way to do that as well! (please do not abuse this function, it only makes it seem that I've high fived people, anyway)

export function put_highfives(request) {
  wixData.query('interactions').find().then(result=>{
		let record = result.items[0]; //item with values
		record.highfives++; // increment this by 1
		console.log(record.highfives);
		wixData.update('interactions', record).then((results) => {
			let item = results; //see item 
			console.log(results);
			} )
		.catch( (err) => {
			let errorMsg = err;
		} );
	});

 I tried to do a put request at first but kept running into problems. I also don't necessarily know what my current high five count accurately. So I decided the best thing was to just alert my website that a high five has occurred and let it handle querying and incrementing the high five value. Later on I did find a way to put the high five information back into my glove and tvhead, through twitch, but another topic for another day.

With the website now modified, time to re-write the portion of my python script that read my website. Now more email crawling.

The http - request :

https://www.natedamen.com/_functions/readInteractions
def getData():
    try:
        rk = requests.get('https://www.natedamen.com/_functions/readInteractions')
    except Exception as err:
        print(traceback.format_exc())

    else:
        datak=rk.json()
        
    return datak

#gets all of the unread messages from the inbox
def dataCrawler():
    t=0
    mCheck = True
    datar=getData()
    oldR=datar

    while True:
        ot=time.time()
        diff = ot - t
    
        #I was getting a lot of errors and crashes, so I want to know what is failing. 
        #This section of code does that, and closes out this script. 
        try:
            datar=getData()
        except Exception as e:
            err=e.args[0]
            print('Data crawler down: '+ str(err))
            sys.exit(0)


        # if Data is different from older data, trigger a tvhead command to twitch.
        if datar['results'][0]['b_1'] > oldR['results'][0]['b_1']:
            chat(s,"<3")
            time.sleep(1 / RATE)
        if datar['results'][0]['b_2'] > oldR['results'][0]['b_2']:
            chat(s,"!sparkles")
            time.sleep(1 / RATE)
        if datar['results'][0]['b_3'] > oldR['results'][0]['b_3']:
            if mCheck == True:
                chat(s,"!mirrorDown")
                mCheck = False
            else:
                chat(s,"!mirrorRight")
                mCheck = True
            time.sleep(1 / RATE)
        if datar['results'][0]['b_4'] > oldR['results'][0]['b_4']:
            chat(s,"!rainbowHeart")
            time.sleep(1 / RATE)
        if datar['results'][0]['b_5'] > oldR['results'][0]['b_5']:
            chat(s,"!Mahearta")
            time.sleep(1 / RATE)
        if datar['results'][0]['b_6'] > oldR['results'][0]['b_6']:
            chat(s,"!heartCycle")
            time.sleep(1 / RATE)
        if datar['results'][0]['b_7'] > oldR['results'][0]['b_7']:
            chat(s,"!sGlitch")
            time.sleep(1 /RATE)
        if datar['results'][0]['b_8'] > oldR['results'][0]['b_8']:
            chat(s,"!noiseScreen")
            time.sleep(1 / RATE)
        if datar['results'][0]['b_9'] > oldR['results'][0]['b_9']:
            chat(s,"!jellyHeart")
            time.sleep(1 / RATE) 
        if datar['results'][0]['b_10'] > oldR['results'][0]['b_10']:
            chat(s,"!reset")
            time.sleep(1 / RATE)
            chat(s,"!mirrorOff")
            time.sleep(1 / RATE)
            chat(s,"<3")
            time.sleep(1 / RATE)
        if datar['results'][0]['b_11'] > oldR['results'][0]['b_11']:
            chat(s,"Selecting Atltvheads!")
            time.sleep(1 / RATE)
        if datar['results'][0]['dim'] > oldR['results'][0]['dim']:
            chat(s,"!dimmer")
            time.sleep(1 / RATE)
        if datar['results'][0]['bright'] > oldR['results'][0]['bright']:
            chat(s,"!brighter")
            time.sleep(1 / RATE)

        oldR=datar

 I want this python code to run non-stop. So I ended up using the multiprocessing library allowing for twitch communication to be run in it's own process, and this data gathering done in another process. but when one process goes down, it doesn't work. They both share variables, and functions. Needless to say, there are a lot of ins and outs and interested parties.

So after struggling to have debug both subscripts to eliminate all of the expectations and errors, for months, I conceded slightly.  I decided the best thing is just to see if the processes are running, if not, restart them. Put a bandaid over the problem.  If any exceptions that I didn't fix or didn't account for come up, just close the process and restart it. If the twitch process went down, I'd also need to restart the connection,

if __name__ == '__main__' :
    p =  multiprocessing.Process(target=pingPong)
    m =  multiprocessing.Process(target=dataCrawler)
    m.start()
    print('Started Email Scanning')
    p.start()
    print('ping pong started')

    while True:      
        if not p.is_alive():
            print('P is :')
            print(p.is_alive())
            while not CONNECTED:
                try:
                    s.connect((cfg.HOST,cfg.PORT))
                    print('reconnected to twitch')
                except socket.error:
                    print(traceback.format_exc())
                else:
                    s.send("PASS {}\r\n".format(cfg.PASS).encode("utf-8"))
                    s.send("NICK {}\r\n".format(cfg.NICK).encode("utf-8"))
                    s.send("JOIN {}\r\n".format(cfg.CHAN).encode("utf-8"))
                    CONNECTED = True
                finally:
                    #print('socket error')
                    time.sleep(2)
                
            print('P is :')
            print(p.is_alive())
            p.terminate()
            time.sleep(1)
            p =  multiprocessing.Process(target=pingPong)
            p.start()
            print('ping pong restart')
        elif not m.is_alive():
            print('M is :')
            print(m.is_alive())
            m.terminate()
            time.sleep(1)
            m =  multiprocessing.Process(target=dataCrawler)
            m.start()
            print('data scan restart')
        else:
            time.sleep(.25)

        time.sleep(1)

Now my website and twitch code run 24-7!  You can check it out at https://www.atltvhead.com Click some buttons and see them appear in the chat box. Also if you'd like to see how many of each button is pressed, you can access my database with this http request

https://www.natedamen.com/_functions/readInteractions

YAY FOR FIXED WEBSITE BUTTONS!

Discussions