微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

让 Twilio 拨打 1 个号码,获取通话状态,然后继续拨打 Apps Script 上的下一个号码

如何解决让 Twilio 拨打 1 个号码,获取通话状态,然后继续拨打 Apps Script 上的下一个号码

我在谷歌电子表格上有一个电话号码列表,我已经编写了应用程序脚本来拨打电话号码。

但是,我希望 twilio 能够拨打第一个号码,获取其通话状态(已完成、忙碌、失败等),在电子表格中更新它,然后继续拨打第二个号码。

This 是我希望电子表格输出的样子。

目前,我无法使用 Apps 脚本从 twilio 获取呼叫状态。很想得到一些关于我做错了什么的反馈。

谢谢。

这是我的 Apps 脚本代码

// Enter your Twilio account information here.
var TWILIO_ACCOUNT_SID = '';
var TWILIO_NUMBER = '';
var TWILIO_AUTH_TOKEN = '';

// Other variables
var STARTROW = 2
var STARTCOL = 1

// Creates the Call button on the menu bar
function onopen() {
  // To learn about custom menus,please read:
  // https://developers.google.com/apps-script/guides/menus
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Call')
      .addItem('Call Selected','confirmCall')
      .addToUi();
};  

// Ensuring variables are entered
function checkSetup() {
  if (TWILIO_ACCOUNT_SID && TWILIO_AUTH_TOKEN) {
    return true;
  } else {
    var ui = SpreadsheetApp.getUi();
    var response = ui.alert('Please check your Twilio account details in AppScript');
    return false;
  }
}

// Confirmation Pop-up alert 
// Asks user if they have updated ngrok website
function confirmCall(){
  // display a dialog Box with a message and "Yes" and "No" buttons.
  var ui = SpreadsheetApp.getUi();
  var response = ui.alert('Is the Phone Number the last column and have you updated the ngrok website in the Apps Script?',ui.ButtonSet.YES_NO);
  
  // Process the user's response.
  if (response == ui.Button.YES) {
    Logger.log('The user clicked "Yes."');
    
    // Starts making the calls
    all_selected(); 
      
  } else {
    ui.alert('Please go to the Tools menu bar > Script Editor to update. \n If unsure,please check manual.');
    Logger.log('The user clicked "No" or the dialog\'s close button.');
  }
}  

// Intiates calls to the selected users 
function all_selected() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var ui = SpreadsheetApp.getUi();
  var totalRows = sheet.getLastRow();
  var numRows = sheet.getLastRow() - STARTROW + 1; 
  var numColumns = sheet.getLastColumn();
  var nextColumn = numColumns + 1;

  // Create new column 
  sheet.getRange(1,nextColumn).setValue("Response")

  if (!checkSetup) {
    return 
  }

  if (numRows <= 0) {
    Logger.log("No one to call");
    var response = ui.alert('No calls to make');
    return;
  }

  for (var i = STARTROW; i <= (totalRows); i++) {
    var number = sheet.getRange(i,numColumns).getValue();
    var response = makeCall(number);

    //browser.msgBox(response);
    // sheet.getRange(i,nextColumn + 1).setValue(response["status"])

    // If there is an error,update cell value to Nil
    if(response.code){
      sheet.getRange(i,nextColumn).setValue("Nil")
      Logger.log("Error has occured.");
    }

  }
}

// Calls a (ONE) person
function makeCall(to) {
  var call_url = "https://api.twilio.com/2010-04-01/Accounts/" + TWILIO_ACCOUNT_SID + "/Calls.json";
  
  var payload = {
    "To": "+" + String(to),"From" : TWILIO_NUMBER,"Url": "http://821f72d16be7.ngrok.io/"   + "voice","status_callback" : 'http://821f72d16be7.ngrok.io/' +  "status","Method": "GET","status_callback_event"  : ['queued','initiated'],"status_callback_method" : 'POST'
  };
  
  var options = {
    "method" : "post","payload" : payload
  };
  
  options.headers = {    
    "Authorization" : "Basic " + Utilities.base64Encode(TWILIO_ACCOUNT_SID + ":" + TWILIO_AUTH_TOKEN)
  };
  
  var response = UrlFetchApp.fetch(call_url,options);
  return JSON.parse(response);
}

这是我的 python Colab 代码

from flask import Flask,request,session
from flask_ngrok import run_with_ngrok

import os
from twilio.rest import Client
from twilio import twiml
from twilio.twiml.voice_response import VoiceResponse,Gather

from google.colab import auth

import gspread
from oauth2client.client import GoogleCredentials

# Change this if using a new sheet
sheet_id = ""

# Accesses the google spreadsheet 
auth.authenticate_user()
gc = gspread.authorize(GoogleCredentials.get_application_default())

# Opens the spreadsheet(****First sheet****)
worksheet = gc.open_by_key(sheet_id).sheet1

# Gets the number of columns in the current sheet
num_col = len(worksheet.get_all_values()[0])
col = num_col + 1

####################################################################
TWILIO_ACCOUNT_SID = ''
TWILIO_NUMBER = ''
TWILIO_AUTH_TOKEN = ''

client = Client(TWILIO_ACCOUNT_SID,TWILIO_AUTH_TOKEN)

# Makes connection using FLASK
app = Flask(__name__)
run_with_ngrok(app)  

@app.route("/status",methods=['GET','POST'])
def status():

    # Need to get the number of rows in that column 
    row = len(worksheet.col_values(num_col))

    worksheet.update_cell(row,col+1,request.values['Status'])
    # client = Client(TWILIO_ACCOUNT_SID,TWILIO_AUTH_TOKEN)
    # record = client.calls.list(limit=1)
    # status = record.status

    
    # if status == 'Failed':
    #   worksheet.update_cell(row,col,"Failed")

@app.route("/voice",'POST'])
def voice():
    """Respond to incoming phone calls with a menu of options"""
    # Start our TwiML response
    resp = VoiceResponse()

    # Start our <Gather> verb
    gather = Gather(num_digits=1,action='/gather')
    gather.say('If you are interested in our service,press 1. If not,press 2.')
    resp.append(gather)

    # If the user doesn't select an option,redirect them into a loop
    resp.redirect('/voice')

    return str(resp)

@app.route('/gather','POST'])
def gather():
    """Processes results from the <Gather> prompt in /voice"""
    # Start our TwiML response
    resp = VoiceResponse()

    # Need to get the number of rows in that column 
    row = len(worksheet.col_values(num_col))
    #row = rows_col + 1

    # If Twilio's request to our app included already gathered digits,# process them
    if 'Digits' in request.values:
        # Get which digit the caller chose
        choice = request.values['Digits']

        # <Say> a different message depending on the caller's choice
        if choice == '1':
            resp.say('You have indicated your interest. We will get back to you soon.')
            # Updating the cells (row,column,data)
            worksheet.update_cell(row,"Yes")
            return str(resp)

        elif choice == '2':
            resp.say('We understand your choice. Thank you.')
            # Updating the cells (row,"No")
            return str(resp)

        else:
            # If the caller didn't choose 1 or 2,apologize and ask them again
            # Updating the cells (row,data)
            ###### sheet.update_cell(row,num_col,"Nil")
            worksheet.update_cell(row,"Never indicate")
            resp.say("Sorry,I don't understand that choice. Please try again.")

    # If the user didn't choose 1 or 2 (or anything),send them back to /voice
    resp.redirect('/voice')
    
    return str(resp)

# if __name__ == "__main__":
#     app.run(debug=True,use_reloader=False)

app.run()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。