functions.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. """
  2. MIT License
  3. Copyright (c) 2023 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
  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.enums import MessageEntityType
  33. from pyrogram.types import Message
  34. from wbb import aiohttpsession as aiosession
  35. from wbb.utils.dbfunctions import start_restart_stage
  36. from wbb.utils.http import get, post
  37. async def restart(m: Message):
  38. if m:
  39. await start_restart_stage(m.chat.id, m.id)
  40. execvp(executable, [executable, "-m", "wbb"])
  41. def generate_captcha():
  42. # Generate one letter
  43. def gen_letter():
  44. return chr(randint(65, 90))
  45. def rndColor():
  46. return randint(64, 255), randint(64, 255), randint(64, 255)
  47. def rndColor2():
  48. return randint(32, 127), randint(32, 127), randint(32, 127)
  49. # Generate a 4 letter word
  50. def gen_wrong_answer():
  51. word = ""
  52. for _ in range(4):
  53. word += gen_letter()
  54. return word
  55. # Generate 8 wrong captcha answers
  56. wrong_answers = []
  57. for _ in range(8):
  58. wrong_answers.append(gen_wrong_answer())
  59. width = 80 * 4
  60. height = 100
  61. correct_answer = ""
  62. font = ImageFont.truetype("assets/arial.ttf", 55)
  63. file = f"assets/{randint(1000, 9999)}.jpg"
  64. image = Image.new("RGB", (width, height), (255, 255, 255))
  65. draw = ImageDraw.Draw(image)
  66. # Draw random points on image
  67. for x in range(width):
  68. for y in range(height):
  69. draw.point((x, y), fill=rndColor())
  70. for t in range(4):
  71. letter = gen_letter()
  72. correct_answer += letter
  73. draw.text((60 * t + 50, 15), letter, font=font, fill=rndColor2())
  74. image = image.filter(ImageFilter.BLUR)
  75. image.save(file, "jpeg")
  76. return [file, 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. if message.reply_to_message:
  176. reply = message.reply_to_message
  177. # if reply to a message and no reason is given
  178. if not reply.from_user:
  179. if (
  180. reply.sender_chat
  181. and reply.sender_chat != message.chat.id
  182. and sender_chat
  183. ):
  184. id_ = reply.sender_chat.id
  185. else:
  186. return None, None
  187. else:
  188. id_ = reply.from_user.id
  189. if len(args) < 2:
  190. reason = None
  191. else:
  192. reason = text.split(None, 1)[1]
  193. return id_, reason
  194. # if not reply to a message and no reason is given
  195. if len(args) == 2:
  196. user = text.split(None, 1)[1]
  197. return await extract_userid(message, user), None
  198. # if reason is given
  199. if len(args) > 2:
  200. user, reason = text.split(None, 2)[1:]
  201. return await extract_userid(message, user), reason
  202. return user, reason
  203. async def extract_user(message):
  204. return (await extract_user_and_reason(message))[0]
  205. def get_file_id_from_message(
  206. message,
  207. max_file_size=3145728,
  208. mime_types=["image/png", "image/jpeg"],
  209. ):
  210. file_id = None
  211. if message.document:
  212. if int(message.document.file_size) > max_file_size:
  213. return
  214. mime_type = message.document.mime_type
  215. if mime_types and mime_type not in mime_types:
  216. return
  217. file_id = message.document.file_id
  218. if message.sticker:
  219. if message.sticker.is_animated:
  220. if not message.sticker.thumbs:
  221. return
  222. file_id = message.sticker.thumbs[0].file_id
  223. else:
  224. file_id = message.sticker.file_id
  225. if message.photo:
  226. file_id = message.photo.file_id
  227. if message.animation:
  228. if not message.animation.thumbs:
  229. return
  230. file_id = message.animation.thumbs[0].file_id
  231. if message.video:
  232. if not message.video.thumbs:
  233. return
  234. file_id = message.video.thumbs[0].file_id
  235. return file_id
  236. def extract_text_and_keyb(ikb, text: str, row_width: int = 2):
  237. keyboard = {}
  238. try:
  239. text = text.strip()
  240. if text.startswith("`"):
  241. text = text[1:]
  242. if text.endswith("`"):
  243. text = text[:-1]
  244. text, keyb = text.split("~")
  245. keyb = findall(r"\[.+\,.+\]", keyb)
  246. for btn_str in keyb:
  247. btn_str = re_sub(r"[\[\]]", "", btn_str)
  248. btn_str = btn_str.split(",")
  249. btn_txt, btn_url = btn_str[0], btn_str[1].strip()
  250. if not get_urls_from_text(btn_url):
  251. continue
  252. keyboard[btn_txt] = btn_url
  253. keyboard = ikb(keyboard, row_width)
  254. except Exception:
  255. return
  256. return text, keyboard
  257. # BUILDING AN AI BY SI_NN_ER_LS
  258. async def check_format(ikb, raw_text: str):
  259. keyb = findall(r"\[.+\,.+\]", raw_text)
  260. if keyb and not "~" in raw_text:
  261. raw_text = raw_text.replace("button=", "\n~\nbutton=")
  262. return raw_text
  263. if "~" in raw_text and not keyb:
  264. raw_text =raw_text.replace("~", "")
  265. return raw_text
  266. if "~" in raw_text and keyb:
  267. if not extract_text_and_keyb(ikb, raw_text):
  268. return ""
  269. else:
  270. return raw_text
  271. else:
  272. return raw_text
  273. async def get_user_id_and_usernames(client) -> dict:
  274. with client.storage.conn:
  275. users = client.storage.conn.execute(
  276. 'SELECT * FROM peers WHERE type in ("user", "bot") AND username NOT null'
  277. ).fetchall()
  278. users_ = {}
  279. for user in users:
  280. users_[user[0]] = user[3]
  281. return users_