""" Betelgeuse TI Comment Moderator Flask app with Meta App Review compliance features: - Visual permission tags on each screen - Hide Comment button (client-side only) - View on Facebook link - Clear permission indicators for screencast """ import os import json import requests from datetime import datetime from flask import Flask, redirect, request, session, render_template_string, url_for, jsonify app = Flask(__name__) app.secret_key = os.environ.get("SECRET_KEY", "dev-key-change-in-prod") # Facebook App Config FB_APP_ID = os.environ.get("FB_APP_ID", "YOUR_APP_ID") FB_APP_SECRET = os.environ.get("FB_APP_SECRET", "YOUR_APP_SECRET") FB_API_VERSION = "v19.0" FB_BASE_URL = f"https://graph.facebook.com/{FB_API_VERSION}" # Redirect URI must match Facebook App settings REDIRECT_URI = os.environ.get("REDIRECT_URI", "https://betelgeuse-ti.vercel.app/callback") # Required permissions REQUIRED_SCOPES = [ "pages_show_list", "pages_read_engagement", "pages_read_user_content" ] # ============================================================================= # HTML TEMPLATES # ============================================================================= BASE_TEMPLATE = """ Betelgeuse TI - Comment Moderator

🌟 Betelgeuse TI

COMMENT MODERATOR

{{ content | safe }}
""" # ============================================================================= # HOME PAGE - LOGGED OUT # ============================================================================= HOME_TEMPLATE = """
App Review Screencast

Real-Time Comment Moderation

Monitor and moderate comments on Facebook Pages you administer. No data stored. Real-time processing only.

🔐 Requested Permissions

pages_read_engagement

Read posts and metrics to select which post to moderate

pages_read_user_content

Read comments with author name, message, and date for moderation

pages_show_list

Display list of Pages you manage

Log in with Facebook

🔒 Privacy Commitment

""" # ============================================================================= # DASHBOARD - LOGGED IN # ============================================================================= DASHBOARD_TEMPLATE = """
1
Choose Page
2
Choose Post
3
Moderate Comments
✅ Successfully authenticated. Select a Page to start moderating.
pages_show_list
📋 Choose Your Page

Select a Facebook Page to load posts for moderation.

{{ pages|length }} Page(s) found

↩️ Disconnect
""" # ============================================================================= # POSTS LIST # ============================================================================= POSTS_TEMPLATE = """ ← Back to Pages
1
Choose Page
2
Choose Post
3
Moderate Comments
pages_read_engagement
📝 Choose a Post

Select a post to view and moderate its comments.

{% for post in posts %}
{% if post.picture %} Post image {% else %}
📄 Text Post
{% endif %}
{{ post.message[:60] }}{% if post.message|length > 60 %}...{% endif %}
📅 {{ post.created_time[:10] }} 💬 {{ post.comments_count }} comments
{% endfor %}
""" # ============================================================================= # COMMENTS VIEW # ============================================================================= COMMENTS_TEMPLATE = """ ← Back to Posts
1
Choose Page
2
Choose Post
3
Moderate Comments
pages_read_user_content
💬 Moderate Comments

Review comments in real time. Hide inappropriate content.

{{ comments|length }}
Total Comments
{{ total_likes }}
Total Likes
0
Flagged
0%
Negative Rate
{% for comment in comments %}
{{ comment.from_name[0] if comment.from_name else '?' }}
{{ comment.from_name or 'Facebook User' }}
ID: {{ comment.id }}
{{ comment.message }}
📅 {{ comment.created_time[:10] }} ❤️ {{ comment.like_count }} likes ⏰ {{ comment.created_time }}
🔗 View on Facebook
{% endfor %}
""" # ============================================================================= # PRIVACY POLICY # ============================================================================= PRIVACY_TEMPLATE = """

Privacy Policy

Updated: May 30, 2026

Betelgeuse IT Services — CNPJ 51.770.524/0001-87

1. Information We Process

Our application processes the following data only in real time:

2. No Data Storage

We do not store, persist, or retain any user data on our servers. All data is obtained directly from the Facebook Graph API and displayed in your browser session.

3. Data Retention

Data is retained only for the duration of your active session (typically less than 30 minutes).

4. Data Sharing

We do not share, sell, rent, or transfer user data to third parties. We do not use comment data to train AI models.

5. Your Rights

6. Contact

