def detect_spam(update, context):
    url = "https://api.intellivoid.net/coffeehouse/v1/nlp/spam_prediction/chatroom"
    user = update.effective_user
    chat = update.effective_chat
    msg = update.effective_message
    bot = context.bot
    if user.id == bot.id:
        return

    from tg_bot import SPB_MODE, CF_API_KEY
    chat_state = sql.does_chat_nlp(chat.id)
    if SPB_MODE and CF_API_KEY and chat_state == True:
        try:
            payload = {'access_key': CF_API_KEY, 'input': msg}
            data = requests.post(url, data=payload)
            res_json = data.json()
            if res_json['success']:
                spam_check = res_json['results']['spam_prediction']['is_spam']
                if spam_check == True:
                    pred = res_json['results']['spam_prediction']['prediction']
                    try:
                        bot.restrict_chat_member(
                            chat.id, user.id,
                            telegram.ChatPermissions(can_send_messages=False))
                        msg.reply_text(
                            f"*⚠ SPAM DETECTED!*\nSpam Prediction: `{pred}`\nUser: `{telegram.utils.helpers.mention_markdown(user.id)}` was muted.",
                            parse_mode=telegram.ParseMode.MARKDOWN,
                        )
                    except telegram.BadRequest:
                        msg.reply_text(
                            f"*⚠ SPAM DETECTED!*\nSpam Prediction: `{pred}`\nUser: `{telegram.utils.helpers.mention_markdown(user.id)}`\nUser could not be restricted due to insufficient admin perms.",
                            parse_mode=telegram.ParseMode.MARKDOWN,
                        )

            elif res_json['error']['error_code'] == 21:
                reduced_msg = msg[0:170]
                payload = {'access_key': CF_API_KEY, 'input': reduced_msg}
                data = requests.post(url, data=payload)
                res_json = data.json()
                spam_check = res_json['results']['spam_prediction']['is_spam']
                if spam_check is True:
                    pred = res_json['results']['spam_prediction']['prediction']
                    try:
                        bot.restrict_chat_member(
                            chat.id, user.id,
                            telegram.ChatPermissions(can_send_messages=False))
                        msg.reply_text(
                            f"*⚠ SPAM DETECTED!*\nSpam Prediction: `{pred}`\nUser: `{telegram.utils.helpers.mention_markdown(user.id)}` was muted.",
                            parse_mode=telegram.ParseMode.MARKDOWN)
                    except telegram.BadRequest:
                        msg.reply_text(
                            f"*⚠ SPAM DETECTED!*\nSpam Prediction: `{pred}`\nUser: `{telegram.utils.helpers.mention_markdown(user.id)}`\nUser could not be restricted due to insufficient admin perms.",
                            parse_mode=telegram.ParseMode.MARKDOWN)
        except BaseException as e:
            log.warning(f"Can't reach SpamProtection API due to {e}")
            return
Beispiel #2
0
def proceed_new_members(update, callback):
    bot = callback.bot
    members = update.message.new_chat_members
    logger.info(members)
    if len(members) == 0:
        return
    chat_id = update.message.chat_id
    API.delete_message(bot, chat_id, update.message.message_id)
    with dataWorker.session_scope() as session:
        chat: GroupStatus = session.query(GroupStatus).get(chat_id)
        reply_template = chat.wel_message
        if chat is None or reply_template is None:
            return
        for member in members:
            reply = reply_template.replace("""{$name}""",
                                           f"""<a href="tg://user?id={member.id}">{member.first_name}</a>""")
            kwargs = {"chat_id": chat_id,
                      "text": reply,
                      "disable_web_page_preview": True}
            if not chat.new_users_blocked or not can_restrict_users(bot, update):
                message = send_wel_message(bot, kwargs)
                time.sleep(30)
                if can_delete_messages(bot, update):
                    API.delete_message(bot, chat_id=message.chat_id, message_id=message.message_id)
            else:

                unlock_button = telegram.InlineKeyboardButton("Я прочитал",
                                                              callback_data="applied " + str(member.id))
                reply_markup = InlineKeyboardMarkup(build_menu([unlock_button], n_cols=1))
                kwargs["reply_markup"] = reply_markup
                msg = send_wel_message(bot, kwargs)
                chat.add_muted(member.id, msg.message_id)
                bot.restrict_chat_member(chat_id, member.id, telegram.ChatPermissions())
Beispiel #3
0
 def kick(self, bot, game):
     try:
         Messages.send_message(bot, self.real_id, Messages.YOU_LOSE)
         Messages.send_message(bot, game.group_id, "بازیکن " + self.first_name + " از بازی حذف شد")
         bot.restrict_chat_member(chat_id=game.group_id, user_id=self.real_id,
                                  permissions=telegram.ChatPermissions(can_send_messages=False))
         # bot.kick_chat_member(game.group_id, self.real_id)
     except Exception as e:
         print(e)
