Exemple #1
0
def main():
    logger.debug("Preparing to register")
    try:
        if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION,
                            SCRIPT_LICENSE, SCRIPT_DESC, 'shutdown', ''):
            init_config()
            weechat.hook_config('plugins.var.python.%s.*' % SCRIPT_NAME,
                                'config_changed', '')
            signal_help = [
                "number: the full number (including country code) to send to",
                "message: the text of the message to send"
            ]
            logger.debug("Registering command...")
            weechat.hook_command("smsg", "Send a message to someone on signal",
                                 "[number] [message]", "\n".join(signal_help),
                                 "%(message)", "send", "")
            weechat.hook_command("signal", "Interact with Signal", "[action]",
                                 "help coming soon...", "%(message)",
                                 "signal_cmd_cb", "")
            for signal in [
                    'quit', 'signal_sighup', 'signal_sigquit',
                    'signal_sigterm', 'upgrade'
            ]:
                weechat.hook_signal(signal, 'kill_daemon', '')
            weechat.hook_signal('upgrade_ended', 'launch_daemon', '')
            if options.get('autoupgrade') == 'on':
                weechat.hook_timer(3 * 24 * 60 * 60 * 1000, 0, 0,
                                   'check_update', '', 'install')
    except Exception:
        logger.exception("Failed to initialize plugin.")
Exemple #2
0
def on_signal(data, signal, signal_data):
    global signal_delay_timer
    global sort_queued

    # If the sort limit timeout is started, we're in the hold-off time after sorting, just queue a sort.
    if sort_limit_timer is not None:
        if sort_queued:
            debug(
                'Signal {0} ignored, sort limit timeout is active and sort is already queued.'
                .format(signal))
        else:
            debug(
                'Signal {0} received but sort limit timeout is active, sort is now queued.'
                .format(signal))
        sort_queued = True
        return weechat.WEECHAT_RC_OK

    # If the signal delay timeout is started, a signal was recently received, so ignore this signal.
    if signal_delay_timer is not None:
        debug(
            'Signal {0} ignored, signal delay timeout active.'.format(signal))
        return weechat.WEECHAT_RC_OK

    # Otherwise, start the signal delay timeout.
    debug(
        'Signal {0} received, starting signal delay timeout of {1} ms.'.format(
            signal, config.signal_delay))
    weechat.hook_timer(config.signal_delay, 0, 1, "on_signal_delay_timeout",
                       "")
    return weechat.WEECHAT_RC_OK
def add_invite(server, channel):
    servbuf = _server_buffer(server)
    if servbuf not in queue:
        queue[servbuf] = [channel]
        weechat.hook_timer(1000, 0, 1, "timer_cb", servbuf)
    else:
        queue[servbuf].append(channel)
Exemple #4
0
def conf_update_cb(data, option, value):
    #Commit data if not part of ignore list.
    if weechat.config_get_plugin("commit_each_change") == "true"  and not option in weechat.config_get_plugin("auto_commit_ignore").split(","):
        #Call use pause else /save will be called before the config is actually saved to disc
        #This is kinda hack but better input would be appricated.
        weechat.hook_timer(500, 0, 1, "commit_cb", "")
    return weechat.WEECHAT_RC_OK
Exemple #5
0
def a_notify(bname, nclass, title, description, priority=pynotify.URGENCY_LOW):
    '''Creates or updates the notification'''
    is_away = STATE['is_away']
    icon = STATE['icon']
    time_out = int(weechat.config_get_plugin("timeout"))
    cur_time = time.time()
    threshold = 1.0
    refresh = 0.01

    try:
        BUFFERS[bname].append(
                description,
                merge=weechat.config_get_plugin("merge") == "on",
                )
    except KeyError:
        BUFFERS[bname] = BufferState(
                title,
                threshold,
                refresh,
                icon=icon,
                priority=priority,
                timeout=time_out,
                )
        BUFFERS[bname].append(
                description,
                merge=weechat.config_get_plugin("merge") == "on",
                )
        weechat.hook_timer(500, 0, 1, "cb_buffer_start", bname)
Exemple #6
0
def main():
    if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, "", ""):
        version = int(weechat.info_get("version_number", "")) or 0

        # unset unused setting from older versions of script
        if weechat.config_is_set_plugin("display_unit"):
            weechat.prnt("", "Option plugins.var.python.bandwidth.display_unit no longer used, removing.")
            weechat.config_unset_plugin("display_unit")

        # set default settings
        for option in SCRIPT_SETTINGS.iterkeys():
            if not weechat.config_is_set_plugin(option):
                weechat.config_set_plugin(option, SCRIPT_SETTINGS[option][0])
            if version >= 0x00030500:
                weechat.config_set_desc_plugin(option, SCRIPT_SETTINGS[option][1])

        # ensure sane refresh_rate setting
        if int(weechat.config_get_plugin("refresh_rate")) < 1:
            weechat.prnt(
                "",
                "{}Invalid value for option plugins.var.python.bandwidth.refresh_rate, setting to default of {}".format(
                    weechat.prefix("error"), SCRIPT_SETTINGS["refresh_rate"][0]
                ),
            )
            weechat.config_set_plugin("refresh_rate", SCRIPT_SETTINGS["refresh_rate"][0])

        # create the bandwidth monitor bar item
        weechat.bar_item_new("bandwidth", "bandwidth_item_cb", "")
        # update it every plugins.var.python.bandwidth.refresh_rate seconds
        weechat.hook_timer(int(weechat.config_get_plugin("refresh_rate")) * 1000, 0, 0, "bandwidth_timer_cb", "")
