Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Python code examples for using Vonage communications APIs

License

NotificationsYou must be signed in to change notification settings

Vonage/vonage-python-code-snippets

Repository files navigation

AuthorIssuesLicenseStarsForksLast CommitSize

The purpose of these Code Snippets is to provide simple examples focusedon one goal. For example, sending an SMS, creating a Vonage Video API session, handling an incoming webhook, or making a Text-to-Speech call.

Table of Contents

Setup

These code samples are meant to be embedded into pages onhttps://developer.vonage.com/. Developers are free to use these code snippets as a reference, but these may require changes to be worked into your specific application. We recommend checking out theVonage Developer Website, which displays these code snippets in a more copy/paste fashion.

To use the examples, you will first need aVonage account. Then renamethe.env.dist file to.env and set the values as required.

For some of the examples you will need tobuy a number.

Running the Examples

If you would like to run these examples yourself, you will need to do the following:

Use a virtual environment:

# Create the virtual environmentpython3 -m venv venv# Activate the virtual environment in Mac/Linux. ./venv/bin/activate# Or on Windows Command Promptvenv\Scripts\activate

Install the dependencies:

pip install -r requirements.txt

Run the code:

For samples that don't use a web server, run with python, e.g.

python sms/send-an-sms.py

For samples that require a web server, run with FastAPI, e.g.

fastapi dev messages/inbound-message.py

SDK Structure

The SDK is a monorepo - lots of packages in a single place. In the SDK, we have:

  1. The top-level packagevonage, which pulls in all the other packages you need.
  2. A package referring to every API supported in the SDK (vonage-sms,vonage-voice,vonage-video etc.)
  3. Internal packages for making HTTP requests, creating JWTs etc. (vonage-http-client,vonage-jwt etc.)
  4. A utilities package (vonage-utils)

There are important things to note:

  1. Thevonage package instantiates each of the API packages. For example, you can callvonage.voice.any_method_from_the_voice_class. This means you don’t have to instantiate packages that you need separately.
  2. Many of the APIs require input data from the user. This is passed in through data models that you will find in the package for the specific API you want to call. This was intentional so the user doesn’t immediately import every data model from every single API whenever they import the top-level package, which would make it harder to find what is actually needed in an IDE, and allows for models with the same names in different namespaces.

For example, to use aVerifyRequest object from thevonage-verify package, you’ll need to first import thevonage package to get theAuth object and theVerify methods, then importVerifyRequest from thevonage-verify package, like so:

fromvonageimportAuth,Vonagefromvonage_verifyimportVerifyRequest,SmsChannelclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_APPLICATION_PRIVATE_KEY_PATH,))verify_request=VerifyRequest(brand=BRAND_NAME,workflow=[SmsChannel(to=TO_NUMBER),],)response=vonage_client.verify.start_verification(verify_request)

This is explained in more detail in the blog post shared above. You can also find full, working examplesin the Python Code Snippets repo.

Getting the Objects You Need Into Your Namespace

If you’re working with e.g. the Voice API, if you know you’re likely to use many of the data models, you can import them all into your app’s namespace (making it easier for your autocomplete etc. to find them) with the* operator, e.g.

fromvonage_voiceimport*request=CreateCallRequest(...)

It’s usually considered better practice to import just what you need, but using this method means the data models will all be available to you if you need to do some quick testing.

How the SDK handles errors

The Vonage Python SDK has various different classes of errors:

  • Some regular Python/package errors that can be raised during the course of SDK operation
  • The top-levelVonageError, that custom SDK errors inherit from
  • Errors raised when using some packages, e.g.VerifyError
  • Errors raised by the HTTP client

It’s likely that when troubleshooting, you’ll especially see HTTP request errors, so let’s discuss these.

HTTP Request Errors

This is a class of errors raised when actually making the HTTP request or when receiving an HTTP response.

The high-level error here is theHttpRequestError. There are other errors which are based on this and have the same properties, but different names that are more specific tothe HTTP status code received from the Vonage server, e.g. anAuthenticationError or aNotFoundError.

Each error of this type has properties that can be accessed when the error is caught, i.e. if you have a try-except block which catches an error, you can then access the error message and the response object which has additional information. This can be useful for debugging.

To catch an error in this way, do this:

try:vonage_client.call_vonage_api(...)exceptHttpRequestErrorase:print(‘Requestfailed:’)print(e.message)print(e.response.text)

You can access any information about the request or the response from thee.response object.

Troubleshooting

Viewing the last request and response

Whether or not an HTTP request was successful, you can access the last request and response sent by accessing the relevant HTTP client attributes like this:

vonage_client.http_client.last_requestvonage_client.http_client.last_response

For example, to see the last request body and headers sent by the SDK, you can do:

print(vonage_client.http_client.last_request.body)print(vonage_client.http_client.last_request.headers)

Authentication errors

If the SDK returns anAuthenticationError, this is because the Vonage Server was not able to authenticate the SDK user. In this case, you should check the authentication details that were provided.

Useful Resources

Request an Example

Pleaseraise an issue to request an example that isn't present within the quickstart. Pull requests will be gratefully received.

License

MIT

Python Code Snippets

This is a list of all supported Python code snippets in the repo, organised by category.

Table of Contents

Account

Snippets in this Section

Configure Account

fromvonageimportAuth,Vonagefromvonage_accountimportSettingsResponseclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))settings:SettingsResponse=client.account.update_default_sms_webhook(mo_callback_url=ACCOUNT_SMS_CALLBACK_URL)print(settings)

Create Secret

fromvonageimportAuth,Vonagefromvonage_accountimportVonageApiSecretclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))response:VonageApiSecret=client.account.create_secret(ACCOUNT_SECRET)print(response)

Fetch A Secret

fromvonageimportAuth,Vonagefromvonage_accountimportVonageApiSecretclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))secret:VonageApiSecret=client.account.get_secret(ACCOUNT_SECRET_ID)print(f'Secret ID:{secret.id}; Created at{secret.created_at}')

Get Balance

fromvonageimportAuth,Vonagefromvonage_accountimportBalanceclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))balance:Balance=client.account.get_balance()print(f'{balance.value:0.2f} EUR, auto-reload:{balance.auto_reload}')

List All Secrets

fromvonageimportAuth,Vonagefromvonage_accountimportVonageApiSecretclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))response:list[VonageApiSecret]=client.account.list_secrets()print(response)

Revoke Secret

fromvonageimportAuth,Vonageclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))client.account.revoke_secret(ACCOUNT_SECRET_ID)

Application

Snippets in this Section

Create Application

fromvonageimportAuth,Vonagefromvonage_applicationimport (ApplicationConfig,ApplicationData,ApplicationUrl,Capabilities,Messages,MessagesWebhooks,Region,Verify,VerifyWebhooks,Voice,VoiceUrl,VoiceWebhooks)client=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))# Voice application optionsvoice=Voice(webhooks=VoiceWebhooks(answer_url=VoiceUrl(address='https://example.com/answer',http_method='POST',connect_timeout=500,socket_timeout=3000,        ),fallback_answer_url=VoiceUrl(address='https://example.com/fallback',http_method='POST',connect_timeout=500,socket_timeout=3000,        ),event_url=VoiceUrl(address='https://example.com/event',http_method='POST',connect_timeout=500,socket_timeout=3000,        ),    ),signed_callbacks=True,conversations_ttl=8000,leg_persistence_time=14,region=Region.NA_EAST,)# Messages application optionsmessages=Messages(version='v1',webhooks=MessagesWebhooks(inbound_url=ApplicationUrl(address='https://example.com/inbound',http_method='POST'        ),status_url=ApplicationUrl(address='https://example.com/status',http_method='POST'        ),    ),authenticate_inbound_media=True,)# Verify application optionsverify=Verify(webhooks=VerifyWebhooks(status_url=ApplicationUrl(address='https://example.com/status',http_method='GET')    ),)# Set the application capabilitiescapabilities=Capabilities(voice=voice,messages=messages,verify=verify)# Set the application configuration that will be appliedparams=ApplicationConfig(name='My Custom Application',capabilities=capabilities,)# Call the APIresponse:ApplicationData=client.application.create_application(params)print(response)

Delete Application

fromvonageimportAuth,Vonageclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))client.application.delete_application(VONAGE_APPLICATION_ID)

Get Application

fromvonageimportAuth,Vonagefromvonage_applicationimportApplicationDataclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))response:ApplicationData=client.application.get_application(VONAGE_APPLICATION_ID)print(response)

List Applications

fromvonageimportAuth,Vonagefromvonage_applicationimportListApplicationsFilterclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))applications,next_page=client.application.list_applications(filter=ListApplicationsFilter(page_size=10,page=1))pprint(f'Applications:\n{applications},\nNext page:{next_page}')

