def screen_away_timer_cb(buffer, args): '''Check if screen is attached, update awayness''' global AWAY, SOCK, CONNECTED_RELAY set_away = w.config_string_to_boolean(w.config_get_plugin('set_away')) check_relays = not w.config_string_to_boolean( w.config_get_plugin('ignore_relays')) suffix = w.config_get_plugin('away_suffix') attached = os.access(SOCK, os.X_OK) # X bit indicates attached # Check wether a client is connected on relay or not CONNECTED_RELAY = False if check_relays: infolist = w.infolist_get('relay', '', '') if infolist: while w.infolist_next(infolist): status = w.infolist_string(infolist, 'status_string') if status == 'connected': CONNECTED_RELAY = True break w.infolist_free(infolist) if (attached and AWAY) or (check_relays and CONNECTED_RELAY and not attached and AWAY): if not w.config_string_to_boolean(w.config_get_plugin('no_output')): w.prnt('', '%s: Screen attached. Clearing away status' % SCRIPT_NAME) for server, nick in get_servers(): if set_away: w.command(server, "/away") if suffix and nick.endswith(suffix): nick = nick[:-len(suffix)] w.command(server, "/nick %s" % nick) AWAY = False if w.config_get_plugin("command_on_attach"): for cmd in w.config_get_plugin("command_on_attach").split(";"): w.command("", cmd) elif not attached and not AWAY: if not CONNECTED_RELAY: if not w.config_string_to_boolean( w.config_get_plugin('no_output')): w.prnt( '', '%s: Screen detached. Setting away status' % SCRIPT_NAME) for server, nick in get_servers(): if suffix and not nick.endswith(suffix): w.command(server, "/nick %s%s" % (nick, suffix)) if set_away: w.command( server, "/away %s %s" % (w.config_get_plugin('message'), time.strftime(w.config_get_plugin('time_format')))) AWAY = True if w.config_get_plugin("command_on_detach"): for cmd in w.config_get_plugin("command_on_detach").split(";"): w.command("", cmd) return w.WEECHAT_RC_OK
def display_cb(data, remaining_calls): """ Displays the timeline """ global db global twitter global buffers global tlid default_color = wc.color("default") show_in_cur = "Off" cur_away = "On" cur_detached = "On" valid_buffers = [] valid_buffers.append(buffers[data]) current_buffer = wc.current_buffer() show_in_cur = wc.config_string_to_boolean(wc.config_get_plugin("show_in_current")) cur_away = wc.config_string_to_boolean(wc.config_get_plugin("current_while_away")) cur_detached = wc.config_string_to_boolean(wc.config_get_plugin("current_while_detached")) away = wc.buffer_get_string(current_buffer, 'localvar_away') # I have NO idea why is doesn't work here but this does so... what? if ( "__TIMELINE" in data and show_in_cur and buffers[data] != current_buffer and (not away or cur_away) and (is_attached() or cur_detached) ): valid_buffers.append(current_buffer) status_dir = os.path.join(wc.config_get_plugin("storage_dir"), tlid[data]) try: for tweet in StatusMonitor(status_dir, twitter.api): tweep_color = wc.color(wc.config_get_plugin("nick_color")) for buf in valid_buffers: screen_name = tweep_color + tweet.screen_name text = tweet.txt if buf is current_buffer: cur_color = wc.color(wc.config_get_plugin("current_color")) screen_name = cur_color + "@" + screen_name text = cur_color + text mention_color = wc.color(wc.config_get_plugin("mention_color")) hash_color = wc.color(wc.config_get_plugin("hash_color")) text = re.sub(r'(?P<name>@\w+)', r"{}\1{}".format(mention_color,default_color), text) text = re.sub(r'(?P<hash>#\w+)', r"{}\1{}".format(hash_color,default_color), text) output = u"%s\t%s" % \ (screen_name, text) if tweet.is_retweet: output += " (RT by @%s)" % tweet.rtscreen_name output += "\n[#STATUSID: %s]" % tweet.id print_to_buffer(buf, output) db.set_last_tid(tweet.screen_name, tweet.id) except TwitterError as error: print_error(error) return wc.WEECHAT_RC_OK
def screen_away_timer_cb(buffer, args): '''Check if screen is attached, update awayness''' global AWAY, SOCK, CONNECTED_RELAY def mosh_state(): try: with open(MOSH_STATE) as f: return f.read() except IOError: return set_away = w.config_string_to_boolean(w.config_get_plugin('set_away')) check_relays = not w.config_string_to_boolean(w.config_get_plugin('ignore_relays')) suffix = w.config_get_plugin('away_suffix') attached = os.access(SOCK, os.X_OK) # X bit indicates attached mosh_state = mosh_state() if attached and mosh_state is not None: attached = mosh_state == 'connected' # Check wether a client is connected on relay or not CONNECTED_RELAY = False if check_relays: infolist = w.infolist_get('relay', '', '') if infolist: while w.infolist_next(infolist): status = w.infolist_string(infolist, 'status_string') if status == 'connected': CONNECTED_RELAY = True break w.infolist_free(infolist) if (attached and AWAY) or (check_relays and CONNECTED_RELAY and not attached and AWAY): w.prnt('', '%s: Screen attached. Clearing away status' % SCRIPT_NAME) for server, nick in get_servers(): if set_away: w.command(server, "/away") if suffix and nick.endswith(suffix): nick = nick[:-len(suffix)] w.command(server, "/nick %s" % nick) AWAY = False for cmd in w.config_get_plugin("command_on_attach").split(";"): w.command("", cmd) elif not attached and not AWAY: if not CONNECTED_RELAY: w.prnt('', '%s: Screen detached. Setting away status' % SCRIPT_NAME) for server, nick in get_servers(): if suffix and not nick.endswith(suffix): w.command(server, "/nick %s%s" % (nick, suffix)); if set_away: w.command(server, "/away %s %s" % (w.config_get_plugin('message'), time.strftime(w.config_get_plugin('time_format')))) AWAY = True for cmd in w.config_get_plugin("command_on_detach").split(";"): w.command("", cmd) return w.WEECHAT_RC_OK
def screen_away_timer_cb(buffer, args): '''Check if screen is attached and update awayness.''' global AWAY, SOCK, CONNECTED_RELAY set_away = w.config_string_to_boolean(w.config_get_plugin('set_away')) check_relays = not w.config_string_to_boolean( w.config_get_plugin('ignore_relays')) suffix = w.config_get_plugin('away_suffix') attached = os.access(SOCK, os.X_OK) # X bit indicates attached. # Check wether a client is connected on relay or not. CONNECTED_RELAY = False if check_relays: infolist = w.infolist_get('relay', '', '') if infolist: while w.infolist_next(infolist): status = w.infolist_string(infolist, 'status_string') if status == 'connected': CONNECTED_RELAY = True break w.infolist_free(infolist) if ((attached and AWAY) or (check_relays and CONNECTED_RELAY and not attached and AWAY)): if not w.config_string_to_boolean(w.config_get_plugin('no_output')): w.prnt('', '{}: Screen attached. Clearing away status'.format( SCRIPT_NAME)) for server, nick in get_servers(): if set_away: w.command(server, '/away') if suffix and nick.endswith(suffix): nick = nick[:-len(suffix)] w.command(server, '/nick {}'.format(nick)) AWAY = False if w.config_get_plugin('command_on_attach'): for cmd in w.config_get_plugin('command_on_attach').split(';'): w.command('', cmd) elif not attached and not AWAY: if not CONNECTED_RELAY: if (not w.config_string_to_boolean( w.config_get_plugin('no_output'))): w.prnt('', '{}: Screen detached. Setting away status'.format( SCRIPT_NAME)) for server, nick in get_servers(): if suffix and not nick.endswith(suffix): w.command(server, '/nick {}{}'.format(nick, suffix)) if set_away: w.command(server, '/away {} {}'.format( w.config_get_plugin('message'), time.strftime(w.config_get_plugin('time_format')))) AWAY = True if w.config_get_plugin('command_on_detach'): for cmd in w.config_get_plugin('command_on_detach').split(';'): w.command('', cmd) return w.WEECHAT_RC_OK
def priv_msg_cb(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight, prefix, message): """Sends highlighted message to be printed on notification""" if not w.config_string_to_boolean(w.config_get_plugin('activated')): _debug('Plugin not activated. Not sending.') return w.WEECHAT_RC_OK if (w.config_string_to_boolean(w.config_get_plugin('smart_notification')) and bufferp == w.current_buffer()): _debug( '"smart_notification" option set but you are on this buffer already. Not sending.' ) return w.WEECHAT_RC_OK if (w.config_string_to_boolean(w.config_get_plugin('only_away')) and not w.buffer_get_string(bufferp, 'localvar_away')): _debug('"only_away" option set but you are not away. Not sending.') return w.WEECHAT_RC_OK ret = None notif_body = u"%s%s%s%s" % ( w.config_get_plugin('nick_separator_left').decode('utf-8'), prefix.decode('utf-8'), w.config_get_plugin('nick_separator_right').decode('utf-8'), message.decode('utf-8')) # Check that it's in a "/q" buffer and that I'm not the one writing the msg is_pm = w.buffer_get_string(bufferp, "localvar_type") == "private" is_notify_private = re.search(r'(^|,)notify_private(,|$)', tagsn) is not None # PM (query) if (is_pm and is_notify_private and w.config_string_to_boolean( w.config_get_plugin('notify_priv_msg'))): ret = send_notification("IRC private message", notif_body, int(w.config_get_plugin("emergency_priv_msg"))) _debug("Message sent: %s. Return: %s." % (notif_body, ret)) # Highlight (your nick is quoted) elif (ishilight == "1" and w.config_string_to_boolean( w.config_get_plugin('notify_hilights'))): bufname = (w.buffer_get_string(bufferp, "short_name") or w.buffer_get_string(bufferp, "name")) ret = send_notification(bufname.decode('utf-8'), notif_body, int(w.config_get_plugin("emergency_hilights"))) _debug("Message sent: %s. Return: %s." % (notif_body, ret)) if ret is not None: _debug(str(ret)) return w.WEECHAT_RC_OK
def priv_msg_cb(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight, prefix, message): """Sends highlighted message to be printed on notification""" if not w.config_string_to_boolean(w.config_get_plugin('activated')): _debug('Plugin not activated. Not sending.') return w.WEECHAT_RC_OK if (w.config_string_to_boolean(w.config_get_plugin('smart_notification')) and bufferp == w.current_buffer()): _debug('"smart_notification" option set but you are on this buffer already. Not sending.') return w.WEECHAT_RC_OK if (w.config_string_to_boolean(w.config_get_plugin('only_away')) and not w.buffer_get_string(bufferp, 'localvar_away')): _debug('"only_away" option set but you are not away. Not sending.') return w.WEECHAT_RC_OK ret = None notif_body = u"%s%s%s%s" % ( w.config_get_plugin('nick_separator_left').decode('utf-8'), prefix.decode('utf-8'), w.config_get_plugin('nick_separator_right').decode('utf-8'), message.decode('utf-8')) # Check that it's in a "/q" buffer and that I'm not the one writing the msg is_pm = w.buffer_get_string(bufferp, "localvar_type") == "private" is_notify_private = re.search(r'(^|,)notify_private(,|$)', tagsn) is not None # PM (query) if (is_pm and is_notify_private and w.config_string_to_boolean(w.config_get_plugin('notify_priv_msg'))): ret = send_notification("IRC private message", notif_body, int(w.config_get_plugin("emergency_priv_msg"))) _debug("Message sent: %s. Return: %s." % (notif_body, ret)) # Highlight (your nick is quoted) elif (ishilight == "1" and w.config_string_to_boolean(w.config_get_plugin('notify_hilights'))): bufname = (w.buffer_get_string(bufferp, "short_name") or w.buffer_get_string(bufferp, "name")) ret = send_notification(bufname.decode('utf-8'), notif_body, int(w.config_get_plugin("emergency_hilights"))) _debug("Message sent: %s. Return: %s." % (notif_body, ret)) if ret is not None: _debug(str(ret)) return w.WEECHAT_RC_OK
def conversation_cb(data, buffer, args): """ Follows the reply trail until the original was found. NOTE: This might block for a while. """ global twitter conversation = [] reply_id = args # Loop as long as there was a reply_id. while reply_id: try: conversation.append(twitter.get_tweet(reply_id)) reply_id = conversation[-1].in_reply_to_status_id except TwitterError as error: print_error(error) break if conversation: # Reverse the conversation to get the oldest first. conversation.reverse() # Now display the conversation. print_to_current("%s-------------------" % wc.color("magenta")) for tweet in conversation: nick_color = wc.info_get("irc_nick_color", tweet.screen_name) screen_name = nick_color + tweet.screen_name expand_urls = wc.config_string_to_boolean(wc.config_get_plugin("expand_urls")) text = tweet.txt_unescaped if expand_urls: text = tweet.txt output = "%s\t%s" % (screen_name, text) if tweet.is_retweet: output += " (RT by @%s)" % tweet.rtscreen_name output += "\n[#STATUSID: %s]" % tweet.id print_to_current(output) print_to_current("%s-------------------" % wc.color("magenta")) return wc.WEECHAT_RC_OK
def show_favorites_cb(data, buffer, args): """ Show all the tweets that are favourited by the user. """ global twitter try: favs = twitter.get_favorites() except TwitterError as error: print_error(error) return wc.WEECHAT_RC_OK if favs: print_to_current("%sFAVOURITES\t%s-------------------" % (wc.color("yellow"), wc.color("magenta"))) for fav in favs: nick_color = wc.info_get("irc_nick_color", fav.screen_name) screen_name = nick_color + fav.screen_name expand_urls = wc.config_string_to_boolean(wc.config_get_plugin("expand_urls")) text = fav.text_unescaped if expand_urls: text = fav.text output = "%s\t%s" % (screen_name, text) if fav.is_retweet: output += " (RT by @%s)" % fav.rtscreen_name output += "\n[#STATUSID: %s]" % fav.id print_to_current(output) print_to_current("%s-------------------" % wc.color("magenta")) return wc.WEECHAT_RC_OK
def run_notify(mtype,urgency,icon,time,nick,chan,message): data = str(mtype) + "\n" data += str(urgency) + "\n" data += str(icon) + "\n" data += str(time) + "\n" #time to display TODO data += str(nick) + "\n" data += str(chan) + "\n" data += str(message) transport = w.config_get_plugin('transport') command = w.config_get_plugin('notify_command'), host = w.config_get_plugin('host') try: if command: p = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) (output, _) = p.communicate(data) if p.returncode != 0: raise Exception("Notify command failed with return code " + str(p.returncode) + "\r\n" + output) else: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, int(w.config_get_plugin('port')))) s.send(str(data)) s.close() except Exception as e: if w.config_string_to_boolean(w.config_get_plugin("display_errors")): w.prnt("", "Could not send notification: %s" % str(e)) w.prnt("", "To hide errors, run: /set plugins.var.python.remote-notify.display_errors off")
def config_change(pointer, name, value): option = name.replace('plugins.var.python.' + SCRIPT_NAME + '.', '') if option == 'prefix_nicks' or option == 'debug' or option == 'ssl_verify' or option == 'notice_notify_block': value = weechat.config_string_to_boolean(value) if option == 'debug': if value == 0: curlopt['verbose'] = "0" if value == 1: curlopt['verbose'] = "1" if option == 'ssl_verify': if value == 0: curlopt['ssl_verifypeer'] = "0" curlopt['ssl_verifyhost'] = "0" if value == 1: curlopt['ssl_verifypeer'] = "1" curlopt['ssl_verifyhost'] = "2" if option == 'client_id': for x in curlopt['httpheader'].split('\n'): if x.startswith('Authorization: Bearer'): curlopt['httpheader'] = x + '\n' + "Client-ID: " + value break if option == 'token': for x in curlopt['httpheader'].split('\n'): if x.startswith('Client-ID:'): curlopt[ 'httpheader'] = x + '\n' + "Authorization: Bearer " + value break OPTIONS[option] = value return weechat.WEECHAT_RC_OK
def send_push(title, body): global last_notification interval = w.config_get_plugin("min_notify_interval") if interval is not None and interval != "" and int(interval) != 0: interval = int(interval) earliest_notification = last_notification + int(interval) if last_notification is not None and time.time( ) <= earliest_notification: debug("Too soon since last notification, skipping") return w.WEECHAT_RC_OK last_notification = time.time() # check to see if the relay is connected, ignore if so check_relays = w.config_string_to_boolean( w.config_get_plugin('ignore_on_relay')) CONNECTED_RELAY = False if check_relays: infolist = w.infolist_get('relay', '', '') if infolist: while w.infolist_next(infolist): status = w.infolist_string(infolist, 'status_string') if status == 'connected': CONNECTED_RELAY = True break w.infolist_free(infolist) if CONNECTED_RELAY is True: # we have a relay conected, don't notify debug("Relay is connected, not sending push.") return w.WEECHAT_RC_OK debug("Sending push. Title: [%s], body: [%s]" % (title, body)) apikey = w.string_eval_expression(w.config_get_plugin("api_key"), {}, {}, {}) apiurl = "https://%[email protected]/v2/pushes" % (apikey) timeout = 20000 # FIXME - actually use config if len(title) is not 0 or len(body) is not 0: deviceiden = w.config_get_plugin("device_iden") if deviceiden == "all": payload = urllib.parse.urlencode({ 'type': 'note', 'title': title, 'body': body }) else: payload = urllib.parse.urlencode({ 'type': 'note', 'title': title, 'body': body, 'device_iden': deviceiden }) w.hook_process_hashtable("url:" + apiurl, { "postfields": payload, "header": "1" }, timeout, "process_pushbullet_cb", "")
def layout_apply_cb(data, buffer, command): if weechat.config_string_to_boolean( weechat.config_get_plugin("layout_apply")): m = LAYOUT_APPLY_RE.match(command) if m: layout_name = m.group(1) or "default" hdata_layout = weechat.hdata_get("layout") layouts = weechat.hdata_get_list(hdata_layout, "gui_layouts") layout = weechat.hdata_search(hdata_layout, layouts, "${layout.name} == " + layout_name, 1) if layout: hdata_layout_buffer = weechat.hdata_get("layout_buffer") layout_buffer = weechat.hdata_pointer(hdata_layout, layout, "layout_buffers") while layout_buffer: plugin_name = weechat.hdata_string(hdata_layout_buffer, layout_buffer, "plugin_name") buffer_name = weechat.hdata_string(hdata_layout_buffer, layout_buffer, "buffer_name") full_name = "{}.{}".format(plugin_name, buffer_name) buffer = weechat.buffer_search("==", full_name) if not buffer: buffer_open_full_name(full_name, noswitch=True) layout_buffer = weechat.hdata_move(hdata_layout_buffer, layout_buffer, 1) return weechat.WEECHAT_RC_OK
def channel_block(server, channel): fail = None config_cycle = lambda opt: weechat.config_string_to_boolean(weechat.config_get_plugin("cycle_%s" % opt)) channels = weechat.infolist_get("irc_channel", "", "%s,%s" % (server, channel)) if weechat.infolist_next(channels): modes = weechat.infolist_string(channels, "modes") if " " in modes: modes, modes_args = modes.split(" ", 1) if not config_cycle("key") and weechat.infolist_string(channels, "key") != "": fail = "cycle_key" elif not config_cycle("invite") and "i" in modes: fail = "cycle_invite" elif not config_cycle("detach"): fail = "cycle_detach" weechat.infolist_free(channels) if fail: weechat.prnt("", "%s: won't automatically cycle %s.%s: %s" % (SCRIPT_NAME, server, channel, fail)) else: servers[server]["channels"].append(channel) buffer = weechat.buffer_search("irc", server) weechat.command(buffer, "/part %s" % channel) weechat.command(buffer, "/nick %s" % servers[server]["nick"])
def channel_block(server, channel): fail = None config_cycle = lambda opt: weechat.config_string_to_boolean( weechat.config_get_plugin("cycle_%s" % opt)) channels = weechat.infolist_get("irc_channel", "", "%s,%s" % (server, channel)) if weechat.infolist_next(channels): modes = weechat.infolist_string(channels, "modes") if " " in modes: modes, modes_args = modes.split(" ", 1) if not config_cycle("key") and weechat.infolist_string( channels, "key") != "": fail = "cycle_key" elif not config_cycle("invite") and "i" in modes: fail = "cycle_invite" elif not config_cycle("detach"): fail = "cycle_detach" weechat.infolist_free(channels) if fail: weechat.prnt( "", "%s: won't automatically cycle %s.%s: %s" % (SCRIPT_NAME, server, channel, fail)) else: servers[server]["channels"].append(channel) buffer = weechat.buffer_search("irc", server) weechat.command(buffer, "/part %s" % channel) weechat.command(buffer, "/nick %s" % servers[server]["nick"])
def show_favorites_cb(data, buffer, args): """ Show all the tweets that are favourited by the user. """ global twitter try: favs = twitter.get_favorites() except TwitterError as error: print_error(error) return wc.WEECHAT_RC_OK if favs: print_to_current("%sFAVOURITES\t%s-------------------" % (wc.color("yellow"), wc.color("magenta"))) for fav in favs: nick_color = wc.info_get("irc_nick_color", fav.screen_name) screen_name = nick_color + fav.screen_name expand_urls = wc.config_string_to_boolean( wc.config_get_plugin("expand_urls")) text = fav.text_unescaped if expand_urls: text = fav.text output = "%s\t%s" % (screen_name, text) if fav.is_retweet: output += " (RT by @%s)" % fav.rtscreen_name output += "\n[#STATUSID: %s]" % fav.id print_to_current(output) print_to_current("%s-------------------" % wc.color("magenta")) return wc.WEECHAT_RC_OK
def config_setup(): for option,value in OPTIONS.items(): weechat.config_set_desc_plugin(option, '%s' % value[1]) if not weechat.config_is_set_plugin(option): weechat.config_set_plugin(option, value[0]) OPTIONS[option] = value[0] else: if option == 'prefix_nicks' or option == 'debug' or option == 'ssl_verify' or option == 'notice_notify_block': OPTIONS[option] = weechat.config_string_to_boolean( weechat.config_get_plugin(option)) else: OPTIONS[option] = weechat.config_get_plugin(option) if option == 'debug': if value == 0: curlopt['verbose'] = "0" else: curlopt['verbose'] = "1" if option == 'ssl_verify': if value == 0: curlopt['ssl_verifypeer'] = "0" curlopt['ssl_verifyhost'] = "0" else: curlopt['ssl_verifypeer'] = "1" curlopt['ssl_verifyhost'] = "2" if option == 'client_id': curlopt['httpheader'] = "Client-ID: " + value[0]
def screen_away_timer_cb(buffer, args): """Check if screen is attached, update awayness""" global AWAY, SOCK, CONNECTED_RELAY set_away = w.config_string_to_boolean(w.config_get_plugin("set_away")) check_relays = not w.config_string_to_boolean(w.config_get_plugin("ignore_relays")) suffix = w.config_get_plugin("away_suffix") attached = os.access(SOCK, os.X_OK) # X bit indicates attached # Check wether a client is connected on relay or not CONNECTED_RELAY = False if check_relays: infolist = w.infolist_get("relay", "", "") if infolist: while w.infolist_next(infolist): status = w.infolist_string(infolist, "status_string") if status == "connected": CONNECTED_RELAY = True break w.infolist_free(infolist) if (attached and AWAY) or (check_relays and CONNECTED_RELAY and not attached and AWAY): w.prnt("", "%s: Screen attached. Clearing away status" % SCRIPT_NAME) for server, nick in get_servers(): if set_away: w.command(server, "/away") if suffix and nick.endswith(suffix): nick = nick[: -len(suffix)] w.command(server, "/nick %s" % nick) AWAY = False for cmd in w.config_get_plugin("command_on_attach").split(";"): w.command("", cmd) elif not attached and not AWAY: if not CONNECTED_RELAY: w.prnt("", "%s: Screen detached. Setting away status" % SCRIPT_NAME) for server, nick in get_servers(): if suffix and not nick.endswith(suffix): w.command(server, "/nick %s%s" % (nick, suffix)) if set_away: w.command(server, "/away %s" % w.config_get_plugin("message")) AWAY = True for cmd in w.config_get_plugin("command_on_detach").split(";"): w.command("", cmd) return w.WEECHAT_RC_OK
def send_notification(chan, message, priority): global p if w.config_string_to_boolean(w.config_get_plugin('use_push_if_possible')): # So far, the length is hardcoded in pynma.py... if len(chan) + len(message) < 1021: chan = "%s - %s" % (chan, message) message = "" return p.push("[IRC]", chan, message, '', priority, batch_mode=False)
def get_matching_buffers(input): """ Return list with buffers matching user input """ global buffers_pos list = [] if len(input) == 0: buffers_pos = 0 input = input.lower() infolist = weechat.infolist_get("buffer", "", "") while weechat.infolist_next(infolist): if weechat.config_get_plugin("short_name") == "on": name = weechat.infolist_string(infolist, "short_name") else: name = weechat.infolist_string(infolist, "name") if weechat.config_get_plugin( "use_core_instead_weechat") == "on" and name == "weechat": name = "core" number = weechat.infolist_integer(infolist, "number") full_name = weechat.infolist_string(infolist, "full_name") if not full_name: full_name = "%s.%s" % (weechat.infolist_string( infolist, "plugin_name"), weechat.infolist_string(infolist, "name")) pointer = weechat.infolist_pointer(infolist, "pointer") matching = name.lower().find(input) >= 0 if not matching and input[-1] == ' ': matching = name.lower().endswith(input.strip()) if not matching and input.isdigit(): matching = str(number).startswith(input) if len(input) == 0 or matching: list.append({ "number": number, "name": name, "full_name": full_name, "pointer": pointer }) if len(input) == 0 and pointer == weechat.current_buffer(): buffers_pos = len(list) - 1 weechat.infolist_free(infolist) if not weechat.config_string_to_boolean( weechat.config_get_plugin('sort_by_activity')): return list # sort buffers like in hotlist. hotlist = [] infolist = weechat.infolist_get("hotlist", "", "") while weechat.infolist_next(infolist): hotlist.append(weechat.infolist_pointer(infolist, "buffer_pointer")) weechat.infolist_free(infolist) last_index = len(hotlist) def priority(b): try: return hotlist.index(b["pointer"]) except ValueError: # not in hotlist, always last. return last_index return sorted(list, key=priority)
def nma_cmd_cb(data, buffer, args): bool_arg = w.config_string_to_boolean(args) status = "%sactivated" % ("" if bool_arg else "de") ret = w.config_set_plugin('activated', args) if ret == w.WEECHAT_CONFIG_OPTION_SET_OK_SAME_VALUE: w.prnt("", "...NMA was already %s" % status) elif ret == w.WEECHAT_CONFIG_OPTION_SET_ERROR: w.prnt("", "Error while setting the config.") return w.WEECHAT_RC_ERROR else: w.prnt("", "Notify My Android notifications %s." % status) return w.WEECHAT_RC_OK
def config_setup(): for option, value in OPTIONS.items(): weechat.config_set_desc_plugin(option, '%s' % value[1]) if not weechat.config_is_set_plugin(option): weechat.config_set_plugin(option, value[0]) OPTIONS[option] = value[0] else: if option == 'prefix_nicks': OPTIONS[option] = weechat.config_string_to_boolean( weechat.config_get_plugin(option)) else: OPTIONS[option] = weechat.config_get_plugin(option)
def config_setup(): for option,value in OPTIONS.items(): weechat.config_set_desc_plugin(option, '%s' % value[1]) if not weechat.config_is_set_plugin(option): weechat.config_set_plugin(option, value[0]) OPTIONS[option] = value[0] else: if option == 'prefix_nicks' or option == 'debug': OPTIONS[option] = weechat.config_string_to_boolean( weechat.config_get_plugin(option)) else: OPTIONS[option] = weechat.config_get_plugin(option)
def hook_modifiers(): """Update modifier hooks to match settings.""" # remove existing modifier hooks global hooks for hook in hooks: weechat.unhook(hook) hooks = [] # add hooks according to settings input_option = weechat.config_get_plugin("input") if weechat.config_string_to_boolean(input_option): hooks.append(weechat.hook_modifier("input_text_display", "modifier_cb", "")) send_option = weechat.config_get_plugin("send") if weechat.config_string_to_boolean(send_option): hooks.append(weechat.hook_modifier("input_text_for_buffer", "modifier_cb", "")) buffer_option = weechat.config_get_plugin("buffer") if weechat.config_string_to_boolean(buffer_option): hooks.append(weechat.hook_modifier("weechat_print", "modifier_cb", ""))
def join(server, channel): key = None if w.config_string_to_boolean(w.config_get_plugin('autojoin_key')): autojoin = w.config_string(w.config_get('irc.server.%s.autojoin' % server)).split(' ', 1) if len(autojoin) > 1: # any keys specified autojoin_keys = dict(zip(autojoin[0].split(','), autojoin[1].split(','))) key = autojoin_keys.get(channel) # defaults to None when not set if key: w.command('', '/quote -server %s JOIN %s %s' % (server, channel, key)) else: w.command('', '/quote -server %s JOIN %s' % (server, channel))
def input_search_cb(data, signal, buffer): """ Handle "input_search" signal. """ if buffer_searching(buffer) and buffer_filtering(buffer) is None: enable = weechat.config_string_to_boolean(weechat.config_get_plugin("enable")) weechat.buffer_set(buffer, "localvar_set_%s" % SCRIPT_LOCALVAR, "1" if enable else "0") weechat.buffer_set(buffer, "localvar_set_%s_warn" % SCRIPT_LOCALVAR, "0") elif not buffer_searching(buffer): weechat.buffer_set(buffer, "localvar_del_%s" % SCRIPT_LOCALVAR, "") weechat.buffer_set(buffer, "localvar_del_%s_warn" % SCRIPT_LOCALVAR, "") buffer_update(buffer) return weechat.WEECHAT_RC_OK
def relay_check(): check_relays = w.config_string_to_boolean( w.config_get_plugin('ignore_on_relay')) if not check_relays: return False infolist = w.infolist_get('relay', '', '') if infolist: while w.infolist_next(infolist): status = w.infolist_string(infolist, 'status_string') if status == 'connected': return True w.infolist_free(infolist) return False
def tweet_share_cb(data, buffer, args): """Share tweet with current IRC channel.""" global twitter try: tweet = twitter.get_tweet(args) except TwitterError as error: print_error(error) return wc.WEECHAT_RC_OK expand_urls = wc.config_string_to_boolean(wc.config_get_plugin("expand_urls")) text = tweet.txt_unescaped if expand_urls: text = tweet.txt message = '<@%s> %s [%s]' % \ (tweet.screen_name, text, tweet.url) wc.command(wc.current_buffer(), '/say %s' % message) return wc.WEECHAT_RC_OK
def send_notification(chan, message, priority): p = nma_get_instance() if not(p): w.prnt("", "[nma] - Problem with NMA instance. Not sending notification") return None _debug("Sending notif with chan '%s', message '%s' and priority '%s'." % (chan, message, priority)) if w.config_string_to_boolean(w.config_get_plugin('use_push_if_possible')): # So far, the length is hardcoded in pynma.py... if len(chan) + len(message) < 1021: chan = "%s - %s" % (chan, message) message = "" ret = p.push("[IRC]", chan, message, '', priority, batch_mode=False) if ret is not None: _debug("Message sent: %s. Return: %s." % (message, ret))
def get_matching_buffers(input): """ Return list with buffers matching user input """ global buffers_pos list = [] if len(input) == 0: buffers_pos = 0 input = input.lower() infolist = weechat.infolist_get("buffer", "", "") while weechat.infolist_next(infolist): if weechat.config_get_plugin("short_name") == "on": name = weechat.infolist_string(infolist, "short_name") else: name = weechat.infolist_string(infolist, "name") if weechat.config_get_plugin("use_core_instead_weechat") == "on" and name == "weechat": name = "core" number = weechat.infolist_integer(infolist, "number") full_name = weechat.infolist_string(infolist, "full_name") if not full_name: full_name = "%s.%s" % (weechat.infolist_string(infolist, "plugin_name"), weechat.infolist_string(infolist, "name")) pointer = weechat.infolist_pointer(infolist, "pointer") matching = name.lower().find(input) >= 0 if not matching and input[-1] == ' ': matching = name.lower().endswith(input.strip()) if not matching and input.isdigit(): matching = str(number).startswith(input) if len(input) == 0 or matching: list.append({"number": number, "name": name, "full_name": full_name, "pointer": pointer}) if len(input) == 0 and pointer == weechat.current_buffer(): buffers_pos = len(list) - 1 weechat.infolist_free(infolist) if not weechat.config_string_to_boolean(weechat.config_get_plugin('sort_by_activity')): return list # sort buffers like in hotlist. hotlist = [] infolist = weechat.infolist_get("hotlist", "", "") while weechat.infolist_next(infolist): hotlist.append(weechat.infolist_pointer(infolist, "buffer_pointer")) weechat.infolist_free(infolist) last_index = len(hotlist) def priority(b): try: return hotlist.index(b["pointer"]) except ValueError: # not in hotlist, always last. return last_index return sorted(list, key=priority)
def tweet_share_cb(data, buffer, args): """Share tweet with current IRC channel.""" global twitter try: tweet = twitter.get_tweet(args) except TwitterError as error: print_error(error) return wc.WEECHAT_RC_OK expand_urls = wc.config_string_to_boolean( wc.config_get_plugin("expand_urls")) text = tweet.txt_unescaped if expand_urls: text = tweet.txt message = '<@%s> %s [%s]' % \ (tweet.screen_name, text, tweet.url) wc.command(wc.current_buffer(), '/say %s' % message) return wc.WEECHAT_RC_OK
def get_servers(): '''Get the servers that are not away, or were set away by this script.''' ignores = w.config_get_plugin('ignore').split(',') infolist = w.infolist_get('irc_server', '', '') buffers = [] while w.infolist_next(infolist): if (not w.infolist_integer(infolist, 'is_connected') == 1 or w.infolist_string(infolist, 'name') in ignores): continue if (not w.config_string_to_boolean(w.config_get_plugin('set_away')) or not w.infolist_integer(infolist, 'is_away') or w.config_get_plugin('message') in w.infolist_string( infolist, 'away_message')): buffers.append((w.infolist_pointer(infolist, 'buffer'), w.infolist_string(infolist, 'nick'))) w.infolist_free(infolist) return buffers
def nma_cmd_cb(data, buffer, args): if args.strip() == "test": send_notification("This is a weechat nma plugin test", "If you receive that, your configuration is ok", 0) return w.WEECHAT_RC_OK bool_arg = w.config_string_to_boolean(args) status = "%sactivated" % ("" if bool_arg else "de") ret = w.config_set_plugin('activated', args) if ret == w.WEECHAT_CONFIG_OPTION_SET_OK_SAME_VALUE: w.prnt("", "...NMA was already %s" % status) elif ret == w.WEECHAT_CONFIG_OPTION_SET_ERROR: w.prnt("", "Error while setting the config.") return w.WEECHAT_RC_ERROR else: w.prnt("", "Notify My Android notifications %s." % status) return w.WEECHAT_RC_OK
def get_servers(): """Get the servers that are not away, or were set away by this script""" ignores = w.config_get_plugin("ignore").split(",") infolist = w.infolist_get("irc_server", "", "") buffers = [] while w.infolist_next(infolist): if not w.infolist_integer(infolist, "is_connected") == 1 or w.infolist_string(infolist, "name") in ignores: continue if ( not w.config_string_to_boolean(w.config_get_plugin("set_away")) or not w.infolist_integer(infolist, "is_away") or w.infolist_string(infolist, "away_message") == w.config_get_plugin("message") ): buffers.append((w.infolist_pointer(infolist, "buffer"), w.infolist_string(infolist, "nick"))) w.infolist_free(infolist) return buffers
def send_push(title, body): global last_notification interval = w.config_get_plugin("min_notify_interval") if interval is not None and interval != "" and int(interval) != 0: interval = int(interval) earliest_notification = last_notification + int(interval) if last_notification is not None and time.time() <= earliest_notification: debug("Too soon since last notification, skipping") return w.WEECHAT_RC_OK last_notification = time.time() # check to see if the relay is connected, ignore if so check_relays = w.config_string_to_boolean(w.config_get_plugin('ignore_on_relay')) CONNECTED_RELAY = False if check_relays: infolist = w.infolist_get('relay', '', '') if infolist: while w.infolist_next(infolist): status = w.infolist_string(infolist, 'status_string') if status == 'connected': CONNECTED_RELAY = True break w.infolist_free(infolist) if CONNECTED_RELAY is True: # we have a relay conected, don't notify debug("Relay is connected, not sending push.") return w.WEECHAT_RC_OK debug("Sending push. Title: [%s], body: [%s]" % (title, body)) apikey = w.config_get_plugin("api_key") apiurl = "https://%[email protected]/v2/pushes" % (apikey) timeout = 20000 # FIXME - actually use config if len(title) is not 0 or len(body) is not 0: deviceiden = w.config_get_plugin("device_iden") if deviceiden == "all": payload = urllib.urlencode({'type': 'note', 'title': title, 'body': body.encode('utf-8')}) else: payload = urllib.urlencode({'type': 'note', 'title': title, 'body': body.encode('utf-8'), 'device_iden': deviceiden}) w.hook_process_hashtable("url:" + apiurl, {"postfields": payload, "header": "1"}, timeout, "process_pushbullet_cb", "")
def config_change(pointer, name, value): option = name.replace('plugins.var.python.'+SCRIPT_NAME+'.','') if option == 'prefix_nicks' or option == 'debug' or option == 'ssl_verify': value=weechat.config_string_to_boolean(value) if option == 'debug': if value == 0: curlopt['verbose'] = "0" if value == 1: curlopt['verbose'] = "1" if option == 'ssl_verify': if value == 0: curlopt['ssl_verifypeer'] = "0" curlopt['ssl_verifyhost'] = "0" if value == 1: curlopt['ssl_verifypeer'] = "1" curlopt['ssl_verifyhost'] = "2" OPTIONS[option] = value return weechat.WEECHAT_RC_OK
def config_change(pointer, name, value): option = name.replace('plugins.var.python.' + SCRIPT_NAME + '.', '') if option == 'prefix_nicks' or option == 'debug' or option == 'ssl_verify': value = weechat.config_string_to_boolean(value) if option == 'debug': if value == 0: curlopt['verbose'] = "0" if value == 1: curlopt['verbose'] = "1" if option == 'ssl_verify': if value == 0: curlopt['ssl_verifypeer'] = "0" curlopt['ssl_verifyhost'] = "0" if value == 1: curlopt['ssl_verifypeer'] = "1" curlopt['ssl_verifyhost'] = "2" OPTIONS[option] = value return weechat.WEECHAT_RC_OK
def input_modifier(data, modifier, modifier_data, string): """ This modifier is called when input text item is built by WeeChat (commonly after changes in input or cursor move), it builds new input with prefix ("Go to:"), and suffix (list of buffers found) """ global old_input, buffers, buffers_pos if modifier_data != weechat.current_buffer(): return "" names = "" input = weechat.string_remove_color(string, "") input = input.lstrip() if old_input == None or input != old_input: old_buffers = buffers buffers = get_matching_buffers(input) if buffers != old_buffers and len(input) > 0: if len(buffers) == 1 and weechat.config_string_to_boolean(weechat.config_get_plugin('auto_jump')): weechat.command(modifier_data, "/wait 1ms /input return") buffers_pos = 0 old_input = input names = buffers_to_string(buffers, buffers_pos, input.strip()) return weechat.config_get_plugin("message") + string + names
def config_setup(): for option, value in OPTIONS.items(): if not weechat.config_is_set_plugin(option): weechat.config_set_plugin(option, value[0]) weechat.config_set_desc_plugin(option, '%s' % value[1]) OPTIONS[option] = value[0] else: if option == 'prefix_nicks' or option == 'debug' or option == 'ssl_verify' or option == 'notice_notify_block': OPTIONS[option] = weechat.config_string_to_boolean( weechat.config_get_plugin(option)) else: OPTIONS[option] = weechat.config_get_plugin(option) if option == 'debug': curlopt['verbose'] = weechat.config_get_plugin(option) if option == 'ssl_verify': if weechat.config_get_plugin(option) == 0: curlopt['ssl_verifypeer'] = "0" curlopt['ssl_verifyhost'] = "0" else: curlopt['ssl_verifypeer'] = "1" curlopt['ssl_verifyhost'] = "2" if option == 'client_id': hlist = [] cidv = weechat.config_get_plugin(option) tokv = weechat.config_get_plugin('token') if cidv: hlist.append('Client-ID: ' + cidv) if tokv: hlist.append('Authorization: Bearer ' + tokv) if hlist: curlopt['httpheader'] = '\n'.join(hlist) if option == 'token': hlist = [] cidv = weechat.config_get_plugin('client_id') tokv = weechat.config_get_plugin(option) if tokv: hlist.append('Authorization: Bearer ' + tokv) if cidv: hlist.append('Client-ID: ' + cidv) if hlist: curlopt['httpheader'] = '\n'.join(hlist)
def edit(data, buf, args): editor = (weechat.config_get_plugin("editor") or os.environ.get("EDITOR", "vim -f")) terminal = (weechat.config_get_plugin("terminal") or os.getenv("TERMCMD")) terminal = terminal or "xterm" run_externally = weechat.config_string_to_boolean( weechat.config_get_plugin("run_externally")) run_externally = bool(run_externally) with open(PATH, "w+") as f: f.write(weechat.buffer_get_string(buf, "input")) if run_externally: hook_editor_process(terminal, editor, PATH, buf) else: run_blocking(editor, PATH, buf) return weechat.WEECHAT_RC_OK
def display_tweet_details(tweet): """Displays details about a particular tweet.""" print_to_current("%s-------------------" % wc.color("magenta")) print_to_current("%sTweet ID\t%s" % (wc.color("*cyan"), tweet.tid)) print_to_current("%sBy\t%s (@%s)" % (wc.color("*cyan"), tweet.name, tweet.screen_name)) expand_urls = wc.config_string_to_boolean(wc.config_get_plugin("expand_urls")) text = tweet.txt_unescaped if expand_urls: text = tweet.txt print_to_current("%sTweet\t%s" % (wc.color("*cyan"), text)) print_to_current("%sClient\t%s" % (wc.color("*cyan"), tweet.source)) if tweet.favorited: print_to_current("%sFavourite\t%s" % (wc.color("*cyan"), tweet.favorited)) if tweet.is_retweet: print_to_current("%sRetweeted By\t%s (@%s)" % (wc.color("*cyan"), tweet.rtname, tweet.rtscreen_name)) if tweet.in_reply_to_status_id: print_to_current("%sReply To\t%s" % (wc.color("*cyan"), tweet.in_reply_to_status_id)) print_to_current("%s-------------------" % wc.color("magenta"))
def check_warnings(): """Warn the user about problematic key bindings and tmux/screen.""" user_warned = False # Warn the user about problematic key bindings that may conflict with # vimode. # The solution is to remove these key bindings, but that's up to the user. infolist = weechat.infolist_get("key", "", "default") problematic_keybindings = [] while weechat.infolist_next(infolist): key = weechat.infolist_string(infolist, "key") command = weechat.infolist_string(infolist, "command") if re.match(REGEX_PROBLEMATIC_KEYBINDINGS, key): problematic_keybindings.append("%s -> %s" % (key, command)) if problematic_keybindings: user_warned = True print_warning("Problematic keybindings detected:") for keybinding in problematic_keybindings: print_warning(" %s" % keybinding) print_warning("These keybindings may conflict with vimode.") print_warning( "You can remove problematic key bindings and add" " recommended ones by using /vimode bind_keys, or only" " list them with /vimode bind_keys --list" ) print_warning("For help, see: %s" % FAQ_KEYBINDINGS) del problematic_keybindings # Warn tmux/screen users about possible Esc detection delays. if "STY" in os.environ or "TMUX" in os.environ: if user_warned: weechat.prnt("", "") user_warned = True print_warning("tmux/screen users, see: %s" % FAQ_ESC) if user_warned and not weechat.config_string_to_boolean(vimode_settings["no_warn"]): if user_warned: weechat.prnt("", "") print_warning("To force disable warnings, you can set" " plugins.var.python.vimode.no_warn to 'on'")
def display_tweet_details(tweet): """Displays details about a particular tweet.""" print_to_current("%s-------------------" % wc.color("magenta")) print_to_current("%sTweet ID\t%s" % (wc.color("*cyan"), tweet.tid)) print_to_current("%sBy\t%s (@%s)" % (wc.color("*cyan"), tweet.name, tweet.screen_name)) expand_urls = wc.config_string_to_boolean( wc.config_get_plugin("expand_urls")) text = tweet.txt_unescaped if expand_urls: text = tweet.txt print_to_current("%sTweet\t%s" % (wc.color("*cyan"), text)) print_to_current("%sClient\t%s" % (wc.color("*cyan"), tweet.source)) if tweet.favorited: print_to_current("%sFavourite\t%s" % (wc.color("*cyan"), tweet.favorited)) if tweet.is_retweet: print_to_current( "%sRetweeted By\t%s (@%s)" % (wc.color("*cyan"), tweet.rtname, tweet.rtscreen_name)) if tweet.in_reply_to_status_id: print_to_current("%sReply To\t%s" % (wc.color("*cyan"), tweet.in_reply_to_status_id)) print_to_current("%s-------------------" % wc.color("magenta"))
def run_notify(mtype, urgency, icon, time, nick, chan, message): data = str(mtype) + "\n" data += str(urgency) + "\n" data += str(icon) + "\n" data += str(time) + "\n" #time to display TODO data += str(nick) + "\n" data += str(chan) + "\n" data += str(message) transport = w.config_get_plugin('transport') command = w.config_get_plugin('notify_command'), host = w.config_get_plugin('host') try: if command: p = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) (output, _) = p.communicate(data) if p.returncode != 0: raise Exception("Notify command failed with return code " + str(p.returncode) + "\r\n" + output) else: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, int(w.config_get_plugin('port')))) s.send(str(data)) s.close() except Exception as e: if w.config_string_to_boolean(w.config_get_plugin("display_errors")): w.prnt("", "Could not send notification: %s" % str(e)) w.prnt( "", "To hide errors, run: /set plugins.var.python.remote-notify.display_errors off" )
def config_setup(): for option,value in OPTIONS.items(): weechat.config_set_desc_plugin(option, '%s' % value[1]) if not weechat.config_is_set_plugin(option): weechat.config_set_plugin(option, value[0]) OPTIONS[option] = value[0] else: if option == 'prefix_nicks' or option == 'debug' or option == 'ssl_verify': OPTIONS[option] = weechat.config_string_to_boolean( weechat.config_get_plugin(option)) if option == 'debug': if value == 0: curlopt['verbose'] = "0" else: curlopt['verbose'] = "1" if option == 'ssl_verify': if value == 0: curlopt['ssl_verifypeer'] = "0" curlopt['ssl_verifyhost'] = "0" else: curlopt['ssl_verifypeer'] = "1" curlopt['ssl_verifyhost'] = "2" else: OPTIONS[option] = weechat.config_get_plugin(option)
def conversation_cb(data, buffer, args): """ Follows the reply trail until the original was found. NOTE: This might block for a while. """ global twitter conversation = [] reply_id = args # Loop as long as there was a reply_id. while reply_id: try: conversation.append(twitter.get_tweet(reply_id)) reply_id = conversation[-1].in_reply_to_status_id except TwitterError as error: print_error(error) break if conversation: # Reverse the conversation to get the oldest first. conversation.reverse() # Now display the conversation. print_to_current("%s-------------------" % wc.color("magenta")) for tweet in conversation: nick_color = wc.info_get("irc_nick_color", tweet.screen_name) screen_name = nick_color + tweet.screen_name expand_urls = wc.config_string_to_boolean( wc.config_get_plugin("expand_urls")) text = tweet.txt_unescaped if expand_urls: text = tweet.txt output = "%s\t%s" % (screen_name, text) if tweet.is_retweet: output += " (RT by @%s)" % tweet.rtscreen_name output += "\n[#STATUSID: %s]" % tweet.id print_to_current(output) print_to_current("%s-------------------" % wc.color("magenta")) return wc.WEECHAT_RC_OK
def check_warnings(): """Warn the user about problematic key bindings and tmux/screen.""" user_warned = False # Warn the user about problematic key bindings that may conflict with # vimode. # The solution is to remove these key bindings, but that's up to the user. infolist = weechat.infolist_get("key", '', "default") problematic_keybindings = [] while weechat.infolist_next(infolist): key = weechat.infolist_string(infolist, "key") command = weechat.infolist_string(infolist, "command") if re.match(REGEX_PROBLEMATIC_KEYBINDINGS, key): problematic_keybindings.append("%s -> %s" % (key, command)) if problematic_keybindings: user_warned = True print_warning("Problematic keybindings detected:") for keybinding in problematic_keybindings: print_warning(" %s" % keybinding) print_warning("These keybindings may conflict with vimode.") print_warning("You can remove problematic key bindings and add" " recommended ones by using /vimode bind_keys, or only" " list them with /vimode bind_keys --list") print_warning("For help, see: %s" % FAQ_KEYBINDINGS) del problematic_keybindings # Warn tmux/screen users about possible Esc detection delays. if "STY" in os.environ or "TMUX" in os.environ: if user_warned: weechat.prnt('', '') user_warned = True print_warning("tmux/screen users, see: %s" % FAQ_ESC) if (user_warned and not weechat.config_string_to_boolean(vimode_settings['no_warn'])): if user_warned: weechat.prnt('', '') print_warning("To force disable warnings, you can set" " plugins.var.python.vimode.no_warn to 'on'")
def read_config(): for item in script_options: script_options[item] = weechat.config_string(weechat.config_get("plugins.var.python."+SCRIPT_NAME+"." + item)) for item in ["auth_complete","print_id","alt_rt_style","home_replies","tweet_nicks"]: #Convert to bool script_options[item] = weechat.config_string_to_boolean(script_options[item])
if __name__ == "__main__": weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, "", "") # Warn the user if he's using an unsupported WeeChat version. VERSION = weechat.info_get("version_number", "") if int(VERSION) < 0x01000000: print_warning("Please upgrade to WeeChat ≥ 1.0.0. Previous versions" " are not supported.") # Set up script options. for option, value in vimode_settings.items(): if weechat.config_is_set_plugin(option): vimode_settings[option] = weechat.config_get_plugin(option) else: weechat.config_set_plugin(option, value[0]) vimode_settings[option] = value[0] weechat.config_set_desc_plugin(option, '%s (default: "%s")' % (value[1], value[0])) # Warn the user about possible problems if necessary. if not weechat.config_string_to_boolean(vimode_settings["no_warn"]): check_warnings() # Create bar items and setup hooks. weechat.bar_item_new("mode_indicator", "cb_mode_indicator", "") weechat.bar_item_new("cmd_text", "cb_cmd_text", "") weechat.bar_item_new("vi_buffer", "cb_vi_buffer", "") weechat.bar_item_new("line_numbers", "cb_line_numbers", "") weechat.bar_new( "vi_cmd", "off", "0", "root", "", "bottom", "vertical", "vertical",
# Warn the user if he's using an unsupported WeeChat version. VERSION = weechat.info_get("version_number", '') if int(VERSION) < 0x01000000: print_warning("Please upgrade to WeeChat ≥ 1.0.0. Previous versions" " are not supported.") # Set up script options. for option, value in vimode_settings.items(): if weechat.config_is_set_plugin(option): vimode_settings[option] = weechat.config_get_plugin(option) else: weechat.config_set_plugin(option, value[0]) vimode_settings[option] = value[0] weechat.config_set_desc_plugin( option, "%s (default: \"%s\")" % (value[1], value[0])) # Warn the user about possible problems if necessary. if not weechat.config_string_to_boolean(vimode_settings['no_warn']): check_warnings() # Create bar items and setup hooks. weechat.bar_item_new("mode_indicator", "cb_mode_indicator", '') weechat.bar_item_new("cmd_text", "cb_cmd_text", '') weechat.bar_item_new("vi_buffer", "cb_vi_buffer", '') vi_cmd = weechat.bar_new("vi_cmd", "off", "0", "root", '', "bottom", "vertical", "vertical", "0", "0", "default", "default", "default", "0", "cmd_text") weechat.hook_config('plugins.var.python.%s.*' % SCRIPT_NAME, 'cb_config', '') weechat.hook_signal("key_pressed", "cb_key_pressed", '') weechat.hook_signal("key_combo_default", "cb_key_combo_default", '') weechat.hook_command( "vimode", SCRIPT_DESC, "[help | bind_keys [--list]]", " help: show help\n"
def display_cb(data, remaining_calls): """ Displays the timeline """ global db global twitter global buffers global tlid default_color = wc.color("default") show_in_cur = "Off" cur_away = "On" cur_detached = "On" valid_buffers = [] valid_buffers.append(buffers[data]) current_buffer = wc.current_buffer() show_in_cur = wc.config_string_to_boolean( wc.config_get_plugin("show_in_current")) cur_away = wc.config_string_to_boolean( wc.config_get_plugin("current_while_away")) cur_detached = wc.config_string_to_boolean( wc.config_get_plugin("current_while_detached")) away = wc.buffer_get_string(current_buffer, 'localvar_away') # I have NO idea why is doesn't work here but this does so... what? if ("__TIMELINE" in data and show_in_cur and buffers[data] != current_buffer and (not away or cur_away) and (is_attached() or cur_detached)): valid_buffers.append(current_buffer) status_dir = os.path.join(wc.config_get_plugin("storage_dir"), tlid[data]) try: for tweet in StatusMonitor(status_dir, twitter.api): tweep_color = wc.color(wc.config_get_plugin("nick_color")) for buf in valid_buffers: screen_name = tweep_color + tweet.screen_name text = tweet.txt if buf is current_buffer: cur_color = wc.color(wc.config_get_plugin("current_color")) screen_name = cur_color + "@" + screen_name text = cur_color + text mention_color = wc.color(wc.config_get_plugin("mention_color")) hash_color = wc.color(wc.config_get_plugin("hash_color")) text = re.sub(r'(?P<name>@\w+)', r"{}\1{}".format(mention_color, default_color), text) text = re.sub(r'(?P<hash>#\w+)', r"{}\1{}".format(hash_color, default_color), text) output = u"%s\t%s" % \ (screen_name, text) if tweet.is_retweet: output += " (RT by @%s)" % tweet.rtscreen_name output += "\n[#STATUSID: %s]" % tweet.id print_to_buffer(buf, output) db.set_last_tid(tweet.screen_name, tweet.id) except TwitterError as error: print_error(error) return wc.WEECHAT_RC_OK
def go_option_enabled(option): """Checks if a boolean script option is enabled or not.""" return weechat.config_string_to_boolean(weechat.config_get_plugin(option))