Spaces:
Sleeping
Sleeping
import re | |
import json | |
from msg import fetch_json_from_github, update_user_json_file, fetch_authenticity_token_and_commit_oid | |
def extract_admin_message(ai_response): | |
""" | |
Extract admin message from AI response and return both the admin message | |
and the cleaned response (without admin tags). | |
""" | |
admin_pattern = r'<order>(.*?)</order>' | |
admin_messages = re.findall(admin_pattern, ai_response, re.DOTALL) | |
# Clean the response by removing admin tags and their content | |
cleaned_response = re.sub(admin_pattern, '', ai_response) | |
if admin_messages: | |
return admin_messages[0].strip(), cleaned_response.strip() | |
else: | |
return None, ai_response | |
def save_admin_message(page_id, message, sender_id, full_name): | |
""" | |
Save admin message to the GitHub JSON file with date and time. | |
""" | |
try: | |
# Import datetime module for timestamp | |
from datetime import datetime | |
# Get current date and time in ISO format | |
timestamp = datetime.now().isoformat() | |
# Fetch current JSON data | |
github_response = fetch_json_from_github() | |
if not github_response["success"]: | |
print(f"Error fetching JSON data: {github_response['message']}") | |
return False | |
# Get the current data | |
data = github_response["data"] | |
# Initialize the page_id entry if it doesn't exist | |
if page_id not in data: | |
data[page_id] = [] | |
# Add the new message with sender_id, full_name, and timestamp | |
new_message = { | |
"message": message, | |
"sender_id": sender_id, | |
"full_name": full_name if full_name else "Unknown User", | |
"timestamp": timestamp | |
} | |
data[page_id].append(new_message) | |
# Convert the updated data to JSON string WITHOUT indentation or line breaks | |
# Use ensure_ascii=False to properly handle Arabic and other non-ASCII characters | |
new_content = json.dumps(data, separators=(',', ':'), ensure_ascii=False) | |
# Get authentication tokens for GitHub | |
authenticity_token, commit_oid = fetch_authenticity_token_and_commit_oid() | |
if not authenticity_token or not commit_oid: | |
print("Failed to get GitHub authentication tokens") | |
return False | |
# Update the file on GitHub | |
update_result = update_user_json_file(authenticity_token, commit_oid, new_content) | |
if update_result["success"]: | |
print(f"Admin message saved successfully with timestamp: {timestamp}") | |
return True | |
else: | |
print(f"Error saving admin message: {update_result['message']}") | |
return False | |
except Exception as e: | |
print(f"Error saving admin message: {str(e)}") | |
return False |