Create telegram_bot.py
Browse files- telegram_bot.py +48 -0
telegram_bot.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import requests
|
3 |
+
from telegram import Update
|
4 |
+
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
|
5 |
+
|
6 |
+
# Set up logging
|
7 |
+
logging.basicConfig(level=logging.INFO)
|
8 |
+
|
9 |
+
TOKEN = "TELEGRAM_BOT_TOKEN"
|
10 |
+
|
11 |
+
# Flask API URL
|
12 |
+
API_URL = "http://DeMaking/decision-helper-bot/process"
|
13 |
+
|
14 |
+
# Function to send user input to Flask API and return the response
|
15 |
+
def get_response_from_api(user_text):
|
16 |
+
try:
|
17 |
+
response = requests.post(API_URL, json={"text": user_text})
|
18 |
+
if response.status_code == 200:
|
19 |
+
return response.json().get("response", "Error: No response received")
|
20 |
+
else:
|
21 |
+
return "Error: API request failed"
|
22 |
+
except Exception as e:
|
23 |
+
logging.error(f"Error connecting to API: {e}")
|
24 |
+
return "Error: Could not connect to the server"
|
25 |
+
|
26 |
+
# Function to handle incoming messages from users
|
27 |
+
def handle_message(update: Update, context: CallbackContext):
|
28 |
+
user_text = update.message.text
|
29 |
+
response = get_response_from_api(user_text)
|
30 |
+
update.message.reply_text(response)
|
31 |
+
|
32 |
+
# Function to handle /start command
|
33 |
+
def start(update: Update, context: CallbackContext):
|
34 |
+
update.message.reply_text("Hello! Tell me your Decision-Making issue in HE or EN, and I'll try to help you.")
|
35 |
+
|
36 |
+
# Initialize Telegram bot
|
37 |
+
def run_telegram_bot():
|
38 |
+
updater = Updater(TOKEN, use_context=True)
|
39 |
+
dp = updater.dispatcher
|
40 |
+
|
41 |
+
dp.add_handler(CommandHandler("start", start))
|
42 |
+
dp.add_handler(MessageHandler(Filters.text & ~Filters.command, handle_message))
|
43 |
+
|
44 |
+
updater.start_polling()
|
45 |
+
updater.idle()
|
46 |
+
|
47 |
+
if __name__ == "__main__":
|
48 |
+
run_telegram_bot()
|