def customize_kick_cb(data, modifier, modifier_data, string):
    message = weechat.config_get_plugin("kick_message")
    if message == "":
        return string

    parsed = get_hashtable(string)
    try:
        parsed["kicked_nick"] = parsed["arguments"].split(" ", 1)[1]
        parsed["kicked_nick"] = parsed["kicked_nick"].split(" :", 1)[0]
    except:
        parsed["kicked_nick"] = ""

    message = create_output(message, parsed, "kick")

    if OPTIONS["debug"] == "on":
        weechat.prnt("", string)
        weechat.prnt("", parsed["channel"])
        weechat.prnt("", parsed["message"])

    buffer_ptr = weechat.buffer_search("irc", "%s.%s" % (modifier_data, parsed["channel"]))
    if not (buffer_ptr):
        return string

    prefix = weechat.config_string(weechat.config_get("weechat.look.prefix_quit"))
    prefix_color = weechat.color(weechat.config_color(weechat.config_get("weechat.color.chat_prefix_quit")))
    message_tags = ""

    if weechat.config_get_plugin("no_log").lower() == "on":
        message_tags = "no_log"
    weechat.prnt_date_tags(buffer_ptr, 0, message_tags, "%s%s\t%s" % (prefix_color, prefix, message))

    return string
def customize_join_cb_signal(data, signal, signal_data):
    weechat.prnt("", "data: %s   signal: %s  signal_data: %s" % (data, signal, signal_data))
    message = weechat.config_get_plugin("join_message")
    if message == "":
        return weechat.WEECHAT_RC_OK

    parsed = get_hashtable(signal_data)
    if parsed["nick"] == own_nick(signal.split(",", 1)[0]):
        return weechat.WEECHAT_RC_OK

    parsed["message"] = ""  # dummy. no message for JOIN
    parsed["kicked_nick"] = ""  # dummy. no KICK here
    message = create_output(message, parsed, "join")

    buffer_ptr = weechat.buffer_search("irc", "%s.%s" % (signal.split(",", 1)[0], parsed["channel"]))

    prefix = weechat.config_string(weechat.config_get("weechat.look.prefix_join"))
    prefix_color = weechat.color(weechat.config_color(weechat.config_get("weechat.color.chat_prefix_join")))
    message_tags = ""

    if weechat.config_get_plugin("no_log").lower() == "on":
        message_tags = "no_log"
    weechat.prnt_date_tags(buffer_ptr, 0, message_tags, "%s%s\t%s" % (prefix_color, prefix, message))

    return weechat.WEECHAT_RC_OK
Example #3
0
def buffer_switch(data, signal, signal_data):
    full_name = weechat.buffer_get_string(
        signal_data, 'full_name')  # get full_name of current buffer
    if full_name == '':  # upps, something totally wrong!
        return weechat.WEECHAT_RC_OK

    for option in list(OPTIONS.keys()):
        option = option.split('.')
        customize_plugin = weechat.config_get_plugin(
            '%s.%s' %
            (option[1], full_name))  # for example: title.irc.freenode.#weechat
        if customize_plugin:  # option exists
            config_pnt = weechat.config_get('weechat.bar.%s.items' % option[1])
            #            current_bar = weechat.config_string(weechat.config_get('weechat.bar.%s.items' % option[1]))
            weechat.config_option_set(config_pnt, customize_plugin,
                                      1)  # set customize_bar
        else:
            current_bar = weechat.config_string(
                weechat.config_get('weechat.bar.%s.items' % option[1]))
            default_plugin = weechat.config_get_plugin(
                'default.%s' % option[1])  # option we are looking for
            if default_plugin == '':  # default_plugin removed by user?
                weechat.config_set_plugin(
                    'default.%s' % option[1],
                    DEFAULT_OPTION[option[1]])  # set default_plugin again!
            if current_bar != default_plugin:
                config_pnt = weechat.config_get('weechat.bar.%s.items' %
                                                option[1])
                weechat.config_option_set(config_pnt, default_plugin,
                                          1)  # set customize_bar

    return weechat.WEECHAT_RC_OK
def customize_kick_cb(data, modifier, modifier_data, string):
    message = weechat.config_get_plugin('kick_message')
    if message == '':
        return string

    parsed = get_hashtable(string)
    try:
        parsed['kicked_nick'] = parsed['arguments'].split(' ', 1)[1]
        parsed['kicked_nick'] = parsed['kicked_nick'].split(' :', 1)[0]
    except:
        parsed['kicked_nick'] = ''

    message = create_output(message,parsed,'kick')

    if OPTIONS['debug'] == 'on':
        weechat.prnt("",string)
        weechat.prnt("",parsed['channel'])
        weechat.prnt("",parsed['message'])

    buf_pointer = weechat.buffer_search('irc',"%s.%s" % (modifier_data,parsed['channel']))

    prefix = weechat.config_string(weechat.config_get('weechat.look.prefix_quit'))
    prefix_color = weechat.color(weechat.config_color(weechat.config_get('weechat.color.chat_prefix_quit')))
    message_tags = ''

    if weechat.config_get_plugin('no_log').lower() == 'on':
        message_tags = 'no_log'
    weechat.prnt_date_tags(buf_pointer,0,message_tags,'%s%s\t%s' % (prefix_color,prefix,message))

    return string
Example #5
0
def print_as_list(target, matches, data, limit, total):
    """Prints the output as a comma-separated list of nicks."""

    col = w.color(w.info_get("irc_nick_color_name", data["setter"]))
    pf = fmt_prefix(data).replace("_target_", "")

    s = "{}\tThe following {} {}"
    if data["mode"] == "special":
        w.prnt(target, s.format(pf, "nick matches" if total == 1 else "nicks match", fmt_banmask(data["mask"])))
    else:
        w.prnt(target, (s + ", {} by {}{}{}").format(
           pf, "nick matches" if total == 1 else "nicks match",
           fmt_banmask(data["mask"]), fmt_mode_char(data["mode"]), col,
           data["setter"], w.color("reset")
        ))

    nicks = []
    remainder = len(matches) - limit
    i = 0
    for name in matches:
       nicks.append("{}{}{}".format(w.color(w.info_get("irc_nick_color_name", name)), name, w.color("reset")))
       i += 1

       if i >= limit:
           break

    if w.config_string(w.config_get("weechat.look.prefix_same_nick")):
        pf = (w.color(w.config_get_plugin("prefix_color")) +
          w.config_string(w.config_get("weechat.look.prefix_same_nick")) +
          w.color("reset"))

    printstr = "{}\t{}".format(pf, ", ".join(nicks))
    if remainder > 0:
        printstr += ", and {} more..".format(remainder)
    w.prnt(target, printstr)
Example #6
0
def get_config_options():
    global COLOR_RESET, COLOR_CHAT_DELIMITERS, COLOR_CHAT_NICK, COLOR_CHAT_HOST, \
           COLOR_CHAT_CHANNEL, COLOR_CHAT, COLOR_MESSAGE_JOIN, COLOR_MESSAGE_QUIT, \
           COLOR_REASON_QUIT, SMART_FILTER
    global send_signals, znc_timestamp

    config_get_string = lambda s: weechat.config_string(weechat.config_get(s))
    COLOR_RESET = weechat.color('reset')
    COLOR_CHAT_DELIMITERS = weechat.color('chat_delimiters')
    COLOR_CHAT_NICK = weechat.color('chat_nick')
    COLOR_CHAT_HOST = weechat.color('chat_host')
    COLOR_CHAT_CHANNEL = weechat.color('chat_channel')
    COLOR_CHAT = weechat.color('chat')
    COLOR_MESSAGE_JOIN = weechat.color(
        config_get_string('irc.color.message_join'))
    COLOR_MESSAGE_QUIT = weechat.color(
        config_get_string('irc.color.message_quit'))
    COLOR_REASON_QUIT = weechat.color(
        config_get_string('irc.color.reason_quit'))

    SMART_FILTER = weechat.config_boolean(
        weechat.config_get("irc.look.smart_filter"))

    send_signals = get_config_boolean('send_signals')
    znc_timestamp = weechat.config_get_plugin('timestamp')
