async def __init(self, configuration, loop):
        await self.__client.get_dialogs()
        # await self.__client.get_entity(89616296) # свея
        self.__client.on(
            ChatAction(configuration.group_id,
                       func=lambda __event: __event.user_joined or __event.
                       user_added))(self.__on_new_user_in_group, )

        print("User bot configured")
Example #2
0
        def decorator(function):
            async def func_callback(event):
                try:
                    await function(event)
                except Exception as e:
                    self.log.error(
                        f"Function '{function.__name__}' stopped due to an unhandled exception",
                        exc_info=True if self.traceback else False)

            tgclient.add_event_handler(func_callback, ChatAction(**args))
            return func_callback
Example #3
0
        def decorator(function):
            async def func_callback(event):
                try:
                    await function(event)
                except Exception as e:
                    self.log.error(
                        f"Function '{function.__name__}' stopped due to an unhandled exception",
                        exc_info=True if self.traceback else False)

            try:
                tgclient.add_event_handler(func_callback,
                                           ChatAction(*args, **kwargs))
            except Exception as e:
                self.log.error(f"Failed to add a chat action feature to client "\
                               f"(in function '{function.__name__}')",
                               exc_info=True if self.traceback else False)
                return None
            return func_callback
Example #4
0
        def decorator(function):
            caller_name = basename(
                getouterframes(currentframe(), 2)[1].filename)[:-3]

            async def func_callback(event):
                try:
                    await function(event)
                except Exception:
                    self.log.error(
                        f"Function '{function.__name__}' stopped "
                        "due to an unhandled exception",
                        exc_info=True if self.traceback else False)

            try:
                _tgclient.add_event_handler(func_callback,
                                            ChatAction(*args, **kwargs))
                update_handlers(caller_name, func_callback)
            except Exception:
                self.log.error(
                    f"Failed to add a chat action feature to "
                    f"client (in function '{function.__name__}')",
                    exc_info=True if self.traceback else False)
                return None
            return func_callback
Example #5
0
from requests import get
from telethon.errors import ChatAdminRequiredError
from telethon.events import ChatAction
from telethon.tl.types import ChannelParticipantsAdmins
from telethon.utils import get_display_name

from ..Config import Config
from ..sql_helper.gban_sql_helper import get_gbanuser, is_gbanned
from ..utils import is_admin
from . import BOTLOG, BOTLOG_CHATID, catub, edit_or_reply, logging, spamwatch

LOGS = logging.getLogger(__name__)
plugin_category = "admin"
if Config.ANTISPAMBOT_BAN:

    @catub.on(ChatAction())
    async def anti_spambot(event):  # sourcery no-metrics
        if not event.user_joined and not event.user_added:
            return
        user = await event.get_user()
        catadmin = await is_admin(event.client, event.chat_id,
                                  event.client.uid)
        if not catadmin:
            return
        catbanned = None
        adder = None
        ignore = None
        if event.user_added:
            try:
                adder = event.action_message.sender_id
            except AttributeError:
Example #6
0
    def __init__(self,
                 session: str,
                 api_id: int,
                 api_hash: str,
                 loop: asyncio.AbstractEventLoop,
                 bot_id: int,
                 chats: Iterable[int] = tuple()):
        """
        Need to create a client with API key, hash, and a session file
        Need a list of whitelisted chat IDs

        Create a queue for incoming messages.

        Args:
            session: Session authorization string
            api_id: API ID of Telegram client
            api_hash: API Hash of Telegram client
            loop: Event loop to run the client on, (can be provided by ``pytest-asyncio``)
        """

        # Build proxy parameters
        # Currently only support SOCKS5 proxy in ALL_PROXY environment variable
        proxy_env = os.environ.get('all_proxy') or os.environ.get('ALL_PROXY')
        if proxy_env and proxy_env.startswith('socks5://'):
            from socks import SOCKS5
            hostname, port, username, password = parse_socks5_link(proxy_env)
            proxy: Optional[Tuple] = (SOCKS5, hostname, port, True, username,
                                      password)
        else:
            proxy = None

        # Telethon client to use
        self.client: TelegramClient = TelegramClient(StringSession(session),
                                                     api_id,
                                                     api_hash,
                                                     proxy=proxy,
                                                     loop=loop,
                                                     sequential_updates=True)

        # Queue for incoming messages
        self.queue: "asyncio.queues.Queue[EventCommon]" = asyncio.queues.Queue(
        )

        # Collect mappings from message ID to its chat (as Telegram API is not sending them)
        self.message_chat_map: Dict[int, TypeInputPeer] = dict()

        self.chats = list(map(abs, chats))
        self.client.parse_mode = "html"
        self.client.add_event_handler(
            self.new_message_handler,
            NewMessage(chats=self.chats, incoming=True, from_users=[bot_id]))
        # self.client.add_event_handler(self.new_message_handler,
        #                               NewMessage(incoming=True))
        self.client.add_event_handler(self.deleted_message_handler,
                                      MessageDeleted())
        self.client.add_event_handler(self.update_handler,
                                      UserUpdate(chats=self.chats))
        self.client.add_event_handler(self.update_handler,
                                      MessageEdited(chats=self.chats))
        self.client.add_event_handler(self.update_handler,
                                      ChatAction(chats=self.chats))

        self.logger = logging.getLogger(__name__)