teamx-cloner commited on
Commit
f6f8afe
·
1 Parent(s): 7f946fb

Update translate.py

Browse files
Files changed (1) hide show
  1. plugins/translate.py +492 -13
plugins/translate.py CHANGED
@@ -1,21 +1,500 @@
1
- from deep_translator import GoogleTranslator
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  from . import *
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
- @ultroid_cmd(pattern="tr (.*)")
5
- async def translate_text(event):
6
- args = event.pattern_match.group(1).strip().split(" | ")
 
 
 
 
 
 
 
7
 
8
- if len(args) != 2:
9
- await eor(event, "`Usage: .translate <text> | <target_language>`")
10
- return
 
 
 
 
11
 
12
- text, target_language = args
13
- xx = await eor(event, "`Translating...`")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  try:
16
- translated = GoogleTranslator(source='auto', target=target_language).translate(text)
17
- await xx.edit(f"**Translated:**\n{translated}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  except Exception as e:
20
- await xx.edit(f"**Error:** `{e}`")
21
-
 
1
+ # Ultroid ~ UserBot
2
+ # Copyright (C) 2023 Ultroid
3
+ #
4
+ # This file is a part of < https://github.com/ufoptg/UltroidBackup/ >
5
+ # PLease read the GNU Affero General Public License in
6
+ # <https://www.github.com/ufoptg/UltroidBackup/blob/main/LICENSE/>.
7
+
8
+ from . import get_help
9
+
10
+ __doc__ = get_help("help_tools")
11
+
12
+ import asyncio
13
+ import glob
14
+ import io
15
+ import os
16
+ import re
17
+
18
+ import pyshorteners
19
+
20
+ try:
21
+ import cv2
22
+ except ImportError:
23
+ cv2 = None
24
+
25
+ try:
26
+ from playwright.async_api import async_playwright
27
+ except ImportError:
28
+ async_playwright = None
29
+ try:
30
+ from htmlwebshot import WebShot
31
+ except ImportError:
32
+ WebShot = None
33
+
34
+ from bs4 import BeautifulSoup
35
+ from requests import get
36
+ from telethon.errors.rpcerrorlist import MessageTooLongError, YouBlockedUserError
37
+ from telethon.tl.functions.contacts import UnblockRequest as unblock
38
+ from telethon.tl import types
39
+ from telethon.tl.types import (
40
+ ChannelParticipantAdmin,
41
+ ChannelParticipantsBots,
42
+ DocumentAttributeVideo,
43
+ )
44
+
45
+ from pyUltroid.fns.tools import metadata, translate
46
+
47
  from . import *
48
+ from . import HNDLR, LOGS, ULTConfig, bash, con, eor, get_string
49
+ from . import humanbytes as hb
50
+ from . import inline_mention, mediainfo, ultroid_cmd
51
+
52
+
53
+ def sanga_seperator(sanga_list):
54
+ string = "".join(info[info.find("\n") + 1 :] for info in sanga_list)
55
+ string = re.sub(r"^$\n", "", string, flags=re.MULTILINE)
56
+ name, username = string.split("Usernames**")
57
+ name = name.split("Names")[1]
58
+ return name, username
59
+
60
+
61
+ def mentionuser(name, userid):
62
+ return f"[{name}](tg://user?id={userid})"
63
+
64
+
65
+ @ultroid_cmd(pattern="tl( (.*)|$)", manager=True)
66
+ async def _(event):
67
+ input_ = event.pattern_match.group(1).strip().split(maxsplit=1)
68
+ txt = input_[1] if len(input_) > 1 else None
69
+ if input_:
70
+ input_ = input_[0]
71
+ if txt:
72
+ text = txt
73
+ elif event.is_reply:
74
+ previous_message = await event.get_reply_message()
75
+ text = previous_message.message
76
+ else:
77
+ return await eor(
78
+ event, f"`{HNDLR}tr LanguageCode` as reply to a message", time=5
79
+ )
80
+ lan = input_ or "en"
81
+ try:
82
+ tt = await translate(text, lang_tgt=lan)
83
+ output_str = f"**Translate**\n\n**Source**:\n`{text}`\n\n**Translation** (`{lan}`):\n`{tt}`"
84
+ await event.eor(output_str)
85
+ except Exception as exc:
86
+ LOGS.exception(exc)
87
+ await event.eor(str(exc), time=5)
88
+
89
+
90
+ @ultroid_cmd(pattern="tr( (.*)|$)", manager=True)
91
+ async def _(event):
92
+ input_ = event.pattern_match.group(1).strip().split(maxsplit=1)
93
+ txt = input_[1] if len(input_) > 1 else None
94
+ if input_:
95
+ input_ = input_[0]
96
+ if txt:
97
+ text = txt
98
+ elif event.is_reply:
99
+ previous_message = await event.get_reply_message()
100
+
101
+ if previous_message.media and hasattr(previous_message.media, 'poll'):
102
+ poll = previous_message.media.poll
103
+ question_text = poll.question.text
104
+ answers_text = "\n".join([f"- {answer.text.text}" for answer in poll.answers])
105
+ text = f"Poll Question:\n{question_text}\n\nPoll Answers:\n{answers_text}"
106
+ else:
107
+ text = previous_message.message
108
+ else:
109
+ return await eor(
110
+ event, f"`{HNDLR}tl LanguageCode` as reply to a message", time=5
111
+ )
112
+
113
+ lan = input_ or "en"
114
+ try:
115
+ tt = await previous_message.translate(lan)
116
+ output_str = f"**Translate**\n\n**Source**:\n`{text}`\n\n**Translation** (`{lan}`):\n`{tt}`"
117
+ await event.eor(output_str)
118
+ except Exception as exc:
119
+ LOGS.exception(exc)
120
+ await event.eor(str(exc), time=5)
121
+
122
+
123
+ @ultroid_cmd(
124
+ pattern="idn( (.*)|$)",
125
+ manager=True,
126
+ )
127
+ async def _(event):
128
+ ult = event
129
+ if match := event.pattern_match.group(1).strip():
130
+ try:
131
+ ids = await event.client.parse_id(match)
132
+ except Exception as er:
133
+ return await event.eor(str(er))
134
+ return await event.eor(
135
+ f"**Chat ID:** `{event.chat_id}`\n**User ID:** `{ids}`"
136
+ )
137
+ data = f"**Current Chat ID:** `{event.chat_id}`"
138
+ if event.reply_to_msg_id:
139
+ event = await event.get_reply_message()
140
+ data += f"\n**From User ID:** `{event.sender_id}`"
141
+ if event.media:
142
+ bot_api_file_id = event.file.id
143
+ data += f"\n**Bot API File ID:** `{bot_api_file_id}`"
144
+ data += f"\n**Msg ID:** `{event.id}`"
145
+ await ult.eor(data)
146
+
147
+
148
+ @ultroid_cmd(pattern="botsub( (.*)|$)", groups_only=True, manager=True)
149
+ async def _(ult):
150
+ mentions = "• **Bots in this Chat**: \n"
151
+ if input_str := ult.pattern_match.group(1).strip():
152
+ mentions = f"• **Bots in **{input_str}: \n"
153
+ try:
154
+ chat = await ult.client.parse_id(input_str)
155
+ except Exception as e:
156
+ return await ult.eor(str(e))
157
+ else:
158
+ chat = ult.chat_id
159
+ try:
160
+ async for x in ult.client.iter_participants(
161
+ chat,
162
+ filter=ChannelParticipantsBots,
163
+ ):
164
+ if isinstance(x.participant, ChannelParticipantAdmin):
165
+ mentions += f"\n⚜️ {inline_mention(x)} `{x.id}`"
166
+ else:
167
+ mentions += f"\n• {inline_mention(x)} `{x.id}`"
168
+ except Exception as e:
169
+ mentions += f" {str(e)}" + "\n"
170
+ await ult.eor(mentions)
171
+
172
+
173
+ @ultroid_cmd(
174
+ pattern="hil( (.*)|$)",
175
+ )
176
+ async def _(ult):
177
+ input_ = ult.pattern_match.group(1).strip()
178
+ if not input_:
179
+ return await ult.eor("`Input some link`", time=5)
180
+ text = None
181
+ if len(input_.split()) > 1:
182
+ spli_ = input_.split()
183
+ input_ = spli_[0]
184
+ text = spli_[1]
185
+ if not text:
186
+ text = "ㅤㅤㅤㅤㅤㅤㅤ"
187
+ await ult.eor(f"[{text}]({input_})", link_preview=False)
188
+
189
+
190
+ @ultroid_cmd(
191
+ pattern="circles$",
192
+ )
193
+ async def _(e):
194
+ reply = await e.get_reply_message()
195
+ if not (reply and reply.media):
196
+ return await e.eor("`Reply to a gif or audio file only.`")
197
+ if "audio" in mediainfo(reply.media):
198
+ msg = await e.eor("`Downloading...`")
199
+ try:
200
+ bbbb = await reply.download_media(thumb=-1)
201
+ except TypeError:
202
+ bbbb = ULTConfig.thumb
203
+ im = cv2.imread(bbbb)
204
+ dsize = (512, 512)
205
+ output = cv2.resize(im, dsize, interpolation=cv2.INTER_AREA)
206
+ cv2.imwrite("img.jpg", output)
207
+ thumb = "img.jpg"
208
+ audio, _ = await e.client.fast_downloader(reply.document)
209
+ await msg.edit("`Creating video note...`")
210
+ await bash(
211
+ f'ffmpeg -i "{thumb}" -i "{audio.name}" -preset ultrafast -c:a libmp3lame -ab 64 circle.mp4 -y'
212
+ )
213
+ await msg.edit("`Uploading...`")
214
+ data = await metadata("circle.mp4")
215
+ file, _ = await e.client.fast_uploader("circle.mp4", to_delete=True)
216
+ await e.client.send_file(
217
+ e.chat_id,
218
+ file,
219
+ thumb=thumb,
220
+ reply_to=reply,
221
+ attributes=[
222
+ DocumentAttributeVideo(
223
+ duration=min(data["duration"], 60),
224
+ w=512,
225
+ h=512,
226
+ round_message=True,
227
+ )
228
+ ],
229
+ )
230
+
231
+ await msg.delete()
232
+ [os.remove(k) for k in [audio.name, thumb]]
233
+ elif mediainfo(reply.media) == "gif" or mediainfo(reply.media).startswith("video"):
234
+ msg = await e.eor("**Creating video note**")
235
+ file = await reply.download_media("resources/downloads/")
236
+ if file.endswith(".webm"):
237
+ nfile = await con.ffmpeg_convert(file, "file.mp4")
238
+ os.remove(file)
239
+ file = nfile
240
+ if file:
241
+ await e.client.send_file(
242
+ e.chat_id,
243
+ file,
244
+ video_note=True,
245
+ thumb=ULTConfig.thumb,
246
+ reply_to=reply,
247
+ )
248
+ os.remove(file)
249
+ await msg.delete()
250
+
251
+ else:
252
+ await e.eor("`Reply to a gif or audio file only.`")
253
+
254
+
255
+ FilesEMOJI = {
256
+ "py": "🐍",
257
+ "json": "🔮",
258
+ ("sh", "bat"): "⌨️",
259
+ (".mkv", ".mp4", ".avi", ".gif", "webm"): "🎥",
260
+ (".mp3", ".ogg", ".m4a", ".opus"): "🔊",
261
+ (".jpg", ".jpeg", ".png", ".webp", ".ico"): "🖼",
262
+ (".txt", ".text", ".log"): "📄",
263
+ (".apk", ".xapk"): "📲",
264
+ (".pdf", ".epub"): "📗",
265
+ (".zip", ".rar"): "🗜",
266
+ (".exe", ".iso"): "⚙",
267
+ }
268
+
269
+
270
+ @ultroid_cmd(
271
+ pattern="Ls( (.*)|$)",
272
+ )
273
+ async def _(e):
274
+ files = e.pattern_match.group(1).strip()
275
+ if not files:
276
+ files = "*"
277
+ elif files.endswith("/"):
278
+ files += "*"
279
+ elif "*" not in files:
280
+ files += "/*"
281
+ files = glob.glob(files)
282
+ if not files:
283
+ return await e.eor("`Directory Empty or Incorrect.`", time=5)
284
+ allfiles = []
285
+ folders = []
286
+ for file in sorted(files):
287
+ if os.path.isdir(file):
288
+ folders.append(f"📂 {file}")
289
+ else:
290
+ for ext in FilesEMOJI.keys():
291
+ if file.endswith(ext):
292
+ allfiles.append(f"{FilesEMOJI[ext]} {file}")
293
+ break
294
+ else:
295
+ if "." in str(file)[1:]:
296
+ allfiles.append(f"🏷 {file}")
297
+ else:
298
+ allfiles.append(f"📒 {file}")
299
+ omk = [*sorted(folders), *sorted(allfiles)]
300
+ text = ""
301
+ fls, fos = 0, 0
302
+ flc, foc = 0, 0
303
+ for i in omk:
304
+ try:
305
+ emoji = i.split()[0]
306
+ name = i.split(maxsplit=1)[1]
307
+ nam = name.split("/")[-1]
308
+ if os.path.isdir(name):
309
+ size = 0
310
+ for path, dirs, files in os.walk(name):
311
+ for f in files:
312
+ fp = os.path.join(path, f)
313
+ size += os.path.getsize(fp)
314
+ if hb(size):
315
+ text += f"{emoji} `{nam}` `{hb(size)}" + "`\n"
316
+ fos += size
317
+ else:
318
+ text += f"{emoji} `{nam}`" + "\n"
319
+ foc += 1
320
+ else:
321
+ if hb(int(os.path.getsize(name))):
322
+ text += (
323
+ f"{emoji} `{nam}` `{hb(int(os.path.getsize(name)))}" + "`\n"
324
+ )
325
+ fls += int(os.path.getsize(name))
326
+ else:
327
+ text += f"{emoji} `{nam}`" + "\n"
328
+ flc += 1
329
+ except BaseException:
330
+ pass
331
+ tfos, tfls, ttol = hb(fos), hb(fls), hb(fos + fls)
332
+ if not hb(fos):
333
+ tfos = "0 B"
334
+ if not hb(fls):
335
+ tfls = "0 B"
336
+ if not hb(fos + fls):
337
+ ttol = "0 B"
338
+ text += f"\n\n`Folders` : `{foc}` : `{tfos}`\n`Files` : `{flc}` : `{tfls}`\n`Total` : `{flc+foc}` : `{ttol}`"
339
+ try:
340
+ if (flc + foc) > 100:
341
+ text = text.replace("`", "")
342
+ await e.eor(text)
343
+ except MessageTooLongError:
344
+ with io.BytesIO(str.encode(text)) as out_file:
345
+ out_file.name = "output.txt"
346
+ await e.reply(f"`{e.text}`", file=out_file, thumb=ULTConfig.thumb)
347
+ await e.delete()
348
+
349
 
350
+ @ultroid_cmd(
351
+ pattern="sgm(|u)(?:\\s|$)([\\s\\S]*)",
352
+ fullsudo=True,
353
+ )
354
+ async def sangmata(event):
355
+ "To get name/username history."
356
+ cmd = event.pattern_match.group(1)
357
+ user = event.pattern_match.group(2)
358
+ reply = await event.get_reply_message()
359
+ loading = await event.eor("`Processing...`")
360
 
361
+ if not user and reply:
362
+ user = str(reply.sender_id)
363
+ if not user:
364
+ return await loading.eor(
365
+ "`Reply to a user's message or provide their ID/username to fetch name/username history.`",
366
+ time=10,
367
+ )
368
 
369
+ try:
370
+ if user.isdigit():
371
+ userinfo = await ultroid_bot.get_entity(int(user))
372
+ else:
373
+ userinfo = await ultroid_bot.get_entity(user)
374
+ except ValueError:
375
+ userinfo = None
376
+
377
+ if not isinstance(userinfo, types.User):
378
+ return await loading.eor("`Unable to fetch user details.`", time=10)
379
+
380
+ async with event.client.conversation("@SangMata_beta_bot") as conv:
381
+ try:
382
+ await conv.send_message(f"{userinfo.id}")
383
+ except YouBlockedUserError:
384
+ await catub(unblock("SangMata_beta_bot"))
385
+ await conv.send_message(f"{userinfo.id}")
386
+
387
+ responses = []
388
+ while True:
389
+ try:
390
+ response = await conv.get_response(timeout=2)
391
+ except asyncio.TimeoutError:
392
+ break
393
+ responses.append(response.text)
394
+ await event.client.send_read_acknowledge(conv.chat_id)
395
+
396
+ if not responses:
397
+ return await loading.eor("`No response from the bot. Please try again later.`", time=10)
398
 
399
+ if any("No data available" in r for r in responses):
400
+ return await loading.eor(
401
+ f"**No data available ({userinfo.id})**\n\n**Tips:**\n1. Add this bot to your groups as admin to increase detection.\n"
402
+ "2. Use search by username. Simply copy a username and send `allhistory @username`.\n"
403
+ "New data will be added if not available.",
404
+ time=15,
405
+ )
406
+
407
+ if any("quota" in r.lower() for r in responses):
408
+ return await loading.eor(
409
+ "**Quota Exceeded**\n\n"
410
+ "Sorry, you have used up your quota for today. Quota refreshes daily at 00:00 UTC.\n\n"
411
+ "**To increase your daily quota:**\n"
412
+ "- Open private chat with @SangMata_BOT or @SangMata_beta_bot.\n"
413
+ '- Send "donate <amount>" to the bot (e.g., "donate 500").\n\n'
414
+ "Need help? Join the support group at @sang_inc.",
415
+ time=20,
416
+ )
417
  try:
418
+ names, usernames = sanga_seperator(responses)
419
+ except ValueError as er:
420
+ return await loading.eor(f"`Error processing data: {er}`", time=10)
421
+
422
+ check = (usernames, "Username") if cmd == "u" else (names, "Name")
423
+ user_name = (
424
+ f"{userinfo.first_name} {userinfo.last_name}"
425
+ if userinfo.last_name
426
+ else userinfo.first_name
427
+ )
428
+ output = (
429
+ f"**➜ User Info:** {mentionuser(user_name, userinfo.id)}\n"
430
+ f"**➜ {check[1]} History:**\n{check[0]}"
431
+ )
432
+ await loading.eor(output)
433
+
434
+ @ultroid_cmd(pattern="webst( (.*)|$)")
435
+ async def webss(event):
436
+ xx = await event.eor(get_string("com_1"))
437
+ xurl = event.pattern_match.group(1).strip()
438
+ if xurl:
439
+ x = get(f"https://mini.s-shot.ru/1920x1080/JpE6/1024/7100/?{xurl}")
440
+ y = "shot.jpg"
441
+ with open(y, "wb") as f:
442
+ f.write(x.content)
443
+ if (await ultroid_bot.get_me()).premium:
444
+ await ultroid_bot.send_file(
445
+ event.chat_id,
446
+ y,
447
+ caption=f"[📷](emoji/5258205968025525531)**WebShot Generated**\n[🔗](emoji/5983262173474853675)**URL** : {xurl}",
448
+ force_document=False,
449
+ )
450
+ else:
451
+ await ultroid_bot.send_file(
452
+ event.chat_id,
453
+ y,
454
+ caption=f"📷**WebShot Generated**\n🔗**URL** : {xurl}",
455
+ force_document=False,
456
+ )
457
+ os.remove(y)
458
+ else:
459
+ await eod(xx, f"Please provide me a URL...", time=5)
460
+ await xx.delete()
461
+
462
+
463
+ @ultroid_cmd(pattern="shrturl ?(.*)")
464
+ async def short_url(event):
465
+ input_url = event.pattern_match.group(1)
466
+
467
+ if not input_url:
468
+ reply_msg = await event.get_reply_message()
469
+ if reply_msg:
470
+ input_url = reply_msg.text
471
+ else:
472
+ return await eor(event, "`Please provide a URL to shorten.`")
473
+
474
+ try:
475
+ s = pyshorteners.Shortener()
476
+ if input_url.lower().startswith("https://tinyurl.com/"):
477
+ response = get(input_url)
478
+ soup = BeautifulSoup(response.text, "html.parser")
479
+ original_url = soup.find("a", {"target": "_blank"}).get("href")
480
+ output_message = (
481
+ f"**Expanded URL**\n"
482
+ f"**Given Link** ➠ **{input_url}**\n"
483
+ f"**Expanded Link** ➠ **{original_url}**"
484
+ )
485
+ else:
486
+ shortened_url = s.tinyurl.short(input_url)
487
+ output_message = (
488
+ f"**Shortened URL**\n"
489
+ f"**Given Link** ➠ **{input_url}**\n"
490
+ f"**Shortened Link** ➠ **{shortened_url}**"
491
+ )
492
+
493
+ if event.reply_to_msg_id:
494
+ await event.delete()
495
+ await event.reply(output_message)
496
+ else:
497
+ await eor(event, output_message)
498
 
499
  except Exception as e:
500
+ await eor(event, f"An error occurred: {e}")