예제 #1
0
def timer_cb(servbuf, remaining_calls):
    channels = queue.pop(servbuf)
    while channels:
        chanstring = ",".join(channels[:10])
        weechat.command(servbuf, "/join {}".format(chanstring))
        channels = channels[10:]
    return _OK
예제 #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 ccflx_cb(data, buffer, args):
    nick = weechat.buffer_get_string(weechat.current_buffer(), 'localvar_nick')
    repl = { 'a': 'â', 'c': 'ĉ', 'e': 'ê', 'g': 'ĝ', 'h': 'ĥ', 'i': 'î', 'j': 'ĵ', 'o': 'ô', 's': 'ŝ', 'u': 'û', 'w': 'ŵ', 'y': 'ŷ', 'z': 'ẑ' }
    for key, value in repl.iteritems():
        args = args.replace(key, value)
    weechat.command("", args)
    return weechat.WEECHAT_RC_OK
예제 #4
0
def lb_line_run():
  global lb_channels, lb_curline, lb_network
  buff = weechat.info_get("irc_buffer", lb_network)
  channel = lb_channels[lb_curline]['channel']
  command = "/join %s" % channel
  weechat.command(buff, command)
  return
예제 #5
0
파일: urlgrab.py 프로젝트: bradfier/configs
def keyEvent (data, bufferp, args):
    global urlGrab , urlGrabSettings, urlgrab_buffer, current_line
    if args == "refresh":
        refresh()
    elif args == "up":
        if current_line > 0:
            current_line = current_line -1
            refresh_line (current_line + 1)
            refresh_line (current_line)
            ugCheckLineOutsideWindow()
    elif args == "down":
         if current_line < len(urlGrab.globalUrls) - 1:
            current_line = current_line +1
            refresh_line (current_line - 1)
            refresh_line (current_line)
            ugCheckLineOutsideWindow()
    elif args == "scroll_top":
        temp_current = current_line
        current_line =  0
        refresh_line (temp_current)
        refresh_line (current_line)
        weechat.command(urlgrab_buffer, "/window scroll_top")
        pass 
    elif args == "scroll_bottom":
        temp_current = current_line
        current_line =  len(urlGrab.globalUrls)
        refresh_line (temp_current)
        refresh_line (current_line)
        weechat.command(urlgrab_buffer, "/window scroll_bottom")
    elif args == "enter":
        if urlGrab.globalUrls[current_line]:
            urlGrabOpenUrl (urlGrab.globalUrls[current_line]['url'])
예제 #6
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
예제 #7
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
예제 #8
0
파일: vimode.py 프로젝트: tarruda/dot-files
def key_C(buf, input_line, cur, count):
    """Delete from cursor to end of line and start Insert mode.
    See Also:
        `key_base()`.
    """
    weechat.command("", "/input delete_end_of_line")
    set_mode("INSERT")
예제 #9
0
def participants_cb(data, buffer, date, tags, displayed, highlight, prefix, message):
    """ Prints number of participants in the current jam. """
    current_jam_info = json.load(urllib2.urlopen(CURRENT_JAM_INFO_URL))
    buffer_name = weechat.buffer_get_string(buffer, "name")
    if(buffer_name in CHANNELS):
        weechat.command(buffer, "Number of participants: "+str(current_jam_info["participants_count"]))
    return weechat.WEECHAT_RC_OK
예제 #10
0
파일: vimode.py 프로젝트: tarruda/dot-files
def key_cc(buf, input_line, cur, count):
    """Delete line and start Insert mode.
    See Also:
        `key_base()`.
    """
    weechat.command("", "/input delete_line")
    set_mode("INSERT")
예제 #11
0
def private_opened_cb(data, signal, signal_data):
    buffer = signal_data
    short_name = weechat.buffer_get_string(buffer, "short_name")
    if _newserv_match(short_name):
        destination = _find_first_buffer_number()
        weechat.command(buffer, "/buffer merge {}".format(destination))
    return weechat.WEECHAT_RC_OK
예제 #12
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", "")
    weechat.buffer_set(lb_buffer, "title", lb_line_format({
      'channel': 'Channel name',
      'users': 'Users',
      'modes': 'Modes',
      'topic': 'Topic',
      'nomodes': None,
    }))
    # 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"))
예제 #13
0
def grabnick(servername, nick):
    if nick and servername:
        if OPTIONS['text']:
            t = Template( string_eval_expression(OPTIONS['text']) )
            text = t.safe_substitute(server=servername, nick=nick)
            weechat.prnt(weechat.current_buffer(), text)
        weechat.command(weechat.buffer_search('irc','%s.%s' % ('server',servername)), OPTIONS['command'] % nick)
