0
votes

When I reply to the message, if I enter "Yes", "yes", or "no", it will give me this error:

Traceback (most recent call last): File "/Library/Python/2.7/site-packages/flask/app.py", line 1836, in call return self.wsgi_app(environ, start_response) File "/Library/Python/2.7/site-packages/flask/app.py", line 1820, in wsgi_app response = self.make_response(self.handle_exception(e)) File "/Library/Python/2.7/site-packages/flask/app.py", line 1403, in handle_exception reraise(exc_type, exc_value, tb) File "/Library/Python/2.7/site-packages/flask/app.py", line 1817, in wsgi_app response = self.full_dispatch_request() File "/Library/Python/2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request rv = self.handle_user_exception(e) File "/Library/Python/2.7/site-packages/flask/app.py", line 1381, in handle_user_exception reraise(exc_type, exc_value, tb) File "/Library/Python/2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request rv = self.dispatch_request() File "/Library/Python/2.7/site-packages/flask/app.py", line 1461, in dispatch_request return self.view_functionsrule.endpoint File "/Users/ryankenny/Desktop/Phase2.py/Test.py", line 59, in hello_guest wks_attendees.update_acell('E'+str(num), int(wks_attendees.acell('E' +str(num)).value) + 1) NameError: global name 'num' is not defined

If I enter anything else, it replies with:

You sent a different keyword, we need a yes or a no, you sent:....".

Here is my code: I named this one Test.py

from __future__ import print_function
import oauth2client
import gspread
import httplib2
import os
from apiclient import discovery
from oauth2client import client, tools
from oauth2client.file import Storage
from flask import Flask,render_template, url_for, request, redirect, make_response
from twilio.twiml.messaging_response import MessagingResponse
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime, timedelta
from twilio.rest  import Client
import time
import json
import gspread


app = Flask(__name__)
json_key = json.load(open('client_secret.json'))
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open("list18") #add your workbook name here
wks_attendees = wks.get_worksheet(0) #attendees worksheet
# ACCOUNT_SID = os.environ['Twilio_account_per']
# AUTH_TOKEN = os.environ['Twilio_account_token_per']
ACCOUNT_SID = 'xxxxxxxxx'
AUTH_TOKEN = 'xxxxxx'
client = Client(ACCOUNT_SID, AUTH_TOKEN)
@app.route("/messages", methods=['GET', 'POST'])
def hello_guest():

    resp = MessagingResponse()
    from_number = request.values.get('From', None)
    from_body = request.values.get('Body', None)
    number = from_number
    body_strip = from_body.lower()
    if "yes" in body_strip:
        # We have a keeper! Find the attendee and update their confirmation_status
        wks_attendees.update_acell("F"+str(guest_confirmation_cell.row), 'Accepted')  # update the status to accepted for that guest
        resp.message(u"\u2665" + "Thanks for confirming, we'll be in touch!" + u"\u2665")  # respond to the guest with a confirmation!
    elif "no" in from_body.lower():
        # update the confirmation_status row to declined for that guest
        wks_attendees.update_acell("F"+str(guest_confirmation_cell.row), 'Declined')
        # respond to the user confirming the action
        resp.message("Sorry to hear that, we still love you though!")
    else:  # respond with invalid keyword
        resp.message("You sent a different keyword, we need a yes or a no, you sent: "+
                     from_body)
    return str(resp)
if __name__ == '__main__':
    app.run(debug=True)

I named this one sheets.py

from flask import Flask,render_template, url_for, request, redirect, make_response
from twilio.twiml.messaging_response import MessagingResponse
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime, timedelta
from twilio.rest  import Client
import time
import json
import gspread
import os
import Test


# app = Flask(__name__)
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']

#credentials = ServiceAccountCredentials(json_key['client_email'], json_key['private_key'].encode(), scope)
#credentials = ServiceAccountCredentials(json_key['client_email'], json_key['private_key'].encode(), scope)
#gc = gspread.authorize(credentials)
credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open("list18") #add your workbook name here
wks_attendees = wks.get_worksheet(0) #attendees worksheet
# ACCOUNT_SID = os.environ['Twilio_account_per']
# AUTH_TOKEN = os.environ['Twilio_account_token_per']
ACCOUNT_SID = 'xxxxxxxx'
AUTH_TOKEN = 'xxxxxx'
client = Client(ACCOUNT_SID, AUTH_TOKEN)


