def extract_user_and_text(message: Message, args: List[str]) -> (Optional[int], Optional[str]): prev_message = message.reply_to_message split_text = message.text.split(None, 1) if len(split_text) < 2: return id_from_reply(message) # only option possible text_to_parse = split_text[1] text = "" entities = list(message.parse_entities([MessageEntity.TEXT_MENTION])) if len(entities) > 0: ent = entities[0] else: ent = None # if entity offset matches (command end/text start) then all good if entities and ent and ent.offset == len( message.text) - len(text_to_parse): ent = entities[0] user_id = ent.user.id text = message.text[ent.offset + ent.length:] elif len(args) >= 1 and args[0][0] == '@': user = args[0] user_id = get_user_id(user) if not user_id: return "error ", " I have no users on my db. You will be able to interact with them if you reply to that person's message, or forward one of that user's messages." else: user_id = user_id res = message.text.split(None, 2) if len(res) >= 3: text = res[2] elif len(args) >= 1 and args[0].isdigit(): user_id = int(args[0]) res = message.text.split(None, 2) if len(res) >= 3: text = res[2] elif prev_message: user_id, text = id_from_reply(message) else: return None, None try: message.bot.get_chat(user_id) except BadRequest as excp: if excp.message in ("User_id_invalid", "Chat not found"): return "error", "I don't seem to have interacted with this user before - feel free to forward a message from them to give me control! (Like a voodoo doll, I need a piece of being able to execute certain commands ...)" else: LOGGER.exception("Exception %s on user %s", excp.message, user_id) return None, None return user_id, text
def purge(update, context): args = context.args msg = update.effective_message # type: Optional[Message] if msg.reply_to_message: user = update.effective_user # type: Optional[User] chat = update.effective_chat # type: Optional[Chat] if user_can_delete(chat, user, context.bot.id): message_id = msg.reply_to_message.message_id if args and args[0].isdigit(): delete_to = message_id + int(args[0]) else: delete_to = msg.message_id - 1 for m_id in range(delete_to, message_id - 1, -1): # Reverse iteration over message ids try: context.bot.deleteMessage(chat.id, m_id) except BadRequest as err: if err.message == "Message can't be deleted": send_message( update.effective_message, tl( update.effective_message, "Tidak dapat menghapus semua pesan. Pesannya mungkin terlalu lama, saya mungkin " "tidak memiliki hak menghapus, atau ini mungkin bukan supergrup." )) elif err.message != "Message to delete not found": LOGGER.exception("Error while purging chat messages.") try: msg.delete() except BadRequest as err: if err.message == "Message can't be deleted": send_message( update.effective_message, tl( update.effective_message, "Tidak dapat menghapus semua pesan. Pesannya mungkin terlalu lama, saya mungkin " "tidak memiliki hak menghapus, atau ini mungkin bukan supergrup." )) elif err.message != "Message to delete not found": LOGGER.exception("Error while purging chat messages.") send_message(update.effective_message, tl(update.effective_message, "Pembersihan selesai.")) return "<b>{}:</b>" \ "\n#PURGE" \ "\n<b>Admin:</b> {}" \ "\nPurged <code>{}</code> messages.".format(html.escape(chat.title), mention_html(user.id, user.first_name), delete_to - message_id) else: send_message( update.effective_message, tl(update.effective_message, "Balas pesan untuk memilih tempat mulai membersihkan.")) return ""
def get_user_id(username): # ensure valid userid if len(username) <= 5: return None if username.startswith('@'): username = username[1:] users = sql.get_userid_by_name(username) if not users: return None elif len(users) == 1: return users[0].user_id else: for user_obj in users: try: userdat = dispatcher.bot.get_chat(user_obj.user_id) if userdat.username == username: return userdat.id except BadRequest as excp: if excp.message == 'Chat not found': pass else: LOGGER.exception("Error extracting user ID") return None
def __list_all_modules(): from os.path import dirname, basename, isfile import glob # This generates a list of modules in this folder for the * in __main__ to work. mod_paths = glob.glob(dirname(__file__) + "/*.py") all_modules = [ basename(f)[:-3] for f in mod_paths if isfile(f) and f.endswith(".py") and not f.endswith('__init__.py') ] if LOAD or NO_LOAD: to_load = LOAD if to_load: if not all( any(mod == module_name for module_name in all_modules) for mod in to_load): LOGGER.error("Invalid loadorder names. Quitting.") quit(1) else: to_load = all_modules if NO_LOAD: LOGGER.info("Not loading: {}".format(NO_LOAD)) return [item for item in to_load if item not in NO_LOAD] return to_load return all_modules
def del_lockables(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[Message] for lockable, filter in LOCK_TYPES.items(): if filter(message) and sql.is_locked(chat.id, lockable) and can_delete(chat, bot.id): if lockable == "bots": new_members = update.effective_message.new_chat_members for new_mem in new_members: if new_mem.is_bot: if not is_bot_admin(chat, bot.id): message.reply_text("Saya melihat bot, dan saya diberitahu untuk menghentikan mereka bergabung... " "tapi saya bukan admin!") return chat.kick_member(new_mem.id) message.reply_text("Hanya admin yang diizinkan menambahkan bot ke obrolan ini! Keluar dari sini!") else: try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("ERROR in lockables") break
def help_button(bot: Bot, update: Update): query = update.callback_query mod_match = re.match(r"help_module\((.+?)\)", query.data) prev_match = re.match(r"help_prev\((.+?)\)", query.data) next_match = re.match(r"help_next\((.+?)\)", query.data) back_match = re.match(r"help_back", query.data) print(query.message.chat.id) try: if mod_match: module = mod_match.group(1) text = tl(update.effective_message, "Ini bantuan untuk modul *{}*:\n").format(HELPABLE[module].__mod_name__) \ + tl(update.effective_message, HELPABLE[module].__help__) query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text=tl(query.message, "Kembali"), callback_data="help_back") ]])) elif prev_match: curr_page = int(prev_match.group(1)) query.message.reply_text(text=tl(query.message, HELP_STRINGS), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules( curr_page - 1, HELPABLE, "help"))) elif next_match: next_page = int(next_match.group(1)) query.message.reply_text(text=tl(query.message, HELP_STRINGS), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules( next_page + 1, HELPABLE, "help"))) elif back_match: query.message.reply_text(text=tl(query.message, HELP_STRINGS), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules(0, HELPABLE, "help"))) # ensure no spinny white circle query.message.delete() bot.answer_callback_query(query.id) except Exception as excp: if excp.message == "Message is not modified": pass elif excp.message == "Query_id_invalid": pass elif excp.message == "Message can't be deleted": pass else: query.message.edit_text(excp.message) LOGGER.exception("Exception in help buttons. %s", str(query.data))
def help_button(update, context): query = update.callback_query mod_match = re.match(r"help_module\((.+?)\)", query.data) prev_match = re.match(r"help_prev\((.+?)\)", query.data) next_match = re.match(r"help_next\((.+?)\)", query.data) back_match = re.match(r"help_back", query.data) print(query.message.chat.id) try: if mod_match: module = mod_match.group(1) text = tl(update.effective_message, "Isso é ajuda para o módulo *{}*:\n").format(HELPABLE[module].__mod_name__) \ + tl(update.effective_message, HELPABLE[module].__help__) query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text=tl(query.message, "Voltar"), callback_data="help_back") ]])) elif prev_match: curr_page = int(prev_match.group(1)) query.message.reply_text(text=tl(query.message, HELP_STRINGS), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules( curr_page - 1, HELPABLE, "help"))) elif next_match: next_page = int(next_match.group(1)) query.message.reply_text(text=tl(query.message, HELP_STRINGS), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules( next_page + 1, HELPABLE, "help"))) elif back_match: query.message.reply_text(text=tl(query.message, HELP_STRINGS), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules(0, HELPABLE, "help"))) query.message.delete() context.bot.answer_callback_query(query.id) except Exception as excp: if excp.message == "A mensagem não pode ser modificada": pass elif excp.message == "Query_id_invalid": pass elif excp.message == "A mensagem não pode ser excluída": pass else: query.message.edit_text(excp.message) LOGGER.exception("Exception in help buttons. %s", str(query.data))
def extract_user_and_text(message: Message, args: List[str]) -> (Optional[int], Optional[str]): prev_message = message.reply_to_message split_text = message.text.split(None, 1) if len(split_text) < 2: return id_from_reply(message) # only option possible text_to_parse = split_text[1] text = "" entities = list(message.parse_entities([MessageEntity.TEXT_MENTION])) if len(entities) > 0: ent = entities[0] else: ent = None # if entity offset matches (command end/text start) then all good if entities and ent and ent.offset == len(message.text) - len(text_to_parse): ent = entities[0] user_id = ent.user.id text = message.text[ent.offset + ent.length:] elif len(args) >= 1 and args[0][0] == '@': user = args[0] user_id = get_user_id(user) if not user_id: return "error", "Saya tidak memiliki pengguna di db saya. Anda akan dapat berinteraksi dengan mereka jika Anda membalas pesan orang itu, atau meneruskan salah satu dari pesan pengguna itu." else: user_id = user_id res = message.text.split(None, 2) if len(res) >= 3: text = res[2] elif len(args) >= 1 and args[0].isdigit(): user_id = int(args[0]) res = message.text.split(None, 2) if len(res) >= 3: text = res[2] elif prev_message: user_id, text = id_from_reply(message) else: return None, None try: message.bot.get_chat(user_id) except BadRequest as excp: if excp.message in ("User_id_invalid", "Chat not found"): return "error", "Saya sepertinya tidak pernah berinteraksi dengan pengguna ini sebelumnya - silakan meneruskan pesan dari mereka untuk memberi saya kontrol! (Seperti boneka voodoo, saya butuh sepotong untuk bisa untuk menjalankan perintah tertentu...)" else: LOGGER.exception("Exception %s on user %s", excp.message, user_id) return None, None return user_id, text
def del_blacklist(update, context): chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[Message] user = update.effective_user bot = context.bot to_match = extract_text(message) if not to_match: return getmode, value = sql.get_blacklist_setting(chat.id) chat_filters = sql.get_chat_blacklist(chat.id) for trigger in chat_filters: pattern = r"( |^|[^\w])" + re.escape(trigger) + r"( |$|[^\w])" if re.search(pattern, to_match, flags=re.IGNORECASE): try: if getmode == 0: return elif getmode == 1: message.delete() elif getmode == 2: message.delete() warn(update.effective_user, chat, tl(update.effective_message, "Mengatakan kata '{}' yang ada di daftar hitam").format(trigger), message, update.effective_user, conn=False) return elif getmode == 3: message.delete() bot.restrict_chat_member(chat.id, update.effective_user.id, can_send_messages=False) bot.sendMessage(chat.id, tl(update.effective_message, "{} di bisukan karena mengatakan kata '{}' yang ada di daftar hitam").format(mention_markdown(user.id, user.first_name), trigger), parse_mode="markdown") return elif getmode == 4: message.delete() res = chat.unban_member(update.effective_user.id) if res: bot.sendMessage(chat.id, tl(update.effective_message, "{} di tendang karena mengatakan kata '{}' yang ada di daftar hitam").format(mention_markdown(user.id, user.first_name), trigger), parse_mode="markdown") return elif getmode == 5: message.delete() chat.kick_member(user.id) bot.sendMessage(chat.id, tl(update.effective_message, "{} di blokir karena mengatakan kata '{}' yang ada di daftar hitam").format(mention_markdown(user.id, user.first_name), trigger), parse_mode="markdown") return elif getmode == 6: message.delete() bantime = extract_time(message, value) chat.kick_member(user.id, until_date=bantime) bot.sendMessage(chat.id, tl(update.effective_message, "{} di blokir selama {} karena mengatakan kata '{}' yang ada di daftar hitam").format(mention_markdown(user.id, user.first_name), value, trigger), parse_mode="markdown") return elif getmode == 7: message.delete() mutetime = extract_time(message, value) bot.restrict_chat_member(chat.id, user.id, until_date=mutetime, can_send_messages=False) bot.sendMessage(chat.id, tl(update.effective_message, "{} di bisukan selama {} karena mengatakan kata '{}' yang ada di daftar hitam").format(mention_markdown(user.id, user.first_name), value, trigger), parse_mode="markdown") return except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("Error while deleting blacklist message.") break
def get_exception(excp, filt, chat): if excp.message == "Unsupported url protocol": return "Anda tampaknya mencoba menggunakan protokol url yang tidak didukung. Telegram tidak mendukung tombol untuk beberapa protokol, seperti tg://. Silakan coba lagi." elif excp.message == "Reply message not found": return "noreply" else: LOGGER.warning("Message %s could not be parsed", str(filt.reply)) LOGGER.exception("Could not parse filter %s in chat %s", str(filt.keyword), str(chat.id)) return "Catatan ini tidak dapat dikirim karena formatnya salah."
def del_blackliststicker(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[Message] user = update.effective_user to_match = message.sticker if not to_match: return getmode, value = sql.get_blacklist_setting(chat.id) chat_filters = sql.get_chat_stickers(chat.id) for trigger in chat_filters: if to_match.set_name.lower() == trigger.lower(): try: if getmode == 0: return elif getmode == 1: message.delete() elif getmode == 2: message.delete() warn(update.effective_user, chat, tl(update.effective_message, "Menggunakan stiker '{}' yang ada di daftar hitam stiker").format(trigger), message, update.effective_user, conn=False) return elif getmode == 3: message.delete() bot.restrict_chat_member(chat.id, update.effective_user.id, can_send_messages=False) bot.sendMessage(chat.id, tl(update.effective_message, "{} di bisukan karena menggunakan stiker '{}' yang ada di daftar hitam stiker").format(mention_markdown(user.id, user.first_name), trigger), parse_mode="markdown") return elif getmode == 4: message.delete() res = chat.unban_member(update.effective_user.id) if res: bot.sendMessage(chat.id, tl(update.effective_message, "{} di tendang karena menggunakan stiker '{}' yang ada di daftar hitam stiker").format(mention_markdown(user.id, user.first_name), trigger), parse_mode="markdown") return elif getmode == 5: message.delete() chat.kick_member(user.id) bot.sendMessage(chat.id, tl(update.effective_message, "{} di blokir karena menggunakan stiker '{}' yang ada di daftar hitam stiker").format(mention_markdown(user.id, user.first_name), trigger), parse_mode="markdown") return elif getmode == 6: message.delete() bantime = extract_time(message, value) chat.kick_member(user.id, until_date=bantime) bot.sendMessage(chat.id, tl(update.effective_message, "{} di blokir selama {} karena menggunakan stiker '{}' yang ada di daftar hitam stiker").format(mention_markdown(user.id, user.first_name), value, trigger), parse_mode="markdown") return elif getmode == 7: message.delete() mutetime = extract_time(message, value) bot.restrict_chat_member(chat.id, user.id, until_date=mutetime, can_send_messages=False) bot.sendMessage(chat.id, tl(update.effective_message, "{} di bisukan selama {} karena menggunakan stiker '{}' yang ada di daftar hitam stiker").format(mention_markdown(user.id, user.first_name), value, trigger), parse_mode="markdown") return except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("Error while deleting blacklist message.") break
def setlog(update, context): message = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] if chat.type == chat.CHANNEL: send_message( update.effective_message, tl( update.effective_message, "Sekarang, teruskan /setlog ke grup yang Anda ingin ikat saluran ini!" )) elif message.forward_from_chat: sql.set_chat_log_channel(chat.id, message.forward_from_chat.id) try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception( "Error deleting message in log channel. Should work anyway though." ) try: context.bot.send_message( message.forward_from_chat.id, tl( update.effective_message, "Saluran ini telah ditetapkan sebagai saluran log untuk {}." ).format(chat.title or chat.first_name)) except Unauthorized as excp: if excp.message == "Forbidden: bot is not a member of the channel chat": context.bot.send_message( chat.id, tl( update.effective_message, "Gagal menyetel saluran log!\nSaya mungkin bukan admin di channel tersebut." )) sql.stop_chat_logging(chat.id) return else: LOGGER.exception("ERROR in setting the log channel.") context.bot.send_message( chat.id, tl(update.effective_message, "Berhasil mengatur saluran log!")) else: send_message( update.effective_message, tl( update.effective_message, "Langkah-langkah untuk mengatur saluran log adalah:\n" " - tambahkan bot ke saluran yang diinginkan\n" " - Kirimkan /setlog ke saluran\n" " - Teruskan /setlog ke grup\n"))
def tl(message, text): if type(message) == int or type(message) == str and message[1:].isdigit(): getlang = sql.get_lang(message) if getlang == 'None' or not getlang: getlang = 'en' else: getlang = sql.get_lang(message.chat.id) if getlang == 'None' or not getlang: if message.from_user.language_code: if message.from_user.language_code in LOADED_LANGS_ID: sql.set_lang(message.chat.id, message.from_user.language_code) getlang = message.from_user.language_code else: sql.set_lang(message.chat.id, 'en') getlang = 'en' else: sql.set_lang(message.chat.id, 'en') getlang = 'en' getlangid = {} for x in LOADED_LANGS_ID: getlangid[x] = x if str(getlang) == 'id': get = getattr(FUNC_LANG['id'], 'id') if text in tuple(get): return get.get(text) if text in ("RUN_STRINGS", "SLAP_TEMPLATES", "ITEMS", "THROW", "HIT", "RAMALAN_STRINGS", "RAMALAN_FIRST"): runstr = getattr(FUNC_LANG['id'], text) return runstr return text elif str(getlang) in LOADED_LANGS_ID: func = getattr(FUNC_LANG[getlang], getlang) if text in ("RUN_STRINGS", "SLAP_TEMPLATES", "ITEMS", "THROW", "HIT", "RAMALAN_STRINGS", "RAMALAN_FIRST"): runstr = getattr(FUNC_LANG[getlang], text) return runstr langtxt = func.get(text) if not langtxt: LOGGER.warning( "Can't get translated string for lang '{}' ('{}')".format( str(getlang), text)) langtxt = text return langtxt else: sql.set_lang(message.chat.id, 'en') get = getattr(FUNC_LANG['en'], 'en') if text in tuple(get): return get.get(text) if text in ("RUN_STRINGS", "SLAP_TEMPLATES", "ITEMS", "THROW", "HIT", "RAMALAN_STRINGS", "RAMALAN_FIRST"): runstr = getattr(FUNC_LANG['en'], text) return runstr return text
def rest_handler(bot: Bot, update: Update): msg = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] for restriction, filter in RESTRICTION_TYPES.items(): if filter(msg) and sql.is_restr_locked(chat.id, restriction) and can_delete(chat, bot.id): try: msg.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("ERROR in restrictions") break
def main(): test_handler = CommandHandler("test", test) start_handler = CommandHandler("start", start, pass_args=True) help_handler = CommandHandler("help", get_help) help_callback_handler = CallbackQueryHandler(help_button, pattern=r"help_") settings_handler = CommandHandler("settings", get_settings) settings_callback_handler = CallbackQueryHandler(settings_button, pattern=r"stngs_") donate_handler = CommandHandler("donate", donate) M_CONNECT_BTN_HANDLER = CallbackQueryHandler(m_connect_button, pattern=r"main_connect") M_SETLANG_BTN_HANDLER = CallbackQueryHandler(m_change_langs, pattern=r"main_setlang") migrate_handler = MessageHandler(Filters.status_update.migrate, migrate_chats) # dispatcher.add_handler(test_handler) dispatcher.add_handler(start_handler) dispatcher.add_handler(help_handler) dispatcher.add_handler(settings_handler) dispatcher.add_handler(help_callback_handler) dispatcher.add_handler(settings_callback_handler) dispatcher.add_handler(migrate_handler) dispatcher.add_handler(donate_handler) dispatcher.add_handler(M_CONNECT_BTN_HANDLER) dispatcher.add_handler(M_SETLANG_BTN_HANDLER) # dispatcher.add_error_handler(error_callback) # add antiflood processor Dispatcher.process_update = process_update if WEBHOOK: LOGGER.info("Using webhooks.") updater.start_webhook(listen="127.0.0.1", port=PORT, url_path=TOKEN) if CERT_PATH: updater.bot.set_webhook(url=URL + TOKEN, certificate=open(CERT_PATH, 'rb')) else: updater.bot.set_webhook(url=URL + TOKEN) else: LOGGER.info("Using long polling.") updater.start_polling(timeout=15, read_latency=4) updater.idle()
def main(): test_handler = CommandHandler("test", test) start_handler = CommandHandler("start", start, pass_args=True) help_handler = CommandHandler("help", get_help) help_callback_handler = CallbackQueryHandler(help_button, pattern=r"help_") settings_handler = CommandHandler("settings", get_settings) settings_callback_handler = CallbackQueryHandler(settings_button, pattern=r"stngs_") source_handler = CommandHandler("source", source) M_CONNECT_BTN_HANDLER = CallbackQueryHandler(m_connect_button, pattern=r"main_connect") M_SETLANG_BTN_HANDLER = CallbackQueryHandler(m_change_langs, pattern=r"main_setlang") # dispatcher.add_handler(test_handler) dispatcher.add_handler(start_handler) dispatcher.add_handler(help_handler) dispatcher.add_handler(settings_handler) dispatcher.add_handler(help_callback_handler) dispatcher.add_handler(settings_callback_handler) dispatcher.add_handler(source_handler) dispatcher.add_handler(M_CONNECT_BTN_HANDLER) dispatcher.add_handler(M_SETLANG_BTN_HANDLER) # dispatcher.add_error_handler(error_callback) if WEBHOOK: LOGGER.info("Using webhooks.") updater.start_webhook(listen="127.0.0.1", port=PORT, url_path=TOKEN) if CERT_PATH: updater.bot.set_webhook(url=URL + TOKEN, certificate=open(CERT_PATH, 'rb')) else: updater.bot.set_webhook(url=URL + TOKEN) else: LOGGER.info("Using long polling.") # updater.start_polling(timeout=15, read_latency=4) updater.start_polling(poll_interval=0.0, timeout=10, clean=True, bootstrap_retries=-1, read_latency=3.0) updater.idle()
def broadcast(bot: Bot, update: Update): to_send = update.effective_message.text.split(None, 1) if len(to_send) >= 2: chats = sql.get_all_chats() or [] failed = 0 for chat in chats: try: bot.sendMessage(int(chat.chat_id), to_send[1]) sleep(0.1) except TelegramError: failed += 1 LOGGER.warning("Couldn't send broadcast to %s, group name %s", str(chat.chat_id), str(chat.chat_name)) update.effective_message.reply_text("Siaran selesai. {} grup gagal menerima pesan, mungkin " "karena ditendang.".format(failed))
def purge(update,context): args = context.args msg = update.effective_message # type: Optional[Message] if msg.reply_to_message: user = update.effective_user # type: Optional[User] chat = update.effective_chat # type: Optional[Chat] if can_delete(chat, context.bot.id): message_id = msg.reply_to_message.message_id if args and args[0].isdigit(): if int(args[0]) < int(1): return delete_to = message_id + int(args[0]) else: delete_to = msg.message_id - 1 for m_id in range(delete_to, message_id - 1, -1): # Reverse iteration over message ids try: context.bot.deleteMessage(chat.id, m_id) except BadRequest as err: if err.message == "Message can't be deleted": send_message(update.effective_message, "Cannot delete all messages. The messages may be too old, I might " "not have delete rights, or this might not be a supergroup.") elif err.message != "Message to delete not found": LOGGER.exception("Error while purging chat messages.") try: msg.delete() except BadRequest as err: if err.message == "Message can't be deleted": send_message(update.effective_message, "Cannot delete all messages. The messages may be too old, I might " "not have delete rights, or this might not be a supergroup.") elif err.message != "Message to delete not found": LOGGER.exception("Error while purging chat messages.") send_message(update.effective_message, "Purge complete.") return "<b>{}:</b>" \ "\n#PURGE" \ "\n<b>• Admin:</b> {}" \ "\nPurged <code>{}</code> messages.".format(html.escape(chat.title), mention_html(user.id, user.first_name), delete_to - message_id) else: msg.reply_text("Reply to a message to select where to start purging from.") return ""
def send(update, message, keyboard, backup_message): chat = update.effective_chat cleanserv = sql.clean_service(chat.id) reply = update.message.message_id # Clean service welcome if cleanserv: reply = False try: msg = dispatcher.bot.send_message(chat.id, message, parse_mode=ParseMode.MARKDOWN, reply_markup=keyboard, reply_to_message_id=reply, disable_web_page_preview=True) except IndexError: msg = dispatcher.bot.send_message(chat.id, markdown_parser(backup_message + tl(update.effective_message, "\nCatatan: pesan saat ini tidak valid " "karena masalah markdown. Bisa jadi " "karena nama pengguna.")), reply_to_message_id=reply, parse_mode=ParseMode.MARKDOWN) except KeyError: msg = dispatcher.bot.send_message(chat.id, markdown_parser(backup_message + tl(update.effective_message, "\nCatatan: pesan saat ini tidak valid " "karena ada masalah dengan beberapa salah tempat. " "Harap perbarui")), reply_to_message_id=reply, parse_mode=ParseMode.MARKDOWN) except BadRequest as excp: if excp.message == "Button_url_invalid": msg = dispatcher.bot.send_message(chat.id, markdown_parser(backup_message + tl(update.effective_message, "\nCatatan: pesan saat ini memiliki url yang tidak " "valid di salah satu tombolnya. Harap perbarui.")), reply_to_message_id=reply, parse_mode=ParseMode.MARKDOWN) elif excp.message == "Unsupported url protocol": msg = dispatcher.bot.send_message(chat.id, markdown_parser(backup_message + tl(update.effective_message, "\nCatatan: pesan saat ini memiliki tombol yang " "menggunakan protokol url yang tidak didukung " "oleh telegram. Harap perbarui.")), reply_to_message_id=reply, parse_mode=ParseMode.MARKDOWN) elif excp.message == "Wrong url host": msg = dispatcher.bot.send_message(chat.id, markdown_parser(backup_message + tl(update.effective_message, "\nCatatan: pesan saat ini memiliki beberapa url " "yang buruk. Harap perbarui.")), reply_to_message_id=reply, parse_mode=ParseMode.MARKDOWN) LOGGER.warning(message) LOGGER.warning(keyboard) LOGGER.exception("Could not parse! got invalid url host errors") else: try: msg = dispatcher.bot.send_message(chat.id, markdown_parser(backup_message + tl(update.effective_message, "\nCatatan: Terjadi kesalahan saat mengirim pesan " "kustom. Harap perbarui.")), reply_to_message_id=reply, parse_mode=ParseMode.MARKDOWN) LOGGER.exception("ERROR!") except BadRequest: print("Cannot send welcome msg, bot is muted!") return "" return msg
def purge(bot: Bot, update: Update, args: List[str]) -> str: spam = spamfilters(update.effective_message.text, update.effective_message.from_user.id, update.effective_chat.id) if spam == True: return update.effective_message.reply_text("Saya kecewa dengan anda, saya tidak akan mendengar kata-kata anda sekarang!") msg = update.effective_message # type: Optional[Message] if msg.reply_to_message: user = update.effective_user # type: Optional[User] chat = update.effective_chat # type: Optional[Chat] if can_delete(chat, bot.id): message_id = msg.reply_to_message.message_id if args and args[0].isdigit(): delete_to = message_id + int(args[0]) else: delete_to = msg.message_id - 1 for m_id in range(delete_to, message_id - 1, -1): # Reverse iteration over message ids try: bot.deleteMessage(chat.id, m_id) except BadRequest as err: if err.message == "Message can't be deleted": bot.send_message(chat.id, "Tidak dapat menghapus semua pesan. Pesannya mungkin terlalu lama, saya mungkin " "tidak memiliki hak menghapus, atau ini mungkin bukan supergrup.") elif err.message != "Message to delete not found": LOGGER.exception("Error while purging chat messages.") try: msg.delete() except BadRequest as err: if err.message == "Message can't be deleted": bot.send_message(chat.id, "Tidak dapat menghapus semua pesan. Pesannya mungkin terlalu lama, saya mungkin " "tidak memiliki hak menghapus, atau ini mungkin bukan supergrup.") elif err.message != "Message to delete not found": LOGGER.exception("Error while purging chat messages.") bot.send_message(chat.id, "Pembersihan selesai.") return "<b>{}:</b>" \ "\n#PURGE" \ "\n<b>Admin:</b> {}" \ "\nDibersihkan <code>{}</code> pesan.".format(html.escape(chat.title), mention_html(user.id, user.first_name), delete_to - message_id) else: msg.reply_text("Balas pesan untuk memilih tempat mulai membersihkan.") return ""
def setlog(bot: Bot, update: Update): spam = spamfilters(update.effective_message.text, update.effective_message.from_user.id, update.effective_chat.id) if spam == True: return update.effective_message.reply_text( "Saya kecewa dengan anda, saya tidak akan mendengar kata-kata anda sekarang!" ) message = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] if chat.type == chat.CHANNEL: message.reply_text( "Sekarang, teruskan /setlog ke grup yang Anda ingin ikat saluran ini!" ) elif message.forward_from_chat: sql.set_chat_log_channel(chat.id, message.forward_from_chat.id) try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception( "Error deleting message in log channel. Should work anyway though." ) try: bot.send_message( message.forward_from_chat.id, "Saluran ini telah ditetapkan sebagai saluran log untuk {}." .format(chat.title or chat.first_name)) except Unauthorized as excp: if excp.message == "Forbidden: bot is not a member of the channel chat": bot.send_message(chat.id, "Successfully set log channel!") else: LOGGER.exception("ERROR in setting the log channel.") bot.send_message(chat.id, "Berhasil mengatur saluran log!") else: message.reply_text( "Langkah-langkah untuk mengatur saluran log adalah:\n" " - tambahkan bot ke saluran yang diinginkan\n" " - Kirimkan /setlog ke saluran\n" " - Teruskan /setlog ke grup\n")
def snipe(update, context: List[str]): args = context.args try: chat_id = str(args[0]) del args[0] except TypeError as excp: update.effective_message.reply_text( "Please give me a chat to echo to!") to_send = " ".join(args) if len(to_send) >= 2: try: context.bot.sendMessage(int(chat_id), str(to_send)) except TelegramError: LOGGER.warning("Couldn't send to group %s", str(chat_id)) update.effective_message.reply_text( "Couldn't send the message. Perhaps I'm not part of that group?" )
def migrate_chats(bot: Bot, update: Update): msg = update.effective_message # type: Optional[Message] if msg.migrate_to_chat_id: old_chat = update.effective_chat.id new_chat = msg.migrate_to_chat_id elif msg.migrate_from_chat_id: old_chat = msg.migrate_from_chat_id new_chat = update.effective_chat.id else: return LOGGER.info("Migrating from %s, to %s", str(old_chat), str(new_chat)) for mod in MIGRATEABLE: mod.__migrate__(old_chat, new_chat) LOGGER.info("Successfully migrated!") raise DispatcherHandlerStop
def del_blackliststicker(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[Message] to_match = message.sticker if not to_match: return chat_filters = sql.get_chat_stickers(chat.id) for trigger in chat_filters: if to_match.set_name.lower() == trigger.lower(): try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("Error while deleting blacklist message.") break
def broadcast(update, context): to_send = update.effective_message.text.split(None, 1) if len(to_send) >= 2: chats = sql.get_all_chats() or [] failed = 0 for chat in chats: try: context.bot.sendMessage(int(chat.chat_id), to_send[1]) sleep(0.1) except TelegramError: failed += 1 LOGGER.warning("Couldn't send broadcast to %s, group name %s", str(chat.chat_id), str(chat.chat_name)) send_message( update.effective_message, "The broadcast is complete. `{}` groups failed to receive the message, maybe " "I'm kicked or muted.".format(failed))
def send_message_raw(chat_id, text, *args, **kwargs): try: return dispatcher.bot.sendMessage(chat_id, text, *args,**kwargs) except error.BadRequest as err: if str(err) == "Reply message not found": try: if kwargs.get('reply_to_message_id'): kwargs['reply_to_message_id'] = None return dispatcher.bot.sendMessage(chat_id, text, *args,**kwargs) except error.BadRequest as err: LOGGER.exception("ERROR: {}".format(err)) elif str(err) == "Have no rights to send a message": try: dispatcher.bot.leaveChat(message.chat.id) dispatcher.bot.sendMessage(-1001287670948, "I am leave chat `{}`\nBecause of: `Muted`".format(message.chat.title)) except error.BadRequest as err: if str(err) == "Chat not found": pass else: LOGGER.exception("ERROR: {}".format(err))
def log_action(bot: Bot, update: Update, *args, **kwargs): result = func(bot, update, *args, **kwargs) chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[Message] if result: if chat.type == chat.SUPERGROUP and chat.username: result += "\n<b>Link:</b> " \ "<a href=\"http://telegram.me/{}/{}\">klik disini</a>".format(chat.username, message.message_id) log_chat = sql.get_chat_log_channel(chat.id) if log_chat: send_log(bot, log_chat, chat.id, result) elif result == "": pass else: LOGGER.warning( "%s was set as loggable, but had no return statement.", func) return result
def main(): test_handler = CommandHandler("teste", test) start_handler = CommandHandler("Iniciar", start, pass_args=True) help_handler = CommandHandler("Ajuda", get_help) help_callback_handler = CallbackQueryHandler(help_button, pattern=r"help_") settings_handler = CommandHandler("Configurações", get_settings) settings_callback_handler = CallbackQueryHandler(settings_button, pattern=r"stngs_") donate_handler = CommandHandler("Doar", donate) M_CONNECT_BTN_HANDLER = CallbackQueryHandler(m_connect_button, pattern=r"main_connect") M_SETLANG_BTN_HANDLER = CallbackQueryHandler(m_change_langs, pattern=r"main_setlang") dispatcher.add_handler(start_handler) dispatcher.add_handler(help_handler) dispatcher.add_handler(settings_handler) dispatcher.add_handler(help_callback_handler) dispatcher.add_handler(settings_callback_handler) dispatcher.add_handler(donate_handler) dispatcher.add_handler(M_CONNECT_BTN_HANDLER) dispatcher.add_handler(M_SETLANG_BTN_HANDLER) if WEBHOOK: LOGGER.info("Using webhooks.") updater.start_webhook(listen="127.0.0.1", port=PORT, url_path=TOKEN) if CERT_PATH: updater.bot.set_webhook(url=URL + TOKEN, certificate=open(CERT_PATH, 'rb')) else: updater.bot.set_webhook(url=URL + TOKEN) else: LOGGER.info("Usando sondagens longas.") updater.start_polling(timeout=15, read_latency=4) updater.idle()
def check_cas(bot: Bot, user_id, user, message): json = requests.get(CAS_URL, params={"user_id": str(user_id)}).json() if json.get("ok"): if json["result"]["offenses"] > 0: is_success = False try: bot.kickChatMember(message.chat.id, user_id) is_success = True except: bot.sendMessage(message.chat.id, "*⚠️ WARNING!*\n{} is a spammer from [CAS ban](https://combot.org/cas/query?u={}) and has been added to fedban list of *Team Nusantara Disciplinary Circle*!\n\nIt's recommended to banned him/her!".format(mention_markdown(user_id, user.first_name), user_id), parse_mode="markdown", disable_web_page_preview=True) if is_success: bot.sendMessage(message.chat.id, "{} has been banned and added to fedban list of *Team Nusantara Disciplinary Circle*!\nReason: [CAS ban](https://combot.org/cas/query?u={}).".format(mention_markdown(user_id, user.first_name), user_id), parse_mode="markdown", disable_web_page_preview=True) fed_id = fedsql.get_fed_info("TeamNusantaraDevs") if fed_id: x = fedsql.fban_user("TeamNusantaraDevs", user_id, user.first_name, user.last_name, user.username, "CAS-Banned", int(time.time())) if not x: LOGGER.warning("Cannot fban spammer user!") return text = "*New FedBan*\n*Fed:* `TeamNusantaraDevs`\n*FedAdmin*: {}\n*User:* {}\n*User ID:* `{}`\n*Reason:* [CAS ban](https://combot.org/cas/query?u={})".format(mention_markdown(692882995, "Emilia"), mention_markdown(user_id, user.first_name + (" " + user.last_name if user.last_name != None else "")), user_id, user_id) bot.sendMessage(-1001338861977, text, parse_mode="markdown", disable_web_page_preview=True) print(">>> NEW FBAN: {} {} in {}".format(user.first_name, user_id, message.chat.title))
def send_message(message, text, target_id=None, *args, **kwargs): if not target_id: try: return message.reply_text(text, *args, **kwargs) except error.BadRequest as err: if str(err) == "Reply message not found": try: return message.reply_text(text, quote=False, *args, **kwargs) except error.BadRequest as err: LOGGER.exception("ERROR: {}".format(err)) elif str(err) == "Have no rights to send a message": try: dispatcher.bot.leaveChat(message.chat.id) dispatcher.bot.sendMessage( DUMP_CHAT, "I am leave chat `{}`\nBecause of: `Muted`".format( message.chat.title)) except error.BadRequest as err: if str(err) == "Chat not found": pass else: LOGGER.exception("ERROR: {}".format(err)) else: try: dispatcher.bot.send_message(target_id, text, *args, **kwarg) except error.BadRequest as err: LOGGER.exception("ERROR: {}".format(err))