Skip to content

Commit

Permalink
Merge pull request #73 from kastaid/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
illvart authored Feb 13, 2024
2 parents 95edc07 + 403331b commit 1818617
Show file tree
Hide file tree
Showing 74 changed files with 1,691 additions and 1,802 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,5 @@ backup

*/plugins/custom/*
!*/plugins/custom/__init__.py

.ruff*
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
# Please read the GNU Affero General Public License in
# < https://github.com/kastaid/getter/blob/main/LICENSE/ >.

FROM python:3.10-slim-bullseye
FROM python:3.12-slim-bookworm

ENV TZ=Asia/Jakarta \
TERM=xterm-256color \
Expand Down
4 changes: 1 addition & 3 deletions getter/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# ruff: noqa: F401
# getter < https://t.me/kastaid >
# Copyright (C) 2022-present kastaid
#
Expand Down Expand Up @@ -28,9 +29,6 @@
sys.exit(1)
if "/com.termux" in sys.executable:
print("You are detected using Termux, maybe the functionality will not work normally.")
if sys.version_info < (3, 10, 0):
print(f"You must use at least Python version 3.10.0, currently {__pyversion__}. Quitting...")
sys.exit(1)

Root: Path = Path(__file__).parent.parent
LOOP = uvloop.new_event_loop()
Expand Down
42 changes: 23 additions & 19 deletions getter/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,34 @@
# < https://github.com/kastaid/getter/blob/main/LICENSE/ >.

