File size: 8,872 Bytes
7c7b615
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
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()