File size: 5,037 Bytes
a6084f0
 
6b71018
a6084f0
 
 
 
 
 
 
 
 
 
46fb941
 
a6084f0
 
 
 
 
 
 
 
 
a5e9afe
 
a6084f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5e9afe
a6084f0
 
b59fa2b
a6084f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import os
from dotenv import load_dotenv
import requests
import asyncio
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes

# Page config
st.set_page_config(page_title="Meme Bot Setup", page_icon="🎭")

# Load environment variables
load_dotenv()
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
IMAGE_API_KEY = os.getenv("IMAGE_API_KEY")

# Initialize session state
if 'bot_running' not in st.session_state:
    st.session_state.bot_running = False

def format_meme_prompt(user_input):
    """Format user input into a meme-specific prompt"""
    return f"Create a funny meme that shows: {user_input}. Make it in classic meme style with impact font text. Make it humorous and shareable. The image should be meme-worthy and entertaining."

def save_credentials(telegram_token, openai_key
):
    """Save credentials to .env file"""
    try:
        with open('.env', 'w') as f:
            f.write(f'TELEGRAM_BOT_TOKEN="{telegram_token}"\n')
            f.write(f'IMAGE_API_KEY="{openai_key}"\n')
        return True
    except Exception as e:
        st.error(f"Error saving credentials: {str(e)}")
        return False

async def test_meme_generation(prompt):
    """Test meme generation with OpenAI API"""
    api_key = os.getenv("IMAGE_API_KEY")
    if not api_key:
        return None, "OpenAI API key not found"
    
    formatted_prompt = format_meme_prompt(prompt)
    headers = {"Authorization": f"Bearer {api_key}"}
    data = {
        "prompt": formatted_prompt,
        "size": "1024x1024",
        "model": "dall-e-3"
    }
    
    try:
        response = requests.post(
            "https://api.openai.com/v1/images/generations",
            json=data,
            headers=headers,
            timeout=100
        )
        if response.status_code == 200:
            return response.json()["data"][0]["url"], None
        else:
            return None, f"API Error: {response.status_code} - {response.text}"
    except Exception as e:
        return None, f"Request failed: {str(e)}"

# Main UI
st.title("🎭 Meme Bot Setup")
st.markdown("Configure your Telegram bot to generate memes!")

# Credentials Section
st.header("Bot Configuration")
with st.form("credentials_form"):
    telegram_token = st.text_input(
        "Telegram Bot Token",
        value=os.getenv("TELEGRAM_BOT_TOKEN", ""),
        type="password",
        help="Get this from @BotFather on Telegram"
    )
    openai_key = st.text_input(
        "OpenAI API Key",
        value=os.getenv("IMAGE_API_KEY", ""),
        type="password",
        help="Get this from OpenAI Platform"
    )
    save_button = st.form_submit_button("Save Credentials")

if save_button:
    if telegram_token and openai_key:
        if save_credentials(telegram_token, openai_key):
            st.success("Credentials saved successfully!")
            load_dotenv()
    else:
        st.error("Please provide both API keys")

# Test Meme Generation
st.header("Test Meme Generation")
test_prompt = st.text_input(
    "Enter your meme idea",
    placeholder="e.g., 'When you forget to save your work'"
)

if st.button("Generate Test Meme"):
    if not os.getenv("IMAGE_API_KEY"):
        st.error("Please set the OpenAI API key first")
    else:
        with st.spinner("Creating your meme..."):
            image_url, error = asyncio.run(test_meme_generation(test_prompt))
            if error:
                st.error(error)
            else:
                st.image(image_url, caption="Your Generated Meme")
                st.success("Meme generated successfully!")

# Bot Status
st.header("Bot Status")
col1, col2 = st.columns(2)

with col1:
    if st.button("Start Bot" if not st.session_state.bot_running else "Stop Bot"):
        if not st.session_state.bot_running:
            if not os.getenv("TELEGRAM_BOT_TOKEN"):
                st.error("Please set the Telegram Bot Token first")
            else:
                st.session_state.bot_running = True
                st.success("Bot started!")
                st.rerun()
        else:
            st.session_state.bot_running = False
            st.warning("Bot stopped")
            st.rerun()

with col2:
    status = "🟒 Running" if st.session_state.bot_running else "πŸ”΄ Stopped"
    st.write(f"Status: {status}")

# Instructions
with st.expander("How to Use"):
    st.markdown("""
    ### Setup Steps:
    1. Get a Telegram Bot Token from [@BotFather](https://t.me/botfather)
    2. Get an OpenAI API key from [OpenAI Platform](https://platform.openai.com)
    3. Enter both keys above and save
    4. Start the bot
    
    ### Using the Bot:
    1. Find your bot on Telegram
    2. Send /start to begin
    3. Send any text to generate a meme
    
    ### Example Prompts:
    - "When the code works on first try"
    - "Me explaining why I need another monitor"
    - "That moment when you forget to git commit"
    """)

# Footer
st.markdown("---")
st.markdown("Made for generating awesome memes 🎭")