randydev commited on
Commit
15fd38b
·
verified ·
1 Parent(s): 5b99e56

Upload chat.py

Browse files
Files changed (1) hide show
  1. chatbot/plugins/chat.py +122 -29
chatbot/plugins/chat.py CHANGED
@@ -23,6 +23,7 @@ import traceback
23
  import requests
24
  import json
25
  import io
 
26
  from datetime import datetime as dt, timedelta
27
 
28
  from gpytranslate import SyncTranslator
@@ -64,24 +65,6 @@ DISABLED_COMMANDS = [
64
  "--deletemydata --reason"
65
  ]
66
 
67
- blacklist_patterns = [
68
- r"\bkill\s*yourself\b",
69
- r"\bi['’]?ll\s*rape\s*you\b",
70
- r"\bhate\s*speech\b",
71
- r"\bbomb\s*threat\b",
72
- r"\bterrorist\b",
73
- r"\bgore\s*content\b",
74
- r"\bchild\s*abuse\b",
75
- r"\bracist\s*slur\b",
76
- r"\bdeepfake\s*porn\b",
77
- r"\bnude\s*minors\b",
78
- r"\bsuicide\s*tutorial\b",
79
- r"\bhow\s*to\s*make\s*a\s*bomb\b",
80
- r"\billegal\s*weapon\b",
81
- r"\bschool\s*shooting\b",
82
- r"\bdeath\s*threat\b",
83
- ]
84
-
85
  def aigen_check(user_id: int, text: str):
86
  result = {}
87
  try:
@@ -118,12 +101,6 @@ def is_command_disabled(text):
118
  else:
119
  return False
120
 
121
- def is_blacklisted_english(text: str) -> bool:
122
- for pattern in blacklist_patterns:
123
- if re.search(pattern, text, re.IGNORECASE):
124
- return True
125
- return False
126
-
127
  def obfuscate(word):
128
  return word.lower()\
129
  .replace("a", "[a@4]")\
@@ -199,6 +176,51 @@ Type anything to begin.
199
 
200
  gen = genai.Client(api_key=GOOGLE_API_KEY)
201
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  # Original: @GeminiAIDev_Bot
203
  # Code by @xtdevs
204
  def replace_with_markdown_list(text, pattern=r"^\s*\*\s*(.*)$"):
@@ -231,6 +253,43 @@ def split_message(text: str) -> List[str]:
231
  async def closeed(client, callback):
232
  await callback.message.delete()
233
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
  @Client.on_callback_query(filters.regex("^modelmenu:([a-f0-9]{8})$"))
235
  async def modelgeminimenu(client, callback):
236
  uuidstr = callback.matches[0].group(1)
@@ -300,7 +359,7 @@ async def geminigen_prompt(client, callback):
300
  get_response = data.get("prompt_image", None)
301
  if not get_response:
302
  return await callback.answer("Server busy try again later", True)
303
- if regex_all_blacklist(get_response) or is_blacklisted_english(get_response):
304
  return await callback.answer("Sorry your account is frozen", True)
305
 
306
  await callback.message.edit_text("....")
@@ -382,7 +441,7 @@ async def flux_prompt(client, callback):
382
  get_response = data.get("prompt_image", None)
383
  if not get_response:
384
  return await callback.answer("Server busy try again later", True)
385
- if regex_all_blacklist(get_response) or is_blacklisted_english(get_response):
386
  return await callback.answer("Sorry your account is frozen", True)
387
 
388
  await callback.message.edit_text("....")
@@ -697,6 +756,7 @@ def create_keyboard(
697
  InlineKeyboardButton(f"♾️", callback_data=f"trmulti_{uuid_str}"),
698
  InlineKeyboardButton(f"🔒", callback_data=f"showchat"),
699
  InlineKeyboardButton(f"⛏️", callback_data=f"modelmenu:{uuid_str}"),
 
700
  InlineKeyboardButton(f"💾", callback_data=f"memory_{uuid_str}")
701
  ],
