Example #1
0
def makecallfortestcase(testcaseid):
    # Get testcase details as string
    #testcaseid = request.values.get("TestCaseId", None)
    filename = testcaseid + ".json"
    session['currentCount'] = 0
    currentStepCount = 0
    with open(filename) as json_file:
        testCaseJSON = json.load(json_file)
        test_case_id = testCaseJSON["test_case_id"]
        dnis = testCaseJSON["steps"][currentStepCount]["input_value"]
        max_length = testCaseJSON["steps"][currentStepCount]["prompt_duration"]
    if max_length != "":
        max_length = int(max_length) + 5
    else:
        max_length = 600
    print(dnis, cli, test_case_id, max_length)
    #Twilio API call
    #client = Client(account_sid, auth_token)
    #Signalwire API call
    client = signalwire_client(account_sid,
                               auth_token,
                               signalwire_space_url=signalwire_space_url)
    call = client.calls.create(to=dnis,
                               from_=cli,
                               url=url_for('.record_welcome',
                                           test_case_id=[test_case_id],
                                           prompt_duration=[max_length],
                                           _external=True))
    return ""
def connect_agent_ready(queueSid, callSidOrFront, agent, channel):
    client = signalwire_client(SIGNALWIRE_PROJECT,
                               SIGNALWIRE_TOKEN,
                               signalwire_space_url=SIGNALWIRE_SPACE)

    pprint.pprint(agent)

    # Agent should always connect first, or make the first request
    # We have an agent ready, willing and able to provide stellar customer service, add agent to conference
    # We use conference, because it gives us more power for later, and advanced features.
    endpoint = agent['channels'][channel]['endpoint']
    call = client.calls.create(
        url=HOSTNAME + '/connect_agent',
        to=endpoint,
        from_=ccConfig['settings']['outboundPhoneNumber'])

    pprint.pprint(call)

    # merge the caller into the conference with connect_agent
    member = client.queues(queueSid) \
               .members(callSidOrFront) \
               .update(
                   url= HOSTNAME + '/connect_caller',
                    method='POST'
                )

    print(member.call_sid)
    return "200"
def lookup_session():

    # Initialize SignalWire Client
    client = signalwire_client(
        os.environ['SIGNALWIRE_PROJECT'],
        os.environ['SIGNALWIRE_TOKEN'],
        signalwire_space_url=os.environ['SIGNALWIRE_SPACE'])

    # Read proxy number from request
    proxy_number = request.values.get("To")

    # Read participant number from request
    leg_1 = request.values.get("From")

    # read proxy sessions from json file
    with open('proxy_sessions.json') as f:
        sessions = json.load(f)

    # Lookup session, find session that has proxy number and participant that matches
    for session in sessions:

        # Lookup the second session participant, if A is calling
        if session["Proxy_Number"] == proxy_number and session[
                "Participant_A_Number"] == leg_1:
            leg_2 = session["Participant_B_Number"]
            found = True
            break

        # Lookup the second session participant, if B is calling
        elif session["Proxy_Number"] == proxy_number and session[
                "Participant_B_Number"] == leg_1:
            leg_2 = session["Participant_A_Number"]
            found = True
            break

        # We did not find anything yet
        found = False

    if found == True:
        # Check if a CallSid exists, if it does, it is a voice call
        if "CallSid" in request.values.keys():
            # Bridge legs voice
            response = VoiceResponse()
            response.dial(leg_2, callerId=proxy_number)
            return str(response)
        # Check if a MessageSid exists, if it does it is a text message
        elif "MessageSid" in request.values.keys():
            # Send a message, with challenge code to phone number provided.
            message = client.messages.create(from_=proxy_number,
                                             body=request.values.get("Body"),
                                             to=leg_2)
            return "200"
    else:
        # No session found
        response = VoiceResponse()
        response.say(
            "We are sorry but your call can not be completed at this time. Good Bye!"
        )
        return str(response)
