-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathussd.py
More file actions
141 lines (127 loc) · 4.84 KB
/
ussd.py
File metadata and controls
141 lines (127 loc) · 4.84 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
131
132
133
134
135
136
137
138
139
140
141
from flask import Flask, request, Response
from dotenv import load_dotenv
import os
import google.generativeai as genai
import logging
import re
#simple logging for debugging
logging.basicConfig(level=logging.INFO)
# Load environment variables
load_dotenv()
app = Flask(__name__)
# Configure Gemini
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
model = genai.GenerativeModel("gemini-flash-1.5")
api_key = os.getenv("GOOGLE_API_KEY")
if not api_key:
raise ValueError("GOOGLE_API_KEY not found in .env file.")
genai.configure(api_key=api_key)
#Define helper function outsdie the route
def clean_response(text):
"""Remove markdown and extra formatting for USSD"""
return re.sub(r'[\*\#\_\`\~]', '', text.replace('\n', ' '))[:1600]
@app.before_request
def log_request():
logging.info(f"Request from {request.form.get('phoneNumber')}: {request.form.get('text')}")
@app.route('/ussd', methods=['POST'])
def ussd():
text = request.values.get('text', '')
session_id = request.values.get('sessionId', '')
phone_number = request.values.get('phoneNumber', '')
service_code = request.values.get('serviceCode', "")
logging.info(f"Incoming USSD request: {text}")
# Split user input (USSD uses * to separate steps)
steps = text.split('*')
response = ""
# main menu
if text == "":
response = "CON Welcome to Bitcoin Academy\n"
response += "1. What is Bitcoin?\n"
response += "2. How Bitcoin Works\n"
response += "3. Bitcoin vs Traditional Currencies\n"
response += "4. Ask AI Assistant"
# Step 1: What is bitcoin
elif text == '1':
response = (
"CON Bitcoin is digital money that anyone can send or receive without a bank.\n\n"
"1. Next\n"
"0. Back"
)
elif text == "1*0":
response = (
"CON Welcome to Bitcoin Academy\n"
"1. What is Bitcoin?\n"
"2. How Bitcoin Works\n"
"3. Bitcoin vs Traditional Currencies\n"
"4. Ask AI Assistant"
)
elif text == "1*1": # if user selects Next
response = (
"CON Bitcoin is secure, borderless and limited to 21 million coins.\n"
"People preferit because it gives controlover their own money.\n"
"0. Back"
)
elif text == "1*0": # if user selects Back
response = (
"CON Welcome to Bitcoin Academy\n"
"1. What is Bitcoin?\n"
"2. How Bitcoin Works\n"
"3. Bitcoin vs Traditional Currencies\n"
"4.Ask AI Assistant"
)
# step2: How Bitcoin Works
elif text == "2":
response = (
"CON Bitcoin works on a network of computers that share one record - called the blockchain.\n\n"
"1. Next\n"
"0. Back"
)
elif text == "2*1": # user selects Next
response = (
"END When you send Bitcoin, computers confirm the transaction and add it to the blockchain. "
"No bank controls it - the system runs through people all over the world."
)
elif text == "2*0": # user selects Back
response = (
"CON Welcome to Bitcoin Academy\n"
"1. What is Bitcoin?\n"
"2. Bitcoin vs Traditional Currencies\n"
"3. Bitcoin Myths"
"4.Ask AI Assistant"
)
# step3: Bitcoin vs Traditional Currencies
elif text == "3":
response = (
"CON Traditional money is controlled by banks.\n"
"Bitcoin is controlled by no one, it is open to everyone.\n\n"
"Key Differences:\n"
"Bitcoin is limited - no inflation.\n"
"You control your money - no permission needed.\n\n"
"0. Back"
)
elif response == "0":
response = (
"CON Welcome to Bitcoin Academy\n"
"1. What is Bitcoin?\n"
"2. How Bitcoin Works\n"
"3. Bitcoin vs Traditional Currencies\n"
"4.Ask AI Assistant"
)
elif steps[0] == "4":
if len(steps) == 1:
response = "CON Ask me any Bitcoin question:"
else:
user_question = " ".join(steps[1:])
prompt = f"Explain this simply to a beginner in Bitcoin and new to technology make it short and easy to relate to: {user_question}"
try:
result = model.generate_content(prompt)
ai_response = clean_response(result.text)
response = f"END {ai_response[:1600]}" # Limit length for USSD
except Exception as e:
response = f"END Sorry, something went wrong: {str(e)}"
else:
response = "END Invalid choice. Please try again."
return Response(response, mimetype="text/plain")
if __name__ == '__main__':
port = int(os.getenv("PORT", 5000))
app.run(host='0.0.0.0', port=port, debug=True)