randydev commited on
Commit
9262f3c
·
verified ·
1 Parent(s): eeae12d

Update Akeno/__main__.py

Browse files
Files changed (1) hide show
  1. Akeno/__main__.py +263 -71
Akeno/__main__.py CHANGED
@@ -1,83 +1,275 @@
1
- #!/usr/bin/env python
2
- # -*- coding: utf-8 -*-
3
- # Copyright 2020-2023 (c) Randy W @xtdevs, @xtsea
4
- #
5
- # from : https://github.com/TeamKillerX
6
- # Channel : @RendyProjects
7
- # This program is free software: you can redistribute it and/or modify
8
- # it under the terms of the GNU Affero General Public License as published by
9
- # the Free Software Foundation, either version 3 of the License, or
10
- # (at your option) any later version.
11
-
12
- # This program is distributed in the hope that it will be useful,
13
- # but WITHOUT ANY WARRANTY; without even the implied warranty of
14
- # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
- # GNU Affero General Public License for more details.
16
- #
17
- # You should have received a copy of the GNU Affero General Public License
18
- # along with this program. If not, see <https://www.gnu.org/licenses/>.
19
-
20
  import asyncio
21
- import importlib
22
  import logging
23
- import sys
24
- from contextlib import closing, suppress
25
- from importlib import import_module
26
 
27
- from pyrogram import idle
28
- from pyrogram.errors import *
29
- from uvloop import install
30
 
31
- from Akeno import clients
32
- from Akeno.plugins import ALL_MODULES
33
- from Akeno.utils.database import db
34
- from Akeno.utils.logger import LOGS
 
 
 
35
 
36
- logging.basicConfig(level=logging.INFO)
37
- logging.getLogger("pyrogram.syncer").setLevel(logging.WARNING)
38
- logging.getLogger("pyrogram.client").setLevel(logging.WARNING)
39
- loop = asyncio.get_event_loop()
 
 
40
 
41
- async def main():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  try:
43
- await db.connect()
44
- for module_name in ALL_MODULES:
45
- imported_module = import_module(f"Akeno.plugins.{module_name}")
46
- for cli in clients:
 
 
 
 
 
 
 
 
 
 
 
47
  try:
48
- await cli.start()
49
- except SessionExpired as e:
50
- LOGS.info(f"Error {e}")
51
- sys.exit(1)
52
- except ApiIdInvalid as e:
53
- LOGS.info(f"Error {e}")
54
- sys.exit(1)
55
- except UserDeactivated as e:
56
- LOGS.info(f"Error {e}")
57
- sys.exit(1)
58
- except AuthKeyDuplicated as e:
59
- LOGS.info(f"Error {e}")
60
- sys.exit(1)
 
 
 
 
 
 
 
 
 
 
 
 
61
  except Exception as e:
