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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pyrogram import Client, filters
|
2 |
+
from config import API_ID, API_HASH, BOT_TOKEN, HUGGINGFACE_TOKEN
|
3 |
+
import requests
|
4 |
+
import os
|
5 |
+
import asyncio
|
6 |
+
import json
|
7 |
+
from datetime import datetime
|
8 |
+
|
9 |
+
# Add these constants at the top
|
10 |
+
API_URL = "https://api-inference.huggingface.co/models/openai/whisper-large-v3-turbo"
|
11 |
+
AI_URL = "https://charan5775-fastest.hf.space/t2t"
|
12 |
+
AI_HEADERS = {
|
13 |
+
"Content-Type": "application/json",
|
14 |
+
"Accept": "application/json"
|
15 |
+
}
|
16 |
+
|
17 |
+
# Initialize message history in memory only
|
18 |
+
message_history = []
|
19 |
+
|
20 |
+
# Create a new Client instance with a custom session name and no local storage
|
21 |
+
app = Client(
|
22 |
+
"my_bot",
|
23 |
+
api_id=API_ID,
|
24 |
+
api_hash=API_HASH,
|
25 |
+
bot_token=BOT_TOKEN,
|
26 |
+
in_memory=True # This prevents SQLite database locks
|
27 |
+
)
|
28 |
+
|
29 |
+
def save_message_to_history(user_id, username, message_type, content, bot_response=None):
|
30 |
+
message_data = {
|
31 |
+
"content": content,
|
32 |
+
"response": bot_response
|
33 |
+
}
|
34 |
+
message_history.append(message_data)
|
35 |
+
print("Message History Update:", json.dumps(message_data, indent=2))
|
36 |
+
|
37 |
+
# Add command to print history
|
38 |
+
@app.on_message(filters.command("history"))
|
39 |
+
async def history_command(client, message):
|
40 |
+
if not message_history:
|
41 |
+
await message.reply_text("No message history available.")
|
42 |
+
return
|
43 |
+
|
44 |
+
try:
|
45 |
+
# Create a formatted message
|
46 |
+
history_text = "📜 Message History:\n\n"
|
47 |
+
for idx, msg in enumerate(message_history[-10:], 1): # Show last 10 messages
|
48 |
+
history_text += f"{idx}. Message: {msg['content']}\n"
|
49 |
+
if msg['response']:
|
50 |
+
history_text += f" Response: {msg['response']}\n"
|
51 |
+
history_text += "\n"
|
52 |
+
|
53 |
+
await message.reply_text(history_text)
|
54 |
+
|
55 |
+
except Exception as e:
|
56 |
+
await message.reply_text(f"Error retrieving history: {str(e)}")
|
57 |
+
|
58 |
+
# Command handler for /start
|
59 |
+
@app.on_message(filters.command("start"))
|
60 |
+
async def start_command(client, message):
|
61 |
+
await message.reply_text("Hello! I'm your Telegram bot. Nice to meet you!")
|
62 |
+
|
63 |
+
# Command handler for /help
|
64 |
+
@app.on_message(filters.command("help"))
|
65 |
+
async def help_command(client, message):
|
66 |
+
help_text = """
|
67 |
+
Available commands:
|
68 |
+
/start - Start the bot
|
69 |
+
/help - Show this help message
|
70 |
+
"""
|
71 |
+
await message.reply_text(help_text)
|
72 |
+
|
73 |
+
# Message handler for regular text messages
|
74 |
+
@app.on_message(filters.text & filters.private & ~filters.command(["start", "help", "info"]))
|
75 |
+
async def echo(client, message):
|
76 |
+
try:
|
77 |
+
thinking_msg = await message.reply_text("🤔 Thinking about your message...")
|
78 |
+
ai_response = await get_ai_response(message.text)
|
79 |
+
await thinking_msg.delete()
|
80 |
+
await message.reply_text(ai_response)
|
81 |
+
|
82 |
+
# Save message to history
|
83 |
+
save_message_to_history(
|
84 |
+
message.from_user.id,
|
85 |
+
message.from_user.username,
|
86 |
+
"text",
|
87 |
+
message.text,
|
88 |
+
ai_response
|
89 |
+
)
|
90 |
+
except Exception as e:
|
91 |
+
await message.reply_text(f"Sorry, I couldn't process your message: {str(e)}")
|
92 |
+
|
93 |
+
# Handle photo messages
|
94 |
+
@app.on_message(filters.photo)
|
95 |
+
async def handle_photo(client, message):
|
96 |
+
response = "Nice photo!"
|
97 |
+
await message.reply_text(response)
|
98 |
+
save_message_to_history(
|
99 |
+
message.from_user.id,
|
100 |
+
message.from_user.username,
|
101 |
+
"photo",
|
102 |
+
"Photo message",
|
103 |
+
response
|
104 |
+
)
|
105 |
+
|
106 |
+
# Handle sticker messages
|
107 |
+
@app.on_message(filters.sticker)
|
108 |
+
async def handle_sticker(client, message):
|
109 |
+
response = "Cool sticker!"
|
110 |
+
await message.reply_text(response)
|
111 |
+
save_message_to_history(
|
112 |
+
message.from_user.id,
|
113 |
+
message.from_user.username,
|
114 |
+
"sticker",
|
115 |
+
"Sticker message",
|
116 |
+
response
|
117 |
+
)
|
118 |
+
|
119 |
+
# Custom command example
|
120 |
+
@app.on_message(filters.command("info"))
|
121 |
+
async def info_command(client, message):
|
122 |
+
user = message.from_user
|
123 |
+
info_text = f"""
|
124 |
+
User Information:
|
125 |
+
ID: {user.id}
|
126 |
+
Name: {user.first_name}
|
127 |
+
Username: @{user.username if user.username else 'None'}
|
128 |
+
"""
|
129 |
+
await message.reply_text(info_text)
|
130 |
+
|
131 |
+
# Add this function after your existing imports
|
132 |
+
async def transcribe_audio(file_path):
|
133 |
+
try:
|
134 |
+
with open(file_path, "rb") as f:
|
135 |
+
data = f.read()
|
136 |
+
response = requests.post(API_URL, data=data)
|
137 |
+
return response.json().get('text', 'Could not transcribe audio')
|
138 |
+
except Exception as e:
|
139 |
+
print(f"Error in transcription: {e}")
|
140 |
+
return "Error transcribing audio"
|
141 |
+
|
142 |
+
# Add this new function after transcribe_audio function
|
143 |
+
async def get_ai_response(text):
|
144 |
+
try:
|
145 |
+
# Create condensed history from all messages
|
146 |
+
context = ""
|
147 |
+
if message_history:
|
148 |
+
# If we have more than 10 messages, summarize older ones
|
149 |
+
if len(message_history) > 10:
|
150 |
+
older_messages = message_history[:-10]
|
151 |
+
recent_messages = message_history[-10:]
|
152 |
+
|
153 |
+
# Summarize older messages in pairs to save space
|
154 |
+
context = "Earlier conversation summary:\n"
|
155 |
+
for i in range(0, len(older_messages), 2):
|
156 |
+
pair = older_messages[i:i+2]
|
157 |
+
combined_content = " | ".join(msg['content'] for msg in pair)
|
158 |
+
if len(combined_content) > 100:
|
159 |
+
combined_content = combined_content[:100] + "..."
|
160 |
+
context += f"Chat: {combined_content}\n"
|
161 |
+
|
162 |
+
# Add a separator
|
163 |
+
context += "\nRecent conversation:\n"
|
164 |
+
|
165 |
+
# Add recent messages in full detail
|
166 |
+
for msg in recent_messages:
|
167 |
+
if msg['content'] and msg['response']:
|
168 |
+
context += f"Human: {msg['content']}\nAssistant: {msg['response']}\n"
|
169 |
+
else:
|
170 |
+
# If less than 10 messages, include all in detail
|
171 |
+
context = "Conversation history:\n"
|
172 |
+
for msg in message_history:
|
173 |
+
if msg['content'] and msg['response']:
|
174 |
+
context += f"Human: {msg['content']}\nAssistant: {msg['response']}\n"
|
175 |
+
|
176 |
+
# Combine context with current query
|
177 |
+
full_query = f"{context}Human: {text}"
|
178 |
+
|
179 |
+
payload = {
|
180 |
+
"query": full_query,
|
181 |
+
"stream": False
|
182 |
+
}
|
183 |
+
|
184 |
+
response = requests.post(AI_URL, json=payload)
|
185 |
+
print(f"Raw API Response: {response.text}") # Debug print
|
186 |
+
|
187 |
+
if response.status_code != 200:
|
188 |
+
print(f"API Error: Status {response.status_code}")
|
189 |
+
return f"Sorry, the AI service returned an error (Status {response.status_code})"
|
190 |
+
|
191 |
+
response_data = response.json()
|
192 |
+
print(f"Parsed Response Data: {response_data}") # Debug print
|
193 |
+
|
194 |
+
# The API returns the response directly
|
195 |
+
if isinstance(response_data, dict) and 'response' in response_data:
|
196 |
+
return response_data['response']
|
197 |
+
else:
|
198 |
+
return str(response_data)
|
199 |
+
|
200 |
+
except requests.exceptions.RequestException as e:
|
201 |
+
print(f"Network error: {e}")
|
202 |
+
return "Sorry, I'm having trouble connecting to the AI service."
|
203 |
+
except json.JSONDecodeError as e:
|
204 |
+
print(f"JSON parsing error: {e}\nResponse text: {response.text}")
|
205 |
+
return "Sorry, I received an invalid response from the AI service."
|
206 |
+
except Exception as e:
|
207 |
+
print(f"Error getting AI response: {str(e)}\nFull error: {repr(e)}")
|
208 |
+
return "Sorry, I couldn't process your message."
|
209 |
+
|
210 |
+
# Update the voice message handler with retry logic
|
211 |
+
@app.on_message(filters.voice | filters.audio)
|
212 |
+
async def handle_voice(client, message):
|
213 |
+
try:
|
214 |
+
# Send a processing message
|
215 |
+
processing_msg = await message.reply_text("🎵 Processing your voice message...")
|
216 |
+
|
217 |
+
# Download the voice message with retry logic
|
218 |
+
max_retries = 3
|
219 |
+
for attempt in range(max_retries):
|
220 |
+
try:
|
221 |
+
message = await app.get_messages(
|
222 |
+
message.chat.id,
|
223 |
+
message.id
|
224 |
+
)
|
225 |
+
voice_file = await message.download()
|
226 |
+
break
|
227 |
+
except Exception as e:
|
228 |
+
if attempt == max_retries - 1:
|
229 |
+
raise e
|
230 |
+
await asyncio.sleep(1)
|
231 |
+
|
232 |
+
transcription = await transcribe_audio(voice_file)
|
233 |
+
await message.reply_text(f"🗣️ Transcription:\n\n{transcription}")
|
234 |
+
|
235 |
+
thinking_msg = await message.reply_text("🤔 Thinking about your message...")
|
236 |
+
ai_response = await get_ai_response(transcription)
|
237 |
+
await thinking_msg.delete()
|
238 |
+
await message.reply_text(ai_response)
|
239 |
+
|
240 |
+
# Save voice message to history
|
241 |
+
save_message_to_history(
|
242 |
+
message.from_user.id,
|
243 |
+
message.from_user.username,
|
244 |
+
"voice",
|
245 |
+
transcription,
|
246 |
+
ai_response
|
247 |
+
)
|
248 |
+
|
249 |
+
# Clean up
|
250 |
+
try:
|
251 |
+
os.remove(voice_file)
|
252 |
+
await processing_msg.delete()
|
253 |
+
except:
|
254 |
+
pass
|
255 |
+
|
256 |
+
except Exception as e:
|
257 |
+
error_message = f"Sorry, there was an error processing your message: {str(e)}"
|
258 |
+
print(error_message)
|
259 |
+
await message.reply_text(error_message)
|
260 |
+
|
261 |
+
# Run the bot
|
262 |
+
if __name__ == "__main__":
|
263 |
+
print("Bot is running...")
|
264 |
+
app.run()
|