예제 #1
0
def urlbar_item_cb(data, item, window):
    ''' Callback that prints the lines in the urlbar '''
    global DISPLAY_ALL, urls
    try:
        visible_amount = int(weechat.config_get_plugin('visible_amount'))
    except ValueError:
        weechat.prnt('', 'Invalid value for visible_amount setting.')

    if not urls:
        return 'Empty URL list'

    if DISPLAY_ALL:
        DISPLAY_ALL = False
        printlist = urls
    else:
        printlist = urls[-visible_amount:]

    result = ''
    for index, url in enumerate(printlist):
        if weechat.config_get_plugin('show_index') == 'on':
            index = index+1
            result += '%s%2d%s %s \r' %\
                (weechat.color("yellow"), index, weechat.color("bar_fg"), url)
        else:
            result += '%s%s \r' %(weechat.color('bar_fg'), url)
    return result
예제 #2
0
def close_time_cb(buffer, args):
    """ Callback for check for inactivity and close """

    for buffer in get_all_buffers():
        name = w.buffer_get_string(buffer, "name")

        date = get_last_line_date(buffer)
        date = time.mktime(time.strptime(date, "%Y-%m-%d %H:%M:%S"))
        now = time.time()
        seconds_old = now - date
        if seconds_old > int(w.config_get_plugin("age_limit")) * 60:
            if is_in_hotlist(buffer):
                # w.prnt('', '%s: Not closing buffer: %s: it is in hotlist' %(SCRIPT_NAME, name))
                continue
            if name in w.config_get_plugin("ignore").split(","):
                # w.prnt('', '%s: Not closing buffer: %s: it is in ignore list' %(SCRIPT_NAME, name))
                continue
            if buffer == w.current_buffer():
                # Never close current buffer
                # w.prnt('', '%s: Not closing buffer: %s: it is in currently active' %(SCRIPT_NAME, name))
                continue
            if len(w.buffer_get_string(buffer, "input")):
                # Don't close buffers with text on input line
                # w.prnt('', '%s: Not closing buffer: %s: it has input' %(SCRIPT_NAME, name))
                continue

            w.prnt("", "%s: Closing buffer: %s" % (SCRIPT_NAME, name))
            w.command(buffer, "/buffer close")
        # else:
        #    w.prnt('', '%s: Not closing buffer: %s: it is too new: %s' %(SCRIPT_NAME, name, seconds_old))

    return w.WEECHAT_RC_OK
예제 #3
0
def on_channel_mode(data, signal, signal_data):
    """Whenever a channel mode is set."""

    if w.config_get_plugin("disabled") in ["true", "yes"]:
        return w.WEECHAT_RC_OK

    parsed = w.info_get_hashtable("irc_message_parse", {"message": signal_data})

    server = signal.split(",")[0]
    channel = parsed["channel"]

    if not should_match(server, channel):
        return w.WEECHAT_RC_OK

    chars = w.config_get_plugin("matching_modes")
    modes_set = parsed["text"].split(" ")[0]
    found = False

    for c in chars:
        if c in modes_set:
            found = True
            break

    if not found:
        return w.WEECHAT_RC_OK

    modes = parse_modes(parsed["text"])

    for mode in modes:
        mode["setter"] = parsed["nick"]
        match_mode(server, channel, mode)

    return w.WEECHAT_RC_OK
예제 #4
0
def notify_private_message_or_action(buffername, prefix, message, highlighted):
    '''Notify on private message or action.'''
    regex = re.compile(r'^CTCP_MESSAGE.+?ACTION (.+)$', re.UNICODE)
    match = regex.match(message)
    if match:
        notify_private_action_message(buffername, prefix,
                                      match.group(1), highlighted)
    else:
        if prefix == ' *':
            regex = re.compile(r'^(\w+) (.+)$', re.UNICODE)
            match = regex.match(message)
            if match:
                prefix = match.group(1)
                message = match.group(2)
                notify_private_action_message(buffername, prefix,
                                              message, highlighted)
        else:
            if highlighted:
                notify_highlighted_message(buffername, prefix, message)
            elif (weechat.config_get_plugin("show_private_message") == "on"
                  or (weechat.config_get_plugin("show_private_message") == "away"
                      and STATE['is_away'])):
                a_notify(
                    'Private',
                    'Private Message',
                    '{0}: {1}'.format(prefix, message))
예제 #5
0
def print_matches(target, matches, data):
    """Print all matching masks to the target channel"""

    verbose = w.config_get_plugin("verbose") in ["true", "yes"]
    limit = int(w.config_get_plugin("limit"))

    if limit < 1:
        limit = 1

    total = len(matches)
    if total == 0:
        if verbose or data["mode"] == "special":
            w.prnt(target, "{}\tNo matches for {}".format(fmt_prefix(data).replace("_target_", ""), fmt_banmask(data["mask"])))
        return

    sorting = w.config_get_plugin("sorting")
    if sorting == "alpha":
       matches = sorted(matches)
    elif sorting == "alpha_ignore_case":
       matches = sorted(matches, key=str.lower)

    if w.config_get_plugin("print_as_list") in ["true", "yes"]:
        print_as_list(target, matches, data, limit, total)
    else:
        print_as_lines(target, matches, data, limit, total)
예제 #6
0
def privmsg(data, signal, signal_data):
    (server, signal) = signal.split(",")
    channels = wc.config_get_plugin('channels').replace(',', '|')
    api_key = wc.config_get_plugin('api_key')
    if re.match('^\${sec\.data\.(.*)}$', api_key):
        api_key = wc.string_eval_expression(api_key, {}, {}, {})
    bots_list = wc.config_get_plugin('other_bots').split(",")
    details = wc.info_get_hashtable("irc_message_parse", {"message": signal_data, "server": server})
    youtube_regex_match = re.compile(r'(.*https?://)?(www\.)?(youtube|youtu|youtube-nocookie)\.(com|be)/(watch\?v=|embed/|v/|.+\?v=)?([a-zA-Z0-9_-]{11})').match(details['text'])
    buffer_name = details['channel']
    buffer_pointer = wc.info_get("irc_buffer", "%s,%s" % (server, buffer_name))
    channels_regex = re.compile(r'(%s)' % (channels), re.I)
    bots_exist = False
    if channels_regex.match(buffer_name) and youtube_regex_match:
        if not bots_list == "not_set":
            for other_bots in bots_list:
                bots_test = wc.nicklist_search_nick(buffer_pointer, "", other_bots)
                if bots_test:
                    bots_exist = True
        if not bots_exist:
            if not api_key == "not_set":
                vid_id = youtube_regex_match.group(6)
                rvt = requests.get('https://www.googleapis.com/youtube/v3/videos/?id={0}&part=snippet&key={1}'.format(vid_id, api_key))
                rvc = requests.get('https://www.googleapis.com/youtube/v3/videos/?id={0}&part=statistics&key={1}'.format(vid_id, api_key))
                try:
                    vid_title = rvt.json()['items'][0]['snippet']['title'].encode('utf-8')
                    vid_channel = rvt.json()['items'][0]['snippet']['channelTitle'].encode('utf-8')
                    vid_views = rvc.json()['items'][0]['statistics']['viewCount']
                    wc.command("", r"/msg {0} [Youtube] {1} | Channel: {2} | Views: {3}".format(buffer_name, vid_title, vid_channel, vid_views))
                except:
                    wc.command("", r"/msg {0} [Youtube] Error getting video info.".format(buffer_name))
            else:
                wc.command("", r"/msg {0} Youtube api key not set.".format(buffer_name))
    return wc.WEECHAT_RC_OK