Update Application

fromvonageimportAuth,Vonagefromvonage_applicationimport (ApplicationConfig,ApplicationData,ApplicationUrl,Messages,MessagesWebhooks)client=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))config=ApplicationConfig(name='My Renamed Application',capabilities=Messages(webhooks=MessagesWebhooks(inbound_url=ApplicationUrl(address='https://example.com/inbound_new_url',http_method='GET'            ),status_url=ApplicationUrl(address='https://example.com/status_new_url',http_method='GET'            ),        ),authenticate_inbound_media=False,    ),)response:ApplicationData=client.application.update_application(id=VONAGE_APPLICATION_ID,config=config)print(response)

Decode Jwt

Snippets in this Section

Decode Jwt

importosfromos.pathimportdirname,joinfromdotenvimportload_dotenv# Load the environmentenvpath=join(dirname(__file__),'../.env')load_dotenv(envpath)VONAGE_SIGNATURE_SECRET=os.getenv('VONAGE_SIGNATURE_SECRET')fromfastapiimportFastAPI,Requestfromvonage_jwt.verify_jwtimportverify_signatureapp=FastAPI()@app.get('/events')asyncdefverify_signed_webhook(request:Request):# Need to get the JWT after "Bearer " in the authorization headerauth_header=request.headers["authorization"].split()token=auth_header[1].strip()ifverify_signature(token,VONAGE_SIGNATURE_SECRET):print('Valid signature')else:print('Invalid signature')

Messages

Snippets in this Section

Inbound Message

frompprintimportpprintfromfastapiimportFastAPI,Requestapp=FastAPI()@app.post('/webhooks/inbound-message')asyncdefinbound_message(request:Request):data=awaitrequest.json()pprint(data)

Message Status

frompprintimportpprintfromfastapiimportFastAPI,Request,statusapp=FastAPI()@app.post('/webhooks/message-status',status_code=status.HTTP_200_OK)asyncdefmessage_status(request:Request):data=awaitrequest.json()pprint(data)

Messenger Send Audio

fromvonageimportAuth,Vonagefromvonage_messagesimportMessengerAudio,MessengerResourceclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=MessengerAudio(to=MESSENGER_RECIPIENT_ID,from_=MESSENGER_SENDER_ID,audio=MessengerResource(url=MESSAGES_AUDIO_URL),)response=client.messages.send(message)print(response)

Messenger Send File

fromvonageimportAuth,Vonagefromvonage_messagesimportMessengerFile,MessengerResourceclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=MessengerFile(to=MESSENGER_RECIPIENT_ID,from_=MESSENGER_SENDER_ID,file=MessengerResource(url=MESSAGES_FILE_URL),)response=client.messages.send(message)print(response)

Messenger Send Image

fromvonageimportAuth,Vonagefromvonage_messagesimportMessengerImage,MessengerResourceclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=MessengerImage(to=MESSENGER_RECIPIENT_ID,from_=MESSENGER_SENDER_ID,image=MessengerResource(url=MESSAGES_IMAGE_URL),)response=client.messages.send(message)print(response)

Messenger Send Text

fromvonageimportAuth,Vonagefromvonage_messagesimportMessengerTextclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=MessengerText(to=MESSENGER_RECIPIENT_ID,from_=MESSENGER_SENDER_ID,text='Hello from the Vonage Messages API.',)try:response=client.messages.send(message)print(response)exceptExceptionase:print(e)print(client.http_client.last_request.url)

Messenger Send Video

fromvonageimportAuth,Vonagefromvonage_messagesimportMessengerResource,MessengerVideoclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=MessengerVideo(to=MESSENGER_RECIPIENT_ID,from_=MESSENGER_SENDER_ID,video=MessengerResource(url=MESSAGES_VIDEO_URL),)response=client.messages.send(message)print(response)

Mms Send Audio

fromvonageimportAuth,Vonagefromvonage_messagesimportMmsAudio,MmsResourceclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=MmsAudio(to=MESSAGES_TO_NUMBER,from_=MMS_SENDER_ID,audio=MmsResource(url=MESSAGES_AUDIO_URL),)response=client.messages.send(message)print(response)

Mms Send Image

fromvonageimportAuth,Vonagefromvonage_messagesimportMmsImage,MmsResourceclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=MmsImage(to=MESSAGES_TO_NUMBER,from_=MMS_SENDER_ID,image=MmsResource(url=MESSAGES_IMAGE_URL),)response=client.messages.send(message)print(response)

Mms Send Vcard

fromvonageimportAuth,Vonagefromvonage_messagesimportMmsResource,MmsVcardclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=MmsVcard(to=MESSAGES_TO_NUMBER,from_=MMS_SENDER_ID,vcard=MmsResource(url=MESSAGES_VCARD_URL),)response=client.messages.send(message)print(response)

Mms Send Video

fromvonageimportAuth,Vonagefromvonage_messagesimportMmsResource,MmsVideoclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=MmsVideo(to=MESSAGES_TO_NUMBER,from_=MMS_SENDER_ID,video=MmsResource(url=MESSAGES_VIDEO_URL),)response=client.messages.send(message)print(response)

Rcs Revoke Message

fromvonageimportAuth,Vonageclient=Vonage(auth=Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))response=client.messages.revoke_rcs_message(MESSAGES_MESSAGE_ID)print(response)

Rcs Send File

fromvonageimportAuth,Vonagefromvonage_messagesimportRcsFile,RcsResourceclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=RcsFile(to=MESSAGES_TO_NUMBER,from_=RCS_SENDER_ID,file=RcsResource(url=MESSAGES_FILE_URL),)response=client.messages.send(message)print(response)

Rcs Send Image

fromvonageimportAuth,Vonagefromvonage_messagesimportRcsImage,RcsResourceclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=RcsImage(to=MESSAGES_TO_NUMBER,from_=RCS_SENDER_ID,image=RcsResource(url=MESSAGES_IMAGE_URL),)response=client.messages.send(message)print(response)

Rcs Send Rich Card Carousel

fromvonageimportAuth,Vonagefromvonage_messagesimportRcsCustomclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))custom_dict= {"contentMessage": {"richCard": {"carouselCard": {"cardWidth":"MEDIUM","cardContents": [                    {"title":"Option 1: Photo","description":"Do you prefer this photo?","suggestions": [                            {"reply": {"text":"Option 1","postbackData":"card_1",                                }                            }                        ],"media": {"height":"MEDIUM","contentInfo": {"fileUrl":MESSAGES_IMAGE_URL,"forceRefresh":"false",                            },                        },                    },                    {"title":"Option 2: Video","description":"Or this video?","suggestions": [                            {"reply": {"text":"Option 2","postbackData":"card_2",                                }                            }                        ],"media": {"height":"MEDIUM","contentInfo": {"fileUrl":MESSAGES_VIDEO_URL,"forceRefresh":"false",                            },                        },                    },                ],            }        }    }}message=RcsCustom(to=MESSAGES_TO_NUMBER,from_=RCS_SENDER_ID,custom=custom_dict,)response=client.messages.send(message)print(response)

Rcs Send Rich Card Standalone

fromvonageimportAuth,Vonagefromvonage_messagesimportRcsCustomclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))custom_dict= {"contentMessage": {"richCard": {"standaloneCard": {"thumbnailImageAlignment":"RIGHT","cardOrientation":"VERTICAL","cardContent": {"title":"Quick question","description":"Do you like this picture?","media": {"height":"TALL","contentInfo": {"fileUrl":MESSAGES_IMAGE_URL,"forceRefresh":"false",                        },                    },"suggestions": [                        {"reply": {"text":"Yes","postbackData":"suggestion_1",                            }                        },                        {"reply": {"text":"I love it!","postbackData":"suggestion_2",                            }                        },                    ],                },            }        }    }}message=RcsCustom(to=MESSAGES_TO_NUMBER,from_=RCS_SENDER_ID,custom=custom_dict,)response=client.messages.send(message)print(response)

Rcs Send Suggested Action Create Calendar Event

fromvonageimportAuth,Vonagefromvonage_messagesimportRcsCustomclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))custom_dict= {"contentMessage": {"text":"Product Launch: Save the date!","suggestions": [            {"action": {"text":"Save to calendar","postbackData":"postback_data_1234","fallbackUrl":"https://www.google.com/calendar","createCalendarEventAction": {"startTime":"2024-06-28T19:00:00Z","endTime":"2024-06-28T20:00:00Z","title":"Vonage API Product Launch","description":"Event to demo Vonage\'s new and exciting API product",                    },                }            }        ],    }}message=RcsCustom(to=MESSAGES_TO_NUMBER,from_=RCS_SENDER_ID,custom=custom_dict,)response=client.messages.send(message)print(response)

Rcs Send Suggested Action Dial