Exemple #7
0
def main():
    if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, "", ""):
        version = int(weechat.info_get('version_number', '')) or 0

        # unset unused setting from older versions of script
        if weechat.config_is_set_plugin('display_unit'):
            weechat.prnt("", "Option plugins.var.python.bandwidth.display_unit no longer used, removing.")
            weechat.config_unset_plugin('display_unit')

        # set default settings
        for option in SCRIPT_SETTINGS.keys():
            if not weechat.config_is_set_plugin(option):
                value = SCRIPT_SETTINGS[option][0]
                if isinstance(value, str):
                    pass
                elif isinstance(value, bytes):
                    pass
                elif isinstance(value, unicode):
                    value = value.encode('utf8')
                weechat.config_set_plugin(option, value)
            if version >= 0x00030500:
                weechat.config_set_desc_plugin(option, SCRIPT_SETTINGS[option][1])

        # ensure sane refresh_rate setting
        if int(weechat.config_get_plugin('refresh_rate')) < 1:
            weechat.prnt("", "{}Invalid value for option plugins.var.python.bandwidth.refresh_rate, setting to default of {}".format(weechat.prefix("error"), SCRIPT_SETTINGS['refresh_rate'][0]))
            weechat.config_set_plugin('refresh_rate', SCRIPT_SETTINGS['refresh_rate'][0])

        # create the bandwidth monitor bar item
        weechat.bar_item_new('bandwidth', 'bandwidth_item_cb', '')
        # update it every plugins.var.python.bandwidth.refresh_rate seconds
        weechat.hook_timer(int(weechat.config_get_plugin('refresh_rate'))*1000, 0, 0, 'bandwidth_timer_cb', '')
Exemple #8
0
def main():
    '''Sets up WeeChat notifications.'''
    # Initialize options.
    for option, value in SETTINGS.items():
        if not weechat.config_is_set_plugin(option):
            weechat.config_set_plugin(option, value)
    # Initialize.
    name = "WeeChat"
    icon = "/usr/share/pixmaps/weechat.xpm"
    notifications = [
        'Public',
        'Private',
        'Action',
        'Notice',
        'Invite',
        'Highlight',
        'Server',
        'Channel',
        'DCC',
        'WeeChat'
    ]
    STATE['icon'] = icon
    # Register hooks.
    weechat.hook_signal(
        'irc_server_connected',
        'cb_irc_server_connected',
        '')
    weechat.hook_signal(
        'irc_server_disconnected',
        'cb_irc_server_disconnected',
        '')
    weechat.hook_signal('upgrade_ended', 'cb_upgrade_ended', '')
    weechat.hook_print('', '', '', 1, 'cb_process_message', '')
    weechat.hook_timer(1000, 1, 65535, "cb_buffer_tick", "")
    pynotify.init(name)
Exemple #9
0
def cb_update_line_numbers(data, signal, signal_data):
    """Call `cb_timer_update_line_numbers()` when switching buffers.
    A timer is required because the bar item is refreshed before the new buffer
    is actually displayed, so ``win_chat_height`` would refer to the old
    buffer. Using a timer refreshes the item after the new buffer is displayed.
    """
    weechat.hook_timer(10, 0, 1, "cb_timer_update_line_numbers", "")
    return weechat.WEECHAT_RC_OK
def send_typing(nick, level):
    if not channel_has_nick(bitlbee_server_name, bitlbee_channel, nick):
        return
    cookie = sending_typing.get(nick, 1) + 1
    if not sending_typing.get(nick, None):
        send_typing_ctcp(nick, level)
    sending_typing[nick] = cookie
    w.hook_timer(4000, 0, 1, "typing_disable_timer", "%s:%i" % (nick, cookie))
Exemple #11
0
def send_typing(nick, level):
    if not channel_has_nick(bitlbee_server_name, bitlbee_channel, nick):
        return
    cookie = sending_typing.get(nick, 1) + 1
    if not sending_typing.get(nick, None):
        send_typing_ctcp(nick, level)
    sending_typing[nick] = cookie
    w.hook_timer(4000, 0, 1, "typing_disable_timer", "%s:%i" % (nick, cookie))
Exemple #12
0
def on_signal(*args, **kwargs):
	global timer
	''' Called whenever the buffer list changes. '''
	if timer is not None:
		weechat.unhook(timer)
		timer = None
	weechat.hook_timer(config.signal_delay, 0, 1, "on_timeout", "")
	return weechat.WEECHAT_RC_OK
Exemple #13
0
def cb_update_line_numbers(data, signal, signal_data):
    """Call `cb_timer_update_line_numbers()` when switching buffers.
    A timer is required because the bar item is refreshed before the new buffer
    is actually displayed, so ``win_chat_height`` would refer to the old
    buffer. Using a timer refreshes the item after the new buffer is displayed.
    """
    weechat.hook_timer(10, 0, 1, "cb_timer_update_line_numbers", "")
    return weechat.WEECHAT_RC_OK
Exemple #14
0
 def Winner(self, winner):
     self.trivial['state'] = 0
     if self.trivial['main_timer']:
         weechat.unhook(self.trivial['main_timer'])
     self.Show_Awards(winner)
     self.Register_Question(winner)
     self.Show_Session_Awards(winner)
     self.Show_Ranking()
     interval = int(self.opts['time_wait'])
     weechat.hook_timer(interval * 1000, 0, 1, 'Wait_Next_Round_cb', self.TrivId)