def customize_join_cb_signal(data, signal, signal_data):
    weechat.prnt("","data: %s   signal: %s  signal_data: %s" % (data,signal,signal_data))
    message = weechat.config_get_plugin('join_message')
    if message == '':
        return weechat.WEECHAT_RC_OK

    parsed = get_hashtable(signal_data)
    if parsed['nick'] == own_nick(signal.split(',', 1)[0]):
        return weechat.WEECHAT_RC_OK

    parsed['message'] = "" # dummy. no message for JOIN
    parsed['kicked_nick'] = '' # dummy. no KICK here
    message = create_output(message,parsed,'join')

    buf_pointer = weechat.buffer_search('irc',"%s.%s" % (signal.split(',', 1)[0],parsed['channel']))

    prefix = weechat.config_string(weechat.config_get('weechat.look.prefix_join'))
    prefix_color = weechat.color(weechat.config_color(weechat.config_get('weechat.color.chat_prefix_join')))
    message_tags = ''

    if weechat.config_get_plugin('no_log').lower() == 'on':
        message_tags = 'no_log'
    weechat.prnt_date_tags(buf_pointer,0,message_tags,'%s%s\t%s' % (prefix_color,prefix,message))

    return weechat.WEECHAT_RC_OK
def customize_privmsg_cb(data, modifier, modifier_data, string):
    weechat.prnt("",data)
    weechat.prnt("",modifier)
    weechat.prnt("",modifier_data)
    weechat.prnt("",string)
    parsed = get_hashtable(string)
    message = parsed['message'].strip()
    # Filter out non-CTCP messages and non ACTION messages
    if not message or ord(message[0]) != 1 or not message[1:].startswith("ACTION"):
        return string
    text = message[8:-1]

    parsed['kicked_nick'] = ''                  # dummy. no irc_KICK here
    parsed['message'] = text
    message = create_output("${*blue}%N %M",parsed,'action')

    buffer_ptr = weechat.buffer_search('irc',"%s.%s" % (modifier_data,parsed['channel']))

    prefix = weechat.config_string(weechat.config_get('weechat.look.prefix_action'))
    prefix_color = weechat.color(weechat.config_color(weechat.config_get('weechat.color.chat_prefix_action')))
    prefix = substitute_colors(prefix)
    message_tags = ''

    if weechat.config_get_plugin('no_log').lower() == 'on':
        message_tags = 'no_log'
    weechat.prnt_date_tags(buffer_ptr,0,message_tags,'%s%s\t%s' % (prefix_color,prefix,message))
    return string
def customize_join_cb(data, modifier, modifier_data, string):
    message = weechat.config_get_plugin("join_message")
    if message == "":
        return string

    parsed = get_hashtable(string)
    if parsed["nick"] == own_nick(modifier_data):
        return string

    parsed["message"] = ""  # dummy. no message for irc_JOIN
    parsed["kicked_nick"] = ""  # dummy. no irc_KICK here
    message = create_output(message, parsed, "join")

    if OPTIONS["debug"] == "on":
        weechat.prnt("", string)
        weechat.prnt("", parsed["channel"])
        weechat.prnt("", parsed["message"])

    buffer_ptr = weechat.buffer_search("irc", "%s.%s" % (modifier_data, parsed["channel"]))

    prefix = weechat.config_string(weechat.config_get("weechat.look.prefix_join"))
    prefix_color = weechat.color(weechat.config_color(weechat.config_get("weechat.color.chat_prefix_join")))
    prefix = substitute_colors(prefix)
    message_tags = ""

    if weechat.config_get_plugin("no_log").lower() == "on":
        message_tags = "no_log"
    weechat.prnt_date_tags(buffer_ptr, 0, message_tags, "%s%s\t%s" % (prefix_color, prefix, message))

    return string
Example #10
0
def print_as_list(target, matches, data, limit, total):
    """Prints the output as a comma-separated list of nicks."""

    col = w.color(w.info_get("irc_nick_color_name", data["setter"]))
    pf = fmt_prefix(data).replace("_target_", "")

    s = "{}\tThe following {} {}"
    if data["mode"] == "special":
        w.prnt(target, s.format(pf, "nick matches" if total == 1 else "nicks match", fmt_banmask(data["mask"])))
    else:
        w.prnt(target, (s + ", {} by {}{}{}").format(
           pf, "nick matches" if total == 1 else "nicks match",
           fmt_banmask(data["mask"]), fmt_mode_char(data["mode"]), col,
           data["setter"], w.color("reset")
        ))

    nicks = []
    remainder = len(matches) - limit
    i = 0
    for name in matches:
       nicks.append("{}{}{}".format(w.color(w.info_get("irc_nick_color_name", name)), name, w.color("reset")))
       i += 1

       if i >= limit:
           break

    if w.config_string(w.config_get("weechat.look.prefix_same_nick")):
        pf = (w.color(w.config_get_plugin("prefix_color")) +
          w.config_string(w.config_get("weechat.look.prefix_same_nick")) +
          w.color("reset"))

    printstr = "{}\t{}".format(pf, ", ".join(nicks))
    if remainder > 0:
        printstr += ", and {} more..".format(remainder)
    w.prnt(target, printstr)
Example #11
0
def main():
    if not weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION,
                            SCRIPT_LICENSE, SCRIPT_DESC, 'exit_cb', ''):
        return weechat.WEECHAT_RC_ERROR

    # registration required for accessing config
    global NOTE_PREFIX
    global ERROR_PREFIX

    NOTE_PREFIX = weechat.color(
        weechat.config_color(
            weechat.config_get(
                'weechat.color.chat_prefix_join'))) + weechat.config_string(
                    weechat.config_get('weechat.look.prefix_join')) + '\t'

    ERROR_PREFIX = weechat.color(
        weechat.config_color(
            weechat.config_get(
                'weechat.color.chat_prefix_error'))) + weechat.config_string(
                    weechat.config_get('weechat.look.prefix_error')) + '\t'

    create_buffer()
    set_default_settings()

    log_debug('Test note', note=1)
    log_debug('Test error', error=1)

    if not get_setting('token'):
        show_auth_hint()
Example #12
0
def find_buffer(server, nick, message_type='whois'):
    # See if there is a target msgbuffer set for this server
    msgbuffer = weechat.config_string(
        weechat.config_get('irc.msgbuffer.%s.%s' % (server, message_type)))
    # No whois msgbuffer for this server; use the global setting
    if msgbuffer == '':
        msgbuffer = weechat.config_string(
            weechat.config_get('irc.msgbuffer.%s' % message_type))

    # Use the fallback msgbuffer setting if private buffer doesn't exist
    if msgbuffer == 'private':
        buffer = weechat.buffer_search('irc', '%s.%s' % (server, nick))
        if buffer != '':
            return buffer
        else:
            msgbuffer = weechat.config_string(
                weechat.config_get('irc.look.msgbuffer_fallback'))

    # Find the appropriate buffer
    if msgbuffer == "current":
        return weechat.current_buffer()
    elif msgbuffer == "weechat":
        return weechat.buffer_search_main()
    else:
        return weechat.buffer_search('irc', 'server.%s' % server)
