Beispiel #1
0
async def spam_watch_(event):
    chat = await event.get_chat()
    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))
                    else:
                        return
                except AttributeError:
                    return
                except BadRequestError:
                    return
                except ValueError:
                    return
                if ENABLE_LOG:
                    await event.client.send_message(
                        LOGGING_CHATID,
                        "#SPAMWATCH_BAN\n"
                        f"USER: [{user.first_name}](tg://user?id={user.id})\n"
                        f"CHAT: {event.chat.title}(`{event.chat_id}`)"
                    )
            else:
                return ""
        else:
            return ""
    except AttributeError:
        return
Beispiel #2
0
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 (not chat.admin_rights and not chat.creator
                    or not event.user_joined and not event.user_added):
                return ""
            try:
                ban = client.get_ban(user.id)
                if ban:
                    await event.client(
                        EditBannedRequest(event.chat_id, user.id,
                                          BANNED_RIGHTS))
                else:
                    return
            except AttributeError:
                return
            except BadRequestError:
                return
            except ValueError:
                return
            if ENABLE_LOG:
                await event.client.send_message(
                    Config.SPAM_WATCH_LOG_CHANNEL,
                    "#SPAMWATCH_BAN\n"
                    f"USER: [{user.first_name}](tg://user?id={user.id})\n"
                    f"CHAT: {event.chat.title}(`{event.chat_id}`)",
                )
        except AttributeError:
            return
Beispiel #3
0
async def spam_watch_(event):
    # user = await get_user_from_event(event)
    client = spamwatch.Client(Config.SPAM_WATCH_API)
    # ban = client.get_ban(event.from_id)
    user = await event.get_user()
    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))
                await event.client.send_message(
                    LOGGING_CHATID, "#SPAM_WATCH\n"
                    f"USER: [{user.first_name}](tg://user?id={user.id})\n"
                    f"CHAT: {event.chat.title}(`{event.chat_id}`)")
            else:
                return
        except BadRequestError:
            return
        if ENABLE_LOG:
            await event.client.send_message(
                LOGGING_CHATID, "#SPAM_WATCH_BAN\n"
                f"USER: [{user.first_name}](tg://user?id={user.id})\n"
                f"CHAT: {event.chat.title}(`{event.chat_id}`)")
Beispiel #4
0
async def parse_info(client, info):
    user_info = '╒═══「 ✨ **User Info** 」\n'
    user_info += f'│ • **First Name:** {info.mention}\n'
    if info.last_name:
        user_info += f'│ • **Last Name:** {info.last_name}\n'
    if info.dc_id:
        user_info += f'│ • **DC:** `{info.dc_id}`\n'
    if SPAMWATCH_API:
        sw = spamwatch.Client(SPAMWATCH_API)
        sw_stats = sw.get_ban(info.id)
        if sw_stats:
            user_info += '│ • **SW Blocked:** `{}`\n'.format(
                sw_stats.reason,
            )
    if info.username:
        user_info += f'│ • **Username:** @{info.username}\n'
    if not info.is_self:
        user_info += '│ • **Last Online:** `{}`\n'.format(LastOnline(info))
        user_info += '│ • **Common Chats:** `{}`\n'.format(
            len(
                (
                    await GetCommon(
                        client, info.id,
                    )
                ).chats,
            ),
        )
    user_info += f'╘══「 **ID:** `{info.id}` 」'
    return user_info
Beispiel #5
0
 async def handler(rkG):
     if rkG.user_joined or rkG.user_added and not rkG.chat_id in W_CHAT and SPAM_PROTECT and swapi and not event.is_private:
         chat = await rkG.get_chat()
         admin = chat.admin_rights
         creator = chat.creator
         if admin or creator:
             return
         sw = spamwatch.Client(swapi)
         guser = await rkG.get_user()
         try:
             sswatch = sw.get_ban(guser.id)
         except:
             return
         if sswatch:
             try:
                 await wolfs.edit_permissions(rkG.chat_id,
                                              guser.id,
                                              view_messages=False)
                 action = "`ban`"
                 return await rkG.reply(
                     f"`{WOLF_NNAME}:` ** This user is detected as spam by SpamWatch!!** \n"
                     f"**Reason **  : `{sswatch.reason}`\n"
                     f"**Victim Id**: [{guser.id}](tg://user?id={guser.id})\n"
                     f"**Action **  : {action}")
             except:
                 return