fromvonageimportAuth,Vonagefromvonage_messagesimportRcsCustomclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))custom_dict= {"contentMessage": {"text":"Call us to claim your free gift!","suggestions": [            {"action": {"text":"Call now!","postbackData":"postback_data_1234","fallbackUrl":"https://www.example.com/contact/","dialAction": {"phoneNumber":"+447900000000"},                }            }        ],    }}message=RcsCustom(to=MESSAGES_TO_NUMBER,from_=RCS_SENDER_ID,custom=custom_dict,)response=client.messages.send(message)print(response)

Rcs Send Suggested Action Multiple

fromvonageimportAuth,Vonagefromvonage_messagesimportRcsCustomclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))custom_dict= {"contentMessage": {"text":"Need some help? Call us now or visit our website for more information.","suggestions": [            {"action": {"text":"Call us","postbackData":"postback_data_1234","fallbackUrl":"https://www.example.com/contact/","dialAction": {"phoneNumber":"+447900000000"},                }            },            {"action": {"text":"Visit site","postbackData":"postback_data_1234","openUrlAction": {"url":"http://example.com/"},                }            },        ],    }}message=RcsCustom(to=MESSAGES_TO_NUMBER,from_=RCS_SENDER_ID,custom=custom_dict,)response=client.messages.send(message)print(response)

Rcs Send Suggested Action Open Url

fromvonageimportAuth,Vonagefromvonage_messagesimportRcsCustomclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))custom_dict= {"contentMessage": {"text":"Check out our latest offers!","suggestions": [            {"action": {"text":"Open product page","postbackData":"postback_data_1234","openUrlAction": {"url":"http://example.com/"},                }            }        ],    }}message=RcsCustom(to=MESSAGES_TO_NUMBER,from_=RCS_SENDER_ID,custom=custom_dict,)response=client.messages.send(message)print(response)

Rcs Send Suggested Action Share Location

fromvonageimportAuth,Vonagefromvonage_messagesimportRcsCustomclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))custom_dict= {"contentMessage": {"text":"Your driver will come and meet you at your specified location.","suggestions": [            {"action": {"text":"Share a location","postbackData":"postback_data_1234","shareLocationAction": {},                }            }        ],    }}message=RcsCustom(to=MESSAGES_TO_NUMBER,from_=RCS_SENDER_ID,custom=custom_dict,)response=client.messages.send(message)print(response)

Rcs Send Suggested Action View Location

fromvonageimportAuth,Vonagefromvonage_messagesimportRcsCustomclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))custom_dict= {"contentMessage": {"text":"Drop by our office!","suggestions": [            {"action": {"text":"View map","postbackData":"postback_data_1234","fallbackUrl":"https://www.google.com/maps/place/Vonage/@51.5230371,-0.0852492,15z","viewLocationAction": {"latLong": {"latitude":"51.5230371","longitude":"-0.0852492",                        },"label":"Vonage London Office",                    },                }            }        ],    }}message=RcsCustom(to=MESSAGES_TO_NUMBER,from_=RCS_SENDER_ID,custom=custom_dict,)response=client.messages.send(message)print(response)

Rcs Send Suggested Reply

fromvonageimportAuth,Vonagefromvonage_messagesimportRcsCustomclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))custom_dict= {"contentMessage": {"text":"What do you think of Vonage APIs?","suggestions": [            {"reply": {"text":"They\'re great!","postbackData":"suggestion_1",                }            },            {"reply": {"text":"They\'re awesome!","postbackData":"suggestion_2",                }            },        ],    }}message=RcsCustom(to=MESSAGES_TO_NUMBER,from_=RCS_SENDER_ID,custom=custom_dict,)response=client.messages.send(message)print(response)

Rcs Send Text

fromvonageimportAuth,Vonagefromvonage_messagesimportRcsTextclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=RcsText(to=MESSAGES_TO_NUMBER,from_=RCS_SENDER_ID,text="This is an RCS message sent via the Vonage Messages API.",)response=client.messages.send(message)print(response)

Rcs Send Video

fromvonageimportAuth,Vonagefromvonage_messagesimportRcsResource,RcsVideoclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=RcsVideo(to=MESSAGES_TO_NUMBER,from_=RCS_SENDER_ID,video=RcsResource(url=MESSAGES_VIDEO_URL),)response=client.messages.send(message)print(response)

Sandbox Messenger Send_Text

importosfromos.pathimportdirname,joinfromdotenvimportload_dotenvdotenv_path=join(dirname(__file__),"../../../.env")load_dotenv(dotenv_path)VONAGE_APPLICATION_ID=os.environ.get("VONAGE_APPLICATION_ID")VONAGE_PRIVATE_KEY=os.environ.get("VONAGE_PRIVATE_KEY")MESSAGES_SANDBOX_HOST=os.environ.get("MESSAGES_SANDBOX_HOST")MESSENGER_RECIPIENT_ID=os.environ.get("MESSENGER_RECIPIENT_ID")MESSENGER_SENDER_ID=os.environ.get("MESSENGER_SENDER_ID")fromvonageimportAuth,HttpClientOptions,Vonagefromvonage_messagesimportMessengerTextclient=Vonage(auth=Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ),http_client_options=HttpClientOptions(api_host=MESSAGES_SANDBOX_HOST),)message=MessengerText(to=MESSENGER_RECIPIENT_ID,from_=MESSENGER_SENDER_ID,text="This is a Facebook Messenger text message sent using the Vonage Messages API via the Messages Sandbox",)response=client.messages.send(message)print(response)

Sandbox Viber Send_Text

importosfromos.pathimportdirname,joinfromdotenvimportload_dotenvdotenv_path=join(dirname(__file__),"../../../.env")load_dotenv(dotenv_path)VONAGE_APPLICATION_ID=os.environ.get("VONAGE_APPLICATION_ID")VONAGE_PRIVATE_KEY=os.environ.get("VONAGE_PRIVATE_KEY")MESSAGES_SANDBOX_HOST=os.environ.get("MESSAGES_SANDBOX_HOST")MESSAGES_TO_NUMBER=os.environ.get("MESSAGES_TO_NUMBER")VIBER_SENDER_ID=os.environ.get("VIBER_SENDER_ID")fromvonageimportAuth,HttpClientOptions,Vonagefromvonage_messagesimportViberTextclient=Vonage(auth=Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ),http_client_options=HttpClientOptions(api_host=MESSAGES_SANDBOX_HOST),)message=ViberText(to=MESSAGES_TO_NUMBER,from_=VIBER_SENDER_ID,text="This is a Viber Service Message text message sent using the Messages API via the Messages Sandbox",)response=client.messages.send(message)print(response)

Sandbox Whatsapp Send_Text

importosfromos.pathimportdirname,joinfromdotenvimportload_dotenvdotenv_path=join(dirname(__file__),"../../../.env")load_dotenv(dotenv_path)VONAGE_APPLICATION_ID=os.environ.get("VONAGE_APPLICATION_ID")VONAGE_PRIVATE_KEY=os.environ.get("VONAGE_PRIVATE_KEY")MESSAGES_SANDBOX_HOST=os.environ.get("MESSAGES_SANDBOX_HOST")MESSAGES_TO_NUMBER=os.environ.get("MESSAGES_TO_NUMBER")WHATSAPP_SENDER_ID=os.environ.get("WHATSAPP_SENDER_ID")fromvonageimportAuth,HttpClientOptions,Vonagefromvonage_messagesimportWhatsappTextclient=Vonage(auth=Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ),http_client_options=HttpClientOptions(api_host=MESSAGES_SANDBOX_HOST),)message=WhatsappText(to=MESSAGES_TO_NUMBER,from_=WHATSAPP_SENDER_ID,text="This is a WhatsApp text message sent using the Vonage Messages API via the Messages Sandbox",)response=client.messages.send(message)print(response)

Sms Send Sms

fromvonageimportAuth,Vonagefromvonage_messagesimportSmsclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))response=client.messages.send(Sms(to=MESSAGES_TO_NUMBER,from_=SMS_SENDER_ID,text='This is an SMS sent using the Vonage Messages API.',    ))print(response)

Verify Signed Webhooks

importosfromos.pathimportdirname,joinfromdotenvimportload_dotenv# Load the environmentenvpath=join(dirname(__file__),'../.env')load_dotenv(envpath)VONAGE_SIGNATURE_SECRET=os.getenv('VONAGE_SIGNATURE_SECRET')fromfastapiimportFastAPI,Requestfromvonage_jwt.verify_jwtimportverify_signatureapp=FastAPI()@app.get('/inbound')asyncdefverify_signed_webhook(request:Request):# Need to get the JWT after "Bearer " in the authorization headerauth_header=request.headers["authorization"].split()token=auth_header[1].strip()ifverify_signature(token,VONAGE_SIGNATURE_SECRET):print('Valid signature')else:print('Invalid signature')

