def captcha_handler(call): user_id = call.from_user.id distinct_key = new_users.build_distinct_key(call.message) if not config.r.exists(distinct_key): return # captcha message doesn't exists user_belong_to_this_captcha = config.r.srem(distinct_key, user_id) if not user_belong_to_this_captcha: return bot.answer_callback_query(call.id, text="Это сообщение не для тебя.") restricted_users_left = config.r.scard(distinct_key) if not restricted_users_left: # if not users left for current captcha, remove captcha message config.r.delete(distinct_key) bot.delete_message(config.chat_id, call.message.message_id) # cancel restriction job because all users already solved the captcha new_users.SCHEDULED_JOBS[new_users.build_distinct_key( call.message)].cancel() if call.data == "captcha_passed": bot.restrict_chat_member(chat_id=config.chat_id, user_id=user_id, can_send_messages=True) new_users.add_user(call.from_user) new_users.restrict(user_id) bot.answer_callback_query(call.id, text="Welcome!") else: new_users.kick_member(user_id)
def on_user_joins(message): logger.info("New chat member, username: @{:s}".format( message.from_user.username or "NONE")) print(message) if re.search(r"\b[bб6][оo][т7t]\b", message.from_user.first_name, re.IGNORECASE | re.UNICODE) or \ re.search(r"\b[bб6][оo][т7t]\b", message.from_user.last_name, re.IGNORECASE | re.UNICODE): if message.from_user.username is not None: username_str = '@{}'.format(message.from_user.username) else: username_str = message.from_user.first_name or 'Ноунейм' message_str = "Возможно [{}] - это бот!\n@via_tcp\n@content_of_brain\n@lopotyana".format( username_str) bot.send_message(message.chat.id, message_str) bot.restrict_chat_member(message.chat.id, message.from_user.id, 0, False, False, False, False) return # Use firstname if username is NONE if message.from_user.username is not None: username_str = '@{}'.format(message.from_user.username) else: username_str = message.from_user.first_name or 'Ноунейм' message_str = "{} готов(а) сжигать пукан свой в пепел вместе с нами!!🔥\nВстречайте героя!👻".format( username_str) bot.send_message(message.chat.id, message_str)
def scan_for_spam(message): messages_count = watching_newcomers(message.from_user.id) if messages_count < 10: monitor.scan_contents(message) elif messages_count == 10: bot.restrict_chat_member( chat_id=config.chat_id, user_id=message.from_user.id, can_send_messages=True, can_send_media_messages=True, can_send_other_messages=True, can_add_web_page_previews=True, )
def chair_bonjour(call): new_user_id = call.data[len( 'choice1$'):] # substring ID from callback data if new_user_id != str(call.from_user.id): # Ignore existing chat memders return # Delete our message bot.delete_message(call.message.chat.id, call.message.message_id) if 'choice1' in call.data: # First button or second button(choice1 or choice2) logger.info("[Bonjour]: @{:s} pressed FIRST button!".format( call.from_user.username or "NONE")) # Getting current timestamp d = datetime.utcnow() d = d + timedelta(0, 30) timestamp = calendar.timegm(d.utctimetuple()) # Catch "user is an administrator of the chat" Exception try: # Ban user from chat for 30 seconds bot.kick_chat_member(call.message.chat.id, new_user_id, until_date=timestamp) except Exception: logger.info( "[EXCEPTION] Bad Request: User is an administrator of the chat!" ) else: logger.info("[Bonjour]: @{:s} pressed SECOND button!".format( call.from_user.username or "NONE")) # Use firstname if username is NONE if call.from_user.username is not None: username_str = '@{}'.format(call.from_user.username) else: username_str = call.from_user.first_name or 'Ноунейм' bot.send_message( call.message.chat.id, username_str + ' решил(а) остатся!☝️ \nВстречайте героя!👻') # Catch "can't demote chat creator" Exception try: # Unrestrict user bot.restrict_chat_member(call.message.chat.id, call.from_user.id, 1, True, True, True, True) except Exception: logger.info("[EXCEPTION] Bad Request: can't demote chat creator!")
def ro_giver(message, r): """Gives RO to users who flood with the !report command, or bans those who have more than 3 warnings """ bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) if int(r.get( message.reply_to_message.message_id)) == config.report_threshold: return session = Session() user_obj = session.query(User).get(message.from_user.id) if not user_obj: user_obj = User(message.from_user.id) session.add(user_obj) session.commit() if message.from_user.id in config.admin_ids: logger.info("Admin {} is flooding with !report. Doing nothing".format( get_user(message.from_user))) session.close() return user_obj.ro_level += 1 session.commit() if user_obj.ro_level < 4: user_ro_minutes = config.ro_levels[user_obj.ro_level] bot.restrict_chat_member( chat_id=config.chat_id, user_id=message.from_user.id, until_date=time.time() + 60 * user_ro_minutes, ) logger.info( "User {0} got {1} minutes of RO for flooding with !report".format( get_user(message.from_user), user_ro_minutes)) else: bot.kick_chat_member(chat_id=config.chat_id, user_id=message.from_user.id) session.delete(user_obj) logger.info("User {} has been banned for flooding with !report".format( get_user(message.from_user))) session.close()
def justify(message): source = message.reply_to_message if not validate_command(message, check_isadmin=True): return if perfect_justice(): bot.reply_to(source, text="Bang! РО на день") tomorrow = datetime.date.today() + datetime.timedelta(1) unix_time = tomorrow.strftime("%s") bot.restrict_chat_member( chat_id=config.chat_id, user_id=source.from_user.id, until_date=unix_time ) else: bot.reply_to(source, text="Lucky one") bot.delete_message(chat_id=message.chat.id, message_id=message.message_id)
def ban_user(chat_id, user_id, time): ''' Restricting chat member Parameters ---------- chat_id : str or int Chat ID user_id : str or int User ID time : int Time in seconds ''' d = datetime.utcnow() d = d + timedelta(0, time) timestamp = calendar.timegm(d.utctimetuple()) bot.restrict_chat_member(chat_id, user_id, timestamp, False, False, False, False)
def callback_inline(call): user_id = int(call.message.text.split(" ")[3]) message_id = int(call.message.text.split(" ")[7]) if not r.get(message_id): bot.answer_callback_query(call.id, text="Это сообщение уже отмодерировано.") return r.delete(message_id) if call.data == "ban": bot.kick_chat_member(chat_id=config.chat_id, user_id=user_id) elif call.data == "release": bot.restrict_chat_member( chat_id=config.chat_id, user_id=user_id, can_send_messages=True, can_send_media_messages=True, can_send_other_messages=True, can_add_web_page_previews=True, ) bot.answer_callback_query(call.id, text="OK.")
def restrict(message): """ Forbid new users from sending inline bot spam. """ session = Session() for new_member in message.new_chat_members: member = session.query(User).filter( User.user_id == new_member.id).one_or_none() # Skip restriction if user already have messages. if member is not None and member.msg_count >= 10: continue bot.restrict_chat_member( chat_id=config.chat_id, user_id=new_member.id, can_send_other_messages=False, can_send_messages=True, can_send_media_messages=True, can_add_web_page_previews=True, ) session.close()
def punisher(message): """Gives RO to user who posted the message, deletes the message from chat, forwards the deleted message to the admins, triggers judgment buttons """ session = Session() user_obj = session.query(User).get(message.from_user.id) if not user_obj: user_obj = User(message.from_user.id) session.add(user_obj) else: user_obj.msg_count -= 1 session.commit() session.close() if r.get("spammer_{}".format(message.from_user.id)): bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) logger.info( "Message {} has been deleted without alerting the admins due to flooding" .format(message.message_id)) return if message.from_user.id not in config.admin_ids: bot.restrict_chat_member(chat_id=config.chat_id, user_id=message.from_user.id) logger.info( "User {} has been restricted for leading to a channel".format( get_user(message.from_user))) r.set(message.message_id, 1) r.set("spammer_{}".format(message.from_user.id), 1, ex=config.spammer_timeout) judgement_text = ("Reported user's ID: {} \n" "Reported message's ID: {} \n" "Что будем делать?".format(message.from_user.id, message.message_id)) keyboard = types.InlineKeyboardMarkup(row_width=2) btn_ban = types.InlineKeyboardButton(text="Отправить в бан", callback_data="ban") btn_release = types.InlineKeyboardButton(text="Снять РО", callback_data="release") keyboard.add(btn_ban, btn_release) for admin_id in config.admin_ids: try: reported = bot.forward_message( chat_id=admin_id, from_chat_id=config.chat_id, message_id=message.message_id, ) bot.reply_to(reported, judgement_text, reply_markup=keyboard) except ApiException as e: if str(e.result) == config.unreachable_exc: continue bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) logger.info("Message {} has been successfully auto-reported".format( message.message_id))