azils3 commited on
Commit
7174173
·
verified ·
1 Parent(s): e44770e

Update utils.py

Browse files
Files changed (1) hide show
  1. utils.py +278 -217
utils.py CHANGED
@@ -9,17 +9,22 @@ from datetime import datetime, timedelta
9
  from database.users_chats_db import db
10
  from bs4 import BeautifulSoup
11
 
 
12
  logger = logging.getLogger(__name__)
13
  logger.setLevel(logging.INFO)
14
 
 
15
  BTN_URL_REGEX = re.compile(r"(\[([^\[]+?)\]\((buttonurl|buttonalert):(?:/{0,2})(.+?)(:same)?\))")
 
 
16
  BANNED = {}
17
  SMART_OPEN = '“'
18
  SMART_CLOSE = '”'
19
  START_CHAR = ('\'', '"', SMART_OPEN)
20
 
21
- # temp db for banned
22
  class temp(object):
 
23
  BANNED_USERS = []
24
  BANNED_CHATS = []
25
  CURRENT = 0
@@ -34,246 +39,278 @@ class temp(object):
34
  GP_SPELL = {}
35
 
36
  async def is_subscribed(bot, query):
37
- logger.info(f"Checking subscription for user_id: {query.from_user.id} in AUTH_CHANNEL: {AUTH_CHANNEL}")
 
38
  try:
39
  user = await bot.get_chat_member(AUTH_CHANNEL, query.from_user.id)
40
- logger.debug(f"User {query.from_user.id} is subscribed.")
41
- except UserNotParticipant:
42
- logger.debug(f"User {query.from_user.id} is not subscribed.")
43
- pass
44
- except Exception as e:
45
- logger.error(f"Error checking subscription: {e}")
46
- print(e)
47
- else:
48
  if user.status != enums.ChatMemberStatus.BANNED:
49
- logger.debug(f"User {query.from_user.id} is not banned.")
50
  return True
51
- logger.debug(f"User {query.from_user.id} is not subscribed.")
 
 
 
 
52
  return False
53
 
54
  async def get_poster(query, bulk=False, id=False, file=None):
55
- logger.info(f"Fetching poster for query: {query}, bulk: {bulk}, id: {id}, file: {file}")
56
- imdb = Cinemagoer()
57
- if not id:
58
- query = (query.strip()).lower()
59
- title = query
60
- year = re.findall(r'[1-2]\d{3}$', query, re.IGNORECASE)
61
- if year:
62
- year = list_to_str(year[:1])
63
- title = (query.replace(year, "")).strip()
64
- logger.debug(f"Extracted year: {year}, title: {title}")
65
- elif file is not None:
66
- year = re.findall(r'[1-2]\d{3}', file, re.IGNORECASE)
67
  if year:
68
- year = list_to_str(year[:1])
69
- logger.debug(f"Extracted year from file: {year}")
70
- else:
71
- year = None
72
- logger.debug("Year not found.")
73
- try:
 
 
 
 
 
 
 
74
  movieid = imdb.search_movie(title.lower(), results=10)
75
- logger.debug(f"Found movie IDs: {movieid}")
76
- except Exception as e:
77
- logger.error(f"Error searching movie: {e}")
78
- return None
79
- if not movieid:
80
- logger.debug("No movie IDs found.")
81
- return None
82
- if year:
83
- filtered=list(filter(lambda k: str(k.get('year')) == str(year), movieid))
84
- if not filtered:
 
 
 
 
85
  filtered = movieid
86
- logger.debug("No filtered results. Using original results.")
87
- logger.debug(f"Filtered results: {filtered}")
 
 
 
 
 
 
 
 
 
 
 
 
88
  else:
89
- filtered = movieid
90
- logger.debug("Using original results.")
91
- movieid=list(filter(lambda k: k.get('kind') in ['movie', 'tv series'], filtered))
92
- if not movieid:
93
- movieid = filtered
94
- logger.debug("No movie or tv series results. Using original results.")
95
- logger.debug(f"Final movie IDs: {movieid}")
96
- if bulk:
97
- logger.debug("Returning bulk results.")
98
- return movieid
99
- movieid = movieid[0].movieID
100
- logger.debug(f"Selected movie ID: {movieid}")
101
- else:
102
- movieid = query
103
- logger.debug(f"Using provided movie ID: {movieid}")
104
- movie = imdb.get_movie(movieid)
105
- if movie.get("original air date"):
106
- date = movie["original air date"]
107
- logger.debug(f"Original air date: {date}")
108
- elif movie.get("year"):
109
- date = movie.get("year")
110
- logger.debug(f"Year: {date}")
111
- else:
112
- date = "N/A"
113
- logger.debug("Date not found. Setting to N/A.")
114
- plot = ""
115
- if not LONG_IMDB_DESCRIPTION:
116
- plot = movie.get('plot')
117
- if plot and len(plot) > 0:
118
- plot = plot[0]
119
- logger.debug(f"Plot: {plot}")
120
- else:
121
- plot = movie.get('plot outline')
122
- logger.debug(f"Plot outline: {plot}")
123
- if plot and len(plot) > 800:
124
- plot = plot[0:800] + "..."
125
- logger.debug(f"Truncated plot: {plot}")
126
- return {
127
- 'title': movie.get('title'),
128
- 'votes': movie.get('votes'),
129
- "aka": list_to_str(movie.get("akas")),
130
- "seasons": movie.get("number of seasons"),
131
- "box_office": movie.get('box office'),
132
- 'localized_title': movie.get('localized title'),
133
- 'kind': movie.get("kind"),
134
- "imdb_id": f"tt{movie.get('imdbID')}",
135
- "cast": list_to_str(movie.get("cast")),
136
- "runtime": list_to_str(movie.get("runtimes")),
137
- "countries": list_to_str(movie.get("countries")),
138
- "certificates": list_to_str(movie.get("certificates")),
139
- "languages": list_to_str(movie.get("languages")),
140
- "director": list_to_str(movie.get("director")),
141
- "writer":list_to_str(movie.get("writer")),
142
- "producer":list_to_str(movie.get("producer")),
143
- "composer":list_to_str(movie.get("composer")) ,
144
- "cinematographer":list_to_str(movie.get("cinematographer")),
145
- "music_team": list_to_str(movie.get("music department")),
146
- "distributors": list_to_str(movie.get("distributors")),
147
- 'release_date': date,
148
- 'year': movie.get('year'),
149
- 'genres': list_to_str(movie.get("genres")),
150
- 'poster': movie.get('full-size cover url'),
151
- 'plot': plot,
152
- 'rating': str(movie.get("rating")),
153
- 'url':f'https://www.imdb.com/title/tt{movieid}'
154
- }
155
 
156
  def list_to_str(k):
157
- logger.debug(f"Converting list to string: {k}")
 
158
  if not k:
159
- logger.debug("List is empty. Returning 'N/A'.")
160
  return "N/A"
161
  elif len(k) == 1:
162
- logger.debug(f"List has one element. Returning: {k[0]}")
163
  return str(k[0])
164
  elif MAX_LIST_ELM:
 
165
  k = k[:int(MAX_LIST_ELM)]
166
- result = ' '.join(f'{elem}, ' for elem in k)
167
- logger.debug(f"Truncated list to {MAX_LIST_ELM} elements. Returning: {result}")
168
- return result
169
  else:
170
- result = ' '.join(f'{elem}, ' for elem in k)
171
- logger.debug(f"Returning full list as string: {result}")
172
- return result
173
 
174
  __repo__ = "https://github.com/MrMKN/PROFESSOR-BOT"
175
- logger.debug(f"Repository URL: {__repo__}")
176
  __version__ = "PROFESSOR-BOT ᴠ4.5.0"
177
- logger.debug(f"Version: {__version__}")
178
  __license__ = "GNU GENERAL PUBLIC LICENSE V2"
179
- logger.debug(f"License: {__license__}")
180
  __copyright__ = "Copyright (C) 2023-present MrMKN <https://github.com/MrMKN>"
181
- logger.debug(f"Copyright: {__copyright__}")
182
 
183
  async def search_gagala(text):
184
- logger.info(f"Searching Google for text: {text}")
 
185
  usr_agent = {
186
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'
187
- }
188
- text = text.replace(" ", '+')
189
- url = f'https://www.google.com/search?q={text}'
190
- response = requests.get(url, headers=usr_agent)
191
- response.raise_for_status()
192
- soup = BeautifulSoup(response.text, 'html.parser')
193
- titles = soup.find_all('h3')
194
- result = [title.getText() for title in titles]
195
- logger.debug(f"Found titles: {result}")
196
- return result
 
 
 
 
 
 
 
 
 
197
 
198
  async def get_settings(group_id):
199
- logger.info(f"Getting settings for group_id: {group_id}")
 
200
  settings = temp.SETTINGS.get(group_id)
 
201
  if not settings:
 
202
  settings = await db.get_settings(group_id)
203
  temp.SETTINGS[group_id] = settings
204
- logger.debug(f"Settings retrieved from database: {settings}")
205
  else:
206
- logger.debug(f"Settings retrieved from cache: {settings}")
 
207
  return settings
208
 
209
  async def save_group_settings(group_id, key, value):
210
- logger.info(f"Saving setting {key} with value {value} for group_id: {group_id}")
 
211
  current = await get_settings(group_id)
212
  current[key] = value
213
  temp.SETTINGS[group_id] = current
214
- await db.update_settings(group_id, current)
215
- logger.debug(f"Updated settings: {current}")
 
 
 
 
 
216
 
217
  def get_size(size):
218
- logger.debug(f"Converting size: {size}")
 
219
  units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"]
220
  size = float(size)
221
  i = 0
 
222
  while size >= 1024.0 and i < len(units):
223
  i += 1
224
  size /= 1024.0
 
225
  result = "%.2f %s" % (size, units[i])
226
  logger.debug(f"Converted size: {result}")
227
  return result
228
 
229
  def get_file_id(msg: Message):
230
- logger.debug(f"Getting file ID from message: {msg}")
231
- if not msg.media:
232
- logger.debug("No media in message.")
 
233
  return None
 
234
  for message_type in ("photo", "animation", "audio", "document", "video", "video_note", "voice", "sticker"):
235
  obj = getattr(msg, message_type)
