functions.py 10 KB

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