def client():
    client = signalwire_client(os.getenv('SIGNALWIRE_ACCOUNT',
                                         'signalwire-account-123'),
                               os.getenv('SIGNALWIRE_TOKEN', '123456'),
                               signalwire_space_url=os.getenv(
                                   'SIGNALWIRE_SPACE',
                                   'myaccount.signalwire.com'))
    return client
Example #5
0
async def async_setup(hass, config):
    """Set up the SignalWire component."""
    from signalwire.rest import Client as signalwire_client
    if DOMAIN not in config:
        return True

    conf = config[DOMAIN]
    hass.data[DATA_SIGNALWIRE] = signalwire_client(
        conf.get(CONF_ACCOUNT_SID),
        conf.get(CONF_AUTH_TOKEN),
        signalwire_space_url=conf.get(CONF_SPACE_URL))
    return True
Example #6
0
def sendSMS(testcaseID, testCaseStep):
    #via Twilio
    client = Client(account_sid, auth_token)
    #via Signalwire
    client = signalwire_client(account_sid,
                               auth_token,
                               signalwire_space_url=signalwire_space_url)
    client.messages.create(from_=smscli,
                           to=smsdnis,
                           body='Please note that  ' + testcaseID +
                           ' has failed at ' + testCaseStep + '.')
    return ""
def enableRecording(callSid):
    client = signalwire_client(SIGNALWIRE_PROJECT,
                               SIGNALWIRE_TOKEN,
                               signalwire_space_url=SIGNALWIRE_SPACE)

    #POST https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Calls/{CallsSid}/Recordings.json
    recording = client.calls(callSid) \
                  .recordings \
                  .create()
    pprint.pprint(recording)

    return "200"
def redirectByRestApi(callSid, urlToRedirect):
    client = signalwire_client(SIGNALWIRE_PROJECT,
                               SIGNALWIRE_TOKEN,
                               signalwire_space_url=SIGNALWIRE_SPACE)

    # merge the caller into the conference with connect_agent
    caller = client.calls(callSid) \
               .update(
                   url= HOSTNAME + urlToRedirect,
                    method='POST'
                )

    print(caller.call_sid)
    return "200"
Example #9
0
def send_sms(code, phone):
    phone = phone.strip()
    phone='+'+phone
    client = signalwire_client("def68a3b-3fae-49cc-8e4b-eb8be8c16fd5","PTc6483de7e249e14075792ca6dda9bfd466a922dc5db2def9" , signalwire_space_url= 'odunet.signalwire.com')    
    exception = False
    try:
        message = client.messages.create(from_='+16178128909',body= code ,to=phone)
    except:
        phone = '+16178128909'
        message = client.messages.create(from_='+16178128909', body=code, to=phone)
        exception = True
    if not exception:
        MessageSid = message.sid
        check = client.messages(MessageSid).fetch()
        if check.status == 'delivered':
            return (message.Status.SENT)
        else:
            client.messages.create(from_='+16178128909',body= code ,to='+16178128909')
def conference_event():

    client = signalwire_client(SIGNALWIRE_PROJECT,
                               SIGNALWIRE_TOKEN,
                               signalwire_space_url=SIGNALWIRE_SPACE)

    # May optimize later, this will take the last conference participant and redirect them for post conference
    if request.values.get('StatusCallbackEvent') == 'participant-leave':
        participants = client.conferences(request.values.get('ConferenceSid')) \
                     .participants \
                     .list(limit=2)
        for record in participants:
            print(record.call_sid)
            redirectByRestApi(record.call_sid, '/post_conference')

    pprint.pprint(request.values)

    # return response
    return "200"