예제 #7
0
def notify_msg(data, bufferp, time, tags, display, is_hilight, prefix, msg):
    """Sends highlighted message to be printed on notification"""

    if ('notify_private' in tags and
        weechat.config_get_plugin('show_priv_msg') == "on") \
        or (int(is_hilight) and \
        weechat.config_get_plugin('show_hilights') == "on"):

        # grab the fully qualified buffer name so we can jump to it later
        buffer = weechat.buffer_get_string(bufferp, "name")

        # choose an appropriate brief name to display in the indicator applet
        if 'notify_private' in tags:
            brief = "private"
        else:
            # prefer short_name
            brief = weechat.buffer_get_string(bufferp, "short_name")
            if not brief:
                # fall back to full name
                brief = buffer

        if weechat.config_get_plugin('debug') == "on":
            print "buffer: " + buffer
            print "brief: " + brief
            print "prefix: " + prefix
            print "msg: " + msg

        # Create an object that will proxy for a particular remote object.
        bus = dbus.SessionBus()
        remote_object = bus.get_object(DBUS_CONNECTION, DBUS_OBJ_PATH)
        remote_object.add_message(buffer, brief, prefix, msg)

    return weechat.WEECHAT_RC_OK
예제 #8
0
def format_weather(weather_data):
    '''
    Formats the weather data dictionary received from Google

    Returns:
      output: a string of formatted weather data.
    '''
    output = weechat.color(weechat.config_get_plugin('output_color')) + weechat.config_get_plugin('format')
    output = output.replace('%C', weechat.config_get_plugin('city'))

    temp = 'N/A'
    condition = 'N/A'

    if weather_data:
        if len(weather_data['current_conditions']):
            if weechat.config_get_plugin('unit') == 'F':
                temp = weather_data['current_conditions']['temp_f'].encode('utf-8')
            else:
                temp = weather_data['current_conditions']['temp_c'].encode('utf-8')

            if weather_data['current_conditions'].has_key('condition'):
                condition = weather_data['current_conditions']['condition'].encode('utf-8')

    output = output.replace('%D', temp)
    output = output.replace('%O', condition)
    output = output.replace('%U', weechat.config_get_plugin('unit'))

    output += weechat.color('reset')

    return output
예제 #9
0
def find_and_process_urls(string, use_color=True):
    new_message = string
    color = weechat.color(weechat.config_get_plugin("color"))
    reset = weechat.color('reset')

    for url in urlRe.findall(string):
        max_url_length = int(weechat.config_get_plugin('urllength'))

        if len(url) > max_url_length and not should_ignore_url(url):
            short_url = get_shortened_url(url)
            if use_color:
                new_message = new_message.replace(
                    url, '%(url)s %(color)s[%(short_url)s]%(reset)s' % dict(
                        color=color,
                        short_url=short_url,
                        reset=reset,
                        url=url
                    )
                )
            else:
                new_message = new_message.replace(url, short_url)
        elif use_color:
            # Highlight the URL, even if we aren't going to shorting it
            new_message = new_message.replace(
                url, '%(color)s %(url)s %(reset)s' % dict(
                    color=color,
                    reset=reset,
                    url=url
                )
            )

    return new_message
예제 #10
0
def get_recent_track(data, command, rc, out, err):
    """Get last track played (artist - name)"""
    if rc == weechat.WEECHAT_HOOK_PROCESS_ERROR:
        weechat.prnt('', "Error with command '{}'".format(command))
    elif rc > 0:
        weechat.prnt('', "rc = {}".format(rc))

    try:
        data = json.loads(out)

        if data.has_key('error'):
            weechat.prnt('', "Last.fm API error: '{}'".format(data['message']))
        else:
            artist = data['recenttracks']['track'][0]['artist']['#text']
            name = data['recenttracks']['track'][0]['name']
            track = "{} - {}".format(artist, name)
            user = data['recenttracks']['@attr']['user'].lower()

            # print username or not, depending on config/arg
            if user == weechat.config_get_plugin('user').lower():
                cmd = weechat.config_get_plugin('command')
            else:
                cmd = weechat.config_get_plugin('command_arg')

            # format isn't picky, ignores {user} if not present
            cmd = cmd.format(user=user, track=track)

            weechat.command(weechat.current_buffer(), cmd)
    except IndexError, KeyError:
        weechat.prnt('', "Error parsing Last.fm data")
예제 #11
0
def format_shared_channels(channels, current_channels):
    """Take a list of channels and format it into a displayable string"""

    count_shared = len(channels["shared"])
    count_total = len(current_channels)
    verbose = w.config_get_plugin("verbose_output") in ["true", "on"]
    output_priority = w.config_get_plugin("output_priority")

    if count_total == count_shared:
        if verbose:
            return "All channels are shared"
        return None

    if not count_shared:
        if verbose:
            return "No channels are shared"
        return None

    if output_priority == "not_shared" or (output_priority == "smart" and count_shared > count_total / 2):
        output = ", ".join(sort_output(channels["not_shared"]))
        append = ", not sharing"
    else:
        output = ", ".join(sort_output(channels["shared"]))
        append = ""

    return "Sharing {}/{} channels{}: {}".format(count_shared, count_total, append, output)
예제 #12
0
def init_options():
    for option,value in OPTIONS.items():
        if not weechat.config_get_plugin(option):
          weechat.config_set_plugin(option, value[0])
        else:
            OPTIONS[option] = weechat.config_get_plugin(option)
        weechat.config_set_desc_plugin(option, '%s (default: "%s")' % (value[1], value[0]))
예제 #13
0
파일: tts.py 프로젝트: DarkDefender/scripts
def tts(text):
    """Pronounce the text"""
    engine = weechat.config_get_plugin('tts_engine')
    lang = weechat.config_get_plugin('language')
    if engine == 'espeak':
        args = {'arg1':text}
        if lang:
            args['arg2'] = '-v'
            args['arg3'] = lang
        hook = weechat.hook_process_hashtable('espeak',args,0,'my_process_cb','')
    elif engine == 'festival':
        args = {'stdin':'1', 'arg1':'festival', 'arg2':'--tts'}
        if lang:
            args['arg3'] = '--language'
            args['arg4'] = lang
        hook = weechat.hook_process_hashtable('festival',args,0,'my_process_cb','')
        weechat.hook_set(hook, "stdin", text)
        weechat.hook_set(hook, "stdin_close", "")
    elif engine == 'picospeaker':
        args = {'stdin':'1'}
        if lang:
            args['arg1'] = '-l'
            args['arg2'] = lang
        hook = weechat.hook_process_hashtable('picospeaker',args,0,'my_process_cb','')
        weechat.hook_set(hook, "stdin", text)
        weechat.hook_set(hook, "stdin_close", "")
예제 #14
0
파일: tweetim.py 프로젝트: s5unty/dotfiles
def parse_out (server, modifier, data, the_string):
    '''Parses outgoing messages, provides @nick completion and url shortening'''
    # data => localhost
    # the_string => PRIVMSG update :help
    # server => 
    # modifier => irc_out_PRIVMSG

    command, buffer, message = the_string.split(' ', 2)
    channel = '.'.join([data, buffer])

    if channel == weechat.config_get_plugin('channel'):
        completion_blacklist = weechat.config_get_plugin('completion_blacklist').split(',')

        # the regexp will match any word that is not preceded by [@#!]
        # oddly, for "@fauno", it will match "auno", when the opposite
        # "(?<=[@#!])\w+" matches the full word with prefix ("@fauno")
        # nevertheless, it breaks the word, so it'll never match an
        # already prefixed nick, hashtag nor group name.
        for word in re.findall(r'[\S]+[^\W]', message, re.UNICODE):
            if word in users and not word in completion_blacklist:
                message = re.sub(r''.join(['(?<![#@!])',word]), ''.join(['@', word]), message)

        if weechat.config_get_plugin('shorten') == 'on':
            u = ur1(weechat.config_get_plugin('shorten_service'))
            for url in re.findall(r'http://[^ ]*', message, re.UNICODE):
                if len(url) > 20:
                    s = u.shorten(url)
                    if s != False:
                        message = message.replace(url, s)

        the_string = ' '.join([command, buffer, message])

    return the_string
예제 #15
0
파일: screen_away.py 프로젝트: ronin13/seed
def screen_away_timer_cb(buffer, args):
    '''Check if screen is attached, update awayness'''

    global AWAY, SOCK

    suffix = w.config_get_plugin('away_suffix')
    attached = os.access(SOCK, os.X_OK) # X bit indicates attached

    if attached and AWAY:
        w.prnt('', '%s: Screen attached. Clearing away status' % SCRIPT_NAME)
        for server, nick in get_servers():
            w.command(server,  "/away")
            if suffix and nick.endswith(suffix):
                nick = nick[:-len(suffix)]
                w.command(server,  "/nick %s" % nick)
        AWAY = False

    elif not attached and not AWAY:
        w.prnt('', '%s: Screen detached. Setting away status' % SCRIPT_NAME)
        for server, nick in get_servers():
            if suffix:
                w.command(server, "/nick %s%s" % (nick, suffix));
            w.command(server, "/away %s" % w.config_get_plugin('message'));
        AWAY = True
        if w.config_get_plugin("command_on_detach"):
            w.command("", w.config_get_plugin("command_on_detach"))

    return w.WEECHAT_RC_OK
def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed,
        ishilight, prefix, message):

    # irc PMs are caught by notify_private, but we need notify_message to
    # capture hilights in channels.
    if 'notify_message' in tagsn and not ishilight:
        return weechat.WEECHAT_RC_OK

    # are we away?
    away = weechat.buffer_get_string(bufferp,"localvar_away")
    if (away == "" and weechat.config_get_plugin("only_away") == "on"):
        return weechat.WEECHAT_RC_OK

    # get local nick for buffer
    mynick = weechat.buffer_get_string(bufferp,"localvar_nick")

    # get buffer info
    name = weechat.buffer_get_string(bufferp,"name")
    server = weechat.buffer_get_string(bufferp, "localvar_server")
    channel = weechat.buffer_get_string(bufferp, "localvar_channel")

    # ignore buffers on ignorelists
    if not (server in weechat.config_get_plugin("ignore_servers") or
        name in weechat.config_get_plugin("ignore_buffers").split(",")):

        # only notify if the message was not sent by myself
        if (weechat.buffer_get_string(bufferp, "localvar_type") == "private") and (prefix!=mynick):
            show_notification(channel, prefix, message)

        elif ishilight == "1":
            buffer = (weechat.buffer_get_string(bufferp, "short_name") or name)
            show_notification(buffer, prefix, message)

    return weechat.WEECHAT_RC_OK
예제 #17
0
def vdm_display(vdm):
    """ Display VDMs in buffer. """
    global vdm_buffer
    weechat.buffer_set(vdm_buffer, "unread", "1")
    if weechat.config_get_plugin("number_as_prefix") == "on":
        separator = "\t"
    else:
        separator = " > "
    colors = weechat.config_get_plugin("colors").split(";");
    vdm2 = vdm[:]
    if weechat.config_get_plugin("reverse") == "on":
        vdm2.reverse()
    for index, item in enumerate(vdm2):
        item_id = item["id"]
        item_text = item["text"]
        if sys.version_info < (3,):
            # python 2.x: convert unicode to str (in python 3.x, id and text are already strings)
            item_id = item_id.encode("UTF-8")
            item_text = item_text.encode("UTF-8")
        weechat.prnt_date_tags(vdm_buffer,
                               0, "notify_message",
                               "%s%s%s%s%s" %
                               (weechat.color(weechat.config_get_plugin("color_number")),
                                item_id,
                                separator,
                                weechat.color(colors[0]),
                                item_text))
        colors.append(colors.pop(0))
        if index == len(vdm) - 1:
            weechat.prnt(vdm_buffer, "------")
        elif weechat.config_get_plugin("blank_line") == "on":
            weechat.prnt(vdm_buffer, "")
