Ejemplo n.º 1
0
from telethon import events
from telethon.utils import pack_bot_file_id

from jarvis import CMD_HELP
from jarvis.plugins.sql_helper.welcome_sql import (
    add_welcome_setting,
    get_current_welcome_settings,
    rm_welcome_setting,
    update_previous_welcome,
)
from jarvis.utils import admin_cmd


@jarvis.on(events.ChatAction())  # pylint:disable=E0602
async def _(event):
    cws = get_current_welcome_settings(event.chat_id)
    if cws:
        # logger.info(event.stringify())
        """user_added=False,
        user_joined=True,
        user_left=False,
        user_kicked=False,"""
        if event.user_joined:
            if cws.should_clean_welcome:
                try:
                    await bot.delete_messages(  # pylint:disable=E0602
                        event.chat_id, cws.previous_welcome
                    )
                except Exception as e:  # pylint:disable=C0103,W0703
                    logger.warn(str(e))  # pylint:disable=E0602
            a_user = await event.get_user()
Ejemplo n.º 2
0
 def decorator(func):
     telethn.add_event_handler(func, events.ChatAction(**args))
     return func
Ejemplo n.º 3
0
                c = words.index(word)
                link = (
                    f"t.me/{event.chat.username}/{event.message.id}"
                    if event.chat.username
                    else f"Occurred in Private Chat - {event.chat.title}"
                )
                logmsg = f"""$AUTOSCAN\n**Scanned user:** [{event.from_id.user_id}](tg://user?id={event.from_id.user_id})\n**Reason:** 0x{c}\n**Chat:** {link}\n**Hue Color:** Yellow-green\n**Message:** {event.text}"""
                await System.send_message(Sibyl_logs, logmsg)
                System.processed += 1
                System.processing -= 1
                return
    System.processed += 1
    System.processing -= 1


@System.bot.on(events.ChatAction(func=lambda e: e.user_joined))
async def auto_wlc_gban(event):
    System.processing += 1
    user = await event.get_user()
    if user.id in MANAGERS or user.id in CARDINAL:
        return
    words = await wlc_collection.get_wlc_bl()
    if words:
        text = user.first_name
        if user.last_name:
            text = text + " " + user.last_name
        for word in words:
            pattern = r"( |^|[^\w])" + word + r"( |$|[^\w])"
            if re.search(pattern, text, flags=re.IGNORECASE):
                c = words.index(word)
                logmsg = f"""$AUTOSCAN\n**Scanned user:** [{user.id}](tg://user?id={user.id})\n**Reason:** 1x{c}\n**User joined and blacklisted string in name**\n**Matched String:** {word}\n"""
        # don't log bots
        return
    if sender.verified:
        # don't log verified accounts
        return

    if not pmpermit_sql.is_approved(chat_id):
        # pm permit
        await do_pm_permit_action(chat_id, event)

    if not no_log_pms_sql.is_approved(chat_id):
        # log pms
        await do_log_pm_action(chat_id, message_text, message_media)


@borg.on(events.ChatAction(blacklist_chats=Config.UB_BLACK_LIST_CHAT))
async def on_new_chat_action_message(event):
    if Config.PM_LOGGR_BOT_API_ID is None:
        return
    # logger.info(event.stringify())
    chat_id = event.chat_id
    message_id = event.action_message.id

    if event.created or event.user_added:
        added_by_users = event.action_message.action.users
        if borg.uid in added_by_users:
            added_by_user = event.action_message.from_id
            # someone added me to chat
            the_message = ""
            the_message += "#MessageActionChatAddUser\n\n"
            the_message += f"[User](tg://user?id={added_by_user}): `{added_by_user}`\n"
Ejemplo n.º 5
0
            for entity in entities:
                if isinstance(
                        entity,
                    (types.MessageEntityTextUrl, types.MessageEntityUrl)):
                    is_url = True
        if is_url:
            try:
                await event.delete()
            except Exception as e:
                await event.reply(
                    "I don't seem to have ADMIN permission here. \n`{}`".
                    format(str(e)))
                update_lock(peer_id, "url", False)


