functions.py 12 KB

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