瀏覽代碼

Calculate distance between two servers

TheHamkerCat 5 年之前
父節點
當前提交
2ccd17dac9
共有 8 個文件被更改,包括 47 次插入 和 79 次删除
  1. 6 69
      wbb/modules/anime.py
  2. 2 1
      wbb/modules/greetings.py
  3. 0 1
      wbb/modules/ocr.py
  4. 6 3
      wbb/modules/pipes.py
  5. 1 2
      wbb/modules/user_info.py
  6. 6 1
      wbb/utils/fetch.py
  7. 23 0
      wbb/utils/functions.py
  8. 3 2
      wbb/utils/inlinefuncs.py

+ 6 - 69
wbb/modules/anime.py

@@ -5,12 +5,15 @@ import requests
 from datetime import timedelta
 from pyrogram import filters
 from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
-
-from wbb import app, telegraph
+from wbb import app
 from wbb.core.decorators.errors import capture_err
 
 __MODULE__ = "Anime"
-__HELP__ = "•Anime uwu•\n\n/anime - search anime on AniList\n /manga - search manga on Anilist\n /char - search character on Anilist\n /nhentai ID - returns the nhentai in telegraph instant preview format."
+__HELP__ = """
+/anime - search anime on AniList
+/manga - search manga on Anilist
+/char - search character on Anilist
+"""
 
 
 def shorten(description, info='anilist.co'):
@@ -301,69 +304,3 @@ async def character_search(_, message):
             await message.reply_photo(image, caption=ms_g)
         else:
             await message.reply(ms_g)
-
-
-@app.on_message(filters.command("nhentai"))
-@capture_err
-async def nhentai(_, message):
-    if len(message.command) < 2:
-        await message.delete()
-        return
-    query = message.text.split(None, 1)[1]
-    title, tags, artist, total_pages, post_url, cover_image = nhentai_data(
-        query)
-    await message.reply_text(
-        f"<code>{title}</code>\n\n<b>Tags:</b>\n{tags}\n<b>Artists:</b>\n{artist}\n<b>Pages:</b>\n{total_pages}",
-        reply_markup=InlineKeyboardMarkup(
-            [
-                [
-                    InlineKeyboardButton(
-                        "Read Here",
-                        url=post_url
-                    )
-                ]
-            ]
-        )
-    )
-
-
-def nhentai_data(noombers):
-    url = f"https://nhentai.net/api/gallery/{noombers}"
-    res = requests.get(url).json()
-    pages = res["images"]["pages"]
-    info = res["tags"]
-    title = res["title"]["english"]
-    links = []
-    tags = ""
-    artist = ''
-    total_pages = res['num_pages']
-    extensions = {
-        'j': 'jpg',
-        'p': 'png',
-        'g': 'gif'
-    }
-    for i, x in enumerate(pages):
-        media_id = res["media_id"]
-        temp = x['t']
-        file = f"{i+1}.{extensions[temp]}"
-        link = f"https://i.nhentai.net/galleries/{media_id}/{file}"
-        links.append(link)
-
-    for i in info:
-        if i["type"] == "tag":
-            tag = i['name']
-            tag = tag.split(" ")
-            tag = "_".join(tag)
-            tags += f"#{tag} "
-        if i["type"] == "artist":
-            artist = f"{i['name']} "
-
-    post_content = "".join(f"<img src={link}><br>" for link in links)
-
-    post = telegraph.create_page(
-        f"{title}",
-        html_content=post_content,
-        author_name="@WilliamButcherBot",
-        author_url="https://t.me/WilliamButcherBot"
-    )
-    return title, tags, artist, total_pages, post['url'], links[0]

+ 2 - 1
wbb/modules/greetings.py

@@ -78,6 +78,7 @@ sends /rules, he'll get the message
 answers_dicc = []
 loop = asyncio.get_running_loop()
 
+
 async def get_initial_captcha_cache():
     global answers_dicc
     answers_dicc = await get_captcha_cache()
@@ -233,7 +234,7 @@ async def callback_query_welcome_button(_, callback_query):
         if answer != correct_answer:
             await callback_query.answer("Yeah, It's Wrong.")
             for iii in answers_dicc:
-                if iii['user_id'] == pending_user_id  and iii['chat_id'] == button_message.chat.id:
+                if iii['user_id'] == pending_user_id and iii['chat_id'] == button_message.chat.id:
                     attempts = iii['attempts']
                     if attempts >= 3:
                         answers_dicc.remove(iii)

+ 0 - 1
wbb/modules/ocr.py

@@ -80,4 +80,3 @@ async def image_ocr(_, message):
     except MessageEmpty:
         await m.edit("There's no text in that image.")
         return
-    

+ 6 - 3
wbb/modules/pipes.py