@WhiteEye.on(events.ChatAction())  # pylint:disable=E0602
async def _(event):
    # TODO: exempt admins from locks
    # check for "lock" "bots"
    if is_locked(event.chat_id, "bots"):
        # bots are limited Telegram accounts,
        # and cannot join by themselves
        if event.user_added:
            users_added_by = event.action_message.from_id
            is_ban_able = False
            rights = types.ChatBannedRights(until_date=None,
                                            view_messages=True)
            added_users = event.action_message.action.users
            for user_id in added_users:
                user_obj = await borg.get_entity(user_id)
                if user_obj.bot:
Ejemplo n.º 6
0
    if event.chat_id == Sibyl_logs:
        return
    text = event.text
    words = await db.get_blacklist()
    if words:
        for word in words:
            pattern = r"( |^|[^\w])" + word + r"( |$|[^\w])"
            if re.search(pattern, text, flags=re.IGNORECASE):
                c = words.index(word)
                link = f"t.me/{event.chat.username}/{event.message.id}" if event.chat.username else f"Occurred in Private Chat - {event.chat.title}"
                logmsg = f"""$AUTOSCAN\n**Scanned user:** [{event.from_id}](tg://user?id={event.from_id})\n**Reason:** 0x{c}\n**Chat:** {link}\n**Hue Color:** Yellow-green\n**Message:** {event.text}"""
                await System.send_message(Sibyl_logs, logmsg)
                return


@System.on(events.ChatAction(func=lambda e: e.user_joined))  # pylint:disable=E0602
async def auto_wlc_gban(event):
    user = await event.get_user()
    if user.id in ENFORCERS or user.id in SIBYL:
        return
    words = await wlc_collection.get_wlc_bl()
    if words:
        text = user.first_name
        if user.last_name: text = text + " " + user.last_name
        for word in words:
            pattern = r"( |^|[^\w])" + word + r"( |$|[^\w])"
            if re.search(pattern, text, flags=re.IGNORECASE):
                c = words.index(word)
                logmsg = f"""$AUTOSCAN\n**Scanned user:** [{user.id}](tg://user?id={user.id})\n**Reason:** 1x{c}\n**User joined and blacklisted string in name**\n**Matched String:** {word}\n"""
                await System.send_message(Sibyl_logs, logmsg)
Ejemplo n.º 7
0
            await event.reply(beautiful)
        else:
            await event.reply(beautifuln)


@UltraBot.on(events.NewMessage(func=lambda e: e.is_private))
async def real_nigga(event):
    if already_added(event.sender_id):
        pass
    elif not already_added(event.sender_id):
        add_usersid_in_db(event.sender_id)
        await UltraBot.send_message(Config.LOG_CHAT,
                                    f"**New User :** `{event.sender_id}`")


@UltraBot.on(events.ChatAction())
async def _(event):
    if event.chat_id == Config.LOG_CHAT:
        return
    okbruh = await UltraBot.get_me()
    if event.user_joined or event.user_added == str(okbruh):
        lol = event.chat_id
        if already_added(event.chat_id):
            pass
        elif not already_added(event.chat_id):
            add_usersid_in_db(event.chat_id)
            await UltraBot.send_message(Config.LOG_CHAT,
                                        f"**New ChatGroup :** `{lol}`")


@UltraBot.on(events.NewMessage(pattern="^/start ?(.*)"))
Ejemplo n.º 8
0
            for entity in entities:
                if isinstance(
                        entity,
                    (types.MessageEntityTextUrl, types.MessageEntityUrl)):
                    is_url = True
        if is_url:
            try:
                await event.delete()
            except Exception as e:
                await event.reply(
                    "I don't seem to have ADMIN permission here. \n`{}`".
                    format(str(e)))
                update_lock(peer_id, "url", False)


@ninjadeep.on(events.ChatAction())  # pylint:disable=E0602
async def _(event):
    # TODO: exempt admins from locks
    # check for "lock" "bots"
    if is_locked(event.chat_id, "bots"):
        # bots are limited Telegram accounts,
        # and cannot join by themselves
        if event.user_added:
            users_added_by = event.action_message.from_id
            is_ban_able = False
            rights = types.ChatBannedRights(until_date=None,
                                            view_messages=True)
            added_users = event.action_message.action.users
            for user_id in added_users:
                user_obj = await borg.get_entity(user_id)
                if user_obj.bot:
