functions.py 8.2 KB

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