Viber Send File

fromvonageimportAuth,Vonagefromvonage_messagesimportViberFile,ViberFileResourceclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=ViberFile(to=MESSAGES_TO_NUMBER,from_=VIBER_SENDER_ID,file=ViberFileResource(url=MESSAGES_FILE_URL),)response=client.messages.send(message)print(response)

Viber Send Image

fromvonageimportAuth,Vonagefromvonage_messagesimportViberImage,ViberImageResourceclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=ViberImage(to=MESSAGES_TO_NUMBER,from_=VIBER_SENDER_ID,image=ViberImageResource(url=MESSAGES_IMAGE_URL),)response=client.messages.send(message)print(response)

Viber Send Text

fromvonageimportAuth,Vonagefromvonage_messagesimportViberTextclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=ViberText(to=MESSAGES_TO_NUMBER,from_=VIBER_SENDER_ID,text="This is a Viber message sent via the Vonage Messages API.",)response=client.messages.send(message)print(response)

Viber Send Video

fromvonageimportAuth,Vonagefromvonage_messagesimportViberVideo,ViberVideoOptions,ViberVideoResourceclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=ViberVideo(to=MESSAGES_TO_NUMBER,from_=VIBER_SENDER_ID,video=ViberVideoResource(url=MESSAGES_VIDEO_URL,thumb_url=MESSAGES_IMAGE_URL),viber_service=ViberVideoOptions(duration=MESSAGES_VIDEO_DURATION,file_size=MESSAGES_VIDEO_FILE_SIZE,    ),)response=client.messages.send(message)print(response)

Webhook Server

frompprintimportpprintfromfastapiimportFastAPI,Request,statusapp=FastAPI()@app.post('/webhooks/message-status',status_code=status.HTTP_200_OK)asyncdefmessage_status(request:Request):data=awaitrequest.json()pprint(data)@app.post('/webhooks/inbound-message')asyncdefinbound_message(request:Request):data=awaitrequest.json()pprint(data)

Whatsapp Mark As Read

importosfromos.pathimportdirname,joinfromdotenvimportload_dotenvdotenv_path=join(dirname(__file__),"../../.env")load_dotenv(dotenv_path)VONAGE_APPLICATION_ID=os.environ.get("VONAGE_APPLICATION_ID")VONAGE_PRIVATE_KEY=os.environ.get("VONAGE_PRIVATE_KEY")GEOSPECIFIC_MESSAGES_API_URL=os.environ.get("GEOSPECIFIC_MESSAGES_API_URL")MESSAGES_MESSAGE_ID=os.environ.get("MESSAGES_MESSAGE_ID")fromvonageimportAuth,HttpClientOptions,Vonageclient=Vonage(auth=Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ),http_client_options=HttpClientOptions(api_host=GEOSPECIFIC_MESSAGES_API_URL),)client.messages.mark_whatsapp_message_read("MESSAGES_MESSAGE_ID")

Whatsapp Send Audio

importosfromos.pathimportdirname,joinfromdotenvimportload_dotenvdotenv_path=join(dirname(__file__),"../../.env")load_dotenv(dotenv_path)VONAGE_APPLICATION_ID=os.environ.get("VONAGE_APPLICATION_ID")VONAGE_PRIVATE_KEY=os.environ.get("VONAGE_PRIVATE_KEY")MESSAGES_TO_NUMBER=os.environ.get("MESSAGES_TO_NUMBER")WHATSAPP_SENDER_ID=os.environ.get("WHATSAPP_SENDER_ID")MESSAGES_AUDIO_URL=os.environ.get("MESSAGES_AUDIO_URL")fromvonageimportAuth,HttpClientOptions,Vonagefromvonage_messagesimportWhatsappAudio,WhatsappAudioResourceclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ),http_client_options=HttpClientOptions(api_host='messages-sandbox.nexmo.com'),)message=WhatsappAudio(to=MESSAGES_TO_NUMBER,from_=WHATSAPP_SENDER_ID,audio=WhatsappAudioResource(url=MESSAGES_AUDIO_URL,caption="Test audio file"),)response=client.messages.send(message)print(response)

Whatsapp Send Authentication Template

importosfromos.pathimportdirname,joinfromdotenvimportload_dotenvdotenv_path=join(dirname(__file__),"../../.env")load_dotenv(dotenv_path)VONAGE_APPLICATION_ID=os.environ.get("VONAGE_APPLICATION_ID")VONAGE_PRIVATE_KEY=os.environ.get("VONAGE_PRIVATE_KEY")MESSAGES_TO_NUMBER=os.environ.get("MESSAGES_TO_NUMBER")WHATSAPP_SENDER_ID=os.environ.get("WHATSAPP_SENDER_ID")WHATSAPP_TEMPLATE_NAME=os.environ.get("WHATSAPP_TEMPLATE_NAME")WHATSAPP_OTP=os.environ.get("WHATSAPP_OTP")fromvonageimportAuth,HttpClientOptions,Vonagefromvonage_messagesimportWhatsappCustomclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ),http_client_options=HttpClientOptions(api_host='messages-sandbox.nexmo.com'),)message=WhatsappCustom(to=MESSAGES_TO_NUMBER,from_=WHATSAPP_SENDER_ID,custom={"type":"template","template": {"name":WHATSAPP_TEMPLATE_NAME,"language": {"policy":"deterministic","code":"en"},"components": [                {"type":"body","parameters": [{"type":"text","text":"'$OTP'"}]},                {"type":"button","sub_type":"url","index":"0","parameters": [{"type":"text","text":WHATSAPP_OTP}],                },            ],        },    },)response=client.messages.send(message)print(response)

Whatsapp Send Button Link

fromvonageimportAuth,Vonagefromvonage_messagesimportWhatsappCustomclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=WhatsappCustom(to=MESSAGES_TO_NUMBER,from_=WHATSAPP_SENDER_ID,custom={"type":"template","template": {"name":WHATSAPP_TEMPLATE_NAME,"language": {"policy":"deterministic","code":"en"},"components": [                {"type":"header","parameters": [                        {"type":"image","image": {"link":MESSAGES_IMAGE_URL,                            },                        },                    ],                },                {"type":"body","parameters": [                        {"type":"text","text":"Joe Bloggs"},                        {"type":"text","text":"AB123456"},                    ],                },                {"type":"button","index":"0","sub_type":"url","parameters": [{"type":"text","text":"AB123456"}],                },            ],        },    },)response=client.messages.send(message)print(response)

Whatsapp Send Button Quick Reply

fromvonageimportAuth,Vonagefromvonage_messagesimportWhatsappCustomclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=WhatsappCustom(to=MESSAGES_TO_NUMBER,from_=WHATSAPP_SENDER_ID,custom={"type":"template","template": {"name":WHATSAPP_TEMPLATE_NAME,"language": {"policy":"deterministic","code":"en"},"components": [                {"type":"header","parameters": [                        {"type":"image","image": {"link":MESSAGES_IMAGE_URL,                            },                        },                    ],                },                {"type":"body","parameters": [                        {"type":"text","parameter_name":"customer_name","text":"Joe Bloggs",                        },                        {"type":"text","parameter_name":"dentist_name","text":"Mr Smith",                        },                        {"type":"text","parameter_name":"appointment_date","text":"2025-02-26",                        },                        {"type":"text","parameter_name":"appointment_location","text":"ACME Dental Practice",                        },                    ],                },                {"type":"button","sub_type":"quick_reply","index":0,"parameters": [{"type":"payload","payload":"Yes-Button-Payload"}],                },                {"type":"button","sub_type":"quick_reply","index":1,"parameters": [{"type":"payload","payload":"No-Button-Payload"}],                },            ],        },    },)response=client.messages.send(message)print(response)

Whatsapp Send Contact

fromvonageimportAuth,Vonagefromvonage_messagesimportWhatsappCustomclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=WhatsappCustom(to=MESSAGES_TO_NUMBER,from_=WHATSAPP_SENDER_ID,custom={"type":"contacts","contacts": [            {"addresses": [                    {"city":"Menlo Park","country":"United States","country_code":"us","state":"CA","street":"1 Hacker Way","type":"HOME","zip":"94025",                    },                    {"city":"Menlo Park","country":"United States","country_code":"us","state":"CA","street":"200 Jefferson Dr","type":"WORK","zip":"94025",                    },                ],"birthday":"2012-08-18","emails": [                    {"email":"test@fb.com","type":"WORK"},                    {"email":"test@whatsapp.com","type":"WORK"},                ],"name": {"first_name":"John","formatted_name":"John Smith","last_name":"Smith",                },"org": {"company":"WhatsApp","department":"Design","title":"Manager",                },"phones": [                    {"phone":"+1 (940) 555-1234","type":"HOME"},                    {"phone":"+1 (650) 555-1234","type":"WORK","wa_id":"16505551234",                    },                ],"urls": [{"url":"https://www.facebook.com","type":"WORK"}],            }        ],    },)response=client.messages.send(message)print(response)

