def get_file_information(ptr_buffer): global hook_process_out, output (logfile,log_enabled) = get_logfile(ptr_buffer) if not log_enabled: output = OPTIONS["log_disabled"] return output = '' if logfile != '': # newline / word / bytes / filename weechat.hook_process("wc %s" % logfile, 50000, "my_hook_process_cb", "") if hook_process_out: lines = hook_process_out[0] words = hook_process_out[1] flength = sizecheck(hook_process_out[2]) tags = {'%L': str(lines), '%W': str(words), '%F': str(flength)} output = substitute_colors(OPTIONS['display']) # replace mandatory tags for tag in list(tags.keys()): # for tag in tags.keys(): output = output.replace(tag, tags[tag]) weechat.bar_item_update(SCRIPT_NAME) return
def postIm(message, handler=None, label=None, title=None, buffer_name=None, prefix=None): USERNAME = weechat.config_get_plugin("username") PASSWORD = weechat.config_get_plugin("password") SECRETKEY = weechat.config_get_plugin("secretkey") if USERNAME != "": url = "http://im.kayac.com/api/post/" + USERNAME opt_dict = { "message": "[%s][%s] - %s\n%s %s" % (label, buffer_name, title, prefix, message), } if PASSWORD != "": opt_dict["password"] = PASSWORD elif SECRETKEY != "": opt_dict["sig"] = hashlib.sha1(opt_dict["message"] + SECRETKEY).hexdigest() else: return opt = urllib.urlencode(opt_dict) cmd = "python -c 'from urllib2 import Request, urlopen; urlopen(Request(\"%s\", \"%s\"))'" % ( url, opt) weechat.hook_process(cmd, 10000, "hook_process_cb", "")
def hook_editor_process(terminal, editor, path, buf): term_cmd = "{} -e".format(terminal) editor_cmd = "{} {}".format(editor, path) weechat.hook_process("{} \"{}\"".format( term_cmd, editor_cmd ), 0, "editor_process_cb", buf)
def triggerwatch(data, buffer, args): global kserver, kchannel, knick, mode if options["enabled"] == "on": try: null, srvmsg = args.split(" PRIVMSG ", 1) except: return w.WEECHAT_RC_OK try: kchannel, query = srvmsg.split(" :{} ".format(options["weather_trigger"]), 1) mode = "conditions" except ValueError: try: kchannel, query = srvmsg.split(" :{} ".format(options["forecast_trigger"]), 1) mode = "forecast" except ValueError: return w.WEECHAT_RC_OK kserver = str(buffer.split(",", 1)[0]) knick = w.info_get("irc_nick_from_host", args) query = query.replace(" ", "%20") autoc_url = "url:http://autocomplete.wunderground.com/aq?query={}&format=JSON".format(query) w.hook_process(autoc_url, 30 * 1000, "wu_autoc", "") return w.WEECHAT_RC_OK
def hipchat_cmd(data, buffer, args): bitlbee_server = weechat.buffer_get_string(buffer, 'name').split('.')[0] if buffer == weechat.buffer_search_main(): weechat.prnt('', 'Hipchat commands must be run in IRC buffer') return weechat.WEECHAT_RC_ERROR if args.startswith('rooms'): room_args = args.split(' ', 1) if room_args[-1].startswith('**'): keyEvent(data, buffer, room_args[-1][2:]) return weechat.WEECHAT_RC_OK rooms_initialise_list(bitlbee_server) weechat.hook_process("url:https://api.hipchat.com/v2/room?auth_token=%s&max-results=1000" % get_token(), 30 * 1000, "room_list_cb", "") elif args == 'autojoin': rooms_initialise_list(bitlbee_server) nick = weechat.info_get('irc_nick', bitlbee_server) weechat.hook_process('url:https://api.hipchat.com/v2/user/@%s/preference/auto-join?' 'auth_token=%s&max-results=500' % (nick, get_token()), 30 * 1000, 'room_list_cb', '') elif args.startswith('whois'): whois_start(args[5:].strip()) elif args == 'fullnames': update_fullnames(buffer) elif args.startswith('nicks'): show_nicks(args.split(' ', 1)[-1]) return weechat.WEECHAT_RC_OK
def wu_autoc(data, command, return_code, out, err): """ weather underground auto search """ global jname if return_code == w.WEECHAT_HOOK_PROCESS_ERROR: w.prnt("", "Error with command `%s'" % command) return w.WEECHAT_RC_OK if return_code > 0: w.prnt("", "return_code = %d" % return_code) if err != "": w.prnt("", "stderr: %s" % err) if out != "": i = json.loads(out) try: loc = next((l for l in i["RESULTS"] if l["type"] == "city"), None) if loc is None: weebuffer("Unable to locate query.") return w.WEECHAT_RC_OK except: weebuffer("Invalid query. Try again.") return w.WEECHAT_RC_OK jname = loc["name"] location = loc["l"] prefix = "[weatherbot] mode:" if mode == "conditions": cond_url = "url:http://api.wunderground.com/api/{}/conditions{}.json".format(options["apikey"], location) w.prnt("", '{} {} {}'.format(prefix, mode, location)) w.hook_process(cond_url, 30 * 1000, "wu_cond", "") if mode == "forecast": fore_url = "url:http://api.wunderground.com/api/{}/forecast{}.json".format(options["apikey"], location) w.prnt("", '{} {} {}'.format(prefix, mode, location)) w.hook_process(fore_url, 30 * 1000, "wu_fore", "") return w.WEECHAT_RC_OK
def show_notification(chan, message): weechat.prnt("", "Showing notification") payload_dic = { "endpoint": weechat.config_get_plugin("endpoint"), "key": weechat.config_get_plugin("key"), "authSecret": weechat.config_get_plugin("authSecret"), "payload": { "channel": chan, "msg": message }, "vapidDetails": { "publicKey": weechat.config_get_plugin("vapidPublicKey"), "privateKey": weechat.config_get_plugin("vapidPrivateKey"), "subject": weechat.config_get_plugin("vapidSubject") } } url = weechat.config_get_plugin("webpushProxy") weechat.prnt("", url) weechat.prnt("", json.dumps(payload_dic)) #payload = urllib.urlencode(payload_dic) python2_bin = weechat.info_get("python2_bin", "") or "python" weechat.prnt("", python2_bin) payload = json.dumps(payload_dic).replace('"', '\\"') #weechat.hook_process( # python2_bin + " -c \"import urllib2\n" # "req = urllib2.Request('" + url + "', '" + payload + "', {'Content-Type': 'application/json'})\n" # "res = urllib2.urlopen(req)\n\"", # 30 * 1000, "", "") cmd = """{} -c "import urllib2 req = urllib2.Request('{}', '{}', {{'Content-Type': 'application/json'}}) res = urllib2.urlopen(req) """.format(python2_bin, url, payload) weechat.prnt("", cmd) weechat.hook_process(cmd, 30 * 1000, "", "")
def hook_process(args, callback, stdin=None, userdata=None): # same as hook_timer. injects a random name in __main__ to # wrap around the actual callback. state = { 'stdout': '', 'stderr': '', } @functools.wraps(callback) def _hook_process_helper(genfuncname, command, rc, out, err): state['stdout'] += out state['stderr'] += err if rc == weechat.WEECHAT_HOOK_PROCESS_RUNNING: return weechat.WEECHAT_RC_OK remove_func(genfuncname) result = callback(rc, state['stdout'], state['stderr'], userdata) if result is None: result = weechat.WEECHAT_RC_OK return result genfuncname = inject_func(_hook_process_helper) cmd = ' '.join(pipes.quote(arg) for arg in args) weechat.hook_process(cmd, 30 * 1000, genfuncname, genfuncname)
def triggerwatch(data, buffer, args): global kserver, kchannel, knick, mode if options["enabled"] == "on": try: null, srvmsg = args.split(" PRIVMSG ", 1) except: return w.WEECHAT_RC_OK try: kchannel, query = srvmsg.split( " :{} ".format(options["weather_trigger"]), 1) mode = "conditions" except ValueError: try: kchannel, query = srvmsg.split( " :{} ".format(options["forecast_trigger"]), 1) mode = "forecast" except ValueError: return w.WEECHAT_RC_OK kserver = str(buffer.split(",", 1)[0]) knick = w.info_get("irc_nick_from_host", args) query = query.replace(" ", "%20") autoc_url = "url:http://autocomplete.wunderground.com/aq?query={}&format=JSON".format( query) w.hook_process(autoc_url, 30 * 1000, "wu_autoc", "") return w.WEECHAT_RC_OK
def hook_process(args, callback, stdin=None, userdata=None): # same as hook_timer. injects a random name in __main__ to # wrap around the actual callback. state = { 'stdout': '', 'stderr': '', } @functools.wraps(callback) def _hook_process_helper(genfuncname, command, rc, out, err): state['stdout'] += out state['stderr'] += err if rc == weechat.WEECHAT_HOOK_PROCESS_RUNNING: return weechat.WEECHAT_RC_OK remove_func(genfuncname) result = callback(rc, state['stdout'], state['stderr'], userdata) if result is None: result = weechat.WEECHAT_RC_OK return result genfuncname = inject_func(_hook_process_helper) cmd = ' '.join(pipes.quote(arg) for arg in args) weechat.hook_process(cmd, 30*1000, genfuncname, genfuncname)
def cmd_help(data, buffer, args): # Get current list of ignored channels in list form ignored_channels = get_ignored_channels() # Used for checking for ignore/unignore commands and getting the arguments ignore_command = re.match("^ignore\s+(.+)", args) unignore_command = re.match("^unignore\s+(.+)", args) if (ignore_command is not None): channels_to_ignore = ignore_command.group(1).split(' ') for channel in channels_to_ignore: if channel not in ignored_channels: ignored_channels.append(channel) w.config_set_plugin("ignored_channels", ','.join(ignored_channels)) w.prnt( "", "Updated. Ignored channels: %s" % w.config_get_plugin("ignored_channels")) elif (unignore_command is not None): channels_to_unignore = unignore_command.group(1).split(' ') for channel in channels_to_unignore: if channel in ignored_channels: ignored_channels.remove(channel) w.config_set_plugin("ignored_channels", ','.join(ignored_channels)) w.prnt( "", "Updated. Ignored channels: %s" % w.config_get_plugin("ignored_channels")) elif (args == "listignores"): w.prnt( "", "Ignored channels: %s" % w.config_get_plugin("ignored_channels")) elif (args == "listdevices"): apikey = w.string_eval_expression(w.config_get_plugin("api_key"), {}, {}, {}) apiurl = "https://joinjoaomgcd.appspot.com/_ah/api/registration/v1/listDevices?apikey=%s" % ( apikey) w.hook_process("url:" + apiurl, 20000, "process_devicelist_cb", "") else: w.prnt( "", """ WeeJoin requires an API key from your Join account to work. Set your API key with (evaluated): /set plugins.var.python.weejoin.api_key <KEY> WeeJoin will by default only send notifications when you are marked away on IRC. You can change this with: /set plugins.var.python.weejoin.away_only [0|1] WeeJoin will by default send to all devices associated with your Join account. You can change this with: /set plugins.var.python.weejoin.device_iden <ID> WeeJoin can ignore repeated notifications if they arrive too often. You can set this with (0 or blank to disable): /set plugins.var.python.weejoin.min_notify_interval <NUMBER> You can get a list of your devices from the Join website, or by using /weejoin listdevices """) return w.WEECHAT_RC_OK
def script_main(data, remaining_calls): # Weechat is single-threaded so a new process is created so other things aren't held up # if retrieving Google Calendar events doesn't return in a timely manner. # https://weechat.org/files/doc/stable/weechat_scripting.en.html#weechat_architecture weechat.hook_process('func:get_calendar', TIMEOUT_MS, 'get_calendar_callback', CALLED_FROM_TIMER) return weechat.WEECHAT_RC_OK
def imap_timer_cb(data, remaining_calls): """Timer callback to update imap bar item.""" if WEECHAT_VERSION >= 0x01050000: w.hook_process('func:imap_get_unread', 30 * 1000, 'imap_process_cb', '') else: imap_update_content(imap_get_unread(None)) # this can block WeeChat! return w.WEECHAT_RC_OK
def async_slack_api_request(browser, request, data): t = int(time.time()) request += "?t=%s" % t data["token"] = stuff["api_token"] data = urllib.urlencode(data) command = 'curl --data "%s" https://%s/api/%s' % (data,domain,request) w.hook_process(command, 5000, '', '') return True
def run_cmd(cmd, srv, chn, fmt): weechat.hook_process("bash -c %s" % (escapeshellarg(cmd)), 5000, "run_proc_cb", json.dumps({ 'srv': srv, 'chn': chn, 'fmt': fmt }))
def do_register(args): if len(args) != 2: prnt("Incorrect usage. Try /help signal") return None number = args[1] weechat.hook_process( '%s -u %s register' % (options['signal_cli_command'], number), 3000, "register_cb", number)
def fn_connected(data, signal, signal_data): global ip_from_option # check if xfer option exists own_ip_option = w.config_get("xfer.network.own_ip") if not own_ip_option: return w.WEECHAT_RC_OK ip_from_option = w.config_string(own_ip_option) w.hook_process("url:%s" % OPTIONS["url"], 60000, "fn_setip", "") return w.WEECHAT_RC_OK
def postIm(message, handler=None, label=None, title=None): USERNAME = weechat.config_get_plugin("username") PASSWORD = weechat.config_get_plugin("password") if USERNAME != "" and PASSWORD != "": url = "http://im.kayac.com/api/post/" + USERNAME opt_dict = {"message": "[%s] - %s\n%s" % (label, title, message), "password": PASSWORD} opt = urllib.urlencode(opt_dict) cmd = 'python -c \'from urllib2 import Request, urlopen; urlopen(Request("%s", "%s"))\'' % (url, opt) weechat.hook_process(cmd, 10000, "hook_process_cb", "")
def fn_connected(data, signal, signal_data): global ip_from_option # check if xfer option exists own_ip_option = w.config_get("xfer.network.own_ip") if not own_ip_option: return w.WEECHAT_RC_OK ip_from_option = w.config_string(own_ip_option) w.hook_process('url:%s' % OPTIONS['url'], 60000, "fn_setip", "") return w.WEECHAT_RC_OK
def do_verify(args): if len(args) != 3: prnt("Incorrect arguments. Try /help signal") return None number = args[1] code = args[2] weechat.hook_process( '%s -u %s verify %s' % (options['signal_cli_command'], number, code), 3000, "verify_cb", number) return weechat.WEECHAT_RC_OK
def extract_new_version(new_version, url, rc, out, err): logger.debug( "Update download finished! Signed binaries are for suckers so we're just gonna extract it!" ) tarball = "/tmp/signal-cli-%s.tar.gz" % new_version weechat.hook_process( 'tar xzf %s -C %s/signal-cli' % (tarball, weechat.info_get("weechat_dir", "")), 60000, 'update_extract_cb', new_version) return weechat.WEECHAT_RC_OK
def cmd_pagetitle_cb(data, buffer, args): if len(args) == 0: return weechat.WEECHAT_RC_ERROR weechat.hook_process( "func:add_page_titles", 30 * 1000, "process_cb", f"{buffer};{args}", ) return weechat.WEECHAT_RC_OK
def oauth_dance(buffer, pin = ""): #Auth the twitter client if pin == "": weechat.prnt(buffer,"Hi there! We're gonna get you all set up to use this plugin.") weechat.hook_process("python3 " + SCRIPT_FILE_PATH + " " + "'' " + "'' " + "auth", 10 * 1000, "oauth_proc_cb", "auth1") else: oauth_verifier = pin.strip() weechat.hook_process("python3 " + SCRIPT_FILE_PATH + " " + script_options["oauth_token"] + " " + script_options["oauth_secret"] + " " + "auth "+ oauth_verifier, 10 * 1000, "oauth_proc_cb", "auth2")
def gcal_command(data, buffer, args): buffer = buffer_get() # TODO Implement init if args == 'init': pass else: weechat.hook_process('func:get_calendar', TIMEOUT_MS, 'get_calendar_callback', CALLED_FROM_CMD) return weechat.WEECHAT_RC_OK
def do_url(item): try: query = urlparse.parse_qs(item[1]["postfields"]) if query.has_key("channel") and item[0].find('history') > -1: channel = query["channel"][0] channel = channels.find(channel) channel.server.buffer_prnt("downloading channel history for %s" % (channel.name), backlog=True) except: pass command = 'curl --data "%s" %s' % (item[1]["postfields"], item[0][4:]) w.hook_process(command, 10000, item[3], item[4])
def get_devices(): api_key = get_api_key() apiurl = 'https://{}@api.pushbullet.com/v2/devices'.format(api_key) w.hook_process( 'url:' + apiurl, int(w.config_get_plugin('api_timeout')) * 1000, 'process_devicelist_cb', '', ) return ""
def cowcall(data, buffer, args): cowfile, sep, say = args.partition(" ") if cowfile == "" or say == "": return weechat.WEECHAT_RC_ERROR say = re.sub(pat, r'\\\1', say) channel = weechat.buffer_get_string(buffer, "localvar_channel") server = weechat.buffer_get_string(buffer, "localvar_server") weechat.hook_process("cowsay -f {} {}".format(cowfile, say), 2000, "cowchat", "{};{}".format(server, channel)) return weechat.WEECHAT_RC_OK
def cowcall(data, buffer, args): cowfile, sep, say = args.partition(" ") if cowfile == "" or say == "": return weechat.WEECHAT_RC_ERROR server, sep, channel = weechat.buffer_get_string(buffer, "name").partition("#") server = server[0:-1] channel = ''.join([sep, channel]) weechat.hook_process("cowsay -f {0} {1}".format(cowfile, say), 2000, "cowchat", "{0};{1}".format(server, channel)) return weechat.WEECHAT_RC_OK
def update_download_cb(info, url, rc, out, err): global downloads_in_progresss info = json.loads(info) downloads_in_progresss.remove(info.get('filename')) if len(downloads_in_progresss) > 0: prnt("%s finished, still waiting on %s" % (info.get('filename'), ", ".join(downloads_in_progresss))) else: weechat.hook_process( "mkdir %s/signal-cli" % weechat.info_get("weechat_dir", ""), 1000, 'extract_new_version', info.get('version')) return weechat.WEECHAT_RC_OK
def oauth_proc_cb(data, command, rc, out, err): global script_options buffer = twit_buf if rc == weechat.WEECHAT_HOOK_PROCESS_ERROR: weechat.prnt("", "Error with command '%s'" % command.replace(script_options["oauth_token"],"").replace(script_options["oauth_secret"],"")) return weechat.WEECHAT_RC_OK if out != "": if data == "nick": weechat.config_set_plugin('screen_name', out.strip()) finish_init() elif data == "friends": process_output = ast.literal_eval(out) if isinstance(process_output[-1], int): t_id = dict_tweet(str(process_output[-1])) + "\t" process_output = process_output[:-1] weechat.prnt_date_tags(buffer, 0, "no_highlight", t_id + "It sees like you are following more than 250 people. Due to twitter api limits " + "it is nearly impossible to get large groups of followers in one go. However the " + "nicks will be added when they tweet something so if you don't have to be able " + "autocomplete them from the start this is not a problem for you." + " If you want to get the rest of the nicks you can use the id of this text.") for nick in process_output: add_to_nicklist(buffer,nick) #Get latest tweets from timeline buffer_input_cb("silent", buffer, ":new") elif data == "auth1": #First auth step to request pin code oauth_token, oauth_token_secret = parse_oauth_tokens(out) script_options['oauth_token'] = oauth_token script_options['oauth_secret'] = oauth_token_secret weechat.prnt(buffer,""" Copy the PIN number that appears on the linked web page and type ":auth <pin>" in weechat. For example ":auth 123456" """) oauth_url = ('https://api.twitter.com/oauth/authorize?oauth_token=' + oauth_token) weechat.prnt(buffer," Please go here to get your PIN: " + oauth_url) elif data == "auth2": oauth_token, oauth_token_secret = parse_oauth_tokens(out) weechat.config_set_plugin('oauth_token', oauth_token) weechat.config_set_plugin('oauth_secret', oauth_token_secret) weechat.config_set_plugin('auth_complete', "on") weechat.prnt(buffer," Done! now you can begin using this script!") weechat.hook_process("python3 " + SCRIPT_FILE_PATH + " " + script_options["oauth_token"] + " " + script_options["oauth_secret"] + " " + "settings []", 10 * 1000, "oauth_proc_cb", "nick") return weechat.WEECHAT_RC_OK
def show_pic(pic, size, x, y): global showtime im = Image.open(pic) ww = im.size[0] hh = im.size[1] if ww >= hh: hh = hh * size / ww ww = size else: ww = ww * size / hh hh = size cmd = "feh -g %sx%s+%s+%s --scale-down " % (ww, hh, str(x), str(y)) w.hook_process(cmd + pic, showtime * 1000, "", "")
def run_rl(srv, chn): logfile = '~/.weechat/logs/irc.%s.%s.weechatlog' % (srv, chn) cmd = '''tail -c "+$[ 1 + $[ RANDOM % $(stat -c '%s' ''' + \ logfile + \ ''') ]]" ''' + \ logfile + \ '''| head -n21 | tail -n20 2>/dev/null | ''' \ '''grep -Pv '(-->|<--|You are now known as)' | shuf -n1 | cut -f3-''' weechat.hook_process( "bash -c %s" % (escapeshellarg(cmd)), 5000, "run_proc_cb", json.dumps({'srv': srv, 'chn': chn, 'fmt': "%s"}))
def giphy_cb(data, buf, args): if not args: weechat.prnt(buf, '[giphy]:\t%sNothing to search for. :(' % (RED,)) return weechat.WEECHAT_RC_ERROR s_args = args.split() if s_args[0][0] == '#': weechat.prnt(buf, '[giphy]:\t%sFancy searches aren\'t allowed yet. :(' % (RED,)) return weechat.WEECHAT_RC_ERROR args = ' '.join(s_args) cmd = 'url:https://api.giphy.com/v1/gifs/search?' + urlencode({'q': args, 'api_key': 'dc6zaTOxFJmzC', 'limit': 1}) cmd_to_query[cmd] = Query(buf, args) weechat.hook_process(cmd, 10000, 'hook_process_cb', '') return weechat.WEECHAT_RC_OK
def postIm(message, handler=None, label=None, title=None): USERNAME = weechat.config_get_plugin("username") PASSWORD = weechat.config_get_plugin("password") if USERNAME != "" and PASSWORD != "": url = "http://im.kayac.com/api/post/" + USERNAME opt_dict = { "message": "[%s] - %s\n%s" % (label, title, message), "password": PASSWORD, } opt = urllib.urlencode(opt_dict) cmd = "python -c 'from urllib2 import Request, urlopen; urlopen(Request(\"%s\", \"%s\"))'" % ( url, opt) weechat.hook_process(cmd, 10000, "hook_process_cb", "")
def shorten(buffer, url): shortener = weechat.config_get_plugin('shortener') if shortener == 'rldn.net': url = "url:http://rldn.net/api/{url}".format(url=url) if shortener == 'is.gd': url = "url:http://is.gd/create.php?format=simple&url={url}".format(url=url) if shortener == 'v.gd': url = "url:http://v.gd/create.php?format=simple&url={url}".format(url=url) weechat.hook_process(url, 30 * 1000, "print_short", buffer) return weechat.WEECHAT_RC_OK
def scp_file(filename, remote_dir): command_string = "scp -q" if configurations['local_identity_key'] != "": command_string += " -i " + configurations['local_identity_key'] if configurations['remote_port'] != "": command_string += " -P " + configurations['remote_port'] command_string += " " + filename if configurations['remote_user'] != "": command_string += " " + configurations['remote_user'] + "@" command_string += configurations['remote_host'] command_string += ":" command_string += remote_dir weechat.hook_process(command_string, 0, 'xfer_scp_process_cb', filename)
def cmd_help(data, buffer, args): # Get current list of ignored channels in list form ignored_channels = get_ignored_channels() # Used for checking for ignore/unignore commands and getting the arguments ignore_command = re.match("^ignore\s+(.+)", args) unignore_command = re.match("^unignore\s+(.+)", args) if(ignore_command is not None): channels_to_ignore = ignore_command.group(1).split(' ') for channel in channels_to_ignore: if channel not in ignored_channels: ignored_channels.append(channel) w.config_set_plugin("ignored_channels", ','.join(ignored_channels)) w.prnt("", "Updated. Ignored channels: %s" % w.config_get_plugin("ignored_channels")) elif(unignore_command is not None): channels_to_unignore = unignore_command.group(1).split(' ') for channel in channels_to_unignore: if channel in ignored_channels: ignored_channels.remove(channel) w.config_set_plugin("ignored_channels", ','.join(ignored_channels)) w.prnt("", "Updated. Ignored channels: %s" % w.config_get_plugin("ignored_channels")) elif(args == "listignores"): w.prnt("", "Ignored channels: %s" % w.config_get_plugin("ignored_channels")) elif(args == "listdevices"): apikey = w.config_get_plugin("api_key") apiurl = "https://%[email protected]/v2/devices" % (apikey) w.hook_process("url:" + apiurl, 20000, "process_devicelist_cb", "") else: w.prnt("", """ Weebullet requires an API key from your Pushbullet account to work. Set your API key with: /set plugins.var.python.weebullet.api_key <KEY> Weebullet will by default only send notifications when you are marked away on IRC. You can change this with: /set plugins.var.python.weebullet.away_only [0|1] Weebullet will by default send to all devices associated with your Pushbullet account. You can change this with: /set plugins.var.python.weebullet.device_iden <ID> Weebullet can ignore repeated notifications if they arrive too often. You can set this with (0 or blank to disable): /set plugins.var.python.weebullet.min_notify_interval <NUMBER> You can get a list of your devices from the Pushbullet website, or by using /weebullet listdevices """) return w.WEECHAT_RC_OK
def msg_cb(data, buffer, date, tags, displayed, highlight, prefix, message): if not checkTime(date): return weechat.WEECHAT_RC_OK match = re.match("^!xander (.+)$", message, re.IGNORECASE) if match is None: return weechat.WEECHAT_RC_OK groups = match.groups() if len(groups) == 0: return weechat.WEECHAT_RC_OK weechat.hook_process("say -v Xander -- '{}'".format(groups[0]), 0, "", "") return weechat.WEECHAT_RC_OK
def show_notification(chan, message): NOTIFO_USER = weechat.config_get_plugin("username") NOTIFO_API_SECRET = weechat.config_get_plugin("api_secret") if NOTIFO_USER != "" and NOTIFO_API_SECRET != "": url = "https://api.notifo.com/v1/send_notification" opt_dict = {"msg": message, "label": "weechat", "title": chan} opt = urllib.urlencode(opt_dict) basic = "Basic %s" % ":".join([NOTIFO_USER, NOTIFO_API_SECRET ]).encode("base64").strip() python2_bin = weechat.info_get("python2_bin", "") or "python" weechat.hook_process( python2_bin + " -c \"import urllib2\n" "req = urllib2.Request('" + url + "', '" + opt + "')\n" "req.add_header('Authorization', '" + basic + "')\n" "res = urllib2.urlopen(req)\n\"", 30 * 1000, "", "")
def show_notification(chan, message): AIRGRAM_KEY = weechat.config_get_plugin("key") AIRGRAM_SECRET = weechat.config_get_plugin("secret") if AIRGRAM_KEY != "" and AIRGRAM_SECRET != "": url = "https://api.airgramapp.com/1/broadcast" opt_dict = {"msg": chan + ":" + message} opt = urllib.urlencode(opt_dict) basic = "Basic %s" % ":".join([AIRGRAM_KEY, AIRGRAM_SECRET ]).encode("base64").strip() python2_bin = weechat.info_get("python2_bin", "") or "python" weechat.hook_process( python2_bin + " -c \"import urllib2\n" "req = urllib2.Request('" + url + "', '" + opt + "')\n" "req.add_header('Authorization', '" + basic + "')\n" "res = urllib2.urlopen(req)\n\"", 30 * 1000, "", "")
def lastfm_cmd(data, buffer, args): """Print last track played""" api_key = weechat.config_get_plugin('api_key') api_url = weechat.config_get_plugin('api_url') timeout = weechat.config_get_plugin('timeout') # use user in argument, or in config if args: user = args else: user = weechat.config_get_plugin('user') url = 'url:' + api_url.format(user=user.lower(), api_key=api_key) weechat.hook_process(url, int(timeout), 'get_recent_track', '') return weechat.WEECHAT_RC_OK
def wg_download_file(url, filename, timeout, callback, callback_data): """Download a file with an URL. Return hook_process created.""" version = weechat.info_get("version_number", "") or 0 if int(version) >= 0x00030700: return weechat.hook_process_hashtable("url:%s" % url, { "file_out": filename }, timeout, callback, callback_data) else: script = [ "import sys", "try:", " if sys.version_info >= (3,):", " import urllib.request", " response = urllib.request.urlopen('%s')" % url, " else:", " import urllib2", " response = urllib2.urlopen(urllib2.Request('%s'))" % url, " f = open('%s', 'wb')" % filename, " f.write(response.read())", " response.close()", " f.close()", "except Exception as e:", " print('error:' + str(e))" ] return weechat.hook_process("python -c \"%s\"" % "\n".join(script), timeout, callback, callback_data)
def shell_exec(buffer, command): """Execute a command.""" global cmd_hook_process, cmd_command, cmd_start_time, cmd_buffer global cmd_stdout, cmd_stderr, cmd_send_to_buffer, cmd_timeout if cmd_hook_process: weechat.prnt(buffer, '%sanother process is running! (use "/%s -kill" to kill it)' % (SHELL_PREFIX, SHELL_CMD)) return if cmd_send_to_buffer == 'new': weechat.prnt(buffer, '-->\t%s%s$ %s%s' % (weechat.color('chat_buffer'), os.getcwd(), weechat.color('reset'), command)) weechat.prnt(buffer, '') args = command.split(' ') if args[0] == 'cd': shell_chdir(buffer, ' '.join(args[1:])) elif args[0] == 'getenv': shell_getenv (buffer, ' '.join(args[1:])) elif args[0] == 'setenv': shell_setenv (buffer, ' '.join(args[1:])) elif args[0] == 'unsetenv': shell_unsetenv (buffer, ' '.join(args[1:])) else: shell_init() cmd_command = command cmd_start_time = datetime.datetime.now() cmd_buffer = buffer version = weechat.info_get("version_number", "") or 0 if int(version) >= 0x00040000: cmd_hook_process = weechat.hook_process_hashtable('sh', { 'arg1': '-c', 'arg2': command }, cmd_timeout * 1000, 'shell_process_cb', command) else: cmd_hook_process = weechat.hook_process("sh -c '%s'" % command, cmd_timeout * 1000, 'shell_process_cb', command)
def finish_init(): global timer_hook buffer = twit_buf if script_options['screen_name'] == "": weechat.hook_process("python3 " + SCRIPT_FILE_PATH + " " + script_options["oauth_token"] + " " + script_options["oauth_secret"] + " " + "settings []", 10 * 1000, "oauth_proc_cb", "nick") return setup_buffer(buffer) #Add friends to nick list and print new tweets weechat.hook_process("python3 " + SCRIPT_FILE_PATH + " " + script_options["oauth_token"] + " " + script_options["oauth_secret"] + " " + "f " + script_options['screen_name'] + " []", 10 * 1000, "oauth_proc_cb", "friends")
def wu_autoc(data, command, return_code, out, err): global jname if return_code == weechat.WEECHAT_HOOK_PROCESS_ERROR: weechat.prnt("", "Error with command '%s'" % command) return weechat.WEECHAT_RC_OK if return_code > 0: weechat.prnt("", "return_code = %d" % return_code) if err != "": weechat.prnt("", "stderr: %s" % err) if out != "": i = ast.literal_eval(out) loc_id = "" try: loc_id = i['RESULTS'][0]['l'] except: reaction = 'Invalid query. Try again.' weebuffer(reaction) return weechat.WEECHAT_RC_OK jname = i['RESULTS'][0]['name'] if jname == "": reaction = 'Unable to locate query.' weebuffer(reaction) return weechat.WEECHAT_RC_OK else: pass cond_url = 'url:http://api.wunderground.com/api/' + apikey + '/conditions' + loc_id + '.json' cond_hook = weechat.hook_process(cond_url, 30 * 1000, "wu_cond", "") return weechat.WEECHAT_RC_OK
def shell_exec(buffer, command): """Execute a command.""" global cmd_hook_process, cmd_command, cmd_start_time, cmd_buffer global cmd_stdout, cmd_stderr, cmd_send_to_buffer, cmd_timeout if cmd_hook_process: weechat.prnt(buffer, '%sanother process is running! (use "/%s -kill" to kill it)' % (SHELL_PREFIX, SHELL_CMD)) return if cmd_send_to_buffer == 'new': weechat.prnt(buffer, '-->\t%s%s$ %s%s' % (weechat.color('chat_buffer'), os.getcwd(), weechat.color('reset'), command)) weechat.prnt(buffer, '') args = command.split(' ') if args[0] == 'cd': shell_chdir(buffer, ' '.join(args[1:])) elif args[0] == 'getenv': shell_getenv (buffer, ' '.join(args[1:])) elif args[0] == 'setenv': shell_setenv (buffer, ' '.join(args[1:])) elif args[0] == 'unsetenv': shell_unsetenv (buffer, ' '.join(args[1:])) else: shell_init() cmd_command = command cmd_start_time = datetime.datetime.now() cmd_buffer = buffer cmd_hook_process = weechat.hook_process(command, cmd_timeout * 1000, 'shell_process_cb', '')
def spotify_print_cb(data, buffer, time, tags, displayed, highlight, prefix, message): global spotify_hook_process, buffer_name msg_buffer_name = get_buffer_name(buffer) # Skip ignored buffers found = False for active_buffer in weechat.config_get_plugin('buffers').split(','): if active_buffer.lower() == msg_buffer_name.lower(): found = True buffer_name = msg_buffer_name break if not found: return weechat.WEECHAT_RC_OK for type, spotify_id in get_spotify_ids(message): url = '%s?uri=spotify:%s:%s' %(gateway, type, spotify_id) if spotify_hook_process != "": weechat.unhook(spotify_hook_process) spotify_hook_process = "" python2_bin = weechat.info_get("python2_bin", "") or "python" spotify_hook_process = weechat.hook_process( python2_bin + " -c \"import urllib2; print urllib2.urlopen('" + url + "').read()\"", 30 * 1000, "spotify_process_cb", "") return weechat.WEECHAT_RC_OK
def launch_daemon(*_): if len(options.get('number', '')) > 0: init_socket() pid_path = '%s/signal.pid' % weechat.info_get("weechat_dir", "") sock_path = '%s/signal.sock' % weechat.info_get("weechat_dir", "") daemon_command = [ 'python', daemon_path, sock_path, pid_path, options.get('number'), options.get('signal_cli_command') ] if options.get('debug', '') != '': daemon_command.append(options.get('debug', '')) logger.debug("Preparing to launch daemon with comand %s" % " ".join(daemon_command)) weechat.hook_process(" ".join(daemon_command), 1000, "daemon_cb", "") return weechat.WEECHAT_RC_OK
def wg_update_cache(): """ Download list of scripts and update local cache. """ global wg_config_option, wg_hook_process, wg_stdout # get data from website, via hook_process if wg_hook_process["update"] != "": weechat.unhook(wg_hook_process["update"]) wg_hook_process["update"] = "" weechat.prnt("", "%s: downloading list of scripts..." % SCRIPT_NAME) wg_stdout["update"] = "" wg_config_create_dir() url = weechat.config_string(wg_config_option["scripts_url"]) filename = wg_config_get_cache_filename() python2_bin = weechat.info_get("python2_bin", "") or "python" wg_hook_process["update"] = weechat.hook_process( python2_bin + " -c \"import urllib, urllib2\n" "req = urllib2.Request('" + url + "')\n" "try:\n" " response = urllib2.urlopen(req)\n" " file = open('" + filename + "', 'w')\n" " file.write(response.read())\n" " response.close()\n" " file.close()\n" "except urllib2.URLError, e:\n" " print 'error:%s' % e.code\n" "\"", TIMEOUT_UPDATE, "wg_process_update_cb", "")
def wg_update_cache(): """ Download list of scripts and update local cache. """ global wg_config_option, wg_hook_process, wg_stdout # get data from website, via hook_process if wg_hook_process["update"] != "": weechat.unhook(wg_hook_process["update"]) wg_hook_process["update"] = "" weechat.prnt("", "%s: downloading list of scripts..." % SCRIPT_NAME) wg_stdout["update"] = "" wg_config_create_dir() url = weechat.config_string(wg_config_option["scripts_url"]) filename = wg_config_get_cache_filename() wg_hook_process["update"] = weechat.hook_process( "python -c \"import urllib, urllib2\n" "req = urllib2.Request('" + url + "')\n" "try:\n" " response = urllib2.urlopen(req)\n" " file = open('" + filename + "', 'w')\n" " file.write(response.read())\n" " response.close()\n" " file.close()\n" "except urllib2.URLError, e:\n" " print 'error:%s' % e.code\n" "\"", TIMEOUT_UPDATE, "wg_process_update_cb", "")
def setup_timeline(timelined, followed=False, search=False): """Sets up the main timeline window.""" global hooks global user global tlid global buffers if not search: name = "timeline" title = "%s's timeline" % user.screen_name prefix = "__TIMELINE" search = False buf_cb = "tweet_cb" else: name = search title = "Twitter search for %s" % search prefix = md5(search).hexdigest() buf_cb = "tweet_cb" buf = wc.buffer_new(name, buf_cb, "", "stop_timelined", prefix) # Some naming wc.buffer_set(buf, "title", title) # We want mentions to highlight. wc.buffer_set(buf, "highlight_words", user.screen_name) if followed: # We want a nicklist to hold everyone we follow. wc.buffer_set(buf, "nicklist", "1") add_to_nicklist(buf, user.screen_name) for screen_name in followed: add_to_nicklist(buf, screen_name) storage_dir = wc.config_get_plugin("storage_dir") command = timelined + " " + storage_dir if search: command += " '%s'" % search timelinestream_hook = wc.hook_process( command, 0, "timelined_cb", prefix) strkey = prefix + "STREAM" hooks[strkey] = timelinestream_hook # Check if there are new timeline entries every second. timelinedisplay_hook = wc.hook_timer(1 * 1000, 60, 0, "display_cb", prefix) diskey = prefix + "DISPLAY" hooks[diskey] = timelinedisplay_hook if search: wc.buffer_set(buf, "display", "1") buffers[prefix] = buf hooks['signal'] = wc.hook_signal("input_text_changed", "timeline_prompt_cb", "") if prefix is "__TIMELINE": tlid[prefix] = "timelined" else: tlid[prefix] = prefix
def show_notification(chan, message): AIRGRAM_KEY = weechat.config_get_plugin("key") AIRGRAM_SECRET = weechat.config_get_plugin("secret") if AIRGRAM_KEY != "" and AIRGRAM_SECRET != "": url = "https://api.airgramapp.com/1/broadcast" opt_dict = { "msg": chan + ":" + message } opt = urllib.urlencode(opt_dict) basic = "Basic %s" % ":".join([AIRGRAM_KEY, AIRGRAM_SECRET]).encode("base64").strip() python2_bin = weechat.info_get("python2_bin", "") or "python" weechat.hook_process( python2_bin + " -c \"import urllib2\n" "req = urllib2.Request('" + url + "', '" + opt + "')\n" "req.add_header('Authorization', '" + basic + "')\n" "res = urllib2.urlopen(req)\n\"", 30 * 1000, "", "")
def nicklist_download(url=None): global nicklist_data, nicklist f = os.path.join(hipchat_dir(), 'nicks.json') if os.path.exists(f): with open(f) as f: nicklist = json.load(f) update_all_fullnames() if nicklist is None: nicklist = {} if not url: url = 'https://api.hipchat.com/v2/user?max-results=1000' weechat.hook_process('url:%s&auth_token=%s' % (url, get_token()), 30000, 'nicklist_download_cb', '')
def whatismyip(data, buffer, args): global process_output url = 'http://automation.whatismyip.com/n09230945.asp' process_output = '' url_hook_process = weechat.hook_process("url:%s" % url, 30 * 1000, "process_complete", "") return weechat.WEECHAT_RC_OK