AstraOS commited on
Commit
7ad85cf
·
verified ·
1 Parent(s): 6397a42

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -80
app.py CHANGED
@@ -1,82 +1,43 @@
1
- import telebot
2
- from fastapi import FastAPI, Request, HTTPException
3
- import uvicorn
4
- from pydantic import BaseModel
 
 
 
5
 
6
- # Your bot token is needed internally to send messages via Telegram's API.
7
- TOKEN = "6655373829:AAGduLdLyNx7zUtxH73Sp3Z1vHKS35tV9WU"
8
- # Your externally configured webhook URL (set up previously via BotFather or API call)
9
- WEBHOOK_URL = "https://astraos-testing.hf.space/webhook"
10
-
11
- # Initialize the TeleBot instance
12
- bot = telebot.TeleBot(TOKEN, parse_mode="HTML")
13
-
14
- # Create a FastAPI app instance
15
  app = FastAPI()
16
-
17
- # --- Models for request validation ---
18
- class MessageRequest(BaseModel):
19
- chat_id: int
20
- text: str
21
-
22
- # --- Endpoints ---
23
-
24
- @app.post("/webhook")
25
- async def telegram_webhook(request: Request):
26
- """
27
- This endpoint receives incoming update payloads from Telegram.
28
- Telegram sends updates as JSON via a POST request to this URL.
29
- """
30
- try:
31
- json_data = await request.json()
32
- except Exception as e:
33
- raise HTTPException(status_code=400, detail="Invalid JSON payload")
34
-
35
- update = telebot.types.Update.de_json(json_data)
36
- # Process the update (this will call any message handlers you've set up)
37
- bot.process_new_updates([update])
38
- # Acknowledge receipt of the update
39
- return {"status": "ok"}
40
-
41
- @app.get("/")
42
- def home():
43
- """
44
- A simple endpoint to verify that your bot’s webhook server is running.
45
- """
46
- return {"message": "Bot is running via webhook"}
47
-
48
- @app.post("/send_message")
49
- async def send_message(msg: MessageRequest):
50
- """
51
- This endpoint allows you to send a message from your bot to a user.
52
- You provide a JSON payload with 'chat_id' and 'text'.
53
-
54
- For example, you can POST:
55
-
56
- {
57
- "chat_id": 123456789,
58
- "text": "Hello from webhook-only mode!"
59
- }
60
-
61
- The message is sent by calling the Telegram Bot API internally.
62
- """
63
- try:
64
- sent_message = bot.send_message(msg.chat_id, msg.text)
65
- return {"status": "sent", "message_id": sent_message.message_id}
66
- except Exception as e:
67
- raise HTTPException(status_code=500, detail=str(e))
68
-
69
- # --- Example Message Handler ---
70
- @bot.message_handler(commands=["start"])
71
- def start_command(message):
72
- """
73
- When a user sends /start to your bot via Telegram (received via webhook),
74
- this handler sends a welcome message.
75
- """
76
- bot.reply_to(message, "Hello! I'm running via FastAPI webhook and ready to send messages!")
77
-
78
- # --- Running the App ---
79
- if __name__ == "__main__":
80
- # We run the FastAPI app using uvicorn. Since your webhook is already set up on Telegram,
81
- # you only need to start the server to receive updates.
82
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ import os
2
+ import streamlit as st
3
+ from telegram import Update
4
+ from telegram.ext import Application, CommandHandler, ContextTypes
5
+ import logging
6
+ import asyncio
7
+ import threading
8
 
 
 
 
 
 
 
 
 
 
9
  app = FastAPI()
10
+ # Enable logging
11
+ logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
12
+ logger = logging.getLogger(__name__)
13
+
14
+ # Load bot token
15
+ BOT_TOKEN = "6655373829:AAGduLdLyNx7zUtxH73Sp3Z1vHKS35tV9WU"
16
+ if not BOT_TOKEN:
17
+ raise ValueError("Bot token is not set in environment variables")
18
+
19
+ # Create the bot application
20
+ application = Application.builder().token(BOT_TOKEN).build()
21
+
22
+ # Define the /start command handler
23
+ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
24
+ await update.message.reply_text("Hello! This bot is running on Hugging Face Spaces 🚀")
25
+
26
+ # Add command handlers
27
+ application.add_handler(CommandHandler("start", start))
28
+
29
+ # Function to run polling in a thread-safe way
30
+ def run_polling():
31
+ loop = asyncio.new_event_loop() # Create a new event loop
32
+ asyncio.set_event_loop(loop) # Set it for the current thread
33
+ loop.run_until_complete(application.run_polling(close_loop=True)) # Run polling in the loop
34
+
35
+ # Streamlit UI
36
+ st.title("Telegram Bot on Streamlit")
37
+ st.write("This bot is running using Streamlit and Python-Telegram-Bot.")
38
+
39
+ # Button to start the bot
40
+ if st.button("Start Bot"):
41
+ thread = threading.Thread(target=run_polling, daemon=True) # Run polling in a background thread
42
+ thread.start()
43
+ st.write("Bot started successfully and is now polling Telegram!")