def customize_part_cb(data, modifier, modifier_data, string):
    message = weechat.config_get_plugin('part_message')
    if message == '':
        return string

    parsed = get_hashtable(string)
    if parsed['nick'] == own_nick(modifier_data):
        return string

    parsed['kicked_nick'] = ''                  # dummy. no irc_KICK here
    message = create_output(message,parsed,'part')

    if OPTIONS['debug'] == 'on':
        weechat.prnt("","debug mode: irc_part")
        weechat.prnt("","string: %s" % string)
        weechat.prnt("",parsed['channel'])
        weechat.prnt("",parsed['message'])

    buf_pointer = weechat.buffer_search('irc',"%s.%s" % (modifier_data,parsed['channel']))

    prefix = weechat.config_string(weechat.config_get('weechat.look.prefix_quit'))
    prefix_color = weechat.color(weechat.config_color(weechat.config_get('weechat.color.chat_prefix_quit')))
    prefix = substitute_colors(prefix)
    message_tags = ''

    if weechat.config_get_plugin('no_log').lower() == 'on':
        message_tags = 'no_log'
    weechat.prnt_date_tags(buf_pointer,0,message_tags,'%s%s\t%s' % (prefix_color,prefix,message))
        
    return string
Example #14
0
def teknik_command(data, buffer, args):
    args = args.strip()
    if args == "":
        weechat.prnt("", "Error: You must specify a command")
    else:
        argv = args.split(" ")
        command = argv[0].lower()

        # Upload a File
        if command == 'upload':
            if len(argv) < 2:
                weechat.prnt("", "Error: You must specify a file")
            else:
                # Get current config values
                apiUrl = weechat.config_string(
                    weechat.config_get('plugins.var.python.teknik.api_url'))
                apiUsername = weechat.config_string(
                    weechat.config_get('plugins.var.python.teknik.username'))
                apiToken = weechat.config_string(
                    weechat.config_get('plugins.var.python.teknik.token'))

                data = {
                    'file': argv[1],
                    'apiUrl': apiUrl,
                    'apiUsername': apiUsername,
                    'apiToken': apiToken
                }
                hook = weechat.hook_process('func:upload_file', 0,
                                            "process_upload", json.dumps(data))

        # Set a config option
        elif command == 'set':
            if len(argv) < 2:
                weechat.prnt("", "Error: You must specify the option to set")
            else:
                option = argv[1].lower()
                if option == 'username':
                    if len(argv) < 3:
                        weechat.prnt("", "Error: You must specify a username")
                    else:
                        teknik_set_username(argv[2])
                elif option == 'token':
                    if len(argv) < 3:
                        weechat.prnt("",
                                     "Error: You must specify an auth token")
                    else:
                        teknik_set_token(argv[2])
                elif option == 'url':
                    if len(argv) < 3:
                        weechat.prnt("", "Error: You must specify an api url")
                    else:
                        teknik_set_url(argv[2])
                else:
                    weechat.prnt("", "Error: Unrecognized Option")
        else:
            weechat.prnt("", "Error: Unrecognized Command")

    return weechat.WEECHAT_RC_OK
Example #15
0
def handle_bouncer_msg(data, signal, signal_data):
    server_name = signal.split(",")[0]
    msg = weechat.info_get_hashtable("irc_message_parse",
                                     {"message": signal_data})

    args = msg["arguments"].split(" ")
    if args[0] != "NETWORK":
        return weechat.WEECHAT_RC_OK

    # Don't connect twice to the same network
    netid = args[1]
    if netid in added_networks:
        return weechat.WEECHAT_RC_OK_EAT

    # Retrieve the network name from the attributes
    net_name = None
    raw_attr_list = args[2].split(";")
    for raw_attr in raw_attr_list:
        k, v = raw_attr.split("=")
        if k == "name":
            net_name = v
            break

    check_char = lambda ch: ch.isalnum() or ch in ".-_"
    net_name = "".join(ch if check_char(ch) else "_" for ch in net_name)

    addr = weechat.config_string(
        weechat.config_get("irc.server." + server_name + ".addresses"))
    add_server = [
        "/server",
        "add",
        net_name,
        addr,
        "-temp",
        "-ssl",
    ]

    # User name settings need to be adapted for new networks
    for k in ["username", "sasl_username"]:
        v = weechat.config_string(
            weechat.config_get("irc.server." + server_name + "." + k))
        if not v:
            continue
        username = v.split("/", maxsplit=1)[0] + "/" + net_name
        add_server.append("-" + k + "=" + username)

    for k in ["password", "sasl_mechanism", "sasl_password"]:
        v = weechat.config_string(
            weechat.config_get("irc.server." + server_name + "." + k))
        add_server.append("-" + k + "=" + v)

    weechat.command(weechat.buffer_search("core", "weechat"),
                    " ".join(add_server))
    weechat.command(weechat.buffer_search("core", "weechat"),
                    "/connect " + net_name)

    return weechat.WEECHAT_RC_OK_EAT
Example #16
0
def irc_nick_find_color(nick):

    color = weechat.info_get('irc_nick_color', nick)
    if not color:
        # probably we're in WeeChat 0.3.0
        color %= weechat.config_integer(weechat.config_get("weechat.look.color_nicks_number"))
        color = weechat.config_get('weechat.color.chat_nick_color%02d' %(color+1))
        color = w.color(weechat.config_string(color))
    return '%s%s%s' %(color, nick, weechat.color('reset'))
Example #17
0
def irc_nick_find_color(nick):

    color = weechat.info_get('irc_nick_color', nick)
    if not color:
        # probably we're in WeeChat 0.3.0
        color %= weechat.config_integer(weechat.config_get("weechat.look.color_nicks_number"))
        color = weechat.config_get('weechat.color.chat_nick_color%02d' %(color+1))
        color = weechat.color(weechat.config_string(color))
    return '%s%s%s' %(color, nick, weechat.color('reset'))
Example #18
0
def irc_nick_find_color(nick, bgcolor='default'):

    color = weechat.info_get('irc_nick_color', nick)
    if not color:
        # probably we're in WeeChat 0.3.0
        color = 0
        for char in nick:
            color += ord(char)

        color %= w.config_integer(w.config_get("weechat.look.color_nicks_number"))
        color = w.config_get('weechat.color.chat_nick_color%02d' %(color+1))
        color = w.config_string(color)
    return '%s%s%s' %(w.color('%s,%s' %(color, bgcolor)), nick, w.color('reset'))
Example #19
0
def init_options():
    # check out if a default item bar exists
    for option,value in OPTIONS.items():
        if not weechat.config_get_plugin(option):
            default_bar = weechat.config_string(weechat.config_get(value))# get original option
            weechat.config_set_plugin(option, default_bar)
            default_option = option.split('.')
            default_bar_value = weechat.config_string(weechat.config_get('weechat.bar.%s.items' % default_option[1]))
            DEFAULT_OPTION[default_option[1]] = default_bar_value
        else:
            default_option = option.split('.')
            default_bar_value = weechat.config_string(weechat.config_get('weechat.bar.%s.items' % default_option[1]))
            DEFAULT_OPTION[default_option[1]] = default_bar_value
Example #20
0
    def getPolicy(self, key):
        """Get the value of a policy option for this context."""
        option = weechat.config_get(self.policy_config_option(key))

        if option == '':
            option = weechat.config_get(
                config_prefix('policy.default.%s' % key.lower()))

        result = bool(weechat.config_boolean(option))

        debug(('getPolicy', key, result))

        return result