Whatsapp Send File

fromvonageimportAuth,Vonagefromvonage_messagesimportWhatsappFile,WhatsappFileResourceclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=WhatsappFile(to=MESSAGES_TO_NUMBER,from_=WHATSAPP_SENDER_ID,file=WhatsappFileResource(url=MESSAGES_FILE_URL,caption="Test file"),)response=client.messages.send(message)print(response)

Whatsapp Send Image

fromvonageimportAuth,Vonagefromvonage_messagesimportWhatsappImage,WhatsappImageResourceclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=WhatsappImage(to=MESSAGES_TO_NUMBER,from_=WHATSAPP_SENDER_ID,image=WhatsappImageResource(url=MESSAGES_IMAGE_URL,caption="Test image"),)response=client.messages.send(message)print(response)

Whatsapp Send Location

fromvonageimportAuth,Vonagefromvonage_messagesimportWhatsappCustomclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=WhatsappCustom(to=MESSAGES_TO_NUMBER,from_=WHATSAPP_SENDER_ID,custom={"type":"location","location": {"longitude":-122.425332,"latitude":37.758056,"name":"Facebook HQ","address":"1 Hacker Way, Menlo Park, CA 94025",        },    },)response=client.messages.send(message)print(response)

Whatsapp Send Media Template

fromvonageimportAuth,Vonagefromvonage_messagesimportWhatsappCustomclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=WhatsappCustom(to=MESSAGES_TO_NUMBER,from_=WHATSAPP_SENDER_ID,custom={"type":"template","template": {"name":WHATSAPP_TEMPLATE_NAME,"language": {"policy":"deterministic","code":"en"},"components": [                {"type":"header","parameters": [                        {"type":"image","image": {"link":MESSAGES_IMAGE_URL,                            },                        },                    ],                },                {"type":"body","parameters": [                        {"type":"text","text":"Joe Bloggs"},                        {"type":"text","text":"AB123456"},                    ],                },            ],        },    },)response=client.messages.send(message)print(response)

Whatsapp Send Product Message Multiple Item

fromvonageimportAuth,Vonagefromvonage_messagesimportWhatsappCustomclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=WhatsappCustom(to=MESSAGES_TO_NUMBER,from_=WHATSAPP_SENDER_ID,custom={'type':'interactive','interactive': {'type':'product_list','header': {'type':'text','text':'Our top products'},'body': {'text':'Check out these great products'},'footer': {'text':'Sale now on!'},'action': {'catalog_id':WHATSAPP_CATALOG_ID,'sections': [                    {'title':'Cool products','product_items': [                            {'WHATSAPP_PRODUCT_ID_1':WHATSAPP_PRODUCT_ID_1},                            {'WHATSAPP_PRODUCT_ID_2':WHATSAPP_PRODUCT_ID_2},                        ],                    },                    {'title':'Awesome products','product_items': [                            {'WHATSAPP_PRODUCT_ID_1':WHATSAPP_PRODUCT_ID_1}                        ],                    },                ],            },        },    },)response=client.messages.send(message)print(response)

Whatsapp Send Product Message Single Item

fromvonageimportAuth,Vonagefromvonage_messagesimportWhatsappCustomclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=WhatsappCustom(to=MESSAGES_TO_NUMBER,from_=WHATSAPP_SENDER_ID,custom={'type':'interactive','interactive': {'type':'product','body': {'text''Check out this cool product'},'footer': {'text':'Sale now on!'},'action': {'catalog_id':WHATSAPP_CATALOG_ID,'product_retailer_id':WHATSAPP_PRODUCT_ID_1,            },        },    },)response=client.messages.send(message)print(response)

Whatsapp Send Sticker By Id

fromvonageimportAuth,Vonagefromvonage_messagesimportWhatsappSticker,WhatsappStickerIdclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=WhatsappSticker(to=MESSAGES_TO_NUMBER,from_=WHATSAPP_SENDER_ID,sticker=WhatsappStickerId(id=WHATSAPP_STICKER_ID),)response=client.messages.send(message)print(response)

Whatsapp Send Sticker By Url

fromvonageimportAuth,Vonagefromvonage_messagesimportWhatsappSticker,WhatsappStickerUrlclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=WhatsappSticker(to=MESSAGES_TO_NUMBER,from_=WHATSAPP_SENDER_ID,sticker=WhatsappStickerUrl(url=WHATSAPP_STICKER_URL),)response=client.messages.send(message)print(response)

Whatsapp Send Template

fromvonageimportAuth,Vonagefromvonage_messagesimport (WhatsappTemplate,WhatsappTemplateResource,WhatsappTemplateSettings)client=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=WhatsappTemplate(to=MESSAGES_TO_NUMBER,from_=WHATSAPP_SENDER_ID,template=WhatsappTemplateResource(name=WHATSAPP_TEMPLATE_NAME,parameters=["Vonage Verification","64873","10"],    ),whatsapp=WhatsappTemplateSettings(locale="en-GB",policy="deterministic",    ),)response=client.messages.send(message)print(response)

Whatsapp Send Text

fromvonageimportAuth,Vonagefromvonage_messagesimportWhatsappTextclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=WhatsappText(to=MESSAGES_TO_NUMBER,from_=WHATSAPP_SENDER_ID,text='Hello from the Vonage Messages API.',)response=client.messages.send(message)print(response)

Whatsapp Send Video

fromvonageimportAuth,Vonagefromvonage_messagesimportWhatsappVideo,WhatsappVideoResourceclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))message=WhatsappVideo(to=MESSAGES_TO_NUMBER,from_=WHATSAPP_SENDER_ID,video=WhatsappVideoResource(url=MESSAGES_VIDEO_URL,caption="Test video file"),)response=client.messages.send(message)print(response)

Number Insight

Snippets in this Section

Async Callback

fromfastapiimportFastAPI,Requestapp=FastAPI()@app.post('/webhooks/insight')asyncdefdisplay_advanced_number_insight_info(request:Request):data=awaitrequest.json()print(data)

Ni Advanced

fromvonageimportAuth,Vonagefromvonage_number_insightimport (AdvancedSyncInsightRequest,AdvancedSyncInsightResponse)client=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))insight:AdvancedSyncInsightResponse=client.number_insight.get_advanced_info_sync(AdvancedSyncInsightRequest(number=INSIGHT_NUMBER))pprint(insight)

Ni Advanced Async Trigger

fromvonageimportAuth,Vonagefromvonage_number_insightimport (AdvancedAsyncInsightRequest,AdvancedAsyncInsightResponse)client=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))insight:AdvancedAsyncInsightResponse=client.number_insight.get_advanced_info_async(AdvancedAsyncInsightRequest(number=INSIGHT_NUMBER,callback=INSIGHT_CALLBACK_URL))pprint(insight)

Ni Basic

fromvonageimportAuth,Vonagefromvonage_number_insightimportBasicInsightRequest,BasicInsightResponseclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))insight:BasicInsightResponse=client.number_insight.get_basic_info(BasicInsightRequest(number=INSIGHT_NUMBER))pprint(insight)

Ni Standard

fromvonageimportAuth,Vonagefromvonage_number_insightimport (StandardInsightRequest,StandardInsightResponse)client=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))insight:StandardInsightResponse=client.number_insight.get_standard_info(StandardInsightRequest(number=INSIGHT_NUMBER))pprint(insight)

Numbers

Snippets in this Section

Buy

fromvonageimportAuth,Vonagefromvonage_numbersimportNumberParams,NumbersStatusclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))status:NumbersStatus=client.numbers.buy_number(params=NumberParams(country=NUMBER_COUNTRY_CODE,msisdn=NUMBER_MSISDN,    ))print(status.model_dump())

Cancel

fromvonageimportAuth,Vonagefromvonage_numbersimportNumberParams,NumbersStatusclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))status:NumbersStatus=client.numbers.cancel_number(NumberParams(country=NUMBER_COUNTRY_CODE,msisdn=NUMBER_MSISDN))print(status.model_dump())

List

fromvonageimportAuth,Vonagefromvonage_numbersimportListOwnedNumbersFilterclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))numbers,count,next=client.numbers.list_owned_numbers(ListOwnedNumbersFilter(pattern=NUMBER_SEARCH_CRITERIA,search_pattern=NUMBER_SEARCH_PATTERN    ))pprint(numbers)print(count)print(next)

Search