Exemple #15
0
def modifier_cb(data,modifier,modifier_data,string):
    global bufp,linetosay
    if len(string)<2 or (string[0]=="/" and string[1]!="/"): return string
    bufp=modifier_data

    linetosay=intlmakeEline(string)
    if linetosay==None: return string

    weechat.hook_timer(10,0,1,"timer_cb","")
    return string
Exemple #16
0
def serverConnected(data, buffer, args):
    global start_time_sec
    start_time_sec = readTimer()
    global connectedState
    connectedState = 1
    # POSIX of the start of the session
    global session_start_time
    session_start_time = time.time()
    weechat.hook_timer(1000,1,0,'updateTimer','')
    return weechat.WEECHAT_RC_OK
Exemple #17
0
def bas_signal_buffer_opened_cb(data, signal, signal_data):
    global bas_options
    buffer = signal_data
    timer = weechat.config_integer(bas_options["look_timer"])
    if timer == 0:
        bas_apply_options_for_buffer(buffer)
    else:
        weechat.hook_timer(timer, 0, 1, "bas_timer_buffer_opened_cb",
                           weechat.buffer_get_string(buffer, "full_name"))
    return weechat.WEECHAT_RC_OK
Exemple #18
0
def cb_buffer_tick(arg, remaining_calls):
    for buf in list(BUFFERS.keys()):
        if not BUFFERS[buf].tick():
            # weechat.prnt('', 'anotify: removing notifier {0}'.format(BUFFERS[buf]._window))
            BUFFERS.pop(buf)

    if remaining_calls == 0:
        weechat.hook_timer(1000, 1, 65535, "cb_buffer_tick", arg)

    return weechat.WEECHAT_RC_OK
def send_typing(nick, level):
    if level == 0 and nick in sending_typing:
        send_typing_ctcp(nick, 0)
        del sending_typing[nick]
    elif level > 0:
        if nick not in sending_typing:
            send_typing_ctcp(nick, level)
        cookie = sending_typing.get(nick, 0) + 1
        sending_typing[nick] = cookie
        w.hook_timer(int(1000 * float(w.config_get_plugin('timeout'))), 0, 1,
                     "typing_disable_timer", "%s:%i" % (nick, cookie))
Exemple #20
0
def bas_signal_buffer_opened_cb(data, signal, signal_data):
    global bas_options
    buffer = signal_data
    timer = weechat.config_integer(bas_options["look_timer"])
    if timer == 0:
        bas_apply_options_for_buffer(buffer)
    else:
        weechat.hook_timer(timer, 0, 1,
                           "bas_timer_buffer_opened_cb",
                           weechat.buffer_get_string(buffer, "full_name"))
    return weechat.WEECHAT_RC_OK
def send_typing(nick, level):
    if level == 0 and nick in sending_typing:
        send_typing_ctcp(nick, 0)
        del sending_typing[nick]
    elif level > 0 :
        if nick not in sending_typing:
            send_typing_ctcp(nick, level)
        cookie = sending_typing.get(nick, 0) + 1
        sending_typing[nick] = cookie
        w.hook_timer( int(1000 * float(w.config_get_plugin('timeout'))), 0, 1,
                      "typing_disable_timer", "%s:%i" % (nick, cookie))
Exemple #22
0
 def Winner(self, winner):
     self.trivial['state'] = 0
     if self.trivial['main_timer']:
         weechat.unhook(self.trivial['main_timer'])
     self.Show_Awards(winner)
     self.Register_Question(winner)
     self.Show_Session_Awards(winner)
     self.Show_Ranking()
     interval = int(self.opts['time_wait'])
     weechat.hook_timer(interval * 1000, 0, 1, 'Wait_Next_Round_cb',
                        self.TrivId)
Exemple #23
0
def modifier_cb(data,modifier,modifier_data,string):
	global nrip
	bufplugin,bufname=modifier_data.split(";")[0:2]
	fullname=bufplugin+"."+bufname
	if fullname.lower()!=BUFFERNAME.lower():
		return string
	# weechat.prnt("",dashprefix+"[rip] SR=<"+str(SEARCHREGEX)+"> string=<"+string+">")
	if re.search(SEARCHREGEX,string,re.IGNORECASE):
		nrip+=1
		weechat.hook_timer(10,0,1,"timer_cb","")
	return string
Exemple #24
0
def run(data, buffer, args):
    global orig_buffer
    orig_buffer = buffer
    weechat.hook_timer(
        random.randrange(MAX_DELAY),
        0,
        1,
        "on_timer",
        "",
    )
    return weechat.WEECHAT_RC_OK