Beispiel #4
0
def r_msg_freq(update, context, secs):
    update.message.reply_text("Астанавитесь!")
    perms = telegram.ChatPermissions(can_send_messages=False,
                                     can_send_media_messages=False,
                                     can_send_polls=False,
                                     can_send_other_messages=False,
                                     can_add_web_page_previews=False,
                                     can_change_info=False,
                                     can_invite_users=False,
                                     can_pin_messages=False)
    context.bot.restrict_chat_member(
        update.message.chat.id, update.message.from_user.id, perms,
        (update.message.date + datetime.timedelta(seconds=secs)))
Beispiel #5
0
def mute(update, context):
    m = extract.sudocheck(update, context)
    if m == 2:
        return
    elif m == 1:
        n = extract.sudocheck(update, context, 0)
        if n == 0:
            update.message.reply_text(
                "I'm afraid I can't stop an owner from speaking...")
            return
        elif n == 1:
            update.message.reply_text(
                "Dang ! I can't hold back an admin from speaking !")
            return

    msg = update.message.reply_to_message
    res = update.message.text.split(None, 1)

    user_id = msg.from_user.id
    chat_id = update.effective_chat.id
    user_name = msg.from_user.username
    first_name = msg.from_user.first_name

    current = eval(str(context.bot.getChat(chat_id).permissions))
    new = {
        'can_send_messages': False,
        'can_send_media_messages': False,
        'can_send_polls': False,
        'can_send_other_messages': False,
        'can_add_web_page_previews': False,
        'can_invite_users': False
    }

    permissions = {
        'can_send_messages': None,
        'can_send_media_messages': None,
        'can_send_polls': None,
        'can_send_other_messages': None,
        'can_add_web_page_previews': None,
        'can_change_info': None,
        'can_pin_messages': None
    }

    permissions.update(current)
    permissions.update(new)
    new_permissions = telegram.ChatPermissions(**permissions)

    context.bot.restrict_chat_member(chat_id,
                                     user_id,
                                     permissions=new_permissions)
    update.message.reply_text("Muted " + str(first_name) + " !")
Beispiel #6
0
def unlock_member(update, callback):
    """

            :param update: telegram.Update
            :type bot: telegram.Bot
    """
    chat_id = update.effective_chat.id
    bot = callback.bot
    if not can_restrict_users(bot, chat_id=chat_id):
        return
    query = update.callback_query
    if "applied" not in query.data:
        return
    user_id = update.effective_user.id
    if str(user_id) not in query.data:
        return
    with dataWorker.session_scope() as session:
        lock_info_query = session.query(MutedUser).filter(MutedUser.chat_id == chat_id,
                                                          MutedUser.user_id == user_id)
        lock_info: MutedUser = lock_info_query.first()
        current = datetime.datetime.utcnow()
        required = lock_info.mute_date
        time_to_mute = lock_info.chat.time_to_mute
        time_to_mute = 30 if time_to_mute is None else time_to_mute
        resulted_time = current - datetime.timedelta(seconds=time_to_mute)
        time_over = required < resulted_time
        if not time_over:
            message = API.send_message(bot, chat_id=chat_id, text="А лукавить нехорошо. Пожалуйста, прочитайте");
            dbWorker.add_time_message(lock_info, message)
            return
        API.restrict_chat_member(bot,
                                 pass_exception=True,
                                 chat_id=chat_id,
                                 user_id=user_id,
                                 permissions=telegram.ChatPermissions(
                                     can_send_messages=True,
                                     can_send_media_messages=True,
                                     can_send_other_messages=True,
                                     can_add_web_page_previews=True)
                                 )
        delete_welcome_message(lock_info, bot)
        session.delete(lock_info)
Beispiel #7
0
def unmute(update, context):
    m = extract.sudocheck(update, context)
    if m == 2:
        return

    msg = update.message.reply_to_message

    user_id = msg.from_user.id
    chat_id = update.effective_chat.id
    user_name = msg.from_user.username
    first_name = msg.from_user.first_name

    current = eval(str(context.bot.getChat(chat_id).permissions))
    new = {
        'can_send_messages': True,
        'can_send_media_messages': True,
        'can_send_polls': True,
        'can_send_other_messages': True,
        'can_add_web_page_previews': True,
    }

    permissions = {
        'can_send_messages': None,
        'can_send_media_messages': None,
        'can_send_polls': None,
        'can_send_other_messages': None,
        'can_add_web_page_previews': None,
        'can_change_info': None,
        'can_invite_users': None,
        'can_pin_messages': None
    }

    permissions.update(current)
    permissions.update(new)
    new_permissions = telegram.ChatPermissions(**permissions)

    context.bot.restrict_chat_member(chat_id,
                                     user_id,
                                     permissions=new_permissions)
    update.message.reply_text("Unmuted " + str(first_name) + " !")
Beispiel #8
0
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from typing import NewType
import telegram
import json


TOKEN = os.environ.get('TOKEN')
PORT = int(os.environ.get('PORT', '8000'))
HOST = os.environ.get('HOST', '')
LISTEN_ADDR = os.environ.get('LISTEN_ADDR', '0.0.0.0')