fromvonageimportAuth,Vonagefromvonage_numbersimportSearchAvailableNumbersFilterclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))numbers,count,next=client.numbers.search_available_numbers(SearchAvailableNumbersFilter(country=NUMBER_COUNTRY_CODE,size=3,pattern=NUMBER_SEARCH_CRITERIA,search_pattern=NUMBER_SEARCH_PATTERN,type=NUMBER_TYPE,features=NUMBER_FEATURES,    ))pprint(numbers)print(count)print(next)fornumberinnumbers:print(f'Tel:{number.msisdn} Cost:{number.cost}')

Update

fromvonageimportAuth,Vonagefromvonage_numbersimportNumbersStatus,UpdateNumberParamsclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))status:NumbersStatus=client.numbers.update_number(UpdateNumberParams(country=NUMBER_COUNTRY_CODE,msisdn=NUMBER_MSISDN,app_id='vonage-application-id',mo_http_url=NUMBER_SMS_CALLBACK_URL,mo_smpp_sytem_type='inbound',voice_callback_value=NUMBER_VOICE_CALLBACK_URL,voice_status_callback=NUMBER_VOICE_STATUS_CALLBACK_URL,    ))print(status.model_dump())

Sms

Snippets in this Section

Delivery Receipts

frompprintimportpprintfromfastapiimportFastAPI,Requestapp=FastAPI()@app.post('/webhooks/delivery-receipt')asyncdefget_delivery_receipt(request:Request):data=awaitrequest.json()pprint(data)

Receive Sms

frompprintimportpprintfromfastapiimportFastAPI,Requestapp=FastAPI()@app.post('/webhooks/inbound')asyncdefinbound_message(request:Request):data=awaitrequest.json()pprint(data)

Send An Sms

fromvonageimportAuth,Vonagefromvonage_smsimportSmsMessage,SmsResponseclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))message=SmsMessage(to=SMS_TO_NUMBER,from_=SMS_SENDER_ID,text="A text message sent using the Vonage SMS API.",)response:SmsResponse=client.sms.send(message)print(response)

Send An Sms With Unicode

fromvonageimportAuth,Vonagefromvonage_smsimportSmsMessage,SmsResponseclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))message=SmsMessage(to=SMS_TO_NUMBER,from_=SMS_SENDER_ID,text='こんにちは世界',type='unicode',)response:SmsResponse=client.sms.send(message)print(response)

Send Signed Sms

fromvonageimportAuth,Vonagefromvonage_smsimportSmsMessage,SmsResponseclient=Vonage(Auth(api_key=VONAGE_API_KEY,signature_secret=SMS_SIGNATURE))message=SmsMessage(to=SMS_TO_NUMBER,from_=SMS_SENDER_ID,text="A text message sent using the Vonage SMS API.",)response:SmsResponse=client.sms.send(message)print(response)

Submit Sms Conversion

fromvonageimportAuth,Vonageclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))client.sms.submit_sms_conversion(message_id='MESSAGE_ID',delivered=True,timestamp='2020-01-01T12:00:00Z',)ifclient.http_client.last_response.status_code==200:print('Conversion submitted successfully.')else:print('Conversion not submitted.')

Verify Signed Sms

importosfromos.pathimportdirname,joinfromdotenvimportload_dotenvenvpath=join(dirname(__file__),'../.env')load_dotenv(envpath)VONAGE_API_KEY=os.getenv("VONAGE_API_KEY")VONAGE_SIGNATURE_SECRET=os.getenv("VONAGE_SIGNATURE_SECRET")fromfastapiimportFastAPI,RequestfromvonageimportAuth,Vonageclient=Vonage(Auth(api_key=VONAGE_API_KEY,signature_secret=VONAGE_SIGNATURE_SECRET))app=FastAPI()@app.post('/')asyncdefverify_signed_webhook(request:Request):data=awaitrequest.json()ifclient.http_client.auth.check_signature(data):print('Valid signature')else:print('Invalid signature')

Subaccounts

Snippets in this Section

Create Subaccount

fromvonageimportAuth,Vonagefromvonage_subaccountsimportNewSubaccount,SubaccountOptionsclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))response:NewSubaccount=client.subaccounts.create_subaccount(SubaccountOptions(name=SUBACCOUNT_NAME,secret=SUBACCOUNT_SECRET))print(response)

Get Subaccount

fromvonageimportAuth,Vonagefromvonage_subaccountsimportSubaccountclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))subaccount:Subaccount=client.subaccounts.get_subaccount(SUBACCOUNT_KEY)print(subaccount)

List Balance Transfers

fromvonageimportAuth,Vonagefromvonage_subaccountsimportListTransfersFilter,Transferclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))response:list[Transfer]=client.subaccounts.list_balance_transfers(ListTransfersFilter(start_date=SUBACCOUNT_START_DATE))print(response)

List Credit Transfers

fromvonageimportAuth,Vonagefromvonage_subaccountsimportListTransfersFilter,Transferclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))response:list[Transfer]=client.subaccounts.list_credit_transfers(ListTransfersFilter(start_date=SUBACCOUNT_START_DATE))print(response)

List Subaccounts

fromvonageimportAuth,Vonagefromvonage_subaccountsimportListSubaccountsResponseclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))response:ListSubaccountsResponse=client.subaccounts.list_subaccounts()print(response)

Reactivate Subaccount

fromvonageimportAuth,Vonagefromvonage_subaccountsimportModifySubaccountOptions,Subaccountclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))response:Subaccount=client.subaccounts.modify_subaccount(subaccount_api_key=SUBACCOUNT_KEY,options=ModifySubaccountOptions(suspended=False),)print(response)

Suspend Subaccount

fromvonageimportAuth,Vonagefromvonage_subaccountsimportModifySubaccountOptions,Subaccountclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))response:Subaccount=client.subaccounts.modify_subaccount(subaccount_api_key=SUBACCOUNT_KEY,options=ModifySubaccountOptions(suspended=True),)print(response)

Transfer Balance

fromvonageimportAuth,Vonagefromvonage_subaccountsimportTransfer,TransferRequestclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))request=TransferRequest(from_=VONAGE_API_KEY,to=SUBACCOUNT_KEY,amount=SUBACCOUNT_BALANCE_AMOUNT)transfer:Transfer=client.subaccounts.transfer_balance(request)print(transfer)

Transfer Credit

fromvonageimportAuth,Vonagefromvonage_subaccountsimportTransfer,TransferRequestclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))request=TransferRequest(from_=VONAGE_API_KEY,to=SUBACCOUNT_KEY,amount=SUBACCOUNT_CREDIT_AMOUNT)response:Transfer=client.subaccounts.transfer_credit(request)print(response)

Transfer Number

fromvonageimportAuth,Vonagefromvonage_subaccountsimportTransferNumberRequest,TransferNumberResponseclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))request=TransferNumberRequest(from_=VONAGE_API_KEY,to=SUBACCOUNT_KEY,number=VONAGE_VIRTUAL_NUMBER)response:TransferNumberResponse=client.subaccounts.transfer_number(request)print(response)

Users

Snippets in this Section

Create User

fromvonageimportAuth,Vonagefromvonage_usersimportChannels,PstnChannel,Userclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))user_options=User(name=USER_NAME,display_name=USER_DISPLAY_NAME,channels=Channels(pstn=[PstnChannel(number=123456)]),)user=client.users.create_user(user_options)print(user)

Delete User

fromvonageimportAuth,Vonageclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))client.users.delete_user(USER_ID)

Get User

fromvonageimportAuth,Vonagefromvonage_usersimportUserclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))user:User=client.users.get_user(USER_ID)print(user)

List Users

fromvonageimportAuth,Vonageclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))users_list,next_page_cursor=client.users.list_users()print(users_list)

Update User

fromvonageimportAuth,Vonagefromvonage_usersimportChannels,PstnChannel,SmsChannel,Userclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))user_params=User(name=USER_NAME,display_name=USER_DISPLAY_NAME,channels=Channels(sms=[SmsChannel(number='1234567890')],pstn=[PstnChannel(number=123456)]    ),)user:User=client.users.update_user(id=USER_ID,params=user_params)print(user)

Verify

Snippets in this Section

Cancel Request

fromvonageimportAuth,Vonageclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))client.verify.cancel_verification(request_id=VERIFY_REQUEST_ID)

Check Verification Code

fromvonageimportAuth,Vonagefromvonage_verifyimportCheckCodeResponseclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))response:CheckCodeResponse=client.verify.check_code(request_id=VERIFY_REQUEST_ID,code=VERIFY_CODE)print(response)

Send Request Email

fromvonageimportAuth,Vonagefromvonage_verifyimport (EmailChannel,StartVerificationResponse,VerifyRequest)client=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))verify_request=VerifyRequest(brand=VERIFY_VERIFY_BRAND_NAME,workflow=[EmailChannel(to=VERIFY_TO_EMAIL),    ],)response:StartVerificationResponse=client.verify.start_verification(verify_request)pprint(response)