Beispiel #6
0
async def info(msg: Message):
    """ To check User's info """
    await msg.edit("```Checking...```")
    user_id = msg.input_str
    replied = msg.reply_to_message
    if not user_id:
        if replied:
            user_id = replied.forward_from.id if replied.forward_from else replied.from_user.id
        else:
            user_id = msg.from_user.id
    try:
        user = await msg.client.get_users(user_id)
    except Exception:
        await msg.edit("```I don't know that User...```", del_in=5)
        return
    await msg.edit("```Getiing Info...```")
    l_name = user.last_name or ''
    username = '******' + user.username if user.username else '`None`'
    common_chats = await msg.client.get_common_chats(user.id)
    user_info = f"""
**About [{user.first_name} {l_name}](tg://user?id={user.id})**:
  - **UserID**: `{user.id}`
  - **Username**: {username}
  - **Last Online**: `{last_online(user)}`
  - **Common Groups**: `{len(common_chats)}`
  - **Contact**: `{user.is_contact}`
        """
    if user:
        if Config.SPAM_WATCH_API:
            status = spamwatch.Client(Config.SPAM_WATCH_API).get_ban(user.id)
            if status is False:
                user_info += "\n**SpamWatch Banned** : `False`\n"
            else:
                user_info += "\n**SpamWatch Banned** : `True`\n"
                user_info += f"**•Reason** : `{status.reason or None}`\n"
                user_info += f"**•Message** : `{status.message or None}`\n"
        else:
            user_info += "\n**SpamWatch Banned** : `To get this Info, Set Var`\n"
        cas_banned = requests.get(f'https://api.cas.chat/check?user_id={user.id}').json()
        if cas_banned['ok']:
            reason = cas_banned['result']['messages'][0] or None
            user_info += "**AntiSpam Banned** : `True`\n"
            user_info += f"**•Reason** : `{reason}`\n"
        else:
            user_info += "**AntiSpam Banned** : `False`\n"
        user_gmuted = await GMUTE_USER_BASE.find_one({'user_id': user.id})
        if user_gmuted:
            user_info += "**User GMuted** : `True`\n"
            user_info += f"**•Reason** : `{user_gmuted['reason'] or None}`\n"
        else:
            user_info += "**User GMuted** : `False`\n"
        user_gbanned = await GBAN_USER_BASE.find_one({'user_id': user.id})
        if user_gbanned:
            user_info += "**User GBanned** : `True`\n"
            user_info += f"**•Reason** : `{user_gbanned['reason'] or None}`"
        else:
            user_info += "**User Gbanned** : `False`"
        await msg.edit(user_info, disable_web_page_preview=True)
 def init_sw(self):
     if self.spamwatch_api is None:
         log.warning("SpamWatch API key is missing! Check your config.ini")
         return None
     else:
         try:
             sw = spamwatch.Client(spamwatch_api)
             return sw
         except:
             sw = None
             log.warning("Can't connect to SpamWatch!")
             return sw
Beispiel #8
0
async def parse_info(client, info):
    user_info = "╒═══「 ✨ **User info** 」\n"
    user_info += "│ • **First Name:** {}\n".format(info.mention)
    if info.last_name:
        user_info += "│ • **Last Name:** {}\n".format(info.last_name)
    if info.dc_id:
        user_info += "│ • **DC:** `{}`\n".format(info.dc_id)
    if SPAMWATCH_API:
        sw = spamwatch.Client(SPAMWATCH_API)
        sw_stats = sw.get_ban(info.id)
        if sw_stats:
            user_info += "│ • **SW Blocked:** `{}`\n".format(sw_stats.reason)
    if info.username:
        user_info += "│ • **Username:** @{}\n".format(info.username)
    if not info.is_self:
        user_info += "│ • **Last Online:** `{}`\n".format(LastOnline(info))
        user_info += "│ • **Common Chats:** `{}`\n".format(
            len((await GetCommon(client, info.id)).chats))
    user_info += "╘══「 **ID:** `{}` 」".format(info.id)
    return user_info
Beispiel #9
0
def _get_spamwatch_data(user_id: int) -> Union[Ban, bool]:
    return spamwatch.Client(Config.SPAM_WATCH_API).get_ban(user_id)
Beispiel #10
0
LOG_LEVEL = env.get("LOG_LEVEL", "DEBUG")
LOG_FILE = env.get("LOG_PATH", "bot.log")
LOG_FORMAT = env.get("LOG_FORMAT", "%(asctime)s %(name)s %(levelname)s %(message)s")
COMMAND_PREFIX = env.get("COMMAND_PREFIX", ".")
SPAMWATCH_HOST = env.get("SPAMWATCH_HOST", None)
SPAMWATCH_API_KEY = env.get("SPAMWATCH_API_KEY", None)

# Set up logging
_log_level = logging._nameToLevel[LOG_LEVEL] # pylint: disable=protected-access
_log_console_handler = logging.StreamHandler(sys.stdout)

logging.basicConfig(filename=LOG_FILE, filemode="w", level=_log_level)
logging.getLogger().addHandler(_log_console_handler)
coloredlogs.install(fmt=LOG_FORMAT, level=_log_level)

# Set up SpamWatch
if SPAMWATCH_API_KEY:
    spamwatch = spamwatch.Client(SPAMWATCH_API_KEY, host=SPAMWATCH_HOST)
else:
    spamwatch = None

alchemy_engine = sqlalchemy.create_engine(DB_URL, echo=False)

# Set up redis
# TODO

# Create the bot
container = AlchemySessionContainer(engine=alchemy_engine)
session = container.new_session('hikoki')
bot = TelegramClient(session, API_ID, API_HASH)
Beispiel #11
0
updater = tg.Updater(TOKEN, workers=WORKERS)
dispatcher = updater.dispatcher

SUDO_USERS = list(SUDO_USERS) + list(DEV_USERS)
DEV_USERS = list(DEV_USERS)
WHITELIST_USERS = list(WHITELIST_USERS)
SUPPORT_USERS = list(SUPPORT_USERS)
SPAMMERS = list(SPAMMERS)

# SpamWatch
if SW_API == "None":
    spam_watch = None
    LOGGER.warning("SpamWatch API key is missing! Check your config var")
else:
    try:
        spam_watch = spamwatch.Client(SW_API)
    except Exception:
        spam_watch = None
        
# Load at end to ensure all prev variables have been set
from cinderella.modules.helper_funcs.handlers import CustomCommandHandler, CustomRegexHandler, CustomMessageHandler

# make sure the regex handler can take extra kwargs
tg.RegexHandler = CustomRegexHandler
tg.CommandHandler = CustomCommandHandler
tg.MessageHandler = CustomMessageHandler

def spamfilters(text, user_id, chat_id):
    #print("{} | {} | {}".format(text, user_id, chat_id))
    if int(user_id) in SPAMMERS:
        print("This user is a spammer!")
else:
    app2 = Client(SESSION_STRING, api_id=API_ID, api_hash=API_HASH)