예제 #14
0
def command_run_input(data, buffer, command):
    """ Function called when a command "/input xxxx" is run """
    global commands, commands_pos
    if command == "/input search_text" or command.find("/input jump") == 0:
        # search text or jump to another buffer is forbidden now
        return w.WEECHAT_RC_OK_EAT
    elif command == "/input complete_next":
        # choose next buffer in list
        commands_pos += 1
        if commands_pos >= len(commands):
            commands_pos = 0
        w.hook_signal_send("input_text_changed",
                                 w.WEECHAT_HOOK_SIGNAL_STRING, "")
        return w.WEECHAT_RC_OK_EAT
    elif command == "/input complete_previous":
        # choose previous buffer in list
        commands_pos -= 1
        if commands_pos < 0:
            commands_pos = len(commands) - 1
        w.hook_signal_send("input_text_changed",
                                 w.WEECHAT_HOOK_SIGNAL_STRING, "")
        return w.WEECHAT_RC_OK_EAT
    elif command == "/input return":
        # As in enter was pressed.
        # Put the current command on the input bar
        histsearch_end(buffer)
        if len(commands) > 0:
            w.command(buffer, "/input insert " + commands[commands_pos])
        return w.WEECHAT_RC_OK_EAT
    return w.WEECHAT_RC_OK
예제 #15
0
def send_messages(server, channel, nick):
    buffer = w.buffer_search("", "%s.%s" % (server, channel))
    messages = postpone_data[server][channel][nick]
    for time, msg in messages:
        tstr = strftime("%Y-%m-%d %H:%M:%S", time.timetuple())
        w.command(buffer, msg + " (This message has been postponed on " + tstr + ".)")
    messages[:] = []
예제 #16
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")
예제 #17
0
def catch_message(data, bufferp, tm, tags, display, is_hilight, prefix, msg):
    """
    server_name = (w.buffer_get_string(bufferp, "name").split("."))[0]
    own_name =  w.info_get("irc_nick", server_name)
    message_from = w.buffer_get_string(bufferp, "localvar_nick")

    logging.debug("Message caught!")
    logging.debug("From:" + message_from)
    logging.debug("Own Name:" + own_name)
    logging.debug("Server Name:" + server_name)
    logging.debug(w.buffer_get_string(bufferp, "localvar_type"))
    logging.debug(msg)
    """

    # Stop if message is from yourself.
    #    if len(msg) == 0 or own_name == message_from:
    if len(msg) == 0:
        return w.WEECHAT_RC_OK

    caught = has_less(msg)

    if caught is True:
        if textblob_analysis(msg) is True:
            #write fewer
            w.command(bufferp, "Stannisbot: fewer")

    return w.WEECHAT_RC_OK
예제 #18
0
파일: flip.py 프로젝트: aimeeble/dotfiles
def flip_hook(data, buffer, args):
    if not args:
        text = u'%s %s' % (flip(), table())
    else:
        text = u'%s %s' % (flip(), flip_text(args))
    weechat.command(buffer, text.encode('utf-8'))
    return weechat.WEECHAT_RC_OK
예제 #19
0
def asciiwrite_cmd (data, buffer, args):

    # On récupère les caractères
    args = [get_char(c) for c in args]

    height = 0
    for char in args:
        if len(char) > height:
            height = len(char)

    args = [ char + ['']*(height-len(char)) for char in args ]

    new_args = []
    for char in args:
        width = 0
        for line in char:
            if len(line) > width:
                width = len(line)
        new_args.append([ line + ' '*(width-len(line)) for line in char ])
    args = new_args

    ascii = [''] * len(args[0])

    for char in args:
        for i in range(len(char)):
            ascii[i] += char[i]

    for line in ascii:
        if line[0] == '/':
            line = '/'+line
        weechat.command (buffer, line)
    weechat.command (buffer, ' ')
    return weechat.WEECHAT_RC_OK
예제 #20
0
def fn_setip(data, command, return_code, out, err):
	global process_output
	process_output += out.strip()
	if int(return_code) >= 0:
		alert("Trying to set ip: '" + process_output + "'")
		w.command("", "/set xfer.network.own_ip %s" %process_output)
	return w.WEECHAT_RC_OK
예제 #21
0
def wg_cmd(data, buffer, args):
    """ Callback for /weeget command. """
    global wg_action, wg_action_args
    if args == "":
        weechat.command("", "/help %s" % SCRIPT_COMMAND)
        return weechat.WEECHAT_RC_OK
    argv = args.strip().split(" ", 1)
    if len(argv) == 0:
        return weechat.WEECHAT_RC_OK

    wg_action = ""
    wg_action_args = ""

    # check arguments
    if len(argv) < 2:
        if argv[0] == "show" or \
                argv[0] == "install" or \
                argv[0] == "remove":
            weechat.prnt("", "%s: too few arguments for action \"%s\""
                         % (SCRIPT_NAME, argv[0]))
            return weechat.WEECHAT_RC_OK

    # execute asked action
    if argv[0] == "update":
        wg_update_cache()
    else:
        wg_action = argv[0]
        wg_action_args = ""
        if len(argv) > 1:
            wg_action_args = argv[1]
        wg_read_scripts()

    return weechat.WEECHAT_RC_OK
예제 #22
0
파일: mpv.py 프로젝트: Luminarys/dotfiles
def mpv_np(data, buffer, args):
	filename, title, progress, duration = parse_info()
        color = "01,01"
        op = "/me nw: %s{} %s{}/{}" % ("11", "09")
	weechat.command(weechat.current_buffer(), 
	    op.format(filename, progress, duration))
	return weechat.WEECHAT_RC_OK