Send Request Silent Auth

fromvonageimportAuth,Vonagefromvonage_verifyimport (SilentAuthChannel,StartVerificationResponse,VerifyRequest)client=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))verify_request=VerifyRequest(brand=VERIFY_BRAND_NAME,workflow=[SilentAuthChannel(to=VERIFY_NUMBER)],)response:StartVerificationResponse=client.verify.start_verification(verify_request)pprint(response)

Send Request Sms

fromvonageimportAuth,Vonagefromvonage_verifyimportSmsChannel,StartVerificationResponse,VerifyRequestclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))verify_request=VerifyRequest(brand=VERIFY_BRAND_NAME,workflow=[SmsChannel(to=VERIFY_NUMBER),    ],)response:StartVerificationResponse=client.verify.start_verification(verify_request)pprint(response)

Send Request Voice

fromvonageimportAuth,Vonagefromvonage_verifyimport (StartVerificationResponse,VerifyRequest,VoiceChannel)client=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))verify_request=VerifyRequest(brand=VERIFY_BRAND_NAME,workflow=[VoiceChannel(to=VERIFY_NUMBER),    ],)response:StartVerificationResponse=client.verify.start_verification(verify_request)pprint(response)

Send Request Whatsapp

fromvonageimportAuth,Vonagefromvonage_verifyimport (StartVerificationResponse,VerifyRequest,WhatsappChannel)client=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))verify_request=VerifyRequest(brand=VERIFY_BRAND_NAME,workflow=[WhatsappChannel(to=VERIFY_NUMBER,from_=VERIFY_FROM_NUMBER),    ],)response:StartVerificationResponse=client.verify.start_verification(verify_request)pprint(response)

Send Request Whatsapp Interactive

fromvonageimportAuth,Vonagefromvonage_verifyimport (StartVerificationResponse,VerifyRequest,WhatsappChannel)client=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))verify_request=VerifyRequest(brand=VERIFY_BRAND_NAME,workflow=[WhatsappChannel(to=VERIFY_NUMBER,from_=VERIFY_FROM_NUMBER),    ],)response:StartVerificationResponse=client.verify.start_verification(verify_request)pprint(response)

Send Request With Fallback

fromvonageimportAuth,Vonagefromvonage_verifyimport (EmailChannel,SilentAuthChannel,StartVerificationResponse,VerifyRequest)client=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))verify_request=VerifyRequest(brand=VERIFY_BRAND_NAME,workflow=[SilentAuthChannel(to=VERIFY_NUMBER),EmailChannel(to=VERIFY_TO_EMAIL,from_=VERIFY_FROM_EMAIL),    ],)response:StartVerificationResponse=client.verify.start_verification(verify_request)pprint(response)

Verify_Legacy

Snippets in this Section

Cancel

fromvonageimportAuth,Vonageclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))client.verify_legacy.cancel_verification(VERIFY_REQUEST_ID)

Check

fromvonageimportAuth,Vonagefromvonage_verify_legacyimportCheckCodeResponseclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))response:CheckCodeResponse=client.verify_legacy.check_code(VERIFY_REQUEST_ID,VERIFY_CODE)print(response)

Psd2 Request

fromvonageimportAuth,Vonagefromvonage_verify_legacyimportPsd2Request,StartVerificationResponseclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))request=Psd2Request(number=VERIFY_NUMBER,payee=VERIFY_PAYEE_NAME,amount=VERIFY_AMOUNT)response:StartVerificationResponse=client.verify_legacy.start_psd2_verification(request)print(response)

Request

fromvonageimportAuth,Vonagefromvonage_verify_legacyimportStartVerificationResponse,VerifyRequestclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))request=VerifyRequest(number=VERIFY_NUMBER,brand='AcmeInc')response:StartVerificationResponse=client.verify_legacy.start_verification(request)print(response)

Search

fromvonageimportAuth,Vonagefromvonage_verify_legacyimportVerifyStatusclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))response:VerifyStatus=client.verify_legacy.search(VERIFY_REQUEST_ID)print(response)

Send Psd2 Verification Request With Workflow

fromvonageimportAuth,Vonagefromvonage_verify_legacyimportPsd2Request,StartVerificationResponseclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))request=Psd2Request(number=VERIFY_NUMBER,payee=VERIFY_PAYEE_NAME,amount=VERIFY_AMOUNT,workflow_id=VERIFY_WORKFLOW_ID,)response:StartVerificationResponse=client.verify_legacy.start_psd2_verification(request)print(response)

Send Verification Request With Workflow

fromvonageimportAuth,Vonagefromvonage_verify_legacyimportStartVerificationResponse,VerifyRequestclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))request=VerifyRequest(number=VERIFY_NUMBER,brand='AcmeInc',workflow_id=VERIFY_WORKFLOW_ID)response:StartVerificationResponse=client.verify_legacy.start_verification(request)print(response)

Trigger Next Step

fromvonageimportAuth,Vonagefromvonage_verify_legacyimportVerifyControlStatusclient=Vonage(Auth(api_key=VONAGE_API_KEY,api_secret=VONAGE_API_SECRET))response:VerifyControlStatus=client.verify_legacy.trigger_next_event(VERIFY_REQUEST_ID)print(response)

Voice

Snippets in this Section

Connect An Inbound Call

importosfromos.pathimportdirname,joinfromdotenvimportload_dotenvfromfastapiimportFastAPIfromvonage_voiceimportConnect,PhoneEndpointdotenv_path=join(dirname(__file__),'../.env')load_dotenv(dotenv_path)VONAGE_VIRTUAL_NUMBER=os.environ.get('VONAGE_VIRTUAL_NUMBER')VOICE_VOICE_TO_NUMBER=os.environ.get('VOICE_VOICE_TO_NUMBER')app=FastAPI()@app.get('/webhooks/answer')asyncdefinbound_call():ncco= [Connect(endpoint=[PhoneEndpoint(number=VOICE_VOICE_TO_NUMBER)],from_=VONAGE_VIRTUAL_NUMBER,        ).model_dump(by_alias=True,exclude_none=True)    ]returnncco

Connect Callers To A Conference

importosfromos.pathimportdirname,joinfromdotenvimportload_dotenvfromfastapiimportFastAPIfromvonage_voiceimportConversation,NccoAction,Talkdotenv_path=join(dirname(__file__),'../.env')load_dotenv(dotenv_path)VOICE_CONFERENCE_NAME=os.environ.get("VOICE_CONFERENCE_NAME")app=FastAPI()@app.get('/webhooks/answer')asyncdefanswer_call():ncco:list[NccoAction]= [Talk(text="Please wait while we connect you to the conference"),Conversation(name=VOICE_CONFERENCE_NAME),    ]return [action.model_dump(by_alias=True,exclude_none=True)foractioninncco]

Earmuff A Call

fromvonageimportAuth,Vonageclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))client.voice.earmuff(VOICE_CALL_ID)sleep(3)client.voice.unearmuff(VOICE_CALL_ID)

Get Recording

fromvonageimportAuth,Vonageclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))client.voice.download_recording(VOICE_RECORDING_URL,'recording.mp3')

Handle User Input

frompprintimportpprintfromfastapiimportBody,FastAPI,Requestfromvonage_voiceimportDtmf,Input,NccoAction,Talkapp=FastAPI()@app.get('/webhooks/answer')asyncdefanswer_call(request:Request):ncco:list[NccoAction]= [Talk(text=f'Hello, please press any key to continue.'),Input(type=['dtmf'],dtmf=Dtmf(timeOut=5,maxDigits=1),eventUrl=[str(request.base_url)+'webhooks/dtmf'],        ),    ]return [action.model_dump(by_alias=True,exclude_none=True)foractioninncco]@app.post('/webhooks/dtmf')asyncdefanswer_dtmf(data:dict=Body(...)):pprint(data)return [Talk(text=f'Hello, you pressed{data['dtmf']['digits']}').model_dump(by_alias=True,exclude_none=True        )    ]

Handle User Input With Asr

frompprintimportpprintfromfastapiimportBody,FastAPI,Requestfromvonage_voiceimportInput,NccoAction,Speech,Talkapp=FastAPI()@app.get('/webhooks/answer')asyncdefanswer_call(request:Request):ncco:list[NccoAction]= [Talk(text=f'Please say something'),Input(type=['speech'],speech=Speech(endOnSilence=1,language='en-US'),eventUrl=[str(request.base_url)+'webhooks/asr'],        ),    ]return [action.model_dump(by_alias=True,exclude_none=True)foractioninncco]@app.post('/webhooks/asr')asyncdefanswer_asr(data:dict=Body(...)):ifdataisnotNoneand'speech'indata:pprint(data)speech=data['speech']['results'][0]['text']return [Talk(text=f'Hello, you said{speech}').model_dump(by_alias=True,exclude_none=True            )        ]return [Talk(text=f'Sorry, I didn\'t understand your input.').model_dump(by_alias=True,exclude_none=True        )    ]