Example #21
0
def hlpv_item_add(buffer, highlight, prefix, message):
    """ Add message to list of messages (will be displayed by item). """
    global hlpv_messages

    if highlight == "1":
        color_type = weechat.config_string(
            weechat.config_get("weechat.color.status_data_highlight"))
        color_string_highlight = weechat.config_get_plugin(
            "color_string_highlight")
        if color_string_highlight == "":
            color_string_highlight = color_type
        string_prefix = "%s%s" % (
            weechat.color(color_string_highlight),
            weechat.config_get_plugin("string_highlight"))
    else:
        color_type = weechat.config_string(
            weechat.config_get("weechat.color.status_data_private"))
        color_string_private = weechat.config_get_plugin(
            "color_string_private")
        if color_string_private == "":
            color_string_private = color_type
        string_prefix = "%s%s" % (weechat.color(color_string_private),
                                  weechat.config_get_plugin("string_private"))
    color_delimiter = weechat.color(
        weechat.config_get_plugin("color_delimiter"))
    if weechat.config_get_plugin("buffer_number") == "on":
        color_buffer_number = weechat.config_get_plugin("color_buffer_number")
        if color_buffer_number == "":
            color_buffer_number = color_type
        buffer_number = "%s%s%s:" % (weechat.color(color_buffer_number),
                                     weechat.buffer_get_integer(
                                         buffer, "number"), color_delimiter)
    else:
        buffer_number = ""
    color_buffer_name = weechat.color(
        weechat.config_get_plugin("color_buffer_name"))
    if weechat.config_get_plugin("buffer_short_name") == "on":
        buffer_name = weechat.buffer_get_string(buffer, "short_name")
    else:
        buffer_name = weechat.buffer_get_string(buffer, "name")
    color_prefix = weechat.color(weechat.config_get_plugin("color_prefix"))
    string_delimiter = weechat.config_get_plugin("string_delimiter")
    color_message = weechat.color(weechat.config_get_plugin("color_message"))
    string = "%s%s%s%s: %s%s%s%s%s%s" % (
        string_prefix, buffer_number, color_buffer_name, buffer_name,
        color_prefix, prefix, color_delimiter, string_delimiter, color_message,
        message)
    if len(hlpv_messages) == 0:
        hlpv_timer()
    hlpv_messages.append(string)
    weechat.bar_item_update("hlpv")
Example #22
0
def handle_bouncer_msg(data, signal, signal_data):
    server = signal.split(",")[0]
    msg = weechat.info_get_hashtable("irc_message_parse",
                                     {"message": signal_data})

    args = msg["arguments"].split(" ")
    if args[0] != "NETWORK":
        return weechat.WEECHAT_RC_OK

    # Don't connect twice to the same network
    netid = args[1]
    if netid in added_networks:
        return weechat.WEECHAT_RC_OK_EAT

    # Retrieve the network name from the attributes
    net_name = None
    raw_attr_list = args[2].split(";")
    for raw_attr in raw_attr_list:
        k, v = raw_attr.split("=")
        if k == "name":
            net_name = v
            break

    addr = weechat.config_string(
        weechat.config_get("irc.server." + server + ".addresses"))
    username = weechat.config_string(
        weechat.config_get("irc.server." + server + ".username"))
    if "/" in username:
        username = username.split("/")[0]
    add_server = [
        "/server",
        "add",
        net_name,
        addr,
        "-temp",
        "-ssl",
        "-username="******"/" + net_name,
    ]

    for k in ["password", "sasl_mechanism", "sasl_username", "sasl_password"]:
        v = weechat.config_string(
            weechat.config_get("irc.server." + server + "." + k))
        add_server.append("-" + k + "=" + v)

    weechat.command(weechat.buffer_search("core", "weechat"),
                    " ".join(add_server))
    weechat.command(weechat.buffer_search("core", "weechat"),
                    "/connect " + net_name)

    return weechat.WEECHAT_RC_OK_EAT
Example #23
0
def obtain_fmuser(who = None, network = None):
    api_key = weechat.config_string(weechat.config_get(CONF_PREFIX
        + CONFKEY_APIKEY))
    username = weechat.config_string(weechat.config_get(CONF_PREFIX
        + CONFKEY_USER))

    timeout_begin()
    if not network:
        network = pylast.LastFMNetwork(api_key = api_key)
    if who:
        user = network.get_user(who)
    else:
        user = network.get_user(username)
    timeout_end()
    return (network, user)
Example #24
0
def irc_nick_find_color(nick):
    if not nick: # nick (actually prefix) is empty, irc_nick_color returns None on empty input
        return ''

    color = weechat.info_get('irc_nick_color', nick)
    if not color:
        # probably we're in WeeChat 0.3.0
        color = 0
        for char in nick:
            color += ord(char)
        
        color %= weechat.config_integer(weechat.config_get("weechat.look.color_nicks_number"))
        color = weechat.config_get('weechat.color.chat_nick_color%02d' %(color+1))
        color = w.color(weechat.config_string(color))
    return '%s%s%s' %(color, nick, weechat.color('reset'))
Example #25
0
def _format_action(server, target, nick, text):
    white = w.color("white")

    snick = w.info_get("irc_nick", server)
    if snick == nick:
        nickc = white
    else:
        nickc = w.color(w.info_get("nick_color_name", nick))

    chanc = w.color(w.config_string(
        w.config_get("weechat.color.chat_channel")))
    delim = w.color(
        w.config_string(w.config_get("weechat.color.chat_delimiters")))
    reset = w.color("reset")
    return f" {white}* {delim}({reset}{target[0]}{delim}){nickc}{nick}{reset} {text}"
def shouldRefresh(message):
    """Determine whether the recency should be refreshed by checking to see if it was highlighted by the pre-existing highlight configuration."""
    words_option = weechat.config_get('weechat.look.highlight')
    highlight_words = weechat.config_string(words_option)
    regex_option = weechat.config_get('weechat.look.highlight_regex')
    highlight_regex = weechat.config_string(regex_option)
    regexes = [x.strip() for x in highlight_regex.split(',')]
    regex_match = False
    for regex in regexes:
        if weechat.string_has_highlight_regex(message, regex):
            regex_match = True
            break

    return (weechat.string_has_highlight(message, highlight_words)
            or regex_match)
Example #27
0
def teknik_command(data, buffer, args):
  args = args.strip()
  if args == "":
    weechat.prnt("", "Error: You must specify a command")
  else:
    argv = args.split(" ")
    command = argv[0].lower()
    
    # Upload a File
    if command == 'upload':
      if len(argv) < 2:
        weechat.prnt("", "Error: You must specify a file")
      else:
        # Get current config values
        apiUrl = weechat.config_string(weechat.config_get('plugins.var.python.teknik.api_url'))
        apiUsername = weechat.config_string(weechat.config_get('plugins.var.python.teknik.username'))
        apiToken = weechat.config_string(weechat.config_get('plugins.var.python.teknik.token'))
        
        data = {'file': argv[1], 'apiUrl': apiUrl, 'apiUsername': apiUsername, 'apiToken': apiToken}
        hook = weechat.hook_process('func:upload_file', 0, "process_upload", json.dumps(data))
        
    # Set a config option
    elif command == 'set':
      if len(argv) < 2:
        weechat.prnt("", "Error: You must specify the option to set")
      else:
        option = argv[1].lower()
        if option == 'username':
          if len(argv) < 3:
            weechat.prnt("", "Error: You must specify a username")
          else:
            teknik_set_username(argv[2])
        elif option == 'token':
          if len(argv) < 3:
            weechat.prnt("", "Error: You must specify an auth token")
          else:
            teknik_set_token(argv[2])
        elif option == 'url':
          if len(argv) < 3:
            weechat.prnt("", "Error: You must specify an api url")
          else:
            teknik_set_url(argv[2])
        else:
          weechat.prnt("", "Error: Unrecognized Option")
    else:
      weechat.prnt("", "Error: Unrecognized Command")
  
  return weechat.WEECHAT_RC_OK