예제 #23
0
파일: go.py 프로젝트: thisismiller/dotfiles
def command_run_input(data, buffer, command):
    """ Function called when a command "/input xxxx" is run """
    global buffers, buffers_pos
    if command == "/input search_text" or command.find("/input jump") == 0:
        # search text or jump to another buffer is forbidden now
        return weechat.WEECHAT_RC_OK_EAT
    elif command == "/input complete_next":
        # choose next buffer in list
        buffers_pos += 1
        if buffers_pos >= len(buffers):
            buffers_pos = 0
        weechat.hook_signal_send("input_text_changed", weechat.WEECHAT_HOOK_SIGNAL_STRING, "")
        return weechat.WEECHAT_RC_OK_EAT
    elif command == "/input complete_previous":
        # choose previous buffer in list
        buffers_pos -= 1
        if buffers_pos < 0:
            buffers_pos = len(buffers) - 1
        weechat.hook_signal_send("input_text_changed", weechat.WEECHAT_HOOK_SIGNAL_STRING, "")
        return weechat.WEECHAT_RC_OK_EAT
    elif command == "/input return":
        # switch to selected buffer (if any)
        go_end(buffer)
        if len(buffers) > 0:
            weechat.command(buffer, "/buffer " + str(buffers[buffers_pos]["number"]))
        return weechat.WEECHAT_RC_OK_EAT
    return weechat.WEECHAT_RC_OK
예제 #24
0
파일: mpv.py 프로젝트: Luminarys/dotfiles
def mpvs_np(data, buffer, args):
	filename, title, progress = parse_info(False)
        color = "01,01"
        op = "/me np: %s{}%s for %s{}" % ("11", "", "09")
	weechat.command(weechat.current_buffer(), 
	    op.format(filename, progress))
	return weechat.WEECHAT_RC_OK
예제 #25
0
파일: vimode.py 프로젝트: jnbek/_weechat
def input_set(data, remaining_calls):
    """Set the input line's content."""
    buf = weechat.current_buffer()
    weechat.buffer_set(buf, "input", data)
    # move the cursor back to its position prior to setting the content
    weechat.command('', "/input move_next_char")
    return weechat.WEECHAT_RC_OK
예제 #26
0
def kickban_callback(data, times_left):
  details = data.split(":")
  buffer_ptr = weechat.buffer_search("irc", details[0])

  if buffer_ptr:
    weechat.command(buffer_ptr, "/unban " + details[1])
  return weechat.WEECHAT_RC_OK
예제 #27
0
파일: vimode.py 프로젝트: jnbek/_weechat
def key_w(buf, input_line, cur, repeat):
    """Simulate vi's behavior for the w key."""
    for _ in range(max([1, repeat])):
        weechat.command('', ("/input move_next_word\n/input move_next_word\n"
                             "/input move_previous_word"))
        if len(input_line[cur:].split(' ')) == 1:
            weechat.command('', "/input move_end_of_line")
예제 #28
0
파일: go.py 프로젝트: gilbertw1/scripts
def go_command_run_input(data, buf, command):
    """Function called when a command "/input xxx" is run."""
    global buffers, buffers_pos
    if command == '/input search_text' or command.find('/input jump') == 0:
        # search text or jump to another buffer is forbidden now
        return weechat.WEECHAT_RC_OK_EAT
    elif command == '/input complete_next':
        # choose next buffer in list
        buffers_pos += 1
        if buffers_pos >= len(buffers):
            buffers_pos = 0
        weechat.hook_signal_send('input_text_changed',
                                 weechat.WEECHAT_HOOK_SIGNAL_STRING, '')
        return weechat.WEECHAT_RC_OK_EAT
    elif command == '/input complete_previous':
        # choose previous buffer in list
        buffers_pos -= 1
        if buffers_pos < 0:
            buffers_pos = len(buffers) - 1
        weechat.hook_signal_send('input_text_changed',
                                 weechat.WEECHAT_HOOK_SIGNAL_STRING, '')
        return weechat.WEECHAT_RC_OK_EAT
    elif command == '/input return':
        # switch to selected buffer (if any)
        go_end(buf)
        if len(buffers) > 0:
            weechat.command(
                buf, '/buffer ' + str(buffers[buffers_pos]['full_name']))
        return weechat.WEECHAT_RC_OK_EAT
    return weechat.WEECHAT_RC_OK
예제 #29
0
def shortenurl(data, buffer, args):
  if len(args) == 0:
    weechat.command("","/help shortenurl")
  urls = re.findall('[a-z]{2,5}://[^\s()\[\]]*', args)
  for url in urls:
    shorten(buffer, url)
  return weechat.WEECHAT_RC_OK
