AforativeBot / app.py
measmonysuon's picture
Update app.py
f0c33ec verified
raw
history blame
4.76 kB
import os
import telebot
import google.generativeai as genai
import logging
import requests
import gradio as gr
import time
# Suppress experimental warnings
os.environ['HF_HUB_DISABLE_EXPERIMENTAL_WARNING'] = '1'
# Configuration
GOOGLE_API_KEY = 'AIzaSyAYXUMnwmR4nUGDCs97FJJsafcQAPAAuzE'
BOT_TOKEN = '7484321656:AAFaswxTqaSHu_s4jd_pk2Q2OJJWYcWHwAM'
WEBHOOK_SECRET = 'A3&c8!jP#xZ1v*Qw5kL^0tR@u9%yS6' # Define your webhook secret here
# Initialize the Telegram bot
bot = telebot.TeleBot(BOT_TOKEN)
# Configure logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('bot_debug.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# Set up Google Generative AI
genai.configure(api_key=GOOGLE_API_KEY)
generation_config = {
"temperature": 1,
"top_p": 0.95,
"top_k": 64,
"max_output_tokens": 8192,
"response_mime_type": "text/plain",
}
model = genai.GenerativeModel(
model_name="gemini-1.5-pro",
generation_config=generation_config,
system_instruction="Please respond to user input"
)
chat_session = model.start_chat(
history=[
{"role": "user", "parts": ["hi\n"]},
{"role": "model", "parts": ["Hello! πŸ‘‹ How can I help you today? 😊 \n"]},
{"role": "user", "parts": ["I am looking for photo booth service?"]},
{"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? ..."]},
{"role": "user", "parts": ["How much for photo booth services?"]},
{"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**. ..."]},
{"role": "user", "parts": ["How about videography service?"]},
{"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. ..."]},
]
)
def handle_update(payload):
"""Handles incoming updates from Telegram."""
if payload.get('message'):
message_text = payload['message'].get('text')
chat_id = payload['message']['chat']['id']
if message_text:
try:
# Generate a response using Google Generative AI
prompt = f"Respond to the user: {message_text}"
response = chat_session.send_message(prompt) # Generate response using text and prompt
response_text = response.text
# Log the response
logger.debug(f"Generated response: {response_text}")
# Send the response to the chat
bot.send_message(chat_id, response_text, parse_mode='Markdown')
logger.info(f"Response sent to chat_id {chat_id}")
except Exception as e:
logger.error(f"Error during GenAI processing: {e}")
error_message = "Sorry, I can't answer this query right now but I will improve from time to time."
bot.send_message(chat_id, error_message, parse_mode='Markdown')
logger.error(f"Error message sent to chat_id {chat_id}")
return 'OK'
def set_telegram_webhook(gradio_url):
"""Sets the webhook for the Telegram bot."""
webhook_url = f"{gradio_url}/webhooks/handle_update"
try:
response = requests.post(
f"https://api.telegram.org/bot{BOT_TOKEN}/setWebhook",
data={"url": webhook_url}
)
result = response.json()
if result.get('ok'):
logger.info("Webhook set successfully.")
else:
logger.error(f"Failed to set webhook: {result}")
except requests.exceptions.RequestException as e:
logger.error(f"Request exception: {e}")
def run_gradio_app():
"""Launches the Gradio app and sets the Telegram webhook."""
with gr.Blocks() as app:
gr.Textbox(label="Input") # Dummy input component
gr.Textbox(label="Output") # Dummy output component
iface = app.launch(server_name="0.0.0.0", server_port=5000, debug=True)
# Directly set the webhook URL for local testing
gradio_url = "http://localhost:5000" # Use local URL for testing
set_telegram_webhook(gradio_url) # Set the webhook for Telegram
if __name__ == "__main__":
run_gradio_app()