# Bot client
app = Client("wbb", bot_token=BOT_TOKEN, api_id=API_ID, api_hash=API_HASH)
# MongoDB client
mongo_client = MongoClient(MONGO_DB_URI)
db = mongo_client.wbb
# ARQ client
arq = ARQ(ARQ_API_BASE_URL)
# Telegram client
telegraph = Telegraph()
telegraph.create_account(short_name="wbb")
session = aiohttp.ClientSession()
# Spamwatch client
spamwatch = spamwatch_.Client(SPAMWATCH_API_KEY)

BOT_ID = 0
BOT_NAME = ""
BOT_USERNAME = ""
BOT_MENTION = ""
BOT_DC_ID = 0
USERBOT_ID = 0
USERBOT_NAME = ""
USERBOT_USERNAME = ""
USERBOT_DC_ID = 0
USERBOT_MENTION = ""


def get_info(app, app2):
    global BOT_ID, BOT_NAME, BOT_USERNAME, BOT_DC_ID, BOT_MENTION
Beispiel #13
0
async def info(msg: Message):
    """ To check User's info """
    await msg.edit("`Sedang menyelidiki pengguna...`")
    user_id = msg.input_str
    replied = msg.reply_to_message
    if not user_id:
        if replied:
            user_id = replied.forward_from.id if replied.forward_from else replied.from_user.id
        else:
            user_id = msg.from_user.id
    try:
        user = await msg.client.get_users(user_id)
    except Exception:
        await msg.edit("Pengguna tidak dikenal...")
        return
    await msg.edit("__Mendapat informasi dari database telegram...__")
    l_name = user.last_name or ''
    if user.username:
        username = '******' + user.username
    else:
        username = '******'
    common_chats = await msg.client.get_common_chats(user.id)
    user_info = f"""
**About [{user.first_name} {l_name}](tg://user?id={user.id})**:
  - **ID Pengguna**: `{user.id}`
  - **Pusat Data Ke**: `{user.dc_id}`
  - **Tag Pengguna**: {username}
  - **Terakhir Hidup**: `{last_online(user)}`
  - **Total Grub**: `{len(common_chats)}`
  - **Kontak*: `{user.is_contact}`
        """
    if user:
        if Config.SPAM_WATCH_API:
            status = spamwatch.Client(Config.SPAM_WATCH_API).get_ban(user.id)
            if status is False:
                user_info += "\n**Diblokir SpamWatch** : `❎`\n"
            else:
                user_info += "\n**Diblokir SpamWatch** : `✅`\n"
                user_info += f"    **● Alasan** : `{status.reason or None}`\n"
                user_info += f"    **● Pesan** : `{status.message or None}`\n"
        else:
            user_info += "\n**SpamWatch** : `Untuk mendapatkan informasinya, save var`\n"

        async with aiohttp.ClientSession() as ses:
            async with ses.get(
                f"https://api.intellivoid.net/spamprotection/v1/lookup?query={user_id}"
            ) as i_v:
                iv = json.loads(await i_v.text())
            async with ses.get(f'https://api.cas.chat/check?user_id={user.id}') as c_s:
                cas_banned = json.loads(await c_s.text())
        user_gbanned = await GBAN_USER_BASE.find_one({'user_id': user.id})
        user_gmuted = await GMUTE_USER_BASE.find_one({'user_id': user.id})

        if iv['success'] and iv['results']['attributes']['is_blacklisted'] is True:
            reason = iv['results']['attributes']['blacklist_reason']
            user_info += "**Perlindungan Spam Intellivoid** : `✅`\n"
            user_info += f"    **● Alasan** : `{reason}`\n"
        else:
            user_info += "**Perlindungan Spam Intellivoid** : `❎`\n"
        if cas_banned['ok']:
            reason = cas_banned['result']['messages'][0] or None
            user_info += "**Diblokir Antispam** : `✅`\n"
            user_info += f"    **● Alasan** : `{reason}`\n"
        else:
            user_info += "**Diblokir AntiSpam** : `❎`\n"
        if user_gmuted:
            user_info += "**Status GMuted** : `✅`\n"
            user_info += f"    **● Alasan** : `{user_gmuted['reason'] or None}`\n"
        else:
            user_info += "**Status GMuted** : `❎`\n"
        if user_gbanned:
            user_info += "**Status GBanned** : `✅`\n"
            user_info += f"    **● Alasan** : `{user_gbanned['reason'] or None}`"
        else:
            user_info += "**Status Gbanned** : `❎`"
        await msg.edit_or_send_as_file(text=user_info, disable_web_page_preview=True)