Example #28
0
def fish_secure_key_cb(data, option, value):
    global fish_secure_key, fish_secure_cipher

    fish_secure_key = weechat.config_string(
        weechat.config_get("fish.secure.key")
    )

    if fish_secure_key == "":
        fish_secure_cipher = None
        return weechat.WEECHAT_RC_OK

    if fish_secure_key[:6] == "${sec.":
        decrypted = weechat.string_eval_expression(
            fish_secure_key, {}, {}, {}
        )
        if decrypted:
            fish_secure_cipher = Blowfish(decrypted)
            return weechat.WEECHAT_RC_OK
        else:
            weechat.config_option_set(fish_config_option["key"], "", 0)
            weechat.prnt("", "Decrypt sec.conf first\n")
            return weechat.WEECHAT_RC_OK

    if fish_secure_key != "":
        fish_secure_cipher = Blowfish(fish_secure_key)

    return weechat.WEECHAT_RC_OK
Example #29
0
def config_cb(data, option, value):
    weechat.config_set_plugin(
        "nick_format",
        weechat.config_string(
            weechat.config_get("plugins.var.python." + SCRIPT_NAME +
                               ".nick_format")))
    return weechat.WEECHAT_RC_OK
Example #30
0
def init_options():
    # check out if a default item bar exists
    for option, value in list(OPTIONS.items()):
        if not weechat.config_get_plugin(option):
            default_bar = weechat.config_string(
                weechat.config_get(value))  # get original option
            weechat.config_set_plugin(option, default_bar)
            default_option = option.split('.')
            default_bar_value = weechat.config_string(
                weechat.config_get('weechat.bar.%s.items' % default_option[1]))
            DEFAULT_OPTION[default_option[1]] = default_bar_value
        else:
            default_option = option.split('.')
            default_bar_value = weechat.config_string(
                weechat.config_get('weechat.bar.%s.items' % default_option[1]))
            DEFAULT_OPTION[default_option[1]] = default_bar_value
Example #31
0
def print_usage(data, buffer, args):
    weechat.prnt(
        buffer, "%s\t%s: script already running..." % (string_eval_expression(
            weechat.config_string(
                weechat.config_get("weechat.look.prefix_error"))),
                                                       SCRIPT_NAME))
    return weechat.WEECHAT_RC_OK
Example #32
0
def bas_config_option_cb(data, option, value):
    if not weechat.config_boolean(bas_options["look_instant"]):
        return weechat.WEECHAT_RC_OK

    if not weechat.config_get(option):  # option was deleted
        return weechat.WEECHAT_RC_OK

    option = option[len("%s.buffer." % CONFIG_FILE_NAME):]

    pos = option.rfind(".")
    if pos > 0:
        buffer_mask = option[0:pos]
        property = option[pos+1:]
        if buffer_mask and property:
            buffers = weechat.infolist_get("buffer", "", buffer_mask)

            if not buffers:
                return weechat.WEECHAT_RC_OK

            while weechat.infolist_next(buffers):
                buffer = weechat.infolist_pointer(buffers, "pointer")
                weechat.buffer_set(buffer, property, value)

            weechat.infolist_free(buffers)

    return weechat.WEECHAT_RC_OK
Example #33
0
 def install(self):
     try:
         numset = 0
         numerrors = 0
         for name in self.options:
             option = weechat.config_get(name)
             if option:
                 if weechat.config_option_set(
                         option, self.options[name],
                         1) == weechat.WEECHAT_CONFIG_OPTION_SET_ERROR:
                     self.prnt_error(
                         'Error setting option "%s" to value "%s" (running an old WeeChat?)'
                         % (name, self.options[name]))
                     numerrors += 1
                 else:
                     numset += 1
             else:
                 self.prnt(
                     'Warning: option not found: "%s" (running an old WeeChat?)'
                     % name)
                 numerrors += 1
         errors = ''
         if numerrors > 0:
             errors = ', %d error(s)' % numerrors
         if self.filename:
             self.prnt('Theme "%s" installed (%d options set%s)' %
                       (self.filename, numset, errors))
         else:
             self.prnt('Theme installed (%d options set%s)' %
                       (numset, errors))
     except:
         if self.filename:
             self.prnt_error('Failed to install theme "%s"' % self.filename)
         else:
             self.prnt_error('Failed to install theme')
Example #34
0
def bas_config_option_cb(data, option, value):
    if not weechat.config_boolean(bas_options["look_instant"]):
        return weechat.WEECHAT_RC_OK

    if not weechat.config_get(option):  # option was deleted
        return weechat.WEECHAT_RC_OK

    option = option[len("%s.buffer." % CONFIG_FILE_NAME):]

    pos = option.rfind(".")
    if pos > 0:
        buffer_mask = option[0:pos]
        property = option[pos + 1:]
        if buffer_mask and property:
            buffers = weechat.infolist_get("buffer", "", buffer_mask)

            if not buffers:
                return weechat.WEECHAT_RC_OK

            while weechat.infolist_next(buffers):
                buffer = weechat.infolist_pointer(buffers, "pointer")
                weechat.buffer_set(buffer, property, value)

            weechat.infolist_free(buffers)

    return weechat.WEECHAT_RC_OK
Example #35
0
def fish_secure_key_cb(data, option, value):
    global fish_secure_key, fish_secure_cipher

    fish_secure_key = weechat.config_string(
        weechat.config_get("fish.secure.key")
    )

    if fish_secure_key == "":
        fish_secure_cipher = None
        return weechat.WEECHAT_RC_OK

    if fish_secure_key[:6] == "${sec.":
        decrypted = weechat.string_eval_expression(
            fish_secure_key, {}, {}, {}
        )
        if decrypted:
            fish_secure_cipher = Blowfish(decrypted)
            return weechat.WEECHAT_RC_OK
        else:
            weechat.config_option_set(fish_config_option["key"], "", 0)
            weechat.prnt("", "Decrypt sec.conf first\n")
            return weechat.WEECHAT_RC_OK

    if fish_secure_key != "":
        fish_secure_cipher = Blowfish(fish_secure_key)

    return weechat.WEECHAT_RC_OK
Example #36
0
def colorize_nick_color(nick, my_nick):
    if nick == my_nick:
        return weechat.color(
            weechat.config_string(
                weechat.config_get('weechat.color.chat_nick_self')))
    else:
        return weechat.info_get('irc_nick_color', nick)
Example #37
0
def get_autojoin_list(server):
    ptr_config_autojoin = weechat.config_get("irc.server.%s.autojoin" % server)

    # option not found! server does not exist
    if not ptr_config_autojoin:
        weechat.prnt(buffer, "%s%s: server '%s' does not exist." % (weechat.prefix("error"), SCRIPT_NAME, server))
        return weechat.WEECHAT_RC_OK

    # get value from autojoin option
    channels = weechat.config_string(ptr_config_autojoin)
    if not channels:
        return 1, 1

    # check for keys
    if len(re.findall(r" ", channels)) == 0:
        list_of_channels = channels.split(",")
        list_of_keys = []
    elif len(re.findall(r" ", channels)) == 1:
        list_of_channels2, list_of_keys = channels.split(" ")
        list_of_channels = list_of_channels2.split(",")
    else:
        weechat.prnt("", "%s%s: irc.server.%s.autojoin not valid..." % (weechat.prefix("error"), SCRIPT_NAME, server))
        return 0, 0

    return list_of_channels, list_of_keys