for num in range(2,4):  #to iterate between guests, amend this based on your total
    print("sleeping for 2 seconds")
    time.sleep(2) #adding a delay to avoid filtering
    guest_number = wks_attendees.acell('B' +str(num)).value
    guest_name = wks_attendees.acell('A'+str(num)).value

    if not guest_number:
        print(guest_name + ' telephone number empty not messaging')
        wks_attendees.update_acell('E'+str(num), '0') #set number to 0

    else:
        print('Sending message to ' + guest_name)
        client.messages.create(
        to="+" + guest_number,
        from_="16467830828", #your twilio number here
        body= u"\u2B50" + u"\u2764" + u"\u2B50" + u"\u2764" + u"\u2B50" + u"\u2764" + u"\u2B50" + u"\u2764" + "\n\n" + u"\u2709" +" Save the date! "+ u"\u2709" +"\n\nRyan Kenny and Rachel Hunt are delighted to invite you to our wedding.\n\nDate: \n\nPlace. Please text YES if you are saving the date and can join us or text NO if sadly, you won't be able to be with us.\n\n" u"\u2B50" + u"\u2764" + u"\u2B50" + u"\u2764" + u"\u2B50" + u"\u2764" + u"\u2B50" + u"\u2764",
        #body ="Hello you lovely people, tomorrow is the big day!!\n\nPost code for the venue: CM6 1RQ\n\nArrival time one thirty for a two o'clock ceremony.\n\nIt is a cash bar, so please bring sufficient money with you as there is no nearby cash machine.\n\nIt might be raining at some point in the day, so an umbrella might be required.\n\nThe venue is non smoking, due to the thatched buildings.\n\nWe could not be more excited that you are joining us for our special day and looking forward to sharing great food and good times!\n\nTom & Lauren",
        )
        wks_attendees.update_acell('E'+str(num), int(wks_attendees.acell('E' +str(num)).value) + 1) #increment the message count row
else:                  # else part of the loop
    print('finished')

Updated WORKING test.py code

from __future__ import print_function
import oauth2client
import gspread
import httplib2
import os
from apiclient import discovery
from oauth2client import client, tools
from oauth2client.file import Storage
from flask import Flask,render_template, url_for, request, redirect, make_response
from twilio.twiml.messaging_response import MessagingResponse
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime, timedelta
from twilio.rest  import Client
import time
import json
import gspread


app = Flask(__name__)
json_key = json.load(open('client_secret.json'))
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open("list18") #add your workbook name here
wks_attendees = wks.get_worksheet(0) #attendees worksheet

ACCOUNT_SID = 'AC08bde2cb40b78d7f1022ba85d6dba741'
AUTH_TOKEN = '3a74f56d324f519b980f1553f1d0ae89'
client = Client(ACCOUNT_SID, AUTH_TOKEN)
@app.route("/messages", methods=['GET', 'POST'])
def hello_guest():

    resp = MessagingResponse()
    from_number = request.values.get('From', None)
    from_body = request.values.get('Body', None)
    number = from_number
    body_strip = from_body.lower()
    clean_number = number.strip("+")
    guest_confirmation_cell = wks_attendees.find(str(clean_number).strip())
    if "yes" in body_strip:
        # We have a keeper! Find the attendee and update their confirmation_status
        wks_attendees.update_acell("F"+str(guest_confirmation_cell.row), 'Accepted')  # update the status to accepted for that guest
        #wks_attendees.update_acell('E'+str(num), int(wks_attendees.acell('E' +str(num)).value) + 1)

        resp.message(u"\u2665" + "Thanks for confirming, we'll be in touch!" + u"\u2665")  # respond to the guest with a confirmation!
    elif "no" in from_body.lower():
        # update the confirmation_status row to declined for that guest
        wks_attendees.update_acell("F"+str(guest_confirmation_cell.row), 'Declined')
        # respond to the user confirming the action
        resp.message("Sorry to hear that, we still love you though!")
    else:  # respond with invalid keyword
        resp.message("You sent a different keyword, we need a yes or a no, you sent: "+
                     from_body)
    return str(resp)
if __name__ == '__main__':
    app.run(debug=True)
1
Removed repetition and re-arranged question to make things read in a more logical order. Added blockquote formatting for response messages. Added a little whitespace in the code to make it easier to read.moopet
The error message you're getting says NameError: global name 'num' is not defined but the line it's referencing (where it says wks_attendees.update_acell('E'+str(num),... isn't in the code you provided. Are you sure you're trying to run the same file you're editing?moopet

1 Answers

1
votes

Developer of that app/Twilio Onboarding here.

It looks like you have condensed the code from the repo somewhat, you are attempting to use a variable num that hasn't been declared so Python is erroring out. That variable is used to set the length of the spreadsheet during the create of the for loop that iterates over the list of attendees in the spreadsheet to update their status.

If you share the complete file or at least the code near line 59 I can help further.