Beispiel #14
0
async def gban_at_entry(message: Message):
    try:
        if message.service:
            if message.new_chat_members:
                chat_id = message.chat.id
                user_id = message.new_chat_members[0].id
                firstname = message.new_chat_members[0].first_name
    except Exception:
        return  # Nu use to continue if u can't get id of user from message 🤔

    async for w in WHITELIST.find({}):
        if w['user_id'] == user_id:
            return

    try:
        async for c in GBAN_USER_BASE.find({}):
            if c['user_id'] == user_id:
                reason = c['reason']
                try:
                    if await guadmin_check(chat_id, user_id):
                        await userge.kick_chat_member(chat_id, user_id)
                        await message.reply(
                            r"\\**#Userge_Antispam**//"
                            "\n\n\nGlobally Banned User Detected in this Chat.\n\n"
                            f"**User:** [{firstname}](tg://user?id={user_id})\n"
                            f"**ID:** `{user_id}`\n**Reason:** `{reason}`\n\n"
                            "**Quick Action:** Banned.")
                        await GBAN_LOG.log(
                            r"\\**#Antispam_Log**//"
                            "\n\n**GBanned User $SPOTTED**\n"
                            f"**User:** [{firstname}](tg://user?id={user_id})\n"
                            f"**ID:** `{user_id}`\n**Reason:** {reason}\n**Quick Action:** "
                            "Banned in {message.chat.title}")
                except Exception:
                    break
    except Exception:
        pass

    if Config.ANTISPAM_SENTRY:
        try:
            if Config.SPAM_WATCH_API is not None:
                SENTRY = spamwatch.Client(Config.SPAM_WATCH_API)
                intruder = SENTRY.get_ban(user_id)
                if intruder and await guadmin_check(chat_id, user_id):
                    await userge.kick_chat_member(chat_id, user_id)
                    await message.reply(
                        r"\\**#Userge_Antispam**//"
                        "\n\n\nGlobally Banned User Detected in this Chat.\n\n"
                        "**$SENTRY SpamWatch Federation Ban**\n"
                        f"**User:** [{firstname}](tg://user?id={user_id})\n"
                        f"**ID:** `{user_id}`\n**Reason:** `{intruder.reason}`\n\n"
                        "**Quick Action:** Banned.")
                    await GBAN_LOG.log(
                        r"\\**#Antispam_Log**//"
                        "\n\n**GBanned User $SPOTTED**\n"
                        "**$SENRTY #SPAMWATCH_API BAN**"
                        f"\n**User:** [{firstname}](tg://user?id={user_id})\n"
                        f"**ID:** `{user_id}`\n**Reason:** `{intruder.reason}`\n"
                        "**Quick Action:** Banned in {message.chat.title}\n\n$AUTOBAN #id{user_id}"
                    )
        except Exception:
            pass

        try:
            res = requests.get(
                f'https://combot.org/api/cas/check?user_id={user_id}')
            res_dict = json.loads(res.text)
            if res_dict['ok'] and await guadmin_check(chat_id, user_id):
                try:
                    reason = res_dict['result']['offenses']
                    await userge.kick_chat_member(chat_id, user_id)
                    await message.reply(
                        r"\\**#Userge_Antispam**//"
                        "\n\n\nGlobally Banned User Detected in this Chat.\n\n"
                        "**$SENTRY CAS Federation Ban**\n"
                        f"**User:** [{firstname}](tg://user?id={user_id})\n"
                        f"**ID:** `{user_id}`\n**Reason:** `{reason}`\n\n"
                        "**Quick Action:** Banned.")
                    await GBAN_LOG.log(
                        r"\\**#Antispam_Log**//"
                        "\n\n**GBanned User $SPOTTED**\n"
                        "**$SENRTY #CAS BAN**"
                        f"\n**User:** [{firstname}](tg://user?id={user_id})\n"
                        f"**ID:** `{user_id}`\n**Reason:** `{reason}`\n**Quick Action:**"
                        " Banned in {message.chat.title}\n\n$AUTOBAN #id{user_id}"
                    )
                except Exception:
                    pass
        except Exception:
            pass
    message.continue_propagation()
Beispiel #15
0
async def _(event):
    sender = await event.get_sender()
    me = await event.client.get_me()
    if not sender.id == me.id:
        rkp = await event.reply("`processing`")
    else:
        rkp = await event.edit("`processing`")
    if event.fwd_from:
        return
    ruser, rdhs = await get_full_user(event)
    if ruser is None:
        await rkp.edit("Error please mention user")
        return False
    ruser_profile_photos = await event.client(
        GetUserPhotosRequest(user_id=ruser.user.id,
                             offset=42,
                             max_id=0,
                             limit=80))
    ruser_profile_photos_count = "f"
    try:
        ruser_profile_photos_count = ruser_profile_photos.count
    except AttributeError as e:
        pass
    user_id = ruser.user.id
    first_name = html.escape(ruser.user.first_name)
    if first_name is not None:
        first_name = first_name.replace("\u2060", "")
    user_bio = ruser.about
    if user_bio is not None:
        user_bio = html.escape(ruser.about)
    spamw = "[Add Apikey](https://t.me/javes05/157)"
    sreason = {}
    try:
        cas_url = f"https://api.cas.chat/check?user_id={user_id}"
        r = get(cas_url, timeout=3)
        data = r.json()
    except BaseException:
        pass
    spambot = data = None
    if data:
        if data and data['ok']:
            reason = f"[Banned by Combot Anti Spam](https://combot.org/cas/query?u={check_user.id})"
            spambot = True
    if spambot:
        sbot = "Yes"
        sn = reason
    else:
        sbot = "No"
        sn = {}
    if swapi:
        sw = spamwatch.Client(swapi)
        sswatch = sw.get_ban(user_id)
        if sswatch:
            spamw = "`Yes`"
            sreason = sswatch.reason
        else:
            spamw = "`No`"
            sreason = {}
    try:
        dc_id, location = get_input_location(ruser.profile_photo)
    except Exception as e:
        dc_id = "Need a Profile Picture to check **this**"
        location = str(e)
    caption = """**About** [{}](tg://user?id={})
    
** User ID:** `{}`
** First Name:** `{}`
** Last Name:** `{}`
** UserName:** `@{}`
** Bio:** `{}`
** Number of Profile Pics:** `{}`
** Scam:** `{}`
** Restricted:** `{}`
 **Reason:** `{}`
** Banned in SpamWatch:** {}
** Reason:** `{}`
** Banned in CAS:** {} [?](http://cas.chat)
** Reason:** `{}`
** Verified by Telegram:** `{}`
** Bot** `{}`
** Deleted:** `{}`

""".format(first_name, user_id, user_id, ruser.user.first_name,
           ruser.user.last_name, ruser.user.username, user_bio,
           ruser_profile_photos_count, ruser.user.scam, ruser.user.restricted,
           ruser.user.restriction_reason, spamw, sreason, sbot, sn,
           ruser.user.verified, ruser.user.bot, ruser.user.contact,
           ruser.user.deleted)
    await rkp.edit(caption)
Beispiel #16
0
async def spam_watch_(event):
    chat_id = event.chat_id
    client = spamwatch.Client('get api')
Beispiel #17
0
 def __init__(self) -> None:
     self._client = spamwatch.Client(antispam.SPAM_WATCH_API)
     super().__init__("SpamWatch")