Exemple #25
0
def pressed_keys_check(data, remaining_calls):
    """Check the pressed keys and changes modes or detects bound keys
    accordingly.

    """
    global pressed_keys, mode, vi_buffer, esc_pressed
    # If the last pressed key was Escape, this one will be detected as an arg
    # as Escape acts like a modifier (pressing Esc, then pressing i is detected
    # as pressing meta-i). We'll emulate it being pressed again, so that the
    # user's input is actually processed normally.
    if esc_pressed is True:
        esc_pressed = False
        weechat.hook_timer(50, 0, 1, "handle_esc", pressed_keys[-1])
    if mode == "INSERT":
        # Ctrl + Space, or Escape
        if pressed_keys == "@" or pressed_keys == "[":
            set_mode("NORMAL")
            if pressed_keys == "[":
                esc_pressed = True
    elif mode == "NORMAL":
        # We strip all numbers and check if the the combo is recognized below,
        # then extract the numbers, if any, and pass them as the repeat factor.
        buffer_stripped = re.sub(num, '', vi_buffer)
        if vi_buffer in ['i', 'a', 'A']:
            set_mode("INSERT")
            if vi_buffer == 'a':
                weechat.command('', "/input move_next_char")
            elif vi_buffer == 'A':
                weechat.command('', "/input move_end_of_line")
        # Pressing '0' should not be detected as a repeat count.
        elif vi_buffer == '0':
            weechat.command('', vi_keys['0'])
        # Quick way to detect repeats (e.g. d5w). This isn't perfect, as things
        # like "5d2w1" are detected as "dw" repeated 521 times, but it should
        # be alright as long as the user doesn't try to break it on purpose.
        # Maximum number of repeats performed is 10000.
        elif buffer_stripped in vi_keys:
            repeat = ''.join(re.findall(num, vi_buffer))
            if len(repeat) > 0:
                repeat = min([int(repeat), 10000])
            else:
                repeat = 0
            if isinstance(vi_keys[buffer_stripped], str):
                for _ in range(1 if repeat == 0 else repeat):
                    weechat.command('', vi_keys[re.sub(num, '', vi_buffer)])
            else:
                buf = weechat.current_buffer()
                input_line = weechat.buffer_get_string(buf, 'input')
                cur = weechat.buffer_get_integer(buf, "input_pos")
                vi_keys[buffer_stripped](buf, input_line, cur, repeat)
        else:
            return weechat.WEECHAT_RC_OK
    clear_vi_buffers()
    return weechat.WEECHAT_RC_OK
Exemple #26
0
def cb_key_pressed(data, signal, signal_data):
    """Detect potential Esc presses.
    Alt and Esc are detected as the same key in most terminals. The difference
    is that Alt signal is sent just before the other pressed key's signal.
    We therefore use a timeout (50ms) to detect whether Alt or Esc was pressed.
    """
    global last_signal_time
    last_signal_time = time.time()
    if signal_data == "\x01[":
        # In 50ms, check if any other keys were pressed. If not, it's Esc!
        weechat.hook_timer(50, 0, 1, "cb_check_esc", "{:f}".format(last_signal_time))
    return weechat.WEECHAT_RC_OK
Exemple #27
0
def cb_key_pressed(data, signal, signal_data):
    """Detect potential Esc presses.
    Alt and Esc are detected as the same key in most terminals. The difference
    is that Alt signal is sent just before the other pressed key's signal.
    We therefore use a timeout (50ms) to detect whether Alt or Esc was pressed.
    """
    global last_signal_time
    last_signal_time = time.time()
    if signal_data == "\x01[":
        # In 50ms, check if any other keys were pressed. If not, it's Esc!
        weechat.hook_timer(50, 0, 1, "cb_check_esc",
                           "{:f}".format(last_signal_time))
    return weechat.WEECHAT_RC_OK
Exemple #28
0
def wee_ns_reconnect_loop(*args):
    weechat.prnt(server.buffer, 'Trying to reconnect...')
    server.connect()
    try:
        reconnect_time = int(server.get_option('reconnect_time'))
    except ValueError:
        reconnect_time = int(server.get_default('reconnect_time'))
    if not server.is_connected and reconnect_time > 0:
        weechat.prnt(server.buffer,
                     'Failed, next attempt in %s seconds'
                     % (server.get_option('reconnect_time'),))
        weechat.hook_timer(reconnect_time * 1000, 0, 1,
                           'wee_ns_reconnect_loop', '')
    return weechat.WEECHAT_RC_OK
Exemple #29
0
def is_printing(current, saved):
    """Is the character a visible, printing character that would normally
    show in the input box?

    Previously saved characters are taken into consideration as well for some
    key combinations, such as the arrows, which are detected as three separate
    events (^A[, [ and A/B/C/D).
    The keys buffers will be cleared if the character isn't visible.

    """
    if current.startswith("") or saved.startswith(""):
        weechat.hook_timer(50, 0, 1, "clear_vi_buffers", '')
        return False
    return True
Exemple #30
0
def wee_ns_reconnect_loop(*args):
    weechat.prnt(server.buffer, 'Trying to reconnect...')
    server.connect()
    try:
        reconnect_time = int(server.get_option('reconnect_time'))
    except ValueError:
        reconnect_time = int(server.get_default('reconnect_time'))
    if not server.is_connected and reconnect_time > 0:
        weechat.prnt(
            server.buffer, 'Failed, next attempt in %s seconds' %
            (server.get_option('reconnect_time'), ))
        weechat.hook_timer(reconnect_time * 1000, 0, 1,
                           'wee_ns_reconnect_loop', '')
    return weechat.WEECHAT_RC_OK
Exemple #31
0
def is_printing(current, saved):
    """Is the character a visible, printing character that would normally
    show in the input box?

    Previously saved characters are taken into consideration as well for some
    key combinations, such as the arrows, which are detected as three separate
    events (^A[, [ and A/B/C/D).
    The keys buffers will be cleared if the character isn't visible.

    """
    if current.startswith("") or saved.startswith(""):
        weechat.hook_timer(50, 0, 1, "clear_vi_buffers", '')
        return False
    return True
