def askFinalAction(self) -> "Optional[str]": history = FileHistory(join(histDir, "action")) auto_suggest = AutoSuggestFromHistory() completer = WordCompleter( list(self._finalActions.keys()), ignore_case=False, match_middle=True, sentence=True, ) while True: action = prompt( "> Select action (ENTER to convert): ", history=history, auto_suggest=auto_suggest, completer=completer, ) if not action: return None if action not in self._finalActions: log.error(f"invalid action: {action}") continue return action
def askFile(self, kind: str, histName: str, varName: str, reading: bool): from shlex import split as shlex_split history = FileHistory(join(histDir, histName)) auto_suggest = AutoSuggestFromHistory() completer_keys = list(self._fsActions.keys()) # Note: isdir and isfile funcs follow sym links, so no worry about links for _path in os.listdir(os.getcwd()): if isdir(_path): continue completer_keys.append(_path) completer = WordCompleter( completer_keys, ignore_case=False, match_middle=False, sentence=True, ) default = getattr(self, varName) while True: filename = prompt( f"> {kind}: ", history=history, auto_suggest=auto_suggest, completer=completer, default=default, ) if not filename: continue parts = shlex_split(filename) if parts[0] in self._fsActions: actionFunc = self._fsActions[parts[0]] try: actionFunc(parts[1:]) except Exception as e: log.exception("") continue setattr(self, varName, filename) return filename raise ValueError(f"{kind} is not given")
def askOutputFormat(self) -> str: history = FileHistory(join(histDir, "format-output")) auto_suggest = AutoSuggestFromHistory() completer = WordCompleter( writeFormatDescList + Glossary.writeFormats, ignore_case=True, match_middle=True, sentence=True, ) while True: value = prompt( "> Output format: ", history=history, auto_suggest=auto_suggest, completer=completer, default=self._outputFormat, ) if not value: continue plugin = self.pluginByNameOrDesc(value) if plugin: return plugin.name raise ValueError("output format is not given")
def __init__(self): #判断运行平台 info = """当前运行平台为 Linux. 请将此二维码全部复制到windowns平台上的编辑器打开,用手机微信扫码登录!若已经登录,请忽略! (注:白色背景色的编辑器请将console_qr的值设置为-2,非白背景色的设置为2) """ #初始化颜色 SysType = sys.platform if SysType == "linux": print(Fore.RED + info) print(Style.RESET_ALL) bot = Bot(console_qr=2, cache_path=True) else: SysType = "win32" bot = Bot(cache_path=True) #基本设置 bot.messages.max_history = 10000 bot.auto_mark_as_read = True #获取登录名 myself = re.sub(">", "", str(bot.self).split()[1]) #初始化表格 table = PrettyTable(["说明", "当前登录用户名", "当前登登陆平台", "好友数量", "帮助信息"]) # 获取所有好友和群组 allfriends = bot.friends() allgroup = bot.groups() friendslist = [] groupslist = [] GList = [] Mplist = [] who = "" #所有好友和群聊和公众号 ALLChats = bot.chats() for all in ALLChats: tmp = re.sub(">", "", str(all).split()[1]) if "Group" in str(all).split()[0]: GList.append(tmp) elif "MP" in str(all).split()[0]: Mplist.append(tmp) #所有朋友 for i in allfriends: name = re.sub(">", "", str(i).split()[1]) friendslist.append(name) #所有群聊 for g in allgroup: groupname = re.sub(">", "", str(g).split()[1]) groupslist.append(groupname) #添加表格数据 if SysType == "win32": ShowsysType = "Windows" else: ShowsysType = SysType table.align["登录名"] = "1" table.padding_width = 2 table.add_row([ "欢迎使用微信终端聊天小工具", myself, ShowsysType, len(friendslist), "进入用户会话后 输入 h 或 help 查看帮助信息" ]) print(table) # 合并 friendslist + groupslist FriendsGroupList = friendslist + GList #构造自动补全的数据 NameCompleter = WordCompleter(FriendsGroupList, ignore_case=True) Emoticon = WordCompleter([ '[捂脸]', '[微笑]', '[撇嘴]', '[色]', '[发呆]', '[得意]', '[大哭]', '[尴尬]', '[发怒]', '[调皮]', '[呲牙]', '[吐]', '[偷笑]', '[愉快]', '[白眼]', '[傲慢]', '[流泪]', '[惊讶]', '[困]', '[害羞]', '[难过]', '[惊恐]', '[闭嘴]', '[囧]', '[流汗]', '[睡]', '[抓狂]', '[憨笑]', '[敲打]', '[鄙视]', '[悠闲]', '[再见]', '[委屈]', '[奋斗]', '[擦汗]', '[快哭了]', '[咒骂]', '[抠鼻]', '[阴脸]', '[疑问]', '[鼓掌]', '[亲亲]', '[嘘]', '[坏笑]', '[可怜]', '[晕]', '[左哼哼]', '[右哼哼]', '[菜刀]', '[衰]', '[西瓜]', '[骷髅]', '[哈欠]', '[啤酒]', '[炸弹]', '[抱拳]', '[咖啡]', '[便便]', '[勾引]', '[猪头]', '[月亮]', '[拳头]', '[玫瑰]', '[太阳]', '[OK]', '[凋谢]', '[拥抱]', '[跳跳]', '[嘴唇]', '[强]', '[发抖]', '[爱心]', '[弱]', '[怄火]', '[心碎]', '[握手]', '[转圈]', '[蛋糕]', '[胜利]', '[笑脸]', '[礼物]', '[生病]', '[奸笑]', '[红包]', '[破涕为笑]', '[机智]', '[發]', '[吐舌]', '[皱眉]', '[福]', '[脸红]', '[耶]', '[恐惧]', '[鬼魂]', '[失望]', '[合十]', '[无语]', '[强壮]', '[嘿哈]' ]) #初始化数据 self.NameCompleter = NameCompleter self.Emoticon = Emoticon self.friendslist = friendslist #所有朋友 self.groupslist = groupslist #仅仅保存到通讯录得群聊 self.GList = GList #所有群聊 self.ALLChatsList = FriendsGroupList #所有好友和群聊列表 self.Mplist = Mplist #关注的微信公众号 self.myself = myself self.bot = bot self.SysType = SysType
def __init__(self): # styling style = Style.from_dict({ 'completion-menu.completion': 'bg:#008888 #ffffff', 'completion-menu.completion.current': 'bg:#00aaaa #000000', 'scrollbar.background': 'bg:#88aaaa', 'scrollbar.button': 'bg:#222222', 'input-field': '#004400', 'buffer': '#ff0066', }) # create input fields self.source_field = make_text_area('[Source folder]: ') self.target_field = make_text_area('[Target folder]: ') self.dry_field = make_text_area('[{:13}]: '.format("Dry? (y/n)")) # get completers initialize_database() con = db_connect() self.source_field.completer = FuzzyCompleter( WordCompleter(get_source_paths(con), ignore_case=True)) self.target_field.completer = FuzzyCompleter( WordCompleter(get_target_paths(con), ignore_case=True)) self.dry_field.completer = WordCompleter( ['Yes', 'No', 'True', 'False', 'yes', 'no'], ignore_case=True) # bottom toolbar def bottom_toolbar_call(): s1 = '<b><style bg="ansired">C-H</style></b>: history mode.' s2 = '<b><style bg="ansired">C-C/C-Q</style></b>: exit app.' s3 = '<b><style bg="ansired">C-O</style></b>: ordered paths.' s4 = '<b><style bg="ansired">C-R</style></b>: reverse paths.' return HTML(" ".join([s1, s2, s3, s4])) self.bottom_toolbar = ConditionalContainer( Window(FormattedTextControl(lambda: bottom_toolbar_call, style='class:bottom-toolbar.text'), style='class:bottom-toolbar', dont_extend_height=True, height=Dimension(min=1)), filter=(~is_done & renderer_height_is_known & Condition(lambda: bottom_toolbar_call is not None))) # create app body self.body = FloatContainer(content=HSplit(children=[ self.source_field, self.target_field, self.dry_field, self.bottom_toolbar ], height=8), floats=[ Float(xcursor=True, ycursor=True, content=CompletionsMenu( max_height=12, scroll_offset=1)) ]) # define internal logic def execute_command(buff): """Send command to subprocess dealing with dry argument recursively""" dry = False if buff.text.lower() in ['n', 'no', 'false'] else True dry_flag = 'DRY' if dry else 'NOT DRY' dry_string = 'n' if dry else '' command = "rsync -avucP{} {} {}".format(dry_string, self.source_field.text, self.target_field.text) def run_script(): subprocess.call(command, shell=True) def print_info(): print_formatted_text( HTML('<ansired>{} </ansired>'.format(dry_flag))) print_formatted_text( HTML('<ansired>{} </ansired>'.format( 'You entered: {}'.format(command)))) print_formatted_text( HTML('<ansired>{} </ansired>'.format('Running...'))) run_in_terminal(print_info) if dry: run_in_terminal(run_script) return else: con = db_connect() create_rsync_record(con, self.source_field.text, self.target_field.text) run_in_terminal(run_script) app = get_app() app.exit() return self.dry_field.buffer.accept_handler = execute_command # Key bindings self.kb = KeyBindings() @self.kb.add('c-q') @self.kb.add('c-c') def _(event): " Quit application. " event.app.exit() #kb.add('enter')(focus_next) self.kb.add('tab')(focus_next) self.kb.add('s-tab')(focus_previous) # The `Application` self.app = Application( layout=Layout(self.body), #style=style, key_bindings=self.kb, full_screen=False, mouse_support=True)
from prompt_toolkit import prompt from prompt_toolkit.completion.word_completer import WordCompleter from AuctionDraftTool import players, fantasy_teams TeamCompleter = WordCompleter(fantasy_teams, ignore_case=True) def welcome_screen_prompt(): print('\n') print( 'Welcome to the Fantasy Auction draft Tool Kit! ~by Tucker Allen (https://github.com/Tucker-Allen)' ) prompt('[Press any key to continue]') def on_the_block_prompt(): PlayerCompleter = WordCompleter(list(players), ignore_case=True) on_the_block = prompt('Player nominated >> ', completer=PlayerCompleter) try: assert on_the_block in list(players.keys()) return on_the_block except: print('Invalid Player name, try again') return on_the_block_prompt() def bought_by_prompt(): bought_by = prompt('Bought By Fantasy Team >> ', completer=TeamCompleter) try: assert bought_by in fantasy_teams return bought_by
from prompt_toolkit import prompt from prompt_toolkit.styles import Style from prompt_toolkit import PromptSession from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.completion.word_completer import WordCompleter session = PromptSession() com=['aa','exitc','see_all_cve','help','see_one_cve','use_cve_poc','use_cve_exp','shodan'] Completer = WordCompleter(com, ignore_case=True) style = Style.from_dict({ # User input (default text). '': '#FFA500', # Prompt. 'pound': '#FFFFFF', 'path': '#FFFFFF', }) message = [ ('class:path', '王嘟嘟-blog:'), ('class:pound', '# '), ] while 1: user_input =session.prompt(message,
from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.completion.word_completer import WordCompleter from prompt_toolkit.completion.fuzzy_completer import FuzzyWordCompleter SQLCompleter = WordCompleter(['select', 'from', 'insert', 'update', 'delete', 'drop'], ignore_case=True) # SQLCompleter = FuzzyWordCompleter(['select', 'from', 'insert', 'update', 'delete', 'drop']) while 1: user_input = prompt('SQL>', history=FileHistory('history.txt'), auto_suggest=AutoSuggestFromHistory(), completer=SQLCompleter, ) print(user_input)
def askWriteOptions(self): plugin = Glossary.plugins[self._inputFormat] options = Glossary.formatsWriteOptions.get(self._outputFormat) if options is None: log.error(f"internal error: invalid format {self._outputFormat!r}") return optionsProp = Glossary.plugins[self._outputFormat].optionsProp history = FileHistory( join(histDir, f"write-options-{self._outputFormat}")) auto_suggest = AutoSuggestFromHistory() completer = WordCompleter( options.keys(), ignore_case=True, match_middle=True, sentence=True, ) while True: try: optName = prompt( ">> WriteOption: Name (ENTER if done): ", history=history, auto_suggest=auto_suggest, completer=completer, ) except (KeyboardInterrupt, EOFError): return if not optName: return option = optionsProp[optName] print(f"Comment: {option.longComment}") valueCompleter = self.getOptionValueCompleter(option) default = self._writeOptions.get(optName) if default is None: default = options[optName] while True: if option.typ == "bool": try: valueNew = checkbox_prompt( f">>> WriteOption: {optName}", default=default, ) except (KeyboardInterrupt, EOFError): break print(f"Set write-option: {optName} = {valueNew!r}") self._writeOptions[optName] = valueNew break try: value = prompt( f">>> WriteOption: {optName} = ", history=FileHistory( join(histDir, f"option-value-{optName}")), auto_suggest=AutoSuggestFromHistory(), default=str(default), completer=valueCompleter, ) except (KeyboardInterrupt, EOFError): break if value == "": if optName in self._writeOptions: print(f"Unset write-option {optName!r}") del self._writeOptions[optName] # FIXME: set empty value? break valueNew, ok = option.evaluate(value) if not ok or not option.validate(valueNew): log.error(f"Invalid write option value {optName}={value!r}" f" for format {self._outputFormat}") continue print(f"Set write-option: {optName} = {valueNew!r}") self._writeOptions[optName] = valueNew break
from prompt_toolkit import print_formatted_text # from prompt_toolkit.contrib.completers import WordCompleter from prompt_toolkit.completion.word_completer import WordCompleter import asyncio import pprint import random import time import requests import webcolors import whosonline.netcheck as netcheck whosonline_completer = WordCompleter(words=[ 'exit', 'hosts', 'nmap', 'stop', 'annoy_calendar', 'os', 'services', 'all', 'fast_nmap_loop', 'spawn_kevin', 'netcheck', 'probe' ], ignore_case=True) NETWORK = '192.168.88.0/24' welcome = ''' : : : : : RRVIttIti+==iiii++iii++=;:, : : IBMMMMWWWWMMMMMBXXVVYYIi=;:, : : tBBMMMWWWMMMMMMBXXXVYIti;;;:,, : t YXIXBMMWMMBMBBRXVIi+==;::;:::: , ;t IVYt+=+iIIVMBYi=:,,,=i+=;:::::, ;; YX=YVIt+=,,:=VWBt;::::=,,:::;;;:;: ;;; VMiXRttItIVRBBWRi:.tXXVVYItiIi==;: ;;;;