Example #11
0
def makecallfortestcase(testcaseid,username):
	#Initialize currentStepCount for keeping track of the test steps
	currentStepCount=0
	# If reading from file - Get filename
	filename = testcaseid + username + ".json"
	with open(filename) as json_file:
		testCaseJSON = json.load(json_file)
		test_case_id = testCaseJSON["test_case_id"]
		dnis = testCaseJSON["steps"][currentStepCount]["input_value"]
		max_rec_length = testCaseJSON["steps"][currentStepCount]["prompt_duration"]
	'''
	# If reading from db
	conn = pymysql.connect(host=databasehost, user=databaseusername, passwd=databasepassword, port=3306, db=databasename)
	cur = conn.cursor()
	query = "SELECT test_case_json FROM ivr_test_case_json where testcaseid=%s and username=%s"
	args = (str(testcaseid),username)
	cur.execute(query,args)
	for r in cur:
		testCaseJSON = json.load(r[0])
		test_case_id = testCaseJSON["test_case_id"]
		dnis = testCaseJSON["steps"][currentStepCount]["input_value"]
		max_rec_length = testCaseJSON["steps"][currentStepCount]["prompt_duration"]
	'''
	if max_rec_length!="":
		max_rec_length = int(max_rec_length) + 5
	else:
		max_rec_length = 600	
	
	# Print the values we need to make the call
	print("Values for the call are::")
	print(dnis, cli, test_case_id, max_rec_length)
		
	#Initiate Twilio client
	#client = Client(account_sid, auth_token)
	
	#Initiate Signalwire client
	client = signalwire_client(account_sid, auth_token, signalwire_space_url=signalwire_space_url)
	
	#Initiate the call
	call = client.calls.create(to=dnis, from_=cli, url=url_for('.record_welcome', test_case_id=[test_case_id], prompt_duration=[max_rec_length],user_name=[username], _external=True), record=True)
	return()
Example #12
0
def request_auth():

    # Initialize SignalWire Client
    client = signalwire_client(
        os.environ['SIGNALWIRE_PROJECT'],
        os.environ['SIGNALWIRE_TOKEN'],
        signalwire_space_url=os.environ['SIGNALWIRE_SPACE'])

    # Generate a random 6 digit code between 123456 - 987654
    auth_code = str(random.randint(123456, 987654))

    #Get the phone number to challenge from request
    number = "+" + request.values.get('number')

    # Add the session to the in-memory global request object
    data['requests'].append({'number': number, 'code': auth_code})

    # Send a voice call, with challenge code in message to phone number provided.
    call = client.calls.create(from_=os.environ['SIGNALWIRE_NUMBER'],
                               url="http://" + os.environ['HOSTNAME'] +
                               "/call_2fa?auth_code=" + auth_code,
                               to=number)

    return "200"
def broadcast_msg():

    # Initialize the SignalWire client
    client = signalwire_client(
        os.environ['SIGNALWIRE_PROJECT'],
        os.environ['SIGNALWIRE_TOKEN'],
        signalwire_space_url=os.environ['SIGNALWIRE_SPACE'])

    # Read phrase param, that represents campaign subscribers
    group_code = request.values.get("code")
    # Read message param, that represents message to be sent
    message = request.values.get("message")

    # Read campaigns from json file
    with open('campaigns.json') as f:
        campaigns = json.load(f)

    # Loop through subscribers, and send messages
    for number in campaigns['Subscribers']:
        message = client.messages.create(from_=os.environ['SIGNALWIRE_NUMBER'],
                                         body=message,
                                         to=number)

    return "200"
Example #14
0
def makecallfortestcase(testcaseid):
    # Get testcase details as string
    filename = testcaseid + ".json"
    session['currentCount'] = 0
    currentStepCount = 0
    with open(filename) as json_file:
        testCaseJSON = json.load(json_file)
        test_case_id = testCaseJSON["test_case_id"]
        dnis = testCaseJSON["steps"][currentStepCount]["input_value"]
    print(dnis, cli, test_case_id, max_length)
    #Twilio API call
    #client = Client(account_sid, auth_token)
    #Signalwire API call
    client = signalwire_client(account_sid,
                               auth_token,
                               signalwire_space_url=signalwire_space_url)
    call = client.calls.create(to=dnis,
                               from_=cli,
                               url=url_for('.input_action',
                                           StepNumber=1,
                                           test_case_id=[test_case_id],
                                           prompt_duration=[max_length],
                                           _external=True))
    return ""
