# sms_processor.py
import subprocess
import re
import requests
import logging
import sqlite3
import sys
import json
from urllib.parse import quote
# Logging yapılandırması
logging.basicConfig(
level=logging.DEBUG, # Daha fazla detay için DEBUG seviyesine çektik
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[
logging.FileHandler("sms_processor.log"),
logging.StreamHandler()
]
)
DB_FILE = "smsai.db"
PROCESSED_SMS_FILE = "processed_sms.json"
def init_db():
"""Veritabanını başlatır ve gerekli tabloları oluşturur."""
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
# numbers tablosu
cursor.execute('''
CREATE TABLE IF NOT EXISTS numbers (
number TEXT PRIMARY KEY,
coin INTEGER DEFAULT 20,
name TEXT,
mail TEXT
)
''')
# messages tablosu
cursor.execute('''
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
number TEXT,
direction TEXT,
content TEXT,
ai_response_id INTEGER,
receivedno INTEGER,
FOREIGN KEY(number) REFERENCES numbers(number)
)
''')
conn.commit()
conn.close()
def load_processed_sms():
"""Processed SMS ID'lerini JSON dosyasından yükler."""
try:
with open(PROCESSED_SMS_FILE, 'r') as f:
processed = json.load(f)
processed_set = set(str(id_) for id_ in processed)
logging.debug(f"Processed SMS IDs loaded: {processed_set}")
return processed_set
except FileNotFoundError:
logging.debug("Processed SMS file not found. Creating a new one.")
return set()
except json.JSONDecodeError as e:
logging.error(f"Processed SMS JSON decode error: {e}")
return set()
def save_processed_sms(processed_sms):
"""Processed SMS ID'lerini JSON dosyasına kaydeder."""
try:
with open(PROCESSED_SMS_FILE, 'w') as f:
json.dump(list(processed_sms), f)
logging.debug(f"Processed SMS IDs saved: {processed_sms}")
except Exception as e:
logging.error(f"Error saving processed SMS IDs: {e}")
def get_number(number):
"""Veritabanında numarayı kontrol eder."""
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute("SELECT * FROM numbers WHERE number = ?", (number,))
result = cursor.fetchone()
conn.close()
return result
def add_number(number, name="", mail="", coin=20):
"""Yeni bir numara ekler."""
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute("INSERT OR IGNORE INTO numbers (number, coin, name, mail) VALUES (?, ?, ?, ?)",
(number, coin, name, mail))
conn.commit()
conn.close()
def update_coins(number, amount):
"""Kullanıcının coin bakiyesini günceller."""
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute("UPDATE numbers SET coin = coin + ? WHERE number = ?", (amount, number))
conn.commit()
cursor.execute("SELECT coin FROM numbers WHERE number = ?", (number,))
coin = cursor.fetchone()[0]
conn.close()
return coin
def deduct_coin(number, amount=1):
"""Kullanıcının coin bakiyesinden belirtilen miktarı düşer."""
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute("UPDATE numbers SET coin = coin - ? WHERE number = ?", (amount, number))
conn.commit()
cursor.execute("SELECT coin FROM numbers WHERE number = ?", (number,))
result = cursor.fetchone()
if result:
coin = result[0]
else:
coin = 0
conn.close()
return coin
def log_message(number, direction, content, ai_response_id=None, receivedno=None):
"""Mesajı veritabanına kaydeder."""
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO messages (number, direction, content, ai_response_id, receivedno)
VALUES (?, ?, ?, ?, ?)
''', (number, direction, content, ai_response_id, receivedno))
conn.commit()
message_id = cursor.lastrowid
conn.close()
return message_id
def normalize_text(text):
"""Türkçe karakterleri uygun şekilde dönüştürür."""
replacements = {
'ç': 'c', 'Ç': 'C',
'ğ': 'g', 'Ğ': 'G',
'ı': 'i', 'İ': 'I',
'ö': 'o', 'Ö': 'O',
'ş': 's', 'Ş': 'S',
'ü': 'u', 'Ü': 'U',
}
return ''.join(replacements.get(c, c) for c in text)
def send_to_ai(prompt):
"""Sends the SMS message to the AI service and returns the response."""
# Normalize and prepare the prompt
normalized_prompt = normalize_text(prompt)
# Define the API endpoint
url = "https://text.pollinations.ai/openai"
# Construct the payload following OpenAI's ChatGPT API format
payload = {
"model": "gpt-3.5-turbo", # Specify the model; adjust as needed
"messages": [
{"role": "user", "content": normalized_prompt}
],
"stream": True # Enable streaming
}
headers = {
"Content-Type": "application/json"
# No Authorization header needed since no API key is required
}
try:
logging.debug(f"Sending request to AI endpoint: {url} with payload: {payload}")
# Make a POST request with streaming enabled
response = requests.post(url, headers=headers, data=json.dumps(payload), stream=True)
if response.status_code != 200:
logging.warning(f"AI service returned status code {response.status_code}")
return "AI servisine bağlanılamadı."
ai_response = ""
# Process the streaming response
for chunk in response.iter_lines():
if chunk:
try:
# Each chunk is a JSON object prefixed with "data: "
decoded_chunk = chunk.decode('utf-8').strip()
if decoded_chunk == "data: [DONE]":
break
if decoded_chunk.startswith("data: "):
json_data = json.loads(decoded_chunk.replace("data: ", ""))
# Extract the assistant's partial message
delta = json_data.get("choices", [{}])[0].get("delta", {}).get("content", "")
ai_response += delta
# Optionally, you can log or process each delta here
except json.JSONDecodeError as e:
logging.error(f"JSON decode error: {e}")
except Exception as e:
logging.error(f"Error processing stream chunk: {e}")
logging.info("AI yanıtı alındı.")
return ai_response.strip()
except Exception as e:
logging.error(f"AI servisi hatası: {e}")
return f"AI servisi hatası: {e}"
def extract_sms_id(log_line):
"""Log satırından SMS ID'sini çıkartır."""
match = re.search(r'uri:\s+content://sms/(\d+)', log_line)
if match:
sms_id = match.group(1).strip()
logging.debug(f"Extracted SMS ID: {sms_id}")
return sms_id
return None
def parse_sms_content(sms_id):
"""SMS içeriğini sorgular ve adres ile body'yi döndürür."""
try:
cmd = [
'adb', 'shell', 'content', 'query',
'--uri', f'content://sms/{sms_id}',
'--projection', 'address,body,type'
]
logging.debug(f"Running command: {' '.join(cmd)}")
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if result.stderr:
logging.error(f"SMS query hatası: {result.stderr}")
return None, None
# Tam çıktıyı loglama
logging.debug(f"SMS query output: {result.stdout}")
address = None
body = None
sms_type = None
# 'address', 'body' ve 'type' alanlarını regex ile çıkarma
address_search = re.search(r'address=([^,]+)', result.stdout)
if address_search:
address = address_search.group(1).strip()
logging.debug(f"Address: {address}")
else:
logging.debug("Address bulunamadı.")
body_search = re.search(r'body=(.*)', result.stdout)
if body_search:
body_full = body_search.group(1).strip()
# Remove ', type=1' or similar suffix
body = re.sub(r',\s*type=\d+', '', body_full).strip()
logging.debug(f"Body (cleaned): {body}")
else:
logging.debug("Body bulunamadı.")
type_search = re.search(r'type=(\d+)', result.stdout)
if type_search:
sms_type = int(type_search.group(1))
logging.debug(f"SMS Type: {sms_type}")
else:
logging.debug("Type bulunamadı.")
# Sadece gelen SMS'leri işle
if sms_type != 1:
logging.debug("SMS tipi alındı ancak gelen SMS değil, işlenmiyor.")
return None, None
logging.debug(f"Parsed SMS - Address: {address}, Body: {body}, Type: {sms_type}")
return address, body
except Exception as e:
logging.error(f"SMS parse hatası: {e}")
return None, None
def escape_message(message):
"""SMS mesajındaki boşluk ve özel karakterleri kaçırır."""
escape_chars = {
' ': '\\ ',
'-': '\\-',
'!': '\\!',
'"': '\\"',
"'": "\\'",
'\\': '\\\\',
'(': '\\(', # Açık parantez
')': '\\)', # Kapalı parantez
'&': '\\&', # Ampersand
';': '\\;', # Noktalı virgül
'|': '\\|', # Boru
'<': '\\<', # Küçük eşit
'>': '\\>', # Büyük eşit
'$': '\\$', # Dolar işareti
'`': '\\`', # Backtick
'*': '\\*', # Yıldız
'?': '\\?', # Soru işareti
}
escaped = ''.join([escape_chars.get(c, c) for c in message])
return escaped
def send_sms(number, message):
"""Yanıt mesajını ShellMS aracılığıyla gönderir."""
try:
escaped_message = escape_message(message)
cmd = [
'adb', 'shell', 'am', 'startservice', '--user', '0',
'-n', 'com.android.shellms/.sendSMS',
'--es', 'contact', number,
'--es', 'msg', escaped_message # Mesajı kaçırılmış şekilde gönder
]
# Komutun loglanması için, 'shell' altındaki tüm argümanları loglamalıyız.
logging.debug(f"Executing ShellMS command: adb {' '.join(cmd[1:])}")
subprocess.run(cmd, check=True)
logging.info(f"Yanıt SMS olarak gönderildi: {number} -> {message}")
except subprocess.CalledProcessError as e:
logging.error(f"SMS gönderim hatası: {e}")
except Exception as e:
logging.error(f"SMS gönderim hatası: {e}")
def main():
"""Ana döngü."""
init_db()
logging.info("SMS dinleniyor...")
processed_sms = load_processed_sms()
try:
# adb logcat komutunu çalıştır
process = subprocess.Popen(
['adb', 'logcat', '-v', 'time'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
universal_newlines=True
)
except Exception as e:
logging.error(f"Logcat başlatma hatası: {e}")
sys.exit(1)
# Logcat satırlarını oku
try:
for line in process.stdout:
line = line.strip()
if 'ReceiveSmsMessageHelper: Received SMS message' in line:
logging.debug(f"Detected SMS log line: {line}")
sms_id = extract_sms_id(line)
if sms_id and sms_id not in processed_sms:
logging.debug(f"Processing SMS ID: {sms_id}")
# Parse SMS content
address, body = parse_sms_content(sms_id)
if address and body:
logging.debug(f"Parsed SMS - Address: {address}, Body: {body}")
# Log the received message in the database
received_message_id = log_message(address, 'received', body)
# Add Sms ID to processed list
processed_sms.add(sms_id)
save_processed_sms(processed_sms)
# Check if the number is registered
user = get_number(address)
if user:
coins = user[1]
logging.debug(f"Kullanıcı {address} bulundu. Coin: {coins}")
if body.startswith('#'):
if coins >= 1:
prompt = body.lstrip('#').strip()
logging.info(f"Gelen SMS: {address} - {prompt}")
ai_response = send_to_ai(prompt)
if ai_response:
# Deduct coins
remaining_coins = deduct_coin(address, 1)
logging.debug(f"{address} numaralı kullanıcının kalan coin sayısı: {remaining_coins}")
# Prepare AI message with coin info
ai_message = f"Coin:{remaining_coins} - {ai_response}"
# Send AI response
send_sms(address, ai_message)
# Log the sent message with reference to received message
sent_message_id = log_message(address, 'sent', ai_message, receivedno=received_message_id)
# Update AI response ID in received message
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute("UPDATE messages SET ai_response_id = ? WHERE id = ?", (sent_message_id, received_message_id))
conn.commit()
conn.close()
# Save changes
logging.info(f"Yanıt SMS olarak gönderildi: {address} -> {ai_message}")
else:
# Coin yeterli değil, gönderim yapma
zero_coin_message = "Coininiz bulunmamaktadır, coin yüklemesi yapmak için https://example.com sitesinden yükleme yapabilirsiniz."
send_sms(address, zero_coin_message)
logging.info(f"Coin eksik, mesaj gönderilmedi: {address}")
# Log the sent zero coin message
sent_zero_coin_id = log_message(address, 'sent', zero_coin_message, receivedno=received_message_id)
else:
logging.debug(f"Filtrelenmeyen SMS: {address} - {body}")
else:
# Kullanıcı kayıtlı değil, ekle ve abonelik mesajı gönder
add_number(address, coin=30) # Yeni kullanıcıya 30 kredi tanımla
welcome_message = "Hoş geldiniz! SMSGPT servisine hoş geldiniz. Hesabınıza 30 kredi tanımlandı."
send_sms(address, welcome_message)
logging.info(f"Hoş geldin mesajı gönderildi ve {address} numarası veritabanına eklendi.")
# Log the sent welcome message
sent_welcome_id = log_message(address, 'sent', welcome_message, receivedno=received_message_id)
except KeyboardInterrupt:
logging.info("Program sonlandırıldı.")
except Exception as e:
logging.error(f"Logcat dinleme hatası: {e}")
finally:
process.terminate()
if __name__ == "__main__":
main()