Giter Club home page Giter Club logo

plivo-go's Introduction

plivo-go

Build, Unit Tests, Linters Status codecov Go Report Card GoDoc

The Plivo Go SDK makes it simpler to integrate communications into your Go applications using the Plivo REST API. Using the SDK, you will be able to make voice calls, send messages and generate Plivo XML to control your call flows.

Prerequisites

  • Go >= 1.13.x

Getting started

The steps described below uses go modules.

Create a new project (optional)
$ mkdir ~/helloplivo
$ cd ~/helloplivo
$ go mod init helloplivo

This will generate a go.mod and go.sum file.

Add plivo-go as a dependency to your project
$ go get github.com/plivo/plivo-go/v7

Authentication

To make the API requests, you need to create a Client and provide it with authentication credentials (which can be found at https://manage.plivo.com/dashboard/).

We recommend that you store your credentials in the PLIVO_AUTH_ID and the PLIVO_AUTH_TOKEN environment variables, so as to avoid the possibility of accidentally committing them to source control. If you do this, you can initialise the client with no arguments and it will automatically fetch them from the environment variables:

package main

import "github.com/plivo/plivo-go/v7"

func main()  {
	client, err := plivo.NewClient("", "", &plivo.ClientOptions{})
	if err != nil {
		panic(err)
	}
}

Alternatively, you can specifiy the authentication credentials while initializing the Client.

package main

import "github.com/plivo/plivo-go/v7"

func main()  {
	client, err := plivo.NewClient("<auth-id>", "<auth-token>", &plivo.ClientOptions{})
	if err != nil {
		panic(err)
	}
}

The Basics

The SDK uses consistent interfaces to create, retrieve, update, delete and list resources. The pattern followed is as follows:

client.Resources.Create(Params{}) // Create
client.Resources.Get(Id) // Get
client.Resources.Update(Id, Params{}) // Update
client.Resources.Delete(Id) // Delete
client.Resources.List() // List all resources, max 20 at a time

Using client.Resources.List() would list the first 20 resources by default (which is the first page, with limit as 20, and offset as 0). To get more, you will have to use limit and offset to get the second page of resources.

Examples

Send a message

package main

import "github.com/plivo/plivo-go/v7"

func main() {
	client, err := plivo.NewClient("", "", &plivo.ClientOptions{})
	if err != nil {
		panic(err)
	}
	client.Messages.Create(plivo.MessageCreateParams{
		Src:  "the_source_number",
		Dst:  "the_destination_number",
		Text: "Hello, world!",
	})
}

Make a call

package main

import "github.com/plivo/plivo-go/v7"

func main() {
	client, err := plivo.NewClient("", "", &plivo.ClientOptions{})
	if err != nil {
		panic(err)
	}
	client.Calls.Create(plivo.CallCreateParams{
		From:      "the_source_number",
		To:        "the_destination_number",
		AnswerURL: "http://answer.url",
	})
}

Lookup a number

package main

import (
	"fmt"
	"log"

	"github.com/plivo/plivo-go/v7"
)

func main() {
	client, err := plivo.NewClient("<auth-id>", "<auth-token>", &plivo.ClientOptions{})
	if err != nil {
		log.Fatalf("plivo.NewClient() failed: %s", err.Error())
	}

	resp, err := client.Lookup.Get("<insert-number-here>", plivo.LookupParams{})
	if err != nil {
		if respErr, ok := err.(*plivo.LookupError); ok {
			fmt.Printf("API ID: %s\nError Code: %d\nMessage: %s\n",
				respErr.ApiID, respErr.ErrorCode, respErr.Message)
			return
		}
		log.Fatalf("client.Lookup.Get() failed: %s", err.Error())
	}

	fmt.Printf("%+v\n", resp)
}

Generate Plivo XML

package main

import "github.com/plivo/plivo-go/v7/xml"

func main() {
	println(xml.ResponseElement{
		Contents: []interface{}{
			new(xml.SpeakElement).SetContents("Hello, world!"),
		},
	}.String())
}

This generates the following XML:

<Response>
  <Speak>Hello, world!</Speak>
</Response>

Run a PHLO

package main

import (
	"fmt"
	"github.com/plivo/plivo-go/v7"
)

// Initialize the following params with corresponding values to trigger resources

const authId = "auth_id"
const authToken = "auth_token"
const phloId = "phlo_id"

// with payload in request

func main() {
	testPhloRunWithParams()
}

func testPhloRunWithParams() {
	phloClient, err := plivo.NewPhloClient(authId, authToken, &plivo.ClientOptions{})
	if err != nil {
		panic(err)
	}
	phloGet, err := phloClient.Phlos.Get(phloId)
	if err != nil {
		panic(err)
	}
	//pass corresponding from and to values
	type params map[string]interface{}
	response, err := phloGet.Run(params{
		"from": "111111111",
		"to":   "2222222222",
	})

	if err != nil {
		println(err)
	}
	fmt.Printf("Response: %#v\n", response)
}

More examples

Refer to the Plivo API Reference for more examples.

Local Development

Note: Requires latest versions of Docker & Docker-Compose. If you're on MacOS, ensure Docker Desktop is running.

  1. Export the following environment variables in your host machine:
export PLIVO_AUTH_ID=<your_auth_id>
export PLIVO_AUTH_TOKEN=<your_auth_token>
export PLIVO_API_DEV_HOST=<plivoapi_dev_endpoint>
export PLIVO_API_PROD_HOST=<plivoapi_public_endpoint>
  1. Run make build. This will create a docker container in which the sdk will be setup and dependencies will be installed.

The entrypoint of the docker container will be the setup_sdk.sh script. The script will handle all the necessary changes required for local development.

  1. The above command will print the docker container id (and instructions to connect to it) to stdout.
  2. The testing code can be added to <sdk_dir_path>/go-sdk-test/test.go in host
    (or /usr/src/app/go-sdk-test/test.go in container)
  3. The sdk directory will be mounted as a volume in the container. So any changes in the sdk code will also be reflected inside the container.
  4. To run test code, run make run CONTAINER=<cont_id> in host.
  5. To run unit tests, run make test CONTAINER=<cont_id> in host.

<cont_id> is the docker container id created in 2.
(The docker container should be running)

Test code and unit tests can also be run within the container using make run and make test respectively. (CONTAINER argument should be omitted when running from the container)

plivo-go's People

Contributors

abinaya-shunmugavel avatar abrolnalin avatar ajay-kg avatar ajay-plivo avatar anukul avatar bhuvanvenkat-plivo avatar govinda-plivo avatar harika245 avatar huzaif-plivo avatar kalyan-plivo avatar kartik-plivo avatar koushik-ayila avatar kritarth-plivo avatar kunal-plivo avatar lsaitharun avatar manas-plivo avatar manish-plivo avatar mohsin-plivo avatar narayana-plivo avatar nirmitijain avatar nixonsam avatar plivo-sdks avatar ppai-plivo avatar prashantp-plivo avatar rajneeshkatkam-plivo avatar shubham-plivo avatar sreyantha-plivo avatar suuhas avatar varshit97plivo avatar vishesh-plivo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

plivo-go's Issues

Polly.Marlene is missing

Hello

in the getLanguageVoices() function the second female german voice Marlene is missing.

Best regards
Alex

xml: Unit test does not compile

Reproduce:

$ cd xml
$ go test
# github.com/plivo/plivo-go/xml [github.com/plivo/plivo-go/xml.test]
./plivoxml_test.go:34: new(SpeakElement).SetContents undefined (type *SpeakElement has no field or method SetContents)
FAIL	github.com/plivo/plivo-go/xml [build failed]

stable is broken oob

go get github.com/plivo/plivo-go

github.com/plivo/plivo-go

../../../go/src/github.com/plivo/plivo-go/plivoclient.go:34:16: undefined: AddressService
../../../go/src/github.com/plivo/plivo-go/plivoclient.go:35:16: undefined: IdentityService

The "total_rate" field is not exposed in the Call struct

The Call struct does not expose a field for accessing the total_rate, which is returned by the REST API (as documented here).
I was hoping to access this field after retrieving a Call instance from the CallService.Get method.

Is it possible to have this field added to the struct?

Error while instaliing

../../go/src/github.com/plivo/plivo-go/plivoclient.go:34:16: undefined: AddressService
../../go/src/github.com/plivo/plivo-go/plivoclient.go:35:16: undefined: IdentityService
I get this when I try to install plvio-go

mac: file name collisions

prashanthpai@Prashanths-Mac: sdk-debug  $ git clone [email protected]:plivo/plivo-go.git
Cloning into 'plivo-go'...
Enter passphrase for key '/Users/prashanthpai/.ssh/id_rsa_work':
remote: Enumerating objects: 1633, done.
remote: Counting objects: 100% (345/345), done.
remote: Compressing objects: 100% (220/220), done.
remote: Total 1633 (delta 182), reused 200 (delta 106), pack-reused 1288
Receiving objects: 100% (1633/1633), 390.43 KiB | 601.00 KiB/s, done.
Resolving deltas: 100% (939/939), done.
warning: the following paths have collided (e.g. case-sensitive paths
on a case-insensitive filesystem) and only one from the same
colliding group is in the working tree:

  'fixtures/MediaGetResponse.json'
  'fixtures/mediaGetResponse.json'
  'fixtures/MediaListResponse.json'
  'fixtures/mediaListResponse.json'
  'fixtures/MPCAddParticipantResponse.json'
  'fixtures/mPCAddParticipantResponse.json'
  'fixtures/MPCGetParticipantResponse.json'
  'fixtures/mPCGetParticipantResponse.json'
  'fixtures/MPCGetResponse.json'
  'fixtures/mPCGetResponse.json'
  'fixtures/MPCListParticipantsResponse.json'
  'fixtures/mPCListParticipantsResponse.json'
  'fixtures/MPCListResponse.json'
  'fixtures/mPCListResponse.json'
  'fixtures/MPCStartRecordResponse.json'
  'fixtures/mPCStartRecordResponse.json'
  'fixtures/MPCUpdateParticipantResponse.json'
  'fixtures/mPCUpdateParticipantResponse.json'

Creating SMS not working

Hi, As of ~12am 11 Nov 2020, began experiencing an issue where any attempts to use client.Messages.Create returns an error: temporary failure. Everything was working as expected before that estimated time provided above.

Have tried sending SMS messages outside of this SDK via http client, and sms was sent successfully. Also, started a new project with the most basic code required to send sms:

package main

import (
	"github.com/plivo/plivo-go"
	"log"
)

func main()  {
	client, err := plivo.NewClient("<redacted>", "<redacted>", &plivo.ClientOptions{})
	if err != nil {
		panic(err)
	}
	resp, err := client.Messages.Create(plivo.MessageCreateParams{
		Src: "<redacted>",
		Dst: "<redacted>",
		Text: "Hello, world!",
	})

	log.Println(resp, err)
}

and seeing this logged out: 2020/11/11 12:49:31 &{ [] } temporary failure

lint: base_resources.go: Fix structcheck/unused check

Steps to reproduce:

  1. Enable structcheck and unused linters by editing .golangci.yml file:
$ git diff
diff --git a/.golangci.yml b/.golangci.yml
index b85db5a..ca0deb1 100644
--- a/.golangci.yml
+++ b/.golangci.yml
@@ -1,7 +1,5 @@
 linters:
   disable:
     - errcheck
-    - structcheck
-    - unused
   enable:
     - misspell
  1. Run golangci-lint:
$ golangci-lint run
base_resources.go:11:2: `client` is unused (structcheck)
	client       *PhloClient
	^
base_resources.go:12:2: `resourceType` is unused (structcheck)
	resourceType BaseResource // Todo: Need this?
	^

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.