@@ -21,7 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
 """
-from wbb import app, app2, SUDOERS, MESSAGE_DUMP_CHAT, USERBOT_ID, BOT_ID
+from wbb import app, app2, SUDOERS, USERBOT_ID, BOT_ID
 from wbb.core.decorators.errors import capture_err
 from wbb.utils.filter_groups import pipes_group
 from wbb.utils.dbfunctions import is_pipe_active, activate_pipe, deactivate_pipe, show_pipes
@@ -73,6 +73,7 @@ loop.create_task(load_pipes())
 
 
 @app.on_message(~filters.me, group=pipes_group)
+@capture_err
 async def pipes_worker_bot(_, message: Message):
     for pipe in pipes_list_bot:
         if pipe['from_chat_id'] == message.chat.id:
@@ -80,6 +81,7 @@ async def pipes_worker_bot(_, message: Message):
 
 
 @app2.on_message(~filters.me, group=pipes_group)
+@capture_err
 async def pipes_worker_userbot(_, message: Message):
     for pipe in pipes_list_userbot:
         if pipe['from_chat_id'] == message.chat.id:
@@ -107,6 +109,7 @@ async def pipes_worker_userbot(_, message: Message):
 
 
 @app.on_message(filters.command("activate_pipe") & filters.user(SUDOERS))
+@capture_err
 async def activate_pipe_func(_, message: Message):
     if len(message.command) != 4:
         await message.reply_text("**Usage:**\n/activate_pipe [FROM_CHAT_ID] [TO_CHAT_ID] [BOT|USERBOT]")
@@ -118,7 +121,6 @@ async def activate_pipe_func(_, message: Message):
     if fetcher != "bot" and fetcher != "userbot":
         await message.reply_text("Wrong fetcher, see help menu.")
         return
-    chat_id = message.chat.id
     if await is_pipe_active(from_chat, to_chat):
         await message.reply_text("This pipe is already active.")
         return
@@ -128,6 +130,7 @@ async def activate_pipe_func(_, message: Message):
 
 
 @app.on_message(filters.command("deactivate_pipe") & filters.user(SUDOERS))
+@capture_err
 async def deactivate_pipe_func(_, message: Message):
     if len(message.command) != 3:
         await message.reply_text("**Usage:**\n/deactivate_pipe [FROM_CHAT_ID] [TO_CHAT_ID]")
@@ -135,7 +138,6 @@ async def deactivate_pipe_func(_, message: Message):
     text = message.text.strip().split()
     from_chat = int(text[1])
     to_chat = int(text[2])
-    chat_id = message.chat.id
     if not await is_pipe_active(from_chat, to_chat):
         await message.reply_text("This pipe is already inactive.")
         return
@@ -145,6 +147,7 @@ async def deactivate_pipe_func(_, message: Message):
 
 
 @app.on_message(filters.command("pipes") & filters.user(SUDOERS))
+@capture_err
 async def show_pipes_func(_, message: Message):
     pipes = pipes_list_bot + pipes_list_userbot
     if not pipes:

+ 1 - 2
wbb/modules/user_info.py

@@ -20,8 +20,7 @@ async def get_user_info(user):
     is_gbanned = await is_gbanned_user(user_id)
     is_sudo = user_id in SUDOERS
     karma = await user_global_karma(user_id)
-    banned_in_spamwatch = False if spamwatch.get_ban(
-        user_id) == False else True
+    banned_in_spamwatch = False if not spamwatch.get_ban(user_id) else True
     caption = f"""
 **ID:** `{user_id}`
 **DC:** {dc_id}

+ 6 - 1
wbb/utils/fetch.py

@@ -23,10 +23,15 @@ SOFTWARE.
 """
 import aiohttp
 
+headers = {
+    'Accept': 'application/json',
+    'Content-Type': 'application/json',
+}
+
 
 async def fetch(url):
     async with aiohttp.ClientSession() as session:
-        async with session.get(url) as resp:
+        async with session.get(url, headers=headers) as resp:
             try:
                 data = await resp.json()
             except Exception:

+ 23 - 0
wbb/utils/functions.py

@@ -23,13 +23,16 @@ SOFTWARE.
 """
 from PIL import Image, ImageDraw, ImageFont, ImageFilter
 from random import randint
+from math import sin, cos, sqrt, atan2, radians
 from wbb.utils import aiodownloader
+from wbb.utils.fetch import fetch
 from carbonnow import Carbon
 import speedtest
 import aiohttp
 import aiofiles
 import pickle
 import codecs
+from asyncio import gather
 
 """
 Just import 'downloader' anywhere and do downloader.download() to
@@ -131,12 +134,32 @@ async def transfer_sh(file):
             download_link = str(await resp.text()).strip()
     return download_link
 
+
 def obj_to_str(object):
     if not object:
         return False
     string = codecs.encode(pickle.dumps(object), "base64").decode()
     return string
 
+
 def str_to_obj(string: str):
     object = pickle.loads(codecs.decode(string.encode(), "base64"))
     return object
+
+
+async def calc_distance_from_ip(ip1: str, ip2: str) -> float:
+    Radius_Earth = 6371.0088
+    data1, data2 = await gather(
+        fetch(f"http://ipinfo.io/{ip1}"),
+        fetch(f"http://ipinfo.io/{ip2}")
+    )
+    lat1, lon1 = data1['loc'].split(",")
+    lat2, lon2 = data2['loc'].split(",")
+    lat1, lon1 = radians(float(lat1)), radians(float(lon1))
+    lat2, lon2 = radians(float(lat2)), radians(float(lon2))
+    dlon = lon2 - lon1
+    dlat = lat2 - lat1
+    a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
+    c = 2 * atan2(sqrt(a), sqrt(1 - a))
+    distance = Radius_Earth * c
+    return distance

+ 3 - 2
wbb/utils/inlinefuncs.py

@@ -63,6 +63,7 @@ keywords_list = [
     "nsfw_scan", "ytmusic", "carbon", "info"
 ]
 
+
 async def inline_help_func(__HELP__):
     buttons = InlineKeyboard(row_width=3)
     buttons.add(*[(InlineKeyboardButton(
@@ -81,9 +82,9 @@ async def inline_help_func(__HELP__):
             description="Get Github Respository Of Bot.",
             input_message_content=InputTextMessageContent(
                 "https://github.com/thehamkercat/WilliamButcherBot"
-                ),
+            ),
             thumb_url="https://hamker.me/gjc9fo3.png"
-            )
+        )
     ]
     answerss = await alive_function(answerss)
     return answerss