236
  if obj:
 
237
  setattr(obj, "message_type", message_type)
238
- logger.debug(f"Found file ID: {obj.file_id}")
239
  return obj
240
 
241
  def extract_user(message: Message) -> Union[int, str]:
242
- logger.debug(f"Extracting user from message: {message}")
 
243
  user_id = None
244
  user_first_name = None
 
245
  if message.reply_to_message:
246
  user_id = message.reply_to_message.from_user.id
247
  user_first_name = message.reply_to_message.from_user.first_name
248
- logger.debug(f"User extracted from reply: {user_id}, {user_first_name}")
249
  elif len(message.command) > 1:
250
  if (len(message.entities) > 1 and message.entities[1].type == enums.MessageEntityType.TEXT_MENTION):
251
  required_entity = message.entities[1]
252
  user_id = required_entity.user.id
253
  user_first_name = required_entity.user.first_name
254
- logger.debug(f"User extracted from text mention: {user_id}, {user_first_name}")
255
  else:
256
  user_id = message.command[1]
257
  user_first_name = user_id
258
- logger.debug(f"User extracted from command: {user_id}, {user_first_name}")
259
  try:
260
  user_id = int(user_id)
261
- logger.debug(f"Converted user_id to integer: {user_id}")
262
- except ValueError:
263
- logger.debug("Failed to convert user_id to integer.")
264
- pass
265
  else:
266
  user_id = message.from_user.id
267
  user_first_name = message.from_user.first_name
268
- logger.debug(f"User extracted from message sender: {user_id}, {user_first_name}")
 
269
  return (user_id, user_first_name)
270
 
271
  def split_quotes(text: str) -> List:
272
- logger.debug(f"Splitting quotes from text: {text}")
 
273
  if not any(text.startswith(char) for char in START_CHAR):
274
- result = text.split(None, 1)
275
- logger.debug(f"No quotes found. Split result: {result}")
276
- return result
277
  counter = 1 # ignore first char -> is some kind of quote
278
  while counter < len(text):
279
  if text[counter] == "\\":
@@ -282,77 +319,73 @@ def split_quotes(text: str) -> List:
282
  break
283
  counter += 1
284
  else:
285
- result = text.split(None, 1)
286
- logger.debug(f"No closing quote found. Split result: {result}")
287
- return result
288
 
289
- # 1 to avoid starting quote, and counter is exclusive so avoids ending
290
  key = remove_escapes(text[1:counter].strip())
291
- # index will be in range, or `else` would have been executed and returned
292
  rest = text[counter + 1:].strip()
293
  if not key:
294
  key = text[0] + text[0]
295
- logger.debug(f"No key found. Using default key: {key}")
296
- result = list(filter(None, [key, rest]))
297
- logger.debug(f"Split result: {result}")
298
- return result
299
 
300
  def parser(text, keyword, cb_data):
301
- logger.debug(f"Parsing text: {text}, keyword: {keyword}, cb_data: {cb_data}")
 
302
  if "buttonalert" in text:
303
  text = (text.replace("\n", "\\n").replace("\t", "\\t"))
304
- logger.debug(f"Text after replacing newline and tab: {text}")
305
  buttons = []
306
  note_data = ""
307
  prev = 0
308
  i = 0
309
  alerts = []
 
310
  for match in BTN_URL_REGEX.finditer(text):
311
  n_escapes = 0
312
  to_check = match.start(1) - 1
313
  while to_check > 0 and text[to_check] == "\\":
314
  n_escapes += 1
315
  to_check -= 1
316
- # if even, not escaped -> create button
317
  if n_escapes % 2 == 0:
318
  note_data += text[prev:match.start(1)]
319
  prev = match.end(1)
320
  if match.group(3) == "buttonalert":
321
- # create a thruple with button label, url, and newline status
322
  if bool(match.group(5)) and buttons:
323
  buttons[-1].append(InlineKeyboardButton(match.group(2), callback_data=f"{cb_data}:{i}:{keyword}"))
324
- logger.debug(f"Added buttonalert button: {match.group(2)}, {match.group(4)}, {match.group(5)}")
325
  else:
326
  buttons.append([InlineKeyboardButton(match.group(2), callback_data=f"{cb_data}:{i}:{keyword}")])
327
- logger.debug(f"Created buttonalert button: {match.group(2)}, {match.group(4)}, {match.group(5)}")
328
  i += 1
329
  alerts.append(match.group(4))
330
- logger.debug(f"Added alert: {match.group(4)}")
331
  elif bool(match.group(5)) and buttons:
332
  buttons[-1].append(InlineKeyboardButton(match.group(2), url=match.group(4).replace(" ", "")))
333
- logger.debug(f"Added button: {match.group(2)}, {match.group(4)}")
334
  else:
335
  buttons.append([InlineKeyboardButton(match.group(2), url=match.group(4).replace(" ", ""))])
336
- logger.debug(f"Created button: {match.group(2)}, {match.group(4)}")
337
  else:
338
  note_data += text[prev:to_check]
339
  prev = match.start(1) - 1
340
- logger.debug(f"Escaped button: {match.group(2)}")
341
  else:
342
  note_data += text[prev:]
