def locale_button(bot, update): chat = update.effective_chat user = update.effective_user # type: Optional[User] query = update.callback_query lang_match = re.findall(r"en|ru|ua|es|tr|id", query.data) if lang_match: if lang_match[0]: switch_to_locale(chat.id, lang_match[0]) query.answer(text="Language changed!") else: query.answer(text="Error!", show_alert=True) try: LANGUAGE = prev_locale(chat.id) locale = LANGUAGE.locale_name curr_lang = list_locales[locale] except: curr_lang = "English" text = "*Select language* \n" text += "User language : `{}`".format(curr_lang) conn = connected(bot, update, chat, user.id, need_admin=False) if not conn == False: try: chatlng = prev_locale(conn).locale_name chatlng = list_locales[chatlng] text += "\nConnected chat language : `{}`".format(chatlng) except: chatlng = "English" text += "*\n\nSelect new user language:*" query.message.reply_text( text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton("English 🇺🇸", callback_data="set_lang_en") ]] + [[ InlineKeyboardButton("Russian 🇷🇺", callback_data="set_lang_ru"), InlineKeyboardButton("Ukrainian 🇺🇦", callback_data="set_lang_ua") ]] + [[ InlineKeyboardButton("Spanish 🇪🇸", callback_data="set_lang_es"), InlineKeyboardButton("Turkish 🇹🇷", callback_data="set_lang_tr") ]] + [[ InlineKeyboardButton("Indonesian 🇮🇩", callback_data="set_lang_id") ]] + [[InlineKeyboardButton("⬅️ Back", callback_data="bot_start")]])) print(lang_match) query.message.delete() bot.answer_callback_query(query.id)
def save(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] conn = connected(bot, update, chat, user.id) if conn: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: chat_id = update.effective_chat.id if chat.type == "private": chat_name = "local notes" else: chat_name = chat.title msg = update.effective_message # type: Optional[Message] note_name, text, data_type, content, buttons = get_note_type(msg) if data_type is None: msg.reply_text("Dude, there's no note!") return if len(text.strip()) == 0: text = note_name if not sql.get_note(chat_id, note_name): sql.add_note_to_db(chat_id, note_name, text, data_type, buttons=buttons, file=content) msg.reply_text( "Ok, added `{note_name}` note in *{chat_name}*.\nGet it with `/get {note_name}`, or `#{note_name}`" .format(note_name=note_name, chat_name=chat_name), parse_mode=ParseMode.MARKDOWN) else: sql.add_note_to_db(chat_id, note_name, text, data_type, buttons=buttons, file=content) msg.reply_text( "Ok, Note `{note_name}` in *{chat_name}* have been updated!.\nGet it with `/get {note_name}`, or `#{note_name}`" .format(note_name=note_name, chat_name=chat_name), parse_mode=ParseMode.MARKDOWN)
def add_blacklist(bot: Bot, update: Update): msg = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] words = msg.text.split(None, 1) conn = connected(bot, update, chat, user.id) if not conn == False: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: chat_id = update.effective_chat.id if chat.type == "private": exit(1) else: chat_name = chat.title if len(words) > 1: text = words[1] to_blacklist = list( set(trigger.strip() for trigger in text.split("\n") if trigger.strip())) for trigger in to_blacklist: sql.add_to_blacklist(chat_id, trigger.lower()) if len(to_blacklist) == 1: msg.reply_text(tld( chat.id, "Added <code>{}</code> to the blacklist in <b>{}</b>!").format( html.escape(to_blacklist[0]), chat_name), parse_mode=ParseMode.HTML) else: msg.reply_text(tld( chat.id, "Added <code>{}</code> to the blacklist in <b>{}</b>!").format( len(to_blacklist)), chat_name, parse_mode=ParseMode.HTML) else: msg.reply_text( tld(chat.id, "Tell me what words you would like to add to the blacklist."))
def stop_filter(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] args = update.effective_message.text.split(None, 1) conn = connected(bot, update, chat, user.id) if not conn == False: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: chat_id = update.effective_chat.id if chat.type == "private": chat_name = "local notes" else: chat_name = chat.title if len(args) < 2: return chat_filters = sql.get_chat_triggers(chat_id) if not chat_filters: update.effective_message.reply_text( tld(chat.id, "No filters are active in {}!").format(chat_name)) return for keyword in chat_filters: if keyword == args[1]: sql.remove_filter(chat_id, args[1]) update.effective_message.reply_text( tld(chat.id, "Yep, I'll stop replying to that in *{}*.").format( chat_name), parse_mode=telegram.ParseMode.MARKDOWN) raise DispatcherHandlerStop update.effective_message.reply_text( tld( chat.id, "That's not a current filter - run /filters for all active filters." ))
def blacklist(bot: Bot, update: Update, args: List[str]): msg = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] conn = connected(bot, update, chat, user.id, need_admin=False) if not conn == False: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: if chat.type == "private": exit(1) else: chat_id = update.effective_chat.id chat_name = chat.title filter_list = tld( chat.id, "<b>Current blacklisted words in {}:</b>\n").format(chat_name) all_blacklisted = sql.get_chat_blacklist(chat_id) if len(args) > 0 and args[0].lower() == 'copy': for trigger in all_blacklisted: filter_list += "<code>{}</code>\n".format(html.escape(trigger)) else: for trigger in all_blacklisted: filter_list += " • <code>{}</code>\n".format(html.escape(trigger)) split_text = split_message(filter_list) for text in split_text: if filter_list == tld( chat.id, "<b>Current blacklisted words in {}:</b>\n").format( chat_name): #We need to translate msg.reply_text(tld( chat.id, "There are no blacklisted messages in <b>{}</b>!").format( chat_name), parse_mode=ParseMode.HTML) return msg.reply_text(text, parse_mode=ParseMode.HTML)
def list_handlers(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] conn = connected(bot, update, chat, user.id, need_admin=False) if not conn == False: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title filter_list = tld(chat.id, "*List of filters in {}:*\n") else: chat_id = update.effective_chat.id if chat.type == "private": chat_name = tld(chat.id, "local filters") filter_list = tld(chat.id, "*local filters:*\n") else: chat_name = chat.title filter_list = tld(chat.id, "*Filters in {}*:\n") all_handlers = sql.get_chat_triggers(chat_id) if not all_handlers: update.effective_message.reply_text( tld(chat.id, "No filters in {}!").format(chat_name)) return for keyword in all_handlers: entry = " • `{}`\n".format(escape_markdown(keyword)) if len(entry) + len(filter_list) > telegram.MAX_MESSAGE_LENGTH: update.effective_message.reply_text( filter_list.format(chat_name), parse_mode=telegram.ParseMode.MARKDOWN) filter_list = entry else: filter_list += entry update.effective_message.reply_text(filter_list.format(chat_name), parse_mode=telegram.ParseMode.MARKDOWN)
def clear(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] conn = connected(bot, update, chat, user.id) if not conn == False: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: chat_id = update.effective_chat.id if chat.type == "private": chat_name = "local notes" else: chat_name = chat.title if len(args) >= 1: notename = args[0] if sql.rm_note(chat_id, notename): update.effective_message.reply_text( "Note succesfully removed from *{}*.".format(chat_name), parse_mode=ParseMode.MARKDOWN) else: update.effective_message.reply_text( "That's not a note in my database!")
def list_notes(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] conn = connected(bot, update, chat, user.id, need_admin=False) if not conn == False: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title msg = "*Notes in {}:*\n" else: chat_id = update.effective_chat.id if chat.type == "private": chat_name = "" msg = "*Local Notes:*\n" else: chat_name = chat.title msg = "*Notes in {}:*\n" note_list = sql.get_all_chat_notes(chat_id) for note in note_list: note_name = " • `#{}`\n".format(note.name) if len(msg) + len(note_name) > MAX_MESSAGE_LENGTH: update.effective_message.reply_text(msg, parse_mode=ParseMode.MARKDOWN) msg = "" msg += note_name if not note_list: update.effective_message.reply_text( "No notes in *{}*!".format(chat_name), parse_mode=ParseMode.MARKDOWN) elif len(msg) != 0: msg += "\nYou can retrieve these notes by using `/get notename`, or `#notename`" update.effective_message.reply_text(msg.format(chat_name), parse_mode=ParseMode.MARKDOWN)
def import_data(bot: Bot, update): msg = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] # TODO: allow uploading doc with command, not just as reply # only work with a doc conn = connected(bot, update, chat, user.id, need_admin=True) if conn: chat = dispatcher.bot.getChat(conn) chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: if update.effective_message.chat.type == "private": update.effective_message.reply_text( "This command can only be runned on group, not PM.") return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title if msg.reply_to_message and msg.reply_to_message.document: try: file_info = bot.get_file(msg.reply_to_message.document.file_id) except BadRequest: msg.reply_text( "Try downloading and uploading the file yourself again, This one seem broken!" ) return with BytesIO() as file: file_info.download(out=file) file.seek(0) data = json.load(file) # only import one group if len(data) > 1 and str(chat.id) not in data: msg.reply_text( "There are more than one group in this file and the chat.id is not same! How am i supposed to import it?" ) return # Check if backup is this chat try: if data.get(str(chat.id)) == None: if conn: text = "Backup comes from another chat, I can't return another chat to chat *{}*".format( chat_name) else: text = "Backup comes from another chat, I can't return another chat to this chat" return msg.reply_text(text, parse_mode="markdown") except: return msg.reply_text( "There is problem while importing the data!.") # Check if backup is from self try: if str(bot.id) != str(data[str(chat.id)]['bot']): return msg.reply_text( "Backup from another bot that is not suggested might cause the problem, documents, photos, videos, audios, records might not work as it should be. However, You can still request a feature regarding this in @HarukaAyaGroup !" ) except: pass # Select data source if str(chat.id) in data: data = data[str(chat.id)]['hashes'] else: data = data[list(data.keys())[0]]['hashes'] try: for mod in DATA_IMPORT: mod.__import_data__(str(chat.id), data) except Exception: msg.reply_text( "An error occurred while recovering your data. The process failed. If you experience a problem with this, please ask in @HarukaAyaGroup . My owner and community will be happy to help. Also, bugs report makes me even better!\nThank you!" ) LOGGER.exception("Imprt for the chat %s with the name %s failed.", str(chat.id), str(chat.title)) return # TODO: some of that link logic # NOTE: consider default permissions stuff? if conn: text = "Backup fully restored on *{}*.".format(chat_name) else: text = "Backup fully restored" msg.reply_text(text, parse_mode="markdown")
def export_data(bot: Bot, update: Update, chat_data): msg = update.effective_message # type: Optional[Message] user = update.effective_user # type: Optional[User] chat_id = update.effective_chat.id chat = update.effective_chat current_chat_id = update.effective_chat.id conn = connected(bot, update, chat, user.id, need_admin=True) if conn: chat = dispatcher.bot.getChat(conn) chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: if update.effective_message.chat.type == "private": update.effective_message.reply_text( "This command can only be used on group, not PM") return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title jam = time.time() new_jam = jam + 10800 checkchat = get_chat(chat_id, chat_data) if checkchat.get('status'): if jam <= int(checkchat.get('value')): timeformatt = time.strftime("%H:%M:%S %d/%m/%Y", time.localtime(checkchat.get('value'))) update.effective_message.reply_text( "You can only backup once a day!\nYou can backup again in about `{}`" .format(timeformatt), parse_mode=ParseMode.MARKDOWN) return else: if user.id != 654839744: put_chat(chat_id, new_jam, chat_data) else: if user.id != 654839744: put_chat(chat_id, new_jam, chat_data) note_list = sql.get_all_chat_notes(chat_id) backup = {} notes = {} button = "" buttonlist = [] namacat = "" isicat = "" rules = "" count = 0 countbtn = 0 # Notes for note in note_list: count += 1 getnote = sql.get_note(chat_id, note.name) namacat += '{}<###splitter###>'.format(note.name) if note.msgtype == 1: tombol = sql.get_buttons(chat_id, note.name) keyb = [] for btn in tombol: countbtn += 1 if btn.same_line: buttonlist.append( ('{}'.format(btn.name), '{}'.format(btn.url), True)) else: buttonlist.append( ('{}'.format(btn.name), '{}'.format(btn.url), False)) isicat += '###button###: {}<###button###>{}<###splitter###>'.format( note.value, str(buttonlist)) buttonlist.clear() elif note.msgtype == 2: isicat += '###sticker###:{}<###splitter###>'.format(note.file) elif note.msgtype == 3: isicat += '###file###:{}<###TYPESPLIT###>{}<###splitter###>'.format( note.file, note.value) elif note.msgtype == 4: isicat += '###photo###:{}<###TYPESPLIT###>{}<###splitter###>'.format( note.file, note.value) elif note.msgtype == 5: isicat += '###audio###:{}<###TYPESPLIT###>{}<###splitter###>'.format( note.file, note.value) elif note.msgtype == 6: isicat += '###voice###:{}<###TYPESPLIT###>{}<###splitter###>'.format( note.file, note.value) elif note.msgtype == 7: isicat += '###video###:{}<###TYPESPLIT###>{}<###splitter###>'.format( note.file, note.value) elif note.msgtype == 8: isicat += '###video_note###:{}<###TYPESPLIT###>{}<###splitter###>'.format( note.file, note.value) else: isicat += '{}<###splitter###>'.format(note.value) for x in range(count): notes['#{}'.format( namacat.split("<###splitter###>")[x])] = '{}'.format( isicat.split("<###splitter###>")[x]) # Rules rules = rulessql.get_rules(chat_id) # Blacklist bl = list(blacklistsql.get_chat_blacklist(chat_id)) # Disabled command disabledcmd = list(disabledsql.get_all_disabled(chat_id)) # Filters (TODO) """ all_filters = list(filtersql.get_chat_triggers(chat_id)) export_filters = {} for filters in all_filters: filt = filtersql.get_filter(chat_id, filters) # print(vars(filt)) if filt.is_sticker: tipefilt = "sticker" elif filt.is_document: tipefilt = "doc" elif filt.is_image: tipefilt = "img" elif filt.is_audio: tipefilt = "audio" elif filt.is_voice: tipefilt = "voice" elif filt.is_video: tipefilt = "video" elif filt.has_buttons: tipefilt = "button" buttons = filtersql.get_buttons(chat.id, filt.keyword) print(vars(buttons)) elif filt.has_markdown: tipefilt = "text" if tipefilt == "button": content = "{}#=#{}|btn|{}".format(tipefilt, filt.reply, buttons) else: content = "{}#=#{}".format(tipefilt, filt.reply) print(content) export_filters[filters] = content print(export_filters) """ # Welcome (TODO) # welc = welcsql.get_welc_pref(chat_id) # Locked locks = locksql.get_locks(chat_id) locked = [] if locks: if locks.sticker: locked.append('sticker') if locks.document: locked.append('document') if locks.contact: locked.append('contact') if locks.audio: locked.append('audio') if locks.game: locked.append('game') if locks.bots: locked.append('bots') if locks.gif: locked.append('gif') if locks.photo: locked.append('photo') if locks.video: locked.append('video') if locks.voice: locked.append('voice') if locks.location: locked.append('location') if locks.forward: locked.append('forward') if locks.url: locked.append('url') restr = locksql.get_restr(chat_id) if restr.other: locked.append('other') if restr.messages: locked.append('messages') if restr.preview: locked.append('preview') if restr.media: locked.append('media') # Warns (TODO) # warns = warnssql.get_warns(chat_id) # Backing up backup[chat_id] = { 'bot': bot.id, 'hashes': { 'info': { 'rules': rules }, 'extra': notes, 'blacklist': bl, 'disabled': disabledcmd, 'locks': locked } } baccinfo = json.dumps(backup, indent=4) f = open("harukab{}.backup".format(chat_id), "w") f.write(str(baccinfo)) f.close() bot.sendChatAction(current_chat_id, "upload_document") tgl = time.strftime("%H:%M:%S - %d/%m/%Y", time.localtime(time.time())) try: bot.sendMessage( MESSAGE_DUMP, "*Successfully imported backup:*\nChat: `{}`\nChat ID: `{}`\nOn: `{}`" .format(chat.title, chat_id, tgl), parse_mode=ParseMode.MARKDOWN) except BadRequest: pass bot.sendDocument( current_chat_id, document=open('harukab{}.backup'.format(chat_id), 'rb'), caption= "*Successfully imported backup:*\nChat: `{}`\nChat ID: `{}`\nOn: `{}`\n\nNote: This `harukab` is specially made for notes." .format(chat.title, chat_id, tgl), timeout=360, reply_to_message_id=msg.message_id, parse_mode=ParseMode.MARKDOWN) os.remove("harukab{}.backup".format(chat_id)) # Cleaning file
def control_panel(bot, update): chat = update.effective_chat user = update.effective_user # ONLY send help in PM if chat.type != chat.PRIVATE: update.effective_message.reply_text( "Contact me in PM to access the control panel.", reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text="Control Panel", url=f"t.me/{bot.username}?start=controlpanel") ]])) return #Support to run from command handler query = update.callback_query if query: try: query.message.delete() except BadRequest as ee: update.effective_message.reply_text( f"Failed to delete query, {ee}") M_match = re.match(r"cntrl_panel_M", query.data) U_match = re.match(r"cntrl_panel_U", query.data) G_match = re.match(r"cntrl_panel_G", query.data) back_match = re.match(r"help_back", query.data) else: M_match = "kyne : none of a Kind" #LMAO, don't uncomment if M_match: text = "*Control panel* 🛠" keyboard = [[ InlineKeyboardButton(text="👤 My settings", callback_data="cntrl_panel_U(1)") ]] #Show connected chat and add chat settings button conn = connected(bot, update, chat, user.id, need_admin=False) if conn: chatG = bot.getChat(conn) #admin_list = chatG.get_administrators() #Unused variable #If user admin member = chatG.get_member(user.id) if member.status in ('administrator', 'creator'): text += f"\nConnected chat - *{chatG.title}* (you {member.status})" keyboard += [[ InlineKeyboardButton(text="👥 Group settings", callback_data="cntrl_panel_G_back") ]] elif user.id in SUDO_USERS: text += f"\nConnected chat - *{chatG.title}* (you sudo)" keyboard += [[ InlineKeyboardButton(text="👥 Group settings (SUDO)", callback_data="cntrl_panel_G_back") ]] else: text += f"\nConnected chat - *{chatG.title}* (you aren't an admin!)" else: text += "\nNo chat connected!" keyboard += [[ InlineKeyboardButton(text="⬅️ Back", callback_data="bot_start") ]] update.effective_message.reply_text( text, reply_markup=InlineKeyboardMarkup(keyboard), parse_mode=ParseMode.MARKDOWN) elif U_match: mod_match = re.match(r"cntrl_panel_U_module\((.+?)\)", query.data) back_match = re.match(r"cntrl_panel_U\((.+?)\)", query.data) chatP = update.effective_chat # type: Optional[Chat] if mod_match: module = mod_match.group(1) R = CHAT_SETTINGS[module].__user_settings__(bot, update, user) text = "You has the following settings for the *{}* module:\n\n".format( CHAT_SETTINGS[module].__mod_name__) + R[0] keyboard = R[1] keyboard += [[ InlineKeyboardButton(text="⬅️ Back", callback_data="cntrl_panel_U(1)") ]] query.message.reply_text( text=text, arse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard)) elif back_match: text = "*User control panel* 🛠" query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules( user.id, 0, USER_SETTINGS, "cntrl_panel_U"))) elif G_match: mod_match = re.match(r"cntrl_panel_G_module\((.+?)\)", query.data) prev_match = re.match(r"cntrl_panel_G_prev\((.+?)\)", query.data) next_match = re.match(r"cntrl_panel_G_next\((.+?)\)", query.data) back_match = re.match(r"cntrl_panel_G_back", query.data) chatP = chat conn = connected(bot, update, chat, user.id) if conn: chat = bot.getChat(conn) else: query.message.reply_text(text="Error with connection to chat") exit(1) if mod_match: module = mod_match.group(1) R = CHAT_SETTINGS[module].__chat_settings__( bot, update, chat, chatP, user) if type(R) is list: text = R[0] keyboard = R[1] else: text = R keyboard = [] text = "*{}* has the following settings for the *{}* module:\n\n".format( escape_markdown(chat.title), CHAT_SETTINGS[module].__mod_name__) + text keyboard += [[ InlineKeyboardButton(text="Back", callback_data="cntrl_panel_G_back") ]] query.message.reply_text( text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard)) elif prev_match: chat_id = prev_match.group(1) curr_page = int(prev_match.group(2)) chat = bot.get_chat(chat_id) query.message.reply_text(tld( user.id, "send-group-settings").format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(curr_page - 1, 0, CHAT_SETTINGS, "cntrl_panel_G", chat=chat_id))) elif next_match: chat_id = next_match.group(1) next_page = int(next_match.group(2)) chat = bot.get_chat(chat_id) query.message.reply_text(tld( user.id, "send-group-settings").format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(next_page + 1, 0, CHAT_SETTINGS, "cntrl_panel_G", chat=chat_id))) elif back_match: text = "Control Panel :3" query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules( user.id, 0, CHAT_SETTINGS, "cntrl_panel_G")))
def filters(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] msg = update.effective_message # type: Optional[Message] args = msg.text.split( None, 1) # use python's maxsplit to separate Cmd, keyword, and reply_text conn = connected(bot, update, chat, user.id) if not conn == False: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: chat_id = update.effective_chat.id if chat.type == "private": chat_name = "local notes" else: chat_name = chat.title if len(args) < 2: return extracted = split_quotes(args[1]) if len(extracted) < 1: return # set trigger -> lower, so as to avoid adding duplicate filters with different cases keyword = extracted[0].lower() is_sticker = False is_document = False is_image = False is_voice = False is_audio = False is_video = False buttons = [] # determine what the contents of the filter are - text, image, sticker, etc if len(extracted) >= 2: offset = len(extracted[1]) - len( msg.text) # set correct offset relative to command + notename content, buttons = button_markdown_parser( extracted[1], entities=msg.parse_entities(), offset=offset) content = content.strip() if not content: msg.reply_text( tld( chat.id, "There is no note message - You can't JUST have buttons, you need a message to go with it!" )) return elif msg.reply_to_message and msg.reply_to_message.sticker: content = msg.reply_to_message.sticker.file_id is_sticker = True elif msg.reply_to_message and msg.reply_to_message.document: content = msg.reply_to_message.document.file_id is_document = True elif msg.reply_to_message and msg.reply_to_message.photo: content = msg.reply_to_message.photo[ -1].file_id # last elem = best quality is_image = True elif msg.reply_to_message and msg.reply_to_message.audio: content = msg.reply_to_message.audio.file_id is_audio = True elif msg.reply_to_message and msg.reply_to_message.voice: content = msg.reply_to_message.voice.file_id is_voice = True elif msg.reply_to_message and msg.reply_to_message.video: content = msg.reply_to_message.video.file_id is_video = True else: msg.reply_text(tld(chat.id, "You didn't specify what to reply with!")) return # Add the filter # Note: perhaps handlers can be removed somehow using sql.get_chat_filters for handler in dispatcher.handlers.get(HANDLER_GROUP, []): if handler.filters == (keyword, chat_id): dispatcher.remove_handler(handler, HANDLER_GROUP) sql.add_filter(chat_id, keyword, content, is_sticker, is_document, is_image, is_audio, is_voice, is_video, buttons) msg.reply_text(tld(chat.id, "Handler '{}' added in *{}*!").format( keyword, chat_name), parse_mode=telegram.ParseMode.MARKDOWN) raise DispatcherHandlerStop
def mute(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[Message] conn = connected(bot, update, chat, user.id) if not conn == False: chatD = dispatcher.bot.getChat(conn) else: if chat.type == "private": exit(1) else: chatD = chat user_id = extract_user(message, args) if not user_id: message.reply_text( tld( chat.id, "You'll need to either give me a username to mute, or reply to someone to be muted." )) return "" if user_id == bot.id: message.reply_text(tld(chat.id, "I'm not muting myself!")) return "" member = chatD.get_member(int(user_id)) if member: if user_id in SUDO_USERS: message.reply_text( tld( chat.id, "No! I'm not muting bot sudoers! That would be a pretty dumb idea." )) elif is_user_admin(chatD, user_id, member=member): message.reply_text( tld( chat.id, "No! I'm not muting chat administrator! That would be a pretty dumb idea." )) elif member.can_send_messages is None or member.can_send_messages: bot.restrict_chat_member(chatD.id, user_id, can_send_messages=False) keyboard = [] reply = tld(chat.id, "{} is muted in {}!").format( mention_html(member.user.id, member.user.first_name), chatD.title) message.reply_text(reply, reply_markup=keyboard, parse_mode=ParseMode.HTML) return "<b>{}:</b>" \ "\n#MUTE" \ "\n<b>Admin:</b> {}" \ "\n<b>User:</b> {}".format(html.escape(chatD.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name)) else: message.reply_text( tld(chat.id, "This user is already muted in {}!").format(chatD.title)) else: message.reply_text( tld(chat.id, "This user isn't in the {}!").format(chatD.title)) return ""
def unblacklist(bot: Bot, update: Update): msg = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] words = msg.text.split(None, 1) conn = connected(bot, update, chat, user.id) if not conn == False: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: chat_id = update.effective_chat.id if chat.type == "private": exit(1) else: chat_name = chat.title if len(words) > 1: text = words[1] to_unblacklist = list( set(trigger.strip() for trigger in text.split("\n") if trigger.strip())) successful = 0 for trigger in to_unblacklist: success = sql.rm_from_blacklist(chat_id, trigger.lower()) if success: successful += 1 if len(to_unblacklist) == 1: if successful: msg.reply_text(tld( chat.id, "Removed <code>{}</code> from the blacklist in <b>{}</b>!" ).format(html.escape(to_unblacklist[0]), chat_name), parse_mode=ParseMode.HTML) else: msg.reply_text( tld(chat.id, "This isn't a blacklisted trigger...!")) elif successful == len(to_unblacklist): msg.reply_text(tld( chat.id, "Removed <code>{}</code> triggers from the blacklist in <b>{}</b>!" ).format(successful, chat_name), parse_mode=ParseMode.HTML) elif not successful: msg.reply_text(tld( chat.id, "None of these triggers were exist, so they weren't removed."). format(successful, len(to_unblacklist) - successful), parse_mode=ParseMode.HTML) else: msg.reply_text(tld( chat.id, "Removed <code>{}</code> triggers from the blacklist in <b>{}</b>! {} did not exist, " "so were not removed.").format( successful, chat_name, len(to_unblacklist) - successful), parse_mode=ParseMode.HTML) else: msg.reply_text( tld( chat.id, "Tell me what words you would like to remove from the blacklist." ))
def get(bot, update, notename, show_none=True, no_format=False): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] conn = connected(bot, update, chat, user.id, need_admin=False) if conn: chat_id = conn send_id = user.id else: chat_id = update.effective_chat.id send_id = chat_id note = sql.get_note(chat_id, notename) message = update.effective_message # type: Optional[Message] if note: # If we're replying to a message, reply to that message (unless it's an error) if message.reply_to_message: reply_id = message.reply_to_message.message_id else: reply_id = message.message_id if note.is_reply: if MESSAGE_DUMP: try: bot.forward_message(chat_id=chat_id, from_chat_id=MESSAGE_DUMP, message_id=note.value) except BadRequest as excp: if excp.message == "Message to forward not found": message.reply_text( "This message seems to have been lost - I'll remove it " "from your notes list.") sql.rm_note(chat_id, notename) else: raise else: try: bot.forward_message(chat_id=chat_id, from_chat_id=chat_id, message_id=note.value) except BadRequest as excp: if excp.message == "Message to forward not found": message.reply_text( "Looks like the original sender of this note has deleted " "their message - sorry! Get your bot admin to start using a " "message dump to avoid this. I'll remove this note from " "your saved notes.") sql.rm_note(chat_id, notename) else: raise else: text = note.value keyb = [] parseMode = ParseMode.MARKDOWN buttons = sql.get_buttons(chat_id, notename) if no_format: parseMode = None text += revert_buttons(buttons) else: keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) try: if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT): try: bot.send_message(send_id, text, reply_to_message_id=reply_id, parse_mode=parseMode, disable_web_page_preview=True, reply_markup=keyboard) except BadRequest as excp: if excp.message == "Wrong http url": failtext = "The URL on the button is invalid! Please update this note!" failtext += "\n\n```\n{}```".format( note.value + revert_buttons(buttons)) message.reply_text(failtext, parse_mode="markdown") print("Gagal mengirim catatan: " + excp.message) pass else: ENUM_FUNC_MAP[note.msgtype](send_id, note.file, caption=text, reply_to_message_id=reply_id, parse_mode=parseMode, disable_web_page_preview=True, reply_markup=keyboard) except BadRequest as excp: if excp.message == "Entity_mention_user_invalid": message.reply_text( "Looks like you tried to mention someone I've never seen before. If you really " "want to mention them, forward one of their messages to me, and I'll be able " "to tag them!") elif FILE_MATCHER.match(note.value): message.reply_text( "This note was an incorrectly imported file from another bot - I can't use " "it. If you really need it, you'll have to save it again. In " "the meantime, I'll remove it from your notes list.") sql.rm_note(chat_id, notename) else: message.reply_text( "This note could not be sent, as it is incorrectly formatted, Please ask in @HarukaAyaGroup if you can't figure out why!" ) LOGGER.exception("Could not parse message #%s in chat %s", notename, str(chat_id)) LOGGER.warning("Message was: %s", str(note.value)) return elif show_none: message.reply_text("This note doesn't exist")
def nomedia(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[Message] conn = connected(bot, update, chat, user.id) if not conn == False: chatD = dispatcher.bot.getChat(conn) else: if chat.type == "private": exit(1) else: chatD = chat user_id = extract_user(message, args) if not user_id: message.reply_text( tld( chat.id, "You'll need to either give me a username to restrict, or reply to someone to be restricted." )) return "" if user_id == bot.id: message.reply_text(tld(chat.id, "I'm not restricting myself!")) return "" member = chatD.get_member(int(user_id)) if member: if is_user_admin(chatD, user_id, member=member): message.reply_text(tld(chat.id, "Afraid I can't restrict admins!")) elif member.can_send_messages is None or member.can_send_messages: bot.restrict_chat_member(chatD.id, user_id, can_send_messages=True, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False) keyboard = [] reply = tld(chat.id, "{} is restricted from sending media in {}!").format( mention_html(member.user.id, member.user.first_name), chatD.title) message.reply_text(reply, reply_markup=keyboard, parse_mode=ParseMode.HTML) return "<b>{}:</b>" \ "\n#RESTRICTED" \ "\n<b>• Admin:</b> {}" \ "\n<b>• User:</b> {}" \ "\n<b>• ID:</b> <code>{}</code>".format(html.escape(chatD.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), user_id) else: message.reply_text( tld(chat.id, "This user is already restricted in {}!")) else: message.reply_text( tld(chat.id, "This user isn't in the {}!").format(chatD.title)) return ""
def media(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[Message] conn = connected(bot, update, chat, user.id) if not conn == False: chatD = dispatcher.bot.getChat(conn) else: if chat.type == "private": exit(1) else: chatD = chat user_id = extract_user(message, args) if not user_id: message.reply_text( tld( chat.id, "You'll need to either give me a username to unrestrict, or reply to someone to be unrestricted." )) return "" member = chatD.get_member(int(user_id)) if member.status != 'kicked' and member.status != 'left': if member.can_send_messages and member.can_send_media_messages \ and member.can_send_other_messages and member.can_add_web_page_previews: message.reply_text( tld( chat.id, "This user already has the rights to send anything in {}." ).format(chatD.title)) else: bot.restrict_chat_member(chatD.id, int(user_id), can_send_messages=True, can_send_media_messages=True, can_send_other_messages=True, can_add_web_page_previews=True) keyboard = [] reply = tld(chat.id, "Yep, {} can send media again in {}!").format( mention_html(member.user.id, member.user.first_name), chatD.title) message.reply_text(reply, reply_markup=keyboard, parse_mode=ParseMode.HTML) return "<b>{}:</b>" \ "\n#UNRESTRICTED" \ "\n<b>• Admin:</b> {}" \ "\n<b>• User:</b> {}" \ "\n<b>• ID:</b> <code>{}</code>".format(html.escape(chatD.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), user_id) else: message.reply_text( tld( chat.id, "This user isn't even in the chat, unrestricting them won't make them send anything than they " "already do!")) return ""
def temp_nomedia(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[Message] conn = connected(bot, update, chat, user.id) if not conn == False: chatD = dispatcher.bot.getChat(conn) else: if chat.type == "private": exit(1) else: chatD = chat user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text( tld(chat.id, "You don't seem to be referring to a user.")) return "" try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text(tld(chat.id, "I can't seem to find this user")) return "" else: raise if is_user_admin(chat, user_id, member): message.reply_text( tld(chat.id, "I really wish I could restrict admins...")) return "" if user_id == bot.id: message.reply_text( tld(chat.id, "I'm not gonna RESTRICT myself, are you crazy?")) return "" if not reason: message.reply_text( tld(chat.id, "You haven't specified a time to restrict this user for!")) return "" split_reason = reason.split(None, 1) time_val = split_reason[0].lower() if len(split_reason) > 1: reason = split_reason[1] else: reason = "" mutetime = extract_time(message, time_val) if not mutetime: return "" log = "<b>{}:</b>" \ "\n#TEMP RESTRICTED" \ "\n<b>• Admin:</b> {}" \ "\n<b>• User:</b> {}" \ "\n<b>• ID:</b> <code>{}</code>" \ "\n<b>• Time:</b> {}".format(html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), user_id, time_val) if reason: log += "\n<b>• Reason:</b> {}".format(reason) try: if member.can_send_messages is None or member.can_send_messages: bot.restrict_chat_member(chat.id, user_id, until_date=mutetime, can_send_messages=True, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False) message.reply_text( tld(chat.id, "Restricted from sending media for {} in {}!").format( time_val, chatD.title)) return log else: message.reply_text( tld(chat.id, "This user is already restricted in {}.").format( chatD.title)) except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text(tld(chat.id, "Restricted for {} in {}!").format( time_val, chatD.title), quote=False) return log else: LOGGER.warning(update) LOGGER.exception("ERROR muting user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message) message.reply_text( tld(chat.id, "Well damn, I can't restrict that user.")) return ""