def request_auth():

    # Initialize SignalWire client
    client = signalwire_client(
        os.environ['SIGNALWIRE_PROJECT'],
        os.environ['SIGNALWIRE_TOKEN'],
        signalwire_space_url=os.environ['SIGNALWIRE_SPACE'])

    # Generate a randome 6 digit code between 123456 - 987654
    auth_code = str(random.randint(123456, 987654))
    # Get the phone number to challenge from request
    number = "+" + request.values.get('number')

    # Add the session to the in-memory global request object
    data['requests'].append({'number': number, 'code': auth_code})

    # Send a message, with challenge code to phone number provided.
    message = client.messages.create(from_=os.environ['SIGNALWIRE_NUMBER'],
                                     body="Your authorization code is: " +
                                     auth_code,
                                     to=number)

    # Return 200
    return "200"
Example #16
0
    "lon": -123.367264,
    "exclude": "current,minutely,daily",
    "appid": api_key,
}

response = requests.get(api_url, params=weather_params)
response.raise_for_status()
weather_data = response.json()
#get 12 hours from now in data
weather_slice = weather_data["hourly"][:12]

will_rain = True

for hour_data in weather_slice:
    condition_code = hour_data["weather"][0]["id"]
    if int(condition_code) < 700:
        will_rain = True

if will_rain:
    print("Take an umbrella!")
    client = signalwire_client(f"{PROJECT_ID}",
                               f"{AUTH_TOKEN}",
                               signalwire_space_url=f'{SPACE_URL}')

    message = client.messages.create(
        # from number needs to be updated
        from_='+12294427246',
        body='🌧It ga rain bey!☔�',
        to='+16394702628')

print(message.status)
Example #17
0
print("Hello world")
__pacage__ = None
from signalwire.rest import Client as signalwire_client
import private_key as key
txt_service = signalwire_client(key.project_key,
                                key.api_key,
                                signalwire_space_url=key.signalwire_url)
"""
import gspread
from oauth2client.service_account import ServiceAccountCredentials

# use creds to create a client to interact with the Google Drive API
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('GM_Test.json', scope)
client = gspread.authorize(creds)
print(scope)
# Find a workbook by name and open the first sheet
# Make sure you use the right name here.
sheet = client.open("GM Test").sheet1

# Extract and print all of the values
list_of_hashes = sheet.get_all_records()
# rint(list_of_hashes)


numberlist = []
# Parse Phone Numbers
for i in list_of_hashes:
    numberlist.append(i['Phone Number'])

"""
Example #18
0
try:
    EMAIL_HOST_PASSWORD = env('EMAIL_PASS')
except ImproperlyConfigured:
    EMAIL_HOST_PASSWORD = None

EMAIL_USE_TLS = True
EMAIL_USE_SSL = False

try:
    SIGNALWIRE_PROJECT = env('SIGNALWIRE_PROJECT')
except ImproperlyConfigured:
    SIGNALWIRE_PROJECT = None

try:
    SIGNALWIRE_TOKEN = env('SIGNALWIRE_TOKEN')
    SIGNALWIRE_CLIENT = signalwire_client(SIGNALWIRE_PROJECT, SIGNALWIRE_TOKEN, signalwire_space_url = env('SIGNALWIRE_SPACE_URL'))
except ImproperlyConfigured:
    SIGNALWIRE_TOKEN = None
    SIGNALWIRE_CLIENT = signalwire_client('', '', signalwire_space_url = '')
try:
    SIGNALWIRE_NUMBER = env('SIGNALWIRE_PHONE_NUMBER')
except ImproperlyConfigured:
    SIGNALWIRE_NUMBER = ''