Ejemplo n.º 9
0
def main():
    logging.basicConfig(level=logging.ERROR)
    extract_configs()
    setup_telegram_connection()
    setup_sqlite_connection('logs.sqlite')

    @CLIENT.on(events.NewMessage())
    async def handlerNewMessage(event):
        try:
            await record_message(event.message, CLIENT)
        except KeyboardInterrupt:
            raise
        except Exception as e:
            print(e)

    @CLIENT.on(events.ChatAction())
    async def handlerChatAction(event):
        event_name = type(event.original_update.message.action).__name__
        date = event.original_update.message.date
        date = date.strftime('%Y.%d.%m %H:%M:%S %a')
        attributes = event.original_update.message.action.__dict__
        attributes['id'] = event.original_update.message.id
        attributes['to_id'] = list(
            event.original_update.message.to_id.__dict__.values())[
                0]  ###########
        attributes['event_name'] = event_name
        attributes['date'] = date
        for k, v in attributes.items():
            if type(v) == list:
                attributes[k] = str(v)
        columns = ','.join(str(e) for e in list(attributes.keys()))
        placeholders = ':' + ', :'.join(
            str(e) for e in list(attributes.keys()))
        CURSOR.execute(
            "INSERT INTO ChatActions (%s) VALUES (%s)" %
            (columns, placeholders), attributes)
        CONN.commit()

    @CLIENT.on(events.MessageEdited())
    async def handlerMessageEdited(event):
        _id = event.message.id
        _to_id = list(event.message.to_id.__dict__.values())[0]
        _from_id = event.message.from_id
        _message = event.message.message
        _date = event.message.date.strftime('%Y.%d.%m %H:%M:%S %a')
        CURSOR.execute(
            "UPDATE Messages SET edited=1 WHERE to_id=:to_id AND id=:id", {
                'id': _id,
                'to_id': _to_id
            })
        CURSOR.execute(
            "INSERT INTO Edited VALUES (:id, :to_id, :from_id, :message, :date)",
            {
                'id': _id,
                'to_id': _to_id,
                'from_id': _from_id,
                'message': _message,
                'date': _date
            })
        CONN.commit()

    @CLIENT.on(events.MessageDeleted())
    async def handlerMessageDeleted(event):
        print(event)
        for i in range(len(event.deleted_ids)):
            attributes = []
            values = []
            attributes.append("id=" + str(event.deleted_ids[i]))
            values.append(str(event.deleted_ids[i]))
            if isinstance(event.original_update, UpdateDeleteChannelMessages):
                attributes.append("to_id=" +
                                  str(event.original_update.channel_id))
                values.append(str(event.original_update.channel_id))

            CURSOR.execute("UPDATE Messages SET deleted=1 WHERE %s" %
                           ' AND '.join(attributes))
            #for i in range(len(event.deleted_ids)):
            current_time = datetime.datetime.now()
            values.append(current_time.strftime('"%Y.%d.%m %H:%M:%S %a"'))
            CURSOR.execute("INSERT INTO Deleted VALUES (%s)" %
                           ', '.join(values))
        CONN.commit()

    @CLIENT.on(events.UserUpdate())
    async def handlerUserUpdate(event):
        id = event.original_update.user_id
        try:
            user = (await CLIENT(
                GetFullUserRequest(await CLIENT.get_input_entity(id)))).user
            username = user.username
            first_name = user.first_name
            last_name = user.last_name
        except Exception as e:
            print(e)
            username = ""
            first_name = ""
            last_name = ""
        event_name = type(event.original_update).__name__
        attributes = event.original_update.status.__dict__
        if len(list(attributes.values())) > 0:
            date = list(attributes.values())[0]
        else:
            date = [0, 0, 0, 0, 0, 0]
        date = date.strftime('%Y.%d.%m %H:%M:%S %a')
        CURSOR.execute(
            "INSERT INTO UserUpdates VALUES(:id, :username, :firstName, :lastName, :update, :date)",
            {
                'id': id,
                'username': username,
                'firstName': first_name,
                'lastName': last_name,
                'update': event_name,
                'date': date
            })
        CONN.commit()

    CLIENT.start()
    CLIENT.run_until_disconnected()
    CONN.close()