Betelgeuse IT Services
CNPJ: 51.770.524/0001-87
Email: falecom@mariomello.com.br
Address: Navegantes, SC, Brazil

""" # ============================================================================= # TERMS OF USE # ============================================================================= TERMS_TEMPLATE = """

Terms of Use

Effective: May 30, 2026

Betelgeuse IT Services — CNPJ 51.770.524/0001-87

1. Service Description

The Betelgeuse TI Comment Moderator is a real-time tool that allows Facebook Page administrators to view and monitor public comments on posts they manage.

2. Eligibility

You must be at least 18 years old and an administrator of the Facebook Page you wish to monitor.

3. Permitted Use

You agree to use this service exclusively for:

You may NOT use this service for:

4. Data Processing

All data processing occurs in real time. We do not store Facebook user data on our servers.

5. Termination

We may suspend access for violations of these terms or Facebook Platform Policies. You may terminate use anytime by disconnecting the app in Facebook Settings.

6. Applicable Law

These terms are governed by the laws of Brazil. Disputes will be resolved in the courts of Navegantes, SC.

7. Contact

Email: falecom@mariomello.com.br

""" # ============================================================================= # DATA DELETION # ============================================================================= DELETE_TEMPLATE = """

Data Deletion Request

LGPD / GDPR Compliant

Betelgeuse IT Services — CNPJ 51.770.524/0001-87

Good news: Our application does not store any personal data on our servers. All Facebook data is processed in real time and exists only during your active browser session.

Immediate Steps (Instant)

  1. Revoke App Access: Go to Facebook Settings → Apps and Websites, find "Betelgeuse TI Comment Moderator" and click "Remove".
  2. Clear Session: Click Log Out to clear your current session.

Contact for Confirmation

If you would like written confirmation that no data is retained, please contact us:

Legal Rights

Under Brazilian LGPD and European GDPR, you have the right to be forgotten. As we do not store personal data, compliance is immediate upon app removal.

""" # ============================================================================= # DATA USE AGREEMENT # ============================================================================= DATA_USE_TEMPLATE = """

Data Use Agreement

Meta Platform Supplemental Terms

Betelgeuse IT Services — CNPJ 51.770.524/0001-87

1. Purpose of Data Use

We use Facebook Platform data exclusively for real-time comment moderation on Facebook Pages administered by the authenticated user.

2. Data We Access

Permission Data Accessed Use
pages_show_list Page name, ID, and category Display list of Pages the user manages
pages_read_engagement Post ID, message, created_time, permalink List posts for the user to select
pages_read_user_content Author name, author ID, message, created_time, like_count Display comments for moderation

3. Prohibited Uses

We expressly commit to NOT:

4. Compliance

We comply with Meta Platform Terms, Meta Data Processing Terms, Brazilian LGPD, and European GDPR.

5. Contact

Email: falecom@mariomello.com.br