예제 #30
0
def shell_process_cb(data, command, rc, stdout, stderr):
    """Callback for hook_process()."""
    global cmd_hook_process, cmd_buffer, cmd_stdout, cmd_stderr, cmd_send_to_buffer
    cmd_stdout += stdout
    cmd_stderr += stderr
    if int(rc) >= 0:
        if cmd_stdout:
            lines = cmd_stdout.rstrip().split('\n')
            if cmd_send_to_buffer == 'current':
                for line in lines:
                    weechat.command(cmd_buffer, '%s' % line)
            else:
                weechat.prnt(cmd_buffer, '')
                if cmd_send_to_buffer != 'new':
                    weechat.prnt(cmd_buffer, '%sCommand "%s" (rc %d), stdout:'
                                 % (SHELL_PREFIX, data, int(rc)))
                for line in lines:
                    weechat.prnt(cmd_buffer, ' \t%s' % line)
        if cmd_stderr:
            lines = cmd_stderr.rstrip().split('\n')
            if cmd_send_to_buffer == 'current':
                for line in lines:
                    weechat.command(cmd_buffer, '%s' % line)
            else:
                weechat.prnt(cmd_buffer, '')
                if cmd_send_to_buffer != 'new':
                    weechat.prnt(cmd_buffer, '%s%sCommand "%s" (rc %d), stderr:'
                                 % (weechat.prefix('error'), SHELL_PREFIX, data, int(rc)))
                for line in lines:
                    weechat.prnt(cmd_buffer, '%s%s' % (weechat.prefix('error'), line))
        cmd_hook_process = ''
        shell_set_title()
    return weechat.WEECHAT_RC_OK
예제 #31
0
def cb_key_alt_j():
    """Callback for `key_alt_j()`.

    See Also:
        `start_catching_keys()`.
    """
    global catching_keys_data
    weechat.command("", "/buffer " + catching_keys_data['keys'])
    catching_keys_data = {'amount': 0}
예제 #32
0
def grabnick(servername, nick):
    if nick and servername:
        if OPTIONS['text']:
            t = Template(string_eval_expression(OPTIONS['text']))
            text = t.safe_substitute(server=servername, nick=nick)
            weechat.prnt(weechat.current_buffer(), text)
        weechat.command(
            weechat.buffer_search('irc', '%s.%s' % ('server', servername)),
            OPTIONS['command'] % nick)
예제 #33
0
def on_command(data, buffer, sargs):
    server = w.buffer_get_string(buffer, 'localvar_server')
    args = shlex.split(sargs)
    def_dur = w.config_get_plugin("default-duration")

    pieces = [
        "KLINE",  # command
        def_dur,  # duration
        None,  # user@host
        None,  # ON
        None,  # server
        None  # reason|operreason
    ]
    dryrun = False
    i = 0
    while i < len(args):
        arg = args[i]
        if arg.startswith("+"):
            args.pop(i)
            duration = from_pretty_time(arg[1:])
            if duration is not None:
                pieces[1] = str(duration)
            else:
                raise ValueError("incorrect kline duration")
        elif arg in ["-t", "--target"]:
            args.pop(i)
            if args[i:]:
                pieces[3] = "ON"
                pieces[4] = args.pop(i)
            else:
                raise ValueError("please provide a target server")
        elif arg in ["-d", "--dry"]:
            args.pop(i)
            dryrun = True
        else:
            i += 1
    pieces[2] = args[0]
    if args[1:]:
        pieces[5] = args[1]
        if args[2:]:
            pieces[5] += f"|{args[2]}"

    pieces = list(filter(bool, pieces))
    if " " in pieces[-1] or pieces[-1].startswith(":"):
        pieces[-1] = f":{pieces[-1]}"
    line = " ".join(pieces)

    if dryrun:
        color = w.color("green")
        reset = w.color("reset")
        sbuffer = w.info_get("irc_buffer", server)

        w.prnt(sbuffer, f"[{color}humankline{reset}] {line}")
    else:
        w.command("", f"/quote -server {server} {line}")
    return w.WEECHAT_RC_OK
예제 #34
0
def auth_command(data, buffer, args):
    list_args = args.split(" ")
    server, channel = get_channel_from_buffer_args(buffer, args)
    #strip spaces
    while '' in list_args:
        list_args.remove('')
    while ' ' in list_args:
        list_args.remove(' ')

    if len(list_args) == 0:
        weechat.command("/help auth")
    elif list_args[0] not in ["add", "del", "list", "cmd"]:
        weechat.prnt(
            buffer,
            "[%s] bad option while using /auth command, try '/help auth' for more info"
            % (NAME))
    elif list_args[0] == "cmd":
        if len(list_args[1:]) == 1 and list_args[1] in weechat.get_server_info(
        ).keys():
            auth_cmd("", list_args[1])
        elif len(list_args[1:]) == 1:
            auth_cmd(list_args[1], server)
        elif len(list_args[1:]) >= 2:
            if list_args[-1] in weechat.get_server_info().keys():
                auth_cmd(" ".join(list_args[1:-1]), list_args[-1])
            else:
                auth_cmd(" ".join(list_args[1:]), server)
        else:
            auth_cmd(" ".join(list_args[1:]), server)
    elif list_args[0] == "list":
        auth_list()
    elif list_args[0] == "add":
        if len(list_args) < 3 or (len(list_args) == 3 and server == ''):
            weechat.prnt(
                buffer,
                "[%s] bad option while using /auth command, try '/help auth' for more info"
                % (NAME))
        else:
            if len(list_args) == 3:
                auth_add(list_args[1], list_args[2], server)
            else:
                auth_add(list_args[1], list_args[2], list_args[3])
    elif list_args[0] == "del":
        if len(list_args) < 2:
            weechat.prnt(
                buffer,
                "[%s] bad option while using /auth command, try '/help auth' for more info"
                % (NAME))
        else:
            if len(list_args) == 2:
                auth_del(list_args[1], server)
            else:
                auth_del(list_args[1], list_args[2])
    else:
        pass
    return weechat.WEECHAT_RC_OK