702
  [
@@ -820,7 +880,7 @@ async def chatbot_talk(client: Client, message: Message):
820
  await client.send_chat_action(message.chat.id, enums.ChatAction.UPLOAD_PHOTO)
821
  await asyncio.sleep(1.5)
822
 
823
- if regex_all_blacklist(caption) or is_blacklisted_english(caption):
824
  await client.send_chat_action(message.chat.id, enums.ChatAction.CANCEL)
825
  return
826
 
@@ -1071,7 +1131,7 @@ async def chatbot_talk(client: Client, message: Message):
1071
  await client.send_chat_action(message.chat.id, enums.ChatAction.UPLOAD_VIDEO)
1072
  await asyncio.sleep(2.0)
1073
  caption = message.caption or "What this?"
1074
- if regex_all_blacklist(caption) or is_blacklisted_english(caption):
1075
  return
1076
 
1077
  backup_chat = await db._get_chatbot_chat_from_db(message.from_user.id)
@@ -1208,7 +1268,7 @@ async def chatbot_talk(client: Client, message: Message):
1208
  await client.send_chat_action(message.chat.id, enums.ChatAction.CANCEL)
1209
  return
1210
 
1211
- if regex_all_blacklist(query_base) or is_blacklisted_english(query_base):
1212
  unfreeze_at = dt.now() + timedelta(days=2)
1213
  await db.user_blacklists.update_one(
1214
  {"user_id": message.from_user.id},
@@ -1340,6 +1400,39 @@ async def chatbot_talk(client: Client, message: Message):
1340
  )
1341
  return
1342
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1343
  if check_is_system.get("is_system", False):
1344
  _deletemydata_match = re.match(r"^--deletemydata\s+--reason\s+(.+)$", query_base, re.IGNORECASE)
1345
  if _deletemydata_match:
 
23
  import requests
24
  import json
25
  import io
26
+ import cohere
27
  from datetime import datetime as dt, timedelta
28
 
29
  from gpytranslate import SyncTranslator
 
65
  "--deletemydata --reason"
66
  ]
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  def aigen_check(user_id: int, text: str):
69
  result = {}
70
  try:
 
101
  else:
102
  return False
103
 
 
 
 
 
 
 
104
  def obfuscate(word):
105
  return word.lower()\
106
  .replace("a", "[a@4]")\
 
176
 
177
  gen = genai.Client(api_key=GOOGLE_API_KEY)
178
 
179
+ async def search_auto_by_cohere(user_id, prompt):
180
+ COHERE_API_KEY = os.environ.get("COHERE_API_KEY")
181
+ co = cohere.Client(api_key=COHERE_API_KEY)
182
+ stream = co.chat_stream(
183
+ model='command-r-08-2024',
184
+ message=prompt,
185
+ temperature=0.3,
186
+ chat_history=chat_history,
187
+ prompt_truncation='AUTO',
188
+ connectors=[{"id":"web-search"}]
189
+ )
190
+ data = []
191
+ output = ""
192
+ for event in stream:
193
+ if event.event_type == "search-results":
194
+ if event.documents:
195
+ data.extend(event.documents)
196
+ elif event.event_type == "text-generation":
197
+ output += event.text
198
+
199
+ if not data:
200
+ data = [{"title": "", "url": ""}]
201
+
202
+ reference_dict = {}
203
+ for item in data:
204
+ title = item.get("title", "").strip()
205
+ url = item.get("url", "").strip()
206
+ if not title or not url:
207
+ continue
208
+ if title not in reference_dict:
209
+ reference_dict[title] = url
210
+ references = ""
211
+ for i, (title, url) in enumerate(reference_dict.items()):
212
+ references += f"{i}. [{title}]({url})\n"
213
+
214
+ if not references.strip():
215
+ references = ""
216
+
217
+ if not output:
218
+ output = "I couldn't generate a response."
219
+
220
+ all_answer = f"{output}\n\n{references}"
221
+ return all_answer
222
+
223
+
224
  # Original: @GeminiAIDev_Bot
225
  # Code by @xtdevs
226
  def replace_with_markdown_list(text, pattern=r"^\s*\*\s*(.*)$"):
 
253
  async def closeed(client, callback):
254
  await callback.message.delete()
255
 
256
+ @Client.on_callback_query(filters.regex("^comode:([a-f0-9]{8})"))
257
+ async def coheresearch(client, callback):
258
+ uuidstr = callback.matches[0].group(1)
259
+ keyboard = []
260
+ keyboard.append([
261
+ InlineKeyboardButton("Deep Search ON", callback_data=f"deeps_on_{uuidstr}"),
262
+ InlineKeyboardButton("Deep Search OFF", callback_data=f"deeps_off_{uuidstr}")
263
+ ])
264
+ keyboard.append([
265
+ InlineKeyboardButton("Back To Menu", callback_data=f"menu_back:{uuidstr}")
266
+ ])
267
+ await callback.edit_message_reply_markup(reply_markup=InlineKeyboardMarkup(keyboard))
268
+
269
+ @Client.on_callback_query(filters.regex("^deeps_(on|off)_([a-f0-9]{8})$"))
270
+ async def deepsearchmode(client, callback):
271
+ user_id = callback.from_user.id
272
+ mode, uuidstr = callback.matches[0].groups()
273
+ try:
274
+ if mode not in ("on", "off"):
275
+ await callback.answer("Mode invalid", show_alert=True)
276
+ return
277
+ is_deepsearch = mode == "on"
278
+ await db.backup_chatbot.update_one(
279
+ {"user_id": user_id},
280
+ {"$set": {"is_deepsearch": is_deepsearch}},
281
+ upsert=True
282
+ )
283
+ await callback.answer(f"Deep Search mode is set to {mode}.", show_alert=True)
284
+ keyboard = create_keyboard(
285
+ user_id=user_id,
286
+ uuid_str=uuidstr
287
+ )
288
+ await callback.edit_message_reply_markup(reply_markup=keyboard)
289
+ except Exception as e:
290
+ LOGS.error(f"Cohere Error: {e}")
291
+ await callback.answer("Please try again later..", show_alert=True)
292
+
293
  @Client.on_callback_query(filters.regex("^modelmenu:([a-f0-9]{8})$"))