Example #38
0
def get_autojoin_list(server):
    ptr_config_autojoin = weechat.config_get('irc.server.%s.autojoin' % server)

    # option not found! server does not exist
    if not ptr_config_autojoin:
        return 0, 0
    channels = weechat.config_string(ptr_config_autojoin)
    # no values for this option
    if not channels:
        return 0, 0

    # check for keys
    if len(re.findall(r" ", channels)) == 0:
        list_of_channels = channels.split(",")
        list_of_keys = []
    elif len(re.findall(r" ", channels)) == 1:
        list_of_channels2, list_of_keys = channels.split(" ")
        list_of_channels = list_of_channels2.split(",")
    else:
        weechat.prnt(
            "", "%s%s: irc.server.%s.autojoin not valid..." %
            (weechat.prefix('error'), SCRIPT_NAME, server))
        return 0, 0

    return list_of_channels, list_of_keys
Example #39
0
 def install(self):
     try:
         numset = 0
         numerrors = 0
         for name in self.options:
             option = weechat.config_get(name)
             if option:
                 if weechat.config_option_set(option, self.options[name], 1) == weechat.WEECHAT_CONFIG_OPTION_SET_ERROR:
                     self.prnt_error('Error setting option "%s" to value "%s" (running an old WeeChat?)' % (name, self.options[name]))
                     numerrors += 1
                 else:
                     numset += 1
             else:
                 self.prnt('Warning: option not found: "%s" (running an old WeeChat?)' % name)
                 numerrors += 1
         errors = ''
         if numerrors > 0:
             errors = ', %d error(s)' % numerrors
         if self.filename:
             self.prnt('Theme "%s" installed (%d options set%s)' % (self.filename, numset, errors))
         else:
             self.prnt('Theme installed (%d options set%s)' % (numset, errors))
     except:
         if self.filename:
             self.prnt_error('Failed to install theme "%s"' % self.filename)
         else:
             self.prnt_error('Failed to install theme')
Example #40
0
def on_msg(*a):
    if len(a) == 8:
        data, buffer, timestamp, tags, displayed, highlight, sender, message = a
        #return when sender is weechat.look.prefix_network
        option = w.config_get("weechat.look.prefix_network")
        if sender == w.config_string(option):
            return w.WEECHAT_RC_OK
        if data == "private" or highlight == "1":

            #set buffer
            buffer = "me" if data == "private" else w.buffer_get_string(buffer, "short_name")

            #set time - displays message forever on highlight
            if highlight == "1" and data == "private":
                mtype = "private_highlight"
                icon = w.config_get_plugin('pm-icon')
                time = w.config_get_plugin('display_time_private_highlight')
            elif highlight == "1":
                mtype = "highlight"
                icon = w.config_get_plugin('icon')
                time = w.config_get_plugin('display_time_highlight')
            else:
                mtype = "private"
                icon = w.config_get_plugin('pm-icon')
                time = w.config_get_plugin('display_time_default')

            urgency = w.config_get_plugin('urgency_default')

            #sent
            run_notify(mtype, urgency, icon, time, sender, buffer, message)
            #w.prnt("", str(a))
    return w.WEECHAT_RC_OK
Example #41
0
 def install(self):
     try:
         numset = 0
         numerrors = 0
         for name in self.options:
             option = weechat.config_get(name)
             if option:
                 rc = weechat.config_option_set(option, self.options[name],
                                                1)
                 if rc == weechat.WEECHAT_CONFIG_OPTION_SET_ERROR:
                     self.prnt_error('Error setting option "{0}" to value '
                                     '"{1}" (running an old WeeChat?)'
                                     ''.format(name, self.options[name]))
                     numerrors += 1
                 else:
                     numset += 1
             else:
                 self.prnt('Warning: option not found: "{0}" '
                           '(running an old WeeChat?)'.format(name))
                 numerrors += 1
         errors = ''
         if numerrors > 0:
             errors = ', {0} error(s)'.format(numerrors)
         if self.filename:
             self.prnt('Theme "{0}" installed ({1} options set{2})'
                       ''.format(self.filename, numset, errors))
         else:
             self.prnt('Theme installed ({0} options set{1})'
                       ''.format(numset, errors))
     except:
         if self.filename:
             self.prnt_error('Failed to install theme "{0}"'
                             ''.format(self.filename))
         else:
             self.prnt_error('Failed to install theme')
Example #42
0
def fmt_prefix(data):
    """Read and transform the prefix as per user settings"""

    fmt = w.config_get_plugin("prefix")

    if "_script_name_" in fmt:
        fmt = fmt.replace("_script_name_", SCRIPT_NAME)
    if "_setter_" in fmt:
        fmt = fmt.replace("_setter_", data["setter"])
    if "_prefix_network_" in fmt:
        fmt = fmt.replace(
            "_prefix_network_",
            w.config_string(w.config_get("weechat.look.prefix_network")))
    col = w.config_get_plugin("prefix_color")

    pfcol = w.color(col)
    reset = w.color("reset")

    if w.string_match(fmt, "[*]", 0):
        fmt = fmt.replace("[", "{}[{}".format(pfcol, reset)).replace(
            "]", "{}]{}".format(pfcol, reset))
    else:
        fmt = "{}{}{}".format(pfcol, fmt, reset)

    return fmt
def buffer_switch_cb(data, signal, signal_data):
    global look_server
    look_server = ""
    look_server = weechat.config_string(
        weechat.config_get("irc.look.server_buffer"))
    if look_server == "independent":  # server buffer independent?
        return weechat.WEECHAT_RC_OK  # better remove script, you don't need it.

    if weechat.buffer_get_string(
            signal_data, 'name') != 'weechat':  # not weechat core buffer
        if (weechat.buffer_get_string(signal_data, 'localvar_type')
                == '') or (weechat.buffer_get_string(
                    signal_data, 'localvar_type') == 'server'):
            return weechat.WEECHAT_RC_OK
    elif weechat.buffer_get_string(signal_data, 'name') == 'weechat':
        return weechat.WEECHAT_RC_OK

    # buffer is channel or private?
    if (weechat.buffer_get_string(signal_data, 'localvar_type')
            == 'channel') or (weechat.buffer_get_string(
                signal_data, 'localvar_type') == 'private'):
        bufpointer = weechat.window_get_pointer(weechat.current_window(),
                                                "buffer")
        servername_from_current_buffer = weechat.buffer_get_string(
            bufpointer, 'localvar_server')
        name = weechat.buffer_get_string(bufpointer, 'name')
        server_switch(signal_data, servername_from_current_buffer, name)
    return weechat.WEECHAT_RC_OK
Example #44
0
 def install(self):
     try:
         numset = 0
         numerrors = 0
         for name in self.options:
             option = weechat.config_get(name)
             if option:
                 rc = weechat.config_option_set(option,
                                                self.options[name], 1)
                 if rc == weechat.WEECHAT_CONFIG_OPTION_SET_ERROR:
                     self.prnt_error('Error setting option "{0}" to value '
                                     '"{1}" (running an old WeeChat?)'
                                     ''.format(name, self.options[name]))
                     numerrors += 1
                 else:
                     numset += 1
             else:
                 self.prnt('Warning: option not found: "{0}" '
                           '(running an old WeeChat?)'.format(name))
                 numerrors += 1
         errors = ''
         if numerrors > 0:
             errors = ', {0} error(s)'.format(numerrors)
         if self.filename:
             self.prnt('Theme "{0}" installed ({1} options set{2})'
                       ''.format(self.filename, numset, errors))
         else:
             self.prnt('Theme installed ({0} options set{1})'
                       ''.format(numset, errors))
     except:
         if self.filename:
             self.prnt_error('Failed to install theme "{0}"'
                             ''.format(self.filename))
         else:
             self.prnt_error('Failed to install theme')