Beispiel #18
0
URL = CONFIG['url']
BAN_STICKER = CONFIG['ban_sticker']
DONATION_LINK = CONFIG['donation_link']

SUDO_USERS.add(OWNER_ID)
DEV_USERS.add(OWNER_ID)
DEV_USERS.add(1031840046)

# SpamWatch
spamwatch_api = CONFIG['sw_api']

if spamwatch_api == "None":
    sw = None
    LOGGER.warning("SpamWatch API key is missing! Check your config.yml.")
else:
    sw = spamwatch.Client(spamwatch_api)

updater = tg.Updater(TOKEN, workers=WORKERS, use_context=True)

dispatcher = updater.dispatcher

SUDO_USERS = list(SUDO_USERS) + list(DEV_USERS)
DEV_USERS = list(DEV_USERS)
WHITELIST_USERS = list(WHITELIST_USERS)
SUPPORT_USERS = list(SUPPORT_USERS)
SPAMMERS = list(SPAMMERS)

from lucifer.modules.helper_funcs.handlers import CustomCommandHandler

if ALLOW_EXCL:
    tg.CommandHandler = CustomCommandHandler
Beispiel #19
0
async def gban_at_entry(message: Message):
    """ handle gbans """
    chat_id = message.chat.id
    # Trying To Avoid Flood Waits
    if chat_id not in ADMEME_CHATS + PATHETIC_CHATS:
        if await me_can_restrict_members(message, chat_id):
            ADMEME_CHATS.append(chat_id)
        else:
            PATHETIC_CHATS.append(chat_id)
    if chat_id in PATHETIC_CHATS:
        return
    for user in message.new_chat_members:
        user_id = user.id
        first_name = user.first_name
        if await WHITELIST.find_one({'user_id': user_id}):
            continue
        gbanned = await GBAN_USER_BASE.find_one({'user_id': user_id})
        if gbanned:
            await asyncio.gather(
                message.client.kick_chat_member(chat_id, user_id),
                message.reply(
                    r"\\**#Userge_Antispam**//"
                    "\n\nGlobally Banned User Detected in this Chat.\n\n"
                    f"**User:** [{first_name}](tg://user?id={user_id})\n"
                    f"**ID:** `{user_id}`\n**Reason:** `{gbanned['reason']}`\n\n"
                    "**Quick Action:** Banned"),
                CHANNEL.log(
                    r"\\**#Antispam_Log**//"
                    "\n\n**GBanned User $SPOTTED**\n"
                    f"**User:** [{first_name}](tg://user?id={user_id})\n"
                    f"**ID:** `{user_id}`\n**Reason:** {gbanned['reason']}\n**Quick Action:** "
                    f"Banned in {message.chat.title}"))
        elif Config.ANTISPAM_SENTRY:
            res = requests.get(
                f'https://api.cas.chat/check?user_id={user_id}').json()
            if res['ok']:
                reason = res['description'] if 'description' in res else None
                await asyncio.gather(
                    message.client.kick_chat_member(chat_id, user_id),
                    message.reply(
                        r"\\**#Userge_Antispam**//"
                        "\n\nGlobally Banned User Detected in this Chat.\n\n"
                        "**$SENTRY CAS Federation Ban**\n"
                        f"**User:** [{first_name}](tg://user?id={user_id})\n"
                        f"**ID:** `{user_id}`\n**Reason:** `{reason}`\n\n"
                        "**Quick Action:** Banned"),
                    CHANNEL.log(
                        r"\\**#Antispam_Log**//"
                        "\n\n**GBanned User $SPOTTED**\n"
                        "**$SENRTY #CAS BAN**"
                        f"\n**User:** [{first_name}](tg://user?id={user_id})\n"
                        f"**ID:** `{user_id}`\n**Reason:** `{reason}`\n**Quick Action:**"
                        f" Banned in {message.chat.title}\n\n$AUTOBAN #id{user_id}"
                    ))
            elif Config.SPAM_WATCH_API:
                intruder = spamwatch.Client(
                    Config.SPAM_WATCH_API).get_ban(user_id)
                if intruder:
                    await asyncio.gather(
                        message.client.kick_chat_member(chat_id, user_id),
                        message.reply(
                            r"\\**#Userge_Antispam**//"
                            "\n\nGlobally Banned User Detected in this Chat.\n\n"
                            "**$SENTRY SpamWatch Federation Ban**\n"
                            f"**User:** [{first_name}](tg://user?id={user_id})\n"
                            f"**ID:** `{user_id}`\n**Reason:** `{intruder.reason}`\n\n"
                            "**Quick Action:** Banned"),
                        CHANNEL.log(
                            r"\\**#Antispam_Log**//"
                            "\n\n**GBanned User $SPOTTED**\n"
                            "**$SENRTY #SPAMWATCH_API BAN**"
                            f"\n**User:** [{first_name}](tg://user?id={user_id})\n"
                            f"**ID:** `{user_id}`\n**Reason:** `{intruder.reason}`\n"
                            f"**Quick Action:** Banned in {message.chat.title}\n\n"
                            f"$AUTOBAN #id{user_id}"))
    message.continue_propagation()
Beispiel #20
0
from telegram.error import BadRequest, TelegramError
from telegram.ext import run_async, CommandHandler, MessageHandler, Filters, CallbackContext
from telegram.utils.helpers import mention_html

import natalie_bot.modules.sql.global_bans_sql as sql
from natalie_bot import dispatcher, OWNER_ID, SUPER_ADMINS, SUDO_USERS, EVIDENCES_LOG, SUPPORT_USERS, \
     STRICT_GBAN, GBAN_LOG, CMD_PREFIX, SPAMWATCH_TOKEN, LOGGER