예제 #35
0
파일: bufsave.py 프로젝트: gsec/dotfiles
def bufsave_cmd(data, buffer, args):
    ''' Callback for /bufsave command '''

    filename = args

    if not filename:
        w.command('', '/help %s' % SCRIPT_COMMAND)
        return w.WEECHAT_RC_OK

    if exists(filename):
        w.prnt('', 'Error: target file already exists!')
        return w.WEECHAT_RC_OK

    try:
        fp = open(filename, 'w')
    except:
        w.prnt('', 'Error writing to target file!')
        return w.WEECHAT_RC_OK

    version = w.info_get('version_number', '') or 0
    if int(version) >= 0x00030600:
        # use hdata with WeeChat >= 0.3.6 (direct access to data, very fast)
        own_lines = w.hdata_pointer(w.hdata_get('buffer'), buffer, 'own_lines')
        if own_lines:
            line = w.hdata_pointer(w.hdata_get('lines'), own_lines,
                                   'first_line')
            hdata_line = w.hdata_get('line')
            hdata_line_data = w.hdata_get('line_data')
            while line:
                data = w.hdata_pointer(hdata_line, line, 'data')
                if data:
                    date = w.hdata_time(hdata_line_data, data, 'date')
                    # since WeeChat 0.3.9, hdata_time returns long instead of string
                    if not isinstance(date, str):
                        date = time.strftime('%F %T',
                                             time.localtime(int(date)))
                    fp.write('%s %s %s\n' %(\
                            date,
                            cstrip(w.hdata_string(hdata_line_data, data, 'prefix')),
                            cstrip(w.hdata_string(hdata_line_data, data, 'message')),
                            ))
                line = w.hdata_move(hdata_line, line, 1)
    else:
        # use infolist with WeeChat <= 0.3.5 (full duplication of lines, slow and uses memory)
        infolist = w.infolist_get('buffer_lines', buffer, '')
        while w.infolist_next(infolist):
            fp.write('%s %s %s\n' %(\
                    w.infolist_time(infolist, 'date'),
                    cstrip(w.infolist_string(infolist, 'prefix')),
                    cstrip(w.infolist_string(infolist, 'message')),
                    ))
        w.infolist_free(infolist)

    fp.close()

    return w.WEECHAT_RC_OK
def add_key_to_list(server, channel, new_key):
    autojoin_list = get_autojoin(server)
    if not autojoin_list:
        return weechat.WEECHAT_RC_OK

    # check autojoin for space
    if len(re.findall(r" ", autojoin_list)) == 0:
        weechat.prnt(
            '', '%s%s: no password(s) set in autojoin for server "%s".' %
            (weechat.prefix('error'), SCRIPT_NAME, server))
        return weechat.WEECHAT_RC_OK
    if len(re.findall(r" ", autojoin_list)) > 1:
        weechat.prnt(
            '',
            '%s%s: autojoin format for server "%s" invalid (two or more spaces).'
            % (weechat.prefix('error'), SCRIPT_NAME, server))
        return weechat.WEECHAT_RC_OK

    # split autojoin option to a channel and a key list
    arg_channel, arg_keys = autojoin_list.split(' ')
    argv_channels = arg_channel.split(',')
    argv_keys = arg_keys.split(',')

    # search for channel name in list of channels and get position
    if channel in argv_channels:
        channel_pos_in_list = argv_channels.index(channel)
        # enough keys in list? list counts from 0!
        if channel_pos_in_list + 1 > len(argv_keys):
            weechat.prnt(
                '',
                '%s%s: not enough keys in list or channel position is not valid. check out autojoin option for server "%s".'
                % (weechat.prefix('error'), SCRIPT_NAME, server))
            return weechat.WEECHAT_RC_OK

        sec_data = check_key_for_secure(argv_keys, channel_pos_in_list)

        # check weechat version and if secure option is on and secure data will be used for this key?
        if int(version) >= 0x00040200 and OPTIONS['secure'].lower(
        ) == 'on' and sec_data == 1:
            sec_data_name = argv_keys[channel_pos_in_list][11:-1]
            weechat.command(
                '',
                '%s/secure set %s %s' % (use_mute(), sec_data_name, new_key))
        else:
            if sec_data == 1:
                weechat.prnt(
                    '',
                    '%s%s: key for channel "%s.%s" not changed! option "plugins.var.python.%s.secure" is off and you are using secured data for key.'
                    % (weechat.prefix('error'), SCRIPT_NAME, server, channel,
                       SCRIPT_NAME))
                return weechat.WEECHAT_RC_OK
            argv_keys[channel_pos_in_list] = new_key
            new_joined_option = '%s %s' % (','.join(argv_channels),
                                           ','.join(argv_keys))
            save_autojoin_option(server, new_joined_option)
    return weechat.WEECHAT_RC_OK
예제 #37
0
def msg_cb(data, buffer, date, tags, displayed, is_hilight, prefix, msg):
  reply = w.config_get_plugin('reply_text')
  if not w.buffer_get_string(buffer, "localvar_type") == "private":
    reply = prefix + ": " + reply
    if is_hilight and msg.endswith('ping'):
      w.command(buffer, reply)
  elif msg == 'ping':
      w.command(buffer, reply)

  return w.WEECHAT_RC_OK
예제 #38
0
def himan_command(data, buffer, args):
    global himan_buffer

    if not himan_buffer:
        w.prnt("", SCRIPT_NAME + ": no himan buffer found, recreating...")
        himan_buffer_create()

    w.command("", "/buffer " + w.buffer_get_string(himan_buffer, "name"))

    return w.WEECHAT_RC_OK
예제 #39
0
def cmd_quickbuffer(data, buffer, command):
    """Any command being run will be checked to see if it matches /<number>, and intercepted if it does"""

    match = QUICKBUFFER_REGEXP.match(command)

    if match:
        w.command(buffer, "/buffer {}".format(match.group(1)))
        return w.WEECHAT_RC_OK_EAT

    return w.WEECHAT_RC_OK
예제 #40
0
def mpv_np(*args, **kwargs):
    try:
        info = mpv_info()
    except Exception as e:
        wc.prnt(wc.current_buffer(),
                'Failed to get mpv info (is socket available?): {}'.format(e))
        return wc.WEECHAT_RC_ERROR
    npstring = Template(wc.config_get_plugin('format')).safe_substitute(info)
    wc.command(wc.current_buffer(), '/me ' + npstring)
    return wc.WEECHAT_RC_OK
예제 #41
0
def execbot_process(buffer, command, return_code, out, err):
    '''Execute the command and return to buffer.'''
    message = "%s ... | $? = %d\n" % (command.split()[0], return_code)
    if out != "":
        message += out
    if err != "":
        message += err

    weechat.command(buffer, message)
    return weechat.WEECHAT_RC_OK
예제 #42
0
def mpv_np_screenshot(*args, **kwargs):
    try:
        info = mpv_info()
        info['url'] = mpv_take_screenshot(info['filename'], info['playbacktime'])
    except Exception as e:
        wc.prnt(wc.current_buffer(), 'Failed to get mpv info (is socket available?): {}'.format(e))
        return wc.WEECHAT_RC_ERROR
    npstring = Template(wc.config_get_plugin('format-ss')).safe_substitute(info)
    wc.command(wc.current_buffer(), '/me ' + npstring)
    return wc.WEECHAT_RC_OK
예제 #43
0
def cmd_fullwidth(data, buf, args):
    chars = list()
    for char in list(args):
        if ord(char) == 32:
            char = chr(12288)
        elif ord(char) > 32 and ord(char) <= 126:
            char = chr(ord(char) + 65248)
        chars.append(char)
    weechat.command(buf, '/input send ' + ''.join(chars))
    return weechat.WEECHAT_RC_OK
예제 #44
0
파일: vimode.py 프로젝트: alejandraa/home
def key_w(repeat):
    """Simulate vi's behavior for the w key."""
    buf = weechat.current_buffer()
    for _ in range(max([1, repeat])):
        input_line = weechat.buffer_get_string(buf, 'input')
        cur = weechat.buffer_get_integer(buf, "input_pos")
        weechat.command('', ("/input move_next_word\n/input move_next_word\n"
                             "/input move_previous_word"))
        if len(input_line[cur:].split(' ')) == 1:
            weechat.command('', "/input move_end_of_line")
예제 #45
0
def remove_server(server, remove_seed=False):
    """ Remove server from the plugin configuration. """
    if remove_seed and weechat.string_eval_expression(
            "${sec.data.%s_seed}" % server, {}, {}, {}):
        weechat.command("", "/secure del %s_seed" % server)

    servers = get_config_as_list("otp_server_names")
    if server in servers:
        servers = [v for v in servers if v != server]
        weechat.config_set_plugin("otp_server_names", ','.join(servers))
예제 #46
0
def enable_check(log_level,buffer):
    log_level = buffer_get_string_log_level(buffer)
    if log_level:
        if not str(log_level).isnumeric() or (int(log_level) < 0) or (int(log_level) > 9):
            log_level = 9 # invalid log level, set default
        weechat.command(buffer,'/logger set %s' % log_level)
        buffer_del_log_level(buffer)
    else:   # no logging and no localvar.
        weechat.command(buffer,'/logger set 9')
    return weechat.WEECHAT_RC_OK
예제 #47
0
    def restore_logging(self, previous_log_level):
        """Restore the log level of the buffer."""
        buf = self.buffer()

        if (previous_log_level >= 0) and (previous_log_level < 10):
            self.print_buffer('Restoring buffer logging value to: %s' %
                              previous_log_level)
            weechat.command(buf, '/mute logger set %s' % previous_log_level)

        del self.previous_log_level