import sys
from asyncio import gather
from importlib import import_module
from time import monotonic
from requests.packages import urllib3
import getter.core.patched # noqa
from getter import (
from . import (
__license__,
__copyright__,
__version__,
__tlversion__,
__layer__,
__pyversion__,
)
from getter.config import Var, hl
from getter.core.base_client import getter_app
from getter.core.helper import plugins_help
from getter.core.property import do_not_remove_credit
from getter.core.startup import (
from .config import Var, hl
from .core.base_client import getter_app
from .core.db import db_connect
from .core.helper import plugins_help, jdata
from .core.property import do_not_remove_credit
from .core.startup import (
trap,
migrations,
autopilot,
verify,
autous,
finishing,
)
from getter.core.utils import time_formatter
from getter.logger import LOG
from .core.utils import time_formatter
from .logger import LOG

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

Expand All @@ -46,6 +48,8 @@


async def main() -> None:
await db_connect()
await jdata.sudo_users()
migrations()
await autopilot()
await verify()
Expand All @@ -54,14 +58,19 @@ async def main() -> None:
plugins = getter_app.all_plugins
for p in plugins:
try:
if p["path"].startswith("custom"):
plugin = "getter.plugins." + p["path"]
else:
plugin = "getter." + p["path"]
plugin = (
"".join(("getter.plugins.", p["path"]))
if p["path"].startswith("custom")
else "".join(("getter.", p["path"]))
)
import_module(plugin)
LOG.success("[+] " + p["name"])
except Exception as err:
LOG.exception(f"[-] {p['name']} : {err}")
from .plugins.afk import handle_afk
from .plugins.pmpermit import handle_pmpermit

await gather(*[handle_afk(), handle_pmpermit()])
loaded_time = time_formatter((monotonic() - load) * 1000)
loaded_msg = ">> Loaded Plugins: {} , Commands: {} (took {}) : {}".format(
plugins_help.count,
Expand All @@ -71,13 +80,8 @@ async def main() -> None:
)
LOG.info(loaded_msg)
do_not_remove_credit()
python_msg = ">> Python Version - {}".format(
__pyversion__,
)
telethon_msg = ">> Telethon Version - {} [Layer: {}]".format(
__tlversion__,
__layer__,
)
python_msg = f">> Python Version - {__pyversion__}"
telethon_msg = f">> Telethon Version - {__tlversion__} [Layer: {__layer__}]"
launch_msg = ">> 🚀 Getter v{} launch ({} - {}) in {} with handler [ {}ping ]".format(
__version__,
getter_app.full_name,
Expand Down
37 changes: 16 additions & 21 deletions getter/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,25 @@
# Please read the GNU Affero General Public License in
# < https://github.com/kastaid/getter/blob/main/LICENSE/ >.

import typing
from base64 import b64decode
from os import getenv
from string import ascii_lowercase
from typing import Any
from zoneinfo import ZoneInfo
from dotenv import load_dotenv, find_dotenv
from pytz import timezone

load_dotenv(find_dotenv("config.env"))


def tobool(val: str) -> typing.Optional[int]:
def tobool(val: str) -> int | None:
"""
Convert a string representation of truth to true (1) or false (0).
https://github.com/python/cpython/blob/main/Lib/distutils/util.py
"""
val = val.lower()
if val in ("y", "yes", "t", "true", "on", "1"):
return 1
elif val in ("n", "no", "f", "false", "off", "0"):
if val in ("n", "no", "f", "false", "off", "0"):
return 0
raise ValueError("invalid truth value %r" % (val,))

Expand All @@ -34,15 +34,10 @@ class Var:
API_HASH: str = getenv("API_HASH", "").strip()
STRING_SESSION: str = getenv("STRING_SESSION", "").strip()
DATABASE_URL: str = (
lambda c: c.replace(c.split("://")[0], "postgresql+psycopg2")
if c.startswith(
(
"postgres:",
"postgresql:",
)
lambda c: (
c.replace(c.split("://")[0], "postgresql+asyncpg") if c.startswith(("postgres:", "postgresql:")) else c
)
else c
)(getenv("DATABASE_URL", "sqlite:///./getter.db").strip())
)(getenv("DATABASE_URL", "sqlite+aiosqlite:///./getter.db").strip())
BOTLOGS: int = int(getenv("BOTLOGS", "0").strip())
HANDLER: str = getenv("HANDLER", ".").strip()
NO_HANDLER: bool = tobool(getenv("NO_HANDLER", "false").strip())
Expand All @@ -53,12 +48,12 @@ class Var:


try:
tz = timezone(Var.TZ)
tz = ZoneInfo(Var.TZ)
except BaseException:
_ = "Asia/Jakarta"
print("An error or unknown TZ :", Var.TZ)
print("Set default TZ as", _)
tz = timezone(_)
tz = ZoneInfo(_)

if not (
Var.HANDLER.lower().startswith(
Expand All @@ -81,16 +76,16 @@ class Var:
)
):
hl = "."
print("Your HANDLER [ {} ] is not supported.".format(Var.HANDLER))
print(f"Your HANDLER [ {Var.HANDLER} ] is not supported.")
print("Set default HANDLER as dot [ .command ]")
else:
hl = "".join(Var.HANDLER.split())

BOTLOGS_CACHE: typing.Set[int] = set()
DEV_CMDS: typing.Dict[str, typing.List[str]] = {}
SUDO_CMDS: typing.Dict[str, typing.List[str]] = {}
INVITE_WORKER: typing.Dict[str, typing.Any] = {}
CALLS: typing.Dict[int, typing.Any] = {}
BOTLOGS_CACHE: list[int] = []
DEV_CMDS: dict[str, list[str]] = {}
SUDO_CMDS: dict[str, list[str]] = {}
INVITE_WORKER: dict[str, Any] = {}
CALLS: dict[int, Any] = {}
TESTER = {5215824623}
# va, vn, en, xl
DEVS = {
Expand All @@ -101,4 +96,4 @@ class Var:
-1001699144606,
-1001700971911,
}
del typing, b64decode, ascii_lowercase, load_dotenv, find_dotenv, timezone
del Any, b64decode, ascii_lowercase, ZoneInfo, load_dotenv, find_dotenv
1 change: 1 addition & 0 deletions getter/core/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# ruff: noqa: F401, F403
# getter < https://t.me/kastaid >
# Copyright (C) 2022-present kastaid
#
Expand Down
77 changes: 40 additions & 37 deletions getter/core/base_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@
import importlib.util
import os
import sys
import typing
from asyncio import sleep, Future
from collections.abc import Coroutine
from inspect import getmembers
from platform import version, machine
from random import choice
from time import time
from typing import Any, NoReturn
from telethon.client.telegramclient import TelegramClient
from telethon.errors import (
ApiIdInvalidError,
Expand All @@ -32,12 +33,19 @@
__version__,
LOOP,
)
from getter.config import Var, DEVS
from getter.core.db import sgvar
from getter.core.functions import display_name
from getter.core.property import do_not_remove_credit, get_blacklisted
from getter.core.utils import time_formatter
from getter.config import (
Var,
tz,
hl,
INVITE_WORKER,
DEVS,
)
from getter.logger import LOG, TelethonLogger
from .db import sgvar
from .functions import display_name
from .helper import plugins_help
from .property import do_not_remove_credit, get_blacklisted
from .utils import time_formatter


class ReverseList(list):
Expand All @@ -48,10 +56,10 @@ def __iter__(self):
class KastaClient(TelegramClient):
def __init__(
self,
session: typing.Union[str, Session],
api_id: typing.Optional[int] = None,
api_hash: typing.Optional[str] = None,
bot_token: typing.Optional[str] = None,
session: str | Session,
api_id: int | None = None,
api_hash: str | None = None,
bot_token: str | None = None,
*args,
**kwargs,
):
Expand All @@ -75,22 +83,18 @@ def __init__(
self.dc_id = self.session.dc_id

def __repr__(self):
return "<Kasta.Client:\n self: {}\n id: {}\n bot: {}\n>".format(
self.full_name,
self.uid,
self._bot,
)
return f"<Kasta.Client:\n self: {self.full_name}\n id: {self.uid}\n bot: {self._bot}\n>"

@property
def __dict__(self) -> typing.Optional[dict]:
def __dict__(self) -> dict | None:
if self.me:
return self.me.to_dict()

async def start_client(self, **kwargs) -> None:
self.log.info("Trying to login...")
do_not_remove_credit()
await sleep(choice((4, 6, 8)))
try:
await sleep(choice((3, 6)))
await self.start(**kwargs)
self._bot = await self.is_bot()
if not self._bot:
Expand All @@ -102,34 +106,24 @@ async def start_client(self, **kwargs) -> None:
self.session.set_dc(opt.id, opt.ip_address, opt.port)
self.session.save()
break
await sleep(5)
await sleep(3)
self.me = await self.get_me()
if self.me.bot:
me = f"@{self.me.username}"
else:
self.me.phone = None
me = self.full_name
await sleep(5)
await sleep(3)
if self.uid not in DEVS:
KASTA_BLACKLIST = await get_blacklisted(
url="https://raw.githubusercontent.com/kastaid/resources/main/kastablacklist.py",
attempts=6,
fallbacks=None,
)
if self.uid in KASTA_BLACKLIST:
self.log.error(
"({} - {}) YOU ARE BLACKLISTED !!".format(
me,
self.uid,
)
)
self.log.error(f"({me} - {self.uid}) YOU ARE BLACKLISTED !!")
sys.exit(1)
self.log.success(
"Logged in as {} [{}]".format(
me,
self.uid,
)
)
self.log.success(f"Logged in as {me} [{self.uid}]")
except (ValueError, ApiIdInvalidError):
self.log.critical("API_ID and API_HASH combination does not match, please re-check! Quitting...")
sys.exit(1)
Expand All @@ -145,10 +139,10 @@ async def start_client(self, **kwargs) -> None:
self.log.exception(f"[KastaClient] - {err}")
sys.exit(1)

def run_in_loop(self, func: typing.Coroutine[typing.Any, typing.Any, None]) -> typing.Any:
def run_in_loop(self, func: Coroutine[Any, Any, None]) -> Any:
return self.loop.run_until_complete(func)

def run(self) -> typing.NoReturn:
def run(self) -> NoReturn:
try:
self.run_until_disconnected()
except InvalidBufferError as err:
Expand All @@ -174,10 +168,13 @@ def add_handler(
return
self.add_event_handler(func, *args, **kwargs)

def reboot(self, message: typ.Message) -> typing.NoReturn:
async def reboot(
self,
message: typ.Message,
) -> NoReturn:
try:
chat_id = message.chat_id or message.from_id
sgvar("_reboot", f"{chat_id}|{message.id}")
await sgvar("_reboot", f"{chat_id}|{message.id}")
except BaseException:
pass
try:
Expand All @@ -200,6 +197,12 @@ def load_plugin(
name = f"getter.plugins.custom.{plug}"
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
mod.Var = Var
mod.tz = tz
mod.hl = hl
mod.INVITE_WORKER = INVITE_WORKER
mod.DEVS = DEVS
mod.plugins_help = plugins_help
spec.loader.exec_module(mod)
self._plugins[plug] = mod
self.log.success(f"Successfully loaded custom plugin {plug}!")
Expand All @@ -215,14 +218,14 @@ def unload_plugin(
) -> None:
name = self._plugins[plugin].__name__
for x in reversed(range(len(self._event_builders))):
ev, cb = self._event_builders[x]
_, cb = self._event_builders[x]
if cb.__module__ == name:
del self._event_builders[x]
del self._plugins[plugin]
self.log.success(f"Removed custom plugin {plugin}!")

@property
def all_plugins(self) -> typing.List[typing.Dict[str, str]]:
def all_plugins(self) -> list[dict[str, str]]:
return [
{
"path": ".".join(str(_.resolve()).replace(".py", "").split("/")[-2:]),
Expand Down
Loading

0 comments on commit 1818617

Please sign in to comment.