forked from Alpha-Mintamir/bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
151 lines (126 loc) Β· 4.98 KB
/
bot.py
File metadata and controls
151 lines (126 loc) Β· 4.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
import requests
import os
from dotenv import load_dotenv
import logging
import re
from flask import Flask, request
# Set up logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.DEBUG
)
logger = logging.getLogger(__name__)
# Load environment variables
load_dotenv()
TELEGRAM_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
BACKEND_URL = 'https://bot-8psi.onrender.com/chat'
def format_for_telegram(text: str) -> str:
"""Format text for Telegram with proper Markdown V2 formatting"""
# First, escape special characters for Markdown V2
special_chars = ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!']
for char in special_chars:
text = text.replace(char, f'\\{char}')
# Format links - replace escaped characters inside link syntax
link_pattern = r'\\\[(.*?)\\\]\\\((.*?)\\\)'
text = re.sub(link_pattern, r'[\1](\2)', text)
# Format bold text
text = text.replace('\\*\\*', '*').replace('\\*\\*', '*')
# Format italic text
text = text.replace('\\_\\_', '_').replace('\\_\\_', '_')
# Format emojis (don't escape emojis)
emoji_pattern = r'([\U0001F300-\U0001F999πππ§π’])'
text = re.sub(emoji_pattern, r'\1', text)
return text
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Send a message when the command /start is issued."""
welcome_message = "Hello! π I'm your Information Systems Department assistant at AAU\\. How can I help you today? π"
await update.message.reply_text(welcome_message, parse_mode='MarkdownV2')
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Send a message when the command /help is issued."""
help_text = """
π *IS Department Bot Help*
Available commands:
/start \- Start the conversation
/help \- Show this help message
You can ask me about:
β’ IS Department information
β’ Course details
β’ Faculty contacts
β’ Events and activities
β’ And more\!
Just type your question naturally and I'll help you out\! π
"""
await update.message.reply_text(help_text, parse_mode='MarkdownV2')
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle incoming messages."""
try:
# Send typing action
await update.message.chat.send_action('typing')
# Make request to backend
response = requests.post(
BACKEND_URL,
headers={'Content-Type': 'application/json'},
json={'message': update.message.text},
timeout=30
)
if response.status_code == 200:
bot_response = response.json().get('response', 'Sorry, I encountered an error.')
formatted_response = format_for_telegram(bot_response)
await update.message.reply_text(
formatted_response,
parse_mode='MarkdownV2',
disable_web_page_preview=True
)
else:
await update.message.reply_text(
"Sorry, I'm having trouble processing your request\\. Please try again later\\.",
parse_mode='MarkdownV2'
)
except Exception as e:
logger.error(f"Error in handle_message: {str(e)}")
await update.message.reply_text(
"Sorry, I encountered an error\\. Please try again later\\.",
parse_mode='MarkdownV2'
)
# Initialize Flask app
app = Flask(__name__)
# Create the Application globally
application = Application.builder().token(TELEGRAM_TOKEN).build()
# Add handlers
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
@app.route('/' + TELEGRAM_TOKEN, methods=['POST'])
async def webhook():
"""Handle incoming webhook requests from Telegram."""
try:
logger.info("Received webhook request")
if request.method == "POST":
update = Update.de_json(request.get_json(), application.bot)
logger.info(f"Processing update: {update}")
await application.process_update(update)
return 'ok', 200
except Exception as e:
logger.error(f"Error in webhook: {str(e)}")
return 'error', 500
@app.route('/')
def index():
"""Simple health check endpoint."""
return 'Bot is running!'
def main():
"""Start the bot."""
try:
# Set webhook
webhook_url = os.getenv('WEBHOOK_URL')
logger.info(f"Setting webhook URL: {webhook_url}")
application.run_webhook(
listen='0.0.0.0',
port=int(os.getenv('PORT', 5000)),
webhook_url=webhook_url
)
except Exception as e:
logger.error(f"Error in main: {str(e)}")
if __name__ == '__main__':
main()