functions.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. """
  2. MIT License
  3. Copyright (c) 2021 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, get_running_loop
  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. from time import time
  30. import aiofiles
  31. import aiohttp
  32. import speedtest
  33. from PIL import Image, ImageDraw, ImageFilter, ImageFont
  34. from pyrogram.types import Message
  35. from wget import download
  36. from wbb import aiohttpsession as aiosession
  37. from wbb import arq
  38. from wbb.utils import aiodownloader
  39. from wbb.utils.dbfunctions import start_restart_stage
  40. from wbb.utils.http import get
  41. """
  42. Just import 'downloader' anywhere and do downloader.download() to
  43. download file from a given url
  44. """
  45. downloader = aiodownloader.Handler()
  46. # Another downloader, but with wget
  47. async def download_url(url: str):
  48. loop = get_running_loop()
  49. file = await loop.run_in_executor(None, download, url)
  50. return file
  51. async def restart(m: Message):
  52. if m:
  53. await start_restart_stage(m.chat.id, m.message_id)
  54. execvp(executable, [executable, "-m", "wbb"])
  55. def generate_captcha():
  56. # Generate one letter
  57. def gen_letter():
  58. return chr(randint(65, 90))
  59. def rndColor():
  60. return (randint(64, 255), randint(64, 255), randint(64, 255))
  61. def rndColor2():
  62. return (randint(32, 127), randint(32, 127), randint(32, 127))
  63. # Generate a 4 letter word
  64. def gen_wrong_answer():
  65. word = ""
  66. for _ in range(4):
  67. word += gen_letter()
  68. return word
  69. # Generate 8 wrong captcha answers
  70. wrong_answers = []
  71. for _ in range(8):
  72. wrong_answers.append(gen_wrong_answer())
  73. width = 80 * 4
  74. height = 100
  75. correct_answer = ""
  76. font = ImageFont.truetype("assets/arial.ttf", 55)
  77. file = f"assets/{randint(1000, 9999)}.jpg"
  78. image = Image.new("RGB", (width, height), (255, 255, 255))
  79. draw = ImageDraw.Draw(image)
  80. # Draw random points on image
  81. for x in range(width):
  82. for y in range(height):
  83. draw.point((x, y), fill=rndColor())
  84. for t in range(4):
  85. letter = gen_letter()
  86. correct_answer += letter
  87. draw.text(
  88. (60 * t + 50, 15), letter, font=font, fill=rndColor2()
  89. )
  90. image = image.filter(ImageFilter.BLUR)
  91. image.save(file, "jpeg")
  92. return [file, correct_answer, wrong_answers]
  93. def test_speedtest():
  94. def speed_convert(size):
  95. power = 2 ** 10
  96. zero = 0
  97. units = {0: "", 1: "Kb/s", 2: "Mb/s", 3: "Gb/s", 4: "Tb/s"}
  98. while size > power:
  99. size /= power
  100. zero += 1
  101. return f"{round(size, 2)} {units[zero]}"
  102. speed = speedtest.Speedtest()
  103. info = speed.get_best_server()
  104. download = speed.download()
  105. upload = speed.upload()
  106. return [speed_convert(download), speed_convert(upload), info]
  107. async def file_size_from_url(url: str) -> int:
  108. async with aiosession.head(url) as resp:
  109. size = int(resp.headers["content-length"])
  110. return size
  111. async def get_http_status_code(url: str) -> int:
  112. async with aiosession.head(url) as resp:
  113. return resp.status
  114. async def make_carbon(code):
  115. url = "https://carbonara.vercel.app/api/cook"
  116. async with aiosession.post(url, json={"code": code}) as resp:
  117. image = BytesIO(await resp.read())
  118. image.name = "carbon.png"
  119. return image
  120. async def transfer_sh(file_or_message):
  121. if isinstance(file_or_message, Message):
  122. file_or_message = await file_or_message.download()
  123. file = file_or_message
  124. async with aiofiles.open(file, "rb") as f:
  125. params = {file: await f.read()}
  126. async with aiohttp.ClientSession() as session:
  127. async with session.post(
  128. "https://transfer.sh/", data=params
  129. ) as resp:
  130. download_link = str(await resp.text()).strip()
  131. return download_link
  132. async def calc_distance_from_ip(ip1: str, ip2: str) -> float:
  133. Radius_Earth = 6371.0088
  134. data1, data2 = await gather(
  135. get(f"http://ipinfo.io/{ip1}"),
  136. get(f"http://ipinfo.io/{ip2}"),
  137. )
  138. lat1, lon1 = data1["loc"].split(",")
  139. lat2, lon2 = data2["loc"].split(",")
  140. lat1, lon1 = radians(float(lat1)), radians(float(lon1))
  141. lat2, lon2 = radians(float(lat2)), radians(float(lon2))
  142. dlon = lon2 - lon1
  143. dlat = lat2 - lat1
  144. a = (
  145. sin(dlat / 2) ** 2
  146. + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
  147. )
  148. c = 2 * atan2(sqrt(a), sqrt(1 - a))
  149. distance = Radius_Earth * c
  150. return distance
  151. def get_urls_from_text(text: str) -> bool:
  152. regex = r"""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]
  153. [.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(
  154. \([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\
  155. ()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))""".strip()
  156. return [x[0] for x in findall(regex, text)]
  157. async def time_converter(message: Message, time_value: str) -> int:
  158. unit = ["m", "h", "d"] # m == minutes | h == hours | d == days
  159. check_unit = "".join(
  160. list(filter(time_value[-1].lower().endswith, unit))
  161. )
  162. currunt_time = datetime.now()
  163. time_digit = time_value[:-1]
  164. if not time_digit.isdigit():
  165. return await message.reply_text("Incorrect time specified")
  166. if check_unit == "m":
  167. temp_time = currunt_time + timedelta(minutes=int(time_digit))
  168. elif check_unit == "h":
  169. temp_time = currunt_time + timedelta(hours=int(time_digit))
  170. elif check_unit == "d":
  171. temp_time = currunt_time + timedelta(days=int(time_digit))
  172. else:
  173. return await message.reply_text("Incorrect time specified.")
  174. return int(datetime.timestamp(temp_time))
  175. async def extract_userid(message, text: str):
  176. """
  177. NOT TO BE USED OUTSIDE THIS FILE
  178. """
  179. def is_int(text: str):
  180. try:
  181. int(text)
  182. except ValueError:
  183. return False
  184. return True
  185. text = text.strip()
  186. if is_int(text):
  187. return int(text)
  188. entities = message.entities
  189. app = message._client
  190. if len(entities) < 2:
  191. return (await app.get_users(text)).id
  192. entity = entities[1]
  193. if entity.type == "mention":
  194. return (await app.get_users(text)).id
  195. if entity.type == "text_mention":
  196. return entity.user.id
  197. return None
  198. async def extract_user_and_reason(message):
  199. args = message.text.strip().split()
  200. text = message.text
  201. user = None
  202. reason = None
  203. if message.reply_to_message:
  204. reply = message.reply_to_message
  205. # if reply to a message and no reason is given
  206. if not reply.from_user:
  207. return None, None
  208. if len(args) < 2:
  209. reason = None
  210. else:
  211. reason = text.split(None, 1)[1]
  212. return reply.from_user.id, reason
  213. # if not reply to a message and no reason is given
  214. if len(args) == 2:
  215. user = text.split(None, 1)[1]
  216. return await extract_userid(message, user), None
  217. # if reason is given
  218. elif len(args) > 2:
  219. user, reason = text.split(None, 2)[1:]
  220. return await extract_userid(message, user), reason
  221. return user, reason
  222. async def extract_user(message):
  223. return (await extract_user_and_reason(message))[0]
  224. def get_file_id_from_message(
  225. message,
  226. max_file_size=3145728,
  227. mime_types=["image/png", "image/jpeg"],
  228. ):
  229. file_id = None
  230. if message.document:
  231. if int(message.document.file_size) > max_file_size:
  232. return
  233. mime_type = message.document.mime_type
  234. if mime_types:
  235. if mime_type not in mime_types:
  236. return
  237. file_id = message.document.file_id
  238. if message.sticker:
  239. if message.sticker.is_animated:
  240. if not message.sticker.thumbs:
  241. return
  242. file_id = message.sticker.thumbs[0].file_id
  243. else:
  244. file_id = message.sticker.file_id
  245. if message.photo:
  246. file_id = message.photo.file_id
  247. if message.animation:
  248. if not message.animation.thumbs:
  249. return
  250. file_id = message.animation.thumbs[0].file_id
  251. if message.video:
  252. if not message.video.thumbs:
  253. return
  254. file_id = message.video.thumbs[0].file_id
  255. return file_id
  256. def extract_text_and_keyb(ikb, text: str, row_width: int = 2):
  257. keyboard = {}
  258. try:
  259. text = text.strip()
  260. if text.startswith("`"):
  261. text = text[1:]
  262. if text.endswith("`"):
  263. text = text[:-1]
  264. text, keyb = text.split("~")
  265. keyb = findall(r"\[.+\,.+\]", keyb)
  266. for btn_str in keyb:
  267. btn_str = re_sub(r"[\[\]]", "", btn_str)
  268. btn_str = btn_str.split(",")
  269. btn_txt, btn_url = btn_str[0], btn_str[1].strip()
  270. if not get_urls_from_text(btn_url):
  271. continue
  272. keyboard[btn_txt] = btn_url
  273. keyboard = ikb(keyboard, row_width)
  274. except Exception:
  275. return
  276. return text, keyboard
  277. async def get_user_id_and_usernames(client) -> dict:
  278. with client.storage.lock, client.storage.conn:
  279. users = client.storage.conn.execute(
  280. 'SELECT * FROM peers WHERE type in ("user", "bot") AND username NOT null'
  281. ).fetchall()
  282. users_ = {}
  283. for user in users:
  284. users_[user[0]] = user[3]
  285. return users_