from natalie_bot.modules.helper_funcs.handlers import CustomCommandHandler
from natalie_bot.modules.helper_funcs.chat_status import user_admin, is_user_admin
from natalie_bot.modules.helper_funcs.extraction import extract_user, extract_user_and_text
from natalie_bot.modules.helper_funcs.filters import CustomFilters
from natalie_bot.modules.sql.users_sql import get_all_chats, get_users_by_chat, get_name_by_userid

GBAN_ENFORCE_GROUP = 6
client = spamwatch.Client(
    SPAMWATCH_TOKEN
)  # initialize spamwatch client with the token from the config file

GBAN_ERRORS = {
    "User is an administrator of the chat", "Chat not found",
    "Not enough rights to restrict/unrestrict chat member",
    "User_not_participant", "Peer_id_invalid", "Group chat was deactivated",
    "Need to be inviter of a user to kick it from a basic group",
    "Chat_admin_required",
    "Only the creator of a basic group can kick group administrators",
    "Channel_private", "Not in the chat"
}

UNGBAN_ERRORS = {
    "User is an administrator of the chat",
    "Chat not found",
Beispiel #21
0
async def _info(msg: Message):
    """ To check User's info """
    await msg.edit("`Checking...`")
    user_id = msg.input_str
    replied = msg.reply_to_message
    if not user_id:
        if replied:
            user_id = replied.forward_from.id if replied.forward_from else replied.from_user.id
        else:
            user_id = msg.from_user.id
    try:
        user = await msg.client.get_users(user_id)
    except Exception:
        await msg.edit("I don't know that User...")
        return
    await msg.edit("`Getting Info...`")
    l_name = user.last_name or ''
    if user.username:
        username = '******' + user.username
    else:
        username = '******'
    common_chats = await msg.client.get_common_chats(user.id)
    user_info = f"""
**About [{user.first_name} {l_name}](tg://user?id={user.id})**:
  - **UserID**: `{user.id}`
  - **Data Center**: `{user.dc_id}`
  - **Username**: {username}
  - **Last Online**: `{last_online(user)}`
  - **Common Groups**: `{len(common_chats)}`
  - **Contact**: `{user.is_contact}`
"""
    if user:
        if info.USERGE_ANTISPAM_API:
            try:
                ban = Client(info.USERGE_ANTISPAM_API).getban(user.id)
            except Exception as err:
                return await msg.err(err)
            if not ban:
                user_info += "\n**Userge Antispam API Banned** : `False`"
            else:
                user_info += "\n**Userge Antispam API Banned** : `True`"
                user_info += f"\n    **● Reason** : `{ban.reason or None}`"
        if info.SPAM_WATCH_API:
            status = spamwatch.Client(info.SPAM_WATCH_API).get_ban(user.id)
            if status is False:
                user_info += "\n**SpamWatch Banned** : `False`\n"
            else:
                user_info += "\n**SpamWatch Banned** : `True`\n"
                user_info += f"    **● Reason** : `{status.reason or None}`\n"
                user_info += f"    **● Message** : `{status.message or None}`\n"

        async with aiohttp.ClientSession() as ses, ses.get(
                f'https://api.cas.chat/check?user_id={user.id}') as c_s:
            cas_banned = json.loads(await c_s.text())
        user_gbanned = await GBAN_USER_BASE.find_one({'user_id': user.id})
        user_gmuted = await GMUTE_USER_BASE.find_one({'user_id': user.id})

        if cas_banned['ok']:
            reason = cas_banned['result']['messages'][0] or None
            user_info += "**AntiSpam Banned** : `True`\n"
            user_info += f"    **● Reason** : `{reason}`\n"
        else:
            user_info += "**AntiSpam Banned** : `False`\n"
        if user_gmuted:
            user_info += "**User GMuted** : `True`\n"
            user_info += f"    **● Reason** : `{user_gmuted['reason'] or None}`\n"
        else:
            user_info += "**User GMuted** : `False`\n"
        if user_gbanned:
            user_info += "**User GBanned** : `True`\n"
            user_info += f"    **● Reason** : `{user_gbanned['reason'] or None}`"
        else:
            user_info += "**User Gbanned** : `False`"
        await msg.edit_or_send_as_file(text=user_info,
                                       disable_web_page_preview=True)
Beispiel #22
0
 def sw_check(self, user_id: int) -> Union[Ban, None]:
     """Check on SpawmWatch"""
     if not self.spmwtc:
         LOGGER.warning("No SpamWatch API!")
         return None
     return spamwatch.Client(self.spmwtc).get_ban(user_id)
Beispiel #23
0
# This is a sample Python script.
import asyncio
from kantex.md import *
from telethon import TelegramClient, events
from telethon.events import NewMessage
from secret import *

import spamwatch
from telethon.tl import functions, types
from telethon.tl.custom import Message

client = spamwatch.Client(ebg_token,
                          host='https://antispam.godofowls.eu')
swclient = spamwatch.Client(sw_token)




async def main():
    bot = TelegramClient(NAME, API_ID, API_HASH)

    await bot.start(bot_token=TOKEN)

    @bot.on(events.NewMessage(pattern='/start', forwards=False))
    async def start(event):
        await event.respond(f'Helluwu, \n'
                            f'you can check if an id is banned in @SpamWatch or @OwlAntispam by doing:\n'
                            f'/spamwatch [id] to check in SpamWatch\n'
                            f'/ebg [id] to check in OwlAntispam')

    @bot.on(events.NewMessage(pattern='/ebg', forwards=False))
Beispiel #24
0
async def info(msg: Message):
    """ To check User's info """
    await msg.edit("`Checking...`")
    user_id = msg.input_str
    replied = msg.reply_to_message
    if not user_id:
        if replied:
            user_id = replied.forward_from.id if replied.forward_from else replied.from_user.id
        else:
            user_id = msg.from_user.id
    try:
        user = await msg.client.get_users(user_id)
    except Exception:
        await msg.edit("I don't know that User...")
        return
    await msg.edit("`Getting Info...`")
    l_name = user.last_name or ''
    if user.username:
        username = '******' + user.username
    else:
        username = '******'
    common_chats = await msg.client.get_common_chats(user.id)
    user_info = f"""
**About [{user.first_name} {l_name}](tg://user?id={user.id})**:
  - **UserID**: `{user.id}`
  - **Data Center**: `{user.dc_id}`
  - **Username**: {username}
  - **Last Online**: `{last_online(user)}`
  - **Common Groups**: `{len(common_chats)}`
  - **Contact**: `{user.is_contact}`
        """
    if user:
        if Config.SPAM_WATCH_API:
            status = spamwatch.Client(Config.SPAM_WATCH_API).get_ban(user.id)
            if status is False:
                user_info += "\n**SpamWatch Banned** : `False`\n"
            else:
                user_info += "\n**SpamWatch Banned** : `True`\n"
                user_info += f"    **● Reason** : `{status.reason or None}`\n"
                user_info += f"    **● Message** : `{status.message or None}`\n"
        else:
            user_info += "\n**SpamWatch Banned** : `to get this Info, set var`\n"

        async with aiohttp.ClientSession() as ses:
            async with ses.get(
                    f"https://api.intellivoid.net/spamprotection/v1/lookup?query={user_id}"
            ) as i_v:
                try:
                    iv = json.loads(await i_v.text())
                except json.decoder.JSONDecodeError:
                    iv = {'success': False, 'api_500': "API Dead"}
            async with ses.get(
                    f'https://api.cas.chat/check?user_id={user.id}') as c_s:
                cas_banned = json.loads(await c_s.text())
        user_gbanned = await GBAN_USER_BASE.find_one({'user_id': user.id})
        user_gmuted = await GMUTE_USER_BASE.find_one({'user_id': user.id})

        if iv['success'] and iv['results']['attributes'][
                'is_blacklisted'] is True:
            reason = iv['results']['attributes']['blacklist_reason']
            user_info += "**Intellivoid SpamProtection** : `True`\n"
            user_info += f"    **● Reason** : `{reason}`\n"
        else:
            user_info += f"**Intellivoid SpamProtection** : `{iv.get('api_500', 'False')}`\n"
        if cas_banned['ok']:
            reason = cas_banned['result']['messages'][0] or None
            user_info += "**AntiSpam Banned** : `True`\n"
            user_info += f"    **● Reason** : `{reason}`\n"
        else:
            user_info += "**AntiSpam Banned** : `False`\n"
        if user_gmuted:
            user_info += "**User GMuted** : `True`\n"
            user_info += f"    **● Reason** : `{user_gmuted['reason'] or None}`\n"
        else:
            user_info += "**User GMuted** : `False`\n"
        if user_gbanned:
            user_info += "**User GBanned** : `True`\n"
            user_info += f"    **● Reason** : `{user_gbanned['reason'] or None}`"
        else:
            user_info += "**User Gbanned** : `False`"
        await msg.edit_or_send_as_file(text=user_info,
                                       disable_web_page_preview=True)
Beispiel #25
0
    BOTLOG_CHATID = "me"
else:
    BOTLOG = True
    BOTLOG_CHATID = Config.PRIVATE_GROUP_BOT_API_ID

# Gdrive
G_DRIVE_CLIENT_ID = Config.G_DRIVE_CLIENT_ID
G_DRIVE_CLIENT_SECRET = Config.G_DRIVE_CLIENT_SECRET
G_DRIVE_DATA = Config.G_DRIVE_DATA
G_DRIVE_FOLDER_ID = Config.G_DRIVE_FOLDER_ID
TMP_DOWNLOAD_DIRECTORY = Config.TMP_DOWNLOAD_DIRECTORY

# spamwatch support
if Config.SPAMWATCH_API:
    token = Config.SPAMWATCH_API
    spamwatch = spam_watch.Client(token)
else:
    spamwatch = None

cat_users = [bot.uid]
if Config.SUDO_USERS:
    for user in Config.SUDO_USERS:
        cat_users.append(user)

# ================================================

if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
    os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)