343
- logger.debug(f"Note data after parsing: {note_data}")
344
  try:
345
- result = (note_data, buttons, alerts)
346
- logger.debug(f"Parsing successful. Result: {result}")
347
- return result
348
  except Exception as e:
349
- logger.error(f"Parsing failed: {e}")
350
  return note_data, buttons, None
351
 
352
  def remove_escapes(text: str) -> str:
353
- logger.debug(f"Removing escapes from text: {text}")
 
354
  res = ""
355
  is_escaped = False
 
356
  for counter in range(len(text)):
357
  if is_escaped:
358
  res += text[counter]
@@ -361,100 +394,128 @@ def remove_escapes(text: str) -> str:
361
  is_escaped = True
362
  else:
363
  res += text[counter]
364
- logger.debug(f"Processed character: {text[counter]}, result so far: {res}")
365
- logger.debug(f"Final result after removing escapes: {res}")
366
  return res
367
-
368
  def humanbytes(size):
 
369
  logger.debug(f"Converting size to human-readable format: {size}")
370
  if not size:
371
- logger.debug("Size is zero. Returning empty string.")
372
  return ""
 
373
  power = 2**10
374
  n = 0
375
  Dic_powerN = {0: ' ', 1: 'Ki', 2: 'Mi', 3: 'Gi', 4: 'Ti'}
 
376
  while size > power:
377
  size /= power
378
  n += 1
379
- logger.debug(f"Converted size: {size}, power: {power}, n: {n}")
380
  result = str(round(size, 2)) + " " + Dic_powerN[n] + 'B'
381
- logger.debug(f"Human-readable size: {result}")
382
  return result
 
 
 
 
 
 
383
 
 
 
 
 
 
 
 
 
384
  async def get_shortlink(link):
385
- logger.info(f"Generating shortlink for link: {link}")
 
386
  url = f'{SHORT_URL}/api'
387
  params = {'api': SHORT_API, 'url': link}
 
388
  try:
389
  async with aiohttp.ClientSession() as session:
390
  async with session.get(url, params=params, raise_for_status=True, ssl=False) as response:
391
  data = await response.json()
392
- logger.debug(f"Shortlink API response: {data}")
393
  if data["status"] == "success":
394
- logger.debug(f"Shortlink generated: {data['shortenedUrl']}")
395
  return data['shortenedUrl']
396
  else:
397
- logger.error(f"Error generating shortlink: {data['message']}")
398
  return link
399
  except Exception as e:
400
- logger.error(f"Exception generating shortlink: {e}")
401
  return link
402
 
403
  def extract_time(time_val):
404
- logger.debug(f"Extracting time from time_val: {time_val}")
 
405
  if any(time_val.endswith(unit) for unit in ("s", "m", "h", "d")):
406
  unit = time_val[-1]
407
  time_num = time_val[:-1] # type: str
 
408
  if not time_num.isdigit():
409
- logger.debug("Time value is not a digit.")
410
  return None
411
 
412
  if unit == "s":
413
  bantime = datetime.now() + timedelta(seconds=int(time_num))
414
- logger.debug(f"Bantime set for seconds: {bantime}")
415
  elif unit == "m":
416
  bantime = datetime.now() + timedelta(minutes=int(time_num))
417
- logger.debug(f"Bantime set for minutes: {bantime}")
418
  elif unit == "h":
419
  bantime = datetime.now() + timedelta(hours=int(time_num))
420
- logger.debug(f"Bantime set for hours: {bantime}")
421
  elif unit == "d":
422
  bantime = datetime.now() + timedelta(days=int(time_num))
423
- logger.debug(f"Bantime set for days: {bantime}")
424
  else:
425
- logger.debug("Invalid time unit.")
426
  return None
427
- logger.debug(f"Extracted bantime: {bantime}")
 
428
  return bantime
429
  else:
430
- logger.debug("Time value does not end with s, m, h, or d.")
431
  return None
432
 
433
  async def admin_check(message: Message) -> bool:
434
- logger.info(f"Checking admin status for message: {message}")
 
435
  if not message.from_user:
436
- logger.debug("Message does not have a from_user.")
437
  return False
 
438
  if message.chat.type not in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
439
- logger.debug("Chat type is not GROUP or SUPERGROUP.")
440
  return False
 
441
  if message.from_user.id in [777000, 1087968824]:
442
- logger.debug("User is a system user.")
443
  return True
 
444
  client = message._client
445
  chat_id = message.chat.id
446
  user_id = message.from_user.id
447
- check_status = await client.get_chat_member(chat_id=chat_id,user_id=user_id)
448
- admin_strings = [enums.ChatMemberStatus.OWNER, enums.ChatMemberStatus.ADMINISTRATOR]
449
- if check_status.status not in admin_strings:
450
- logger.debug("User is not an admin.")
 
 
 
 
 
 
 
 
 
451
  return False
452
- else:
453
- logger.debug("User is an admin.")
454
- return True
455
 
456
  async def admin_filter(filt, client, message):
457
- logger.info(f"Applying admin filter for message: {message}")
458
- result = await admin_check(message)
459
- logger.debug(f"Admin filter result: {result}")
460
- return result
 
 
9
  from database.users_chats_db import db