Exemple #32
0
def cowchat(data, command, return_code, out, err):
    if return_code != 0:
        weechat.prnt(weechat.current_buffer(), "Cowchat error: {0}".format(return_code))
        for line in err.split("\n")[:-1]:
            weechat.prnt(weechat.current_buffer(), line)
        return weechat.WEECHAT_RC_ERROR
    lines = out.split("\n")
    cowchat_line("{}\n{}".format(data, out), len(lines) - 1)
    weechat.hook_timer(2000, 0, len(lines) - 1, "cowchat_line", "{}\n{}".format(data, out))
#    for line in out.split("\n"):
#        if len(line) > 1 and line[0] == '/':
#            line = '/' + line
#        weechat.hook_signal_send("irc_input_send", weechat.WEECHAT_HOOK_SIGNAL_STRING,
#                                 "{};2;;{}".format(data, line))
    return weechat.WEECHAT_RC_OK
Exemple #33
0
def masshl_cmd_cb(data, buffer, args):
	global nicks
	server   = weechat.buffer_get_string(buffer, 'localvar_server')
	channel  = weechat.buffer_get_string(buffer, 'localvar_channel')
	nicklist = weechat.infolist_get('irc_nick', '', server+','+channel)
	while weechat.infolist_next(nicklist):
		nicks.append(weechat.infolist_string(nicklist, 'name'))
	weechat.infolist_free(nicklist)
	del server, channel, nicklist
	nicks.pop(0)
	if args[:2] == '-1':
		weechat.command(buffer, ', '.join(nicks))
	else:
		weechat.hook_timer(100, 0, len(nicks), 'timer_cb', '[split]'.join((buffer,args)))
	return weechat.WEECHAT_RC_OK
Exemple #34
0
def pressed_keys_check(data, remaining_calls):
    """Check the pressed keys and changes modes or detects bound keys
    accordingly.

    """
    global pressed_keys, mode, vi_buffer, esc_pressed
    # If the last pressed key was Escape, this one will be detected as an arg
    # as Escape acts like a modifier (pressing Esc, then pressing i is detected
    # as pressing meta-i). We'll emulate it being pressed again, so that the
    # user's input is actually processed normally.
    if esc_pressed is True:
        esc_pressed = False
        weechat.hook_timer(50, 0, 1, "handle_esc", pressed_keys[-1])
    if mode == "INSERT":
        # Ctrl + Space, or Escape
        if pressed_keys == "@" or pressed_keys == "[":
            set_mode("NORMAL")
            if pressed_keys == "[":
                esc_pressed = True
    elif mode == "NORMAL":
        # We strip all numbers and check if the the combo is recognized below,
        # then extract the numbers, if any, and pass them as the repeat factor.
        buffer_stripped = re.sub(num, '', vi_buffer)
        if vi_buffer in ['i', 'a', 'A']:
            set_mode("INSERT")
            if vi_buffer == 'a':
                weechat.command('', "/input move_next_char")
            elif vi_buffer == 'A':
                weechat.command('', "/input move_end_of_line")
        # Quick way to detect repeats (e.g. d5w). This isn't perfect, as things
        # like "5d2w1" are detected as "dw" repeated 521 times, but it should
        # be alright as long as the user doesn't try to break it on purpose.
        # Maximum number of repeats performed is 10000.
        elif buffer_stripped in vi_keys:
            repeat = ''.join(re.findall(num, vi_buffer))
            if len(repeat) > 0:
                repeat = min([int(repeat), 10000])
            else:
                repeat = 0
            if isinstance(vi_keys[buffer_stripped], str):
                for _ in range(1 if repeat == 0 else repeat):
                    weechat.command('', vi_keys[re.sub(num, '', vi_buffer)])
            else:
                vi_keys[buffer_stripped](repeat)
        else:
            return weechat.WEECHAT_RC_OK
    clear_vi_buffers()
    return weechat.WEECHAT_RC_OK
Exemple #35
0
def minesweeper_timer_start():
    """Start timer."""
    global minesweeper
    if not minesweeper['timer']:
        minesweeper['time'] = 0
        minesweeper['timer'] = weechat.hook_timer(1000, 0, 0,
                                                  'minesweeper_timer_cb', '')
def load_config(data=None, option=None, value=None):
    """
    Load configuration options and (re)register hook_timer to clear old
    messages based on the current value of check_every.  If check_every is 0
    then messages are never cleared.
    """

    # On initial load set any unset options to the defaults.
    if not option:
        for option, default in settings.iteritems():
            if not weechat.config_is_set_plugin(option):
                weechat.config_set_plugin(option, default)

    if not option or option.endswith('check_every'):
        # If hook_timer for clearing old messages is set already, clear it.
        old_hook = globals().get('CLEAR_HOOK', None)
        if old_hook is not None:
            weechat.unhook(old_hook)

        # Register hook_timer to clear old messages.
        check_every = get_option_int('check_every') * 1000
        if check_every:
            globals()['CLEAR_HOOK'] = weechat.hook_timer(
                    check_every, 0, 0, 'clear_messages_cb', '')

    return weechat.WEECHAT_RC_OK