Example #45
0
def get_path():
    """ get logger path """
    options = {
        'directory': 'data',
    }
    return w.string_eval_path_home(
        w.config_string(w.config_get("logger.file.path")), {}, {}, options)
Example #46
0
def save_new_force_nicks():
    global colored_nicks
    #    new_nick_color_force = ';'.join([ ':'.join(item) for item in colored_nicks.items()])
    new_nick_color_force = ';'.join(
        [':'.join(item) for item in list(colored_nicks.items())])
    config_pnt = weechat.config_get(nick_option)
    weechat.config_option_set(config_pnt, new_nick_color_force, 1)
Example #47
0
def join_cb(data, signal, signal_data):
    server = signal.split(',')[0]
    if weechat.info_get("irc_nick_from_host", signal_data) != weechat.info_get(
            "irc_nick", server):
        # nick which has joined is not our current nick
        return weechat.WEECHAT_RC_OK
    weechat.command("", "/mute /set irc.server.%s.autoconnect on" % (server, ))

    channel = signal_data.split()[-1][1:]
    # Fix up prefixless channels, : prefixed channels
    channel = channel if channel[0] != ':' else channel[1:]
    channel = '#' + channel if channel[0] != '#' else channel
    autojoin = weechat.config_string(
        weechat.config_get("irc.server.%s.autojoin" % (server, )))
    if autojoin:
        autojoin = ','.join(
            ['#' + w if w[0] != '#' else w for w in autojoin.split(',')])
        if not channel in autojoin.split(','):
            weechat.command(
                "", "/mute /set irc.server.%s.autojoin %s,%s" %
                (server, autojoin, channel))
        else:
            weechat.command(
                "",
                "/mute /set irc.server.%s.autojoin %s" % (server, autojoin))
    else:
        weechat.command(
            "", "/mute /set irc.server.%s.autojoin %s" % (server, channel))

    weechat.command("", "/save irc")
    return weechat.WEECHAT_RC_OK
Example #48
0
def read_history(filename, ptr_buffer):
    global_history = 0

    # get buffer_autoset_option as a fallback. could happen that the localvar is not already set to buffer
    plugin = weechat.buffer_get_string(ptr_buffer, 'localvar_plugin')
    name = weechat.buffer_get_string(ptr_buffer, 'localvar_name')
    buffer_autoset_option = (
        'buffer_autoset.buffer.%s.%s.localvar_set_save_history' %
        (plugin, name))
    buffer_autoset_option = weechat.config_get(buffer_autoset_option)

    # global history does not use buffer pointers!
    if filename == filename_global_history:
        global_history = 1

    filename = get_filename_with_path(filename)

    # filename exists?
    if not os.path.isfile(filename):
        return

    # check for buffer history (0, global = 1)
    if global_history == 0 and OPTIONS['save_buffer'].lower() == 'off':
        # localvar_save_history exists for buffer?
        if not ptr_buffer and not buffer_autoset_option and not weechat.buffer_get_string(
                ptr_buffer, 'localvar_save_history'):
            return
    hdata = weechat.hdata_get('history')
    if not hdata:
        return

    try:
        f = open(filename, 'r')
        #        for line in f.xreadlines():    # old python 2.x
        for line in f:  # should also work with python 2.x
            #            line = line.decode('utf-8')
            line = str(line.strip())
            if ptr_buffer:
                # add to buffer history
                weechat.hdata_update(hdata, '', {
                    'buffer': ptr_buffer,
                    'text': line
                })
            else:
                # add to global history
                weechat.hdata_update(hdata, '', {'text': line})
        f.close()
    except:
        if global_history == 1:
            weechat.prnt(
                '', '%s%s: Error loading global history from "%s"' %
                (weechat.prefix('error'), SCRIPT_NAME, filename))
        else:
            name = weechat.buffer_get_string(ptr_buffer, 'localvar_name')
            weechat.prnt(
                '',
                '%s%s: Error loading buffer history for buffer "%s" from "%s"'
                % (weechat.prefix('error'), SCRIPT_NAME, name, filename))
        raise
Example #49
0
def open_query_buffer(server_name, nick):
    starting_buffer = weechat.current_buffer()
    noswitch = ""
    switch_autojoin = weechat.config_get("irc.look.buffer_switch_autojoin")
    if not weechat.config_boolean(switch_autojoin):
        noswitch = "-noswitch"
    weechat.command('','/query %s -server %s %s' % ( noswitch, server_name, nick ))
    weechat.buffer_set(starting_buffer, 'display', 'auto')
Example #50
0
def shutdown_cb():
    # write back default options to original options, then quit...
    for option in OPTIONS.keys():
        option = option.split('.')
        default_plugin = weechat.config_get_plugin('default.%s' % option[1])
        config_pnt = weechat.config_get('weechat.bar.%s.items' % option[1])
        weechat.config_option_set(config_pnt,default_plugin,1)
    return weechat.WEECHAT_RC_OK
Example #51
0
def shutdown_cb():
    # write back default options to original options, then quit...
    for option in list(OPTIONS.keys()):
        option = option.split('.')
        default_plugin = weechat.config_get_plugin('default.%s' % option[1])
        config_pnt = weechat.config_get('weechat.bar.%s.items' % option[1])
        weechat.config_option_set(config_pnt, default_plugin, 1)
    return weechat.WEECHAT_RC_OK
Example #52
0
def print_messages(mailbox='INBOX'):
    ''' Print all unread messages in a folder to buffer '''

    global imap_buffer, active_message_line, active_message_uid

    w.buffer_clear(imap_buffer)
    imap = Imap()

    typ, data = imap.messages(mailbox)
    if not typ == 'OK':
        print 'bad type returned'
        imap.logout()
        return

    y = 0
    for num in data[0].split():
        typ, data = imap.conn.fetch(num, '(FLAGS INTERNALDATE BODY[HEADER.FIELDS (SUBJECT FROM)])')
        data = data[0] # only one message is returned
        meta, headers = data[0], data[1]
        #flags = re.search(r'\(FLAGS \((?P<flags>.+)\) ', meta).groupdict()['flags']

        internaldate = datetime.fromtimestamp(time.mktime(i.Internaldate2tuple(meta)))
        internaldate = internaldate.strftime(w.config_get_plugin('time_format'))
        internaldate = internaldate.replace(':', '%s:%s' %
                (w.color(w.config_string(
                w.config_get('weechat.color.chat_time_delimiters'))),
                w.color('reset')))
        internaldate = internaldate.strip()
                
        sender = re.search(r'From: ?(?P<from>.+)\s', headers, re.I)
        if sender:
            sender = sender.groupdict()['from']

        subject = re.search(r'Subject: ?(?P<subject>.+)\s', headers, re.I)
        if subject:
            subject = subject.groupdict()['subject']


        sender = imap.decode_helper(sender)
        subject = imap.decode_helper(subject)

        bgcolor = 'default'
        if y == active_message_line:
            active_message_uid = num
            bgcolor = 'red'

        if ' ' in sender:
            sender = irc_nick_find_color(sender.split()[0].strip('"'))
        else:
            sender = irc_nick_find_color(sender)

        w.prnt(imap_buffer, '%s %s\t%s %s' % \
                (internaldate, sender, w.color('default,%s' %bgcolor), subject))
        y += 1
        if y == 25:
            break

    imap.logout()