10
  from bs4 import BeautifulSoup
11
 
12
+ # Initialize logger with enhanced configuration
13
  logger = logging.getLogger(__name__)
14
  logger.setLevel(logging.INFO)
15
 
16
+ # Log regex pattern compilation
17
  BTN_URL_REGEX = re.compile(r"(\[([^\[]+?)\]\((buttonurl|buttonalert):(?:/{0,2})(.+?)(:same)?\))")
18
+ logger.debug("Button URL regex pattern compiled successfully")
19
+
20
  BANNED = {}
21
  SMART_OPEN = '“'
22
  SMART_CLOSE = '”'
23
  START_CHAR = ('\'', '"', SMART_OPEN)
24
 
25
+ # Temporary database class with logging
26
  class temp(object):
27
+ logger.info("Initializing temporary storage for banned users/chats and settings")
28
  BANNED_USERS = []
29
  BANNED_CHATS = []
30
  CURRENT = 0
 
39
  GP_SPELL = {}
40
 
41
  async def is_subscribed(bot, query):
42
+ """Check if user is subscribed to auth channel with detailed logging"""
43
+ logger.debug(f"Checking subscription status for user {query.from_user.id}")
44
  try:
45
  user = await bot.get_chat_member(AUTH_CHANNEL, query.from_user.id)
46
+ logger.info(f"User {query.from_user.id} membership status: {user.status}")
47
+
 
 
 
 
 
 
48
  if user.status != enums.ChatMemberStatus.BANNED:
49
+ logger.info(f"User {query.from_user.id} is valid subscriber")
50
  return True
51
+ logger.warning(f"User {query.from_user.id} is banned in auth channel")
52
+ except UserNotParticipant:
53
+ logger.warning(f"User {query.from_user.id} not in auth channel")
54
+ except Exception as e:
55
+ logger.error(f"Subscription check error for {query.from_user.id}: {str(e)}")
56
  return False
57
 
58
  async def get_poster(query, bulk=False, id=False, file=None):
59
+ """Fetch movie details from IMDb with comprehensive logging"""
60
+ logger.info(f"Starting IMDb lookup for: {query}")
61
+ imdb = Cinemagoer()
62
+
63
+ try:
64
+ if not id:
65
+ logger.debug("Processing title-based search")
66
+ query = (query.strip()).lower()
67
+ title = query
68
+ year = re.findall(r'[1-2]\d{3}$', query, re.IGNORECASE)
69
+
 
70
  if year:
71
+ logger.debug(f"Year found in query: {year}")
72
+ year = list_to_str(year[:1])
73
+ title = (query.replace(year, "")).strip()
74
+ elif file is not None:
75
+ logger.debug("Extracting year from filename")
76
+ year = re.findall(r'[1-2]\d{3}', file, re.IGNORECASE)
77
+ if year:
78
+ year = list_to_str(year[:1])
79
+ else:
80
+ year = None
81
+ logger.debug("No year information found")
82
+
83
+ logger.info(f"Searching IMDb for: {title} ({year if year else 'no year'})")
84
  movieid = imdb.search_movie(title.lower(), results=10)
85
+
86
+ if not movieid:
87
+ logger.warning("No IMDb results found")
88
+ return None
89
+
90
+ logger.debug(f"Found {len(movieid)} potential matches")
91
+
92
+ if year:
93
+ logger.debug("Filtering results by year")
94
+ filtered = list(filter(lambda k: str(k.get('year')) == str(year), movieid))
95
+ if not filtered:
96
+ logger.warning("No year matches, using original results")
97
+ filtered = movieid
98
+ else:
99
  filtered = movieid
100
+
101
+ logger.debug("Filtering by media type")
102
+ movieid = list(filter(lambda k: k.get('kind') in ['movie', 'tv series'], filtered))
103
+
104
+ if not movieid:
105
+ logger.warning("No valid media types found, using raw results")
106
+ movieid = filtered
107
+
108
+ if bulk:
109
+ logger.info("Returning bulk results")
110
+ return movieid
111
+
112
+ movieid = movieid[0].movieID
113
+ logger.info(f"Selected IMDb ID: {movieid}")
114
  else:
115
+ logger.info(f"Using provided IMDb ID: {query}")
116
+ movieid = query
117
+
118
+ logger.debug("Fetching detailed movie information")
119
+ movie = imdb.get_movie(movieid)
120
+
121
+ logger.debug("Processing movie metadata")
122
+ date = movie.get("original air date") or movie.get("year") or "N/A"
123
+ plot = ""
124
+
125
+ if not LONG_IMDB_DESCRIPTION:
126
+ plot = movie.get('plot')
127
+ if plot and len(plot) > 0:
128
+ plot = plot[0]
129
+ logger.debug("Using short plot description")
130
+ else:
131
+ plot = movie.get('plot outline')
132
+ logger.debug("Using long plot outline")
133
+
134
+ if plot and len(plot) > 800:
135
+ logger.debug("Trimming plot description")
136
+ plot = plot[0:800] + "..."
137
+
138
+ logger.info("Successfully processed IMDb data")
139
+ return {
140
+ 'title': movie.get('title'),
141
+ 'votes': movie.get('votes'),
142
+ "aka": list_to_str(movie.get("akas")),
143
+ "seasons": movie.get("number of seasons"),
144
+ "box_office": movie.get('box office'),
145
+ 'localized_title': movie.get('localized title'),
146
+ 'kind': movie.get("kind"),
147
+ "imdb_id": f"tt{movie.get('imdbID')}",
148
+ "cast": list_to_str(movie.get("cast")),
149
+ "runtime": list_to_str(movie.get("runtimes")),
150
+ "countries": list_to_str(movie.get("countries")),
151
+ "certificates": list_to_str(movie.get("certificates")),
152
+ "languages": list_to_str(movie.get("languages")),
153
+ "director": list_to_str(movie.get("director")),
154
+ "writer":list_to_str(movie.get("writer")),
155
+ "producer":list_to_str(movie.get("producer")),
156
+ "composer":list_to_str(movie.get("composer")) ,
157
+ "cinematographer":list_to_str(movie.get("cinematographer")),
158
+ "music_team": list_to_str(movie.get("music department")),
159
+ "distributors": list_to_str(movie.get("distributors")),
160
+ 'release_date': date,
161
+ 'year': movie.get('year'),
162
+ 'genres': list_to_str(movie.get("genres")),
163
+ 'poster': movie.get('full-size cover url'),
164
+ 'plot': plot,
165
+ 'rating': str(movie.get("rating")),
166
+ 'url':f'https://www.imdb.com/title/tt{movieid}'
167
+ }
168
+ except Exception as e:
169
+ logger.error(f"IMDb processing failed: {str(e)}")
170
+ return None
 
 
 
 
 
 
 
 
 
 
171
 
172
  def list_to_str(k):
173
+ """Convert list to formatted string with logging"""
174
+ logger.debug("Converting list to string")
175
  if not k:
176
+ logger.debug("Empty list received")
177
  return "N/A"
178
  elif len(k) == 1:
179
+ logger.debug("Single-item list converted")
180
  return str(k[0])
181
  elif MAX_LIST_ELM:
182
+ logger.debug(f"Truncating list to {MAX_LIST_ELM} elements")
183
  k = k[:int(MAX_LIST_ELM)]
184
+ return ' '.join(f'{elem}, ' for elem in k)
 
 
185
  else:
186
+ logger.debug("Converting full list")
187
+ return ' '.join(f'{elem}, ' for elem in k)
 
188
 
189
  __repo__ = "https://github.com/MrMKN/PROFESSOR-BOT"
 
190
  __version__ = "PROFESSOR-BOT ᴠ4.5.0"
 
191
  __license__ = "GNU GENERAL PUBLIC LICENSE V2"
 
192
  __copyright__ = "Copyright (C) 2023-present MrMKN <https://github.com/MrMKN>"
 
193
 
194
  async def search_gagala(text):
195
+ """Perform Google search with logging"""
196
+ logger.info(f"Initializing search for: {text}")
197
  usr_agent = {
198
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
199
+ 'Chrome/61.0.3163.100 Safari/537.36'
200
+ }
201
+ try:
202
+ text = text.replace(" ", '+')
203
+ url = f'https://www.google.com/search?q={text}'
204
+ logger.debug(f"Requesting URL: {url}")
205
+
206
+ response = requests.get(url, headers=usr_agent)
207
+ response.raise_for_status()
208
+ logger.info("Google search successful")
209
+
210
+ soup = BeautifulSoup(response.text, 'html.parser')
211
+ titles = soup.find_all('h3')
212
+ logger.debug(f"Found {len(titles)} search results")
213
+
214
+ return [title.getText() for title in titles]
215
+ except Exception as e:
216
+ logger.error(f"Search failed: {str(e)}")
217
+ return []
218
 
219
  async def get_settings(group_id):
220
+ """Retrieve group settings with caching and logging"""
221
+ logger.debug(f"Fetching settings for group {group_id}")
222
  settings = temp.SETTINGS.get(group_id)
223
+
224
  if not settings:
225
+ logger.info("Cache miss - loading from database")
226
  settings = await db.get_settings(group_id)
227
  temp.SETTINGS[group_id] = settings
 
228
  else:
229
+ logger.debug("Using cached settings")
230
+
231
  return settings
232
 
233
  async def save_group_settings(group_id, key, value):
234
+ """Update group settings with transaction logging"""
235
+ logger.info(f"Updating setting {key} for group {group_id}")
236
  current = await get_settings(group_id)
237
  current[key] = value
238
  temp.SETTINGS[group_id] = current
239
+
240
+ try:
241
+ await db.update_settings(group_id, current)
242
+ logger.debug("Database update successful")
243
+ except Exception as e:
244
+ logger.error(f"Settings update failed: {str(e)}")
245
+ raise
246
 
247
  def get_size(size):
248
+ """Convert bytes to human-readable format with logging"""
249
+ logger.debug(f"Converting size: {size} bytes")
250
  units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"]
251
  size = float(size)
252
  i = 0
253
+
254
  while size >= 1024.0 and i < len(units):
255
  i += 1
256
  size /= 1024.0
257
+
258
  result = "%.2f %s" % (size, units[i])
259
  logger.debug(f"Converted size: {result}")
