functions.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. """
  2. MIT License
  3. Copyright (c) 2024 TheHamkerCat
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. """
  20. import asyncio
  21. from asyncio import gather
  22. from datetime import datetime, timedelta
  23. from io import BytesIO
  24. from math import atan2, cos, radians, sin, sqrt
  25. from os import execvp
  26. from random import randint
  27. from re import findall, search
  28. from re import sub as re_sub
  29. from sys import executable
  30. from typing import Dict
  31. import aiofiles
  32. import speedtest
  33. from PIL import Image, ImageDraw, ImageFilter, ImageFont
  34. from pyrogram import errors
  35. from pyrogram.enums import MessageEntityType
  36. from pyrogram.types import Message
  37. from wbb import aiohttpsession as aiosession
  38. from wbb.utils.dbfunctions import start_restart_stage
  39. from wbb.utils.http import get, post
  40. async def restart(m: Message):
  41. if m:
  42. await start_restart_stage(m.chat.id, m.id)
  43. execvp(executable, [executable, "-m", "wbb"])
  44. def generate_captcha():
  45. # Generate one letter
  46. def gen_letter():
  47. return chr(randint(65, 90))
  48. def rndColor():
  49. return (randint(64, 255), randint(64, 255), randint(64, 255))
  50. def rndColor2():
  51. return (randint(32, 127), randint(32, 127), randint(32, 127))
  52. wrong_answers = [
  53. "".join(gen_letter() for _ in range(4)) for _ in range(8)
  54. ]
  55. width, height = 320, 100
  56. correct_answer = ""
  57. font = ImageFont.truetype("assets/arial.ttf", 55)
  58. # White background
  59. image = Image.new("RGB", (width, height), (255, 255, 255))
  60. draw = ImageDraw.Draw(image)
  61. # Noise (draw random lines instead of painting every pixel)
  62. for _ in range(120):
  63. x1, y1 = randint(0, width), randint(0, height)
  64. x2, y2 = randint(0, width), randint(0, height)
  65. draw.line((x1, y1, x2, y2), fill=rndColor(), width=1)
  66. # Text
  67. for t in range(4):
  68. letter = gen_letter()
  69. correct_answer += letter
  70. draw.text((60 * t + 50, 15), letter, font=font, fill=rndColor2())
  71. image = image.filter(ImageFilter.BLUR)
  72. buf = BytesIO() # on memory
  73. image.save(buf, "JPEG")
  74. buf.name = "captcha.jpg"
  75. buf.seek(0)
  76. return [buf, correct_answer, wrong_answers]
  77. def test_speedtest():
  78. def speed_convert(size):
  79. power = 2**10
  80. zero = 0
  81. units = {0: "", 1: "Kb/s", 2: "Mb/s", 3: "Gb/s", 4: "Tb/s"}
  82. while size > power:
  83. size /= power
  84. zero += 1
  85. return f"{round(size, 2)} {units[zero]}"
  86. speed = speedtest.Speedtest()
  87. info = speed.get_best_server()
  88. download = speed.download()
  89. upload = speed.upload()
  90. return [speed_convert(download), speed_convert(upload), info]
  91. async def get_http_status_code(url: str) -> int:
  92. async with aiosession.head(url) as resp:
  93. return resp.status
  94. async def make_carbon(code):
  95. url = "https://carbonara.solopov.dev/api/cook"
  96. async with aiosession.post(url, json={"code": code}) as resp:
  97. image = BytesIO(await resp.read())
  98. image.name = "carbon.png"
  99. return image
  100. async def transfer_sh(file_or_message):
  101. if isinstance(file_or_message, Message):
  102. file_or_message = await file_or_message.download()
  103. file = file_or_message
  104. async with aiofiles.open(file, "rb") as f:
  105. params = {file: await f.read()}
  106. resp = await post("https://transfer.sh/", data=params)
  107. url = resp.strip()
  108. return url
  109. async def calc_distance_from_ip(ip1: str, ip2: str) -> float:
  110. Radius_Earth = 6371.0088
  111. data1, data2 = await gather(
  112. get(f"http://ipinfo.io/{ip1}"),
  113. get(f"http://ipinfo.io/{ip2}"),
  114. )
  115. lat1, lon1 = data1["loc"].split(",")
  116. lat2, lon2 = data2["loc"].split(",")
  117. lat1, lon1 = radians(float(lat1)), radians(float(lon1))
  118. lat2, lon2 = radians(float(lat2)), radians(float(lon2))
  119. dlon = lon2 - lon1
  120. dlat = lat2 - lat1
  121. a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
  122. c = 2 * atan2(sqrt(a), sqrt(1 - a))
  123. distance = Radius_Earth * c
  124. return distance
  125. def get_urls_from_text(text: str) -> bool:
  126. regex = r"""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]
  127. [.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(
  128. \([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\
  129. ()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))""".strip()
  130. return [x[0] for x in findall(regex, str(text))]
  131. async def time_converter(message: Message, time_value: str) -> datetime:
  132. unit = ["m", "h", "d"] # m == minutes | h == hours | d == days
  133. check_unit = "".join(list(filter(time_value[-1].lower().endswith, unit)))
  134. currunt_time = datetime.now()
  135. time_digit = time_value[:-1]
  136. if not time_digit.isdigit():
  137. return await message.reply_text("Incorrect time specified")
  138. if check_unit == "m":
  139. temp_time = currunt_time + timedelta(minutes=int(time_digit))
  140. elif check_unit == "h":
  141. temp_time = currunt_time + timedelta(hours=int(time_digit))
  142. elif check_unit == "d":
  143. temp_time = currunt_time + timedelta(days=int(time_digit))
  144. else:
  145. return await message.reply_text("Incorrect time specified.")
  146. return temp_time
  147. async def extract_userid(message, text: str):
  148. """
  149. NOT TO BE USED OUTSIDE THIS FILE
  150. """
  151. def is_int(text: str):
  152. try:
  153. int(text)
  154. except ValueError:
  155. return False
  156. return True
  157. text = text.strip()
  158. if is_int(text):
  159. return int(text)
  160. entities = message.entities
  161. app = message._client
  162. if len(entities) < 2:
  163. return (await app.get_users(text)).id
  164. entity = entities[1]
  165. if entity.type == MessageEntityType.MENTION:
  166. return (await app.get_users(text)).id
  167. if entity.type == MessageEntityType.TEXT_MENTION:
  168. return entity.user.id
  169. return None
  170. async def extract_user_and_reason(message, sender_chat=False):
  171. args = message.text.strip().split()
  172. text = message.text
  173. user = None
  174. reason = None
  175. try:
  176. if message.reply_to_message:
  177. reply = message.reply_to_message
  178. # if reply to a message and no reason is given
  179. if not reply.from_user:
  180. if (
  181. reply.sender_chat
  182. and reply.sender_chat != message.chat.id
  183. and sender_chat
  184. ):
  185. id_ = reply.sender_chat.id
  186. else:
  187. return None, None
  188. else:
  189. id_ = reply.from_user.id
  190. if len(args) < 2:
  191. reason = None
  192. else:
  193. reason = text.split(None, 1)[1]
  194. return id_, reason
  195. # if not reply to a message and no reason is given
  196. if len(args) == 2:
  197. user = text.split(None, 1)[1]
  198. return await extract_userid(message, user), None
  199. # if reason is given
  200. if len(args) > 2:
  201. user, reason = text.split(None, 2)[1:]
  202. return await extract_userid(message, user), reason
  203. return user, reason
  204. except errors.UsernameInvalid:
  205. return "", ""
  206. async def extract_user(message):
  207. return (await extract_user_and_reason(message))[0]
  208. def get_file_id_from_message(
  209. message,
  210. max_file_size=3145728,
  211. mime_types=["image/png", "image/jpeg"],
  212. ):
  213. file_id = None
  214. if message.document:
  215. if int(message.document.file_size) > max_file_size:
  216. return
  217. mime_type = message.document.mime_type
  218. if mime_types and mime_type not in mime_types:
  219. return
  220. file_id = message.document.file_id
  221. if message.sticker:
  222. if message.sticker.is_animated:
  223. if not message.sticker.thumbs:
  224. return
  225. file_id = message.sticker.thumbs[0].file_id
  226. else:
  227. file_id = message.sticker.file_id
  228. if message.photo:
  229. file_id = message.photo.file_id
  230. if message.animation:
  231. if not message.animation.thumbs:
  232. return
  233. file_id = message.animation.thumbs[0].file_id
  234. if message.video:
  235. if not message.video.thumbs:
  236. return
  237. file_id = message.video.thumbs[0].file_id
  238. return file_id
  239. def extract_text_and_keyb(ikb, text: str, row_width: int = 2):
  240. keyboard = {}
  241. try:
  242. text = text.strip()
  243. if text.startswith("`"):
  244. text = text[1:]
  245. if text.endswith("`"):
  246. text = text[:-1]
  247. if "~~" in text:
  248. text = text.replace("~~", "¤¤")
  249. text, keyb = text.split("~")
  250. if "¤¤" in text:
  251. text = text.replace("¤¤", "~~")
  252. keyb = findall(r"\[.+\,.+\]", keyb)
  253. for btn_str in keyb:
  254. btn_str = re_sub(r"[\[\]]", "", btn_str)
  255. btn_str = btn_str.split(",")
  256. btn_txt, btn_url = btn_str[0], btn_str[1].strip()
  257. if not get_urls_from_text(btn_url):
  258. continue
  259. keyboard[btn_txt] = btn_url
  260. keyboard = ikb(keyboard, row_width)
  261. except Exception:
  262. return
  263. return text, keyboard
  264. async def check_format(ikb, raw_text: str):
  265. keyb = findall(r"\[.+\,.+\]", raw_text)
  266. if keyb and not "~" in raw_text:
  267. raw_text = raw_text.replace("button=", "\n~\nbutton=")
  268. return raw_text
  269. if "~" in raw_text and keyb:
  270. if not extract_text_and_keyb(ikb, raw_text):
  271. return ""
  272. else:
  273. return raw_text
  274. else:
  275. return raw_text
  276. async def get_data_and_name(replied_message, message):
  277. text = message.text.markdown if message.text else message.caption.markdown
  278. name = text.split(None, 1)[1].strip()
  279. text = name.split(" ", 1)
  280. if len(text) > 1:
  281. name = text[0]
  282. data = text[1].strip()
  283. if replied_message and (
  284. replied_message.sticker or replied_message.video_note
  285. ):
  286. data = None
  287. else:
  288. if replied_message and (
  289. replied_message.sticker or replied_message.video_note
  290. ):
  291. data = None
  292. elif (
  293. replied_message
  294. and not replied_message.text
  295. and not replied_message.caption
  296. ):
  297. data = None
  298. else:
  299. data = (
  300. replied_message.text.markdown
  301. if replied_message.text
  302. else replied_message.caption.markdown
  303. )
  304. command = message.command[0]
  305. match = f"/{command} " + name
  306. if not message.reply_to_message and message.text:
  307. if match == data:
  308. data = "error"
  309. elif not message.reply_to_message and not message.text:
  310. if match == data:
  311. data = None
  312. return data, name
  313. async def get_specific_usernames(client, user_ids: list) -> Dict[int, str]:
  314. def _fetch_users():
  315. ids_str = ','.join(str(uid) for uid in user_ids)
  316. with client.storage.conn:
  317. query = f"""
  318. SELECT usernames.id, usernames.username
  319. FROM usernames
  320. WHERE usernames.id IN ({ids_str})
  321. AND username IS NOT NULL
  322. """
  323. result = client.storage.conn.execute(query).fetchall()
  324. users_ = {}
  325. for row in result:
  326. users_[row[0]] = row[1]
  327. return users_
  328. try:
  329. users = await asyncio.to_thread(_fetch_users)
  330. return users
  331. except Exception as e:
  332. print(f"Error fetching users: {e}")
  333. return {}