Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -8,10 +8,13 @@ import logging
|
|
8 |
import re
|
9 |
from telebot.apihelper import ApiTelegramException
|
10 |
import time
|
|
|
|
|
11 |
|
12 |
# Replace with your actual API keys and bot token
|
13 |
GOOGLE_API_KEY = 'AIzaSyAYXUMnwmR4nUGDCs97FJJsafcQAPAAuzE'
|
14 |
BOT_TOKEN = '7484321656:AAFaswxTqaSHu_s4jd_pk2Q2OJJWYcWHwAM'
|
|
|
15 |
|
16 |
# Initialize the Telegram bot
|
17 |
bot = telebot.TeleBot(BOT_TOKEN)
|
@@ -22,100 +25,54 @@ logging.basicConfig(
|
|
22 |
level=logging.DEBUG,
|
23 |
format='%(asctime)s - %(levelname)s - %(message)s',
|
24 |
handlers=[
|
25 |
-
logging.FileHandler('bot_debug.log'),
|
26 |
-
logging.StreamHandler()
|
27 |
]
|
28 |
)
|
29 |
logger = logging.getLogger(__name__)
|
30 |
|
31 |
-
# Configure Google Generative AI
|
32 |
-
genai.configure(api_key=GOOGLE_API_KEY)
|
33 |
-
|
34 |
-
# Create the model
|
35 |
-
generation_config = {
|
36 |
-
"temperature": 1,
|
37 |
-
"top_p": 0.95,
|
38 |
-
"top_k": 64,
|
39 |
-
"max_output_tokens": 8192,
|
40 |
-
"response_mime_type": "text/plain",
|
41 |
-
}
|
42 |
-
|
43 |
-
model = genai.GenerativeModel(
|
44 |
-
model_name="gemini-1.5-pro",
|
45 |
-
generation_config=generation_config,
|
46 |
-
system_instruction="Please respond to user input"
|
47 |
-
)
|
48 |
-
|
49 |
-
chat_session = model.start_chat(
|
50 |
-
history=[
|
51 |
-
{"role": "user", "parts": ["hi\n"]},
|
52 |
-
{"role": "model", "parts": ["Hello! 👋 How can I help you today? 😊 \n"]},
|
53 |
-
{"role": "user", "parts": ["I am looking for photo booth service?"]},
|
54 |
-
{"role": "model", "parts": ["That's great! 🎉 I can definitely help you with information about Aforative Media's photo booth services. \n\nTo give you the most relevant information, could you tell me a little more about what you're looking for? ..."]},
|
55 |
-
{"role": "user", "parts": ["How much for photo booth services?"]},
|
56 |
-
{"role": "model", "parts": ["You're smart to ask about pricing upfront! 😉 \n\nAforative Media's Mr. & Ms. Booth photo booth services start at **USD 390 for a minimum of 2 hours**. ..."]},
|
57 |
-
{"role": "user", "parts": ["How about videography service?"]},
|
58 |
-
{"role": "model", "parts": ["You're thinking about capturing the memories on film too? Excellent choice! Videography adds a whole other dimension to remembering special events. \n\nAforative Media offers excellent videography services, and just like their photo booths, their videography packages are competitively priced and flexible. ..."]},
|
59 |
-
]
|
60 |
-
)
|
61 |
-
|
62 |
-
# Initialize Flask app
|
63 |
-
app = Flask(__name__)
|
64 |
-
|
65 |
-
@app.route(f'/bot{BOT_TOKEN}', methods=['POST'])
|
66 |
-
def webhook():
|
67 |
-
"""Handles incoming updates from Telegram."""
|
68 |
-
try:
|
69 |
-
json_str = request.get_data(as_text=True)
|
70 |
-
logger.debug(f"Received update: {json_str}")
|
71 |
-
update = telebot.types.Update.de_json(json_str)
|
72 |
-
bot.process_new_updates([update])
|
73 |
-
return 'ok', 200
|
74 |
-
except Exception as e:
|
75 |
-
logger.error(f"Error in webhook: {e}")
|
76 |
-
return 'error', 500
|
77 |
-
|
78 |
-
@bot.message_handler(content_types=['text'])
|
79 |
-
def handle_text_messages(message):
|
80 |
-
"""Handles text messages and responds based on predefined questions or Generative AI."""
|
81 |
-
logger.debug(f"Received message: {message.text} from chat_id {message.chat.id}")
|
82 |
-
try:
|
83 |
-
prompt = f"Respond to the user: {message.text}"
|
84 |
-
response = chat_session.send_message(prompt) # Generate response using text and prompt
|
85 |
-
response_text = response.text
|
86 |
-
|
87 |
-
# Log the response
|
88 |
-
logger.debug(f"Generated response: {response_text}")
|
89 |
-
|
90 |
-
# Send the response to the chat
|
91 |
-
bot.send_message(message.chat.id, response_text, parse_mode='Markdown')
|
92 |
-
logger.info(f"Response sent to chat_id {message.chat.id}")
|
93 |
-
|
94 |
-
except Exception as e:
|
95 |
-
logger.error(f"Error during GenAI processing: {e}")
|
96 |
-
error_message = "Sorry, I can't answer this query right now but I will improve from time to time."
|
97 |
-
bot.send_message(message.chat.id, error_message, parse_mode='Markdown')
|
98 |
-
logger.error(f"Error message sent to chat_id {message.chat.id}")
|
99 |
-
|
100 |
def set_webhook():
|
101 |
"""Sets the webhook for the Telegram bot."""
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
if __name__ == "__main__":
|
120 |
-
set_webhook() # Set the webhook
|
121 |
-
|
|
|
8 |
import re
|
9 |
from telebot.apihelper import ApiTelegramException
|
10 |
import time
|
11 |
+
from huggingface_hub import webhook_endpoint, WebhookPayload
|
12 |
+
from gradio import Interface
|
13 |
|
14 |
# Replace with your actual API keys and bot token
|
15 |
GOOGLE_API_KEY = 'AIzaSyAYXUMnwmR4nUGDCs97FJJsafcQAPAAuzE'
|
16 |
BOT_TOKEN = '7484321656:AAFaswxTqaSHu_s4jd_pk2Q2OJJWYcWHwAM'
|
17 |
+
WEBHOOK_URL = f"https://measmonysuon-flyingbird.hf.space/bot{BOT_TOKEN}"
|
18 |
|
19 |
# Initialize the Telegram bot
|
20 |
bot = telebot.TeleBot(BOT_TOKEN)
|
|
|
25 |
level=logging.DEBUG,
|
26 |
format='%(asctime)s - %(levelname)s - %(message)s',
|
27 |
handlers=[
|
28 |
+
logging.FileHandler('bot_debug.log'),
|
29 |
+
logging.StreamHandler()
|
30 |
]
|
31 |
)
|
32 |
logger = logging.getLogger(__name__)
|
33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
def set_webhook():
|
35 |
"""Sets the webhook for the Telegram bot."""
|
36 |
+
try:
|
37 |
+
response = requests.get(f"https://api.telegram.org/bot{BOT_TOKEN}/setWebhook?url={WEBHOOK_URL}")
|
38 |
+
result = response.json()
|
39 |
+
if result.get('ok'):
|
40 |
+
logger.info("Webhook set successfully.")
|
41 |
+
else:
|
42 |
+
logger.error(f"Failed to set webhook: {result}")
|
43 |
+
except requests.exceptions.RequestException as e:
|
44 |
+
logger.error(f"Request exception: {e}")
|
45 |
+
|
46 |
+
@webhook_endpoint
|
47 |
+
async def handle_update(payload: WebhookPayload) -> None:
|
48 |
+
"""Handles incoming updates from Telegram."""
|
49 |
+
logger.debug(f"Received payload: {payload}")
|
50 |
+
if payload.message:
|
51 |
+
message_text = payload.message.get('text')
|
52 |
+
chat_id = payload.message.get('chat').get('id')
|
53 |
+
|
54 |
+
if message_text:
|
55 |
+
try:
|
56 |
+
# Generate a response using Google Generative AI or predefined responses
|
57 |
+
prompt = f"Respond to the user: {message_text}"
|
58 |
+
response = requests.post(
|
59 |
+
"https://api.your-ai-service.com/generate", # Replace with your AI service URL
|
60 |
+
json={"prompt": prompt, "api_key": GOOGLE_API_KEY}
|
61 |
+
).json()
|
62 |
+
response_text = response.get('text', 'Sorry, I didn\'t understand that.')
|
63 |
+
|
64 |
+
# Send the response back to the chat
|
65 |
+
bot.send_message(chat_id, response_text, parse_mode='Markdown')
|
66 |
+
logger.info(f"Response sent to chat_id {chat_id}")
|
67 |
+
|
68 |
+
except Exception as e:
|
69 |
+
logger.error(f"Error during message processing: {e}")
|
70 |
+
bot.send_message(chat_id, "Sorry, I can't answer this query right now.", parse_mode='Markdown')
|
71 |
+
|
72 |
+
# Initialize the Gradio interface
|
73 |
+
iface = Interface(fn=handle_update, inputs=[], outputs=[])
|
74 |
+
|
75 |
+
# Run the Gradio app
|
76 |
if __name__ == "__main__":
|
77 |
+
set_webhook() # Set the webhook for Telegram
|
78 |
+
iface.launch()
|