260
  return result
261
 
262
  def get_file_id(msg: Message):
263
+ """Extract file ID from message with media type detection"""
264
+ logger.debug("Extracting file ID from message")
265
+ if not msg.media:
266
+ logger.warning("No media found in message")
267
  return None
268
+
269
  for message_type in ("photo", "animation", "audio", "document", "video", "video_note", "voice", "sticker"):
270
  obj = getattr(msg, message_type)
271
  if obj:
272
+ logger.info(f"Extracted media type: {message_type}")
273
  setattr(obj, "message_type", message_type)
 
274
  return obj
275
 
276
  def extract_user(message: Message) -> Union[int, str]:
277
+ """Extract user ID and name from message with logging"""
278
+ logger.debug("Extracting user information from message")
279
  user_id = None
280
  user_first_name = None
281
+
282
  if message.reply_to_message:
283
  user_id = message.reply_to_message.from_user.id
284
  user_first_name = message.reply_to_message.from_user.first_name
285
+ logger.info(f"User extracted from reply: {user_id} - {user_first_name}")
286
  elif len(message.command) > 1:
287
  if (len(message.entities) > 1 and message.entities[1].type == enums.MessageEntityType.TEXT_MENTION):
288
  required_entity = message.entities[1]
289
  user_id = required_entity.user.id
290
  user_first_name = required_entity.user.first_name
291
+ logger.info(f"User extracted from mention: {user_id} - {user_first_name}")
292
  else:
293
  user_id = message.command[1]
294
  user_first_name = user_id
 
295
  try:
296
  user_id = int(user_id)
297
+ logger.info(f"User ID converted to int: {user_id}")
298
+ except ValueError:
299
+ logger.warning("Failed to convert user ID to int")
 
300
  else:
301
  user_id = message.from_user.id
302
  user_first_name = message.from_user.first_name
303
+ logger.info(f"User extracted from message sender: {user_id} - {user_first_name}")
304
+
305
  return (user_id, user_first_name)
306
 
307
  def split_quotes(text: str) -> List:
308
+ """Split quoted text into key and value with logging"""
309
+ logger.debug("Splitting quotes from text")
310
  if not any(text.startswith(char) for char in START_CHAR):
311
+ logger.debug("No starting quote found, splitting by space")
312
+ return text.split(None, 1)
313
+
314
  counter = 1 # ignore first char -> is some kind of quote
315
  while counter < len(text):
316
  if text[counter] == "\\":
 
319
  break
320
  counter += 1
321
  else:
322
+ logger.debug("No ending quote found, returning split")
323
+ return text.split(None, 1)
 
324
 
 
325
  key = remove_escapes(text[1:counter].strip())
 
326
  rest = text[counter + 1:].strip()
327
  if not key:
328
  key = text[0] + text[0]
329
+
330
+ logger.debug(f"Split result: key='{key}', rest='{rest}'")
331
+ return list(filter(None, [key, rest]))
 
332
 
333
  def parser(text, keyword, cb_data):
334
+ """Parse buttons and alerts from text with logging"""
335
+ logger.debug("Parsing buttons and alerts from text")
336
  if "buttonalert" in text:
337
  text = (text.replace("\n", "\\n").replace("\t", "\\t"))
338
+
339
  buttons = []
340
  note_data = ""
341
  prev = 0
342
  i = 0
343
  alerts = []
344
+
345
  for match in BTN_URL_REGEX.finditer(text):
346
  n_escapes = 0
347
  to_check = match.start(1) - 1
348
  while to_check > 0 and text[to_check] == "\\":
349
  n_escapes += 1
350
  to_check -= 1
351
+
352
  if n_escapes % 2 == 0:
353
  note_data += text[prev:match.start(1)]
354
  prev = match.end(1)
355
  if match.group(3) == "buttonalert":
 
356
  if bool(match.group(5)) and buttons:
357
  buttons[-1].append(InlineKeyboardButton(match.group(2), callback_data=f"{cb_data}:{i}:{keyword}"))
 
358
  else:
359
  buttons.append([InlineKeyboardButton(match.group(2), callback_data=f"{cb_data}:{i}:{keyword}")])
 
360
  i += 1
361
  alerts.append(match.group(4))
362
+ logger.debug(f"Button alert added: {match.group(2)}")
363
  elif bool(match.group(5)) and buttons:
364
  buttons[-1].append(InlineKeyboardButton(match.group(2), url=match.group(4).replace(" ", "")))
365
+ logger.debug(f"Button URL added: {match.group(2)}")
366
  else:
367
  buttons.append([InlineKeyboardButton(match.group(2), url=match.group(4).replace(" ", ""))])
368
+ logger.debug(f"Button added: {match.group(2)}")
369
  else:
370
  note_data += text[prev:to_check]
371
  prev = match.start(1) - 1
372
+
373
  else:
374
  note_data += text[prev:]
375
+
376
  try:
377
+ logger.info("Parsing completed successfully")
378
+ return note_data, buttons, alerts
 
379
  except Exception as e:
380
+ logger.error(f"Parsing error: {str(e)}")
381
  return note_data, buttons, None
382
 
383
  def remove_escapes(text: str) -> str:
384
+ """Remove escape characters from text with logging"""
385
+ logger.debug("Removing escape characters from text")
386
  res = ""
387
  is_escaped = False
388
+
389
  for counter in range(len(text)):
390
  if is_escaped:
391
  res += text[counter]
 
394
  is_escaped = True
395
  else:
396
  res += text[counter]
397
+
398
+ logger.debug("Escape characters removed successfully")
399
  return res
400
+
401
  def humanbytes(size):
402
+ """Convert bytes to human-readable format with logging"""
403
  logger.debug(f"Converting size to human-readable format: {size}")
404
  if not size:
405
+ logger.warning("No size provided for conversion")
406
  return ""
407
+
408
  power = 2**10
409
  n = 0
410
  Dic_powerN = {0: ' ', 1: 'Ki', 2: 'Mi', 3: 'Gi', 4: 'Ti'}
411
+
412
  while size > power:
413
  size /= power
414
  n += 1
415
+
416
  result = str(round(size, 2)) + " " + Dic_powerN[n] + 'B'
417
+ logger.debug(f"Converted size: {result}")
418
  return result
419
+
420
+ def get_time(seconds):
421
+ """Convert seconds to human-readable time format with logging"""
422
+ logger.debug(f"Converting seconds to time format: {seconds}")
423
+ periods = [('ᴅ', 86400), ('ʜ', 3600), ('ᴍ', 60), ('ꜱ', 1)]
424
+ result = ''
425
 
426
+ for period_name, period_seconds in periods:
427
+ if seconds >= period_seconds:
428
+ period_value, seconds = divmod(seconds, period_seconds)
429
+ result += f'{int(period_value)}{period_name}'
430
+
431
+ logger.debug(f"Converted time: {result}")
432
+ return result
433
+
434
  async def get_shortlink(link):
435
+ """Get shortened link using API with logging"""
436
+ logger.info(f"Requesting short link for: {link}")
437
  url = f'{SHORT_URL}/api'
438
  params = {'api': SHORT_API, 'url': link}
439
+
440
  try:
441
  async with aiohttp.ClientSession() as session:
442
  async with session.get(url, params=params, raise_for_status=True, ssl=False) as response:
443
  data = await response.json()
 
444
  if data["status"] == "success":
445
+ logger.info("Short link retrieved successfully")
446
  return data['shortenedUrl']
447
  else:
448
+ logger.error(f"Error from short link API: {data['message']}")
449
  return link
450
  except Exception as e:
451
+ logger.error(f"Short link request failed: {str(e)}")
452
  return link
453
 
454
  def extract_time(time_val):
455
+ """Extract time from string with logging"""
456
+ logger.debug(f"Extracting time from value: {time_val}")
457
  if any(time_val.endswith(unit) for unit in ("s", "m", "h", "d")):
458
  unit = time_val[-1]
459
  time_num = time_val[:-1] # type: str
460
+
461
  if not time_num.isdigit():
462
+ logger.warning("Invalid time number provided")
463
  return None
464
 
465
  if unit == "s":
466
  bantime = datetime.now() + timedelta(seconds=int(time_num))
 
467
  elif unit == "m":
468
  bantime = datetime.now() + timedelta(minutes=int(time_num))
 
469
  elif unit == "h":
470
  bantime = datetime.now() + timedelta(hours=int(time_num))
 
471
  elif unit == "d":
472
  bantime = datetime.now() + timedelta(days=int(time_num))
 
473
  else:
474
+ logger.error("Unknown time unit provided")
475
  return None
476
+
477
+ logger.info(f"Extracted ban time: {bantime}")
478
  return bantime
479
  else:
480
+ logger.warning("No valid time unit found")
481
  return None
482
 
483
  async def admin_check(message: Message) -> bool:
484
+ """Check if user is an admin with logging"""
485
+ logger.debug("Checking admin status for user")
486
  if not message.from_user:
487
+ logger.warning("Message has no user information")
488
  return False
489
+
490
  if message.chat.type not in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
491
+ logger.warning("Message is not from a group or supergroup")
492
  return False
493
+
494
  if message.from_user.id in [777000, 1087968824]:
495
+ logger.info("User is a bot admin")
496
  return True
497
+
498
  client = message._client
499
  chat_id = message.chat.id
500
  user_id = message.from_user.id
501
+
502
+ try:
503
+ check_status = await client.get_chat_member(chat_id=chat_id, user_id=user_id)
504
+ admin_strings = [enums.ChatMemberStatus.OWNER, enums.ChatMemberStatus.ADMINISTRATOR]
505
+
506
+ if check_status.status not in admin_strings:
507
+ logger.info(f"User {user_id} is not an admin")
508
+ return False
509
+ else:
510
+ logger.info(f"User {user_id} is an admin")
511
+ return True
512
+ except Exception as e:
513
+ logger.error(f"Admin check failed for user {user_id}: {str(e)}")
514
  return False
 
 
 
515
 
516
  async def admin_filter(filt, client, message):
517
+ """Filter for admin messages with logging"""
518
+ logger.debug("Applying admin filter")
519
+ is_admin = await admin_check(message)
520
+ logger.info(f"Admin filter result: {is_admin}")
521
+ return is_admin