measmonysuon commited on
Commit
3fb5a70
Β·
verified Β·
1 Parent(s): 5ccffc3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -42
app.py CHANGED
@@ -1,19 +1,14 @@
1
  import telebot
2
  import os
3
- import requests # For Telegram API requests
4
  import google.generativeai as genai
5
  import tempfile
6
  import logging
7
  import re
8
- from telegram import Bot
9
- from telegram.constants import ParseMode
10
- from telegram.error import TelegramError
11
  from requests.exceptions import RequestException, ConnectionError
12
  from telebot.apihelper import ApiTelegramException
13
  import time
14
- from flask import Flask, request
15
- from telegram import Update
16
- from telegram.ext import Dispatcher, CommandHandler, MessageHandler, Filters
17
 
18
  # Replace with your actual API keys and bot token
19
  GOOGLE_API_KEY = 'AIzaSyAYXUMnwmR4nUGDCs97FJJsafcQAPAAuzE'
@@ -50,62 +45,60 @@ model = genai.GenerativeModel(
50
  chat_session = model.start_chat(
51
  history=[
52
  {"role": "user", "parts": ["hi\n"]},
53
- {"role": "model", "parts": ["Hello! πŸ‘‹ How can I help you today? 😊 \n"]},
54
- {"role": "user", "parts": ["i am looking for photo booth service?"]},
55
  {"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? ..."]},
56
- {"role": "user", "parts": ["how much for photo booth services?"]},
57
  {"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**. ..."]},
58
  {"role": "user", "parts": ["How about videography service?"]},
59
- {"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. ..."]},
60
  ]
61
  )
62
 
63
  # Initialize Flask app
64
  app = Flask(__name__)
65
 
66
- # Define your command and message handlers
67
- def start(update, context):
68
- context.bot.send_message(chat_id=update.effective_chat.id, text="Hello, I am your bot!")
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- def handle_message(update, context):
 
 
71
  try:
72
- chat_session = model.start_chat() # Start a new chat session for context
73
- prompt = f"Respond to the user: {update.message.text}"
74
  response = chat_session.send_message(prompt) # Generate response using text and prompt
75
  response_text = response.text
76
-
77
  # Determine whether to reply in private or group chat with Markdown formatting
78
- if update.message.chat.type == 'private':
79
- context.bot.send_message(chat_id=update.effective_chat.id, text=response_text, parse_mode=ParseMode.MARKDOWN)
80
  else:
81
- context.bot.send_message(chat_id=update.effective_chat.id, text=response_text, parse_mode=ParseMode.MARKDOWN)
82
-
83
- logger.info(f"Response sent to chat_id {update.effective_chat.id}")
84
 
 
 
85
  except Exception as e:
86
  logger.error(f"Error during GenAI processing: {e}")
87
  error_message = "Sorry, I can't answer this query right now but I will improve from time to time."
88
 
89
- if update.message.chat.type == 'private':
90
- context.bot.send_message(chat_id=update.effective_chat.id, text=error_message, parse_mode=ParseMode.MARKDOWN)
91
  else:
92
- context.bot.send_message(chat_id=update.effective_chat.id, text=error_message, parse_mode=ParseMode.MARKDOWN)
93
-
94
- logger.error(f"Error message sent to chat_id {update.effective_chat.id}")
95
-
96
- # Define webhook endpoint
97
- @app.route('/' + BOT_TOKEN, methods=['POST'])
98
- def webhook():
99
- try:
100
- update = Update.de_json(request.get_json(force=True), bot)
101
- dispatcher.process_update(update)
102
- except ConnectionError as e:
103
- logger.error(f"Network-related error occurred: {e}")
104
- except TelegramError as e:
105
- logger.error(f"Telegram API error occurred: {e}")
106
- except Exception as e:
107
- logger.error(f"Unexpected error occurred: {e}")
108
- return 'ok', 200
109
 
110
  # Function to set the webhook with Telegram
111
  def set_webhook():
 
1
  import telebot
2
  import os
3
+ import requests
4
  import google.generativeai as genai
5
  import tempfile
6
  import logging
7
  import re
8
+ from flask import Flask, request
 
 
9
  from requests.exceptions import RequestException, ConnectionError
10
  from telebot.apihelper import ApiTelegramException
11
  import time
 
 
 
12
 
13
  # Replace with your actual API keys and bot token
14
  GOOGLE_API_KEY = 'AIzaSyAYXUMnwmR4nUGDCs97FJJsafcQAPAAuzE'
 
45
  chat_session = model.start_chat(
46
  history=[
47
  {"role": "user", "parts": ["hi\n"]},
48
+ {"role": "model", "parts": ["Hello! πŸ‘‹ How can I help you today? 😊 \n"]},
49
+ {"role": "user", "parts": ["I am looking for photo booth service?"]},
50
  {"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? ..."]},
51
+ {"role": "user", "parts": ["How much for photo booth services?"]},
52
  {"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**. ..."]},
53
  {"role": "user", "parts": ["How about videography service?"]},
54
+ {"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. ..."]},
55
  ]
56
  )
57
 
58
  # Initialize Flask app
59
  app = Flask(__name__)
60
 
61
+ # Define the webhook route
62
+ @app.route('/' + BOT_TOKEN, methods=['POST'])
63
+ def webhook():
64
+ try:
65
+ json_str = request.get_data(as_text=True)
66
+ update = telebot.types.Update.de_json(json_str)
67
+ handle_message(update)
68
+ except ConnectionError as e:
69
+ logger.error(f"Network-related error occurred: {e}")
70
+ except ApiTelegramException as e:
71
+ logger.error(f"Telegram API error occurred: {e}")
72
+ except Exception as e:
73
+ logger.error(f"Unexpected error occurred: {e}")
74
+ return 'ok', 200
75
 
76
+ # Function to handle incoming messages
77
+ def handle_message(update):
78
+ message = update.message
79
  try:
80
+ prompt = f"Respond to the user: {message.text}"
 
81
  response = chat_session.send_message(prompt) # Generate response using text and prompt
82
  response_text = response.text
83
+
84
  # Determine whether to reply in private or group chat with Markdown formatting
85
+ if message.chat.type == 'private':
86
+ bot.send_message(message.chat.id, response_text, parse_mode='Markdown')
87
  else:
88
+ bot.send_message(message.chat.id, response_text, parse_mode='Markdown')
 
 
89
 
90
+ logger.info(f"Response sent to chat_id {message.chat.id}")
91
+
92
  except Exception as e:
93
  logger.error(f"Error during GenAI processing: {e}")
94
  error_message = "Sorry, I can't answer this query right now but I will improve from time to time."
95
 
96
+ if message.chat.type == 'private':
97
+ bot.send_message(message.chat.id, error_message, parse_mode='Markdown')
98
  else:
99
+ bot.send_message(message.chat.id, error_message, parse_mode='Markdown')
100
+
101
+ logger.error(f"Error message sent to chat_id {message.chat.id}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
  # Function to set the webhook with Telegram
104
  def set_webhook():