Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

VPS runtime asynchronous Error Fixes #187

Open
Gareryer opened this issue Aug 3, 2024 · 2 comments
Open

VPS runtime asynchronous Error Fixes #187

Gareryer opened this issue Aug 3, 2024 · 2 comments

Comments

@Gareryer
Copy link

Gareryer commented Aug 3, 2024

I keep getting this error

admin@server:/usr/local/bin/Link-Bypasser-Bot# python3 main.py
Bot Starting
/usr/local/bin/Link-Bypasser-Bot/main.py:230: RuntimeWarning: coroutine 'SendMessage.send_message' was never awaited
  app.send_message(
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
object NoneType can't be used in 'await' expression
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/pyrogram/dispatcher.py", line 477, in handler_worker
    await handler.callback(self.client, *args)
  File "/usr/local/lib/python3.10/dist-packages/pyrogram/handlers/message_handler.py", line 163, in resolve_future_or_callback
    await self.original_callback(client, message, *args)
TypeError: object NoneType can't be used in 'await' expression

I thought it because I didn't implement .env so i did

TOKEN=246:AAY
ID=12345
HASH=xxxx
Laravel_Session=
XSRF_TOKEN=
GDTot_Crypt=
DCRYPT=
KCRYPT=
HCRYPT=
KATCRYPT=
UPTOBOX_TOKEN=
TERA_COOKIE=
CLOUDFLARE=
PORT=5000
DB_API=Cfg
DB_OWNER=xxx...rish
DB_NAME=xxx...db

but then i realize its relating to asynchronous function or coroutine in the main.py script that is being used improperly or not awaited. So i rewrite the main.py

from pyrogram import Client, filters
from pyrogram.types import (
    InlineKeyboardMarkup,
    InlineKeyboardButton,
    BotCommand,
    Message,
)
from os import environ, remove
from json import load
from re import search

from texts import HELP_TEXT
import bypasser
import freewall
from time import time
from db import DB
import asyncio

# Load config
with open("config.json", "r") as f:
    DATA = load(f)

def getenv(var):
    return environ.get(var) or DATA.get(var, None)

# Initialize bot
bot_token = getenv("TOKEN")
api_hash = getenv("HASH")
api_id = getenv("ID")
app = Client("my_bot", api_id=api_id, api_hash=api_hash, bot_token=bot_token)

with app:
    app.set_bot_commands(
        [
            BotCommand("start", "Welcome Message"),
            BotCommand("help", "List of All Supported Sites"),
        ]
    )

# Initialize database
db_api = getenv("DB_API")
db_owner = getenv("DB_OWNER")
db_name = getenv("DB_NAME")
try:
    database = DB(api_key=db_api, db_owner=db_owner, db_name=db_name)
except Exception as e:
    print(f"Database is Not Set: {e}")
    database = None

# Handle index
async def handle_index(ele: str, message: Message, msg: Message):
    result = bypasser.scrapeIndex(ele)
    try:
        await app.delete_messages(message.chat.id, msg.id)
    except:
        pass
    if database and result:
        database.insert(ele, result)
    for page in result:
        await app.send_message(
            message.chat.id,
            page,
            reply_to_message_id=message.id,
            disable_web_page_preview=True,
        )

# Loop thread
async def loop_thread(message: Message, otherss=False):
    urls = []
    texts = message.caption if otherss else message.text

    if not texts:
        return

    for ele in texts.split():
        if "http://" in ele or "https://" in ele:
            urls.append(ele)
    
    if not urls:
        return

    if bypasser.ispresent(bypasser.ddl.ddllist, urls[0]):
        msg = await app.send_message(message.chat.id, "⚡ __generating...__", reply_to_message_id=message.id)
    elif freewall.pass_paywall(urls[0], check=True):
        msg = await app.send_message(message.chat.id, "🕴️ __jumping the wall...__", reply_to_message_id=message.id)
    else:
        msg_text = "🔎 __bypassing...__" if "https://olamovies" not in urls[0] and "https://psa.wf/" not in urls[0] else "⏳ __this might take some time...__"
        msg = await app.send_message(message.chat.id, msg_text, reply_to_message_id=message.id)

    strt = time()
    links = ""
    temp = None

    for ele in urls:
        df_find = database.find(ele) if database else None
        if df_find:
            print("Found in DB")
            temp = df_find
        elif search(r"https?:\/\/(?:[\w.-]+)?\.\w+\/\d+:", ele):
            await handle_index(ele, message, msg)
            return
        elif bypasser.ispresent(bypasser.ddl.ddllist, ele):
            try:
                temp = bypasser.ddl.direct_link_generator(ele)
            except Exception as e:
                temp = f"**Error**: {e}"
        elif freewall.pass_paywall(ele, check=True):
            freefile = freewall.pass_paywall(ele)
            if freefile:
                try:
                    await app.send_document(message.chat.id, freefile, reply_to_message_id=message.id)
                    remove(freefile)
                    await app.delete_messages(message.chat.id, [msg.id])
                    return
                except:
                    pass
            else:
                await app.send_message(message.chat.id, "__Failed to Jump__", reply_to_message_id=message.id)
        else:
            try:
                temp = bypasser.shortners(ele)
            except Exception as e:
                temp = f"**Error**: {e}"

        print("bypassed:", temp)
        if temp is not None:
            if not df_find and ("http://" in temp or "https://" in temp) and database:
                print("Adding to DB")
                database.insert(ele, temp)
            links += temp + "\n"

    end = time()
    print("Took {:.2f} sec".format(end - strt))

    if otherss:
        try:
            await app.send_photo(
                message.chat.id,
                message.photo.file_id,
                f"__{links}__",
                reply_to_message_id=message.id,
            )
            await app.delete_messages(message.chat.id, [msg.id])
            return
        except:
            pass

    try:
        final = []
        tmp = ""
        for ele in links.split("\n"):
            tmp += ele + "\n"
            if len(tmp) > 4000:
                final.append(tmp)
                tmp = ""
        final.append(tmp)
        await app.delete_messages(message.chat.id, msg.id)
        tmsgid = message.id
        for ele in final:
            tmsg = await app.send_message(
                message.chat.id,
                f"__{ele}__",
                reply_to_message_id=tmsgid,
                disable_web_page_preview=True,
            )
            tmsgid = tmsg.id
    except Exception as e:
        await app.send_message(
            message.chat.id,
            f"__Failed to Bypass : {e}__",
            reply_to_message_id=message.id,
        )

# Start command
@app.on_message(filters.command(["start"]))
async def send_start(client: Client, message: Message):
    await app.send_message(
        message.chat.id,
        f"__👋 Hi **{message.from_user.mention}**, I am Link Bypasser Bot. Just send me any supported links and I will get you results.\nCheckout /help to Read More__",
        reply_markup=InlineKeyboardMarkup(
            [
                [InlineKeyboardButton("🌐 Source Code", url="https://github.com/bipinkrish/Link-Bypasser-Bot")],
                [InlineKeyboardButton("Replit", url="https://replit.com/@bipinkrish/Link-Bypasser#app.py")],
            ]
        ),
        reply_to_message_id=message.id,
    )

# Help command
@app.on_message(filters.command(["help"]))
async def send_help(client: Client, message: Message):
    await app.send_message(
        message.chat.id,
        HELP_TEXT,
        reply_to_message_id=message.id,
        disable_web_page_preview=True,
    )

# Links
@app.on_message(filters.text)
async def receive(client: Client, message: Message):
    asyncio.create_task(loop_thread(message))

# Doc thread
async def doc_thread(message: Message):
    msg = await app.send_message(message.chat.id, "🔎 __bypassing...__", reply_to_message_id=message.id)
    print("sent DLC file")
    file = await app.download_media(message)
    dlccont = open(file, "r").read()
    links = bypasser.getlinks(dlccont)
    await app.edit_message_text(message.chat.id, msg.id, f"__{links}__", disable_web_page_preview=True)
    remove(file)

# Files
@app.on_message([filters.document, filters.photo, filters.video])
async def docfile(client: Client, message: Message):
    try:
        if message.document.file_name.endswith("dlc"):
            asyncio.create_task(doc_thread(message))
            return
    except:
        pass
    asyncio.create_task(loop_thread(message, True))

# Server loop
print("Bot Starting")
app.run()

Key Changes:

  • Awaited all async functions: Replaced all app.send_message(...) and similar calls with await app.send_message(...).
  • Replaced threads with asyncio tasks: Used asyncio.create_task() to handle tasks instead of using threading.
  • Converted functions to async: Modified functions like send_start, send_help, handle_index, etc., to async.

This version should resolve the issues with unawaited coroutines and is more aligned with asynchronous programming best practices.

@bipinkrish
Copy link
Owner

I was very beginner when I start this project so expect ver bad code, open a PR for this please

@Gareryer
Copy link
Author

Gareryer commented Aug 3, 2024

I was very beginner when I start this project so expect ver bad code, open a PR for this please

btw, https://shrs.link seems to not be working

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants