예제 #1
0
def check_buffer_type(window, data, value):
    bufpointer = weechat.window_get_pointer(window,"buffer")
    if bufpointer == "":
        return ""

    value = value.split(' ', 1)
    if len(value) <= 1:
        return ""

    # format is : buffer_type (channel,server,private,all) | signal (e.g: buffer_switch)
    channel_type_and_signal = value[0]
    if channel_type_and_signal.find('|') >= 0:
        channel_type = channel_type_and_signal[0:channel_type_and_signal.find("|")]
        signal_type = channel_type_and_signal[channel_type_and_signal.find("|")+1:]
        unhook(data)
        add_hook(signal_type, data)
    else:
        channel_type = value[0]

    value = value[1]

    if channel_type == 'all' or weechat.buffer_get_string(bufpointer,'localvar_type') == channel_type:
        return value
    if channel_type == '!all':
        a = ["channel","server","private"]
        if weechat.buffer_get_string(bufpointer,'localvar_type') in a:
            return value
    return ""
예제 #2
0
파일: tts.py 프로젝트: DarkDefender/scripts
def names_for_buffer(buffer):
    """Returns a list of all names for the given buffer."""
    # The 'buffer' parameter passed to our callback is actually the buffer's ID
    # (e.g. '0x2719cf0'). We have to check its name (e.g. 'freenode.#weechat')
    # and short name (e.g. '#weechat') because these are what users specify in
    # their configs.
    buffer_names = []

    full_name = weechat.buffer_get_string(buffer, 'name')
    if full_name:
        buffer_names.append(full_name)

    short_name = weechat.buffer_get_string(buffer, 'short_name')
    if short_name:
        buffer_names.append(short_name)
        # Consider >channel and #channel to be equal buffer names. The reason
        # is that the https://github.com/rawdigits/wee-slack plugin replaces
        # '#' with '>' to indicate that someone in the buffer is typing. This
        # fixes the behavior of several configuration options (e.g.
        # 'tts_on_all_messages_in_buffers') when weechat_notify_send is used
        # together with the wee_slack plugin.
        #
        # Note that this is only needed to be done for the short name. Indeed,
        # the full name always stays unchanged.
        if short_name.startswith('>'):
            buffer_names.append('#' + short_name[1:])

    return buffer_names
예제 #3
0
def get_buffer_info(buf):
    server = weechat.buffer_get_string(buf, b'localvar_server').decode(
        'utf-8', 'replace')
    channel = weechat.buffer_get_string(buf, b'localvar_channel').decode(
        'utf-8', 'replace')

    return server, channel
예제 #4
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
예제 #5
0
def check_buffer_timer_cb(data, remaining_calls):
    global WEECHAT_VERSION,whitelist

    # search for buffers in hotlist
    ptr_infolist = weechat.infolist_get("hotlist", "", "")
    while weechat.infolist_next(ptr_infolist):
        ptr_buffer = weechat.infolist_pointer(ptr_infolist, "buffer_pointer")
        localvar_name = weechat.buffer_get_string(ptr_buffer, 'localvar_name')
        # buffer in whitelist? go to next buffer
        buf_type = weechat.buffer_get_string(ptr_buffer,'localvar_type')
        # buffer is a query buffer?
        if OPTIONS['ignore_query'].lower() == 'on' and buf_type == 'private':
            continue
        # buffer in whitelist?
        if localvar_name in whitelist:
            continue
        if ptr_buffer:
            if get_time_from_line(ptr_buffer):
                if OPTIONS['clear'].lower() == 'hotlist' or OPTIONS['clear'].lower() == 'all':
                    weechat.buffer_set(ptr_buffer, "hotlist", '-1')
                if OPTIONS['clear'].lower() == 'unread' or OPTIONS['clear'].lower() == 'all':
                    weechat.command(ptr_buffer,"/input set_unread_current_buffer")

    weechat.infolist_free(ptr_infolist)
    return weechat.WEECHAT_RC_OK
예제 #6
0
def word_magic(data, buffer, command):
    # get the input string
    uinput = w.buffer_get_string(buffer, "input")

    # if the buffer is blacklisted, do nothing
    if w.buffer_get_string(buffer, "short_name") in w.config_get_plugin(
            "blacklist_buffers").split(","):
        return w.WEECHAT_RC_OK

    if command == "/input return":
        # in case the line's empty, do nothing
        if uinput == "":
            return w.WEECHAT_RC_OK
        # bypass this using a backslash as the first character
        elif uinput.startswith("\\"):
            uinput = uinput.replace("\\", "", 1)
        # we don't want to capitalize basic URLs
        elif uinput[:4] == "http": # I'M TOO LAZY FOR REGEX MATCHING
            return w.WEECHAT_RC_OK
        # if we point to a user, don't capitalise this
        elif isnick(buffer, uinput.split()[0][:-1]):
            return w.WEECHAT_RC_OK
        # if everything else is fine, replace the first char with its capital
        else:
            uinput = uinput.replace(uinput[0], uinput[0].upper(), 1)
        # set the new string into the input
        w.buffer_set(buffer, "input", uinput)
    return w.WEECHAT_RC_OK
예제 #7
0
def notify(data, buffer, timestamp, tags, displayed, highlighted, prefix, message):
    buffer_name = weechat.buffer_get_string(buffer, 'name')
    buffer_type = weechat.buffer_get_string(buffer, 'localvar_type')
    server      = weechat.buffer_get_string(buffer, 'localvar_server')

    message     = None

    if buffer_type not in ['private', 'channel']:
        return weechat.WEECHAT_RC_OK

    if buffer_type == 'channel' and highlighted == 0:
        return weechat.WEECHAT_RC_OK

    if buffer_type == 'private':
        message = '{nick} sent you a private message on {server}'.format(nick=prefix, server=server)

    elif buffer_type == 'channel':
        channel = buffer_name.split('.', 1)[1]
        message = '{nick} mentioned you in {channel}'.format(nick=prefix, channel=channel)

    if message == None:
        return weechat.WEECHAT_RC_OK

    process_endpoint = 'url:https://api.pushover.net:443/1/messages.json'
    post_data = urllib.urlencode({
        'token':   OPTIONS['apptoken'],
        'user':    OPTIONS['userkey'],
        'sound':   OPTIONS['sound'],
        'message': message,
    })

    weechat.hook_process_hashtable(process_endpoint, { 'post': '1', 'postfields': post_data }, OPTIONS['timeout'], 'message_sent', '')

    return weechat.WEECHAT_RC_OK
예제 #8
0
def twitch_buffer_switch(data, signal, signal_data):
    server = weechat.buffer_get_string(signal_data, 'localvar_server')
    type = weechat.buffer_get_string(signal_data, 'localvar_type')
    if not (server in OPTIONS['servers'].split() and type == 'channel'):
        return weechat.WEECHAT_RC_OK
    twitch_main('', signal_data, 'bs')
    return weechat.WEECHAT_RC_OK
def notify(data, buffer, date, tags, displayed, highlight, prefix, message):
	# ignore if it's yourself
	own_nick = weechat.buffer_get_string(buffer, 'localvar_nick')
	if prefix == own_nick or prefix == ('@%s' % own_nick):
		return weechat.WEECHAT_RC_OK

	# ignore messages older than the configured theshold (such as ZNC logs) if enabled
	if weechat.config_get_plugin('ignore_old_messages') == 'on':
		message_time = datetime.datetime.utcfromtimestamp(int(date))
		now_time = datetime.datetime.utcnow()

		# ignore if the message is greater than 5 seconds old
		if (now_time - message_time).seconds > 5:
			return weechat.WEECHAT_RC_OK

	# passing `None` or `''` still plays the default sound so we pass a lambda instead
	sound = weechat.config_get_plugin('sound_name') if weechat.config_get_plugin('sound') == 'on' else lambda:_
	activate_bundle_id = weechat.config_get_plugin('activate_bundle_id')
	if weechat.config_get_plugin('show_highlights') == 'on' and int(highlight):
		channel = weechat.buffer_get_string(buffer, 'localvar_channel')
		if weechat.config_get_plugin('show_message_text') == 'on':
			Notifier.notify(message, title='%s %s' % (prefix, channel), sound=sound, appIcon=WEECHAT_ICON, activate=activate_bundle_id)
		else:
			Notifier.notify('In %s by %s' % (channel, prefix), title='Highlighted Message', sound=sound, appIcon=WEECHAT_ICON, activate=activate_bundle_id)
	elif weechat.config_get_plugin('show_private_message') == 'on' and 'notify_private' in tags:
		if weechat.config_get_plugin('show_message_text') == 'on':
			Notifier.notify(message, title='%s [private]' % prefix, sound=sound, appIcon=WEECHAT_ICON, activate=activate_bundle_id)
		else:
			Notifier.notify('From %s' % prefix, title='Private Message', sound=sound, appIcon=WEECHAT_ICON, activate=activate_bundle_id)
	return weechat.WEECHAT_RC_OK
예제 #10
0
def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight, prefix, message):
    """Sends highlighted message to be printed on notification"""
    # string for show_notification return
    snreturn = None
    # smart_notification
    if (weechat.config_get_plugin('smart_notification') == "on" and bufferp == weechat.current_buffer()):
        pass
    # are we away and want highlights? check: w.infolist_integer(infolist, 'is_away')
    elif (weechat.config_get_plugin('notify_when_away') == "off" and weechat.buffer_get_string(bufferp, 'localvar_away')):
        pass
    elif (weechat.buffer_get_string(bufferp, "localvar_type") == "private" and weechat.config_get_plugin('show_priv_msg') == "on"):
        # should we ignore messages from something like ZNC with * prefix?
        ignprefix = weechat.config_get_plugin('ignore_nicks_startwith')
        if ignprefix != '' and prefix.startswith(ignprefix):  # if not empty..
            pass
        # if im sending a message to someone, don't pop up a notification.
        elif weechat.buffer_get_string(bufferp, "localvar_nick") != prefix:
            snreturn = show_notification(prefix, message)
    elif (ishilight == "1" and weechat.config_get_plugin('show_hilights') == "on"):
        buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name"))
        snreturn = show_notification(buffer, prefix + weechat.config_get_plugin('nick_separator') + message)
    # check to see if we had an error showing notification and return to user
    if snreturn:
        weechat.prnt(bufferp, snreturn)
    return weechat.WEECHAT_RC_OK
예제 #11
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
예제 #12
0
def fn_privmsg(data, bufferp, time, tags, display, is_hilight, prefix, msg):
	global bfList
	global settings
	servername = (w.buffer_get_string(bufferp, "name").split("."))[0]
	ownNick = w.info_get("irc_nick", servername)
	mySound = ""
	if not muted and prefix != ownNick:
		if settings["player"] == "":
			errMsg("'Player' isn't set!")
		else:
			for lEntry in bfList:
				if lEntry["buffer"] == w.buffer_get_string(bufferp, "name"):
					# we found a buffer of that name
					if lEntry["status"] == "on":
						if lEntry["sound"] == "":
							if settings["psound"] == "":
								errMsg("No sound defined! Please set either the " +
										 "regular 'psound'-option or the 'sound'-" +
										 "option for this buffer.")
							else:
								mySound = settings["psound"]
						else:
							mySound = lEntry["sound"]
						s.Popen([settings["player"], expanduser(mySound)],
								stderr=s.STDOUT, stdout=s.PIPE)
					break
	return w.WEECHAT_RC_OK
예제 #13
0
def allquery_command_cb(data, buffer, args):
    """ Callback for /allquery command """
    args = args.strip()
    if args == "":
        weechat.command("", "/help %s" % SCRIPT_COMMAND)
        return weechat.WEECHAT_RC_OK
    argv = args.split(" ")

    exclude_nick = None

    if argv[0].startswith("-exclude="):
        exclude_nick = make_list(argv[0])
        command = " ".join(argv[1::])
    else:
        command = args
    if not command.startswith("/"):
        weechat.command("", "/help %s" % SCRIPT_COMMAND)
        return weechat.WEECHAT_RC_OK

    infolist = weechat.infolist_get("buffer", "", "")
    while weechat.infolist_next(infolist):
        if weechat.infolist_string(infolist, "plugin_name") == "irc":
            ptr = weechat.infolist_pointer(infolist, "pointer")
            server = weechat.buffer_get_string(ptr, "localvar_server")
            query = weechat.buffer_get_string(ptr, "localvar_channel")
            execute_command = re.sub(r'\b\$nick\b', query, command)
            if weechat.buffer_get_string(ptr, "localvar_type") == "private":
                if exclude_nick is not None:
                    if not query in exclude_nick:
                        weechat.command(ptr, execute_command)
                else:
                    weechat.command(ptr, execute_command)
    weechat.infolist_free(infolist)
    return weechat.WEECHAT_RC_OK
예제 #14
0
def notification_callback(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight, prefix, message):

    is_away = weechat.buffer_get_string(bufferp, 'localvar_away')
    is_focused = bufferp == weechat.current_buffer()
    do_prowl = True # If set to False depending on state and settings, no Prowl notification will be sent

    if (is_away):
        if (is_focused and weechat.config_get_plugin('notify_focused_away') != 'on'):
            do_prowl = False
        elif (not is_focused and weechat.config_get_plugin('notify_unfocused_away') != 'on'):
            do_prowl = False
    else:
        if (is_focused and weechat.config_get_plugin('notify_focused_active') != 'on'):
            do_prowl = False
        elif (not is_focused and weechat.config_get_plugin('notify_unfocused_active') != 'on'):
            do_prowl = False

    if (do_prowl):
        if (weechat.buffer_get_string(bufferp, 'localvar_type') == 'private' and weechat.config_get_plugin('show_priv_msg') == 'on' and prefix != weechat.buffer_get_string(bufferp, 'localvar_nick')):
            send_prowl_notification(prefix, message, True)
        elif (ishilight == '1' and weechat.config_get_plugin('show_hilights') == 'on'):
            buffer = (weechat.buffer_get_string(bufferp, 'short_name') or weechat.buffer_get_string(bufferp, 'name'))
            send_prowl_notification(buffer, prefix + weechat.config_get_plugin('nick_separator') + message, False)

    return weechat.WEECHAT_RC_OK
예제 #15
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
예제 #16
0
def buffer_opened_cb(data, signal, signal_data):
    ptr_buffer = signal_data
    plugin = weechat.buffer_get_string(ptr_buffer, 'localvar_plugin')
    name = weechat.buffer_get_string(ptr_buffer, 'localvar_name')
    filename = get_filename_with_path('%s.%s' % (plugin,name))
    read_history(filename,ptr_buffer)
    return weechat.WEECHAT_RC_OK
예제 #17
0
def opall(data, buffer, args):
    channel = weechat.buffer_get_string(buffer, 'localvar_channel')
    server = weechat.buffer_get_string(buffer, 'localvar_server')

    if not weechat.info_get('irc_is_channel', channel):
        weechat.prnt(buffer, '%sopall: Not an IRC channel' % weechat.prefix('error'))
        return weechat.WEECHAT_RC_OK

    toOp = withoutOp(server, channel)
    if len(toOp) == 0:
        return weechat.WEECHAT_RC_OK

    # how many people can we op at once
    modes = int(weechat.info_get('irc_server_isupport_value', '%s,MODES' % server)) or 0
    if modes == 0:
        weechat.prnt(buffer, '%sopall: failed to determine MODES' % weechat.prefix('error'))
        return weechat.WEECHAT_RC_ERROR

    frm = 0
    to = modes
    while len(toOp) > frm:
        weechat.command(buffer, '/OP %s' % ' '.join(toOp[frm:to]))
        frm = to
        to += modes

    return weechat.WEECHAT_RC_OK
예제 #18
0
파일: lnotify.py 프로젝트: Shrews/scripts
def handle_msg(data, pbuffer, date, tags, displayed, highlight, prefix, message):
    highlight = bool(highlight) and cfg["highlight"]
    query = true[cfg["query"]]
    notify_away = true[cfg["notify_away"]]
    buffer_type = weechat.buffer_get_string(pbuffer, "localvar_type")
    away = weechat.buffer_get_string(pbuffer, "localvar_away")
    x_focus = False
    window_name = ""

    # Check to make sure we're in X and xdotool exists.
    # This is kinda crude, but I'm no X master.
    if (environ.get('DISPLAY') != None) and path.isfile("/bin/xdotool"):
        window_name = subprocess.check_output(["xdotool", "getwindowfocus", "getwindowname"])

    if "WeeChat" in window_name:
        x_focus = True

    if pbuffer == weechat.current_buffer() and x_focus:
        return weechat.WEECHAT_RC_OK

    if away and not notify_away:
        return weechat.WEECHAT_RC_OK

    buffer_name = weechat.buffer_get_string(pbuffer, "short_name")


    if buffer_type == "private" and query:
        notify_user(buffer_name, message)
    elif buffer_type == "channel" and highlight:
        notify_user("{} @ {}".format(prefix, buffer_name), message)

    return weechat.WEECHAT_RC_OK
예제 #19
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
def at_completion(data, buffer, command):
    if not config['enable']:
        return weechat.WEECHAT_RC_OK
    
    input = weechat.buffer_get_string(buffer, 'input')
    if input[0] != '/':
        buffer_name = weechat.buffer_get_string(buffer,'name')
        plugin_name = weechat.buffer_get_string(buffer,'plugin')
        # don't nick complete in core
        if plugin_name == 'core': return weechat.WEECHAT_RC_OK
        server_name = buffer_name.split('.')[0]
        if (server_name not in config['servers'] 
           or not check_buffers(buffer_name) ):
           return weechat.WEECHAT_RC_OK
        pos = weechat.buffer_get_integer(buffer, 'input_pos')
        if pos > 0 and (pos == len(input) or input[pos] == ' '):
            n = input.rfind(' ', 0, pos)
            e = input.find(' ',n)
            at = 0
            word = input[n+1:pos]
            if e != n :
              word = word[:e]
            if word[0] == '@':
                word = word[1:]
                at = 1
            nicklist = weechat.infolist_get('nicklist', buffer, '')
            if nicklist:
                nick = walk_nicklist(nicklist,word)
                if nick != "":
                    complete = '%s@%s %s' %(input[:pos-len(word)-at],nick,input[pos:])
                    weechat.buffer_set(buffer, 'input', complete)
                    weechat.buffer_set(buffer, 'input_pos', str(pos - len(word) + len(nick)+2))
                    return weechat.WEECHAT_RC_OK_EAT
    return weechat.WEECHAT_RC_OK
예제 #21
0
파일: slack.py 프로젝트: palbo/dotfiles
def unread_cb(data, buffer, command):
    global all_channels
    channels = []
    if command.find("set_unread_current_buffer") >= 0:
        if w.buffer_get_string(buffer, "localvar_server") == "slack" and \
           w.buffer_get_string(buffer, "localvar_type") in ["channel", "private"]:
            channels.append(w.buffer_get_string(buffer, "localvar_channel"))
    else:
        channels = _channels()

    for c in channels:
        cs = c.lstrip("#")
        if cs in all_channels:
            try:
                if c.startswith("#"):
                    if cs in private_groups:
                        r = slack.groups.mark(all_channels[cs], time.time())
                    else:
                        r = slack.channels.mark(all_channels[cs], time.time())
                else:
                    r = slack.im.mark(all_channels[cs], time.time())
                #w.prnt("", "%s: %s" % (c, r.body["ok"] and "ok" or "not ok"))
            except:
                w.prnt("", "Error while setting unread marker on %s" % c)
    w.prnt("", "%d channels marked as read" % len(channels))

    return w.WEECHAT_RC_OK
예제 #22
0
def show_item(data, item, window):
    bufpointer = weechat.window_get_pointer(window, "buffer")
    if bufpointer == "":
        return ""

    if weechat.buffer_get_string(bufpointer, "name") != "weechat":  # not weechat core buffer
        if weechat.buffer_get_string(bufpointer, "localvar_type") == "":  # buffer with free content?
            return ""

    lines_after, lines_count, percent, current_line = count_lines(window, bufpointer)

    if lines_count == 0:  # buffer empty?
        return ""

    tags = {"%C": str(current_line), "%A": str(lines_after), "%L": str(lines_count), "%P": str(percent) + "%"}

    bufsize_item = substitute_colors(OPTIONS["format"])

    # replace mandatory tags
    for tag in list(tags.keys()):
        #    for tag in tags.keys():
        bufsize_item = bufsize_item.replace(tag, tags[tag])

    # replace optional tags
    # %{…} only if lines after (e.g. %A > 0)
    if lines_after > 0:
        for regex_tag in regex_optional_tags.findall(bufsize_item):
            bufsize_item = bufsize_item.replace(regex_tag, regex_tag.lstrip("%{").rstrip("}"))
    else:
        bufsize_item = regex_optional_tags.sub("", bufsize_item)

    return bufsize_item
예제 #23
0
def prepare_notification(buffer, is_highlight, nick, message):
    """Prepares a notification from the given data."""
    if is_highlight:
        source = (weechat.buffer_get_string(buffer, 'short_name') or
                  weechat.buffer_get_string(buffer, 'name'))
        message = nick + nick_separator() + message
    else:
        # A private message.
        source = nick

    max_length = int(weechat.config_get_plugin('max_length'))
    if max_length > 0:
        ellipsis = weechat.config_get_plugin('ellipsis')
        message = shorten_message(message, max_length, ellipsis)

    if weechat.config_get_plugin('escape_html') == 'on':
        message = escape_html(message)

    message = escape_slashes(message)

    icon = weechat.config_get_plugin('icon')
    timeout = weechat.config_get_plugin('timeout')
    urgency = weechat.config_get_plugin('urgency')

    return Notification(source, message, icon, timeout, urgency)
예제 #24
0
def nicklist_cmd_cb(data, buffer, args):
    ''' Command /nicklist '''
    if args == '':
        display_action()
        display_buffers()
    else:
        current_buffer_name = w.buffer_get_string(buffer, 'plugin') + '.' + w.buffer_get_string(buffer, 'name')
        if args == 'show':
            w.config_set_plugin('action', 'show')
            #display_action()
            w.command('', '/window refresh')
        elif args == 'hide':
            w.config_set_plugin('action', 'hide')
            #display_action()
            w.command('', '/window refresh')
        elif args == 'add':
            list = get_buffers_list()
            if current_buffer_name not in list:
                list.append(current_buffer_name)
                w.config_set_plugin('buffers', ','.join(list))
                #display_buffers()
                w.command('', '/window refresh')
            else:
                w.prnt('', '%s: buffer "%s" is already in list' % (SCRIPT_NAME, current_buffer_name))
        elif args == 'remove':
            list = get_buffers_list()
            if current_buffer_name in list:
                list.remove(current_buffer_name)
                w.config_set_plugin('buffers', ','.join(list))
                #display_buffers()
                w.command('', '/window refresh')
            else:
                w.prnt('', '%s: buffer "%s" is not in list' % (SCRIPT_NAME, current_buffer_name))
    
    return w.WEECHAT_RC_OK
예제 #25
0
파일: lnotify.py 프로젝트: eayin2/weetray
def get_notified(data, bufferp, uber_empty, tagsn, isdisplayed,
        ishilight, prefix, message):

    if (weechat.buffer_get_string(bufferp, "localvar_type") == "private" and
            weechat.config_get_plugin('show_priv_msg') == "on"):
        buffer = (weechat.buffer_get_string(bufferp, "short_name") or
                weechat.buffer_get_string(bufferp, "name"))
        if buffer == prefix:
            n = pynotify.Notification("WeeChat", "%s said: %s" % (prefix,
                message),weechat.config_get_plugin('show_icon'))
            Popen("/usr/bin/python2.7 /usr/share/weetray/main.py", shell=True)
            if not n.show():
                print "Failed to send notification"

    elif (ishilight == "1" and
            weechat.config_get_plugin('show_highlight') == "on"):
        buffer = (weechat.buffer_get_string(bufferp, "short_name") or
                weechat.buffer_get_string(bufferp, "name"))
        n = pynotify.Notification("WeeChat", "In %s, %s said: %s" % (buffer,
            prefix, message),weechat.config_get_plugin('show_icon'))
        Popen("/usr/bin/python2.7 /usr/share/weetray/main.py", shell=True)
        if not n.show():
            print "Failed to send notification"

    return weechat.WEECHAT_RC_OK
예제 #26
0
def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed,
                ishighlight, prefix, message):

    if weechat.config_get_plugin("enabled") == "off":
        return weechat.WEECHAT_RC_OK

    # get local nick for buffer
    mynick = weechat.buffer_get_string(bufferp, "localvar_nick")
    # strip channel op prefix
    stripped_prefix = prefix.replace("@", "")

    # check if we should not notify on this channel/nick priv_msg
    channel = weechat.buffer_get_string(bufferp, "localvar_channel")
    exclude_channels = weechat.config_get_plugin("exclude_channels").split(',')
    if channel in exclude_channels:
        return weechat.WEECHAT_RC_OK

    always_notify_channels = weechat.config_get_plugin("always_notify_channels").split(',')

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

    # notify on hilight or in always notifying channel and not sent by myself
    elif (ishighlight == "1" and weechat.config_get_plugin("show_highlight") == "on") or \
        (channel in always_notify_channels and stripped_prefix != mynick):

        buf = (weechat.buffer_get_string(bufferp, "short_name") or
               weechat.buffer_get_string(bufferp, "name"))
        show_notification(buf, prefix, message)

    return weechat.WEECHAT_RC_OK
예제 #27
0
def save_history():
    global history_list
    # get buffers
    ptr_infolist_buffer = weechat.infolist_get('buffer','','')

    while weechat.infolist_next(ptr_infolist_buffer):
        ptr_buffer = weechat.infolist_pointer(ptr_infolist_buffer,'pointer')

        # check for localvar_save_history
        if not weechat.buffer_get_string(ptr_buffer, 'localvar_save_history') and OPTIONS['save_buffer'].lower() == 'off':
            continue

        plugin = weechat.buffer_get_string(ptr_buffer, 'localvar_plugin')
        name = weechat.buffer_get_string(ptr_buffer, 'localvar_name')
        filename = get_filename_with_path('%s.%s' % (plugin,name))

        get_buffer_history(ptr_buffer)
        if len(history_list):
            write_history(filename)

    weechat.infolist_free(ptr_infolist_buffer)

    if OPTIONS['save_global'].lower() != 'off':
        get_buffer_history('')  # buffer pointer (if not set, return global history) 
        if len(history_list):
            write_history(filename_global_history)
예제 #28
0
def priv_msg_cb(data, bufferp, uber_empty, tagsn, isdisplayed,
        ishilight, prefix, message):
    """Sends highlighted message to be printed on notification"""

    am_away = w.buffer_get_string(bufferp, 'localvar_away')

    if not am_away:
	w.prnt("", "[weebullet] Not away, skipping notification")
	return w.WEECHAT_RC_OK

    notif_body = u"<%s> %s" % (
        prefix.decode('utf-8'),
	message.decode('utf-8')
    )

    # Check that it's in a "/q" buffer and that I'm not the one writing the msg
    is_pm = w.buffer_get_string(bufferp, "localvar_type") == "private"
    is_notify_private = re.search(r'(^|,)notify_private(,|$)', tagsn) is not None
    # PM (query)
    if (is_pm and is_notify_private):
	send_push(
		title="Privmsg from %s" % prefix.decode('utf-8'),
		body=notif_body
	)

    # Highlight (your nick is quoted)
    elif (ishilight == "1"):
        bufname = (w.buffer_get_string(bufferp, "short_name") or
                w.buffer_get_string(bufferp, "name"))
	send_push(
		title="Highlight in %s" % bufname.decode('utf-8'),
		body=notif_body
	)

    return w.WEECHAT_RC_OK
예제 #29
0
def handle_msg(data, pbuffer, date, tags, displayed, highlight, prefix, message):
    highlight = bool(highlight) and cfg["highlight"]
    query = true[cfg["query"]]
    notify_away = true[cfg["notify_away"]]
    buffer_type = weechat.buffer_get_string(pbuffer, "localvar_type")
    away = weechat.buffer_get_string(pbuffer, "localvar_away")


    if pbuffer == weechat.current_buffer() and buffer_type == "private":
        return weechat.WEECHAT_RC_OK

    if away and not notify_away:
        return weechat.WEECHAT_RC_OK

    buffer_name = weechat.buffer_get_string(pbuffer, "short_name")

    if "is back on server" in message:
        return weechat.WEECHAT_RC_OK
    elif "has quit" in message:
        return weechat.WEECHAT_RC_OK

    if buffer_type == "private" and query:
        notify_user(buffer_name, message)
    elif buffer_type == "channel" and highlight:
        notify_user("{} @ {}".format(prefix, buffer_name), message)

    return weechat.WEECHAT_RC_OK
예제 #30
0
def show_spell_suggestion_item_cb (data, item, window):
    buffer = weechat.window_get_pointer(window,"buffer")
    if buffer == '':
        return ''

    if OPTIONS['replace_mode'].lower() == "on":
        if not weechat.buffer_get_string(buffer,'localvar_inline_suggestions'):
            return ''
        tab_complete,position,aspell_suggest_items = weechat.buffer_get_string(buffer,'localvar_inline_suggestions').split(':',2)
        return aspell_suggest_items

    tab_complete,position,aspell_suggest_item = get_position_and_suggest_item(buffer)
    localvar_aspell_suggest = get_localvar_aspell_suggest(buffer)

    # localvar_aspell_suggest = word,word2/wort,wort2
    if localvar_aspell_suggest:
        misspelled_word,aspell_suggestions = localvar_aspell_suggest.split(':')
        aspell_suggestions_orig = aspell_suggestions
        aspell_suggestions = aspell_suggestions.replace('/',',')
        aspell_suggestion_list = aspell_suggestions.split(',')

        if not position:
            return ''
        if int(position) < len(aspell_suggestion_list):
            reset_color = weechat.color('reset')
            color = weechat.color("red")
            new_word = aspell_suggestion_list[int(position)].replace(aspell_suggestion_list[int(position)],'%s%s%s' % (color, aspell_suggestion_list[int(position)], reset_color))
    else:
        return ''

    return aspell_suggestions_orig
예제 #31
0
def get_userhost_from_nick(buffer, nick):
    """Return host of a given nick in buffer."""
    channel = weechat.buffer_get_string(buffer, 'localvar_channel')
    server = weechat.buffer_get_string(buffer, 'localvar_server')
    if channel and server:
        infolist = weechat.infolist_get('irc_nick', '',
                                        '%s,%s' % (server, channel))
        if infolist:
            try:
                while weechat.infolist_next(infolist):
                    name = weechat.infolist_string(infolist, 'name')
                    if nick == name:
                        return weechat.infolist_string(infolist, 'host')
            finally:
                weechat.infolist_free(infolist)
    return ''
예제 #32
0
def hook_message_send(data, buffer, command):
    text = weechat.buffer_get_string(buffer, 'input').decode("utf-8")
    if text.startswith('/') and not text.startswith('//'):
        return weechat.WEECHAT_RC_OK

    for original in replacements:
        text = text.replace(original, replacements[original])

    if text.startswith(">"):
        text = u"3" + text

    if weechat.buffer_get_string(buffer, "name").startswith("bitlbee"):
        text = stripFormatting.sub("", text)

    weechat.buffer_set(buffer, 'input', text.encode("utf-8"))
    return weechat.WEECHAT_RC_OK
예제 #33
0
def cb_process_message(data, wbuffer, date, tags, displayed, highlight, prefix,
                       message):
    '''Delegates incoming messages to appropriate handlers.'''
    tags = set(tags.split(','))
    functions = globals()
    is_public_message = tags.issuperset(
        TAGGED_MESSAGES['public message or action'])
    buffer_name = weechat.buffer_get_string(wbuffer, 'name')
    dcc_buffer_regex = re.compile(r'^irc_dcc\.', re.UNICODE)
    dcc_buffer_match = dcc_buffer_regex.match(buffer_name)
    highlighted = False
    if int(highlight):
        highlighted = True
    # Private DCC message identifies itself as public.
    if is_public_message and dcc_buffer_match:
        notify_private_message_or_action(buffer_name, prefix, message,
                                         highlighted)
        return weechat.WEECHAT_RC_OK
    # Pass identified, untagged message to its designated function.
    for key, value in UNTAGGED_MESSAGES.items():
        match = value.match(message)
        if match:
            functions[DISPATCH_TABLE[key]](match)
            return weechat.WEECHAT_RC_OK
    # Pass identified, tagged message to its designated function.
    for key, value in TAGGED_MESSAGES.items():
        if tags.issuperset(value):
            functions[DISPATCH_TABLE[key]](buffer_name, prefix, message,
                                           highlighted)
            return weechat.WEECHAT_RC_OK
    return weechat.WEECHAT_RC_OK
예제 #34
0
def aspell_suggest_cb(data, signal, signal_data):
    buffer = signal_data
    if OPTIONS['replace_mode'].lower() == 'on':
        localvar_aspell_suggest = get_localvar_aspell_suggest(buffer)
        if localvar_aspell_suggest:
            # aspell says, suggested word is also misspelled. check out if we already have a suggestion list and don't use the new misspelled word!
            if weechat.buffer_get_string(buffer,
                                         'localvar_inline_suggestions'):
                return weechat.WEECHAT_RC_OK
            if not ":" in localvar_aspell_suggest:
                return weechat.WEECHAT_RC_OK
            misspelled_word, aspell_suggestions = localvar_aspell_suggest.split(
                ':')
            aspell_suggestions = aspell_suggestions.replace('/', ',')
            weechat.buffer_set(buffer, 'localvar_set_inline_suggestions',
                               '%s:%s:%s' % ('2', '0', aspell_suggestions))
            weechat.bar_item_update('spell_suggestion')
            return weechat.WEECHAT_RC_OK

    if OPTIONS['auto_pop_up_item'].lower() == 'on':
        auto_suggest_cmd_cb('', buffer, '')
        weechat.buffer_set(buffer,
                           'localvar_del_spell_correction_suggest_input_line',
                           '')
    weechat.bar_item_update('spell_suggestion')
    return weechat.WEECHAT_RC_OK
예제 #35
0
def command_run_input(data, buffer, command):
    """ Function called when a command "/input xxxx" is run """
    if command == "/input return":  # As in enter was pressed.

        # Get input contents
        input_s = w.buffer_get_string(buffer, 'input')

        # Skip modification of settings
        if input_s.startswith('/set '):
            return w.WEECHAT_RC_OK

        # Iterate transformation pairs
        for replace_item in w.config_get_plugin('replacement_pairs').split(
                ','):
            if replace_item:
                orig, replaced = replace_item.split('=')
                input_s = input_s.replace(orig, replaced)
        # Iterate words
        for replace_item in w.config_get_plugin('replacement_words').split(
                ','):
            if replace_item:
                orig, replaced = replace_item.split('=')
                # Search for whitespace+word+whitespace and replace the word
                input_s = re.sub('(\s+|^)%s(\s+|$)' % orig,
                                 '\\1%s\\2' % replaced, input_s)

        # Spit it out
        w.buffer_set(buffer, 'input', input_s)
    return w.WEECHAT_RC_OK
예제 #36
0
def autojoinem_completion_cb(data, completion_item, buffer, completion):
    #    server = weechat.buffer_get_string(buffer, 'localvar_server')                               # current buffer
    input_line = weechat.buffer_get_string(buffer, 'input')

    # get information out of the input_line
    argv = input_line.strip().split(" ", 3)
    if (len(argv) >= 3 and argv[1] == 'del'):
        server = argv[2]

    list_of_channels, list_of_keys = get_autojoin_list(buffer, server)
    if list_of_channels == 1:
        return weechat.WEECHAT_RC_OK

    if (len(argv) >= 4 and argv[1] == 'del'):
        list_of_current_channels = argv[3].split(' ')
        missing_channels = get_difference(list_of_channels,
                                          list_of_current_channels)
        if not missing_channels:
            return weechat.WEECHAT_RC_OK
        list_of_channels = missing_channels

    for i, elem in enumerate(list_of_channels):
        weechat.hook_completion_list_add(completion, list_of_channels[i], 0,
                                         weechat.WEECHAT_LIST_POS_END)
    return weechat.WEECHAT_RC_OK
예제 #37
0
파일: spotify.py 프로젝트: vmindru/scripts
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(w.config_get_plugin('client_id'), w.config_get_plugin('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
예제 #38
0
def lb_create_buffer():
  global lb_buffer, lb_curline

  if not lb_buffer:
    lb_buffer = weechat.buffer_new("listbuffer", "lb_input_cb", \
                "", "lb_close_cb", "")
    lb_set_buffer_title()
    # Sets notify to 0 as this buffer does not need to be in hotlist.
    weechat.buffer_set(lb_buffer, "notify", "0")
    weechat.buffer_set(lb_buffer, "nicklist", "0")
    weechat.buffer_set(lb_buffer, "type", "free")
    weechat.buffer_set(lb_buffer, "key_bind_ctrl-L", "/listbuffer **refresh")
    weechat.buffer_set(lb_buffer, "key_bind_meta2-A", "/listbuffer **up")
    weechat.buffer_set(lb_buffer, "key_bind_meta2-B", "/listbuffer **down")
    weechat.buffer_set(lb_buffer, "key_bind_meta2-1~", "/listbuffer **scroll_top")
    weechat.buffer_set(lb_buffer, "key_bind_meta2-4~", "/listbuffer **scroll_bottom")
    weechat.buffer_set(lb_buffer, "key_bind_meta-ctrl-J", "/listbuffer **enter")
    weechat.buffer_set(lb_buffer, "key_bind_meta-ctrl-M", "/listbuffer **enter")
    weechat.buffer_set(lb_buffer, "key_bind_meta->", "/listbuffer **sort_next")
    weechat.buffer_set(lb_buffer, "key_bind_meta-<", "/listbuffer **sort_previous")
    weechat.buffer_set(lb_buffer, "key_bind_meta-/", "/listbuffer **sort_invert")
    lb_curline = 0
  if weechat.config_get_plugin("autofocus") == "on":
    if not weechat.window_search_with_buffer(lb_buffer):
      weechat.command("", "/buffer " + weechat.buffer_get_string(lb_buffer,"name"))
예제 #39
0
def buffer_switch_cb(data, buffer, command):
    if command == '':
        return weechat.WEECHAT_RC_OK

    args = command.strip().split(' ',)[1:]
    if len(args) != 1:
        return weechat.WEECHAT_RC_OK

    ptr_buffer = ''
    # check if argument is a buffer "number"
    destination_buffer = get_destination_buffer_number(args[0])
    if destination_buffer:
        if destination_buffer < 1:
            destination_buffer = 1
        buffer_name, ptr_buffer = infolist_get_buffer_name_and_ptr_by_number(destination_buffer)
    else:
        # search for buffer name
        buffer_name, ptr_buffer = infolist_get_buffer_name_and_ptr_by_name(args[0])

    if not ptr_buffer:
        return weechat.WEECHAT_RC_OK

    if ptr_buffer == weechat.window_get_pointer(weechat.current_window(), 'buffer'):
        return weechat.WEECHAT_RC_OK

    window_number = weechat.buffer_get_string(ptr_buffer, 'localvar_stick_buffer_to_window')
    if not window_number:
        window_number = get_default_stick_window_number()
    if window_number:
        weechat.command('', '/window %s' % window_number)
    return weechat.WEECHAT_RC_OK
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
예제 #41
0
파일: weetext.py 프로젝트: weechat/scripts
def decrypt(message, buf):
    username = weechat.buffer_get_string(buf, 'name')
    if os.path.exists(weechat_dir + key_dir + "/cryptkey." + username):
        p = subprocess.Popen([
            "openssl", "enc", "-d", "-a",
            "-" + weechat.config_get_plugin("cipher"), "-pass",
            "file:" + weechat_dir + key_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 message
        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 '\x19' + weechat.color('lightred') + weechat.config_get_plugin(
            "message_indicator") + '\x1C' + decrypted
    else:
        return message
예제 #42
0
def my_modifier_cb(data, modifier, modifier_data, string):
    if w.buffer_get_string(w.buffer_search('irc',modifier_data.split(";")[1]),"localvar_noirccolors") == "true":
        try:
            nick, message = string.split("\t")
        except ValueError, e:
            return string
        return "%s\t%s" % (nick, w.string_remove_color(message,""))
예제 #43
0
def game_api(data, command, rc, stdout, stderr):
    try:
        jsonDict = json.loads(stdout.strip())
    except Exception as e:
        weechat.prnt(
            data, '%stwitch.py: error communicating with twitch api' %
            weechat.prefix('error'))
        if OPTIONS['debug']:
            weechat.prnt(
                data,
                '%stwitch.py: return code: %s' % (weechat.prefix('error'), rc))
            weechat.prnt(
                data,
                '%stwitch.py: stdout: %s' % (weechat.prefix('error'), stdout))
            weechat.prnt(
                data,
                '%stwitch.py: stderr: %s' % (weechat.prefix('error'), stderr))
            weechat.prnt(
                data,
                '%stwitch.py: exception: %s' % (weechat.prefix('error'), e))
        return weechat.WEECHAT_RC_OK

    if 'data' in jsonDict.keys():
        if not jsonDict['data']:
            return weechat.WEECHAT_RC_OK
        if len(jsonDict['data']) == 1:
            jsonDict['data'] = jsonDict['data'][0]
        old_title = weechat.buffer_get_string(data, "title")
        id = jsonDict['data']['id']
        name = makeutf8(jsonDict['data']['name'])
        new_title = old_title.replace('<{}>'.format(id), '<{}>'.format(name))
        weechat.buffer_set(data, "title", new_title)
        gameid_cache[id] = name
    return weechat.WEECHAT_RC_OK
예제 #44
0
def infolist_relay():
    infolist_relay = weechat.infolist_get('relay', '', '')
    if infolist_relay:
        while weechat.infolist_next(infolist_relay):
            status = weechat.infolist_integer(infolist_relay, 'status')
            status_string = weechat.infolist_string(infolist_relay,
                                                    'status_string')
#            weechat.prnt('', '%d %s' % (status, status_string))
        weechat.infolist_free(
            infolist_relay)  # don't forget to free() infolist!
    return weechat.WEECHAT_RC_OK

    #
    # =============================[ localvars() ]============================
    weechat.buffer_set(buffer, 'localvar_set_<name_of_localvar>', '%s' % value)
    weechat.buffer_get_string(buffer, 'localvar_<name_of_localvar>')
예제 #45
0
def buffer_filtering(buffer):
    """
	Check whether "buffer" should be filtered.
	"""

    local = weechat.buffer_get_string(buffer, "localvar_%s" % SCRIPT_LOCALVAR)
    return {"": None, "0": False, "1": True}[local]
예제 #46
0
파일: aban.py 프로젝트: NetSysFire/aban.py
def prepare_and_send_signal(buffer, nick, action):
    global PENDING_ACTIONS
    # needed to get the server buffer (irc.server.#somechannel)
    buffer_info = weechat.buffer_get_string(buffer, "full_name").split(".")
    if buffer_info.pop(0) != "irc":
        log_warning("aban can only be used in irc channel buffers")
        return weechat.WEECHAT_RC_ERROR

    server, channel = buffer_info
    if not channel.startswith("#"):
        log_warning("aban can only be used in irc channel buffers")
        return weechat.WEECHAT_RC_ERROR
    if weechat.info_get('irc_nick', server) == nick:
        log_warning(f"You probably do not want to {action} yourself.")
        return weechat.WEECHAT_RC_ERROR
    # see known issues section in the README
    PENDING_ACTIONS[nick] = {
        "server": server,
        "channel": channel,
        "action": action
    }

    weechat.hook_hsignal_send("irc_redirect_command", {
        "server": server,
        "pattern": "who",
        "signal": "action"
    })
    weechat.hook_signal_send('irc_input_send',
                             weechat.WEECHAT_HOOK_SIGNAL_STRING,
                             f"{server};;2;;/who {nick} %a")

    # to please pylint
    return weechat.WEECHAT_RC_OK
예제 #47
0
def message_hook(data, bufferp, uber_empty, tagsn, is_displayed,
                 is_highlighted, prefix, message):
    is_pm = w.buffer_get_string(bufferp, 'localvar_type') == 'private'
    regular_channel = not is_subscribed(bufferp) and not is_pm

    if is_ignored(bufferp) and regular_channel:
        log('ignored regular channel skipping')
        return w.WEECHAT_RC_OK

    if not is_displayed:
        log('not a displayed message skipping')
        return w.WEECHAT_RC_OK

    if not is_highlighted and regular_channel:
        return w.WEECHAT_RC_OK

    log('passed all checks')

    if is_pm:
        title = 'Private message from {}'.format(prefix.decode('utf-8'))
    else:
        title = 'Message on {} from {}'.format(get_buf_name(bufferp),
                                               prefix.decode('utf-8'))

    send_push(title=title, message=message.decode('utf-8'))

    return w.WEECHAT_RC_OK
예제 #48
0
def show_item(data, item, window):
    bufpointer = weechat.window_get_pointer(window, "buffer")
    if bufpointer == "":
        return ""

    if weechat.buffer_get_string(
            bufpointer, 'name') != 'weechat':  # not weechat core buffer
        if weechat.buffer_get_string(
                bufpointer,
                'localvar_type') == '':  # buffer with free content?
            return ""

    lines_after, lines_count, percent, current_line = count_lines(
        window, bufpointer)

    if lines_count == 0:  # buffer empty?
        return ""

    tags = {
        '%C': str(current_line),
        '%A': str(lines_after),
        '%L': str(lines_count),
        '%P': str(percent) + "%"
    }

    bufsize_item = OPTIONS['format']

    # substitute colors in output
    for color_tag in regex_color.findall(bufsize_item):
        bufsize_item = bufsize_item.replace(
            color_tag, weechat.color(color_tag.lstrip('${').rstrip('}')))

    # replace mandatory tags
    for tag in tags.keys():
        bufsize_item = bufsize_item.replace(tag, tags[tag])

    # replace optional tags
    # %{…} only if lines after (e.g. %A > 0)
    if lines_after > 0:
        for regex_tag in regex_optional_tags.findall(bufsize_item):
            bufsize_item = bufsize_item.replace(
                regex_tag,
                regex_tag.lstrip('%{').rstrip('}'))
    else:
        bufsize_item = regex_optional_tags.sub('', bufsize_item)

    return bufsize_item
예제 #49
0
def priv_msg_cb(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight,
                prefix, message):
    """Sends highlighted message to be printed on notification"""

    if w.config_get_plugin("away_only") == "1":
        am_away = w.buffer_get_string(bufferp, 'localvar_away')
    else:
        am_away = True

    if not am_away:
        # TODO: make debug a configurable
        debug("Not away, skipping notification")
        return w.WEECHAT_RC_OK

    # If 'inactive_only' is enabled, we need to check if the notification is
    # coming from the active buffer.
    if w.config_get_plugin("inactive_only") == "1":
        if w.current_buffer() == bufferp:
            # The notification came from the current buffer - don't notify
            debug("Notification came from the active buffer, "
                  "skipping notification")
            return w.WEECHAT_RC_OK

    notif_body = u"<%s> %s" % (prefix, message)

    # Check that it's in a "/q" buffer and that I'm not the one writing the msg
    is_pm = w.buffer_get_string(bufferp, "localvar_type") == "private"
    is_notify_private = re.search(r'(^|,)notify_private(,|$)',
                                  tagsn) is not None
    # PM (query)
    if (is_pm and is_notify_private):
        send_push(title="Privmsg from %s" % prefix, body=notif_body)

    # Highlight (your nick is quoted)
    elif (str(ishilight) == "1"):
        bufname = (w.buffer_get_string(bufferp, "short_name")
                   or w.buffer_get_string(bufferp, "name"))

        ignored_channels = get_ignored_channels()

        if bufname not in ignored_channels:
            send_push(title="Highlight in %s" % bufname, body=notif_body)
        else:
            debug("[weejoin] Ignored channel, skipping notification in %s" %
                  bufname)

    return w.WEECHAT_RC_OK
예제 #50
0
def command_main(data, buffer, args):
  infolist = w.infolist_get("buffer", "", "")
  buffer_groups = {}
  results = []
  buffer_count = 0
  merge_count = 0
  numbers = set()
  while w.infolist_next(infolist):
    bplugin = w.infolist_string(infolist, "plugin_name")
    bname = w.infolist_string(infolist, "name")
    bpointer = w.infolist_pointer(infolist, "pointer")
    bnumber = w.infolist_integer(infolist, "number")
    btype = w.buffer_get_string(bpointer, 'localvar_type')
    if not bnumber in numbers:
      numbers.add(bnumber)
    else:
      merge_count += 1

    if btype == 'server':
      bdesc = 'servers'
    elif btype == 'channel':
      bdesc = 'channels'
    elif btype == 'private':
      bdesc = 'queries'
    else:
      bdesc = bplugin

    buffer_groups.setdefault(bdesc,[]).append({'name': bname, 'pointer': bpointer})

  w.infolist_free(infolist)

  infolist = w.infolist_get("window", "", "")
  windows_v = set()
  windows_h = set()
  windows = set()
  while w.infolist_next(infolist):
    window = w.infolist_pointer(infolist, "pointer")
    window_w = w.infolist_integer(infolist, "width_pct")
    window_h = w.infolist_integer(infolist, "height_pct")
    windows.add(window)
    if window_h == 100 and window_w != 100:
      windows_v.add(window)
    elif window_w == 100 and window_h != 100:
      windows_h.add(window)
    #else: #both 100%, thus no splits
  w.infolist_free(infolist)

  window_count = len(windows)

  for desc, buffers in buffer_groups.iteritems():
    buffer_count += len(buffers)
    results.append('%i %s' % (len(buffers), desc))

  buffer_stats = ', '.join(sorted(results, key = lambda item: (int(item.partition(' ')[0]) if item[0].isdigit() else float('inf'), item),reverse=True)) # descending numerical sort of strings
  stats_string = '%i buffers (%i merged): %s; %i windows' % (buffer_count, merge_count, buffer_stats, window_count)
  if '-split' in args:
    stats_string += ": %i vertically / %i horizontally split" % (len(windows_v), len(windows_h))
  w.command("", "/input insert %s" % stats_string)
  return w.WEECHAT_RC_OK
예제 #51
0
def ircrypt_command(data, buffer, args):
    '''Hook to handle the /ircrypt weechat command.
	'''
    argv = args.split()

    # list
    if not argv or argv == ['list']:
        return ircrypt_command_list()

    # Check if a server was set
    if (len(argv) > 2 and argv[1] == '-server'):
        server = argv[2]
        del argv[1:3]
        args = (args.split(' ', 2) + [''])[2]
    else:
        # Try to determine the server automatically
        server = weechat.buffer_get_string(buffer, 'localvar_server')

    # All remaining commands need a server name
    if not server:
        ircrypt_error('Unknown Server. Please use -server to specify server',
                      buffer)
        return weechat.WEECHAT_RC_ERROR

    if argv[:1] == ['plain']:
        return ircrypt_command_plain(buffer, server, args, argv)

    try:
        target = '%s/%s' % (server, argv[1])
    except:
        ircrypt_error('Unknown command. Try  /help ircrypt', buffer)
        return weechat.WEECHAT_RC_OK

    # Set keys
    if argv[:1] == ['set-key']:
        if len(argv) < 3:
            return weechat.WEECHAT_RC_ERROR
        return ircrypt_command_set_keys(target, ' '.join(argv[2:]))

    # Remove keys
    if argv[:1] == ['remove-key']:
        if len(argv) != 2:
            return weechat.WEECHAT_RC_ERROR
        return ircrypt_command_remove_keys(target)

    # Set special cipher for channel
    if argv[:1] == ['set-cipher']:
        if len(argv) < 3:
            return weechat.WEECHAT_RC_ERROR
        return ircrypt_command_set_cip(target, ' '.join(argv[2:]))

    # Remove secial cipher for channel
    if argv[:1] == ['remove-cipher']:
        if len(argv) != 2:
            return weechat.WEECHAT_RC_ERROR
        return ircrypt_command_remove_cip(target)

    ircrypt_error('Unknown command. Try  /help ircrypt', buffer)
    return weechat.WEECHAT_RC_OK
예제 #52
0
def buffer_get_float(buffer, property):
    """A variant of weechat.buffer_get_x() for floats.

    This variant is needed because WeeChat supports only buffer_get_string()
    and buffer_get_int().
    """
    value = weechat.buffer_get_string(buffer, property)
    return float(value) if value else 0.0
예제 #53
0
def print_cb(data, buf, date, tags, displayed, highlight, prefix, message):
    if highlight != 1 and weechat.buffer_get_string(
            buf, "localvar_type") != "private":
        return weechat.WEECHAT_RC_OK
    if ONLY_AWAY == True and len(
            weechat.buffer_get_string(buf, "localvar_away")) == 0:
        return weechat.WEECHAT_RC_OK
    if RATE_LIMITED == True:
        #weechat.prnt("", "I've been rate limited")
        return weechat.WEECHAT_RC_OK
    if PRIVATE_MESSAGE_CONTENT:
        message = "Message privacy option is enabled."
    bufname = weechat.buffer_get_string(buf, "short_name")
    msg = "[%s] <%s> %s" % (bufname, prefix, message)
    send_notif(msg)
    #weechat.prnt("", msg )
    return weechat.WEECHAT_RC_OK
예제 #54
0
def go_start(buffer):
    """ Start go on buffer """
    global saved_input, old_input, buffers_pos
    hook_all()
    saved_input = weechat.buffer_get_string(buffer, "input")
    weechat.buffer_set(buffer, "input", "")
    old_input = None
    buffers_pos = 0
예제 #55
0
def weechat_on_msg_cb(*a):

    keys = [
        'data', 'buffer', 'timestamp', 'tags', 'displayed', 'highlight',
        'sender', 'message'
    ]
    msg = dict(zip(keys, a))

    msg['buffer_long'] = weechat.buffer_get_string(msg['buffer'], 'name')
    msg['buffer_full'] = weechat.buffer_get_string(msg['buffer'], 'full_name')
    msg['buffer'] = weechat.buffer_get_string(msg['buffer'], 'short_name')

    mqttclient.publish(weechat.config_get_plugin('mqtt_channel'),
                       json.dumps(msg),
                       retain=True)

    return weechat.WEECHAT_RC_OK
예제 #56
0
def histsearch_start(buffer):
    """ Start histsearch on buffer """
    global saved_input, old_input, commands_pos
    hook_all()
    saved_input = w.buffer_get_string(buffer, "input")
    w.buffer_set(buffer, "input", "")
    old_input = None
    commands_pos = 0
예제 #57
0
def get_current_query_buffers():
    stored_query_buffers_per_server = {}

    ptr_infolist_buffer = weechat.infolist_get('buffer', '', '')
    while weechat.infolist_next(ptr_infolist_buffer):
        ptr_buffer = weechat.infolist_pointer(ptr_infolist_buffer,'pointer')

        buf_type = weechat.buffer_get_string(ptr_buffer, 'localvar_type')
        if buf_type == 'private':
            server_name = weechat.buffer_get_string(ptr_buffer, 'localvar_server')
            channel_name = weechat.buffer_get_string(ptr_buffer, 'localvar_channel')

            stored_query_buffers_per_server.setdefault(server_name, set([]))
            stored_query_buffers_per_server[server_name].add(channel_name)
    weechat.infolist_free(ptr_infolist_buffer)

    return stored_query_buffers_per_server
예제 #58
0
def airgram_show(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight,
                 prefix, message):

    if (bufferp == weechat.current_buffer()):
        pass

    elif weechat.buffer_get_string(bufferp, "localvar_type") == "private":
        buffer = (weechat.buffer_get_string(bufferp, "short_name")
                  or weechat.buffer_get_string(bufferp, "name"))
        show_notification("PM", prefix + ": " + message)

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

    return weechat.WEECHAT_RC_OK
예제 #59
0
def completer(data, completion_item, buffer, completion):
    channel = weechat.buffer_get_string(buffer, 'localvar_channel')
    if not weechat.info_get('irc_is_channel', channel):
        return WEECHAT_RC_OK

    server = weechat.buffer_get_string(buffer, 'localvar_server')
    input = weechat.buffer_get_string(buffer, 'input')
    type = input.split()[2]
    patterns = get_patterns_in_config('%s.%s.%s' %(server, channel, type))

    if not patterns:
        return WEECHAT_RC_OK

    for mask in patterns[(server, channel)][type]:
        weechat.hook_completion_list_add(completion, mask, 0, weechat.WEECHAT_LIST_POS_END)

    return WEECHAT_RC_OK
예제 #60
0
def my_completer(data, buffer, command):
    global latest_speaker
    str_input = weechat.buffer_get_string(weechat.current_buffer(), "input")
    if command == "/input complete_next" and str_input == '':
        nick = latest_speaker.get(buffer, "")
        if nick != "":
            weechat.command(buffer, '/input insert ' + nick + ':\\x20')
    return weechat.WEECHAT_RC_OK