예제 #18
0
파일: go.py 프로젝트: Gres/dotfiles
def go_buffers_to_string(listbuf, pos, strinput):
    """Return string built with list of buffers found (matching user input)."""
    string = ''
    strinput = strinput.lower()
    for i in range(len(listbuf)):
        selected = '_selected' if i == pos else ''
        index = listbuf[i]['name'].lower().find(strinput)
        if index >= 0:
            index2 = index + len(strinput)
            name = '%s%s%s%s%s' % (
                listbuf[i]['name'][:index],
                weechat.color(weechat.config_get_plugin(
                    'color_name_highlight' + selected)),
                listbuf[i]['name'][index:index2],
                weechat.color(weechat.config_get_plugin(
                    'color_name' + selected)),
                listbuf[i]['name'][index2:])
        else:
            name = listbuf[i]['name']
        string += ' %s%s%s%s%s' % (
            weechat.color(weechat.config_get_plugin(
                'color_number' + selected)),
            str(listbuf[i]['number']),
            weechat.color(weechat.config_get_plugin(
                'color_name' + selected)),
            name,
            weechat.color('reset'))
    return '  ' + string if string else ''
예제 #19
0
def a_notify(bname, nclass, title, description, priority=pynotify.URGENCY_LOW):
    '''Creates or updates the notification'''
    is_away = STATE['is_away']
    icon = STATE['icon']
    time_out = int(weechat.config_get_plugin("timeout"))
    cur_time = time.time()
    threshold = 1.0
    refresh = 0.01

    try:
        BUFFERS[bname].append(
                description,
                merge=weechat.config_get_plugin("merge") == "on",
                )
    except KeyError:
        BUFFERS[bname] = BufferState(
                title,
                threshold,
                refresh,
                icon=icon,
                priority=priority,
                timeout=time_out,
                )
        BUFFERS[bname].append(
                description,
                merge=weechat.config_get_plugin("merge") == "on",
                )
        weechat.hook_timer(500, 0, 1, "cb_buffer_start", bname)
예제 #20
0
파일: title.py 프로젝트: aimeeble/dotfiles
def update_title(data, signal, signal_data):
    ''' The callback that adds title. '''

    if w.config_get_plugin('short_name') == 'on':
        title = w.buffer_get_string(w.current_buffer(), 'short_name')
    else:
        title = w.buffer_get_string(w.current_buffer(), 'name')

    hotlist = w.infolist_get('hotlist', '', '')
    hot_text = ''
    while w.infolist_next(hotlist):
        priority = w.infolist_integer(hotlist, 'priority')
        if priority >= int(w.config_get_plugin('title_priority')):
            number = w.infolist_integer(hotlist, 'buffer_number')
            thebuffer = w.infolist_pointer(hotlist, 'buffer_pointer')
            name = w.buffer_get_string(thebuffer, 'short_name')

            hot_text += ' %s' % number
    if hot_text:
        title += ' [A:%s]' % hot_text
    w.infolist_free(hotlist)

    w.window_set_title(title)

    return w.WEECHAT_RC_OK
