measmonysuon commited on
Commit
ddd106f
·
verified ·
1 Parent(s): cb28e95

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -88
app.py CHANGED
@@ -1,18 +1,21 @@
1
- import os
 
2
  import logging
3
- import httpx
4
- import asyncio
5
- from flask import Flask, request, jsonify
 
 
6
 
7
  # Configuration
8
- BOT_TOKEN = '7484321656:AAExhpS7sOGMu2BCuPQrDjuXpY3sEQmBgfY'
9
- WEBHOOK_SECRET = 'A3%26c8%21jP%23xZ1v*Qw5kL%5E0tR%40u9%25yS6' # URL-encoded secret
10
- POWER_USER_ID = 75516649
11
 
12
- # Proxy Configuration
13
- PROXY_URL = 'http://eR3LhYeoZXNWhIp:clIvQ2hSkO5CtLl@107.180.131.170:58874'
14
 
15
- # Initialize logging
16
  logging.basicConfig(
17
  level=logging.DEBUG,
18
  format='%(asctime)s - %(levelname)s - %(message)s',
@@ -23,89 +26,57 @@ logging.basicConfig(
23
  )
24
  logger = logging.getLogger(__name__)
25
 
26
- app = Flask(__name__)
27
-
28
- async def bot_send_message(chat_id, text):
29
- """Send a message to the specified chat ID using the proxy configuration."""
30
- async with httpx.AsyncClient(proxies=PROXY_URL) as client:
31
- response = await client.post(
32
- f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage",
33
- data={"chat_id": chat_id, "text": text, "parse_mode": "Markdown"}
34
- )
35
- if response.status_code == 200:
36
- logger.info(f"Message sent successfully to chat_id {chat_id}")
37
- else:
38
- logger.error(f"Failed to send message: {response.text}")
39
-
40
- @app.route(f'/webhooks/{WEBHOOK_SECRET}', methods=['POST'])
41
- def handle_update():
42
- """Handles incoming updates from Telegram."""
43
- payload = request.json
44
- logger.debug(f"Received payload: {payload}")
45
-
46
- if payload.get('message'):
47
- message_text = payload['message'].get('text')
48
- chat_id = payload['message']['chat']['id']
49
 
50
- if message_text:
51
- try:
52
- # Forward message to Gradio and get the response
53
- async def forward_message():
54
- async with httpx.AsyncClient(proxies=PROXY_URL) as client:
55
- response = await client.post(
56
- 'http://localhost:7860/', # Gradio app URL
57
- json={'text': message_text}
58
- )
59
- if response.status_code == 200:
60
- response_text = response.json().get('data', 'Error processing request.')
61
- else:
62
- response_text = 'Error occurred while processing your request.'
63
- await bot_send_message(chat_id, response_text)
64
 
65
- asyncio.run(forward_message())
66
- logger.info(f"Response sent to chat_id {chat_id}")
 
 
 
67
 
68
- except Exception as e:
69
- logger.error(f"Error during processing: {e}")
70
- error_message = "Sorry, I can't answer this query right now but I will improve from time to time."
71
- asyncio.run(bot_send_message(chat_id, error_message))
72
- logger.error(f"Error message sent to chat_id {chat_id}")
 
 
 
 
 
 
 
73
 
74
- return jsonify({'status': 'ok'}), 200
 
 
 
 
 
 
 
 
 
75
 
76
- async def set_telegram_webhook(flask_url):
77
- """Sets the webhook for the Telegram bot using the provided Flask URL."""
78
- webhook_url = f"{flask_url}/webhooks/{WEBHOOK_SECRET}"
79
- retry_attempts = 5
80
- retry_delay = 1 # seconds
81
-
82
- for attempt in range(retry_attempts):
83
- try:
84
- async with httpx.AsyncClient(proxies=PROXY_URL) as client:
85
- response = await client.post(
86
- f"https://api.telegram.org/bot{BOT_TOKEN}/setWebhook",
87
- data={"url": webhook_url},
88
- )
89
- result = response.json()
90
- if result.get('ok'):
91
- logger.info("Webhook set successfully.")
92
- return
93
- elif result.get('error_code') == 429:
94
- retry_after = result['parameters'].get('retry_after', retry_delay)
95
- logger.warning(f"Rate limit exceeded. Retrying after {retry_after} seconds.")
96
- await asyncio.sleep(retry_after)
97
- else:
98
- logger.error(f"Failed to set webhook: {result}")
99
- return
100
- except httpx.RequestError as e:
101
- logger.error(f"Request exception: {e}")
102
- return
103
 
104
- def run_flask_app():
105
- """Launches the Flask app and sets the Telegram webhook."""
106
- flask_url = "https://your-flask-url.com" # Replace with your actual Flask URL
107
- asyncio.run(set_telegram_webhook(flask_url)) # Set the webhook before starting the Flask app
108
- app.run(host="0.0.0.0", port=5000, debug=True)
 
109
 
110
  if __name__ == "__main__":
111
- run_flask_app()
 
1
+ import telebot
2
+ import google.generativeai as genai
3
  import logging
4
+ import requests
5
+ import gradio as gr
6
+
7
+ # Suppress experimental warnings
8
+ os.environ['HF_HUB_DISABLE_EXPERIMENTAL_WARNING'] = '1'
9
 
10
  # Configuration
11
+ GOOGLE_API_KEY = 'AIzaSyAYXUMnwmR4nUGDCs97FJJsafcQAPAAuzE'
12
+ BOT_TOKEN = '7484321656:AAFaswxTqaSHu_s4jd_pk2Q2OJJWYcWHwAM'
13
+ WEBHOOK_URL = f"https://measmonysuon-flyingbird.hf.space/webhooks/handle_update"
14
 
15
+ # Initialize the Telegram bot
16
+ bot = telebot.TeleBot(BOT_TOKEN)
17
 
18
+ # Configure logging
19
  logging.basicConfig(
20
  level=logging.DEBUG,
21
  format='%(asctime)s - %(levelname)s - %(message)s',
 
26
  )
27
  logger = logging.getLogger(__name__)
28
 
29
+ # Set up Google Generative AI
30
+ genai.configure(api_key=GOOGLE_API_KEY)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
+ generation_config = {
33
+ "temperature": 1,
34
+ "top_p": 0.95,
35
+ "top_k": 64,
36
+ "max_output_tokens": 8192,
37
+ "response_mime_type": "text/plain",
38
+ }
 
 
 
 
 
 
 
39
 
40
+ model = genai.GenerativeModel(
41
+ model_name="gemini-1.5-pro",
42
+ generation_config=generation_config,
43
+ system_instruction="Please respond to user input"
44
+ )
45
 
46
+ chat_session = model.start_chat(
47
+ history=[
48
+ {"role": "user", "parts": ["hi\n"]},
49
+ {"role": "model", "parts": ["Hello! 👋 How can I help you today? 😊 \n"]},
50
+ {"role": "user", "parts": ["I am looking for photo booth service?"]},
51
+ {"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? ..."]},
52
+ {"role": "user", "parts": ["How much for photo booth services?"]},
53
+ {"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**. ..."]},
54
+ {"role": "user", "parts": ["How about videography service?"]},
55
+ {"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. ..."]},
56
+ ]
57
+ )
58
 
59
+ def generate_response(user_input):
60
+ """Generate a response using Google Generative AI."""
61
+ try:
62
+ prompt = f"Respond to the user: {user_input}"
63
+ response = chat_session.send_message(prompt) # Generate response using text and prompt
64
+ response_text = response.text
65
+ return response_text
66
+ except Exception as e:
67
+ logger.error(f"Error during GenAI processing: {e}")
68
+ return "Sorry, I can't answer this query right now but I will improve from time to time."
69
 
70
+ # Define Gradio interface
71
+ def gradio_handle_update(user_input):
72
+ return generate_response(user_input)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
+ iface = gr.Interface(
75
+ fn=gradio_handle_update,
76
+ inputs=gr.Textbox(label="User Input"),
77
+ outputs=gr.Textbox(label="Bot Response"),
78
+ live=True
79
+ )
80
 
81
  if __name__ == "__main__":
82
+ iface.launch() # Launch the Gradio app