Close

The Rube Goldberg Website Button

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 08/02/2018 at 16:060 Comments

***Edit to use the website buttons, the Atltvhead must be on, I live stream every Friday 6pm Est. 

Oh man! What I am about to share with you is not the best example of coding, making, communicating, but it works!

Here is a photo from my mobile site and buttons: 

Design intent: give non twitch users ability to change the screen

-buttons on my website (not a mobile app)

-literally zero changes to the atltvhead microcontroller code

-must work with Wix we site

-must work with me existing Twitch.tv interface/api

Process Flow:

Wix Javascript -> Google Api Python (email)-> Twitch Api Python -> Twitch API C++ (Atltvhead)

Build Out: Wix

Since my website is hosted on Wix, and I didn't want to buy a home server to host my website and possible open my networks firewall, I had to figure out a way to send out button presses. 

Wix Code is a relatively new way to intereact and design for Wix websites. See the photo below.

This Javascript based side of the websites allows for button presses to trigger lines of code. It also allows for the addition of website users from the back end. 

For my website, I was able to make these button presses send a premade email. The subject of the email changes for each button. The email address and particular subject lines will be read with a Python script in the next section.  Below is the code from my wix site. 

import wixCRM from 'wix-crm';
import wixUsers from 'wix-users';


//...



export function ButtonOnPress(event, $w) {
    //Add your code for this event here: 
    wixCRM.createContact({
        "emails":['Your_Email_Here']
        })
        .then((contactId)=>{
            wixCRM.emailContact('Pre_Made_Wix_Email_Here',contactId, {
                  variables: {
            command: 'Subject_Here'
        }})
        .catch( (err) => {
            console.log(err)
        });
    });
}

Build Out: Python Script

To use this script you will have to follow Google's Python API getting started guide and give permission to modify emails. You will need a Google email account, and a twitch account for the chatbot to function.

How this Python script functions by constantly reading the unread emails in an inbox. When a particular subject is found it sends a message to the twitch server, putting text command into the chat of a particular streamer. It finishes by marking that email read and continuing to read the unread messages in the inbox. 

Find more info for the Google side here and Twitch side here!

"""
Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
from apiclient import discovery
from apiclient import errors
from httplib2 import Http
from oauth2client import file, client, tools
import base64

import cfg #configure file with Twitch account, Aouth password, and which stream chat you are going to 
import socket
import re
import time
import multiprocessing


def chat(sock, msg):
    """
    Send a chat message to the server.
    Keyword arguments:
    sock -- the socket over which to send the message
    msg  -- the message to be sent
    """
    sock.send("PRIVMSG {} :{}\r\n".format(cfg.CHAN, msg).encode("utf-8"))



s = socket.socket()
s.connect((cfg.HOST,cfg.PORT))
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"))

CHAT_MSG=re.compile(r"^:\w+!\w+@\w+.tmi.twitch.tv PRIVMSG #\w+ :")



# Setup the Gmail API
SCOPES = 'https://www.googleapis.com/auth/gmail.modify' # we are using modify and not readonly, as we will be marking the messages Read
store = file.Storage('storage.json') 
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)
service = discovery.build('gmail', 'v1', http=creds.authorize(Http()))

user_id = 'me'
label_id_one = 'INBOX'
label_id_two = 'UNREAD'

#gets all of the unread messages from the inbox
def remail():
    while True:
        unread_msgs = service.users().messages().list(userId='me',labelIds=[label_id_two]).execute()

    
        mess = unread_msgs['messages']
        final_list=[]
    
        #print ("Total messaged retrived: ", str(len(mess)))
        for msgs in mess:
            temp_dict = { }
            m_id = msgs['id']
            message = service.users().messages().get(userId=user_id, id=m_id).execute() #get message using api
            payId=message['payload']
            headr =payId['headers']
    
            for one in headr:
                if one['name'] == 'Subject':
                       msg_subject = one['value']
                       temp_dict['Subject']= msg_subject
                else:
                       pass
           
            for three in headr:
                    if three['name']=='From':
                       msg_from = three['value']
                       temp_dict['Sender']= msg_from
                    else:
                       pass
            #print(temp_dict['Subject'])
            #print(temp_dict['Sender'])
                
            if temp_dict['Subject'] == 'Email_Subject_1':
                chat(s,"Chat_Command_1")
                service.users().messages().modify(userId=user_id, id=m_id, body={ 'removeLabelIds': ['UNREAD']}).execute() 

            elif temp_dict['Subject'] == 'Email_Subject_2':
                chat(s,"Chat_Command_2")
                service.users().messages().modify(userId=user_id, id=m_id, body={ 'removeLabelIds': ['UNREAD']}).execute()


                
        time.sleep(1 / cfg.RATE)
             




def pingPong(): 
    while True:    
        response = s.recv(1024).decode("utf-8")
        if response == "PING :tmi.twitch.tv\r\n":
            s.send("PONG :tmi.twitch.tv\r\n".encode("utf-8"))       
            
    time.sleep(1 / cfg.RATE)




if __name__ == '__main__' :
    p =  multiprocessing.Process(target=pingPong)
    m =  multiprocessing.Process(target=remail)
    p.start()
    m.start()


Discussions