Exemple #37
0
def floodit_input_buffer(data, buffer, input):
    """Input data in floodit buffer."""
    global floodit
    if input:
        args = input.split(' ')
        if args[0] in ('d', 'demo'):
            if not floodit['timer']:
                delay = 500
                if len(args) > 1:
                    try:
                        delay = int(args[1])
                    except:
                        delay = 500
                if delay <= 0:
                    delay = 1
                if floodit['end']:
                    floodit_new_game()
                floodit['timer'] = weechat.hook_timer(delay, 0, 0,
                                                      'floodit_timer_cb', '')
        elif args[0] in ('s', 'single'):
            floodit['mode'] = 'single'
            floodit_new_game()
        elif args[0] in ('v', 'versus'):
            floodit['mode'] = 'versus'
            floodit_new_game()
        elif args[0] in ('n', 'new'):
            floodit_new_game()
        elif args[0] in ('q', 'quit'):
            weechat.buffer_close(floodit['buffer'])
        elif args[0] == '+':
            floodit_change_size(+1)
        elif args[0] == '-':
            floodit_change_size(-1)
    return weechat.WEECHAT_RC_OK
Exemple #38
0
def set_timer():
    """Update timer hook with new interval"""

    global TIMER
    if TIMER:
        w.unhook(TIMER)
    TIMER = w.hook_timer(int(w.config_get_plugin("interval")) * 1000, 0, 0, "screen_away_timer_cb", "")
Exemple #39
0
def keep_alive_buffer(buffer):
    remove_keep_alive(buffer)

    if buffer_is_hidable(buffer):
        KEEP_ALIVE_BUFFERS[buffer] = weechat.hook_timer(
            KEEP_ALIVE_TIMEOUT, 0, 1, "on_temporary_active_buffer_timeout",
            buffer)
Exemple #40
0
def switch_current_buffer():
    """Save current buffer and ensure that it's visible, then if the
    buffer is elegible to be hidden, we add it to the list of the buffers
    to be hidden after a delay
    """
    global CURRENT_BUFFER
    global CURRENT_BUFFER_TIMER_HOOK

    previous_buffer = CURRENT_BUFFER
    CURRENT_BUFFER = weechat.current_buffer()

    if previous_buffer == CURRENT_BUFFER:
        return

    if weechat.buffer_get_integer(CURRENT_BUFFER, "hidden") == 1:
        weechat.buffer_set(CURRENT_BUFFER, "hidden", "0")

    if weechat.config_get_plugin("keep_open") != "off":
        if CURRENT_BUFFER_TIMER_HOOK is not None:
            weechat.unhook(CURRENT_BUFFER_TIMER_HOOK)
            CURRENT_BUFFER_TIMER_HOOK = None
            maybe_hide_buffer(previous_buffer)
        else:
            keep_alive_buffer(previous_buffer)

        CURRENT_BUFFER_TIMER_HOOK = weechat.hook_timer(
            MINIMUM_BUFFER_LIFE, 0, 1,
            "on_current_buffer_is_still_active_timeout", "")
    else:
        maybe_hide_buffer(previous_buffer)
Exemple #41
0
def set_timer():
    '''Update timer hook with new interval.'''
    global TIMER
    if TIMER:
        w.unhook(TIMER)
    TIMER = w.hook_timer(int(w.config_get_plugin('interval')) * 1000, 0, 0,
                         'screen_away_timer_cb', '')
def set_timer():
    '''Update timer hook with new interval'''

    global TIMER
    if TIMER:
        weechat.unhook(TIMER)
    TIMER = weechat.hook_timer(INTERVAL, 0, 0, "timer_cb", '')
def set_timer():
    # Update timer hook with new interval. 0 means deactivated
    global TIMER
    if TIMER:
        weechat.unhook(TIMER)
    if int(weechat.config_get_plugin('interval')) >= 1:
        TIMER = weechat.hook_timer(int(weechat.config_get_plugin('interval')) * 1000,0, 0, "timer_dummy_cb", '')
Exemple #44
0
def on_signal_delay_timeout(pointer, remaining_calls):
    """ Called when the signal_delay_timer triggers. """
    global signal_delay_timer
    global sort_limit_timer
    global sort_queued

    signal_delay_timer = None

    # If the sort limit timeout was started, we're still in the no-sort period, so just queue a sort.
    if sort_limit_timer is not None:
        debug(
            'Signal delay timeout expired, but sort limit timeout is active, sort is now queued.'
        )
        sort_queued = True
        return weechat.WEECHAT_RC_OK

    # Time to sort!
    debug('Signal delay timeout expired, starting sort.')
    do_sort()

    # Start the sort limit timeout if not disabled.
    if config.sort_limit > 0:
        debug('Starting sort limit timeout of {0} ms.'.format(
            config.sort_limit))
        sort_limit_timer = weechat.hook_timer(config.sort_limit, 0, 1,
                                              "on_sort_limit_timeout", "")

    return weechat.WEECHAT_RC_OK