예제 #48
0
def twitch_reconnect(data, modifier, modifier_data, string):
    server = modifier_data
    buffer = weechat.buffer_search("irc", "server.%s" % server)
    if buffer:
        pcolor = weechat.color('chat_prefix_network')
        ccolor = weechat.color('chat')
        weechat.prnt(
            buffer, "%s--%s Server sent reconnect request. Issuing /reconnect" % (pcolor, ccolor))
        weechat.command(buffer, "/reconnect")
    return ""
예제 #49
0
def weather_data_cb(data, command, rc, stdout, stderr):
    '''
    Callback for the data fetching process.
    '''
    global last_city, last_run
    global gweather_hook_process, gweather_stdout, gweather_output

    if rc == weechat.WEECHAT_HOOK_PROCESS_ERROR or stderr != '':
        weechat.prnt('', '%sgweather: Weather information fetching failed: %s' % (\
            weechat.prefix("error"), stderr))
        return weechat.WEECHAT_RC_ERROR

    if stdout:
        gweather_stdout += stdout

    if int(rc) < 0:
        # Process not ready
        return weechat.WEECHAT_RC_OK

    # Update status variables for succesful run
    last_run = time()
    last_location = weechat.config_get_plugin('location')
    gweather_hook_process = ''

    if not gweather_stdout:
        return weechat.WEECHAT_RC_OK

    try:
        # The first row should contain "content-type" from HTTP header
        content_type, xml_response = gweather_stdout.split('\n', 1)
    except:
        # Failed to split received data in two at carridge return
        weechat.prnt(
            '', '%sweather: Invalid data received' % (weechat.prefix("error")))
        gweather_stdout = ''
        return weechat.WEECHAT_RC_ERROR

    gweather_stdout = ''

    # Determine the used character set in the response
    try:
        charset = content_type.split('charset=')[1]
    except:
        charset = 'utf-8'

    if charset.lower() != 'utf-8':
        xml_response = xml_response.decode(charset).encode('utf-8')

    # Feed the respose to parser and parsed data to formatting
    weather_data = parse_google_weather(xml_response)
    gweather_output = format_weather(weather_data)
    if gweather_output:
        weechat.command(weechat.current_buffer(), gweather_output)

    return weechat.WEECHAT_RC_OK
예제 #50
0
파일: go.py 프로젝트: PairUp/irc-dots
def go_now(buffer, args):
    """ Go to buffer specified by args """
    buffers = get_matching_buffers(args)
    # Prefer buffer that matches at beginning
    for index in range(len(buffers)):
        if re.search(r"^#?" + re.escape(args), buffers[index]["name"]):
            weechat.command(buffer, "/buffer " + str(buffers[index]["number"]))
            return None
    # Otherwise, just take first buffer in list
    if len(buffers) > 0:
        weechat.command(buffer, "/buffer " + str(buffers[0]["number"]))
예제 #51
0
파일: allquery.py 프로젝트: 48ca/dot-files
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
    current_server = None

    if '-current' in argv:
        current_server = weechat.buffer_get_string(weechat.current_buffer(),
                                                   "localvar_server")
        # remove "-current" + whitespace from argumentlist
        args = args.replace("-current", "")
        args = args.lstrip()
        argv.remove("-current")

    # search for "-exclude" in arguments
    i = 0
    for entry in argv[0:]:
        if entry.startswith("-exclude="):
            exclude_nick = make_list(argv[i])
            command = " ".join(argv[i + 1::])
            break
        i += 1
    else:
        command = args

    # no command found.
    if not command:
        return weechat.WEECHAT_RC_OK

    if not command.startswith("/"):
        command = "/%s" % command

    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'\$nick', query, command)
            if weechat.buffer_get_string(ptr, "localvar_type") == "private":
                if current_server is not None:
                    if server == current_server:
                        exclude_nick_and_server(ptr, query, server,
                                                exclude_nick, execute_command)
                else:
                    exclude_nick_and_server(ptr, query, server, exclude_nick,
                                            execute_command)
    weechat.infolist_free(infolist)
    return weechat.WEECHAT_RC_OK
예제 #52
0
def timer_cb(data, remaining_calls):
    """Timer callback."""
    buf, level, network, channel, nick = reop_data['cmd'].pop()

    if _level(network, channel, nick) < level:
        if level == 2:
            command(buf, '/mode {} +o {}'.format(channel, nick))
        elif level == 1:
            command(buf, '/mode {} +v {}'.format(channel, nick))

    return WEECHAT_RC_OK
예제 #53
0
def say(srv, chn, msg, cmd="say"):
    global shout_tokens
    buffer = weechat.info_get("irc_buffer", srv + "," + chn)
    if not buffer:
        return
    if shout_tokens > 0 and not 'http' in msg:
        shout_tokens -= 1
        msg = msg.upper()
    if len(msg) > 350:
        msg = msg[:350] + "... aight ENOUGH"
    weechat.command(buffer, "/" + cmd + " " + msg)