Example #53
0
def hlpv_item_add(buffer, highlight, prefix, message):
    """ Add message to list of messages (will be displayed by item). """
    global hlpv_messages

    if highlight == "1":
        color_type = weechat.config_string(weechat.config_get("weechat.color.status_data_highlight"))
        color_string_highlight = weechat.config_get_plugin("color_string_highlight")
        if color_string_highlight == "":
            color_string_highlight = color_type
        string_prefix = "%s%s" % (weechat.color(color_string_highlight),
                                  weechat.config_get_plugin("string_highlight"))
    else:
        color_type = weechat.config_string(weechat.config_get("weechat.color.status_data_private"))
        color_string_private = weechat.config_get_plugin("color_string_private")
        if color_string_private == "":
            color_string_private = color_type
        string_prefix = "%s%s" % (weechat.color(color_string_private),
                                  weechat.config_get_plugin("string_private"))
    color_delimiter = weechat.color(weechat.config_get_plugin("color_delimiter"))
    if weechat.config_get_plugin("buffer_number") == "on":
        color_buffer_number = weechat.config_get_plugin("color_buffer_number")
        if color_buffer_number == "":
            color_buffer_number = color_type
        buffer_number = "%s%s%s:" % (weechat.color(color_buffer_number),
                                     weechat.buffer_get_integer(buffer, "number"),
                                     color_delimiter)
    else:
        buffer_number = ""
    color_buffer_name = weechat.color(weechat.config_get_plugin("color_buffer_name"))
    if weechat.config_get_plugin("buffer_short_name") == "on":
        buffer_name = weechat.buffer_get_string(buffer, "short_name")
    else:
        buffer_name = weechat.buffer_get_string(buffer, "name")
    color_prefix = weechat.color(weechat.config_get_plugin("color_prefix"))
    string_delimiter = weechat.config_get_plugin("string_delimiter")
    color_message = weechat.color(weechat.config_get_plugin("color_message"))
    string = "%s%s%s%s: %s%s%s%s%s%s" % (string_prefix, buffer_number,
                                         color_buffer_name, buffer_name,
                                         color_prefix, prefix,
                                         color_delimiter, string_delimiter,
                                         color_message, message)
    if len(hlpv_messages) == 0:
        hlpv_timer()
    hlpv_messages.append(string)
    weechat.bar_item_update("hlpv")
Example #54
0
def url_recv_cb(data, buffer, time, tags, displayed, highlight, prefix, message):
    if w.config_get_plugin('debug') == 'on':
        w.prnt("","%s: Got url %s" % (SCRIPT_NAME, message))

    #do not trigger on filtered lines and notices
    if displayed == '0' or prefix == w.config_string(w.config_get('weechat.look.prefix_network')):
        #leave alone
        if w.config_get_plugin('debug') == 'on':
            w.prnt("","%s: not displayed, or sent from network. Ignoring" % SCRIPT_NAME)
        return w.WEECHAT_RC_OK

    buf_name = w.buffer_get_string(buffer,"name")
    if w.config_get_plugin('debug') == 'on':
        w.prnt("","%s: from buffer %s" % (SCRIPT_NAME, buf_name))

    #skip ignored buffers
    ignore_buffers = w.config_get_plugin('ignore_buffers').split(',')
    if buf_name in ignore_buffers:
        if w.config_get_plugin('debug') == 'on':
            w.prnt("","%s: %s is on ignore_buffer list" % (SCRIPT_NAME, buf_name))
        return w.WEECHAT_RC_OK

    FNULL=open(os.devnull,'w')

    #can have multiple imgs per msg?
    for url in urlRe.findall(message):
        found = False
        if w.config_get_plugin('debug') == 'on':
            w.prnt("","%s: testing url %s" % (SCRIPT_NAME,url))
        #is the url for an image?
        if imgRe.match(url):
            found = True
            if w.config_get_plugin('debug') == 'on':
                w.prnt("","%s: found image!" % SCRIPT_NAME)
        elif imgServiceRe.match(url):
            found = True
            if w.config_get_plugin('debug') == 'on':
                w.prnt("","%s: found image service!" % SCRIPT_NAME)
            
            if "imgur" in url:
                url = re.sub(r'.*imgur\.com/(.*)',
                        r'http://i\.imgur\.com/\1\.jpg',
                        url)
            #elif "cl.ly" in url:
            #keyword blacklisting?
            #domains are tied to the service. guess the services could be blacklisted

        if found:
            #blacklist
            subprocess.call(['%s/get_view_img.sh' % w.info_get("weechat_dir",""),
                                '%s/img_cache' % w.info_get("weechat_dir",""),
                                url],
                            stdout=FNULL,stderr=subprocess.STDOUT)
            

    
    return w.WEECHAT_RC_OK 
    def getPolicy(self, key):
        """Get the value of a policy option for this context."""
        key_lower = key.lower()

        if key_lower in READ_ONLY_POLICIES:
            result = READ_ONLY_POLICIES[key_lower]
        else:
            option = weechat.config_get(self.policy_config_option(key))

            if option == '':
                option = weechat.config_get(
                    config_prefix('policy.default.%s' % key_lower))

            result = bool(weechat.config_boolean(option))

        debug(('getPolicy', key, result))

        return result
Example #56
0
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
Example #57
0
def get_buffer(server, nick):
    msgbuffer = weechat.config_string(weechat.config_get('irc.msgbuffer.%s.%s' % (server, 'whois')))
    if msgbuffer == '':
        msgbuffer = weechat.config_string(weechat.config_get('irc.msgbuffer.%s' % 'whois'))

    if msgbuffer == 'private':
        buffer = weechat.buffer_search('irc', '%s.%s' %(server, nick))
        if buffer != '':
            return buffer
        else:
            msgbuffer = weechat.config_string(weechat.config_get('irc.look.msgbuffer_fallback'))

    if msgbuffer == "current":
        return weechat.current_buffer()
    elif msgbuffer == "weechat":
        return weechat.buffer_search_main()
    else:
        return weechat.buffer_search('irc', 'server.%s' % server)
def customize_quit_cb(data, modifier, modifier_data, string):
    message = weechat.config_get_plugin('quit_message')
    if message == '':
        return string

    parsed = get_hashtable(string)
    if parsed['nick'] == own_nick(modifier_data):
        return string

    parsed['kicked_nick'] = ''                  # dummy. no irc_KICK here
    message = create_output(message,parsed,'quit')

    if OPTIONS['debug'] == 'on':
        weechat.prnt("","debug mode: irc_quit")
        weechat.prnt("","string: %s" % string)
        weechat.prnt("",parsed['channel'])
        weechat.prnt("",parsed['message'])

    buf_pointer = weechat.buffer_search('irc',"%s.%s" % (modifier_data,parsed['channel']))

    prefix = weechat.config_string(weechat.config_get('weechat.look.prefix_quit'))
    prefix_color = weechat.color(weechat.config_color(weechat.config_get('weechat.color.chat_prefix_quit')))
    prefix = substitute_colors(prefix)
    message_tags = ''


    ptr_infolist = weechat.infolist_get("buffer", "", "")
    while weechat.infolist_next(ptr_infolist):
        ptr_buffer = weechat.infolist_pointer(ptr_infolist, "pointer")
        if weechat.buffer_get_string(ptr_buffer, 'plugin') != 'irc':
            continue
        localvar_type = weechat.buffer_get_string(ptr_buffer, 'localvar_type')
        localvar_server = weechat.buffer_get_string(ptr_buffer, 'localvar_server')
        if localvar_type != 'channel' or localvar_server != modifier_data:
            continue
#        localvar_channel = weechat.buffer_get_string(buffer, 'localvar_channel')
        if (weechat_nicklist_search_nick(ptr_buffer,parsed['nick'])):
            if weechat.config_get_plugin('no_log').lower() == 'on':
                message_tags = 'no_log'
                weechat.prnt_date_tags(ptr_buffer,0,message_tags,'%s%s\t%s' % (prefix_color,prefix,message))
    weechat.infolist_free(ptr_infolist)

    return string