def search_slack(keys, query): wf = Workflow() search_results = [] for key in keys: api_key = str(key) slack_auth = web.get('https://slack.com/api/auth.test?token=' + api_key + '&pretty=1').json() if slack_auth['ok'] is False: wf.add_item( 'Authentication failed.' 'Try saving your API key again', valid=False) wf.send_feedback() else: results = web.get('https://slack.com/api/search.messages?token=' + api_key + '&query=' + query + '&count=10&pretty=1').json() if results['messages']['total'] > 0: for result in results['messages']['matches']: search_results.append({ 'text': result['text'], 'channel': result['channel']['name'], 'user': result['username'], 'team': slack_auth['team'], 'link': result['permalink'] }) else: search_results.append({ 'text': 'False', 'team': slack_auth['team'] }) return search_results
def slack_list(keys): wf = Workflow() slack_search = [] for key in keys: api_key = str(key) slack_auth = web.get('https://slack.com/api/auth.test?token=' + api_key + '&pretty=1').json() if slack_auth['ok'] is False: wf.add_item(title='Authentication failed. Check your API key', valid=False) wf.send_feedback() break else: slack_channels = web.get('https://slack.com/api/channels.list?token=' + api_key + '&exclude_archived=1&pretty=1').json() slack_users = web.get('https://slack.com/api/users.list?token=' + api_key + '&pretty=1').json() slack_groups = web.get('https://slack.com/api/groups.list?token=' + api_key + '&pretty=1').json() for channels in slack_channels['channels']: slack_search.append({'name': channels['name'], 'team': slack_auth['team'],'team_id': slack_auth['team_id'], 'id': channels['id'], 'type': 'channel', 'api_key': api_key}) for users in slack_users['members']: slack_search.append({'name': users['name'], 'team': slack_auth['team'],'team_id': slack_auth['team_id'], 'id': users['id'], 'type': 'user', 'api_key': api_key}) slack_search.append({'name': users['profile']['real_name'], 'team': slack_auth['team'],'team_id': slack_auth['team_id'], 'id': users['id'], 'type': 'user', 'api_key': api_key}) for groups in slack_groups['groups']: if 'name' in groups: slack_search.append({'name': groups['name'], 'team': slack_auth['team'],'team_id': slack_auth['team_id'], 'id': groups['id'], 'type': 'group', 'api_key': api_key}) return slack_search
def slack_list(keys): wf = Workflow() slack_search = [] for key in keys: api_key = str(key) slack_auth = web.get('https://slack.com/api/auth.test?token=' + api_key + '&pretty=1').json() if slack_auth['ok'] is False: wf.add_item(title='Authentication failed. Check your API key', valid=False) wf.send_feedback() break else: slack_channels = web.get('https://slack.com/api/channels.list?token=' + api_key + '&exclude_archived=1&pretty=1').json() slack_users = web.get('https://slack.com/api/users.list?token=' + api_key + '&pretty=1').json() slack_groups = web.get('https://slack.com/api/groups.list?token=' + api_key + '&pretty=1').json() for channels in slack_channels['channels']: slack_search.append({'name': channels['name'], 'team': slack_auth['team']}) for users in slack_users['members']: slack_search.append({'name': users['name'], 'team': slack_auth['team']}) for groups in slack_groups['groups']: if 'name' in groups: slack_search.append({'name': groups['name'], 'team': slack_auth['team']}) return slack_search
def slack_list(keys): wf = Workflow() slack_snooze = [] for key in keys: api_key = str(key) slack_auth = web.get('https://slack.com/api/auth.test?token=' + api_key + '&pretty=1').json() if slack_auth['ok'] is False: wf.add_item(title='Authentication failed. Check your API key', valid=False) wf.send_feedback() break else: slack_dnd = web.get( 'https://slack.com/api/dnd.info?token={token}&pretty=1'.format( token=api_key)).json() if slack_dnd['snooze_enabled'] is True: slack_snooze.append({ 'team': slack_auth['team'], 'status': 'Snoozed' }) else: slack_snooze.append({ 'team': slack_auth['team'], 'status': 'Active' }) return slack_snooze
def hipchat_keys(): wflw = Workflow() try: keys = wflw.get_password('hipchat_api_key') except PasswordNotFound: wflw.add_item(title='No API key set. Please run hipchat_api_token', valid=False) wflw.send_feedback() return 0 return keys.split(",")
def slack_keys(): wf = Workflow() try: slack_keys = wf.get_password('slack_api_key') except PasswordNotFound: wf.add_item(title='No API key set. Please run slt', valid=False) wf.send_feedback() return 0 keys = slack_keys.split(",") return keys
class ListHandler(object): """ The new way of fetching and displaying lists. Converting over to this. """ def __init__( self, query='', cache_timeout=60 * 10 ): self.workflow = Workflow() self.query = query self.cache_timeout = cache_timeout @property def cache_key(self): return self.__class__.__name__ def run(self): result = self.workflow.run(self._run) self.workflow.send_feedback() sys.exit(result) def fetch(self): raise NotImplementedError def _run(self, workflow): items = workflow.cached_data( self.cache_key, self.fetch, self.cache_timeout ) if self.query: items = self.filtered_items(items, self.query) for item in items: self.add_item(item) def add_item(self, item): raise NotImplementedError def filtered_items(self, items, query): return self.workflow.filter( query, items, key=lambda x: str(x) )
def my_slack_info(keys): wf = Workflow() my_info = [] for key in keys: api_key = str(key) slack_user_info = web.get('https://slack.com/api/auth.test?token=' + api_key + '&pretty=1').json() if slack_user_info['ok'] is False: wf.add_item(title='Authenticantion failed. Please check your API keys.', valid=False) wf.send_feedback() else: my_info.append({'team': slack_user_info['team'], 'user': slack_user_info['user'], 'team_id': slack_user_info['team_id']}) return my_info
def my_slack_info(keys): wf = Workflow() my_info = [] for key in keys: api_key = str(key) slack_user_info = web.get('https://slack.com/api/auth.test?token=' + api_key + '&pretty=1').json() if slack_user_info['ok'] is False: wf.add_item(title='Authentication failed. Please check your API keys.', valid=False) wf.send_feedback() else: my_info.append({'team': slack_user_info['team'], 'user': slack_user_info['user'], 'team_id': slack_user_info['team_id']}) return my_info
def hipchat_list(keys): wflw = Workflow() hipchat_search = [] for key in keys: api_key = str(key) try: hipchat_auth = web.get(wflw.settings['api_url'] + '/v2/room?auth_token=' + api_key + '&auth_test=true', None, timeout=wflw.settings['timeout']) except URLError, requests.SSLError: wflw.add_item(title='Error connecting to HipChat API.', valid=False) wflw.send_feedback() return None if not hipchat_auth or \ not hipchat_auth.status_code == requests.codes.accepted or \ not 'success' in hipchat_auth.json(): wflw.add_item(title='Authentication failed. Check your API token', valid=False) wflw.send_feedback() return None else: try: hipchat_rooms = web.get(wflw.settings['api_url'] + '/v2/room?auth_token=' + api_key + '&max-results=1000', None, timeout=wflw.settings['timeout'] ).json() hipchat_users = web.get(wflw.settings['api_url'] + '/v2/user?auth_token=' + api_key + '&max-results=1000', None, timeout=wflw.settings['timeout'] ).json() except URLError, requests.SSLError: wflw.add_item(title='Error fetching lists from HipChat API.', valid=False) wflw.send_feedback() return None for room in hipchat_rooms['items']: hipchat_search.append({ 'name': room['name'], 'id': room['id'], 'description': "%s Room" % room['privacy'].title(), 'type': 'room' }) for user in hipchat_users['items']: hipchat_search.append({ 'name': user['name'], 'mention_name': user['mention_name'], 'id': user['id'], 'description': "User @%s" % user['mention_name'], 'type': "user"})
def main(): wf = Workflow() args = parse_args(wf.args) title = 'Add this link' if args.add_archive: title = 'Add and archive this link' wf.add_item(title, arg=args.query, valid=True) tags = wf.cached_data('pocket_tags', max_age=0) if tags: for tag in tags: if args.query: autocomplete = '%s, #%s' % (args.query, tag) else: autocomplete = '#%s' % tag wf.add_item(' > Add #%s' % tag, autocomplete=autocomplete, valid=False) wf.send_feedback()
def search_slack(keys, query): wf = Workflow() search_results = [] for key in keys: api_key = str(key) slack_auth = web.get('https://slack.com/api/auth.test?token=' + api_key + '&pretty=1').json() if slack_auth['ok'] is False: wf.add_item('Authentication failed.' 'Try saving your API key again', valid=False) wf.send_feedback() else: results = web.get('https://slack.com/api/search.messages?token=' + api_key + '&query=' + query + '&count=10&pretty=1').json() if results['messages']['total'] > 0: for result in results['messages']['matches']: search_results.append({'text': result['text'], 'channel': result['channel']['name'], 'user': result['username'], 'team': slack_auth['team'], 'link': result['permalink']}) else: search_results.append({'text': 'False', 'team': slack_auth['team']}) return search_results
if len(ACTIONS) > 0: for action in ACTIONS: WF.add_item( action['name'], action['description'], uid=action['name'], autocomplete=action['autocomplete'], arg=action['arg'], valid=action['valid'], icon=get_icon("chevron-right"), ) else: WF.add_item( "No action found for '%s'" % query, autocomplete="", icon=get_icon("info") ) if len(WF._items) == 0: WF.add_item( "No formula found for '%s'" % query[query.find(" ") + 1:], autocomplete="%s " % query[:query.find(" ")], icon=get_icon("info") ) WF.send_feedback() # refresh cache cmd = ['/usr/bin/python', WF.workflowfile('cask_refresh.py')] run_in_background('cask_refresh', cmd)
ex = info["exchange"] total = amount * ex / exchange if total < 1: title = "{:0.6f} {}".format(total, cur) else: title = "{:0.2f} {}".format(total, cur) subtitle = "[{}] 1 {} = {:0.4f} {}".format( info["type"], currency, ex / exchange, cur, ) workflow.add_item( title=title, subtitle=subtitle, arg=title.split(" ")[0], copytext=title, icon=info["img"], valid=True, ) if __name__ == u"__main__": wf = Workflow() wf.run(main) wf.send_feedback() sys.exit()
if len(ACTIONS) > 0: for action in ACTIONS: WF.add_item( action['name'], action['description'], uid=action['name'], autocomplete=action['autocomplete'], arg=action['arg'], valid=action['valid'], icon=get_icon("chevron-right") ) else: WF.add_item( "No action found for '%s'" % query, autocomplete="", icon=get_icon("info") ) if len(WF._items) == 0: WF.add_item( "No formula found for '%s'" % query[query.find(" ") + 1:], autocomplete="%s " % query[:query.find(" ")], icon=get_icon("info") ) WF.send_feedback() # refresh cache cmd = ['/usr/bin/python', WF.workflowfile('brew_refresh.py')] run_in_background('brew_refresh', cmd)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # if __name__ == "__main__": arg = sys.argv[1] if len(sys.argv) > 1 else "" wf = Workflow() func = ["ball", "colr", "draw", "flip", "pick", "rand", "roll", "tell"] sub = { "ball": "Ask the Magic 8-Ball! `ball`", "colr": "See a Random Color! `colr`", "draw": "Draw a Card! `draw n`", "flip": "Flip a coin! Heads or Tails? `flip n`", "pick": "Just Pick One! `pick a,b,c`", "rand": "Generate a Random Number! `rand a..b`", "roll": "Roll a Dice! `roll nDk`", "tell": "Tell me! Yes or No? `tell`" } for f in func: if arg in f: wf.add_item(title=f, subtitle=sub[f], autocomplete="{} ".format(f), icon="resources/icon/{}.png".format(f), valid=False) elif f in arg: sys.exit(wf.run(locals()[f])) wf.send_feedback() # Send the results to Alfred as XML
icon='icons/warning.png' ) wf.send_feedback() return if __name__ == '__main__': # Configure a Workflow class and a logger: wf = Workflow(libraries=['./lib']) log = wf.logger # Configure a LpvmUtilities class: util = utilities.LpvmUtilities(wf) # Notify the user if they are not logged in: if not util.is_logged_in(): log.warning('Not logged into LastPass.') wf.add_item( 'Not logged in to LastPass.', 'Hit ENTER to open an Alfred command to login to LastPass.', valid=True, arg="login", icon='icons/warning.png' ) wf.send_feedback() sys.exit(1) # Run! sys.exit(wf.run(main))
# !/usr/bin/python # encoding: utf-8 from workflow import Workflow wf = Workflow() wf.clear_cache() wf.add_item(u'清除完毕') wf.send_feedback();
def getServerStatus(server_name): wf = Workflow() server_status = "" player_status = "" # Try and connect to Minecraft server try: server = MinecraftServer.lookup(server_name) status = server.status() latency = server.status().latency # Assign Default Values server_status = "Server is online" # Stores server host name server_name = "Server: {0}".format(server.host) # Store the Server message of the day motd = "" # Stores the server software brand and version server_software = "" # Stores the amount of players connected and the max available players player_status = "There are currently {0}/{1} players online".format(status.players.online, status.players.max) # Stores the server latency ping = ("The server replied in {0} ms".format(latency)) # If Query is enabled, will store the list of players connected detailed_players_connected = "" # Check to see if the server has query enabled try: query = server.query() motd = query.motd status = server.status() server_software = "{0} {1}".format(str(query.software.brand).capitalize(), status.version.name) intro = "" if status.players.online == 0: intro = "Player Information" elif status.players.online == 1: intro = "The following player is online: " else: intro = "The following players are online: " detailed_players_connected = intro + "{0}".format(", ".join(query.players.names)) except Exception: server_software = "Version: {0}".format(status.version.name) detailed_players_connected = "Player Information" # Populate Alfred with server information wf.add_item(title=server_name, subtitle=motd, icon=u'resources/server.png') wf.add_item(title=server_status, subtitle=server_software, icon=u'resources/online.png') wf.add_item(title=player_status, subtitle=detailed_players_connected, icon=u'resources/players.png') if ping != "": wf.add_item(title=ping, subtitle=u'Server Ping', icon=u'resources/ping.png') wf.send_feedback() except Exception: server_status = "Could not connect to server: {0}".format(server_name) wf.add_item(title=server_status, subtitle=u'Server Offline', icon=u'resources/offline.png') wf.send_feedback()
class UnifiedConverter: def __init__(self): self.wf = Workflow() self.models = [MD5(), DateTime(), Base64(), Html(), Javascript()] self.modelDict = dict() for m in self.models: self.modelDict[m.name] = m def convert(self, query): result = [] result += self.autocomplete(query) result += self.convert_by_type(query) result += self.convert_all(query) # sort self.add_to_wf(result) self.wf.send_feedback() def convert_all(self, query): result = [] if not query: return result for m in self.models: result += m.convert(query) return result def convert_by_type(self, query): query = str(query).strip() if query.find(' ') == -1: return [] group = query.split(' ', 1) type_value = group[0] input_value = group[1] if type_value in self.modelDict: return self.modelDict[type_value].convert(input_value) def autocomplete(self, query): result = [] if query.find(' ') >= 0: return result # 不是空的话有数量限制 for m in self.models: result += m.autocomplete(query) return result def add_to_wf(self, items): for item in items: self.wf.add_item(title=item.title, subtitle=item.subtitle, modifier_subtitles=item.modifier_subtitles, arg=item.arg, autocomplete=item.autocomplete, valid=item.valid, uid=item.uid, icon=item.icon, icontype=item.icontype, type=item.type, largetext=item.largetext, copytext=item.copytext)