functions.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. import codecs
  21. import pickle
  22. from asyncio import gather, get_running_loop
  23. from io import BytesIO
  24. from math import atan2, cos, radians, sin, sqrt
  25. from random import randint
  26. from re import findall
  27. import aiofiles
  28. import aiohttp
  29. import speedtest
  30. from PIL import Image, ImageDraw, ImageFilter, ImageFont
  31. from wget import download
  32. from wbb import aiohttpsession as aiosession
  33. from wbb.utils import aiodownloader
  34. from wbb.utils.fetch import fetch
  35. """
  36. Just import 'downloader' anywhere and do downloader.download() to
  37. download file from a given url
  38. """
  39. downloader = aiodownloader.Handler()
  40. # Another downloader, but with wget
  41. async def download_url(url: str):
  42. loop = get_running_loop()
  43. file = await loop.run_in_executor(None, download, url)
  44. return file
  45. def generate_captcha():
  46. # Generate one letter
  47. def gen_letter():
  48. return chr(randint(65, 90))
  49. def rndColor():
  50. return (randint(64, 255), randint(64, 255), randint(64, 255))
  51. def rndColor2():
  52. return (randint(32, 127), randint(32, 127), randint(32, 127))
  53. # Generate a 4 letter word
  54. def gen_wrong_answer():
  55. word = ""
  56. for _ in range(4):
  57. word += gen_letter()
  58. return word
  59. # Generate 8 wrong captcha answers
  60. wrong_answers = []
  61. for _ in range(8):
  62. wrong_answers.append(gen_wrong_answer())
  63. width = 80 * 4
  64. height = 100
  65. correct_answer = ""
  66. font = ImageFont.truetype("assets/arial.ttf", 55)
  67. file = f"assets/{randint(1000, 9999)}.jpg"
  68. image = Image.new("RGB", (width, height), (255, 255, 255))
  69. draw = ImageDraw.Draw(image)
  70. # Draw random points on image
  71. for x in range(width):
  72. for y in range(height):
  73. draw.point((x, y), fill=rndColor())
  74. for t in range(4):
  75. letter = gen_letter()
  76. correct_answer += letter
  77. draw.text((60 * t + 50, 15), letter, font=font, fill=rndColor2())
  78. image = image.filter(ImageFilter.BLUR)
  79. image.save(file, "jpeg")
  80. return [file, correct_answer, wrong_answers]
  81. def test_speedtest():
  82. def speed_convert(size):
  83. power = 2 ** 10
  84. zero = 0
  85. units = {0: "", 1: "Kb/s", 2: "Mb/s", 3: "Gb/s", 4: "Tb/s"}
  86. while size > power:
  87. size /= power
  88. zero += 1
  89. return f"{round(size, 2)} {units[zero]}"
  90. speed = speedtest.Speedtest()
  91. info = speed.get_best_server()
  92. download = speed.download()
  93. upload = speed.upload()
  94. return [speed_convert(download), speed_convert(upload), info]
  95. async def file_size_from_url(url: str) -> int:
  96. async with aiosession.head(url) as resp:
  97. size = int(resp.headers["content-length"])
  98. return size
  99. async def get_http_status_code(url: str) -> int:
  100. async with aiosession.head(url) as resp:
  101. return resp.status
  102. async def make_carbon(code):
  103. url = "https://carbonara.vercel.app/api/cook"
  104. async with aiosession.post(url, json={"code": code}) as resp:
  105. image = BytesIO(await resp.read())
  106. image.name = "carbon.png"
  107. return image
  108. async def transfer_sh(file):
  109. async with aiofiles.open(file, "rb") as f:
  110. params = {file: await f.read()}
  111. async with aiohttp.ClientSession() as session:
  112. async with session.post("https://transfer.sh/", data=params) as resp:
  113. download_link = str(await resp.text()).strip()
  114. return download_link
  115. def obj_to_str(object):
  116. if not object:
  117. return False
  118. string = codecs.encode(pickle.dumps(object), "base64").decode()
  119. return string
  120. def str_to_obj(string: str):
  121. object = pickle.loads(codecs.decode(string.encode(), "base64"))
  122. return object
  123. async def calc_distance_from_ip(ip1: str, ip2: str) -> float:
  124. Radius_Earth = 6371.0088
  125. data1, data2 = await gather(
  126. fetch(f"http://ipinfo.io/{ip1}"), fetch(f"http://ipinfo.io/{ip2}")
  127. )
  128. lat1, lon1 = data1["loc"].split(",")
  129. lat2, lon2 = data2["loc"].split(",")
  130. lat1, lon1 = radians(float(lat1)), radians(float(lon1))
  131. lat2, lon2 = radians(float(lat2)), radians(float(lon2))
  132. dlon = lon2 - lon1
  133. dlat = lat2 - lat1
  134. a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
  135. c = 2 * atan2(sqrt(a), sqrt(1 - a))
  136. distance = Radius_Earth * c
  137. return distance
  138. def get_urls_from_text(text: str) -> bool:
  139. regex = r"""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]
  140. [.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(
  141. \([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\
  142. ()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))""".strip()
  143. return [x[0] for x in findall(regex, text)]
  144. async def extract_userid(message, text: str):
  145. text = text.strip()
  146. entities = message.entities
  147. app = message._client
  148. if len(entities) < 2:
  149. return (await app.get_users(text)).id
  150. entity = entities[1]
  151. if entity.type == "mention":
  152. return (await app.get_users(text)).id
  153. if entity.type == "text_mention":
  154. return entity.user.id
  155. return None
  156. async def extract_user_and_reason(message):
  157. args = message.text.strip().split()
  158. text = message.text
  159. user = None
  160. reason = None
  161. if message.reply_to_message:
  162. reply = message.reply_to_message
  163. # if reply to a message and no reason is given
  164. if not reply.from_user:
  165. return None, None
  166. if len(args) < 2:
  167. reason = None
  168. else:
  169. reason = text.split(None, 1)[1]
  170. return reply.from_user.id, reason
  171. # if not reply to a message and no reason is given
  172. if len(args) == 2:
  173. user = text.split(None, 1)[1]
  174. return await extract_userid(message, user), None
  175. # if reason is given
  176. elif len(args) > 2:
  177. user, reason = text.split(None, 2)[1:]
  178. return await extract_userid(message, user), reason
  179. return user, reason
  180. async def extract_user(message):
  181. return (await extract_user_and_reason(message))[0]