294
  async def modelgeminimenu(client, callback):
295
  uuidstr = callback.matches[0].group(1)
 
359
  get_response = data.get("prompt_image", None)
360
  if not get_response:
361
  return await callback.answer("Server busy try again later", True)
362
+ if regex_all_blacklist(get_response):
363
  return await callback.answer("Sorry your account is frozen", True)
364
 
365
  await callback.message.edit_text("....")
 
441
  get_response = data.get("prompt_image", None)
442
  if not get_response:
443
  return await callback.answer("Server busy try again later", True)
444
+ if regex_all_blacklist(get_response):
445
  return await callback.answer("Sorry your account is frozen", True)
446
 
447
  await callback.message.edit_text("....")
 
756
  InlineKeyboardButton(f"♾️", callback_data=f"trmulti_{uuid_str}"),
757
  InlineKeyboardButton(f"🔒", callback_data=f"showchat"),
758
  InlineKeyboardButton(f"⛏️", callback_data=f"modelmenu:{uuid_str}"),
759
+ InlineKeyboardButton(f"💡", callback_data=f"comode:{uuid_str}"),
760
  InlineKeyboardButton(f"💾", callback_data=f"memory_{uuid_str}")
761
  ],
762
  [
 
880
  await client.send_chat_action(message.chat.id, enums.ChatAction.UPLOAD_PHOTO)
881
  await asyncio.sleep(1.5)
882
 
883
+ if regex_all_blacklist(caption):
884
  await client.send_chat_action(message.chat.id, enums.ChatAction.CANCEL)
885
  return
886
 
 
1131
  await client.send_chat_action(message.chat.id, enums.ChatAction.UPLOAD_VIDEO)
1132
  await asyncio.sleep(2.0)
1133
  caption = message.caption or "What this?"
1134
+ if regex_all_blacklist(caption):
1135
  return
1136
 
1137
  backup_chat = await db._get_chatbot_chat_from_db(message.from_user.id)
 
1268
  await client.send_chat_action(message.chat.id, enums.ChatAction.CANCEL)
1269
  return
1270
 
1271
+ if regex_all_blacklist(query_base):
1272
  unfreeze_at = dt.now() + timedelta(days=2)
1273
  await db.user_blacklists.update_one(
1274
  {"user_id": message.from_user.id},
 
1400
  )
1401
  return
1402
 
1403
+ if check_is_system.get("is_deepsearch", False):
1404
+ uuid_code = str(uuid.uuid4())[:8]
1405
+ backup_chat = await db._get_chatbot_chat_from_db(user_id)
1406
+ backup_chat.append({"role": "user", "parts": [{"text": prompt}]})
1407
+ results = await search_auto_by_cohere(message.from_user.id, query_base):
1408
+ if len(results) > 4096:
1409
+ text_parts = split_message(results)
1410
+ for part in text_parts:
1411
+ await message.reply_text(part)
1412
+ else:
1413
+ keyboard_like = create_keyboard(
1414
+ user_id=message.from_user.id,
1415
+ uuid_str=uuid_code
1416
+ )
1417
+ await message.reply_text(
1418
+ results,
1419
+ disable_web_page_preview=True,
1420
+ reply_markup=keyboard_like
1421
+ )
1422
+ translation_entry = {
1423
+ "uuid": uuid_code,
1424
+ "text": results,
1425
+ "timestamp": dt.now().isoformat()
1426
+ }
1427
+ await db.backup_chatbot.update_one(
1428
+ {"user_id": message.from_user.id},
1429
+ {"$push": {"translate_history": translation_entry}},
1430
+ upsert=True
1431
+ )
1432
+ backup_chat.append({"role": "model", "parts": [{"text": results}]})
1433
+ await db._update_chatbot_chat_in_db(message.from_user.id, backup_chat)
1434
+ return
1435
+
1436
  if check_is_system.get("is_system", False):
1437
  _deletemydata_match = re.match(r"^--deletemydata\s+--reason\s+(.+)$", query_base, re.IGNORECASE)
1438
  if _deletemydata_match: