-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.py
69 lines (53 loc) · 2.06 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import os
import boto3
from flask import Flask, request
from twilio.rest import Client
TWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID')
TWILIO_AUTH_TOKEN = os.environ.get('TWILIO_AUTH_TOKEN')
TWILIO_PHONE_NUMBER = os.environ.get('TWILIO_PHONE_NUMBER')
ALLOWED_SENDER = os.environ.get('ALLOWED_SENDER')
EC2_INSTANCE_ID = os.environ.get('EC2_INSTANCE_ID')
EC2_REGION = os.environ.get('EC2_REGION')
client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
app = Flask(__name__)
ec2 = boto3.resource('ec2', region_name=EC2_REGION)
@app.route('/', methods=['POST'])
def handle_text():
"""
Takes a text message. If the content is "VPN ON" it starts the VPN box, if the content is "VPN OFF" it
stops the VPN box. When the command is done, a follow up text is returned to the sender.
"""
sender = request.values.get('From', '')
if sender != ALLOWED_SENDER:
# Only allow from my number, disregard the message.
return "Success"
content = request.values.get('Body', '')
instance = ec2.Instance(EC2_INSTANCE_ID)
if content.lower() == 'vpn off':
if instance.state['Name'] != 'running':
msg = 'The VPN is not running and has a status of: {}'.format(instance.state['Name'])
respond_with(msg)
return "Success"
instance.stop()
respond_with("The instance has been stopped")
elif content.lower() == 'vpn on':
if instance.state['Name'] != 'stopped':
msg = 'The VPN is not off, please try again later. It has a state of: {}'.format(instance.state['Name'])
respond_with(msg)
return "Success"
instance.start()
respond_with("The instance has been started")
else:
respond_with("I only respond to the commands 'VPN on' and 'VPN off'")
return "Success"
def respond_with(text):
"""
Sends a text message response to the sender
"""
client.messages.create(
body=text,
from_=TWILIO_PHONE_NUMBER,
to=ALLOWED_SENDER
)
if __name__ == '__main__':
app.run(debug=True, port=3000)