Exemple #45
0
def floodit_input_buffer(data, buffer, input):
    """Input data in floodit buffer."""
    global floodit
    if input:
        args = input.split(' ')
        if args[0] in ('d', 'demo'):
            if not floodit['timer']:
                delay = 500
                if len(args) > 1:
                    try:
                        delay = int(args[1])
                    except:
                        delay = 500
                if delay <= 0:
                    delay = 1
                if floodit['end']:
                    floodit_new_game()
                floodit['timer'] = weechat.hook_timer(delay, 0, 0, 'floodit_timer_cb', '')
        elif args[0] in ('s', 'single'):
            floodit['mode'] = 'single'
            floodit_new_game()
        elif args[0] in ('v', 'versus'):
            floodit['mode'] = 'versus'
            floodit_new_game()
        elif args[0] in ('n', 'new'):
            floodit_new_game()
        elif args[0] in ('q', 'quit'):
            weechat.buffer_close(floodit['buffer'])
        elif args[0] == '+':
            floodit_change_size(+1)
        elif args[0] == '-':
            floodit_change_size(-1)
    return weechat.WEECHAT_RC_OK
Exemple #46
0
def samegame_play(x, y):
    """Play at (x,y), and check if game has ended."""
    global samegame, samegame_settings
    if samegame["board"][y][x] < 0:
        return
    board = copy.deepcopy(samegame["board"])
    count = samegame_play_xy(board, x, y)
    if count < 2:
        return
    samegame["board_undo"] = copy.deepcopy(samegame["board"])
    samegame["score_undo"] = samegame["score"]
    count = samegame_play_xy(samegame["board"], x, y)
    samegame["score"] += (count - 1) ** 2
    delay = 50
    try:
        delay = int(samegame_settings["speed"])
    except:
        delay = 50
    if delay < 0:
        delay = 0
    elif delay > 500:
        delay = 500
    if delay == 0:
        while samegame_collapse_blocks():
            pass
        samegame_check_end()
    else:
        samegame["timer"] = weechat.hook_timer(delay, 0, 0, "samegame_timer_cb", "")
    samegame_display()
    return
Exemple #47
0
def hook_timer(seconds, callback, userdata=None):
    # Inject a random name for the helper function into the __main__ module
    # so weechat can find it, because weechat only takes strings as callbacks
    # and only looks in the __main__ module globals dict (afaik)
    # https://github.com/weechat/weechat/blob/master/src/plugins/python/weechat-python.c#L328-L330

    # use a random name to avoid name conflicts (assuming rational naming).

    @functools.wraps(callback)
    def _hook_timer_helper(genfuncname, remaining_calls):
        # nonlocal callback, userdata, generated_func_name  # py2.7 duh!
        try:
            result = callback(userdata)
        except:
            raise
        finally:
            remove_func(genfuncname)

        if result is None:
            result = weechat.WEECHAT_RC_OK
        return result

    genfuncname = inject_func(_hook_timer_helper)

    # align_seconds/maxcalls won't be implemented for now.
    return weechat.hook_timer(int(seconds*1000), 0, 1, genfuncname, genfuncname)
Exemple #48
0
def switch_current_buffer():
    """Save current buffer and ensure that it's visible, then if the
    buffer is elegible to be hidden, we add it to the list of the buffers
    to be hidden after a delay
    """
    global CURRENT_BUFFER
    global CURRENT_BUFFER_TIMER_HOOK

    previous_buffer = CURRENT_BUFFER
    CURRENT_BUFFER = weechat.current_buffer()

    if previous_buffer == CURRENT_BUFFER:
        return

    if weechat.buffer_get_integer(CURRENT_BUFFER, "hidden") == 1:
        weechat.buffer_set(CURRENT_BUFFER, "hidden", "0")

    if weechat.config_get_plugin("keep_open") != "off":
        if CURRENT_BUFFER_TIMER_HOOK is not None:
            weechat.unhook(CURRENT_BUFFER_TIMER_HOOK)
            CURRENT_BUFFER_TIMER_HOOK = None
            maybe_hide_buffer(previous_buffer)
        else:
            keep_alive_buffer(previous_buffer)

        CURRENT_BUFFER_TIMER_HOOK = weechat.hook_timer(MINIMUM_BUFFER_LIFE, 0, 1,
            "on_current_buffer_is_still_active_timeout", "")
    else:
        maybe_hide_buffer(previous_buffer)
Exemple #49
0
def samegame_play(x, y):
    """Play at (x,y), and check if game has ended."""
    global samegame, samegame_settings
    if samegame['board'][y][x] < 0:
        return
    board = copy.deepcopy(samegame['board'])
    count = samegame_play_xy(board, x, y)
    if count < 2:
        return
    samegame['board_undo'] = copy.deepcopy(samegame['board'])
    samegame['score_undo'] = samegame['score']
    count = samegame_play_xy(samegame['board'], x, y)
    samegame['score'] += (count - 1)**2
    delay = 50
    try:
        delay = int(samegame_settings['speed'])
    except:
        delay = 50
    if delay < 0:
        delay = 0
    elif delay > 500:
        delay = 500
    if delay == 0:
        while samegame_collapse_blocks():
            pass
        samegame_check_end()
    else:
        samegame['timer'] = weechat.hook_timer(delay, 0, 0,
                                               'samegame_timer_cb', '')
    samegame_display()
    return
Exemple #50
0
def set_localvars(input):
    buffers = weechat.infolist_get("buffer", "", "*")
    while weechat.infolist_next(buffers):
        pointer = weechat.infolist_pointer(buffers, "pointer")
        name = weechat.infolist_string(buffers, "short_name")

        localvar = None
        localvar_hidden = None
        if active:
            if input in name:
                localvar = "1"
                localvar_hidden = "0"
            else:
                localvar = "0"
                localvar_hidden = "1"

        buffer_set_localvar(pointer, SCRIPT_LOCALVAR, localvar)
        buffer_set_localvar(pointer, SCRIPT_LOCALVAR_HIDDEN, localvar_hidden)

    weechat.infolist_free(buffers)

    weechat.bar_item_update("buflist")

    global timer
    if active:
        # update_buflist_buffers(None, None)
        if timer:
            weechat.unhook(timer)
        timer = weechat.hook_timer(1, 0, 1, "update_buflist_buffers", "")