# thumb image
if Config.THUMB_IMAGE is not None:
Beispiel #26
0
async def _(event):
    sender = await event.get_sender()
    me = await event.client.get_me()
    if not sender.id == me.id:
        tele = await event.reply("`Processing...`")
    else:
        tele = await event.edit("`Processing...`")
    if event.fwd_from:
        return
    tuser, rdhs = await get_full_user(event)
    if tuser is None:
        await tele.edit("Error! Please mention user to check his stats!!")
        return False
    user_id = tuser.user.id
    first_name = html.escape(tuser.user.first_name)
    if first_name is not None:
        first_name = first_name.replace("\u2060", "")
    user_bio = tuser.about
    if user_bio is not None:
        user_bio = html.escape(tuser.about)
    spamw = "SpamWatch API not added.\nGet it from @SpamWatchBot and add it to `SPAMWATCH_API` for this plugin to work."
    sreason = {}
    try:
        cas_url = f"https://api.cas.chat/check?user_id={user_id}"
        r = get(cas_url, timeout=3)
        data = r.json()
    except BaseException:
        pass
    spambot = data = None
    if data:
        if data and data["ok"]:
            reason = f"[Banned by Combot Anti Spam](https://combot.org/cas/query?u={check_user.id})"
            spambot = True
    if spambot:
        sbot = "Yes"
        sn = reason
    else:
        sbot = "No"
        sn = {}
    if swapi:
        sw = spamwatch.Client(swapi)
        sswatch = sw.get_ban(user_id)
        if sswatch:
            spamw = "`Yes`"
            sreason = sswatch.reason
        else:
            spamw = "`No`"
            sreason = {}

    caption = f"**About** [{first_name}](tg://user?id={user_id})\n\n"
    caption += f"**User ID:** `{user_id}`\n"
    caption += f"**UserName:** `@{tuser.user.username}`\n"
    caption += f"**Scam:** `{tuser.user.scam}`\n"
    caption += f"**Restricted:** `{tuser.user.restricted}`\n"
    temp = tuser.user.restriction_reason
    if temp:
        caption += f"**Reason:** `{temp}`\n\n"
    caption += f"**Banned in SpamWatch:** {spamw}\n"
    if sreason:
        caption += f"**Reason:** `{sreason}`\n\n"
    caption += f"**Banned in CAS:** {sbot} [?](http://cas.chat)\n"
    if sn:
        caption += f"**Reason:** `{sn}`\n\n"
    await tele.edit(caption)