Ejemplo n.º 10
0
ENABLE_LOG = True
LOGGING_CHATID = Config.PRIVATE_CHANNEL_BOT_API_ID
BANNED_RIGHTS = ChatBannedRights(
    until_date=None,
    view_messages=True,
    send_messages=True,
    send_media=True,
    send_stickers=True,
    send_gifs=True,
    send_games=True,
    send_inline=True,
    embed_links=True,
)


@borg.on(events.ChatAction(func=lambda e: e.is_group))
async def spam_watch_(event):
    chat = await event.get_chat()
    if Config.SPAM_WATCHAPI:
        client = spamwatch.Client(Config.SPAM_WATCH_API)
        user = await event.get_user()
        try:
            if (chat.admin_rights or chat.creator):
                if (event.user_joined or event.user_added):
                    try:
                        ban = client.get_ban(event.action_message.from_id)
                        if ban:
                            await borg(
                                EditBannedRequest(event.chat_id,
                                                  event.action_message.from_id,
                                                  BANNED_RIGHTS))
Ejemplo n.º 11
0
channel = xchannel.replace("@", "")


# join check
async def get_user_join(id):
    ok = True
    try:
        await BotzHub(GetParticipantRequest(channel=channel, user_id=id))
        ok = True
    except UserNotParticipantError:
        ok = False
    return ok


@BotzHub.on(events.ChatAction())
async def _(event):
    if on_join is False:
        return
    if event.user_joined or event.user_added:
        user = await event.get_user()
        chat = await event.get_chat()
        title = chat.title if chat.title else "this chat"
        pp = await BotzHub.get_participants(chat)
        count = len(pp)
        mention = f"[{get_display_name(user)}](tg://user?id={user.id})"
        name = user.first_name
        last = user.last_name
        if last:
            fullname = f"{name} {last}"
        else:
Ejemplo n.º 12
0
from telethon.tl.types import InputPeerEmpty
from telethon.tl.types import ChannelAdminLogEventsFilter
from telethon.tl.types import ChannelAdminLogEventActionParticipantJoin
from telethon.tl.types import InputUserSelf
from telethon.tl.types import InputUser
import asyncio
import logging


api_id = 3409046
api_hash = '48ae9fbdf79edda291e1fa5796fc4665'
#phone_number = '+528132341246'
################################################
channel = '@pruebastienda'

@events.register(events.ChatAction(func=lambda e: e.action_message is None))
def chat_action_empty(event: events.ChatAction.Event):
    #print(event.stringify())
    print('this event')
async def main():
    client = TelegramClient('sessionname', api_id, api_hash)  # feel free to edit %sessionname% as you want
    client.add_event_handler(chat_action_empty)
    await client.start()
    me = await client.get_me()
    #print('Logged in as {} with Telethon version {}'.format(me.username, TelegramClient.__version__))
    await client.run_until_disconnected()
asyncio.get_event_loop().run_until_complete(main())

async def handler(event):
# event.input_chat may be None, use event.get_input_chat()
Ejemplo n.º 13
0
__author__ = 'smailzhu'

parser = ConfigParser()
parser.read('config.ini', encoding='utf-8')
api_id = int(parser.get('api', 'id'))
api_hash = parser.get('api', 'hash')
try:
    target_chat = int(parser.get('target', 'chat'))
except Exception:
    target_chat = parser.get('target', 'chat')

with TelegramClient('session_name', api_id, api_hash) as client:
    chat = client.get_entity(target_chat)


    @client.on(events.ChatAction(chats=target_chat))
    async def handler(event):
        if not event.user_added:
            return
        from_id = event.action_message.from_id
        msg = f"You have been invited by id: `{from_id}` to this spam group, " \
            "Please click report button above and forward this message to @HexJudge\n" \
            f"您已經被 id: `{from_id}` 給拉入到此騷擾群組,請點擊畫面上方回報來檢舉並轉傳此訊息至 @HexJudge"
        await event.reply(msg)


    client.start()
    client.run_until_disconnected()
    client.disconnect()