""" # ============================================================================= # FLASK ROUTES # ============================================================================= @app.route("/") def home(): if "access_token" in session: return redirect("/dashboard") return render_template_string(BASE_TEMPLATE, content=HOME_TEMPLATE) @app.route("/login") def login(): scopes = ",".join(REQUIRED_SCOPES) auth_url = ( f"https://www.facebook.com/{FB_API_VERSION}/dialog/oauth" f"?client_id={FB_APP_ID}" f"&redirect_uri={REDIRECT_URI}" f"&scope={scopes}" f"&response_type=code" ) return redirect(auth_url) @app.route("/callback") def callback(): code = request.args.get("code") if not code: return "Error: No code provided", 400 # Exchange code for access token token_url = f"{FB_BASE_URL}/oauth/access_token" params = { "client_id": FB_APP_ID, "client_secret": FB_APP_SECRET, "redirect_uri": REDIRECT_URI, "code": code } try: resp = requests.get(token_url, params=params, timeout=30) data = resp.json() if "access_token" not in data: return f"Error: {data}", 400 session["access_token"] = data["access_token"] return redirect("/dashboard") except Exception as e: return f"Error during authentication: {str(e)}", 500 @app.route("/dashboard") def dashboard(): if "access_token" not in session: return redirect("/") # Get pages using pages_show_list try: resp = requests.get( f"{FB_BASE_URL}/me/accounts", params={"access_token": session["access_token"]}, timeout=30 ) data = resp.json() pages = data.get("data", []) return render_template_string( BASE_TEMPLATE, content=render_template_string(DASHBOARD_TEMPLATE, pages=pages) ) except Exception as e: return f"Error: {str(e)}", 500 @app.route("/posts") def posts(): if "access_token" not in session: return redirect("/") page_id = request.args.get("page_id") if not page_id: return redirect("/dashboard") session["current_page_id"] = page_id # Get page access token try: resp = requests.get( f"{FB_BASE_URL}/me/accounts", params={"access_token": session["access_token"]}, timeout=30 ) accounts = resp.json().get("data", []) page_token = None for acc in accounts: if acc["id"] == page_id: page_token = acc["access_token"] break if not page_token: return "Error: Could not get page token", 400 # Get posts using pages_read_engagement resp = requests.get( f"{FB_BASE_URL}/{page_id}/posts", params={ "access_token": page_token, "fields": "id,message,created_time,picture,comments.summary(true)" }, timeout=30 ) posts_data = resp.json().get("data", []) # Format posts posts = [] for post in posts_data: posts.append({ "id": post["id"], "message": post.get("message", "(Media Post)"), "created_time": post.get("created_time", ""), "picture": post.get("picture", ""), "comments_count": post.get("comments", {}).get("summary", {}).get("total_count", 0) }) return render_template_string( BASE_TEMPLATE, content=render_template_string(POSTS_TEMPLATE, posts=posts, page_id=page_id) ) except Exception as e: return f"Error: {str(e)}", 500 @app.route("/comments") def comments(): if "access_token" not in session: return redirect("/") post_id = request.args.get("post_id") page_id = request.args.get("page_id") or session.get("current_page_id") if not post_id: return redirect("/dashboard") try: # Get page access token resp = requests.get( f"{FB_BASE_URL}/me/accounts", params={"access_token": session["access_token"]}, timeout=30 ) accounts = resp.json().get("data", []) page_token = None for acc in accounts: if acc["id"] == page_id: page_token = acc["access_token"] break if not page_token: return "Error: Could not get page token", 400 # Get comments using pages_read_user_content resp = requests.get( f"{FB_BASE_URL}/{post_id}/comments", params={ "access_token": page_token, "fields": "id,from,message,created_time,like_count,permalink_url" }, timeout=30 ) comments_data = resp.json().get("data", []) # Format comments comments = [] total_likes = 0 for c in comments_data: from_data = c.get("from", {}) # Build Facebook comment URL utilizing the requested API permalink fb_url = c.get("permalink_url") # Fallback de segurança mantendo a sua lógica original if not fb_url: comment_full_id = c["id"] parts = comment_full_id.split("_") if len(parts) >= 2: fb_url = f"https://www.facebook.com/{parts[0]}?comment_id={parts[1]}" else: fb_url = f"https://www.facebook.com/{comment_full_id}" # SANITIZAÇÃO BRUTA: Remove qualquer duplicação de domínio forçando a limpeza da string if isinstance(fb_url, str): fb_url = fb_url.replace("https://www.facebook.com/https://www.facebook.com/", "https://www.facebook.com/") comments.append({ "id": c["id"], "from_name": from_data.get("name", "Facebook User"), "message": c.get("message", ""), "created_time": c.get("created_time", ""), "like_count": c.get("like_count", 0), "fb_url": fb_url }) total_likes += c.get("like_count", 0) return render_template_string( BASE_TEMPLATE, content=render_template_string( COMMENTS_TEMPLATE, comments=comments, page_id=page_id, total_likes=total_likes ) ) except Exception as e: return f"Error: {str(e)}", 500 @app.route("/logout") def logout(): session.clear() return redirect("/") # ============================================================================= # LEGAL PAGES # ============================================================================= @app.route("/privacy") def privacy(): return render_template_string(BASE_TEMPLATE, content=PRIVACY_TEMPLATE) @app.route("/terms") def terms(): return render_template_string(BASE_TEMPLATE, content=TERMS_TEMPLATE) @app.route("/delete") def delete(): return render_template_string(BASE_TEMPLATE, content=DELETE_TEMPLATE) @app.route("/data-use") def data_use(): return render_template_string(BASE_TEMPLATE, content=DATA_USE_TEMPLATE) # ============================================================================= # MAIN # ============================================================================= if __name__ == "__main__": app.run(debug=True, host="0.0.0.0", port=5000)