PERM_NO_NOTHING = telegram.ChatPermissions(
        can_send_messages=False
        , can_send_media_messages=False
        , can_send_polls=False
        , can_send_other_messages=False
        , can_add_web_page_previews=False
        , can_invite_users=False
        , can_pin_messages=False
        , can_change_info=False
    )

class DbMan(object):
    def __init__(self,dbname):
        self.conn = sqlite3.connect(dbname, check_same_thread=False)
        self.conn.create_function('uuidgen',1,uuid.uuid4())
        self.cur = self.conn.cursor()

    def query(self, arg:str):
        self.cur.execute(arg)
        self.conn.commit()
        return self.cur
def warn_strike(update, context):
    database.create_settings_base()
    m = extract.sudocheck(update, context)
    if m == 2:
        return
    else:
        n = extract.sudocheck(update, context, objective=0, udel=0)
        if n == 0:
            update.message.reply_text("Try /rip instead...")
            return
        elif n == 1:
            update.message.reply_text("Can't warn an Admin !")
            return

    reason = "~"

    try:
        res = update.message.text.split(None, 1)
        reason = res[1]
    except:
        pass

    msg = update.message.reply_to_message

    warn_user_id = str(msg.from_user.id)
    warn_by_user_id = str(update.message.from_user.id)
    msg_id = msg.message_id

    chat = msg['chat']
    chat_idd = chat.id
    chat_id = re.sub(r'[^\w]', '', str(chat_idd))

    database.create_warn_base()
    rem = database.add_warn_base_2(chat_id=chat_id,
                                   user_id=warn_user_id,
                                   striked_by=warn_by_user_id,
                                   message_id=msg_id,
                                   reason=reason,
                                   remove=0)

    sett = database.add_settings_base(chat_id=chat_id)
    text = ""
    warn_lim = sett[0][0]
    action = sett[0][1]
    a = 0
    if int(rem) >= int(warn_lim):
        text = ("<a href='tg://user?id=" + str(warn_user_id) + "'>" +
                msg.from_user.first_name + "</a>" +
                " has been warn struck by " + "<a href='tg://user?id=" +
                str(update.message.from_user.id) + "'>" +
                str(update.message.from_user.first_name) + "</a> !"
                "\n\nReason : '<i><a href='https://telegram.me/" +
                chat.username + "/" + str(msg_id) + "'>" + reason +
                "</a></i>'" + "\nStrikes  : <b>" + rem + "/" + warn_lim +
                "</b> " + "\n\n<b>Limit Reached !</b>" + " (Action : <b>" +
                action + "</b>)")
        a = 1

    else:
        text = ("<a href='tg://user?id=" + str(warn_user_id) + "'>" +
                msg.from_user.first_name + "</a>" +
                " has been warn struck by " + "<a href='tg://user?id=" +
                str(update.message.from_user.id) + "'>" +
                str(update.message.from_user.first_name) + "</a> !"
                "\n\nReason : '<i><a href='https://telegram.me/" +
                chat.username + "/" + str(msg_id) + "'>" + reason +
                "</a></i>'" + "\nStrikes  : <b>" + rem + "/" + warn_lim +
                "</b> " + "\n\n<b>" + warn_lim + " of " + warn_lim + "</b>" +
                " strikes result in <b>" + sett[0][1] + "</b>, So watch out !")

    if a == 1:
        i = ""
        if action == "mute":

            current = eval(str(context.bot.getChat(chat_idd).permissions))
            new = {
                'can_send_messages': False,
                'can_send_media_messages': False,
                'can_send_polls': False,
                'can_send_other_messages': False,
                'can_add_web_page_previews': False,
            }

            permissions = {
                'can_send_messages': None,
                'can_send_media_messages': None,
                'can_send_polls': None,
                'can_send_other_messages': None,
                'can_add_web_page_previews': None,
                'can_change_info': None,
                'can_invite_users': None,
                'can_pin_messages': None
            }

            permissions.update(current)
            permissions.update(new)
            new_permissions = telegram.ChatPermissions(**permissions)

            context.bot.restrict_chat_member(chat_idd,
                                             warn_user_id,
                                             permissions=new_permissions)
            i = "<a href='tg://user?id=" + str(
                warn_user_id
            ) + "'>" + msg.from_user.first_name + "</a>" + " has been <b>Muted</b> !"
            pass

        elif action == "kick":
            kick = update.effective_chat.unban_member(warn_user_id)
            #i = "<a href='tg://user?id=" + str(warn_user_id) + "'>" + msg.from_user.first_name +"</a>" + " has been <b>Kicked</b> !"
        elif action == "ban":
            ban = update.effective_chat.kick_member(warn_user_id)
            i = "<a href='tg://user?id=" + str(
                warn_user_id
            ) + "'>" + msg.from_user.first_name + "</a>" + " has been <b>Banned</b> !"

        context.bot.send_message(chat_id=chat_idd, text=i, parse_mode="HTML")

    update.message.reply_text(text=text,
                              parse_mode="HTML",
                              disable_web_page_preview=True)