randydev commited on
Commit
a9422f7
1 Parent(s): 430fc73

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +272 -0
main.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ import os
4
+
5
+ from pyrogram import Client, filters
6
+ from pyrogram import *
7
+ from pyrogram.types import Message
8
+
9
+ # Your other imports
10
+ from dotenv import load_dotenv
11
+ from database import db
12
+ from logger import LOGS
13
+ from RyuzakiLib import GeminiLatest # and other imports as needed
14
+ import google.generativeai as genai
15
+ from google.api_core.exceptions import InvalidArgument
16
+
17
+ # Load environment variables
18
+ load_dotenv()
19
+ API_ID = os.getenv("API_ID")
20
+ API_HASH = os.getenv("API_HASH")
21
+ BOT_TOKEN = os.getenv("BOT_TOKEN")
22
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
23
+
24
+ # Validate essential environment variables
25
+ if not all([API_ID, API_HASH, BOT_TOKEN, GOOGLE_API_KEY]):
26
+ LOGS.critical("Missing one or more essential environment variables.")
27
+ exit(1)
28
+
29
+ # Initialize Pyrogram Client
30
+ client = Client(
31
+ "chatbotai",
32
+ api_id=API_ID,
33
+ api_hash=API_HASH,
34
+ bot_token=BOT_TOKEN
35
+ )
36
+
37
+ # Define your handler
38
+ @client.on_message(
39
+ filters.incoming
40
+ & (
41
+ filters.text
42
+ | filters.photo
43
+ | filters.video
44
+ | filters.audio
45
+ | filters.voice
46
+ | filters.regex(r"\b(Randy|Rendi)\b(.*)", flags=re.IGNORECASE)
47
+ )
48
+ & filters.private
49
+ & ~filters.via_bot
50
+ & ~filters.forwarded,
51
+ group=2,
52
+ )
53
+ async def chatbot_talk(client: Client, message: Message):
54
+ try:
55
+ genai.configure(api_key=GOOGLE_API_KEY)
56
+
57
+ # Handling Photo Messages
58
+ if message.photo:
59
+ file_path = await message.download()
60
+ caption = message.caption or "What's this?"
61
+ x = GeminiLatest(api_keys=GOOGLE_API_KEY)
62
+
63
+ # Send initial processing message
64
+ ai_reply = await message.reply_text("Processing...")
65
+
66
+ try:
67
+ backup_chat = await db._get_chatbot_chat_from_db(message.from_user.id)
68
+ backup_chat.append({"role": "user", "parts": [{"text": caption}]})
69
+
70
+ response_reads = x.get_response_image(caption, file_path)
71
+
72
+ if len(response_reads) > 4096:
73
+ with open("chat.txt", "w+", encoding="utf8") as out_file:
74
+ out_file.write(response_reads)
75
+ await message.reply_document(
76
+ document="chat.txt",
77
+ disable_notification=True
78
+ )
79
+ await ai_reply.delete()
80
+ os.remove("chat.txt")
81
+ else:
82
+ await ai_reply.edit_text(response_reads)
83
+
84
+ backup_chat.append({"role": "model", "parts": [{"text": response_reads}]})
85
+ await db._update_chatbot_chat_in_db(message.from_user.id, backup_chat)
86
+
87
+ os.remove(file_path)
88
+ return
89
+ except InvalidArgument as e:
90
+ await ai_reply.edit_text(f"Error: {e}")
91
+ return
92
+ except Exception as e:
93
+ await ai_reply.edit_text(f"Error: {e}")
94
+ return
95
+
96
+ # Handling Audio or Voice Messages
97
+ if message.audio or message.voice:
98
+ ai_reply = await message.reply_text("Processing...")
99
+ audio_file_name = await message.download()
100
+ caption = message.caption or "What's this?"
101
+ model = genai.GenerativeModel(
102
+ model_name="gemini-1.5-flash",
103
+ safety_settings={
104
+ genai.types.HarmCategory.HARM_CATEGORY_HATE_SPEECH: genai.types.HarmBlockThreshold.BLOCK_NONE,
105
+ genai.types.HarmCategory.HARM_CATEGORY_HARASSMENT: genai.types.HarmBlockThreshold.BLOCK_NONE,
106
+ genai.types.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: genai.types.HarmBlockThreshold.BLOCK_NONE,
107
+ genai.types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: genai.types.HarmBlockThreshold.BLOCK_NONE,
108
+ }
109
+ )
110
+ backup_chat = await db._get_chatbot_chat_from_db(message.from_user.id)
111
+ backup_chat.append({"role": "user", "parts": [{"text": caption}]})
112
+
113
+ ai_reply.edit_text("Uploading file...")
114
+ audio_file = genai.upload_file(path=audio_file_name)
115
+
116
+ while audio_file.state.name == "PROCESSING":
117
+ await asyncio.sleep(10)
118
+ audio_file = genai.get_file(audio_file.name)
119
+
120
+ if audio_file.state.name == "FAILED":
121
+ await ai_reply.edit_text(f"Error: {audio_file.state.name}")
122
+ return
123
+
124
+ try:
125
+ response = model.generate_content(
126
+ [audio_file, caption],
127
+ request_options={"timeout": 600}
128
+ )
129
+ if len(response.text) > 4096:
130
+ with open("chat.txt", "w+", encoding="utf8") as out_file:
131
+ out_file.write(response.text)
132
+ await message.reply_document(
133
+ document="chat.txt",
134
+ disable_notification=True
135
+ )
136
+ await ai_reply.delete()
137
+ os.remove("chat.txt")
138
+ else:
139
+ await ai_reply.edit_text(response.text)
140
+
141
+ backup_chat.append({"role": "model", "parts": [{"text": response.text}]})
142
+ await db._update_chatbot_chat_in_db(message.from_user.id, backup_chat)
143
+
144
+ audio_file.delete()
145
+ os.remove(audio_file_name)
146
+ return
147
+ except InvalidArgument as e:
148
+ await ai_reply.edit_text(f"Error: {e}")
149
+ return
150
+ except Exception as e:
151
+ await ai_reply.edit_text(f"Error: {e}")
152
+ return
153
+
154
+ # Handling Video Messages
155
+ if message.video:
156
+ ai_reply = await message.reply_text("Processing...")
157
+ video_file_name = await message.download(file_name="newvideo.mp4")
158
+ caption = message.caption or "What's this?"
159
+ model = genai.GenerativeModel(
160
+ model_name="gemini-1.5-pro",
161
+ safety_settings={
162
+ genai.types.HarmCategory.HARM_CATEGORY_HATE_SPEECH: genai.types.HarmBlockThreshold.BLOCK_NONE,
163
+ genai.types.HarmCategory.HARM_CATEGORY_HARASSMENT: genai.types.HarmBlockThreshold.BLOCK_NONE,
164
+ genai.types.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: genai.types.HarmBlockThreshold.BLOCK_NONE,
165
+ genai.types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: genai.types.HarmBlockThreshold.BLOCK_NONE,
166
+ }
167
+ )
168
+ backup_chat = await db._get_chatbot_chat_from_db(message.from_user.id)
169
+ backup_chat.append({"role": "user", "parts": [{"text": caption}]})
170
+
171
+ ai_reply.edit_text("Uploading file...")
172
+ video_file = genai.upload_file(path=video_file_name)
173
+
174
+ while video_file.state.name == "PROCESSING":
175
+ await asyncio.sleep(10)
176
+ video_file = genai.get_file(video_file.name)
177
+
178
+ if video_file.state.name == "FAILED":
179
+ await ai_reply.edit_text(f"Error: {video_file.state.name}")
180
+ return
181
+
182
+ try:
183
+ response = model.generate_content(
184
+ [video_file, caption],
185
+ request_options={"timeout": 600}
186
+ )
187
+ if len(response.text) > 4096:
188
+ with open("chat.txt", "w+", encoding="utf8") as out_file:
189
+ out_file.write(response.text)
190
+ await message.reply_document(
191
+ document="chat.txt",
192
+ disable_notification=True
193
+ )
194
+ await ai_reply.delete()
195
+ os.remove("chat.txt")
196
+ else:
197
+ await ai_reply.edit_text(response.text)
198
+
199
+ backup_chat.append({"role": "model", "parts": [{"text": response.text}]})
200
+ await db._update_chatbot_chat_in_db(message.from_user.id, backup_chat)
201
+
202
+ video_file.delete()
203
+ os.remove(video_file_name)
204
+ return
205
+ except InvalidArgument as e:
206
+ await ai_reply.edit_text(f"Error: {e}")
207
+ return
208
+ except Exception as e:
209
+ await ai_reply.edit_text(f"Error: {e}")
210
+ return
211
+
212
+ # Handling Text Messages
213
+ if message.text:
214
+ query = message.text.strip()
215
+ match = re.search(r"\b(Randy|Rendi)\b(.*)", query, flags=re.IGNORECASE)
216
+ if match:
217
+ rest_of_sentence = match.group(2).strip()
218
+ query_base = rest_of_sentence if rest_of_sentence else query
219
+ else:
220
+ query_base = query
221
+
222
+ parts = query.split(maxsplit=1)
223
+ command = parts[0].lower()
224
+ pic_query = parts[1].strip() if len(parts) > 1 else ""
225
+
226
+ try:
227
+ model_flash = genai.GenerativeModel(
228
+ model_name="gemini-1.5-flash"
229
+ )
230
+ backup_chat = await db._get_chatbot_chat_from_db(message.from_user.id)
231
+ backup_chat.append({"role": "user", "parts": [{"text": query_base}]})
232
+
233
+ chat_session = model_flash.start_chat(history=backup_chat)
234
+ response_data = chat_session.send_message(query_base)
235
+ output = response_data.text
236
+
237
+ if len(output) > 4096:
238
+ with open("chat.txt", "w+", encoding="utf8") as out_file:
239
+ out_file.write(output)
240
+ await message.reply_document(
241
+ document="chat.txt",
242
+ disable_notification=True
243
+ )
244
+ os.remove("chat.txt")
245
+ else:
246
+ await message.reply_text(output)
247
+
248
+ backup_chat.append({"role": "model", "parts": [{"text": output}]})
249
+ await db._update_chatbot_chat_in_db(message.from_user.id, backup_chat)
250
+ except Exception as e:
251
+ await message.reply_text(str(e))
252
+ # End of handler
253
+
254
+ # Define the main coroutine
255
+ async def main():
256
+ await db.connect() # Connect to your database
257
+ LOGS.info("Connected to the database.")
258
+ await client.start() # Start the Pyrogram client
259
+ LOGS.info("Bot started successfully.")
260
+ await idle() # Keep the bot running until interrupted
261
+ LOGS.info("Bot stopping...")
262
+ await client.stop() # Ensure the client stops gracefully
263
+
264
+ # Entry point
265
+ if __name__ == "__main__":
266
+ try:
267
+ asyncio.run(main())
268
+ except (KeyboardInterrupt, SystemExit):
269
+ LOGS.info("Bot has been terminated by the user.")
270
+ except Exception as e:
271
+ LOGS.error(f"Unexpected error: {e}")
272
+