62
- LOGS.info(f"Error starting userbot: {e}")
63
- ex = await cli.get_me()
64
- LOGS.info(f"Started {ex.first_name}")
65
- await cli.send_message("me", "Starting Akeno Userbot")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  try:
67
- await cli.join_chat("RendyProjects")
68
- except UserIsBlocked:
69
- return LOGS.info("You have been blocked. Please support @xtdevs")
70
- await idle()
71
- except Exception as e:
72
- LOGS.info(f"Error in main: {e}")
73
- finally:
74
- for task in asyncio.all_tasks():
75
- task.cancel()
76
- LOGS.info("All tasks completed successfully!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  if __name__ == "__main__":
79
- install()
80
- with closing(loop):
81
- with suppress(asyncio.exceptions.CancelledError):
82
- loop.run_until_complete(main())
83
- loop.run_until_complete(asyncio.sleep(3.0))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ chat_user = await db.get_chatbot(message.chat.id)
56
+ if not chat_user:
57
+ return # Exit if no chatbot is configured for the chat
58
+
59
+ genai.configure(api_key=GOOGLE_API_KEY)
60
+
61
+ # Handling Photo Messages
62
+ if message.photo:
63
+ file_path = await message.download()
64
+ caption = message.caption or "What's this?"
65
+ x = GeminiLatest(api_keys=GOOGLE_API_KEY)
66
+
67
+ # Send initial processing message
68
+ ai_reply = await message.reply_text("Processing...")
69
+
70
  try:
71
+ backup_chat = await db._get_chatbot_chat_from_db(message.from_user.id)
72
+ backup_chat.append({"role": "user", "parts": [{"text": caption}]})
73
+
74
+ response_reads = x.get_response_image(caption, file_path)
75
+
76
+ if len(response_reads) > 4096:
77
+ with open("chat.txt", "w+", encoding="utf8") as out_file:
78
+ out_file.write(response_reads)
79
+ await message.reply_document(
80
+ document="chat.txt",
81
+ disable_notification=True
82
+ )
83
+ await ai_reply.delete()
84
+ os.remove("chat.txt")
85
+ else:
86
+ await ai_reply.edit_text(response_reads)
87
+
88
+ backup_chat.append({"role": "model", "parts": [{"text": response_reads}]})
89
+ await db._update_chatbot_chat_in_db(message.from_user.id, backup_chat)
90
+
91
+ os.remove(file_path)
92
+ return
93
+ except InvalidArgument as e:
94
+ await ai_reply.edit_text(f"Error: {e}")
95
+ return
96
  except Exception as e:
97
+ await ai_reply.edit_text(f"Error: {e}")
98
+ return
99
+
100
+ # Handling Audio or Voice Messages
101
+ if message.audio or message.voice:
102
+ ai_reply = await message.reply_text("Processing...")
103
+ audio_file_name = await message.download()
104
+ caption = message.caption or "What's this?"
105
+ model = genai.GenerativeModel(
106
+ model_name="gemini-1.5-flash",
107
+ safety_settings={
108
+ genai.types.HarmCategory.HARM_CATEGORY_HATE_SPEECH: genai.types.HarmBlockThreshold.BLOCK_NONE,
109
+ genai.types.HarmCategory.HARM_CATEGORY_HARASSMENT: genai.types.HarmBlockThreshold.BLOCK_NONE,
110
+ genai.types.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: genai.types.HarmBlockThreshold.BLOCK_NONE,
111
+ genai.types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: genai.types.HarmBlockThreshold.BLOCK_NONE,
112
+ }
113
+ )
114
+ backup_chat = await db._get_chatbot_chat_from_db(message.from_user.id)
115
+ backup_chat.append({"role": "user", "parts": [{"text": caption}]})
116
+
117
+ ai_reply.edit_text("Uploading file...")
118
+ audio_file = genai.upload_file(path=audio_file_name)
119
+
120
+ while audio_file.state.name == "PROCESSING":
121
+ await asyncio.sleep(10)
122
+ audio_file = genai.get_file(audio_file.name)
123
+
124
+ if audio_file.state.name == "FAILED":
125
+ await ai_reply.edit_text(f"Error: {audio_file.state.name}")
126
+ return
127
+
128
  try:
129
+ response = model.generate_content(
130
+ [audio_file, caption],
131
+ request_options={"timeout": 600}
132
+ )
133
+ if len(response.text) > 4096:
134
+ with open("chat.txt", "w+", encoding="utf8") as out_file:
135
+ out_file.write(response.text)
136
+ await message.reply_document(
137
+ document="chat.txt",
138
+ disable_notification=True
139
+ )
140
+ await ai_reply.delete()
141
+ os.remove("chat.txt")
142
+ else:
143
+ await ai_reply.edit_text(response.text)
144
+
145
+ backup_chat.append({"role": "model", "parts": [{"text": response.text}]})
146
+ await db._update_chatbot_chat_in_db(message.from_user.id, backup_chat)
147
+
148
+ audio_file.delete()
149
+ os.remove(audio_file_name)
150
+ return
151
+ except InvalidArgument as e:
152
+ await ai_reply.edit_text(f"Error: {e}")
153
+ return
154
+ except Exception as e:
155
+ await ai_reply.edit_text(f"Error: {e}")
156
+ return
157
 
158
+ # Handling Video Messages
159
+ if message.video:
160
+ ai_reply = await message.reply_text("Processing...")
161
+ video_file_name = await message.download(file_name="newvideo.mp4")
162
+ caption = message.caption or "What's this?"
163
+ model = genai.GenerativeModel(
164
+ model_name="gemini-1.5-pro",
165
+ safety_settings={
166
+ genai.types.HarmCategory.HARM_CATEGORY_HATE_SPEECH: genai.types.HarmBlockThreshold.BLOCK_NONE,
167
+ genai.types.HarmCategory.HARM_CATEGORY_HARASSMENT: genai.types.HarmBlockThreshold.BLOCK_NONE,
168
+ genai.types.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: genai.types.HarmBlockThreshold.BLOCK_NONE,
169
+ genai.types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: genai.types.HarmBlockThreshold.BLOCK_NONE,
170
+ }
171
+ )
172
+ backup_chat = await db._get_chatbot_chat_from_db(message.from_user.id)
173
+ backup_chat.append({"role": "user", "parts": [{"text": caption}]})
174
+
175
+ ai_reply.edit_text("Uploading file...")
176
+ video_file = genai.upload_file(path=video_file_name)
177
+
178
+ while video_file.state.name == "PROCESSING":
179
+ await asyncio.sleep(10)
180
+ video_file = genai.get_file(video_file.name)
181
+
182
+ if video_file.state.name == "FAILED":
183
+ await ai_reply.edit_text(f"Error: {video_file.state.name}")
184
+ return
185
+
186
+ try:
187
+ response = model.generate_content(
188
+ [video_file, caption],
189
+ request_options={"timeout": 600}
190
+ )
191
+ if len(response.text) > 4096:
192
+ with open("chat.txt", "w+", encoding="utf8") as out_file:
193
+ out_file.write(response.text)
194
+ await message.reply_document(
195
+ document="chat.txt",
196
+ disable_notification=True
197
+ )
198
+ await ai_reply.delete()
199
+ os.remove("chat.txt")
200
+ else:
201
+ await ai_reply.edit_text(response.text)
202
+
203
+ backup_chat.append({"role": "model", "parts": [{"text": response.text}]})
204
+ await db._update_chatbot_chat_in_db(message.from_user.id, backup_chat)
205
+
206
+ video_file.delete()
207
+ os.remove(video_file_name)
208
+ return
209
+ except InvalidArgument as e:
210
+ await ai_reply.edit_text(f"Error: {e}")
211
+ return
212
+ except Exception as e:
213
+ await ai_reply.edit_text(f"Error: {e}")
214
+ return
215
+
216
+ # Handling Text Messages
217
+ if message.text:
218
+ query = message.text.strip()
219
+ match = re.search(r"\b(Randy|Rendi)\b(.*)", query, flags=re.IGNORECASE)
220
+ if match:
221
+ rest_of_sentence = match.group(2).strip()
222
+ query_base = rest_of_sentence if rest_of_sentence else query
223
+ else:
224
+ query_base = query
225
+
226
+ parts = query.split(maxsplit=1)
227
+ command = parts[0].lower()
228
+ pic_query = parts[1].strip() if len(parts) > 1 else ""
229
+
230
+ try:
231
+ model_flash = genai.GenerativeModel(
232
+ model_name="gemini-1.5-flash"
233
+ )
234
+ backup_chat = await db._get_chatbot_chat_from_db(message.from_user.id)
235
+ backup_chat.append({"role": "user", "parts": [{"text": query_base}]})
236
+
237
+ chat_session = model_flash.start_chat(history=backup_chat)
238
+ response_data = chat_session.send_message(query_base)
239
+ output = response_data.text
240
+
241
+ if len(output) > 4096:
242
+ with open("chat.txt", "w+", encoding="utf8") as out_file:
243
+ out_file.write(output)
244
+ await message.reply_document(
245
+ document="chat.txt",
246
+ disable_notification=True
247
+ )
248
+ os.remove("chat.txt")
249
+ else:
250
+ await message.reply_text(output)
251
+
252
+ backup_chat.append({"role": "model", "parts": [{"text": output}]})
253
+ await db._update_chatbot_chat_in_db(message.from_user.id, backup_chat)
254
+ except Exception as e:
255
+ await message.reply_text(str(e))
256
+ # End of handler
257
+
258
+ # Define the main coroutine
259
+ async def main():
260
+ await db.connect() # Connect to your database
261
+ LOGS.info("Connected to the database.")
262
+ await client.start() # Start the Pyrogram client
263
+ LOGS.info("Bot started successfully.")
264
+ await idle() # Keep the bot running until interrupted
265
+ LOGS.info("Bot stopping...")
266
+ await client.stop() # Ensure the client stops gracefully
267
+
268
+ # Entry point
269
  if __name__ == "__main__":
270
+ try:
271
+ asyncio.run(main())
272
+ except (KeyboardInterrupt, SystemExit):
273
+ LOGS.info("Bot has been terminated by the user.")
274
+ except Exception as e:
275
+ LOGS.error(f"Unexpected error: {e}")