Alibrown's picture
Create app.py
7c7b615 verified
import gradio as gr
import tweepy
import facebook
from instabot import Bot
import tempfile
import os
from datetime import datetime
import json
class SocialMediaManagerWeb:
def __init__(self):
self.temp_dir = tempfile.mkdtemp()
self.credentials_cache = {}
def save_credentials_temp(self, twitter_api_key, twitter_api_secret, twitter_access_token,
twitter_token_secret, facebook_token, instagram_user, instagram_pass):
"""Speichert Credentials temporär im Browser-Speicher"""
credentials = {
"twitter": {
"api_key": twitter_api_key,
"api_secret": twitter_api_secret,
"access_token": twitter_access_token,
"token_secret": twitter_token_secret
},
"facebook": {
"token": facebook_token
},
"instagram": {
"username": instagram_user,
"password": instagram_pass
}
}
# Hier werden die Credentials im Browser-Cache gespeichert
self.credentials_cache = credentials
return "Credentials wurden temporär gespeichert. Diese werden nicht dauerhaft gespeichert."
def post_to_social(self, message, image, twitter_enabled, facebook_enabled, instagram_enabled):
"""Hauptfunktion zum Posten auf sozialen Netzwerken"""
if not message.strip():
return "Fehler: Nachricht darf nicht leer sein!"
if not (twitter_enabled or facebook_enabled or instagram_enabled):
return "Fehler: Wähle mindestens ein Netzwerk aus!"
log_messages = []
# Bild temporär speichern, falls hochgeladen
image_path = None
if image is not None:
image_path = os.path.join(self.temp_dir, "temp_image.jpg")
image.save(image_path)
# Auf Twitter posten
if twitter_enabled:
twitter_log = self._post_to_twitter(message, image_path)
log_messages.append(twitter_log)
# Auf Facebook posten
if facebook_enabled:
facebook_log = self._post_to_facebook(message, image_path)
log_messages.append(facebook_log)
# Auf Instagram posten
if instagram_enabled:
instagram_log = self._post_to_instagram(message, image_path)
log_messages.append(instagram_log)
# Temporäre Datei löschen
if image_path and os.path.exists(image_path):
os.remove(image_path)
return "\n".join(log_messages)
def _post_to_twitter(self, message, image_path):
"""Auf Twitter posten"""
timestamp = datetime.now().strftime('%H:%M:%S')
if len(message) > 280:
return f"[{timestamp}] Twitter Fehler: Nachricht überschreitet 280 Zeichen ({len(message)})"
if not self.credentials_cache.get("twitter", {}).get("api_key"):
return f"[{timestamp}] Twitter Fehler: Keine API-Credentials gefunden"
try:
twitter_creds = self.credentials_cache["twitter"]
auth = tweepy.OAuthHandler(
twitter_creds["api_key"],
twitter_creds["api_secret"]
)
auth.set_access_token(
twitter_creds["access_token"],
twitter_creds["token_secret"]
)
api = tweepy.API(auth)
if image_path:
media = api.media_upload(image_path)
api.update_status(status=message, media_ids=[media.media_id])
else:
api.update_status(status=message)
return f"[{timestamp}] Erfolgreich auf Twitter gepostet"
except Exception as e:
return f"[{timestamp}] Twitter Fehler: {str(e)}"
def _post_to_facebook(self, message, image_path):
"""Auf Facebook posten"""
timestamp = datetime.now().strftime('%H:%M:%S')
if not self.credentials_cache.get("facebook", {}).get("token"):
return f"[{timestamp}] Facebook Fehler: Kein Access Token gefunden"
try:
fb_token = self.credentials_cache["facebook"]["token"]
graph = facebook.GraphAPI(fb_token)
if image_path:
with open(image_path, "rb") as image:
graph.put_photo(image=image, message=message)
else:
graph.put_object("me", "feed", message=message)
return f"[{timestamp}] Erfolgreich auf Facebook gepostet"
except Exception as e:
return f"[{timestamp}] Facebook Fehler: {str(e)}"
def _post_to_instagram(self, message, image_path):
"""Auf Instagram posten"""
timestamp = datetime.now().strftime('%H:%M:%S')
if not image_path:
return f"[{timestamp}] Instagram Fehler: Bild ist für Instagram-Posts erforderlich"
if not self.credentials_cache.get("instagram", {}).get("username"):
return f"[{timestamp}] Instagram Fehler: Keine Anmeldedaten gefunden"
try:
insta_creds = self.credentials_cache["instagram"]
bot = Bot()
bot.login(
username=insta_creds["username"],
password=insta_creds["password"]
)
bot.upload_photo(image_path, caption=message)
return f"[{timestamp}] Erfolgreich auf Instagram gepostet"
except Exception as e:
return f"[{timestamp}] Instagram Fehler: {str(e)}"
# Gradio Interface erstellen
def create_app():
manager = SocialMediaManagerWeb()
with gr.Blocks(title="Social Media Manager Web") as app:
gr.Markdown("# Social Media Manager Web")
with gr.Tabs():
# Post Tab
with gr.TabItem("Beitrag posten"):
with gr.Row():
with gr.Column():
message_input = gr.Textbox(
label="Nachricht",
placeholder="Gib deine Nachricht hier ein...",
lines=5
)
image_input = gr.Image(label="Bild (optional)", type="pil")
with gr.Row():
twitter_check = gr.Checkbox(label="Twitter", value=False)
facebook_check = gr.Checkbox(label="Facebook", value=False)
instagram_check = gr.Checkbox(label="Instagram", value=False)
post_button = gr.Button("Auf ausgewählten Netzwerken posten")
with gr.Column():
output_log = gr.Textbox(label="Log", lines=10)
# Credentials Tab
with gr.TabItem("Anmeldedaten"):
gr.Markdown("""
### Deine Anmeldedaten
Diese werden nur temporär im Browser gespeichert und nicht auf dem Server.
""")
with gr.Group():
gr.Markdown("#### Twitter")
twitter_api_key = gr.Textbox(label="API Key")
twitter_api_secret = gr.Textbox(label="API Secret")
twitter_access_token = gr.Textbox(label="Access Token")
twitter_token_secret = gr.Textbox(label="Token Secret")
with gr.Group():
gr.Markdown("#### Facebook")
facebook_token = gr.Textbox(label="Access Token")
with gr.Group():
gr.Markdown("#### Instagram")
instagram_user = gr.Textbox(label="Benutzername")
instagram_pass = gr.Textbox(label="Passwort", type="password")
save_button = gr.Button("Anmeldedaten speichern")
save_output = gr.Textbox(label="Status")
# Event-Handler
post_button.click(
fn=manager.post_to_social,
inputs=[message_input, image_input, twitter_check, facebook_check, instagram_check],
outputs=output_log
)
save_button.click(
fn=manager.save_credentials_temp,
inputs=[twitter_api_key, twitter_api_secret, twitter_access_token,
twitter_token_secret, facebook_token, instagram_user, instagram_pass],
outputs=save_output
)
return app
if __name__ == "__main__":
app = create_app()
app.launch()