#CA_CARRIERS_LIST = ['@txt.bellmobility.ca','@txt.bell.ca','@fido.ca','@pcs.rogers.com','@msg.telus.com',
#'@vmobile.ca','@msg.koodomobile.com','@sms.sasktel.com','@txt.freedommobile.ca','@mobiletxt.ca']

#CA_CARRIERS_LIST = ['@txt.bell.ca','@pcs.rogers.com','@msg.telus.com','@msg.koodomobile.com','@sms.sasktel.com','@txt.freedommobile.ca']

try:
    MS_TEAMS_MEETING_URL_1 = env('MS_TEAMS_TEMP_LINK_1')
from signalwire.rest import Client as signalwire_client

account = "YOURACCOUNT"
token = "YOURTOKEN"
client = signalwire_client(account,
                           token,
                           signalwire_space_url='yourspace.signalwire.com')

call = client.calls.create(
    to="+1xxx",
    from_="+1yyy",  #must be a number in your Signalwire account
    url="https://cdn.signalwire.com/default-music/playlist.xml",
    method="GET")

print(call)

# get the latest 5 calls and print their statuses
callrec = client.calls.list()
for record in callrec[:5]:
    print(record.sid)
    print(record.status)
Example #20
0
#!/usr/bin/python3

from signalwire.rest import Client as signalwire_client

client = signalwire_client("YOU_PROJECT_ID",
                           "YOU_PROJECT_ID",
                           signalwire_space_url='joshebosh.signalwire.com')

message = client.messages.create(
    from_='+1XXXYYYZZZZ',
    body='this is a test',
    to='+1XXXYYYZZZZ',
    media_url=['http://1co.joshebosh.com/pics/josheboshGIF.gif'])

print(message.sid)
Example #21
0
import boto3
from boto3.dynamodb.conditions import Key
from datetime import datetime
from signalwire.rest import Client as signalwire_client
import requests

# setup

with open(f'{os.path.dirname(__file__)}/keys.json') as f: keys = json.load(f)

tableName = 'sms-ruletable-2'
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(tableName)
client = signalwire_client(
    keys['project-id'], 
    keys['auth-token'], 
    signalwire_space_url = 'smsbot.signalwire.com'
)


# Time

def time_since_midnight():
    now = datetime.now()
    midnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
    return int((now - midnight).total_seconds())

# Lambda 

def get_body ( event ):
    return json.loads(event['body'])
def text_inbound():

    # Initialize the SignalWire client
    client = signalwire_client(
        os.environ['SIGNALWIRE_PROJECT'],
        os.environ['SIGNALWIRE_TOKEN'],
        signalwire_space_url=os.environ['SIGNALWIRE_SPACE'])

    # Read campaigns from json file
    with open('campaigns.json') as f:
        campaigns = json.load(f)

    # Read Do Not Contact Json
    with open('donotcontact.json') as f:
        donotcontact = json.load(f)

    # Read params passed in by request
    phrase = request.values.get("Body")
    number = request.values.get("From")

    print(donotcontact)
    print(number)

    # If number is on do not contact list, ignore request
    for x in donotcontact['DoNotContact']:
        print(x[0])
        if number == x[0]:
            return "200"

    # Trim the phrase provided
    phrase = phrase.strip()

    # Check phrase for STOP / UNSUBSCRIBE
    if phrase.lower() == "stop" or phrase.lower(
    ) == "unsubscribe" or phrase.lower() == "remove":

        # Add number to DoNotContact file
        donotcontact['DoNotContact'].append({number})

        # Write updated DoNotContact to file
        with open('donotcontact.json', 'w') as f:
            print(donotcontact)
            json.dump(donotcontact, f, default=set_default)

        # Send receipt of unsubscribe message
        message = client.messages.create(
            from_=os.environ['SIGNALWIRE_NUMBER'],
            body="You have been removed from our list.",
            to=number)

        # Send email to administrator or your hook logic, unsubscribed
        send_email("Subscriber requested to be removed: \n" + " Number: " +
                   number)

        return "200"

    # Loop through all campaigns for active phrase
    for campaign in campaigns:

        if phrase in campaign["Phrases"]:

            # If the number is in a campaign then they are already subscribed, else add them to the campaign
            for x in campaign['Subscribers']:

                if number == x[0]:

                    # Send already subscribed message
                    message = client.messages.create(
                        from_=os.environ['SIGNALWIRE_NUMBER'],
                        body="You are already subscribed to '" + phrase + "'",
                        to=number)

                else:

                    # Add new number to campaign subscriber list
                    campaign["Subscribers"].append({number})

                    # write updated data to file
                    with open('campaigns.json', 'w') as f:
                        json.dump(campaigns, f, default=set_default)

                    # Send message
                    message = client.messages.create(
                        from_=os.environ['SIGNALWIRE_NUMBER'],
                        body="Thank you for subscribing to '" + phrase + "'",
                        to=number)

                    # Send email to administrator or your hook logic
                    send_email("New subscriber to campaign: " + phrase + "\n" +
                               " Number: " + number)

    return "200"