Ejemplo n.º 14
0
channel = xchannel.replace("@", "")


# join check
async def get_user_join(id):
    ok = True
    try:
        await coffinx(GetParticipantRequest(channel=channel, user_id=id))
        ok = True
    except UserNotParticipantError:
        ok = False
    return ok


@coffinx.on(events.ChatAction())
async def _(event):
    if on_join is False:
        return
    if event.user_joined or event.user_added:
        user = await event.get_user()
        chat = await event.get_chat()
        title = chat.title if chat.title else "this chat"
        pp = await BotzHub.get_participants(chat)
        count = len(pp)
        mention = f"[{get_display_name(user)}](tg://user?id={user.id})"
        name = user.first_name
        last = user.last_name
        if last:
            fullname = f"{name} {last}"
        else:
Ejemplo n.º 15
0
from telethon.tl.functions.channels import JoinChannelRequest
from telethon.errors import ChannelPrivateError, ChannelBannedError


# How often to attempt to rejoin
REFETCH_TIME = 90
chat = "@telethonofftopic"


@borg.on(events.NewMessage(chats=chat))
async def last_msg_draft(event):
    last_msg = event.id
    storage.last_msg = last_msg


@borg.on(events.ChatAction(chats=chat, func=lambda e: e.user_joined))
async def joined(event):
    if event.user_id != borg.uid:
        return
    last_msg = storage.last_msg or 0
    await borg(SaveDraftRequest(peer=chat, message="", reply_to_msg_id=last_msg))


async def fetch_chats():
    while True:
        try:
            await borg(JoinChannelRequest(chat))
        except (ChannelBannedError, ChannelPrivateError):
            logger.info("Still banned")
            await sleep(REFETCH_TIME + 60)
        await sleep(REFETCH_TIME)