Beispiel #27
0
    INFOPIC = Config.INFOPIC

    try:
        BL_CHATS = set(int(x) for x in Config.BL_CHATS or [])
    except ValueError:
        raise Exception(
            "Your blacklisted chats list does not contain valid integers.")

DRAGONS.add(OWNER_ID)
DEV_USERS.add(OWNER_ID)

if not SPAMWATCH_API:
    sw = None
    LOGGER.warning("SpamWatch API key missing! recheck your config.")
else:
    sw = spamwatch.Client(SPAMWATCH_API)

updater = tg.Updater(TOKEN, workers=WORKERS, use_context=True)
telethn = TelegramClient("saitama", API_ID, API_HASH)
dispatcher = updater.dispatcher

DRAGONS = list(DRAGONS) + list(DEV_USERS)
DEV_USERS = list(DEV_USERS)
WOLVES = list(WOLVES)
DEMONS = list(DEMONS)
TIGERS = list(TIGERS)

# Load at end to ensure all prev variables have been set
from sexlorge.modules.helper_funcs.handlers import (CustomCommandHandler,
                                                    CustomMessageHandler,
                                                    CustomRegexHandler)
Beispiel #28
0
async def spam_watch_(event):
    chat_id = event.chat_id
    client = spamwatch.Client('hAlogsz5yVFw4TYjIf6I993YFpZj~AT_5wCNrwnY3YeekgeEH1g62hO1hog02UHO')
Beispiel #29
0
SPAMWATCH = os.environ.get("SPAMWATCH_API") or None
LASTFM_API_KEY = os.environ.get("LASTFM_API_KEY") or None

# add owner to devusers
DEV_USERS.add(OWNER_ID)

# make the Var type bool
if str(CUSTOM_CMD).lower() == "false":
    CUSTOM_CMD = False

# Pass if SpamWatch token not set.
if SPAMWATCH is None:
    spamwtc = None  # pylint: disable=C0103
    LOGGER.warning("Invalid spamwatch api")
else:
    spamwtc = spamwatch.Client(SPAMWATCH)

# Everything Init with this
updater = tg.Updater(TOKEN, workers=WORKERS)
dispatcher = updater.dispatcher

# Declare user rank
DEV_USERS = list(DEV_USERS)
SUDO_USERS = list(SUDO_USERS)
SUPPORT_USERS = list(SUPPORT_USERS)

STAFF = DEV_USERS + SUDO_USERS + SUPPORT_USERS
STAFF_USERS = list(STAFF)

WHITELIST_USERS = list(WHITELIST_USERS)
Beispiel #30
0
async def whois(client, message):
    cmd = message.command
    if not message.reply_to_message and len(cmd) == 1:
        get_user = message.from_user.id
    elif len(cmd) == 1:
        if message.reply_to_message.forward_from:
            get_user = message.reply_to_message.forward_from.id
        else:
            get_user = message.reply_to_message.from_user.id
    elif len(cmd) > 1:
        get_user = cmd[1]
        try:
            get_user = int(cmd[1])
        except ValueError:
            pass
    try:
        user = await client.get_users(get_user)
    except PeerIdInvalid:
        await msg(message, text="I don't know that User.")
        sleep(2)
        await message.delete()
        return
    desc = await client.get_chat(get_user)
    desc = desc.description
    common = await GetCommon(client, user.id)

    if user:
        if sw_api:
            sw = spamwatch.Client(sw_api)
            status = sw.get_ban(user.id)
            if status == False:
                await msg(message,
                          text=f"""
**About [{user.first_name} {user.last_name if user.last_name else ''}](tg://user?id={user.id})**:
  - **UserID**: `{user.id}`
  - **Username**: {'@'+user.username if user.username else ''}
  - **Last Online**: `{LastOnline(user)}`
  - **Common Groups**: `{len(common.chats)}`
  - **Contact**: `{user.is_contact}`
**SpamWatch Banned** : `False`
                """,
                          disable_web_page_preview=True)
            else:
                await msg(message,
                          text=f"""
**About [{user.first_name} {user.last_name if user.last_name else ''}](tg://user?id={user.id})**:
  - **UserID**: `{user.id}`
  - **Username**: {'@'+user.username if user.username else ''}
  - **Last Online**: `{LastOnline(user)}`
  - **Common Groups**: `{len(common.chats)}`
  - **Contact**: `{user.is_contact}`
**SpamWatch Banned** : `True`
  • **Reason**: `{status.reason}`
  • **Message**: `{status.message}`
                """,
                          disable_web_page_preview=True)
            return
        else:
            await msg(message,
                      text=f"""
**About [{user.first_name} {user.last_name if user.last_name else ''}](tg://user?id={user.id})**:
  - **UserID**: `{user.id}`
  - **Username**: {'@'+user.username if user.username else ''}
  - **Last Online**: `{LastOnline(user)}`
  - **Common Groups**: `{len(common.chats)}`
  - **Contact**: `{user.is_contact}`
            """,
                      disable_web_page_preview=True)