【问题标题】:Twilio HTTP error and Google SpreadsheetTwilio HTTP 错误和 Google 电子表格
【发布时间】: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


【解决方案1】:

该应用程序的开发者/Twilio 在此处入职。

看起来您已经在某种程度上压缩了 repo 中的代码,您正在尝试使用尚未声明的变量 num,因此 Python 出错了。该变量用于设置the length of the spreadsheet 在创建循环遍历电子表格中的与会者列表以更新其状态的循环期间。

如果您分享完整的文件或至少第 59 行附近的代码,我可以提供进一步的帮助。

【讨论】:

  • 谢谢汤姆。我刚刚编辑了上面的代码。如果您有解决方案,请告诉我。 :) 我感谢一切。
  • "/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) 你分享了最新版本的错误吗?由于 test.py 中的代码不匹配。我在 test.py 中注意到的另一件事是您丢失了: number = from_number clean_number = number.strip("+") guest_confirmation_cell = wks_attendees.find(str(clean_number).strip()) 因为当您需要时将需要它们实际更新客人确认状态您可以将它们添加并重新运行test.py
  • 谢谢汤姆。我将根据我最近的更改重新编辑我的代码。我添加了 from_number clean_number = number.strip("+") 和 guest_confirmation_cell =wks_attendees.find(str(clean_number).strip())。但是,如果我的代码已经在工作,它会去哪里以及它实际上会做什么? wks_attendees.update_acell('E'+str(num), int(wks_attendees.acell('E' +str(num)).value) + 1)?不再有错误。不过,我还有另一个问题。我正在使用 ngrok 作为 http 隧道。不过,我只有 8 个小时才能得到一个新的。有什么办法可以延长使用时间,或者刷新一下?
  • 您在修改后的代码中的位置很好。 wks_attendees.update_acell('E'+str(num), int(wks_attendees.acell('E' +str(num)).value) + 1) 只是更新发送给特定客人的消息量。 Re ngrok,您可以支付升级费用以获得永久隧道,或者像我为婚礼所做的那样在Heroku 上举办婚礼
  • 非常感谢汤姆。你帮了很多忙。
猜你喜欢
  • 2015-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-04
  • 1970-01-01
相关资源
最近更新 更多