Ejemplo n.º 16
0
See /help for more info.
"""

from asyncio import sleep
from telethon import events, errors


# /start
@borg.on(borg.cmd(r"start$"))
async def on_start(event):
    if event.is_private:  # If command was sent in private
        await event.respond(__doc__, link_preview=False)


# Reply when added to group
@borg.on(events.ChatAction(func=lambda e: e.user_added and e.is_group))
async def added_to_group(event):
    me = (await event.client.get_me()).id

    response = None
    # Check which users were added to the group,
    # if the bot is amongst them, send the message
    for u in event.users:
        if me == u.id:
            response = await event.respond(__doc__, link_preview=False)

    if not response:
        return

    # Delete the message after a minute
    await sleep(60)
Ejemplo n.º 17
0
# Ultroid - UserBot
# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.

from telethon import events

from . import *


@asst.on(events.ChatAction(func=lambda x: x.user_added))
async def dueha(e):
    user = await e.get_user()
    if not user.is_self:
        return
    sm = udB.get_key("ON_MNGR_ADD")
    if sm == "OFF":
        return
    if not sm:
        sm = "Thanks for Adding me :)"
    await e.reply(sm, link_preview=False)
Ejemplo n.º 18
0
    format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s',
    level=logging.WARNING)
from telethon import events
from telethon.tl.functions.channels import EditBannedRequest
from telethon.tl.types import ChatBannedRights

CHATS_TO_MONITOR_FOR_ADDED_BOTS = [
    # add the ID of the groups (Use .get_id command)
    # seperated by commas
    # usernames also work, but it is pointless,
    # since non admin users cannot add bots to
    # public groups (Telegram Limitation)
]


@borg.on(events.ChatAction(chats=CHATS_TO_MONITOR_FOR_ADDED_BOTS))  # pylint:disable=E0602
async def kick_if_bots(event):
    if event.user_added:
        users_added_by = event.action_message.from_id
        if users_added_by == borg.uid:
            logger.info("Don't BAN yourself")
            return False
        is_ban_able = False
        rights = ChatBannedRights(until_date=None, view_messages=True)
        added_users = event.action_message.action.users
        for user_id in added_users:
            user_obj = await borg.get_entity(user_id)
            if user_obj.bot:
                is_ban_able = True
                try:
                    # kick the bot
Ejemplo n.º 19
0
            for entity in entities:
                if isinstance(
                        entity,
                    (types.MessageEntityTextUrl, types.MessageEntityUrl)):
                    is_url = True
        if is_url:
            try:
                await event.delete()
            except Exception as e:
                await event.reply(
                    "I don't seem to have ADMIN permission here. \n`{}`".
                    format(str(e)))
                update_lock(peer_id, "url", False)


@friday.on(events.ChatAction())  # pylint:disable=E0602
async def _(event):
    # TODO: exempt admins from locks
    # check for "lock" "bots"
    if is_locked(event.chat_id, "bots"):
        # bots are limited Telegram accounts,
        # and cannot join by themselves
        if event.user_added:
            users_added_by = event.action_message.sender_id
            is_ban_able = False
            rights = types.ChatBannedRights(until_date=None,
                                            view_messages=True)
            added_users = event.action_message.action.users
            for user_id in added_users:
                user_obj = await borg.get_entity(user_id)
                if user_obj.bot:
Ejemplo n.º 20
0

def save_config():
    with open('config.json', 'w', encoding='utf-8') as f:
        json.dump(config, f, indent=4)


async def safe_delete_message(bot, delay, *args, **kwarg):
    await asyncio.sleep(delay)
    try:
        await bot(DeleteMessagesRequest(*args, **kwarg))
    except errors.BadRequestError:  # msg to delete not found
        pass


@events.register(events.ChatAction())
async def challenge_user(event):
    global config, current_challenges

    bot = event.client
    chat = event.chat
    target = event.user

    if event.user_added:
        me = await bot.get_me()
        if me.id in event.user_ids:
            async with config_lock:
                group_config = config.get(str(event.chat.id), config['*'])
                await event.respond(
                    message=group_config['msg_self_introduction'])
        return None
Ejemplo n.º 21
0
            for entity in entities:
                if isinstance(
                    entity, (types.MessageEntityTextUrl, types.MessageEntityUrl)
                ):
                    is_url = True
        if is_url:
            try:
                await event.delete()
            except Exception as e:
                await event.reply(
                    "I don't seem to have ADMIN permission here. \n`{}`".format(str(e))
                )
                update_lock(peer_id, "url", False)


@bot.on(events.ChatAction())
async def _(event):
    if not event.is_private:
        chat = await event.get_chat()
        admin = chat.admin_rights
        creator = chat.creator
        if not admin and not creator:
            return
    # check for "lock" "bots"
    if not is_locked(event.chat_id, "bots"):
        return
    # bots are limited Telegram accounts,
    # and cannot join by themselves
    if event.user_added:
        users_added_by = event.action_message.sender_id
        is_ban_able = False
Ejemplo n.º 22
0
        await event.reply("**This user is curently banned on this companion and it shouldn't be here**")
    rights = ChatBannedRights(
        until_date=None,
        view_messages=True,
        send_messages=True,
        send_media=True,
        send_stickers=True,
        send_gifs=True,
        send_games=True,
        send_inline=True,
        embed_links=True
    )
    await client(EditBannedRequest(chat.id, user, rights))


@client.on(events.ChatAction(chats=GBAN_ALLOWED_CHATS))
@client.log_exception
async def ban_on_join(event):
    chat = await event.get_chat()
    user = await event.get_user()
    if event.user_joined:
        if chat.creator or chat.admin_rights:
            if user.id in GBANNED_USERS:
                reason = GBANNED_USERS.get(user.id)
                if reason:
                    await event.reply("**This user is curently banned on this companion and it shouldn't be here**\n"
                                      f"__Reason:__ {reason}")
                else:
                    await event.reply("**This user is curently banned on this companion and it shouldn't be here**")
                rights = ChatBannedRights(
                    until_date=None,
Ejemplo n.º 23
0
            for entity in entities:
                if isinstance(
                        entity,
                    (types.MessageEntityTextUrl, types.MessageEntityUrl)):
                    is_url = True
        if is_url:
            try:
                await event.delete()
            except Exception as e:
                await event.reply(
                    "I don't seem to have ADMIN permission here. \n`{}`".
                    format(str(e)))
                update_lock(peer_id, "url", False)


@borg.on(events.ChatAction())
async def _(event):
    try:
        from sql_helpers.locks_sql import update_lock, is_locked
    except Exception as e:
        logger.info("DB_URI is not configured.")
        logger.info(str(e))
        return False
    # TODO: exempt admins from locks
    # check for "lock" "bots"
    if is_locked(event.chat_id, "bots"):
        # bots are limited Telegram accounts,
        # and cannot join by themselves
        if event.user_added:
            users_added_by = event.action_message.from_id
            is_ban_able = False
from telethon import events
from telethon.tl.functions.channels import EditBannedRequest
from telethon.tl.types import ChatBannedRights

from sample_config import Config

CHATS_TO_MONITOR_FOR_ADDED_BOTS = [
    # add the ID of the groups (Use .get_id command)
    # seperated by commas
    # usernames also work, but it is pointless,
    # since non admin users cannot add bots to
    # public groups (Telegram Limitation)
]


@borg.on(events.ChatAction(chats=CHATS_TO_MONITOR_FOR_ADDED_BOTS))
async def kick_if_bots(event):
    if event.user_added:
        users_added_by = event.action_message.from_id
        if users_added_by == borg.uid:
            logger.info("Don't BAN yourself")
            return False
        is_ban_able = False
        rights = ChatBannedRights(until_date=None, view_messages=True)
        added_users = event.action_message.action.users
        for user_id in added_users:
            user_obj = await borg.get_entity(user_id)
            if user_obj.bot:
                is_ban_able = True
                try:
                    # kick the bot
Ejemplo n.º 25
0
            elif user.id not in users_ignored:
                # TODO: when a account is deleted and recreated within one check interval, the
                # recreation message should be reported after the deletion message
                await report(
                    f"🆕 #u_{user.id} {render_user(user)} is #newly found:\n"
                    f"now is at {render_datetime()}")
                logger.debug(f"{user.id} is newly found")
                # TODO: avoid race condition
            now_blocked.append(user)
        if (serialized := serialize_vector(now_blocked)) != d:
            await blockedUsersStorage.store(serialized)
        tracked_user_ids = {user.id for user in now_blocked}


@client.on(
    events.ChatAction(func=lambda event: event.user_joined or event.user_added)
)
async def handler_user_join(event):
    # TODO: there is possibility that some of joining messages are discarded
    async with check_lock:
        for user in await event.get_users():
            if user.id in tracked_user_ids:
                chat = await event.get_chat()
                await report(
                    f"❕ #u_{user.id} {render_user(user)} #joined {render_chat(chat)}\nnow is at {render_datetime()}"
                )


# TODO: abstract blocked users manager like .contacts or .auth so that to avoid manually managing
#       tracked_user_ids
Ejemplo n.º 26
0
#!/usr/bin/env python3

import aiocron
from telethon import events, utils, errors


@userbot.on(events.ChatAction(chats="@emacszh"))
async def remove_join_messages(event) -> None:
    """remove user joinning message."""
    if event.user_joined:
        await event.delete()


@aiocron.crontab("* 2 * * *")
async def remove_deleted_account(channel: str = "@emacszh") -> None:
    """remove all deleted account from channel everyday."""
    async for user in userbot.iter_participants(channel):
        if user.deleted:
            try:
                await userbot.kick_participant(channel, user)
            except errors.rpcerrorlist.UserAdminInvalidError:
                # 群主踢不掉
                pass
Ejemplo n.º 27
0
    if isinstance(entity, tl.types.ChannelForbidden):
        return
    if isinstance(entity, tl.types.Channel) and entity.left:
        return
    channel = await borg.get_input_entity(channel_id)
    self_participant = await borg(
        GetParticipantRequest(channel, InputUserSelf()))
    if not isinstance(
            self_participant,
        (tl.types.ChannelParticipantSelf, tl.types.ChannelParticipantAdmin)):
        return
    inviter_id = self_participant.participant.inviter_id
    await on_added(inviter_id, channel_id)


@borg.on(events.ChatAction(func=lambda e: e.user_added or e.created))
async def on_group_added(e):
    am = e.action_message
    if borg.uid not in getattr(am.action, 'users', []):
        return
    await on_added(am.from_id, am.to_id)


@borg.on(
    events.NewMessage(pattern=r"\.auth",
                      outgoing=True,
                      func=lambda e: e.is_private))
async def on_auth(e):
    logger.info(f'Adding temporary auth for {e.chat_id}')
    add_auths[e.chat_id] = time.time() + AUTH_TIME
    await e.delete()
Ejemplo n.º 28
0
@System.on(events.NewMessage(incoming=True))
async def auto_gban_request(event):
    if event.from_id in ENFORCERS or event.from_id in SIBYL: return
    text = event.text
    words = await get_blacklist()
    sender = await event.get_sender()
    if event.chat_id == Sibyl_logs: return 
    if words:
      for word in words:
          pattern = r"( |^|[^\w])" + word + r"( |$|[^\w])"
          if re.search(pattern, text, flags=re.IGNORECASE):
                  await System.send_message(Sibyl_logs, f"$AUTO\nTriggered by: [{event.from_id}](tg://user?id={event.from_id})\nMessage: {event.text}")
                  return


@System.on(events.ChatAction())  # pylint:disable=E0602
async def auto_wlc_gban(event):
    user = await event.get_user()
    if user.id in ENFORCERS or user.id in SIBYL: return
    if event.user_joined:
      words = await get_wlc_bl()
      if words:
        text = user.first_name
        for word in words:
           pattern = r"( |^|[^\w])" + word + r"( |$|[^\w])"
           if re.search(pattern, text, flags=re.IGNORECASE):
                   await System.send_message(Sibyl_logs, f"$AUTO\nTriggered by: [{event.from_id}](tg://user?id={event.from_id})\nUser joined and blacklisted string in name\nMatched String = {word}")

__plugin_name__ ="blacklist" 

help_plus ="""
Ejemplo n.º 29
0
from telethon import events
from telethon.utils import pack_bot_file_id
from userbot.plugins.sql_helper.welcome_sql import get_current_welcome_settings, \
    add_welcome_setting, rm_welcome_setting, update_previous_welcome