Exemple #51
0
def remind_set(buf,args,priv,cmd):
	global timer_map

	args=args.strip()
	if args=="list":
		list_reminders(buf)
		return weechat.WEECHAT_RC_OK

	m=re.match(r"delete +(\d+)$",args)
	if m:
		delete_reminder(buf,int(m.group(1)))
		return weechat.WEECHAT_RC_OK

	m=re.match(r"(\d\d):(\d\d)(.*)$",args)
	if not m:
		weechat.prnt(buf,errorprefix+"Invalid format; expected "+cmd+" 16:00 do something")
		return weechat.WEECHAT_RC_OK
	hour,minute,message=int(m.group(1)),int(m.group(2)),m.group(3).strip()

	if hour<0 or hour>=24 or minute<0 or minute>=60:
		weechat.prnt(buf,errorprefix+"Invalid time format")
		return weechat.WEECHAT_RC_OK

	now=datetime.now()
	when=datetime(now.year,now.month,now.day,hour,minute)
	if when<now:
		when=datetime(now.year,now.month,now.day+1,hour,minute)

	i=uniqid()
	hook=weechat.hook_timer((when-now).seconds*1000,0,1,"timer_cb",hex(i))
	timer_map[i]=(when,buf,message,priv,hook)

	weechat.prnt(buf,"Reminding at "+("00"+str(hour))[-2:]+":"+("00"+str(minute))[-2:])

	return weechat.WEECHAT_RC_OK
Exemple #52
0
def setup_timeline(timelined, followed=False, search=False):
    """Sets up the main timeline window."""
    global hooks
    global user
    global tlid
    global buffers
    if not search:
        name = "timeline"
        short_name = "twitter"
        title = "%s's timeline" % user.screen_name
        prefix = "__TIMELINE"
        search = False
        buf_cb = "tweet_cb"
    else:
        name = search
        short_name = search
        title = "Twitter search for %s" % search
        prefix = md5(search).hexdigest()
        buf_cb = "tweet_cb"
    buf = wc.buffer_new(name, buf_cb, "", "stop_timelined", prefix)
    # Some naming
    wc.buffer_set(buf, "title", title)
    wc.buffer_set(buf, "short_name", short_name)

    # We want mentions to highlight.
    wc.buffer_set(buf, "highlight_words", user.screen_name)

    if followed:
        # We want a nicklist to hold everyone we follow.
        wc.buffer_set(buf, "nicklist", "1")
        add_to_nicklist(buf, user.screen_name)

        for screen_name in followed:
            add_to_nicklist(buf, screen_name)

    storage_dir = wc.config_get_plugin("storage_dir")
    command = timelined + " " + storage_dir
    if search:
        command += " '%s'" % search
    timelinestream_hook = wc.hook_process(command, 0, "timelined_cb", prefix)

    strkey = prefix + "STREAM"
    hooks[strkey] = timelinestream_hook

    # Check if there are new timeline entries every second.
    timelinedisplay_hook = wc.hook_timer(1 * 1000, 60, 0, "display_cb", prefix)
    diskey = prefix + "DISPLAY"
    hooks[diskey] = timelinedisplay_hook
    if search:
        wc.buffer_set(buf, "display", "1")
    buffers[prefix] = buf

    hooks['signal'] = wc.hook_signal("input_text_changed",
                                     "timeline_prompt_cb", "")

    if prefix is "__TIMELINE":
        tlid[prefix] = "timelined"
    else:
        tlid[prefix] = prefix
Exemple #53
0
def set_timer():
    '''Update timer hook with new interval'''

    global TIMER
    if TIMER:
        w.unhook(TIMER)
    TIMER = w.hook_timer(int(w.config_get_plugin('interval')) * 1000,
            0, 0, "screen_away_timer_cb", '')
Exemple #54
0
def set_timer():
    """Update timer hook with new interval"""

    global TIMER
    if TIMER:
        w.unhook(TIMER)
    TIMER = w.hook_timer(
        int(w.config_get_plugin('interval')) * 1000, 0, 0, 'timer_cb', '')
Exemple #55
0
def set_timer():
    global TIMER
    if TIMER:
        weechat.unhook(TIMER)
    if int(OPTIONS['interval']) == 0:
        return
    TIMER = weechat.hook_timer(int(OPTIONS['interval']) * 1000,
            0, 0, 'check_buffer_timer_cb', '')
Exemple #56
0
def cmd_help_toggle():
    """Toggle help on/off."""
    global cmdhelp_hooks, cmdhelp_settings
    if cmdhelp_hooks['modifier']:
        unhook(('timer', 'modifier'))
    else:
        cmdhelp_hooks['modifier'] = weechat.hook_modifier(
            'input_text_display_with_cursor', 'input_modifier_cb', '')
        timer = cmdhelp_settings['timer']
        if timer and timer != '0':
            try:
                value = float(timer)
                if value > 0:
                    weechat.hook_timer(value * 1000, 0, 1, 'timer_cb', '')
            except:
                pass
    weechat.bar_item_update('input_text')