예제 #21
0
def encrypt(data, msgtype, servername, args):
  pre, message = string.split(args, ":", 1)
  prestr=pre.split(" ")
  username=prestr[-2]
  if os.path.exists(weechat_dir + "/cryptkey." + username):
    p = subprocess.Popen(["openssl", "enc", "-a", "-" + weechat.config_get_plugin("cipher"), "-pass" ,"file:" + weechat_dir + "/cryptkey." + username], bufsize=4096, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
    p.stdin.write(message)
    p.stdin.close()
    encrypted = p.stdout.read()
    p.stdout.close()
    encrypted = encrypted.replace("\n","|")
    if len(encrypted) > 400:
      splitmsg=string.split(message," ")
      cutpoint=len(splitmsg)/2
      p = subprocess.Popen(["openssl", "enc", "-a", "-" + weechat.config_get_plugin("cipher"), "-pass" ,"file:" + weechat_dir + "/cryptkey." + username], bufsize=4096, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
      p.stdin.write(string.join(splitmsg[:cutpoint]," ") + "\n")
      p.stdin.close()
      encrypted = p.stdout.read()
      p.stdout.close()
      encrypted = encrypted.replace("\n","|")
      p = subprocess.Popen(["openssl", "enc", "-a", "-" + weechat.config_get_plugin("cipher"), "-pass" ,"file:" + weechat_dir + "/cryptkey." + username], bufsize=4096, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
      p.stdin.write( string.join(splitmsg[cutpoint:]," ") )
      p.stdin.close()
      encrypted2 = p.stdout.read()
      p.stdout.close()
      encrypted2 = encrypted2.replace("\n","|")
      encrypted = encrypted + "\n" + pre + ":" + encrypted2[10:]
    return pre + ":" + encrypted[10:]
  else:
    return args
예제 #22
0
파일: surl.py 프로젝트: eBrnd/sURL
def make_redirect(url, target):
	template = """<!DOCTYPE html>
<html>
	<head>
		<title>Redirect</title>
		<meta http-equiv="refresh" content="0; url=%s" />
	</head>
	<body>
		Redirecting to %s.<br/>
		Click <a href="%s">here</a> to proceed
	</body>
</html>
"""
	url = url.replace("&", "&amp;")

	dir = weechat.config_get_plugin("directory")
	try:
		id = 0
		last_file = os.path.join(dir, ".last")
		if os.path.isfile(last_file):
			with open(last_file) as last:
				id = int(last.readline(30).strip())
		id = id + 1
		with open(last_file, "w+") as last:
			last.write(str(id))
		redir_name = str(id) + weechat.config_get_plugin("suffix")
		with open(os.path.join(dir, redir_name), "w+") as redirector:
			redirector.write(template % (url, url, url))
		weechat.prnt(target, "[AKA] %s/%s" % (weechat.config_get_plugin("prefix"), redir_name))
	except:
		weechat.prnt(target, "[sURL] Could not create file")
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_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
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
예제 #26
0
def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed,
        ishilight, prefix, message):

    #are we away?
    away = weechat.buffer_get_string(bufferp,"localvar_away")
    if (away == "" and weechat.config_get_plugin("only_away") == "on"):
        return weechat.WEECHAT_RC_OK
        
    #get local nick for buffer
    mynick = weechat.buffer_get_string(bufferp,"localvar_nick")

    # get name of buffer
    name = weechat.buffer_get_string(bufferp,"name")

    # ignore buffers on ignorelist
    if not name in weechat.config_get_plugin("ignore").split(","):
        # only notify if the message was not sent by myself
        if (weechat.buffer_get_string(bufferp, "localvar_type") == "private") and (prefix!=mynick):
            show_notification(prefix, prefix, message)

        elif ishilight == "1":
            buffer = (weechat.buffer_get_string(bufferp, "short_name") or name)
            show_notification(buffer, prefix, message)

    return weechat.WEECHAT_RC_OK
예제 #27
0
def decrypt(data, msgtype, servername, args):
  hostmask, chanmsg = string.split(args, "PRIVMSG ", 1)
  channelname, message = string.split(chanmsg, " :", 1)
  if re.match(r'^\[\d{2}:\d{2}:\d{2}]\s', message):
    timestamp = message[:11]
    message = message[11:]
  else:
    timestamp = ''
  if channelname[0] == "#":
    username=channelname
  else:
    username, rest = string.split(hostmask, "!", 1)
    username = username[1:]
  if os.path.exists(weechat_dir + "/cryptkey." + username):
    p = subprocess.Popen(["openssl", "enc", "-d", "-a", "-" + weechat.config_get_plugin("cipher"), "-pass" ,"file:" + weechat_dir + "/cryptkey." + username], bufsize=4096, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
    p.stdin.write("U2FsdGVkX1" + message.replace("|","\n"))
    p.stdin.close()
    decrypted = p.stdout.read()
    p.stdout.close()
    if decrypted == "":
      return args
    decrypted = ''.join(c for c in decrypted if ord(c) > 31 or ord(c) == 9 or ord(c) == 2 or ord(c) == 3 or ord(c) == 15)
    return hostmask + "PRIVMSG " + channelname + " :" + chr(3) + "04" + weechat.config_get_plugin("message_indicator") + chr(15) + timestamp + decrypted
  else:
    return args
예제 #28
0
def spotify_print_cb(data, buffer, time, tags, displayed, highlight, prefix,
                     message):
    notice = w.config_get_plugin('emit_notice')
    buffer_name = w.buffer_get_string(buffer, "name")
    server, channel = buffer_name.split('.')
    buffers_to_check = w.config_get_plugin('buffers').split(',')
    client_credentials_manager = SpotifyClientCredentials(
        get_oauth('client_id'), get_oauth('client_secret'))
    spotify = spotipy.Spotify(
        client_credentials_manager=client_credentials_manager)

    command = "msg"
    if notice == "on":
        command = "notice"

    if buffer_name.lower() not in [
            buffer.lower() for buffer in buffers_to_check
    ]:
        return w.WEECHAT_RC_OK

    for type, id in get_spotify_ids(message):
        if type == 'album':
            results = spotify.album(id)
        elif type == 'track':
            results = spotify.track(id)
        elif type == 'artist':
            results = spotify.artist(id)
        reply = parse_response(results, type)
        w.command('', "/%s -server %s %s %s" % (command, server, channel,
                                                reply))
    return w.WEECHAT_RC_OK
예제 #29
0
def keydict_update(*args):
    '''Populate a python dictionary with relevant key=>buffer mappings.'''

    global keydict

    keylist = w.infolist_get('key', '', '')
    if w.config_get_plugin('use_keybindings') == 'on':
        while w.infolist_next(keylist):
            key = w.infolist_string(keylist, 'key')
            # we dont want jump sequences
            if 'j' in key:
                continue
            key = key.replace('meta-', '')
            key = key.replace('ctrl-', '^')
            if w.config_get_plugin('skip_number_binds') == 'on':
                # skip entries where buffer number = key, typically entries below 11
                if key.isdigit():
                    continue
            command = w.infolist_string(keylist, 'command')
            # we only care about commands that leads to buffers
            if command.startswith('/buffer'):
                command = command.replace('/buffer ', '')
                buffer = command.lstrip('*')
                keydict[buffer] = key
    w.infolist_free(keylist)
    return w.WEECHAT_RC_OK
예제 #30
0
def conf_update_cb(data, option, value):
    #Commit data if not part of ignore list.
    if weechat.config_get_plugin("commit_each_change") == "true"  and not option in weechat.config_get_plugin("auto_commit_ignore").split(","):
        #Call use pause else /save will be called before the config is actually saved to disc
        #This is kinda hack but better input would be appricated.
        weechat.hook_timer(500, 0, 1, "commit_cb", "")
    return weechat.WEECHAT_RC_OK
예제 #31
0
def docgen_cmd_cb(data, buf, args):
    """Callback for /docgen command."""
    if args:
        locales = args.split(' ')
    else:
        locales = LOCALE_LIST
    commands = get_commands()
    options = get_options()
    infos = get_infos()
    infos_hashtable = get_infos_hashtable()
    infolists = get_infolists()
    hdata = get_hdata()
    completions = get_completions()
    url_options = get_url_options()
    default_aliases = get_default_aliases()
    irc_colors = get_irc_colors()
    plugins_priority = get_plugins_priority()

    # get path and replace ~ by home if needed
    path = weechat.config_get_plugin('path')
    if path.startswith('~'):
        path = os.environ['HOME'] + path[1:]

    # write to doc files, by locale
    num_files = defaultdict(int)
    num_files_updated = defaultdict(int)

    # pylint: disable=undefined-variable
    translate = lambda s: (s and _(s)) or s
    escape = lambda s: s.replace('|', '\\|')

    for locale in locales:
        for key in num_files:
            if key != 'total2':
                num_files[key] = 0
                num_files_updated[key] = 0
        trans = gettext.translation('weechat',
                                    weechat.info_get('weechat_localedir', ''),
                                    languages=[locale + '.UTF-8'],
                                    fallback=True)
        trans.install()
        directory = path + '/' + locale[0:2] + '/autogen'
        if not os.path.isdir(directory):
            weechat.prnt(
                '', '{0}docgen error: directory "{1}" does not exist'
                ''.format(weechat.prefix('error'), directory))
            continue

        # write commands
        for plugin in commands:
            doc = AutogenDoc(directory, 'user', plugin + '_commands')
            for i, command in enumerate(sorted(commands[plugin])):
                if i > 0:
                    doc.write('\n')
                _cmd = commands[plugin][command]
                args = translate(_cmd['args'])
                args_formats = args.split(' || ')
                desc = translate(_cmd['description'])
                args_desc = translate(_cmd['args_description'])
                doc.write('[[command_{0}_{1}]]\n'.format(plugin, command))
                doc.write('* `+{0}+`: {1}\n\n'.format(command, desc))
                doc.write('----\n')
                prefix = '/' + command + '  '
                if args_formats != ['']:
                    for fmt in args_formats:
                        doc.write(prefix + fmt + '\n')
                        prefix = ' ' * len(prefix)
                if args_desc:
                    doc.write('\n')
                    for line in args_desc.split('\n'):
                        doc.write(line + '\n')
                doc.write('----\n')
            doc.update('commands', num_files, num_files_updated)

        # write config options
        for config in options:
            doc = AutogenDoc(directory, 'user', config + '_options')
            i = 0
            for section in sorted(options[config]):
                for option in sorted(options[config][section]):
                    if i > 0:
                        doc.write('\n')
                    i += 1
                    _opt = options[config][section][option]
                    opt_type = _opt['type']
                    string_values = _opt['string_values']
                    default_value = _opt['default_value']
                    opt_min = _opt['min']
                    opt_max = _opt['max']
                    null_value_allowed = _opt['null_value_allowed']
                    desc = translate(_opt['description'])
                    type_nls = translate(opt_type)
                    values = ''
                    if opt_type == 'boolean':
                        values = 'on, off'
                    elif opt_type == 'integer':
                        if string_values:
                            values = string_values.replace('|', ', ')
                        else:
                            values = '{0} .. {1}'.format(opt_min, opt_max)
                    elif opt_type == 'string':
                        if opt_max <= 0:
                            values = _('any string')
                        elif opt_max == 1:
                            values = _('any char')
                        elif opt_max > 1:
                            values = '{0} ({1}: {2})'.format(
                                _('any string'), _('max chars'), opt_max)
                        else:
                            values = _('any string')
                        default_value = '"{0}"'.format(
                            default_value.replace('"', '\\"'))
                    elif opt_type == 'color':
                        values = _('a WeeChat color name (default, black, '
                                   '(dark)gray, white, (light)red, '
                                   '(light)green, brown, yellow, (light)blue, '
                                   '(light)magenta, (light)cyan), a terminal '
                                   'color number or an alias; attributes are '
                                   'allowed before color (for text color '
                                   'only, not background): \"*\" for bold, '
                                   '\"!\" for reverse, \"/\" for italic, '
                                   '\"_\" for underline')
                    doc.write('* [[option_{0}.{1}.{2}]] *{3}.{4}.{5}*\n'
                              ''.format(config, section, option, config,
                                        section, option))
                    doc.write('** {0}: pass:none[{1}]\n'.format(
                        _('description'), desc.replace(']', '\\]')))
                    doc.write('** {0}: {1}\n'.format(_('type'), type_nls))
                    doc.write('** {0}: {1}\n'.format(_('values'), values))
                    doc.write('** {0}: `+{1}+`\n'
                              ''.format(_('default value'), default_value))
                    if null_value_allowed:
                        doc.write('** {0}\n'.format(
                            _('undefined value allowed (null)')))
            doc.update('options', num_files, num_files_updated)

        # write default aliases
        doc = AutogenDoc(directory, 'user', 'alias_default_aliases')
        doc.write('[width="100%",cols="2m,5m,5",options="header"]\n')
        doc.write('|===\n')
        doc.write('| {0} | {1} | {2}\n\n'
                  ''.format(_('Alias'), _('Command'), _('Completion')))
        for alias in default_aliases:
            doc.write('| {0} | {1} | {2}\n'
                      ''.format(escape(alias['name']),
                                escape(alias['command']),
                                escape(alias['completion'] or '-')))
        doc.write('|===\n')
        doc.update('alias_default_aliases', num_files, num_files_updated)

        # write IRC colors
        doc = AutogenDoc(directory, 'user', 'irc_colors')
        doc.write('[width="30%",cols="^2m,3",options="header"]\n')
        doc.write('|===\n')
        doc.write('| {0} | {1}\n\n'
                  ''.format(_('IRC color'), _('WeeChat color')))
        for color in irc_colors:
            doc.write('| {0} | {1}\n'
                      ''.format(escape(color['color_irc']),
                                escape(color['color_weechat'])))
        doc.write('|===\n')
        doc.update('irc_colors', num_files, num_files_updated)

        # write infos hooked
        doc = AutogenDoc(directory, 'plugin_api', 'infos')
        doc.write('[width="100%",cols="^1,^2,6,6",options="header"]\n')
        doc.write('|===\n')
        doc.write('| {0} | {1} | {2} | {3}\n\n'
                  ''.format(_('Plugin'), _('Name'), _('Description'),
                            _('Arguments')))
        for plugin in sorted(infos):
            for info in sorted(infos[plugin]):
                _inf = infos[plugin][info]
                desc = translate(_inf['description'])
                args_desc = translate(_inf['args_description'] or '-')
                doc.write('| {0} | {1} | {2} | {3}\n\n'
                          ''.format(escape(plugin), escape(info), escape(desc),
                                    escape(args_desc)))
        doc.write('|===\n')
        doc.update('infos', num_files, num_files_updated)

        # write infos (hashtable) hooked
        doc = AutogenDoc(directory, 'plugin_api', 'infos_hashtable')
        doc.write('[width="100%",cols="^1,^2,6,6,8",options="header"]\n')
        doc.write('|===\n')
        doc.write('| {0} | {1} | {2} | {3} | {4}\n\n'
                  ''.format(_('Plugin'), _('Name'), _('Description'),
                            _('Hashtable (input)'), _('Hashtable (output)')))
        for plugin in sorted(infos_hashtable):
            for info in sorted(infos_hashtable[plugin]):
                _inh = infos_hashtable[plugin][info]
                desc = translate(_inh['description'])
                args_desc = translate(_inh['args_description'])
                output_desc = translate(_inh['output_description']) or '-'
                doc.write('| {0} | {1} | {2} | {3} | {4}\n\n'
                          ''.format(escape(plugin), escape(info), escape(desc),
                                    escape(args_desc), escape(output_desc)))
        doc.write('|===\n')
        doc.update('infos_hashtable', num_files, num_files_updated)

        # write infolists hooked
        doc = AutogenDoc(directory, 'plugin_api', 'infolists')
        doc.write('[width="100%",cols="^1,^2,5,5,5",options="header"]\n')
        doc.write('|===\n')
        doc.write('| {0} | {1} | {2} | {3} | {4}\n\n'
                  ''.format(_('Plugin'), _('Name'), _('Description'),
                            _('Pointer'), _('Arguments')))
        for plugin in sorted(infolists):
            for infolist in sorted(infolists[plugin]):
                _inl = infolists[plugin][infolist]
                desc = translate(_inl['description'])
                pointer_desc = translate(_inl['pointer_description']) or '-'
                args_desc = translate(_inl['args_description']) or '-'
                doc.write('| {0} | {1} | {2} | {3} | {4}\n\n'
                          ''.format(escape(plugin), escape(infolist),
                                    escape(desc), escape(pointer_desc),
                                    escape(args_desc)))
        doc.write('|===\n')
        doc.update('infolists', num_files, num_files_updated)

        # write hdata hooked
        doc = AutogenDoc(directory, 'plugin_api', 'hdata')
        doc.write(':hdata_update_create: __create\n')
        doc.write(':hdata_update_delete: __delete\n')
        doc.write('[width="100%",cols="^1,^2,2,2,5",options="header"]\n')
        doc.write('|===\n')
        doc.write('| {0} | {1} | {2} | {3} | {4}\n\n'
                  ''.format(_('Plugin'), _('Name'), _('Description'),
                            _('Lists'), _('Variables')))
        for plugin in sorted(hdata):
            for hdata_name in sorted(hdata[plugin]):
                _hda = hdata[plugin][hdata_name]
                anchor = 'hdata_{0}'.format(hdata_name)
                desc = translate(_hda['description'])
                variables = _hda['vars']
                variables_update = _hda['vars_update']
                lists = _hda['lists']
                doc.write('| {0}\n'.format(escape(plugin)))
                doc.write('| [[{0}]]<<{0},{1}>>\n'
                          ''.format(escape(anchor), escape(hdata_name)))
                doc.write('| {0}\n'.format(escape(desc)))
                doc.write('| {0}\n'.format(escape(lists) if lists else '-'))
                doc.write('| {0}\n'.format(escape(variables)))
                if variables_update:
                    doc.write('*{0}* +\n{1}'.format(_('Update allowed:'),
                                                    escape(variables_update)))
                doc.write('\n')
        doc.write('|===\n')
        doc.update('hdata', num_files, num_files_updated)

        # write completions hooked
        doc = AutogenDoc(directory, 'plugin_api', 'completions')
        doc.write('[width="100%",cols="^1,^2,7",options="header"]\n')
        doc.write('|===\n')
        doc.write('| {0} | {1} | {2}\n\n'
                  ''.format(_('Plugin'), _('Name'), _('Description')))
        for plugin in sorted(completions):
            for completion_item in sorted(completions[plugin]):
                _cmp = completions[plugin][completion_item]
                desc = translate(_cmp['description'])
                doc.write('| {0} | {1} | {2}\n\n'
                          ''.format(escape(plugin), escape(completion_item),
                                    escape(desc)))
        doc.write('|===\n')
        doc.update('completions', num_files, num_files_updated)

        # write url options
        doc = AutogenDoc(directory, 'plugin_api', 'url_options')
        doc.write('[width="100%",cols="2,^1,7",options="header"]\n')
        doc.write('|===\n')
        doc.write('| {0} | {1} | {2}\n\n'
                  ''.format(_('Option'),
                            _('Type') + ' ^(1)^',
                            _('Constants') + ' ^(2)^'))
        for option in url_options:
            constants = option['constants']
            if constants:
                constants = ' ' + constants
            doc.write('| {0} | {1} |{2}\n\n'
                      ''.format(escape(option['name']), escape(option['type']),
                                escape(constants)))
        doc.write('|===\n')
        doc.update('url_options', num_files, num_files_updated)

        # write plugins priority
        doc = AutogenDoc(directory, 'plugin_api', 'plugins_priority')
        for priority in sorted(plugins_priority, reverse=True):
            plugins = ', '.join(sorted(plugins_priority[priority]))
            doc.write('. {0} ({1})\n'.format(escape(plugins), priority))
        doc.update('plugins_priority', num_files, num_files_updated)

        # write counters
        weechat.prnt(
            '', 'docgen: {0}: {1} files, {2} updated'
            ''.format(locale, num_files['total1'],
                      num_files_updated['total1']))
    weechat.prnt(
        '', 'docgen: total: {0} files, {1} updated'
        ''.format(num_files['total2'], num_files_updated['total2']))
    return weechat.WEECHAT_RC_OK
예제 #32
0
 def check_config(self):
     for opt in self.opts:
         self.opts[opt] = weechat.config_get_plugin(opt)
예제 #33
0
 def init_config(self):
     for opt, value in self.opts.items():
         temp = weechat.config_get_plugin(opt)
         if not len(temp):
             weechat.config_set_plugin(opt, value)
예제 #34
0
def init_config():
    global default_options, options
    for option, default_value in default_options.items():
        if not weechat.config_is_set_plugin(option):
            weechat.config_set_plugin(option, default_value)
        options[option] = weechat.config_get_plugin(option)
예제 #35
0
def get_ignored_channels():
    ignored_channels = w.config_get_plugin("ignored_channels")
    if ignored_channels == "":
        return []
    else:
        return [channel.strip() for channel in ignored_channels.split(',')]
예제 #36
0
def debug(msg):
    if str(w.config_get_plugin("debug")) is not "0":
        w.prnt("", "[weebullet] DEBUG: %s" % str(msg))
예제 #37
0
configs = {
    "api_key": REQUIRED,
    "away_only": "1",  # only send when away
    "device_iden": "all",  # send to all devices
    "ignored_channels": "",  # no ignored channels
    "min_notify_interval": "0",  # seconds, don't notify
    #   more often than this
    "debug": "0",  # enable debugging
    "ignore_on_relay": "0",  # if relay connected,
    #   don't send push notification
}

last_notification = 0  # 0 seconds from the epoch

for option, default_value in configs.items():
    if w.config_get_plugin(option) == "":
        if configs[option] == REQUIRED:
            w.prnt(
                "",
                w.prefix("error") +
                "pushbullet: Please set option: %s" % option)
            if type(default_value) == "str":
                w.prnt(
                    "",
                    "pushbullet: /set plugins.var.python.weebullet.%s STRING" %
                    option)
            elif type(default_value) == "int":
                w.prnt(
                    "",
                    "pushbullet: /set plugins.var.python.weebullet.%s INT" %
                    option)
예제 #38
0
    shell_in_home("commit -m \"%s\"" % weechat.config_get_plugin("commit_message"))

    # set hook back to 0
    confversion_commit_finish_hook = 0

    return weechat.WEECHAT_RC_OK

def conf_update_cb(data, option, value):
    #Commit data if not part of ignore list.
    if weechat.config_get_plugin("commit_each_change") == "true"  and not option in weechat.config_get_plugin("auto_commit_ignore").split(","):
        #Call use pause else /save will be called before the config is actually saved to disc
        #This is kinda hack but better input would be appricated.
        weechat.hook_timer(500, 0, 1, "commit_cb", "")
    return weechat.WEECHAT_RC_OK

def confversion_cmd(data, buffer, args):
    commit_cb()
    return weechat.WEECHAT_RC_OK

if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE,
                    SCRIPT_DESC, "", ""):
    for option, default_value in settings.iteritems():
        if weechat.config_get_plugin(option) == "":
            weechat.config_set_plugin(option, default_value)

    weechat.hook_command("confversion", "Saves configurations to version control", "",
                         "",
                         "", "confversion_cmd", "")
    init_repo()
    hook = weechat.hook_config("*", "conf_update_cb", "")
예제 #39
0
# Main script.
# ============

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", "0", "0", "default", "default", "default", "0",
예제 #40
0
def ver_method():
    return weechat.config_get_plugin("versioning_method")
예제 #41
0
def ignored_nicks():
    """A generator of nicks from which notifications should be ignored."""
    for nick in weechat.config_get_plugin('ignore_nicks').split(','):
        yield nick.strip()
예제 #42
0
def logging_enabled():
    """Return True if logging is enabled"""
    return weechat.config_get_plugin("logging") == "on"
예제 #43
0
def notify_for_current_buffer():
    """Should we also send notifications for the current buffer?"""
    return weechat.config_get_plugin('notify_for_current_buffer') == 'on'
예제 #44
0
def nick_separator():
    """Returns a nick separator to be used."""
    separator = weechat.config_get_plugin('nick_separator')
    return separator if separator else default_value_of('nick_separator')
예제 #45
0
            "    size_ls : less than <Kib> for log-files to purge\n"
            "        age : older than <days> for log-files to purge (maximum value: 9999)\n"
            "     age_ls : younger than <days> for log-files to purge\n"
            "     delete : argument for security reasons\n"
            "\n"
            #                             str_commands + "\n"
            "Examples:\n"
            "  show log-files older than 100 days\n"
            "    /" + SCRIPT_NAME + " age 100\n"
            "  purge log-files older than 100 days\n"
            "    /" + SCRIPT_NAME + " age 100 delete\n"
            "  show log-files younger than 10 days\n"
            "    /" + SCRIPT_NAME + " age_ls 10\n"
            "  purge log-files younger than 10 days\n"
            "    /" + SCRIPT_NAME + " age_ls 10 delete\n"
            "  show log-files greater than 100 KiB\n"
            "    /" + SCRIPT_NAME + " size 100\n"
            "  purge log-files greater than 100 KiB\n"
            "    /" + SCRIPT_NAME + " size 100 delete\n",
            "age|age_ls|size|size_ls %-",
            "purgelogs_cb",
            "")
    w.hook_config('plugins.var.python.%s.blacklist' % SCRIPT_NAME,
                  'update_blacklist', '')

    for option, default_value in purgelogs_options.iteritems():
        if w.config_get_plugin(option) == "":
            w.config_set_plugin(option, default_value)
        else:
            blacklist = w.config_get_plugin('blacklist').split(',')
예제 #46
0
def notify_when_away():
    """Should we also send notifications when away?"""
    return weechat.config_get_plugin('notify_when_away') == 'on'
예제 #47
0
def notify_on_privmsgs():
    """Should we send notifications on private messages?"""
    return weechat.config_get_plugin('notify_on_privmsgs') == 'on'
예제 #48
0
def update_blacklist(*args):
    global blacklist
    if w.config_get_plugin('blacklist'):
        blacklist = w.config_get_plugin('blacklist').split(',')
    return w.WEECHAT_RC_OK
예제 #49
0
def should_notifications_be_transient():
    """Should the sent notifications be transient, i.e. should they be removed
    from the notification bar once they expire or are dismissed?
    """
    return weechat.config_get_plugin('transient') == 'on'
예제 #50
0
def ignored_buffers():
    """A generator of buffers from which notifications should be ignored."""
    for buffer in weechat.config_get_plugin('ignore_buffers').split(','):
        yield buffer.strip()
예제 #51
0
        #alert("Option {0} has been changed to {1}".format(myOption,
        #			settings[myOption]))
    except KeyError:
        errMsg("There is no option named %s" % myOption)
    return w.WEECHAT_RC_OK


if __name__ == "__main__" and import_ok:
    if w.register(SCR_NAME, SCR_AUTHOR, SCR_VERSION, SCR_LICENSE, SCR_DESC, "",
                  ""):
        # synchronize weechat- and scriptsettings
        for option, default_value in settings.items():
            if not w.config_is_set_plugin(option):
                w.config_set_plugin(option, default_value)
            else:
                settings[option] = w.config_get_plugin(option)
                if option == "buffers":  # need to set buffers seperately
                    myBuffers = settings[option][2:-2]
                    try:
                        myBuffers = myBuffers.split("'}{'")
                        for tmp in myBuffers:
                            myBuffer, myStatus, mySound = tmp.split("','")
                            bfList += [{
                                "buffer": myBuffer,
                                "status": myStatus,
                                "sound": mySound
                            }]
                    except:
                        myBuffers = ""
        w.hook_print("", "", "", 1, "fn_privmsg", "")  # catch prvmsg
        w.hook_config("plugins.var.python." + SCR_NAME + ".*",
예제 #52
0
def notify_on_highlights():
    """Should we send notifications on highlights?"""
    return weechat.config_get_plugin('notify_on_highlights') == 'on'
예제 #53
0
def hlpv_timer():
    weechat.hook_timer(
        int(weechat.config_get_plugin("visible_seconds")) * 1000, 0, 1,
        "hlpv_timer_cb", "")
예제 #54
0
def notify_on_filtered_messages():
    """Should we also send notifications for filtered (hidden) messages?"""
    return weechat.config_get_plugin('notify_on_filtered_messages') == 'on'
예제 #55
0
def notify_dcc_send_completed(match):
    'Notify on DCC send completion.'
    if weechat.config_get_plugin("show_dcc") == "on":
        file_name = match.group(1)
        growl_notify('DCC', 'Upload Complete', file_name)
예제 #56
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:
        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")
예제 #57
0
def notify_dcc_get_failed(match):
    'Notify on DCC get failure.'
    if weechat.config_get_plugin("show_dcc") == "on":
        file_name = match.group(1)
        a_notify('DCC', 'Download Failed', file_name)
예제 #58
0
def notify_dcc_send_failed(match):
    'Notify on DCC send failure.'
    if weechat.config_get_plugin("show_dcc") == "on":
        file_name = match.group(1)
        growl_notify('DCC', 'Upload Failed', file_name)
예제 #59
0
def notify_dcc_get_completed(match):
    'Notify on DCC get completion.'
    if weechat.config_get_plugin("show_dcc") == "on":
        file_name = match.group(1)
        a_notify('DCC', 'Download Complete', file_name)
예제 #60
0
def urlserver_end():
    """Script unloaded (oh no, why?)"""
    urlserver_server_stop()
    urlserver_write_urls()
    return weechat.WEECHAT_RC_OK


if __name__ == '__main__' and import_ok:
    if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION,
                        SCRIPT_LICENSE, SCRIPT_DESC, 'urlserver_end', ''):
        # set default settings
        version = weechat.info_get('version_number', '') or 0
        for option, value in urlserver_settings_default.items():
            if weechat.config_is_set_plugin(option):
                urlserver_settings[option] = weechat.config_get_plugin(option)
            else:
                weechat.config_set_plugin(option, value[0])
                urlserver_settings[option] = value[0]
            if int(version) >= 0x00030500:
                weechat.config_set_desc_plugin(
                    option, '%s (default: "%s")' % (value[1], value[0]))

        # detect config changes
        weechat.hook_config('plugins.var.python.%s.*' % SCRIPT_NAME,
                            'urlserver_config_cb', '')

        # add command
        weechat.hook_command(
            SCRIPT_COMMAND, SCRIPT_DESC, 'start|restart|stop|status || clear',
            '  start: start server\n'