【发布时间】:2018-08-27 14:03:56
【问题描述】:
当我回复消息时,如果我输入“是”、“是”或“否”,它会给我这个错误:
Traceback(最近一次调用最后一次): 调用中的文件“/Library/Python/2.7/site-packages/flask/app.py”,第 1836 行 return self.wsgi_app(environ, start_response) wsgi_app 中的文件“/Library/Python/2.7/site-packages/flask/app.py”,第 1820 行 响应 = self.make_response(self.handle_exception(e)) 文件“/Library/Python/2.7/site-packages/flask/app.py”,第 1403 行,在 handle_exception 中 reraise(exc_type, exc_value, tb) wsgi_app 中的文件“/Library/Python/2.7/site-packages/flask/app.py”,第 1817 行 响应 = self.full_dispatch_request() 文件“/Library/Python/2.7/site-packages/flask/app.py”,第 1477 行,在 full_dispatch_request rv = self.handle_user_exception(e) 文件“/Library/Python/2.7/site-packages/flask/app.py”,第 1381 行,在 handle_user_exception reraise(exc_type, exc_value, tb) 文件“/Library/Python/2.7/site-packages/flask/app.py”,第 1475 行,在 full_dispatch_request rv = self.dispatch_request() 文件“/Library/Python/2.7/site-packages/flask/app.py”,第 1461 行,在 dispatch_request 中 返回 self.view_functionsrule.endpoint 文件“/Users/ryankenny/Desktop/Phase2.py/Test.py”,第 59 行,在 hello_guest wks_attendees.update_acell('E'+str(num), int(wks_attendees.acell('E' +str(num)).value) + 1) NameError:未定义全局名称“num”
如果我输入其他内容,它会回复:
您发送了一个不同的关键字,我们需要一个是或否,您发送了:...."。
这是我的代码: 我将这个命名为 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)
我把这个命名为 sheet.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')
更新了 WORKING 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 = '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)
【问题讨论】:
-
删除了重复并重新安排了问题,以使内容以更合乎逻辑的顺序阅读。为响应消息添加了块引用格式。在代码中添加了一些空格,以便于阅读。
-
您收到的错误消息显示
NameError: global name 'num' is not defined,但它所引用的行(其中显示wks_attendees.update_acell('E'+str(num),...不在您提供的代码中。您确定要运行您正在编辑同一文件?
标签: python python-3.x python-2.7 google-api twilio