from userbot.utils import admin_cmd


@bot.on(events.ChatAction())  # pylint:disable=E0602
async def _(event):
    cws = get_current_welcome_settings(event.chat_id)
    if cws:
        # logger.info(event.stringify())
        """user_added=False,
        user_joined=True,
        user_left=False,
        user_kicked=False,"""
        if event.user_joined:
            if cws.should_clean_welcome:
                try:
                    await bot.delete_messages(  # pylint:disable=E0602
                        event.chat_id, cws.previous_welcome)
                except Exception as e:  # pylint:disable=C0103,W0703
                    logger.warn(str(e))  # pylint:disable=E0602
            a_user = await event.get_user()
            chat = await event.get_chat()
            me = await bot.get_me()

            title = chat.title if chat.title else "this chat"
            participants = await event.client.get_participants(chat)
            count = len(participants)
            mention = "[{}](tg://user?id={})".format(a_user.first_name,
Ejemplo n.º 30
0
# From CatUserbot , And Yes I am Noob

from requests import get
from telethon import events
from telethon.errors import ChatAdminRequiredError
from telethon.tl.types import ChannelParticipantsAdmins

from FreakyUserbot import BOTLOG, BOTLOG_CHATID, LOGS, spamwatch
from FreakyUserbot.sql_helper.gban_sql import get_gbanuser, is_gbanned
from FreakyUserbot.utils import Freaky_on_cmd, is_admin

if Config.ANTI_SPAMBOT:

    @Freaky.on(events.ChatAction())
    async def anti_spambot(event):
        if not event.user_joined and not event.user_added:
            return
        chat = event.chat_id
        user = await event.get_user()
        freakadmin = await is_admin(bot, chat, bot.uid)
        if not freakadmin:
            return
        freakbanned = None
        adder = None
        ignore = None
        if event.user_added:
            try:
                adder = event.action_message.sender_id
            except AttributeError:
                return
        async for admin in event.client.iter_participants(