예제 #54
0
def filter_addreplace(name, buffers, tags, regex):
    """
	Add (or replace if already exists) a filter named "name" with specified argumets.
	"""

    if filter_exists(name):
        filter_del(name)

    weechat.command(
        weechat.buffer_search_main(),
        "/mute filter add %s %s %s %s" % (name, buffers, tags, regex))
예제 #55
0
def mplayer_msg(world, world_eol, userdata):
    fn = getFilename()
    ver = getVersion()
    if type(fn) == str:
        # we've got a string for fn
        all = '/me is now watching: ' + fn + ' [' + ver + ']'
        weechat.command(weechat.current_buffer(), all)
        return 0
    else:
        # we've got None (or something went very-very wrong)
        return 1
예제 #56
0
 def np(self):
     """Pushes result of np template substitution to current buffer.
     """
     ds = self.currentsong()
     if len(ds) == 0:
         wc.prnt(self.wcb or wc.current_buffer(),
                 "MPC: ERROR: mpd is stopped")
         return
     wc.command(
         self.wcb or wc.current_buffer(),
         Template(wc.config_get_plugin("format")).safe_substitute(ds))
예제 #57
0
def weather_cb(server, buffer, argList):
    ''' Callback for the Google weather bar item. '''
    global last_run, last_city, current_city
    global gweather_output, gweather_hook_process

    if (argList.partition(" ")[0] == "default"):
        weechat.config_set_plugin('city', argList.partition(" ")[2])
        current_city = weechat.config_get_plugin('city')
        weechat.prnt(weechat.current_buffer(),
                     "Saving new location as: %s" % current_city)

    if (argList == '' and weechat.config_get_plugin('city') == ''):
        weechat.prnt(weechat.current_buffer(),
                     "Error: no default city, provide one with command")
        return weechat.WEECHAT_RC_ERROR

    if (len(argList) > 0):
        if (weechat.config_get_plugin('city') == ''):
            weechat.config_set_plugin('city', argList)
        current_city = argList
    else:
        current_city = weechat.config_get_plugin('city')

    location_id, hl = map(quote, (current_city, \
                                  weechat.config_get_plugin('language')))
    url = GOOGLE_WEATHER_URL % (location_id, hl)

    # Use cached copy if it is updated recently enough
    if current_city == last_city and \
       (time() - last_run) < (int(weechat.config_get_plugin('interval')) * 60):
        weechat.command(weechat.current_buffer(), gweather_output)
        return weechat.WEECHAT_RC_OK

    last_city = current_city

    command = 'urllib2.urlopen(\'%s\')' % (url)

    if gweather_hook_process != "":
        weechat.unhook(gweather_hook_process)
        gweather_hook_process = ''

    # Fire up the weather informationg fetching
    python2_bin = weechat.info_get("python2_bin", "") or "python"
    gweather_hook_process = weechat.hook_process(\
        python2_bin + " -c \"import urllib2;\
                     handler = "                                 + command + ";\
                     print handler.info().dict['content-type'];\
                     print handler.read();\
                     handler.close();\""                                        ,
        int(weechat.config_get_plugin('timeout')) * 1000, "weather_data_cb", "")

    # The old cached string is returned here. gweather_data_cb() will
    # request a new update after the data is fetched and parsed.
    return weechat.WEECHAT_RC_OK
예제 #58
0
def twitter_cb(data, command, rc, stdout, stderr):
        global cmd_hook_process, cmd_buffer, cmd_stdout, cmd_stderr
        cmd_stdout += stdout
        cmd_stderr += stderr
        if int(rc) >= 0:
                if cmd_stderr != "":
                        weechat.prnt(cmd_buffer, "%s" % cmd_stderr)
                if cmd_stdout != "":
                        weechat.command(cmd_buffer, weechat.config_get_plugin("command") % cmd_stdout)
                cmd_hook_process = ""
        return weechat.WEECHAT_RC_OK
예제 #59
0
def exclude_hotlist():
    if OPTIONS['hotlist'] == '0' or OPTIONS['hotlist'] == '':
        return weechat.WEECHAT_RC_OK
    infolist = weechat.infolist_get('hotlist', '', '')
    while weechat.infolist_next(infolist):
        buffer_number = weechat.infolist_integer(infolist, 'buffer_number')
        priority = weechat.infolist_integer(infolist, 'priority')
        if int(OPTIONS['hotlist']) == priority or OPTIONS['hotlist'] == '4':
            weechat.command('', '/buffer unhide %s' % buffer_number)
    weechat.infolist_free(infolist)
    return weechat.WEECHAT_RC_OK
예제 #60
0
def ws_command(data, buffer, args):
    try:
        artist, title = dbc.get_song()
        string = u"%s♫ %sNow playing:%s %s%s - %s%s %s♫" % (
            "\x034", "\x0312", "\x038\x02\x02", artist, "\x0312",
            "\x039\x02\x02", title, "\x034")
        weechat.command(buffer, string)
    except Exception as err:
        weechat.prnt("", "%sException: %s" % (weechat.prefix("error"), err))
    finally:
        return weechat.WEECHAT_RC_OK