# twilio is external package
# To download in windpows open cmd and type the commands pip install twilio
# Go to official website of twilio and sign up
# After signing up, you will get your Account sid, authorization token and twilio phone number
from twilio.rest import Client

Account_sid = "ACf1ebdb3f0b7d1d8b6f9c5b9daff132c8"
Auth_token = "00d9672af167fbf501f851d70f2a5e88"

client = Client(Account_sid, Auth_token)

message = client.messages.create(
    body="My name is afzaal",
    to="+917702993904",  #  replace with your registered phone number
    from_="+114172655607")  # replace with your twilio phone number

print(message.sid)
Beispiel #2
0
# When everything done, release the capture
                    cap.release()
                    out.release()
                print("Video Saved.")

#Sendinf the saved video of the unknown person via Email


                

                

#Send SMS
               TWILIO_SID = "AC5dd4f3412ee73c41b76c12be1802d3e1"
               TWILIO_AUTH = "a692cb465ae735cf88ed59ded6de3fa6"
               client = Client(TWILIO_SID, TWILIO_AUTH)
               TO = "phone number 1"
               FROM "phone number 2"
client.messages.create(to=TO, from_=FROM, body="Alert! unknown person is detected"
                f=False
  
# stop the timer and display FPS information
fps.stop()

print("[INFO] elasped time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))

# do a bit of cleanup
cv2.destroyAllWindows()
vs.stop()
Beispiel #3
0
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Required to use Flask sessions and the debug toolbar
app.secret_key = os.environ.get("APPSECRET_KEY")

# Normally, if you use an undefined variable in Jinja2, it fails
# silently. This is horrible. Fix this so that, instead, it raises an
# error.
app.jinja_env.undefined = StrictUndefined

twilio_account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
twilio_auth_token = os.environ.get('TWILIO_AUTH_TOKEN')

twilio_client = Client(twilio_account_sid, twilio_auth_token)

GBOOKS_KEY = os.environ.get("GBOOKS")


@app.route('/')
def index():
    """Homepage."""

    return render_template("homepage.html")


@app.route('/register', methods=['GET'])
def register_form():
    """Display form for user signup."""
Beispiel #4
0
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
import json
import random
import time
import hashlib
import threading
import asyncio

# Your Account Sid and Auth Token from twilio.com/console
# DANGER! This is insecure. See http://twil.io/secure
account = json.load(open('account.json', encoding="utf8"))

client = Client(account["account_sid"], account["auth_token"])

# Scripts Json
scripts = json.load(open('scripts.json', encoding="utf8"))
start_state = scripts["init"]

# States Json
states = json.load(open('states.json', encoding="utf8"))


def say_after(delay, what, number):
    time.sleep(delay)
    message = client.messages \
                .create(
                     body=what,
                     from_=account["number"],
willrain = False

parameters = {
    "appid": OWM_API_KEY,
    "exclude": "current,minutely,daily",
    "lat": MY_LAT,
    "lon": MY_LON
}

response = requests.get("https://api.openweathermap.org/data/2.5/onecall", params=parameters)
response.raise_for_status()

hourly: [] = response.json()["hourly"][:12]

for tempdata in hourly:
    if tempdata["weather"][0]["id"] < 700:
        willrain = True

if willrain:
    client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)

    message = client.messages \
        .create(
            body="It's going to rain today. Remember to bring an umbrella.",
            from_="YOUR TWILIO PHONE NUMBER",
            to="YOUR PHONE NUMBER"
        )

    print(message.status)
Beispiel #6
0
def send_text(message, sid, token, to_num, from_num):
    # Create Client object and send text using provided information
    client = Client(sid, token)
    text = client.messages.create(body='Our records show that ' + message,
                                  from_=from_num,
                                  to=to_num)
Beispiel #7
0
# check.py
import os
from appconfig import TwilioConfig, PayloadConfig, DBConfig
import json
import requests
import pymongo
from pymongo import MongoClient
from twilio.rest import Client
import datetime as dt

acc_sid, auth_t, twil_num = TwilioConfig()
user, pwrd, location = DBConfig()
m_corps, w_corps, entry = PayloadConfig()

tw_client = Client(acc_sid, auth_t)
uri = 'mongodb://' + user + ':' + pwrd + location
client = MongoClient(uri, connectTimeoutMS=30000)
db = client.get_database("coatcheck")
jacket = db.jacket


def sendMessage(twilioclient, msg_body, msg_from, msg_to):
    message = twilioclient.messages.create(body=msg_body,
                                           from_=msg_from,
                                           to=msg_to)


def updateLastStock(size, item):
    '''
  Params: Size, Item
  Function: Updates the stock of a specified item and size in the database
Beispiel #8
0
def clientRegister(request):
    if request.method == "POST":
        form = ClientRegistration(request.POST)
        print(request.POST)
        if form.is_valid():
            name = form.cleaned_data.get('name')
            phone = form.cleaned_data.get('phone')
            email = form.cleaned_data.get('email')
            altUser = Clients.objects.filter(email=email, phone=phone)
            print(altUser)
            if altUser.exists():
                user = Clients.objects.get(name=altUser[0])
                user.inMeeting = True
                user.checkInTime = timezone.now()
                user.checkOutTime = timezone.now()
                user.save()
            else:
                user = Clients(name=name, phone=phone, email=email)
                user.inMeeting=True
                user.checkInTime = timezone.now()
                user.checkOutTime = timezone.now()
                user.save()
            print(name, phone, email, user)
            print(user.checkInTime, Clients.objects.get(name=user.name).inMeeting)
            if user is not None:

                # # Sending Email to Host
                m = "Hey {host}, {guest} just checked-in for the meeting. {guest}'s email  is {email} and phone number is {phoneNum}".format(
                    host=request.user.username,
                    guest=user.name,
                    email=user.email,
                    phoneNum=user.phone
                )
                message = Mail(
                    from_email=os.environ.get('DEFAULT_FROM_EMAIL'),
                    to_emails=request.user.email,
                    subject='Check-In from new Guest',
                    html_content=m)

                sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
                response = sg.send(message)
                print(response.status_code, response.body, response.headers)
                print('Email send')


                # SMS send to host
                smsContext = {
                    "host": request.user.username,
                    "guestName": user.name,
                    "guestEmail": user.email,
                    "guestPhone": phone
                }
                client = Client(settings.ACCOUNT_SID, settings.AUTH_TOKEN)
                smsBody = render_to_string("snippets/sms.html", smsContext)
                smsPhone = "+{}{}".format(request.user.profile.phone.country_code,
                                          request.user.profile.phone.national_number)
                print(smsBody, smsPhone)
                try:
                    smsMessage = client.messages \
                        .create(
                            body=smsBody,
                            from_=os.environ.get('TWILIO_PHONE_NUMBER'),
                            to=smsPhone
                        )
                    print(smsMessage.sid)
                    print('SMS send')

                except:
                    print('SMS send failed')

                messages.success(request, 'Thanks for Checking-In. Enjoy the meeting.')
                print(user, user.checkInTime, user.checkOutTime)
                return redirect(reverse('god:client'))

    else:
        form = ClientRegistration(None)

    context = {
        "form": form
    }

    return render(request, 'auth/clientRegistration.html', context)
 def __init__(self):
     # Find these values at https://twilio.com/user/account
     account_sid = app.config['TWILIO_ACCOUNT_SID']
     auth_token = app.config['TWILIO_AUTH_TOKEN']
     self.client = Client(account_sid, auth_token)
Beispiel #10
0
 def __init__(self):
     self.account_sid = os.environ["TWILIO_ACCOUNT_SID"]
     self.auth_token = os.environ["TWILIO_AUTH_TOKEN"]
     self.messaging_service_sid = os.environ["MESSAGING_SERVICE_SID"]
     self.to = os.environ["PHONE_NUMBER"]
     self.message = Client(self.account_sid, self.auth_token).messages
Beispiel #11
0
import getrecipe

from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse, Message
from twilio.rest import Client
import urllib
import requests
from random import randint

# Account SID and Auth Token from www.twilio.com/console
client = Client('AC14dec95859e2f7bbfe87f47536d1e471',
                'bb8cf2f2f568bc4d18f31894c293f33c')
app = Flask(__name__)


# A route to respond to SMS messages and kick off a phone call.
@app.route('/sms', methods=['GET', 'POST'])
def inbound_sms():
    response = MessagingResponse()
    food_item = urllib.quote(request.form['Body'])
    recipe = getrecipe.get_recipe(food_item)
    ingridients = ['\n']

    for i in range(len(recipe[3])):
        ingridients[0] += (recipe[3][i].encode("utf-8"))
        ingridients[0] += ("\n")

    response.message("\nName \n" + recipe[0].encode("utf-8") +
                     "\n Recipe Link \n" + recipe[1].encode("utf-8") +
                     "\n Calories - " + str(recipe[2]).encode("utf-8") + "\n" +
                     ingridients[0])
Beispiel #12
0
askSMS = input('I can text you new articles every day at noon while this process runs. Interested? (Y/N)')

# prompt intro message if yes, otherwise exit program
if askSMS.lower() == 'y' or askSMS.lower() == 'yes':
    print('''
Great! 
Because there are mischievous people out there, you will need a Twilio account for this to work.
If you don't have an account, please sign up at https://www.twilio.com/login to get started.
''')
else:
    print('Kk, goodbye!')
    exit()

# get account info from Twilio
accountSID = input('Enter your account SID: ')
authToken = input('Enter your Auth Token: ')
twilioCli = Client(accountSID, authToken)
myTwilioNumber = input('Enter your Twilio number in format +15551234567: ')
myCellNumber = input('Enter you cellphone number in format +15551234567: ')

# set a daily action at noon using schedule 
schedule.every().day.at("12:00").do(
    # create and send message
    message=twilioCli.messages.create(
        body='\nHere is your latest article from The Onion:\n' + listings[chooseArticle]['url'],
        from_=myTwilioNumber,
        to=myCellNumber
    )
)
Beispiel #13
0
 def sendSms(self, matches, phoneNumber):
     client = Client("REMITTED FOR GITHUB", "REMITTED FOR GITHUB")
     client.messages.create(to=f"+1{phoneNumber}",
                            from_="+12052878153",
                            body=f"Matches found: {matches}")
Beispiel #14
0
# Make a Twilio account and fill information in here
# Options
phone_receive = '' # '+15557362'
phone_send = '' # '+15557362'
SID = ''
auth_token = ''
# /

# Imports
from twilio.rest import Client
#/

# Setup
client = Client(SID, auth_token)
# /

# Defs
def send_message(msg):
    message = client.messages.create(from_=phone_send, body=msg, to=phone_receive) 
# /
from twilio.rest import Client
import os

# Initialize the client
account = os.environ.get("TWILIO_ACME_ACCOUNT_SID")
token = os.environ.get("TWILIO_ACME_AUTH_TOKEN")
chat_service = os.environ.get("TWILIO_ACME_CHAT_SERVICE_SID")

client = Client(account, token)

messages = client.chat \
                .services(chat_service) \
                .channels("CH1cfc90f587304eafb7af60199aceb635") \
                .messages \
                .list()

for message in messages:
    print(message.from_ + ": " + message.body)
def setup_twilio_client():
    account_sid = secrets.TWILIO_ACCOUNT_SID
    auth_token = secrets.TWILIO_AUTH_TOKEN
    return Client(account_sid, auth_token)
Beispiel #17
0
from apscheduler.schedulers.background import BackgroundScheduler
import datetime
from flask import Flask, request, redirect, jsonify
from flask_cors import CORS
from json import loads
import math
import random
import requests
import twilio.twiml
from twilio.twiml.messaging_response import MessagingResponse
from twilio.rest import Client

client = Client("AC4e7890114509da5929a4bc79ebf8bdc0",
                "47ee8d75ad0e2973601122c2a65d7b7c")

app = Flask(__name__)
CORS(app)

database = {}
comments = {}
new_event_id = -1
subscribers = {"+16475153544"}
# This has a sample user.
# They want to be alerted via text, for all crimes that occur.


def distance(loc, event):
    x_loc = loc[0]
    y_loc = loc[1]
    x_event = event[2]
    y_event = event[3]
def textmyself(message):
    c = Client(account_SID, auth_token)
    c.messages.create(body=message, from_=twilio_number, to=my_number)
Beispiel #19
0
#Get the chapter of the book from the webpage
chapter = soup.find("h4", class_="chapter").text.lstrip("CHAPTER ")

all_verses = soup.findAll("p", class_="verses")
mychoice = random.choice(all_verses)

message = book + chapter + ":" + mychoice.text.lstrip()

print(message)

#text my choice to my phone!
accountSID = 'ACd6351ff4800a312d3756d77307724047'

authToken = '4b146ee9261e04a21ad2736e8fa0e3ab'

client = Client(accountSID, authToken)

TwilioNumber = ""

myCellPhone = ""

#send text message
textmessage = client.messages.create(to=myCellPhone,
                                     from_=TwilioNumber,
                                     body=message)
print(accountSID)

# to set it up to automatically run this program, set it up in task manager:
# create a .bat file that has the line:

# python "C:\Users\johnny_bhojwani\Box Sync\MIS 4V98 - PYTHON\Web Scaping\webscraping - Bible - Recovery Version - KEY.py
difference = yesterday_closing_price - day_before_yesterday_closing_price

diff_percent = round(difference / yesterday_closing_price) * 100
up_down = None
if difference > 0:
    up_down = "🔺"
else:
    up_down = "🔻"

if abs(diff_percent) > 5:
    news_params = {
        "apiKey": NEWS_API_KEY,
        "qInTitle": COMPANY_NAME,
    }

    news_response = requests.get(NEWS_ENDPOINT, params=news_params)
    articles = news_response.json()['articles']
    three_articles = articles[:3]
    formatted_articles = [
        f"{STOCK_NAME}: {up_down}{diff_percent}%\nHeadline: {article['title']}. \nBrief: {article['description']}"
        for article in three_articles
    ]

    client = Client(TWILIO_SID, TWILIO_AUTH_TOKEN)
    for article in formatted_articles:
        message = client.messages.create(
            body=article,
            from_="+15103302089",
            to="",
        )
def send_sms(msg, to_number):
    twilio_client = Client(settings.TWILIO_ACCOUNT_SID,
                           settings.TWILIO_AUTH_TOKEN)
    from_number = settings.TWILIO_FROM_NUMBER

    twilio_client.messages.create(body=msg, to=to_number, from_=from_number)
Beispiel #22
0
from twilio.rest import Client

# setting up the auth
account = "AC3547c4a4a87da54f6998d4a25bda063751" # random token
auth_token = "8a2fbe9744c3das72667e9421d4ff3e0a04" # random auth token

client = Client(account, auth_token)

def send_message(client=client, message=None):
    message = client.messages.create(to="+122241244", from_="+1421341445", body = message)


Beispiel #23
0
import scipy.signal
import time
from numba import jit
import sys
import datetime
import torch
from joblib import load
import twilio
from twilio.rest import Client
#add rainfallcamera module
sys.path.append('../rainfallcamera/')
from PReNet.generator import Generator_lstm
from PReNet.execute_cpu import RRCal

#SMS configuration, pls comment if you do not want to use SMS alert
client = Client('ACed145775d56edb163f7c8790e8947fcf',
                '66f63f8d7ee7194804ed0e0b06c978a1')


def get_video(use_GPU,
              ip='10.65.1.71',
              port='8080',
              username='******',
              password='******'):
    #construct url
    url = 'http://%s:%s@%s:%s/stream/video/mjpeg?resolution=HD' % (
        username, password, ip, port)
    cap = cv2.VideoCapture(url)
    first = True
    rnn_model = readmodel(use_GPU)
    cls_model = class_model()
    records_time = datetime.datetime.now().strftime("%Y-%m-%d")
Beispiel #24
0
def notify_me(message):
    client = Client(account_sid, auth_token)
    message = client.messages.create(body=message,
                                     from_=config["from_number"],
                                     to=config["to_number"])
Beispiel #25
0
from os import environ as env
from twilio.rest import Client

# Twilio Config
ACCOUNT_SID = env.get("ACCOUNT_SID")
AUTH_TOKEN = env.get("AUTH_TOKEN")
FROM_NUMBER = env.get("FROM_NUMBER")
TO_NUMBER = env.get("TO_NUMBER")

# create a twilio client using account_sid and auth token
tw_client = Client(ACCOUNT_SID, AUTH_TOKEN)


def send(payload_params=None):
    """send sms to the specified number"""
    msg = tw_client.messages.create(
        from_=FROM_NUMBER, body=payload_params["msg"], to=TO_NUMBER
    )

    if msg.sid:
        return msg
def init_twilio():
    account_sid = "AC0d464a30a7c6e7fbacd8dab0441ae589"
    auth_token = "0753453d03c18573e2c09ba41f925a8f"
    client = Client(account_sid, auth_token)
    return client
Beispiel #27
0
 def __init__(self):
     self.client = Client(TWILIO_SID, TWILIO_AUTH_TOKEN)
Beispiel #28
0
def que(url):
    r = requests.get(url)

    if r.text[3:7] != 'avai':
        print(url)
        fin(r.text)

    decoded = r.content.decode('utf-8-sig')
    data = json.loads(decoded)
    sku = data['availabilities'][0]['sku']
    avai = data['availabilities'][0]['shipping']['purchasable']

    if not avai and sku == sku1:
        print('1 no')
        return

    if not avai and sku == sku2:
        print('2 no')
        return

    if not avai and sku == sku3:
        print('3 no')
        return

    if avai and sku == sku1:
        client = Client(account_sid, auth_token)
        client.messages.create(
                body='MARIO STOCK! ' + purchase1,
                from_='+17784880707',
                to='+17789182800'
            )
        client.messages.create(
                body='ASK MIKE WHAT HAPPENED!',
                from_='+17784880707',
                to='+17789802577'
            )
        print('1 yes')
        fin('EXIT WITH MARIO')

    if avai and sku == sku2:
        client = Client(account_sid, auth_token)
        client.messages.create(
                body='GREY STOCK! ' + purchase2,
                from_='+17784880707',
                to='+17789182800'
            )
        client.messages.create(
                body='ASK MIKE WHAT HAPPENED!',
                from_='+17784880707',
                to='+17789802577'
            )
        print('2 yes')
        fin('EXIT WITH GREY')

    if avai and sku == sku3:
        client = Client(account_sid, auth_token)
        client.messages.create(
                body='R&B STOCK! ' + purchase3,
                from_='+17784880707',
                to='+17789182800'
            )
        client.messages.create(
                body='ASK MIKE WHAT HAPPENED!',
                from_='+17784880707',
                to='+17789802577'
            )
        print('3 yes')
        fin('EXIT WITH R&B')

    else:
        print('ERROR')
        print(url)
        fin('ERROR')
if __name__ == "__main__":
    url = input(colored("Enter the product Link: ","blue"))
    mobile_num = input(colored("\nEnter your Phone number to recieve Alerts: +91-","blue"))
    price_set = input(colored("\nEnter the Target Price: ","red"))

    write_csv.save(url, mobile_num, price_set)

    HEADERS = { "user-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'}
    req = requests.get(url,headers=HEADERS)
    soup = BeautifulSoup(req.content, 'lxml')
    price = (soup.find(id='priceblock_ourprice').text)
    product = soup.find(id='productTitle').text.strip()
    price_curr = float((price.split()[1]).replace(',',''))

    twilio_info = pandas.read_csv('twilio_info.csv')
    account_sid = str(twilio_info.loc[0,'account_sid'])
    auth_token = str(twilio_info.loc[0,'auth_token'])
    client = Client(account_sid, auth_token)
    message = client.messages.create(
                              from_='whatsapp:+14155238886',
                              body='Hello! This is a WhatsAppPriceAlert. \n\nYour Price Alert Has Been Set.\n\nYour product *'+product+'* \n\nCurrent Price: *'+price+'*'+'\nTarget Price set: *'+price_set+'*',
                              to='whatsapp:+91' + mobile_num
                          )
    print(colored('\nYour Price Alert Has Been Set.'+'\n',"green")+message.sid)
    print(colored('\nChecking...','red'))
    track.check()
    schedule.every().hour.do(track.check)
    while True:
        schedule.run_pending()
        time.sleep(1)
Beispiel #30
0
 def setup_clients(self):
     """Initializes API clients using initialized keys"""
     self.wa_client = wolframalpha.Client(self._wa_key)
     self.owm_client = pyowm.OWM(self._owm_key)
     self.sr_client = sr.Recognizer()
     self.twilio_client = Client(self._twilio_sid, self._twilio_token)