Make An Outbound Call

fromvonageimportAuth,Vonagefromvonage_voiceimportCreateCallRequest,Phone,ToPhoneclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))response=client.voice.create_call(CreateCallRequest(answer_url=[VOICE_ANSWER_URL],to=[ToPhone(number=VOICE_TO_NUMBER)],from_=Phone(number=VONAGE_VIRTUAL_NUMBER),    ))pprint(response)

Make Outbound Call Ncco

fromvonageimportAuth,Vonagefromvonage_voiceimportCreateCallRequest,Phone,Talk,ToPhoneclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))response=client.voice.create_call(CreateCallRequest(ncco=[Talk(text='This is a text to speech call from Vonage.')],to=[ToPhone(number=VOICE_TO_NUMBER)],from_=Phone(number=VONAGE_VIRTUAL_NUMBER),    ))pprint(response)

Mute A Call

fromvonageimportAuth,Vonageclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))client.voice.mute(VOICE_CALL_ID)sleep(5)client.voice.unmute(VOICE_CALL_ID)

Play Audio Stream Into Call

fromvonageimportAuth,Vonagefromvonage_voiceimportAudioStreamOptions,CallMessageclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))response:CallMessage=client.voice.play_audio_into_call(VOICE_CALL_ID,audio_stream_options=AudioStreamOptions(stream_url=[VOICE_STREAM_URL]),)pprint(response)

Play Dtmf Into Call

fromvonageimportAuth,Vonagefromvonage_voiceimportCallMessageclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))response:CallMessage=client.voice.play_dtmf_into_call(uuid=VOICE_CALL_ID,dtmf=VOICE_DTMF_DIGITS)pprint(response)

Play Tts Into Call

fromvonageimportAuth,Vonagefromvonage_voiceimportCallMessage,TtsStreamOptionsclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))response:CallMessage=client.voice.play_tts_into_call(uuid=VOICE_CALL_ID,tts_options=TtsStreamOptions(text=VOICE_TEXT,language=VOICE_LANGUAGE),)pprint(response)

Receive An Inbound Call

fromfastapiimportFastAPI,Queryfromvonage_voiceimportTalkapp=FastAPI()@app.get('/webhooks/answer')asyncdefanswer_call(from_:str=Query(...,alias='from')):from_='-'.join(from_)return [Talk(text=f'Thank you for calling from{from_}').model_dump(by_alias=True,exclude_none=True        )    ]

Record A Call

importosfromos.pathimportdirname,joinfrompprintimportpprintfromdotenvimportload_dotenvfromfastapiimportBody,FastAPIfromvonage_voiceimportConnect,NccoAction,PhoneEndpoint,Recorddotenv_path=join(dirname(__file__),'../.env')load_dotenv(dotenv_path)VONAGE_VIRTUAL_NUMBER=os.environ.get('VONAGE_VIRTUAL_NUMBER')VOICE_TO_NUMBER=os.environ.get('VOICE_TO_NUMBER')app=FastAPI()@app.get('/webhooks/answer')asyncdefinbound_call():ncco:list[NccoAction]= [Record(eventUrl=['https://demo.ngrok.io/webhooks/recordings']),Connect(from_=VONAGE_VIRTUAL_NUMBER,endpoint=[PhoneEndpoint(number=VOICE_TO_NUMBER)]        ),    ]return [action.model_dump(by_alias=True,exclude_none=True)foractioninncco]@app.post('/webhooks/recordings')asyncdefrecordings(data:dict=Body(...)):pprint(data)return {'message':'webhook received'}

Record A Call With Split Audio

importosfromos.pathimportdirname,joinfrompprintimportpprintfromdotenvimportload_dotenvfromfastapiimportBody,FastAPIfromvonage_voiceimportConnect,NccoAction,PhoneEndpoint,Recorddotenv_path=join(dirname(__file__),'../.env')load_dotenv(dotenv_path)VONAGE_VIRTUAL_NUMBER=os.environ.get('VONAGE_VIRTUAL_NUMBER')VOICE_TO_NUMBER=os.environ.get('VOICE_TO_NUMBER')app=FastAPI()@app.get('/webhooks/answer')asyncdefinbound_call():ncco:list[NccoAction]= [Record(split='conversation',channels=2,eventUrl=['https://demo.ngrok.io/webhooks/recordings'],        ),Connect(from_=VONAGE_VIRTUAL_NUMBER,endpoint=[PhoneEndpoint(number=VOICE_TO_NUMBER)]        ),    ]return [step.model_dump(by_alias=True,exclude_none=True)forstepinncco]@app.post('/webhooks/recordings')asyncdefrecordings(data:dict=Body(...)):pprint(data)return {'message':'webhook received'}

Record A Conversation

importosfromos.pathimportdirname,joinfrompprintimportpprintfromdotenvimportload_dotenvfromfastapiimportBody,FastAPIfromvonage_voiceimportConversationdotenv_path=join(dirname(__file__),'../.env')load_dotenv(dotenv_path)VOICE_CONFERENCE_NAME=os.environ.get('VOICE_CONFERENCE_NAME')app=FastAPI()@app.get('/webhooks/answer')asyncdefanswer_call():ncco= [Conversation(name=VOICE_CONFERENCE_NAME,record=True,eventMethod='POST',eventUrl=['https://demo.ngrok.io/webhooks/recordings'],        )    ]returnncco@app.post('/webhooks/recordings')asyncdefrecordings(data:dict=Body(...)):pprint(data)return {'message':'webhook received'}

Record A Message

frompprintimportpprintfromfastapiimportBody,FastAPI,Requestfromvonage_voiceimportNccoAction,Record,Talkapp=FastAPI()@app.get('/webhooks/answer')asyncdefanswer_call(request:Request):print(request.base_url)ncco:list[NccoAction]= [Talk(text='Please leave a message after the tone, then press #. We will get back to you as soon as we can.'        ),Record(endOnSilence=3,endOnKey='#',beepStart=True,eventUrl=[str(request.base_url)+'webhooks/recordings'],        ),Talk(text='Thank you for your message. Goodbye.'),    ]return [action.model_dump(by_alias=True,exclude_none=True)foractioninncco]@app.post('/webhooks/recordings')asyncdefrecordings(data:dict=Body(...)):pprint(data)return {'message':'webhook received'}

Retrieve Info For A Call

fromvonageimportAuth,Vonagefromvonage_voiceimportCallInfoclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))response:CallInfo=client.voice.get_call(VOICE_CALL_ID)pprint(response)

Retrieve Info For All Calls

fromvonageimportAuth,Vonagefromvonage_voiceimportListCallsFilterclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))now=datetime.now(timezone.utc)date_end=now.strftime('%Y-%m-%dT%H:%M:%SZ')start=now-timedelta(hours=24)date_start=start.strftime('%Y-%m-%dT%H:%M:%SZ')calls,_=client.voice.list_calls(ListCallsFilter(date_start=date_start,date_end=date_end))forcallincalls:pprint(call)

Track Ncco

fromfastapiimportFastAPI,Requestfromvonage_voiceimportNccoAction,Notify,Talkapp=FastAPI()@app.get('/webhooks/answer')asyncdefinbound_call(request:Request):ncco:list[NccoAction]= [Talk(text=f'Thanks for calling the notification line.'),Notify(payload={"foo":"bar"},eventUrl=[str(request.base_url)+'webhooks/notification'],        ),Talk(text=f'You will never hear me as the notification URL will return an NCCO.'),    ]return [action.model_dump(by_alias=True,exclude_none=True)foractioninncco]@app.post('/webhooks/notification')asyncdefon_notification():return [Talk(text=f'Your notification has been received, loud and clear').model_dump(by_alias=True,exclude_none=True        )    ]

Transfer A Call

fromvonageimportAuth,Vonageclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))client.voice.transfer_call_answer_url(VOICE_CALL_ID,VOICE_NCCO_URL)

Transfer Call Inline Ncco

fromvonageimportAuth,Vonagefromvonage_voiceimportTalkclient=Vonage(Auth(application_id=VONAGE_APPLICATION_ID,private_key=VONAGE_PRIVATE_KEY,    ))ncco= [Talk(text='This is a transfer action using an inline NCCO')]client.voice.transfer_call_ncco(VOICE_CALL_ID,ncco)

About

Python code examples for using Vonage communications APIs

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors32

Languages


[8]ページ先頭

©2009-2025 Movatter.jp