def ban_invited_bots(message): if not validate_command(message, check_isinchat=True): return new_users.ban_bots(message) new_users.restrict(message) bot.delete_message(chat_id=message.chat.id, message_id=message.message_id)
def bl_add(message, is_forward): user = message.reply_to_message.forward_from if is_forward else message.reply_to_message.from_user with shelve.open(config.data_name, 'c', writeback=True) as data: data['admins'] = config.admins_default if not data.get( 'admins') else data['admins'] data['whitelist'] = {} if not data.get( 'whitelist') else data['whitelist'] data['blacklist'] = {} if not data.get( 'blacklist') else data['blacklist'] user_id = user.id # Checks the user's list status and acts accordingly if user_id in data['blacklist']: send_to_admin(message, 'User {} is already blacklisted.', data['admins'], is_forward) return if user_id in data['whitelist']: del data['whitelist'][user_id] data['blacklist'][user_id] = [ ' '.join(get_user(user).split(' ')[1:]), message.from_user.id ] bot.delete_message(chat_id=message.chat.id, message_id=message.reply_to_message.message_id) send_to_admin(message, 'User {} has been successfully added to the blacklist.', data['admins'], is_forward)
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 sticker_message(msg): if any(msg.sticker.file_id == sticker_ID for sticker_ID in config.stickers_black_list): bot.delete_message(msg.chat.id, msg.message_id) logger.info("{:s}: [STICKER] {:s} in BLACKLIST! Deleted!".format( msg.from_user.first_name, msg.sticker.file_id)) logger.info("{:s}: [STICKER] {:s}".format(msg.from_user.first_name, msg.sticker.file_id))
def paste(message): source = message.reply_to_message source_text = source.text or source.caption new_paste = make_paste(source_text, source.from_user.first_name) if not new_paste: return bot.reply_to(source, text=new_paste, disable_web_page_preview=True) bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) logger.info( "User {0} has requested a paste version of a message {1}".format( get_user(message.from_user), message.reply_to_message.message_id))
def photo_receive(message): ''' Recognizes photos with the comment "персик" Ban for NSFW ''' file_id = message.photo[len(message.photo) - 1].file_id if message.caption and message.forward_from is None: if re.match('(?i)(\W|^).*?!п[eеэ][pр][cс](и|ч[eеи]к).*?(\W|$)', message.caption): bot.reply_to(message, "".join([ message.from_user.first_name, picturedetect.reply_get_concept_msg(file_id) ]), parse_mode='Markdown') logger.info("Photo by Username @{:s} | ID {:s}".format( (message.from_user.username or "NONE"), file_id)) try: os.makedirs("./photos") except FileExistsError: pass file_patch = './photos/{:s}.jpg'.format(file_id) _file = Path(file_patch) if _file.is_file() is not True: file_info = bot.get_file(file_id) file_patch = utils.file_download(file_info, './photos/') if file_patch is None: logger.error("File download error!'") bot.reply_to(message, ru_strings.SOME_ERROR_MESSAGE['strings'], parse_mode='Markdown') bot.send_sticker(message.chat.id, ru_strings.SOME_ERROR_MESSAGE['stickers'][0]) return if not allow_nsfw: if picturedetect.nsfw_test(file_patch, 0.75): bot.delete_message(message.chat.id, message.message_id) bot.send_message( message.chat.id, "*{} уходит в бан на {} {}! Причина: NSFW*".format( message.from_user.first_name, 2, 'мин.'), parse_mode='Markdown') ban_user(message.chat.id, message.from_user.id, 2 * 60)
def false_ban(message): ''' Ban prank KEK For meanmail exclusive ''' orig_time = time = 40 if message.chat.type != 'private' and message.reply_to_message is None: bot.delete_message(message.chat.id, message.message_id) time_str = re.search('[0-9]{1,8}', message.text) if time_str: orig_time = time = int(time_str.group(0)) time_time = re.search('([0-9]{1,5})\s?(с(ек)?|м(ин)?|ч(ас)?|д(ен|н)?)', message.text) time_text = 'сек.' if time_time: text = re.search('[А-Яа-я]{1,2}', time_time.group(0)) if text: if text.group(0)[0] == "м": time = time * 60 time_text = "мин." elif text.group(0)[0] == "ч": time = time * 60 * 60 time_text = "ч." elif text.group(0)[0] == "д": time = time * 24 * 60 * 60 time_text = "д." user_to_ban = None ban_message_num = int(time < 30) if message.chat.type == 'private': user_to_ban = message.reply_to_message.forward_from elif message.reply_to_message is None: user_to_ban = message.from_user ban_message_num = 2 else: user_to_ban = message.reply_to_message.from_user if message.from_user.id == message.reply_to_message.from_user.id: ban_message_num = 2 try: bot.send_message( config.send_chat_id, ru_strings.BAN_MESSAGE['strings'][ban_message_num].format( user_to_ban.first_name, orig_time, time_text), parse_mode='Markdown') except Exception as e: logger.error("[ban_command()] Unexpected error: {}".format(e))
def user_penalty_off(message): ''' Disables the restriction of users to use certain letters. ''' bot.delete_message(message.chat.id, message.message_id) if message.reply_to_message: if penalty_users_id.count(message.reply_to_message.from_user.id) == 1: penalty_users_id.remove(message.reply_to_message.from_user.id) bot.send_message( message.chat.id, "*Пользователь {} прощен!*".format( message.reply_to_message.from_user.first_name), parse_mode='Markdown')
def user_penalty_on(message): ''' Enables the restriction of users to use certain letters. ''' bot.delete_message(message.chat.id, message.message_id) if message.reply_to_message: if penalty_users_id.count(message.reply_to_message.from_user.id) == 0: penalty_users_id.append(message.reply_to_message.from_user.id) bot.send_message( message.chat.id, "*Пользователь {} наказан! Недоступны буквы: a, у, е*".format( message.reply_to_message.from_user.first_name), parse_mode='Markdown')
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 text_to_speech_voice(message): try: bot.delete_message(message.chat.id, message.message_id) except Exception as e: logger.error("(TTS) Unexpected error: {}".format(e)) if message.reply_to_message: text = message.reply_to_message.text else: text = message.text[11:] file = text_to_speech(text) with open(file, 'rb') as audio: bot.send_voice(message.chat.id, voice=audio)
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 roulette_game(message): if message.chat.type != 'private': # Only in chat r_number = randrange(0, 6) if r_number == 3: bot.send_message(message.chat.id, ru_strings.ROULETTE_MESSAGE['strings'][0].format( message.from_user.first_name), parse_mode='Markdown') ban_user(config.send_chat_id, message.from_user.id, 1200) else: msg = bot.send_message( message.chat.id, ru_strings.ROULETTE_MESSAGE['strings'][1].format( message.from_user.first_name), parse_mode='Markdown') sleep(10) bot.delete_message(message.chat.id, message.message_id) bot.delete_message(msg.chat.id, msg.message_id)
def persik_keyword(message): if message.forward_from: return try: logger.info("!Persik command by {:s}, Username @{:s}".format( message.from_user.first_name, (message.from_user.username or "NONE"))) if message.reply_to_message and message.reply_to_message.photo: file_info = bot.get_file(message.reply_to_message.photo[ len(message.reply_to_message.photo) - 1].file_id) msg = picturedetect.reply_get_concept_msg(file_info.file_id) if msg is None: bot.reply_to(message, ru_strings.SOME_ERROR_MESSAGE['strings'], parse_mode='Markdown') bot.send_sticker(message.chat.id, ru_strings.SOME_ERROR_MESSAGE['stickers'][0]) return bot.delete_message(message.chat.id, message.message_id) bot.reply_to(message.reply_to_message, "".join([message.from_user.first_name, msg]), parse_mode='Markdown') return if len(message.text) < 10: come_here_message(message) return for template in MESSAGE_TEMPLATES: if re.search(template[0], message.text, re.I | re.U): template[1](message) return random_message(message, ru_strings.NA_MESSAGE, REPLY_MESSAGE) logger.info("UNKNOWN command by {:s}, Username @{:s}".format( message.from_user.first_name, (message.from_user.username or "NONE"))) except Exception as e: logger.error("(persik_keyword) Unexpected error: {}".format(e))
def require_approval(message, require_text, admins, too_long=False): admins_failed_contact = [] # Tries to delete the original message from the main chat try: bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) # If bot hasn't got the rights, or the message has already been deleted # Aborts deletion except ApiException as e: if str(e.result) == r'<Response [400]>': bot.send_message(config.chat_id, 'ERROR!\nCan\'t delete the message! Please, grant me '\ 'admin rights in your group or make sure that the message has not been already deleted.') logger.error( 'Can\'t delete the message! Admin rights required or the message is already deleted!' ) else: print(e.result) logger.exception('ApiException.') # Initializes the main judgment keyboard keyboard = types.InlineKeyboardMarkup(row_width=2) button_yes = types.InlineKeyboardButton(text='✅ Yes', callback_data='yes') button_no = types.InlineKeyboardButton(text='🚫 No', callback_data='no') button_untrusted = types.InlineKeyboardButton( text='❌ Restrict this user from posting any links', callback_data='untrusted') button_banned = types.InlineKeyboardButton(text='☠️ Ban this user', callback_data='banned') keyboard.add(button_yes, button_no) keyboard.add(button_untrusted) keyboard.add(button_banned) # Initializes the backup judgment keyboard for a case, when it's impossible # to get the user's date (message is too large to add anything) keyboard_backup = types.InlineKeyboardMarkup(row_width=2) button_yes_backup = types.InlineKeyboardButton(text='✅ Yes', callback_data='yes_huge') button_no_backup = types.InlineKeyboardButton(text='🚫 No', callback_data='no_huge') keyboard_backup.add(button_yes_backup, button_no_backup) # Initializes the judgment keyboard kb = keyboard_backup if too_long else keyboard # Tries to deliver the judgment message to all admins for admin in admins: try: bot.send_message(admin, require_text, reply_markup=kb) except ApiException as e: if str(e.result) == r'<Response [403]>': admins_failed_contact.append(admin) logger.error('Admin {} couldn\'t be reached'.format( admins[admin])) continue else: print(e.result) logger.exception('ApiException.') # If none of the admins were reached # sends an error message to the chat if admins_failed_contact == [*admins]: bot.send_message(config.chat_id, 'ERROR!\nCouldn\'t contact any of the admins.')
def meta_question(message): source = message.reply_to_message bot.reply_to(source, text=config.nometa) bot.delete_message(message_id=message.message_id, chat_id=message.chat.id)
def edit_handler(message): if penalty_users_id.count(message.from_user.id) > 0: if any((c in penalty_letter_set) for c in message.text): bot.delete_message(message.chat.id, message.message_id)
def report_to_admins(message): if not validate_command(message, check_isreply=True): bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) return report.my_report(message)
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))
def ban_user_command(message): ''' Alot of magic ''' orig_time = 40 time = 40 administrators = bot.get_chat_administrators(message.chat.id) if message.reply_to_message is not None: if all(message.from_user.id != member.user.id for member in administrators) and \ message.from_user.id != message.reply_to_message.from_user.id: return if message.chat.type != 'private' and message.reply_to_message is None: bot.delete_message(message.chat.id, message.message_id) time_str = re.search('[0-9]{1,8}', message.text) if time_str: orig_time = time = int(time_str.group(0)) time_time = re.search('([0-9]{1,8})\s?(с(ек)?|м(ин)?|ч(ас)?|д(ен|н)?)', message.text) time_text = 'сек.' if time_time: text = re.search('[А-Яа-я]{1,2}', time_time.group(0)) if text: if text.group(0)[0] == "м": time = time * 60 time_text = "мин." elif text.group(0)[0] == "ч": time = time * 60 * 60 time_text = "ч." elif text.group(0)[0] == "д": time = time * 24 * 60 * 60 time_text = "д." user_to_ban = None ban_message_num = int(time < 30) if message.chat.type == 'private': if all(message.from_user.id != user for user in config.allowed_users): return user_to_ban = message.reply_to_message.forward_from elif message.reply_to_message is None: user_to_ban = message.from_user ban_message_num = 2 if time < 40: time = 40 orig_time = 40 else: user_to_ban = message.reply_to_message.from_user if message.from_user.id == message.reply_to_message.from_user.id: ban_message_num = 2 if time < 40: time = 40 orig_time = 40 try: ban_user(config.send_chat_id, user_to_ban.id, time) bot.send_message( config.send_chat_id, ru_strings.BAN_MESSAGE['strings'][ban_message_num].format( user_to_ban.first_name, orig_time, time_text), parse_mode='Markdown') logger.info("User {}, Username @{} - banned!".format( user_to_ban.id, (user_to_ban.username or "NONE"))) except Exception as e: logger.error("[ban_command()] Unexpected error: {}".format(e))