import os
from signalwire.rest import Client as signalwire_client
import logging
#write requests & responses from SignalWire to log file, useful for debugging:
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(levelname)s %(message)s',
    filename='/usr/local/signalwire/python3/calls/logs/signalwire_calls.log',
    filemode='a')

project = os.environ.get('SIGNALWIRE_API_PROJECT')
token = os.environ.get('SIGNALWIRE_API_TOKEN')
client = signalwire_client(project,
                           token,
                           signalwire_space_url='tornado.signalwire.com')

call = client.calls.create(from_='+14153587900',
                           url='http://your-application.com/docs/voice.xml',
                           to='+16466796505')

#print list of all call properties to console, useful for learning info available you can work with?
print(call.account_sid)
print(call.annotation)
print(call.answered_by)
print(call.api_version)
print(call.caller_name)
print(call.date_created)
print(call.date_updated)
print(call.direction)
print(call.duration)
print(call.end_time)
Example #24
0
from datetime import datetime, timedelta
import numpy as np
import pickle, json

global client, df, LOCATIONS, DEFAULT_RESPONSE, ADVICE, og_date, phone_data, phone_to
phone_to = '+16364749180'
og_date = "03-11-2020"
url = f'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/03-11-2020.csv'
df = pd.read_csv(url)
df['Last Update'] = df['Last Update'].apply(lambda x: x.split("T")[0])
df = df.replace(np.nan, '', regex=True)
LOCATIONS = list(df['Country/Region'].unique()) + list(
    df['Province/State'].unique())

client = signalwire_client(
    "6c37ce1d-ee94-4b5b-961a-2fb9683933b2",
    "PT2cbd11afb7172b795e31508c411a20a7faef8c973e5ac2ac",
    signalwire_space_url='coronasmss.signalwire.com')

DEFAULT_RESPONSE = """Welcome to the corona info line!
Text 'tips' to get information from the CDC about best practices
A location you want the most up to date report. EX: 'Missouri' or 'Italy'
If you want to sign up for daily updates in regards to corona updates text: 'Daily Italy' or 'Daily Washington'"""

ADVICE = """CDC ADVICE: \n
Avoid close contact with people who are sick\n
If you are ill, stay home and seek healthcare if needed\n
Avoid touching your eyes, nose, or mouth with unwashed hands.\n
Cover your coughs or sneezes, in your elbow or into a tissue\n
Wash your hands often with soap and water for at least 20 seconds\n
Clean and disinfect “high touch” objects and surfaces such as doorknobs, faucet handles, railings, and shared keyboards.\n
Get plenty of rest\n
Example #25
0
 def __init__(self):
     self.client = signalwire_client(
         var.projectId,
         var.apiToken,
         signalwire_space_url=var.signalwire_space_url)