### Install twilio-ruby Gem Source: https://github.com/twilio/twilio-ruby/blob/main/README.md Instructions for installing the twilio-ruby gem using Bundler or Rubygems. Includes commands for cloning the repository and installing from source. ```ruby gem 'twilio-ruby', '~> 7.10.4' ``` ```bash gem install twilio-ruby -v 7.10.4 ``` ```bash git clone git@github.com:twilio/twilio-ruby.git cd twilio-ruby make install ``` -------------------------------- ### Install twilio-ruby Gem Source: https://context7.com/twilio/twilio-ruby/llms.txt Instructions for installing the twilio-ruby gem using Bundler or RubyGems. ```ruby # Gemfile gem 'twilio-ruby', '~> 7.10.4' # Or install directly # gem install twilio-ruby -v 7.10.4 ``` -------------------------------- ### Twiml - Support Recording Noun Source: https://github.com/twilio/twilio-ruby/blob/main/CHANGES.md Adds support for the `` noun under the `` verb in TwiML. ```APIDOC ### TwiML Verbs - `` - `` - `` - `` - `` - `` - `` - `` - `` - `` (New support) #### `` with `` ```xml Recording started. ``` ``` -------------------------------- ### Twilio Ruby: Setup Client Capability Token Source: https://github.com/twilio/twilio-ruby/wiki/JWT-Tokens Initializes the Twilio Client Capability object with account credentials. This is the first step in generating a token for Twilio Client. ```ruby require 'twilio-ruby' # put your own account credentials here: account_sid = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' auth_token = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy' # set up capability = Twilio::JWT::ClientCapability.new account_sid, auth_token ``` -------------------------------- ### Configure Environment Variables for Proxy Source: https://github.com/twilio/twilio-ruby/blob/main/advanced-examples/custom-http-client.md Example configuration for a .env file to store Twilio credentials and proxy server details. ```env ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx AUTH_TOKEN= your_auth_token HTTPS_PROXY=https://127.0.0.1:8888 HTTP_PROXY=http://127.0.0.1:8888 ``` -------------------------------- ### Generated File Header Example (Ruby) Source: https://github.com/twilio/twilio-ruby/blob/main/CONTRIBUTING.md This is an example of a header found in generated Ruby files within the twilio-ruby project. If a file contains this header, changes should be made by the project maintainers, but issues can still be reported. ```ruby """ This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ ``` ```ruby """ * This code was generated by * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ * """ ``` -------------------------------- ### Test Twilio Ruby Installation with SMS Source: https://github.com/twilio/twilio-ruby/blob/main/README.md A Ruby code snippet to verify the twilio-ruby installation by sending a test SMS message. Requires Twilio account credentials. ```ruby require "twilio-ruby" # Your Account SID and Auth Token from console.twilio.com account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" @client = Twilio::REST::Client.new account_sid, auth_token message = @client.messages.create( body: "Hello from Ruby", to: "+12345678901", # Text this number from: "+15005550006", # From a valid Twilio number ) puts message.sid ``` -------------------------------- ### Send and Manage SMS Messages Source: https://github.com/twilio/twilio-ruby/blob/main/README.md Provides examples for sending a new SMS, listing existing messages, and fetching a specific message by its SID. ```ruby # Send SMS @client.messages.create( from: '+14159341234', to: '+16105557069', body: 'Hey there!' ) # List SMS @client.messages.list(limit: 20) # Fetch by SID message_sid = 'SMxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' @client.messages(message_sid).fetch ``` -------------------------------- ### Trusthub API - Update Email in Examples Source: https://github.com/twilio/twilio-ruby/blob/main/CHANGES.md Changes the email value in Trusthub API examples to a valid format. ```APIDOC ### Example Contact Info (Trusthub API) ```json { "firstName": "John", "lastName": "Doe", "email": "john.doe@example.com", "phone": "+15551234567" } ``` ``` -------------------------------- ### Wise_owl API - Get Chat, Send Message, Create Chat Updates Source: https://github.com/twilio/twilio-ruby/blob/main/CHANGES.md Updates Get Chat, Send Message, and Create Chat to include 'contexts' in the Message object, instead of the root Chat object. ```APIDOC ## POST /wise_owl/chats/{chatId}/messages ### Description Sends a message within a chat. The `contexts` field is now part of the `message` object. ### Method POST ### Endpoint /wise_owl/chats/{chatId}/messages ### Parameters #### Path Parameters - **chatId** (string) - Required - The unique ID of the chat. #### Request Body - **message** (object) - Required - The message object. - **body** (string) - Required - The content of the message. - **contexts** (array) - Optional - Contextual information for the message. - **key** (string) - The context key. - **value** (string) - The context value. ### Response #### Success Response (201) - **messageSid** (string) - The unique ID of the sent message. - **chatId** (string) - The ID of the chat. - **contexts** (array) - The contexts included in the message. #### Response Example ```json { "messageSid": "SM123", "chatId": "CH456", "contexts": [ { "key": "user_intent", "value": "get_help" } ] } ``` ``` -------------------------------- ### Trusthub API - Toll-Free Initialize API Payload Updates Source: https://github.com/twilio/twilio-ruby/blob/main/CHANGES.md Adds new parameters to the toll-free initialize API payload and updates examples. ```APIDOC ## POST /v1/Tollfree/Initialize ### Description Initializes a toll-free number. New parameters have been added to the payload. ### Method POST ### Endpoint /v1/Tollfree/Initialize ### Parameters #### Request Body - **customerProfileSid** (string) - Required - The SID of the customer profile. - **useCase** (string) - Required - The use case for the toll-free number. - **businessName** (string) - Required - The name of the business. - **businessAddress** (object) - Required - The business address. - **street** (string) - Required. - **city** (string) - Required. - **state** (string) - Required. - **zip** (string) - Required. - **country** (string) - Required. - **contactInfo** (object) - Required - Contact information. - **firstName** (string) - Required. - **lastName** (string) - Required. - **email** (string) - Required. - **phone** (string) - Required. - **additionalParameters** (object) - Optional - Additional parameters for initialization. - **customer_profile_sid** (string) - Optional - The SID of the customer profile (alternative to top-level parameter). ### Response #### Success Response (201) - **sid** (string) - The unique ID of the toll-free initialization request. - **status** (string) - The status of the initialization. #### Response Example ```json { "sid": "TF123", "status": "pending" } ``` ``` -------------------------------- ### Oauth - Get UserInfo Resource Source: https://github.com/twilio/twilio-ruby/blob/main/CHANGES.md Adds an endpoint to retrieve user information based on an access token. ```APIDOC ## GET /oauth/userinfo ### Description Retrieves information about the authenticated user associated with the provided access token. ### Method GET ### Endpoint /oauth/userinfo ### Parameters #### Path Parameters None #### Query Parameters None #### Request Headers - **Authorization** (string) - Required - Bearer token (e.g., `Bearer ACCESS_TOKEN`). ### Request Example ``` GET /oauth/userinfo HTTP/1.1 Host: example.com Authorization: Bearer ACCESS_TOKEN_VALUE ``` ### Response #### Success Response (200) Returns a JSON object containing the user's profile information. #### Response Example ```json { "sub": "user_id_12345", "name": "John Doe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Generate TwiML for SMS with Media and Redirect Source: https://context7.com/twilio/twilio-ruby/llms.txt This snippet demonstrates how to generate TwiML responses for SMS messages. It includes examples for sending a message with media and for redirecting to another TwiML endpoint. ```ruby response = Twilio::TwiML::MessagingResponse.new do |r| r.message do |m| m.body('Here is the image you requested:') m.media('https://example.com/image.jpg') end end ``` ```ruby response = Twilio::TwiML::MessagingResponse.new do |r| r.redirect('https://example.com/sms-handler', method: 'POST') end ``` -------------------------------- ### Initialize Twilio Client with Custom Proxy Client Source: https://github.com/twilio/twilio-ruby/blob/main/advanced-examples/custom-http-client.md Demonstrates how to instantiate the custom HTTP client and inject it into the Twilio REST Client to send an SMS via a proxy. ```ruby require "rubygems" require "twilio-ruby" require "dotenv/load" require_relative "MyRequestClass" account_sid = ENV["ACCOUNT_SID"] auth_token = ENV["AUTH_TOKEN"] proxy_address = ENV["PROXY_ADDRESS"] proxy_protocol = ENV["PROXY_PROTOCOL"] proxy_port = ENV["PROXY_PORT"] my_request_client = MyRequestClass.new(proxy_protocol, proxy_address, proxy_port) @client = Twilio::REST::Client.new(account_sid, auth_token, nil, nil, my_request_client) message = @client.messages .create( to: "+593978613041", body: "RB This is the ship that made the Kesssssel Run in fourteen parsecs?", from: "+13212855389", ) puts "Message SID: #{message.sid}" ``` -------------------------------- ### Trusthub API - Remove Invalid Status Transition Example Source: https://github.com/twilio/twilio-ruby/blob/main/CHANGES.md Removes an invalid status transition from 'Draft' to 'Submitted' in the examples for the Trusthub API. ```APIDOC ### Example Status Transitions (Trusthub API) * **Draft** -> **Pending Review** * **Pending Review** -> **Approved** * **Pending Review** -> **Rejected** * **Approved** -> **Active** * **Rejected** -> **Draft** *Note: The transition from 'Draft' to 'Submitted' is not a valid status transition and has been removed from examples.* ``` -------------------------------- ### Standard Twilio REST Client Initialization Source: https://github.com/twilio/twilio-ruby/blob/main/advanced-examples/custom-http-client.md Demonstrates the default initialization of the Twilio REST client without custom HTTP configurations. This is the standard approach for direct connections to Twilio APIs. ```ruby @client = Twilio::REST::Client.new(account_sid, auth_token) message = @client.messages .create( to: "+15558675310", body: "Hey there!", from: "+15017122661", ) ``` -------------------------------- ### Memory API - Initial Endpoints Source: https://github.com/twilio/twilio-ruby/blob/main/CHANGES.md Adds initial Memory API endpoints with darkseagreen badge status. ```APIDOC ## POST /v1/Memory/Items ### Description Creates a new item in the Memory API. This endpoint is marked with a 'darkseagreen' status badge, indicating it's an initial release. ### Method POST ### Endpoint /v1/Memory/Items ### Parameters #### Request Body - **content** (string) - Required - The content of the memory item. - **metadata** (object) - Optional - Additional metadata for the item. ### Response #### Success Response (201) - **sid** (string) - The unique ID of the created memory item. - **status** (string) - The status of the item. #### Response Example ```json { "sid": "ME123", "status": "created" } ``` ``` -------------------------------- ### Initialize Twilio REST Client Source: https://github.com/twilio/twilio-ruby/wiki/documentation/REST Instantiate the Twilio REST Client using your account SID and authentication token. This client serves as the entry point for accessing all Twilio API resources. ```ruby @client = Twilio::REST::Client.new 'your_account_sid', 'your_auth_token' ``` -------------------------------- ### Iterate Through Records with Pagination Source: https://github.com/twilio/twilio-ruby/blob/main/README.md Demonstrates how to use the list and stream methods to handle collections of records, with the library automatically managing pagination. ```ruby require 'twilio-ruby' account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' @client = Twilio::REST::Client.new(account_sid, auth_token) @client.calls.list .each do |call| puts call.direction end ``` -------------------------------- ### Numbers - Get Port In Request API Source: https://github.com/twilio/twilio-ruby/blob/main/CHANGES.md Introduces an API to retrieve Port In requests for phone numbers. ```APIDOC ## GET /v1/PhoneNumbers/Porting/Requests ### Description Retrieves a list of Port In requests for phone numbers. ### Method GET ### Endpoint /v1/PhoneNumbers/Porting/Requests ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Returns a list of Port In requests. #### Response Example { "requests": [ { "sid": "PNxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "account_sid": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "notification_email": "user@example.com", "created_at": "2024-01-25T10:00:00Z" } ] } ``` -------------------------------- ### Initialize Twilio Client with Custom Proxy HTTP Client Source: https://github.com/twilio/twilio-ruby/blob/main/advanced-examples/custom-http-client.md Shows how to instantiate a custom HTTP client class and inject it into the Twilio REST client. This allows for custom proxy authentication and routing configurations. ```ruby require "twilio-ruby" require_relative "MyRequestClass" account_sid = ENV["ACCOUNT_SID"] auth_token = ENV["AUTH_TOKEN"] proxy_address = ENV["PROXY_ADDRESS"] proxy_protocol = ENV["PROXY_PROTOCOL"] proxy_port = ENV["PROXY_PORT"] my_request_client = MyRequestClass.new(proxy_protocol, proxy_address, proxy_port) @client = Twilio::REST::Client.new(account_sid, auth_token, nil, nil, my_request_client) message = @client.messages.create( to: "+593978613041", body: "RB This is the ship that made the Kesssssel Run in fourteen parsecs?", from: "+13212855389" ) puts "Message SID: #{message.sid}" ``` -------------------------------- ### TrustHub - Initialize Compliance Inquiry Source: https://github.com/twilio/twilio-ruby/blob/main/CHANGES.md Adds an optional `NotificationEmail` field to the POST /v1/ComplianceInquiries/Customers/Initialize API. ```APIDOC ## POST /v1/ComplianceInquiries/Customers/Initialize ### Description Initializes a compliance inquiry for a customer. An optional `NotificationEmail` field can now be provided. ### Method POST ### Endpoint /v1/ComplianceInquiries/Customers/Initialize ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **NotificationEmail** (string) - Optional - The email address to send notifications to regarding the compliance inquiry. ### Request Example ```json { "NotificationEmail": "customer@example.com" } ``` ### Response #### Success Response (200) Indicates the compliance inquiry was successfully initialized. #### Response Example ```json { "sid": "CIxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "account_sid": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "status": "initialized" } ``` ``` -------------------------------- ### Listing and Streaming Resources Source: https://github.com/twilio/twilio-ruby/wiki/documentation/REST Use the list method to fetch a collection of resources based on filters, or use stream for lazy loading of records. ```ruby @calls.list(from: '+14159355555') ``` -------------------------------- ### Manage Call Queues with Twilio Ruby Source: https://context7.com/twilio/twilio-ruby/llms.txt Demonstrates creating, listing, inspecting members, dequeuing, and deleting call queues. Requires a valid Twilio account SID and auth token. ```ruby require 'twilio-ruby' @client = Twilio::REST::Client.new('ACxxx', 'auth_token') # Create a new queue queue = @client.queues.create( friendly_name: 'Support Queue', max_size: 100 ) puts "Queue SID: #{queue.sid}" # List all queues @client.queues.list.each do |q| puts "#{q.friendly_name}: #{q.current_size} callers waiting" end # Get queue members queue_sid = 'QUxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' members = @client.queues(queue_sid).members.list members.each do |member| puts "Call #{member.call_sid} - Wait time: #{member.wait_time}s" end # Dequeue a member to a specific URL @client.queues(queue_sid) .members('CAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') .update(url: 'http://example.com/dequeue', method: 'POST') # Delete a queue @client.queues(queue_sid).delete ``` -------------------------------- ### Accessing Twilio Resources (Ruby) Source: https://github.com/twilio/twilio-ruby/wiki/Ruby-Version-5.x-Upgrade-Guide Demonstrates the change in accessing individual Twilio resources, moving from a direct `.get` method to a chained context-based `.fetch` method. This change improves network efficiency and clarifies HTTP interactions. ```ruby # Old call = @client.account.calls.get('CA123xxx') ``` ```ruby # New call = @client.api.v2010.account.calls('CA123xxx').fetch ## OR call = @client.api.account.calls('CA123xxx').fetch ``` ```ruby > workspace = @client.taskrouter.workspaces('WSxxx') #=> > workspace.fetch #=> ``` -------------------------------- ### Customize HTTP Client Source: https://github.com/twilio/twilio-ruby/blob/main/README.md Shows how to modify the Faraday-based HTTP client by changing the adapter or adding custom middleware. ```ruby @client.http_client.adapter = :typhoeus @client.http_client.configure_connection do |faraday| faraday.use SomeMiddleware end ``` -------------------------------- ### Listing Twilio Resources (Ruby) Source: https://github.com/twilio/twilio-ruby/wiki/Ruby-Version-5.x-Upgrade-Guide Illustrates the two new methods for listing resources: `list` which returns an Array, and `stream` which returns an Enumerable for efficient, paged iteration. Both methods support automatic paging with `limit`, `page_size`, and `page_limit` parameters. ```ruby > @client.api.account.messages.list #=> [#, #, ...] ``` ```ruby > @client.api.account.messages.stream(limit: 5).each {|m| puts m.sid} MS111xxx MS222xxx MS333xxx MS444xxx MS555xxx ``` ```ruby @client.api.account.incoming_phone_numbers.stream(limit: 3000, page_size: 100) do |number| puts number.phone_number end ``` ```ruby > @client.conversations.completed.list(page_size: 100, page_limit: 10).size #=> 1000 ``` -------------------------------- ### Memory API - Import Profiles V2 Source: https://github.com/twilio/twilio-ruby/blob/main/CHANGES.md Adds new paths for listing and retrieving profile imports using version 2. ```APIDOC ## POST /v1/Stores/{storeId}/Profiles/Imports ### Description Imports profiles into a store. This is a V2 endpoint. ### Method POST ### Endpoint /v1/Stores/{storeId}/Profiles/Imports ### Parameters #### Path Parameters - **storeId** (string) - Required - The unique ID of the store. #### Request Body - **fileUrl** (string) - Required - The URL of the file containing profile data. ### Response #### Success Response (201) - **importId** (string) - The ID of the import job. - **status** (string) - The status of the import job. #### Response Example ```json { "importId": "IM123", "status": "queued" } ``` ## GET /v1/Stores/{storeId}/Profiles/Imports/{importId} ### Description Retrieves the status of a profile import job. ### Method GET ### Endpoint /v1/Stores/{storeId}/Profiles/Imports/{importId} ### Parameters #### Path Parameters - **storeId** (string) - Required - The unique ID of the store. - **importId** (string) - Required - The unique ID of the import job. ### Response #### Success Response (200) - **importId** (string) - The ID of the import job. - **status** (string) - The status of the import job. - **processedCount** (integer) - The number of profiles processed. - **errorCount** (integer) - The number of profiles with errors. #### Response Example ```json { "importId": "IM123", "status": "completed", "processedCount": 100, "errorCount": 0 } ``` ``` -------------------------------- ### Autopilot Assistant Webhooks Source: https://github.com/twilio/twilio-ruby/blob/main/CHANGES.md Introduces the 'autopilot' subdomain and adds Webhooks resource to Autopilot Assistant, migrating resources from 'preview.understand'. ```APIDOC ## POST /autopilot/assistants/{assistantSid}/webhooks ### Description Creates a new webhook for an Autopilot Assistant. ### Method POST ### Endpoint /autopilot/assistants/{assistantSid}/webhooks ### Parameters #### Path Parameters - **assistantSid** (string) - Required - The unique ID of the assistant. #### Request Body - **eventType** (string) - Required - The type of event that triggers the webhook. - **url** (string) - Required - The URL to send webhook requests to. ### Request Example ```json { "eventType": "on_message", "url": "https://example.com/webhook" } ``` ### Response #### Success Response (201) - **sid** (string) - The unique ID of the webhook. - **eventType** (string) - The type of event. - **url** (string) - The webhook URL. #### Response Example ```json { "sid": "WH123", "eventType": "on_message", "url": "https://example.com/webhook" } ``` ``` -------------------------------- ### Configure Twilio Client Region and Edge Source: https://github.com/twilio/twilio-ruby/blob/main/README.md Demonstrates how to set the region and edge properties on the Twilio client to route requests to specific data centers. ```ruby @client = Twilio::REST::Client.new account_sid, auth_token @client.region = 'au1' @client.edge = 'sydney' ``` -------------------------------- ### List and Iterate Through Calls with Twilio Ruby Source: https://context7.com/twilio/twilio-ruby/llms.txt Demonstrates various ways to retrieve call logs, including filtering, streaming for lazy loading, and manual pagination. ```ruby require 'twilio-ruby' @client = Twilio::REST::Client.new('ACxxx', 'auth_token') # List calls with filters calls = @client.calls.list( limit: 10, start_time: Time.new(2024, 1, 1) ) calls.each do |call| price = call.price || '0.00' puts "#{call.sid}\t#{call.from}\t#{call.to}\t#{call.status}\t$#{price}" end # Stream through all calls (lazy loading with pagination) @client.calls.stream.each do |call| puts "#{call.sid}: #{call.direction} - #{call.duration}s" end # Manual pagination page = @client.calls.page(page_size: 50) loop do page.each { |call| puts call.sid } page = page.next_page break if page.nil? end ``` -------------------------------- ### List and Fetch Messages with Twilio Ruby Source: https://context7.com/twilio/twilio-ruby/llms.txt Demonstrates how to retrieve a list of messages with filtering and pagination, as well as fetching details for a specific message by its SID. ```ruby require 'twilio-ruby' @client = Twilio::REST::Client.new('ACxxx', 'auth_token') # List recent messages with limit messages = @client.messages.list(limit: 20) messages.each do |message| puts "#{message.sid}: #{message.from} -> #{message.to}: #{message.body}" end # Filter messages by date messages = @client.messages.list( date_sent: Date.new(2024, 1, 1), limit: 50 ) # Fetch a specific message by SID message_sid = 'SMxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' message = @client.messages(message_sid).fetch puts "Body: #{message.body}" puts "Status: #{message.status}" puts "Price: #{message.price} #{message.price_unit}" ``` -------------------------------- ### Dial and Connect Calls with TwiML Source: https://context7.com/twilio/twilio-ruby/llms.txt Demonstrates how to route calls to various endpoints including phone numbers, SIP addresses, Twilio Clients, and conferences. ```ruby require 'twilio-ruby' response = Twilio::TwiML::VoiceResponse.new do |r| r.say(message: 'Please hold while we connect you.', voice: 'alice') r.dial( caller_id: '+15017122661', timeout: 30, action: '/dial-complete', record: 'record-from-answer' ) do |d| d.number('+15558675310', status_callback: '/number-events') d.client('jenny') d.sip('sip:user@example.com') d.conference('MyRoom', start_conference_on_enter: true, end_conference_on_exit: false, wait_url: 'http://example.com/hold-music' ) end end puts response.to_s ``` -------------------------------- ### Configure Twilio Ruby Client with Default Credentials Source: https://github.com/twilio/twilio-ruby/wiki/documentation/Util This snippet shows how to set the default account SID and auth token for the Twilio Ruby client. After configuration, you can instantiate the client without passing these values, simplifying subsequent API interactions. ```ruby @account_sid = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' @auth_token = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy' Twilio.configure do |config| config.account_sid = @account_sid config.auth_token = @auth_token end @client = Twilio::REST::Client.new ``` -------------------------------- ### Configurable HTTP Client (Ruby) Source: https://github.com/twilio/twilio-ruby/wiki/Ruby-Version-5.x-Upgrade-Guide Explains how to customize the HTTP client used by the Twilio::REST client. You can provide your own implementation conforming to the `Twilio::HTTP::HttpClient` interface or configure the default Faraday adapter, such as switching to `:typhoeus`. ```ruby custom_client = MyCustomClient.new @client = Twilio::REST::Client.new('ACxxx', 'AUTHTOKEN', http_client: custom_client) ``` ```ruby @client.http_client.adapter = :typhoeus ``` -------------------------------- ### Authenticate Twilio Client with Credentials Source: https://github.com/twilio/twilio-ruby/blob/main/README.md Ruby code to initialize the Twilio REST client using Account SID and Auth Token. ```ruby require 'twilio-ruby' # Your Account SID and Auth Token from console.twilio.com account_sid = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' auth_token = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy' # Initialize the Twilio Client with your credentials @client = Twilio::REST::Client.new account_sid, auth_token ``` -------------------------------- ### Configure Custom HTTP Client with Proxy in Twilio Ruby Source: https://context7.com/twilio/twilio-ruby/llms.txt Demonstrates how to configure a custom HTTP client to route Twilio API requests through a proxy server. This involves creating a custom client class that utilizes Faraday for HTTP requests and specifying the proxy URL during client initialization. ```ruby require 'twilio-ruby' require 'faraday' # Custom HTTP client class for proxy support class ProxyHttpClient attr_accessor :adapter attr_reader :timeout, :last_response, :last_request def initialize(proxy_url, timeout: nil) @proxy_url = proxy_url @timeout = timeout @adapter = Faraday.default_adapter end def request(host, port, method, url, params = {}, data = {}, headers = {}, auth = nil, timeout = nil) connection = Faraday.new(url: "#{host}:#{port}", ssl: { verify: true }) do |f| f.request :url_encoded f.adapter @adapter f.headers = headers f.basic_auth(auth[0], auth[1]) if auth f.proxy = @proxy_url if @proxy_url f.options.timeout = timeout || @timeout end response = connection.send(method.downcase.to_sym, url, method == 'GET' ? params : data) @last_response = Twilio::Response.new(response.status, response.body, headers: response.headers) @last_response end end # Use custom client with proxy proxy_client = ProxyHttpClient.new('http://proxy.example.com:8080') # @client = Twilio::REST::Client.new('ACxxx', 'auth_token', nil, nil, proxy_client) # Example API call using the proxied client # message = @client.messages.create( # from: '+15017122661', # to: '+15558675310', # body: 'Message via proxy!' # ) ``` -------------------------------- ### Voice API - ProvisioningStatus Endpoints Source: https://github.com/twilio/twilio-ruby/blob/main/CHANGES.md Adds public API endpoints for ProvisioningStatus in the Voice product. ```APIDOC ## GET /v1/Voice/ProvisioningStatus ### Description Retrieves the provisioning status for voice resources. ### Method GET ### Endpoint /v1/Voice/ProvisioningStatus ### Parameters #### Query Parameters - **resourceSid** (string) - Optional - Filter by a specific resource SID. ### Response #### Success Response (200) - **provisioningStatus** (array) - A list of provisioning status objects. - **sid** (string) - The unique ID of the resource. - **status** (string) - The current provisioning status. #### Response Example ```json { "provisioningStatus": [ { "sid": "VO123", "status": "active" } ] } ``` ``` -------------------------------- ### Create and Manage Conversations with Twilio Ruby Source: https://context7.com/twilio/twilio-ruby/llms.txt Demonstrates how to create and manage multi-party conversations using the Twilio Conversations API. This includes creating a conversation, adding SMS and Chat participants, sending a message, and listing messages within a conversation. It requires a Twilio REST client instance. ```ruby require 'twilio-ruby' # Initialize the Twilio client # @client = Twilio::REST::Client.new('ACxxx', 'auth_token') # Create a conversation conversation = @client.conversations.v1.conversations.create( friendly_name: 'Support Chat #1234' ) conversation_sid = conversation.sid puts "Conversation SID: #{conversation_sid}" # Add an SMS participant sms_participant = @client.conversations.v1 .conversations(conversation_sid) .participants .create( messaging_binding_address: '+15558675310', messaging_binding_proxy_address: '+15017122661' ) # Add a Chat participant chat_participant = @client.conversations.v1 .conversations(conversation_sid) .participants .create(identity: 'agent-alice') # Send a message to the conversation message = @client.conversations.v1 .conversations(conversation_sid) .messages .create( author: 'agent-alice', body: 'Hello! How can I help you today?' ) puts "Message SID: #{message.sid}" # List conversation messages @client.conversations.v1 .conversations(conversation_sid) .messages .list(limit: 50) .each do |msg| puts "#{msg.author}: #{msg.body}" end ``` -------------------------------- ### Twilio Client Authentication with OAuth 2.0 Source: https://context7.com/twilio/twilio-ruby/llms.txt Demonstrates client authentication using the OAuth 2.0 Client Credentials flow, suitable for token-based authentication. This method is currently in beta. ```ruby require 'twilio-ruby' require 'twilio-ruby/credential/client_credential_provider' # Create credential provider with OAuth client credentials credential_provider = Twilio::REST::ClientCredentialProvider.new( ENV['CLIENT_ID'], ENV['CLIENT_SECRET'] ) # Initialize client with credential provider client = Twilio::REST::Client.new(ENV['ACCOUNT_SID']) .credential_provider(credential_provider) # Send a message using OAuth authentication message = client.messages.create( from: ENV['TWILIO_PHONE_NUMBER'], to: ENV['PHONE_NUMBER'], body: 'Hello from OAuth!' ) puts message.sid # => "SMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ``` -------------------------------- ### Manage Twilio Accounts and Subaccounts Source: https://context7.com/twilio/twilio-ruby/llms.txt Demonstrates how to list all accounts, create new subaccounts, update friendly names, and change account status to suspended or closed using the Twilio Ruby client. ```ruby # List all accounts (including subaccounts) @client.api.accounts.list.each do |acct| puts "#{acct.sid}: #{acct.friendly_name} (#{acct.status})" end # Create a subaccount subaccount = @client.api.accounts.create( friendly_name: 'Customer ABC Subaccount' ) puts "Subaccount SID: #{subaccount.sid}" # Update account friendly name @client.api.accounts(subaccount.sid).update( friendly_name: 'Customer ABC - Updated' ) # Suspend a subaccount @client.api.accounts(subaccount.sid).update(status: 'suspended') # Close a subaccount (permanent) @client.api.accounts(subaccount.sid).update(status: 'closed') ``` -------------------------------- ### Twilio Client Authentication with Account SID and Auth Token Source: https://context7.com/twilio/twilio-ruby/llms.txt Initializes the Twilio client using Account SID and Auth Token credentials from the Twilio Console. This is the standard method for authenticating API requests. ```ruby require 'twilio-ruby' # Initialize with Account SID and Auth Token account_sid = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' auth_token = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy' @client = Twilio::REST::Client.new(account_sid, auth_token) # The client is now ready to make API calls puts @client.account_sid # => "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/twilio/twilio-ruby/blob/main/README.md Shows how to configure the Twilio client to log API activity by attaching a Ruby Logger instance set to DEBUG level. ```ruby @client = Twilio::REST::Client.new account_sid, auth_token myLogger = Logger.new(STDOUT) myLogger.level = Logger::DEBUG @client.logger = myLogger ``` -------------------------------- ### Make Outbound Voice Calls with Twilio Ruby Source: https://context7.com/twilio/twilio-ruby/llms.txt Shows how to initiate outbound phone calls using either a TwiML URL or inline TwiML instructions. ```ruby require 'twilio-ruby' @client = Twilio::REST::Client.new('ACxxx', 'auth_token') # Make a call with TwiML URL call = @client.calls.create( from: '+15017122661', to: '+15558675310', url: 'http://example.com/twiml/voice-response.xml' ) puts "Call SID: #{call.sid}" puts "Status: #{call.status}" puts "Direction: #{call.direction}" # Make a call with inline TwiML call = @client.calls.create( from: '+15017122661', to: '+15558675310', twiml: 'Hello from Twilio!' ) ``` -------------------------------- ### Authenticate Twilio Client with API Key Source: https://github.com/twilio/twilio-ruby/blob/main/README.md Ruby code to initialize the Twilio REST client using an API Key SID, API Key Secret, and Account SID. ```ruby require 'twilio-ruby' # Your Account SID from console.twilio.com account_sid = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # API Key from twilio.com/console/project/api-keys api_key_sid = 'zzzzzzzzzzzzzzzzzzzzzz' api_key_secret = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy' # set up a client to talk to the Twilio REST API using an API Key @client = Twilio::REST::Client.new api_key_sid, api_key_secret, account_sid ``` -------------------------------- ### Managing Instance Resources Source: https://github.com/twilio/twilio-ruby/wiki/documentation/REST Retrieve specific instance resources to access their properties, update their configuration, or delete them from the Twilio account. ```ruby @incoming_numbers = @client.api.incoming_phone_numbers @number = @incoming_numbers('PNxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') print @number.voice_url @number.update( :voice_url => 'http://yourapp.com/new_call_handler', :sms_url => 'http://yourapp.com/new_sms_handler' ) @caller_ids = @client.api.outgoing_caller_ids @caller_ids('PNxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx').delete ``` -------------------------------- ### Constructing a TwiML Voice Response Source: https://github.com/twilio/twilio-ruby/wiki/documentation/TwiML This snippet demonstrates how to initialize a VoiceResponse object and use block syntax to nest TwiML verbs like 'say' and 'dial'. The resulting object can be serialized to an XML string for use in Twilio webhooks. ```ruby require 'twilio-ruby' response = Twilio::TwiML::VoiceResponse.new do |r| r.say(message: 'hello there', voice: 'alice') r.dial(caller_id: '+14159992222') do |d| d.client(identity: 'Jenny') end end puts response.to_s ``` ```xml hello there jenny ``` -------------------------------- ### Accessing API Resources Source: https://github.com/twilio/twilio-ruby/wiki/documentation/REST Navigate the API resource hierarchy by chaining methods on the client instance to reach specific list or instance resources. ```ruby @calls = @client.api.v2010.calls @participants = @client.api.v2010.conferences('a_conference_sid').participants ``` -------------------------------- ### Manage Twilio Accounts and Subaccounts with Ruby Source: https://context7.com/twilio/twilio-ruby/llms.txt This code snippet demonstrates how to interact with your main Twilio account and manage subaccounts. It shows how to fetch account information, such as the friendly name, status, and type of your account. ```ruby require 'twilio-ruby' # Initialize the Twilio client # @client = Twilio::REST::Client.new('ACxxx', 'auth_token') # Get your account info account = @client.api.account.fetch puts "Account: #{account.friendly_name}" puts "Status: #{account.status}" puts "Type: #{account.type}" ``` -------------------------------- ### Serverless - Node.js 18 Runtime Source: https://github.com/twilio/twilio-ruby/blob/main/CHANGES.md Adds Node.js 18 as a valid runtime for Serverless builds. ```APIDOC ## Serverless Build Runtimes ### Description Node.js 18 is now supported as a valid runtime environment for Serverless builds. ### Method N/A (Configuration update) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### API - Create Participant API Optional Parameter Source: https://github.com/twilio/twilio-ruby/blob/main/CHANGES.md Adds an optional `clientNotificationUrl` parameter to the create participant API. ```APIDOC ## POST /2010-04-01/Accounts/{accountSid}/Calls/{callSid}/Participants.json ### Description Adds a participant to a call. An optional `clientNotificationUrl` can be provided. ### Method POST ### Endpoint /2010-04-01/Accounts/{accountSid}/Calls/{callSid}/Participants.json ### Parameters #### Path Parameters - **accountSid** (string) - Required - The account SID. - **callSid** (string) - Required - The call SID. #### Request Body - **to** (string) - Required - The phone number to add as a participant. - **from** (string) - Required - The phone number to add from. - **url** (string) - Required - The URL TwiML instructions for the participant. - **clientNotificationUrl** (string) - Optional - The URL to send participant status notifications to. ### Response #### Success Response (201) - **sid** (string) - The unique ID of the participant. - **status** (string) - The status of the participant. #### Response Example ```json { "sid": "PA123", "status": "ringing" } ``` ``` -------------------------------- ### Handle API Exceptions Source: https://github.com/twilio/twilio-ruby/blob/main/README.md Demonstrates wrapping API calls in a begin-rescue block to catch and handle Twilio::REST::RestError exceptions. ```ruby begin messages = @client.messages.list(limit: 20) rescue Twilio::REST::RestError => e puts e.message end ``` -------------------------------- ### Collect User Input via TwiML Gather Source: https://context7.com/twilio/twilio-ruby/llms.txt Configures TwiML to collect DTMF tones or speech input from callers. Includes fallback logic if no input is received. ```ruby require 'twilio-ruby' response = Twilio::TwiML::VoiceResponse.new do |r| r.gather( input: 'dtmf speech', action: '/handle-input', method: 'POST', timeout: 5, num_digits: 1, language: 'en-US', hints: 'sales, support, billing' ) do |gather| gather.say(message: 'Press 1 for sales, 2 for support, or say your request.') end # Fallback if no input received r.say(message: 'We did not receive any input. Goodbye!') end puts response.to_s ``` -------------------------------- ### Verify - Verification Creation Parameter Source: https://github.com/twilio/twilio-ruby/blob/main/CHANGES.md Adds an optional `Tags` parameter to Verification creation requests. ```APIDOC ## POST /v2/Services/{ServiceSid}/Verifications ### Description When creating a Verification, you can now include an optional `Tags` parameter to categorize your verifications. ### Method POST ### Endpoint /v2/Services/{ServiceSid}/Verifications ### Parameters #### Path Parameters - **ServiceSid** (string) - Required - The SID of the service. #### Query Parameters None #### Request Body - **To** (string) - Required - The phone number or email address to verify. - **Channel** (string) - Required - The channel to use for verification (e.g., 'sms', 'email', 'call'). - **Tags** (array of strings) - Optional - An array of tags to associate with the verification. ### Request Example ```json { "To": "+15558675310", "Channel": "sms", "Tags": ["onboarding", "new_user"] } ``` ### Response #### Success Response (201) Returns the created verification object. #### Response Example ```json { "sid": "VExxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "account_sid": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "service_sid": "VAxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "to": "+15558675310", "channel": "sms", "tags": ["onboarding", "new_user"], "status": "pending", "date_created": "2024-01-25T10:00:00Z" } ``` ``` -------------------------------- ### Record Calls with TwiML Source: https://context7.com/twilio/twilio-ruby/llms.txt Configures TwiML to record caller audio, including options for transcription, silence trimming, and status callbacks. ```ruby require 'twilio-ruby' response = Twilio::TwiML::VoiceResponse.new do |r| r.say(message: 'Please leave a message after the beep.', voice: 'alice') r.record( action: '/handle-recording', method: 'POST', max_length: 120, timeout: 10, finish_on_key: '#', play_beep: true, trim: 'trim-silence', transcribe: true, transcribe_callback: '/transcription-complete', recording_status_callback: '/recording-status' ) r.say(message: 'I did not receive a recording. Goodbye!') end puts response.to_s ``` -------------------------------- ### Make a Phone Call Source: https://github.com/twilio/twilio-ruby/blob/main/README.md Uses the Twilio client to initiate a voice call by providing the from, to, and callback URL parameters. ```ruby @client.calls.create( from: '+14159341234', to: '+16105557069', url: 'http://example.com' ) ``` -------------------------------- ### Verify API - Phone Verification Source: https://context7.com/twilio/twilio-ruby/llms.txt Demonstrates how to create and manage phone number verifications using the Twilio Verify API. This includes creating a verification service and sending verification codes via SMS (or other channels). ```ruby require 'twilio-ruby' @client = Twilio::REST::Client.new('ACxxx', 'auth_token') # Create a Verify Service service = @client.verify.v2.services.create( friendly_name: 'My Verification Service', code_length: 6, lookup_enabled: true, do_not_share_warning_enabled: true ) service_sid = service.sid puts "Service SID: #{service_sid}" # Send a verification code via SMS verification = @client.verify.v2 .services(service_sid) .verifications .create( to: '+15558675310', channel: 'sms' # or 'call', 'email', 'whatsapp' ) puts "Verification Status: #{verification.status}" # => Verification Status: pending ``` -------------------------------- ### API - Create Call API Optional Parameter Source: https://github.com/twilio/twilio-ruby/blob/main/CHANGES.md Adds an optional `clientNotificationUrl` parameter to the create call API. ```APIDOC ## POST /2010-04-01/Accounts/{accountSid}/Calls.json ### Description Creates a new call. An optional `clientNotificationUrl` can be provided. ### Method POST ### Endpoint /2010-04-01/Accounts/{accountSid}/Calls.json ### Parameters #### Path Parameters - **accountSid** (string) - Required - The account SID. #### Request Body - **to** (string) - Required - The phone number to call. - **from** (string) - Required - The phone number to call from. - **url** (string) - Required - The URL TwiML instructions. - **clientNotificationUrl** (string) - Optional - The URL to send call status notifications to. ### Response #### Success Response (201) - **sid** (string) - The unique ID of the call. - **status** (string) - The status of the call. #### Response Example ```json { "sid": "CA123", "status": "queued" } ``` ```