Beispiel #1
0
def imap_get_unread(data):
    """Return the unread count."""
    imap = Imap()
    if not w.config_get_plugin('message'):
        output = ""
    else:
        output = '%s' % (
            string_eval_expression(w.config_get_plugin('message')))
    any_with_unread = False
    mailboxes = w.config_get_plugin('mailboxes').split(',')
    count = []
    for mailbox in mailboxes:
        mailbox = mailbox.strip()
        unreadCount = imap.unreadCount(mailbox)
        if unreadCount > 0:
            any_with_unread = True
            count.append('%s%s: %s%s' % (
                w.color(w.config_get_plugin('mailbox_color')),
                mailbox,
                w.color(w.config_get_plugin('count_color')),
                unreadCount))
    imap.logout()
    sep = '%s' % (
        string_eval_expression(w.config_get_plugin('separator')))
    output = output + sep.join(count) + w.color('reset')

    return output if any_with_unread else ''
Beispiel #2
0
def shell_exec(buffer, command):
    """Execute a command."""
    global cmd_hook_process, cmd_command, cmd_start_time, cmd_buffer
    global cmd_stdout, cmd_stderr, cmd_send_to_buffer, cmd_timeout
    if cmd_hook_process:
        weechat.prnt(buffer,
                     '%sanother process is running! (use "/%s -kill" to kill it)'
                     % (SHELL_PREFIX, SHELL_CMD))
        return
    if cmd_send_to_buffer == 'new':
        weechat.prnt(buffer, '-->\t%s%s$ %s%s'
                     % (weechat.color('chat_buffer'), os.getcwd(), weechat.color('reset'), command))
        weechat.prnt(buffer, '')
    args = command.split(' ')
    if args[0] == 'cd':
        shell_chdir(buffer, ' '.join(args[1:]))
    elif args[0] == 'getenv':
        shell_getenv (buffer, ' '.join(args[1:]))
    elif args[0] == 'setenv':
        shell_setenv (buffer, ' '.join(args[1:]))
    elif args[0] == 'unsetenv':
        shell_unsetenv (buffer, ' '.join(args[1:]))
    else:
        shell_init()
        cmd_command = command
        cmd_start_time = datetime.datetime.now()
        cmd_buffer = buffer
        cmd_hook_process = weechat.hook_process(command, cmd_timeout * 1000, 'shell_process_cb', '')
Beispiel #3
0
def show_favorites_cb(data, buffer, args):
    """
    Show all the tweets that are favourited by the user.
    """
    global twitter
    try:
        favs = twitter.get_favorites()
    except TwitterError as error:
        print_error(error)
        return wc.WEECHAT_RC_OK
    if favs:
        print_to_current("%sFAVOURITES\t%s-------------------" %
                (wc.color("yellow"), wc.color("magenta")))
        for fav in favs:
            nick_color = wc.info_get("irc_nick_color", fav.screen_name)
            screen_name = nick_color + fav.screen_name
            expand_urls = wc.config_string_to_boolean(wc.config_get_plugin("expand_urls"))
            text = fav.text_unescaped
            if expand_urls:
                text = fav.text
            output = "%s\t%s" % (screen_name, text)
            if fav.is_retweet:
                output += " (RT by @%s)" % fav.rtscreen_name
            output += "\n[#STATUSID: %s]" % fav.id
            print_to_current(output)
        print_to_current("%s-------------------" % wc.color("magenta"))
    return wc.WEECHAT_RC_OK
Beispiel #4
0
def get_option_list_and_desc(option, displayname):
    """Get list of options and description for option(s)."""
    global cmdhelp_settings, cmdhelp_option_infolist
    global cmdhelp_option_infolist_fields
    options = []
    description = ''
    cmdhelp_option_infolist = weechat.infolist_get('option', '', option)
    if cmdhelp_option_infolist:
        cmdhelp_option_infolist_fields = {}
        while weechat.infolist_next(cmdhelp_option_infolist):
            options.append(weechat.infolist_string(cmdhelp_option_infolist,
                                                   'full_name'))
            if not description:
                fields = weechat.infolist_fields(cmdhelp_option_infolist)
                for field in fields.split(','):
                    items = field.split(':', 1)
                    if len(items) == 2:
                        cmdhelp_option_infolist_fields[items[1]] = items[0]
                description = re.compile(r'\$\{[^\}]+\}').sub(
                    format_option, cmdhelp_settings['format_option'])
                if displayname:
                    description = '%s%s%s: %s' % (
                        weechat.color(cmdhelp_settings['color_option_name']),
                        weechat.infolist_string(cmdhelp_option_infolist,
                                                'full_name'),
                        weechat.color(cmdhelp_settings['color_option_help']),
                        description)
        weechat.infolist_free(cmdhelp_option_infolist)
        cmdhelp_option_infolist = ''
        cmdhelp_option_infolist_fields = {}
    return options, description
Beispiel #5
0
def format_option(match):
    """Replace ${xxx} by its value in option format."""
    global cmdhelp_settings, cmdhelp_option_infolist
    global cmdhelp_option_infolist_fields
    string = match.group()
    end = string.find('}')
    if end < 0:
        return string
    field = string[2:end]
    color1 = ''
    color2 = ''
    pos = field.find(':')
    if pos:
        color1 = field[0:pos]
        field = field[pos+1:]
    if color1:
        color1 = weechat.color(color1)
        color2 = weechat.color(cmdhelp_settings['color_option_help'])
    fieldtype = cmdhelp_option_infolist_fields.get(field, '')
    if fieldtype == 'i':
        string = str(weechat.infolist_integer(cmdhelp_option_infolist, field))
    elif fieldtype == 's':
        string = weechat.infolist_string(cmdhelp_option_infolist, field)
    elif fieldtype == 'p':
        string = weechat.infolist_pointer(cmdhelp_option_infolist, field)
    elif fieldtype == 't':
        date = weechat.infolist_time(cmdhelp_option_infolist, field)
        # since WeeChat 2.2, infolist_time returns a long integer instead of
        # a string
        if not isinstance(date, str):
            date = time.strftime('%F %T', time.localtime(int(date)))
        string = date
    return '%s%s%s' % (color1, string, color2)
Beispiel #6
0
    def refresh_line(self, y):
        format = "%%s%%s %%s%%-%ds%%s%%s %%s - %%s" % (self.max_buffer_width-4)
        color_time = "cyan"
        color_buffer = "red"
        color_info = "green"
        color_url = "blue"
        color_bg_selected = "red"

        if y == self.current_line:
            color_time = "%s,%s" % (color_time, color_bg_selected)
            color_buffer = "%s,%s" % (color_buffer, color_bg_selected)
            color_info = "%s,%s" % (color_info, color_bg_selected)
            color_url = "%s,%s" % (color_url, color_bg_selected)

        color_time = weechat.color(color_time)
        color_buffer = weechat.color(color_buffer)
        color_info = weechat.color(color_info)
        color_url = weechat.color(color_url)

        text = ''
        if len(self.urls) - 1 > y :
            url = self.urls[y]
            url_info = self.url_infos[url]
            text = format % (color_time,
                             url_info['time'],
                             color_buffer,
                             url_info['buffer'],
                             color_info,
                             url_info['info'],
                             color_url,
                             url_info['url']
                             )
        weechat.prnt_y(self.url_buffer,y,text)
Beispiel #7
0
def hook_commands_and_completions():
    compl_list = []
    com_list = []
    desc_list = []
    for command in sorted(command_dict):
        compl_list.append(command)
        com_list.append(command + weechat.color("*red") + " or " +
                weechat.color('reset') + command_dict[command] + "\n")
        desc_list.append(weechat.color("chat_nick_other") + command + ":    \n" + desc_dict[command])
    weechat.hook_command("twitter", "Command to interact with the twitter api/plugin",
        " | ".join(com_list),
        "You can type all of these command in the twitter buffer if you add a ':' before the command, IE:\n"
        ":limits\n\n"
        "If you don't type a command in the twitter buffer you will tweet that instead,\n"
        "text after 140 chars will turn red to let you know were twitter will cut off your tweet.\n\n"
        + weechat.color("*red") + "NOTE:\n"
        "There are limits on how many twitter api calls you can do, some calls are _quite_ restricted.\n"
        "So if you get HTML errors from the twitter lib you probably exceeded the limit\n"
        "you can check out your limits with the rate_limits/limits command.\n"
        "_Most_ commands in this plugin only uses one call. If you want to check old tweets\n"
        "in your home timeline it's better to request many tweets in one go.\n"
        "That way you don't have to request new tweets as often to go further back in the timeline.\n"
        "And thus you are less likely to hit the limit of requests you can do in the 15 min time window.\n"
        "\nYou can write newlines in your tweet with html newline '&#13;&#10;' (you can autocomplete it)\n"
        "\nThe 'number' next to the nicks in the chat window is the <id> of the tweet it's used\n"
        "in the some of the twitter plugin commands.\n\n"
        "Command desc:\n"+ "\n".join(desc_list),
        " || ".join(compl_list),
        "my_command_cb", "")
Beispiel #8
0
def get_help_command(plugin, input_cmd, input_args):
    """Get help for command in input."""
    global cmdhelp_settings
    if input_cmd == 'set' and input_args:
        return get_help_option(input_args)
    infolist = weechat.infolist_get('hook', '', 'command,%s' % input_cmd)
    cmd_plugin_name = ''
    cmd_command = ''
    cmd_args = ''
    cmd_desc = ''
    while weechat.infolist_next(infolist):
        cmd_plugin_name = (weechat.infolist_string(infolist, 'plugin_name') or
                           'core')
        cmd_command = weechat.infolist_string(infolist, 'command')
        cmd_args = weechat.infolist_string(infolist, 'args_nls')
        cmd_desc = weechat.infolist_string(infolist, 'description')
        if weechat.infolist_pointer(infolist, 'plugin') == plugin:
            break
    weechat.infolist_free(infolist)
    if cmd_plugin_name == 'alias':
        return '%sAlias %s%s%s => %s%s' % (
            weechat.color(cmdhelp_settings['color_alias']),
            weechat.color(cmdhelp_settings['color_alias_name']),
            cmd_command,
            weechat.color(cmdhelp_settings['color_alias']),
            weechat.color(cmdhelp_settings['color_alias_value']),
            cmd_desc,
        )
    if input_args:
        cmd_args = get_command_arguments(input_args, cmd_args)
    if not cmd_args:
        return None
    return '%s%s' % (weechat.color(cmdhelp_settings['color_arguments']),
                     cmd_args)
Beispiel #9
0
def nameday_print(days):
    """Print name day for today and option N days in future."""
    global nameday_i18n
    today = date.today()
    current_time = time.time()
    string = '%02d/%02d: %s' % (today.day, today.month,
                                nameday_get_date(today, gender=True,
                                                 colorMale='color_male',
                                                 colorFemale='color_female'))
    if days < 0:
        days = 0
    elif days > 50:
        days = 50
    if days > 0:
        string += '%s (' % weechat.color('reset')
        for i in range(1, days + 1):
            if i > 1:
                string += '%s, ' % weechat.color('reset')
            date2 = date.fromtimestamp(current_time + ((3600 * 24) * i))
            string += '%02d/%02d: %s' % (date2.day, date2.month,
                                         nameday_get_date(date2, gender=True,
                                                          colorMale='color_male',
                                                          colorFemale='color_female'))
        string += '%s)' % weechat.color('reset')
    weechat.prnt('', string)
Beispiel #10
0
def vdm_display(vdm):
    """ Display VDMs in buffer. """
    global vdm_buffer
    weechat.buffer_set(vdm_buffer, "unread", "1")
    if weechat.config_get_plugin("number_as_prefix") == "on":
        separator = "\t"
    else:
        separator = " > "
    colors = weechat.config_get_plugin("colors").split(";");
    vdm2 = vdm[:]
    if weechat.config_get_plugin("reverse") == "on":
        vdm2.reverse()
    for index, item in enumerate(vdm2):
        item_id = item["id"]
        item_text = item["text"]
        if sys.version_info < (3,):
            # python 2.x: convert unicode to str (in python 3.x, id and text are already strings)
            item_id = item_id.encode("UTF-8")
            item_text = item_text.encode("UTF-8")
        weechat.prnt_date_tags(vdm_buffer,
                               0, "notify_message",
                               "%s%s%s%s%s" %
                               (weechat.color(weechat.config_get_plugin("color_number")),
                                item_id,
                                separator,
                                weechat.color(colors[0]),
                                item_text))
        colors.append(colors.pop(0))
        if index == len(vdm) - 1:
            weechat.prnt(vdm_buffer, "------")
        elif weechat.config_get_plugin("blank_line") == "on":
            weechat.prnt(vdm_buffer, "")
Beispiel #11
0
def fmt_banmask(mask):
    """Formats a banmask"""

    green = w.color("green")
    reset = w.color("reset")

    return "{}[{}{}{}]{}".format(green, reset, mask, green, reset)
Beispiel #12
0
def format_weather(weather_data):
    '''
    Formats the weather data dictionary received from Google

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

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

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

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

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

    output += weechat.color('reset')

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

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

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

    return new_message
Beispiel #14
0
def fish_alert(buffer, message):
    mark = "%s%s%s\t" % (
            weechat.color(weechat.config_color(fish_config_option["alert"])),
            weechat.config_string(fish_config_option["marker"]),
            weechat.color("chat"))

    weechat.prnt(buffer, "%s%s" % (mark, message))
Beispiel #15
0
def print_as_lines(target, matches, data, limit, total):
    """Prints the output as a line-separated list of nicks."""

    prefix = fmt_prefix(data)
    mstring = "{}{}".format(fmt_mode_char(data["mode"]), "" if data["set"] else " removal")
    mask = fmt_banmask(data["mask"])
    target_in_prefix = "_target_" in prefix
    i = 0

    for name in matches:
        if target_in_prefix:
            pf = prefix.replace("_target_", "{}{}{}".format(
                w.color(w.info_get("irc_nick_color_name", name)),
                name, w.color("reset")))
        else:
            pf = prefix

        if (total - (limit - i) == 1) or (i >= limit):
            left = total - i
            left -= 1 if target_in_prefix else 0

            w.prnt(target, "{}\tand {} more match{}..".format(pf, left, "es" if left != 1 else ""))
            break

        if target_in_prefix:
            w.prnt(target, "{}\tmatches {} {}".format(pf, mstring, mask))
        else:
            w.prnt(target, "{}\t{} {} matches {}".format(pf, mstring, mask, fmt_nick(name)))
        i += 1
Beispiel #16
0
    def print_tasks(self):

        w.buffer_clear(self.buffer)

        list_id = self.lists[self.active_list_name]
        rspTasks = self.rtm.tasks.getList(list_id=list_id, filter='status:incomplete')
        for task in reversed(rspTasks.tasks.list.taskseries):
            if not self.active_task_id:
                self.active_task_id = task.id

            priority = task.task.priority
            
            fgcolor = 'default'
            bgcolor = 'default'
            if priority == '3':
                fgcolor = 'green'
            elif priority == '2':
                fgcolor = 'cyan'
            elif priority == '1':
                fgcolor = 'yellow'
            elif priority == 'N':
                fgcolor = 'default'
            if int(task.id) == int(self.active_task_id):
                bgcolor = 'red'
            try:
                ttime = datetime.datetime.fromtimestamp(time.mktime(time.strptime(task.created, "%Y-%m-%dT%H:%M:%SZ")))
            except Exception, e:
                ttime = ''
                print task.created, e
           
            task_name = task.name.encode('UTF-8')
            task_name = '%s%s%s' %(w.color('%s,%s' %(fgcolor,bgcolor)), task_name, w.color('reset'))
            taskstr = '%s\t%s %s' %(ttime, '', task_name)
            w.prnt(self.buffer, taskstr)
Beispiel #17
0
def get_list_commands(plugin, input_cmd, input_args):
    """Get list of commands (beginning with current input)."""
    global cmdhelp_settings
    infolist = weechat.infolist_get('hook', '', 'command,%s*' % input_cmd)
    commands = []
    plugin_names = []
    while weechat.infolist_next(infolist):
        commands.append(weechat.infolist_string(infolist, 'command'))
        plugin_names.append(
            weechat.infolist_string(infolist, 'plugin_name') or 'core')
    weechat.infolist_free(infolist)
    if commands:
        if len(commands) > 1 or commands[0].lower() != input_cmd.lower():
            commands2 = []
            for index, command in enumerate(commands):
                if commands.count(command) > 1:
                    commands2.append('%s(%s)' % (command, plugin_names[index]))
                else:
                    commands2.append(command)
            return '%s%d commands: %s%s' % (
                weechat.color(cmdhelp_settings['color_list_count']),
                len(commands2),
                weechat.color(cmdhelp_settings['color_list']),
                ', '.join(commands2))
    return None
Beispiel #18
0
def search_whois_cb(data, signal, hashtable):
    ht = hashtable["output"]  # string
    ret = re.search(r"(\S+) \* :(.+)$", ht, re.M)
    if ret:
        masked_ip = ret.group(1)
        w.prnt_date_tags("", 0, "no_log", "RESULT about {}{}".format(w.color("*lightblue"), masked_ip))
        lst = stick(masked_ip)
        for dic in lst:
            w.prnt_date_tags(
                "",
                0,
                "no_log",
                "\n  ".join(
                    [
                        "{}#{}: {}".format(w.color("_lightgreen"), dic["number"], dic["login_time"]),
                        "names: {}{}{} / {} / {}".format(
                            w.color("*lightred"),
                            dic["login_nick"][0],
                            w.color("chat"),
                            dic["login_nick"][1],
                            dic["login_nick"][2],
                        ),
                        "channels: {}".format(dic["login_channels"]),
                    ]
                ),
            )
    # else:
    #     w.prnt_date_tags("", 0, "no_log", "error: Not Found MASKED_IP")
    return w.WEECHAT_RC_OK
Beispiel #19
0
def go_buffers_to_string(listbuf, pos, strinput):
    """Return string built with list of buffers found (matching user input)."""
    string = ''
    strinput = strinput.lower()
    for i in range(len(listbuf)):
        selected = '_selected' if i == pos else ''
        index = listbuf[i]['name'].lower().find(strinput)
        if index >= 0:
            index2 = index + len(strinput)
            name = '%s%s%s%s%s' % (
                listbuf[i]['name'][:index],
                weechat.color(weechat.config_get_plugin(
                    'color_name_highlight' + selected)),
                listbuf[i]['name'][index:index2],
                weechat.color(weechat.config_get_plugin(
                    'color_name' + selected)),
                listbuf[i]['name'][index2:])
        else:
            name = listbuf[i]['name']
        string += ' %s%s%s%s%s' % (
            weechat.color(weechat.config_get_plugin(
                'color_number' + selected)),
            str(listbuf[i]['number']),
            weechat.color(weechat.config_get_plugin(
                'color_name' + selected)),
            name,
            weechat.color('reset'))
    return '  ' + string if string else ''
Beispiel #20
0
def hotlist_item_cb(data, item, window):
    priorities = {}
    titles = {}

    hdata_hotlist = w.hdata_get('hotlist')
    ptr_hotlist = w.hdata_get_list(hdata_hotlist, 'gui_hotlist')
    while ptr_hotlist:
        priority = w.hdata_integer(hdata_hotlist, ptr_hotlist, 'priority')
        buffer = w.hdata_pointer(hdata_hotlist, ptr_hotlist, 'buffer')
        count = w.hdata_integer(
            hdata_hotlist, ptr_hotlist, '%d|count' % GUI_HOTLIST_MESSAGE)
        number = w.buffer_get_integer(buffer, 'number')
        name = w.buffer_get_string(buffer, 'short_name')

        if priority != GUI_HOTLIST_LOW:
            priorities[number] = priority
            titles[number] = '%d:%s' % (number, name)
            if count:
                titles[number] += '(%d)' % count

        ptr_hotlist = w.hdata_move(hdata_hotlist, ptr_hotlist, 1)

    items = []
    for number, priority in sorted(priorities.items()):
        items.append('%s %s %s' % (
            w.color(COLORS[priority]),
            titles[number],
            w.color('reset')))
    return ' '.join(items)
Beispiel #21
0
def get_help_option(input_args):
    """Get help about option or values authorized for option."""
    global cmdhelp_settings, cmdhelp_option_infolist
    global cmdhelp_option_infolist_fields
    pos = input_args.find(' ')
    if pos > 0:
        option = input_args[0:pos]
    else:
        option = input_args
    options, description = get_option_list_and_desc(option, False)
    if not options and not description:
        options, description = get_option_list_and_desc('%s*' % option, True)
    if len(options) > 1:
        try:
            max_options = int(cmdhelp_settings['max_options'])
        except ValueError:
            max_options = 5
        if len(options) > max_options:
            text = '%s...' % ', '.join(options[0:max_options])
        else:
            text = ', '.join(options)
        return '%s%d options: %s%s' % (
            weechat.color(cmdhelp_settings['color_list_count']),
            len(options),
            weechat.color(cmdhelp_settings['color_list']),
            text)
    if description:
        return '%s%s' % (weechat.color(cmdhelp_settings['color_option_help']),
                         description)
    return '%sNo help for option %s' % (
        weechat.color(cmdhelp_settings['color_no_help']), option)
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
Beispiel #23
0
def shell_exec(buffer, command):
    """Execute a command."""
    global cmd_hook_process, cmd_command, cmd_start_time, cmd_buffer
    global cmd_stdout, cmd_stderr, cmd_send_to_buffer, cmd_timeout
    if cmd_hook_process:
        weechat.prnt(buffer,
                     '%sanother process is running! (use "/%s -kill" to kill it)'
                     % (SHELL_PREFIX, SHELL_CMD))
        return
    if cmd_send_to_buffer == 'new':
        weechat.prnt(buffer, '-->\t%s%s$ %s%s'
                     % (weechat.color('chat_buffer'), os.getcwd(), weechat.color('reset'), command))
        weechat.prnt(buffer, '')
    args = command.split(' ')
    if args[0] == 'cd':
        shell_chdir(buffer, ' '.join(args[1:]))
    elif args[0] == 'getenv':
        shell_getenv (buffer, ' '.join(args[1:]))
    elif args[0] == 'setenv':
        shell_setenv (buffer, ' '.join(args[1:]))
    elif args[0] == 'unsetenv':
        shell_unsetenv (buffer, ' '.join(args[1:]))
    else:
        shell_init()
        cmd_command = command
        cmd_start_time = datetime.datetime.now()
        cmd_buffer = buffer
        version = weechat.info_get("version_number", "") or 0
        if int(version) >= 0x00040000:
            cmd_hook_process = weechat.hook_process_hashtable('sh', { 'arg1': '-c', 'arg2': command },
                                                              cmd_timeout * 1000, 'shell_process_cb', command)
        else:
            cmd_hook_process = weechat.hook_process("sh -c '%s'" % command, cmd_timeout * 1000, 'shell_process_cb', command)
Beispiel #24
0
def conversation_cb(data, buffer, args):
    """
    Follows the reply trail until the original was found.
    NOTE: This might block for a while.
    """
    global twitter
    conversation = []
    reply_id = args
    # Loop as long as there was a reply_id.
    while reply_id:
        try:
            conversation.append(twitter.get_tweet(reply_id))
            reply_id = conversation[-1].in_reply_to_status_id
        except TwitterError as error:
            print_error(error)
            break
    if conversation:
        # Reverse the conversation to get the oldest first.
        conversation.reverse()
        # Now display the conversation.
        print_to_current("%s-------------------" % wc.color("magenta"))
        for tweet in conversation:
            nick_color = wc.info_get("irc_nick_color", tweet.screen_name)
            screen_name = nick_color + tweet.screen_name
            expand_urls = wc.config_string_to_boolean(wc.config_get_plugin("expand_urls"))
            text = tweet.txt_unescaped
            if expand_urls:
                text = tweet.txt
            output = "%s\t%s" % (screen_name, text)
            if tweet.is_retweet:
                output += " (RT by @%s)" % tweet.rtscreen_name
            output += "\n[#STATUSID: %s]" % tweet.id
            print_to_current(output)
        print_to_current("%s-------------------" % wc.color("magenta"))
    return wc.WEECHAT_RC_OK
def tc_bar_item (data, item, window):
    '''Item constructor'''
    global length, cursor_pos, tc_input_text, count_over,tc_options
    count_over = '0'

    # reverse check for max_chars
    reverse_chars = (int(tc_options['max_chars']) - length)
#    reverse_chars = (int(max_chars) - length)
    if reverse_chars == 0:
        reverse_chars = "%s" % ("0")
    else:
        if reverse_chars < 0:
            count_over = "%s%s%s" % (w.color(tc_options['warn_colour']),str(reverse_chars*-1), w.color('default'))
            reverse_chars = "%s" % ("0")
            tc_action_cb()
        else:
            reverse_chars = str(reverse_chars)
    out_format = tc_options['format']
    if length >= int(tc_options['warn']):
        length_warn = "%s%s%s" % (w.color(tc_options['warn_colour']), str(length), w.color('default'))
        out_format = out_format.replace('%L', length_warn)
    else:
        out_format = out_format.replace('%L', str(length))

    out_format = out_format.replace('%P', str(cursor_pos))
    out_format = out_format.replace('%R', reverse_chars)
    out_format = out_format.replace('%C', count_over)
    tc_input_text = out_format

    return tc_input_text
def show_spell_suggestion_item_cb(data, item, window):
    buffer = weechat.window_get_pointer(window, "buffer")
    if buffer == "":
        return ""

    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),
            )
    #            weechat.prnt("",new_word)
    else:
        return ""

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

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

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

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

       if i >= limit:
           break

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

    printstr = "{}\t{}".format(pf, ", ".join(nicks))
    if remainder > 0:
        printstr += ", and {} more..".format(remainder)
    w.prnt(target, printstr)
Beispiel #28
0
def tc_bar_item (data, item, window):
    '''Item constructor'''
    global laenge, cursor_pos, tc_input_text, count_over
    count_over = "0"

    # reverse check for max_chars
    reverse_chars = (int(max_chars) - laenge)
    if reverse_chars == 0:
        reverse_chars = "%s" % ("0")
    else:
        if reverse_chars < 0:
            count_over = "%s%s%s" % (w.color(warn_colour),str(reverse_chars*-1), w.color('default'))
            reverse_chars = "%s" % ("0")
        else:
            reverse_chars = str(reverse_chars)
    out_format = format
    if laenge >= int(warn):
        laenge_warn = "%s%s%s" % (w.color(warn_colour), str(laenge), w.color('default'))
        out_format = out_format.replace('%L', laenge_warn)
    else:
        out_format = out_format.replace('%L', str(laenge))

    out_format = out_format.replace('%P', str(cursor_pos))
    out_format = out_format.replace('%R', reverse_chars)
    out_format = out_format.replace('%C', count_over)
    tc_input_text = out_format
    return tc_input_text
Beispiel #29
0
def print_tweet_data(buffer,tweets,data):

    for message in tweets:
        nick = message[1]
        text = message[3]
        reply_id = ""
        if script_options['tweet_nicks']:
            parse_for_nicks(text,buffer)
            add_to_nicklist(buffer,nick,tweet_nicks_group[buffer])

        if script_options['print_id']:
            t_id = weechat.color('reset') + ' ' + dict_tweet(message[2])
        else:
            t_id = ''

        if len(message) == 5:
            #This is a reply to a tweet
            arrow_col = weechat.color('chat_prefix_suffix')
            reset_col = weechat.color('reset')
            reply_id = arrow_col +  "<" + reset_col + dict_tweet(message[4]) + arrow_col + "> " + reset_col
            temp_text = text
            text = reply_id
            reply_id = temp_text

        weechat.prnt_date_tags(buffer, message[0], "notify_message",
                "%s%s\t%s%s" % (nick, t_id, text,reply_id))
    if data == "id":
        try:
            if script_options['last_id'] < tweets[-1][2]:
                script_options['last_id'] = tweets[-1][2]
                # Save last id
                weechat.config_set_plugin("last_id",script_options["last_id"])
        except:
            pass
Beispiel #30
0
def urlbar_item_cb(data, item, window):
    ''' Callback that prints the lines in the urlbar '''
    global DISPLAY_ALL, urls
    try:
        visible_amount = int(weechat.config_get_plugin('visible_amount'))
    except ValueError:
        weechat.prnt('', 'Invalid value for visible_amount setting.')

    if not urls:
        return 'Empty URL list'

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

    result = ''
    for index, url in enumerate(printlist):
        if weechat.config_get_plugin('show_index') == 'on':
            index = index+1
            result += '%s%2d%s %s \r' %\
                (weechat.color("yellow"), index, weechat.color("bar_fg"), url)
        else:
            result += '%s%s \r' %(weechat.color('bar_fg'), url)
    return result
Beispiel #31
0
def go_buffers_to_string(listbuf, pos, strinput):
    """Return string built with list of buffers found (matching user input)."""
    string = ''
    strinput = strinput.lower()
    for i in range(len(listbuf)):
        selected = '_selected' if i == pos else ''
        buffer_name = listbuf[i]['name']
        index = buffer_name.lower().find(strinput)
        if index >= 0:
            index2 = index + len(strinput)
            name = '%s%s%s%s%s' % (
                buffer_name[:index],
                weechat.color(
                    weechat.config_get_plugin('color_name_highlight' +
                                              selected)),
                buffer_name[index:index2],
                weechat.color(
                    weechat.config_get_plugin('color_name' + selected)),
                buffer_name[index2:])
        elif go_option_enabled("fuzzy_search") and \
                go_match_fuzzy(buffer_name.lower(), strinput):
            name = ""
            prev_index = -1
            for char in strinput.lower():
                index = buffer_name.lower().find(char, prev_index + 1)
                if prev_index < 0:
                    name += buffer_name[:index]
                    name += weechat.color(
                        weechat.config_get_plugin('color_name_highlight' +
                                                  selected))
                if prev_index >= 0 and index > prev_index + 1:
                    name += weechat.color(
                        weechat.config_get_plugin('color_name' + selected))
                    name += buffer_name[prev_index + 1:index]
                    name += weechat.color(
                        weechat.config_get_plugin('color_name_highlight' +
                                                  selected))
                name += buffer_name[index]
                prev_index = index

            name += weechat.color(
                weechat.config_get_plugin('color_name' + selected))
            name += buffer_name[prev_index + 1:]
        else:
            name = buffer_name
        string += ' '
        if go_option_enabled('buffer_number'):
            string += '%s%s' % (weechat.color(
                weechat.config_get_plugin('color_number' + selected)),
                                str(listbuf[i]['number']))
        string += '%s%s%s' % (weechat.color(
            weechat.config_get_plugin('color_name' + selected)), name,
                              weechat.color('reset'))
    return '  ' + string if string else ''
Beispiel #32
0
def bar_item_cmodes(data, item, window):
    buffer = w.window_get_pointer(window, "buffer")
    server = w.buffer_get_string(buffer, "localvar_server")
    channel = w.buffer_get_string(buffer, "localvar_channel")

    if w.info_get("irc_is_channel", channel):
        cinfo = w.infolist_get("irc_channel", '', f"{server},{channel}")
        w.infolist_next(cinfo)
        modes = w.infolist_string(cinfo, "modes")
        w.infolist_free(cinfo)

        modes, _, args = modes.lstrip("+").partition(" ")
        args = args.split(" ")
        modes = list(modes)

        isupport_chanmodes = w.info_get("irc_server_isupport_value",
                                        f"{server},CHANMODES").split(",", 3)
        modes_with_args = set("".join(isupport_chanmodes[:3]))

        for i, mode in enumerate(modes):
            if mode in modes_with_args and args:
                modes[i] = (mode, args.pop(0))
            else:
                modes[i] = (mode, None)
        args.clear()

        modes.sort(key=lambda m: m[0])
        if w.config_get_plugin("args-first") == "yes":
            modes.sort(key=lambda m: 0 if m[1] else 1)

        modesf = mode_setting("cmodes", server) or default_cmodes(server)
        for i, (mode, arg) in enumerate(modes):
            if mode in modesf:
                color = w.color(modesf[mode])
            else:
                color = w.color(
                    w.config_string(
                        w.config_get("irc.color.item_channel_modes")))

            mode = f"{color}{mode}"
            if arg:
                args.append(f"{color}{arg}")
            modes[i] = mode

        args = " ".join(args)
        if args:
            args = f" {args}"
        return "+" + "".join(modes) + args
    return ""
Beispiel #33
0
def nick_colors_cmd_cb(data, buffer, args):
    global colored_nicks

    if args == "":  # no args given. quit
        return weechat.WEECHAT_RC_OK

    argv = args.strip().split(" ")
    if (len(argv) == 0) or (len(argv) >= 4):  # maximum of 3 args!!
        return weechat.WEECHAT_RC_OK

    bufpointer = weechat.window_get_pointer(buffer, 'buffer')  # current buffer

    create_list()

    if argv[0].lower() == 'list':  # list all nicks
        if len(colored_nicks) == 0:
            weechat.prnt(
                buffer, '%sno nicks in \"irc.look.nick_color_force\"...' %
                weechat.prefix("error"))
            return weechat.WEECHAT_RC_OK
        if len(argv) == 2:
            if argv[1] in colored_nicks:
                color = colored_nicks[argv[1]]  # get color from given nick
                weechat.prnt(
                    buffer,
                    "%s%s: %s" % (weechat.color(color), argv[1], color))
            else:
                weechat.prnt(buffer, "no color set for: %s" % (argv[1]))
            return weechat.WEECHAT_RC_OK

        weechat.prnt(buffer, "List of nicks in : nick_color_force")
        for nick, color in colored_nicks.items():
            weechat.prnt(buffer,
                         "%s%s: %s" % (weechat.color(color), nick, color))
        return weechat.WEECHAT_RC_OK

    if (argv[0].lower() == 'add') and (len(argv) == 3):
        if argv[1] in colored_nicks:  # search if nick exists
            colored_nicks[argv[1]] = argv[2]
        else:
            colored_nicks[argv[1]] = argv[2]  # add [nick] = [color]
        save_new_force_nicks()

    if (argv[0].lower() == 'del') and (len(argv) == 2):
        if argv[1] in colored_nicks:  # search if nick exists
            del colored_nicks[argv[1]]
            save_new_force_nicks()

    return weechat.WEECHAT_RC_OK
Beispiel #34
0
def lb_line_format(list_data,curr=False):
  str = ""
  if (curr):
    str += weechat.color("yellow,red")
  channel_text = list_data['channel'].ljust(int(weechat.config_get_plugin('channel_min_width')))
  users_text = "(%s)" % list_data['users']
  padded_users_text = users_text.rjust(int(weechat.config_get_plugin('users_min_width')) + 2)
  str += "%s%s %s " % (weechat.color("bold"), channel_text, padded_users_text)
  if not list_data['nomodes']:
    modes = "[%s]" % list_data['modes']
  else:
    modes = "[]"
  str += "%s: " % modes.rjust(int(weechat.config_get_plugin('modes_min_width')) + 2)
  str += "%s" % list_data['topic']
  return str
Beispiel #35
0
def _format_action(server, target, nick, text):
    white = w.color("white")

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

    chanc = w.color(w.config_string(
        w.config_get("weechat.color.chat_channel")))
    delim = w.color(
        w.config_string(w.config_get("weechat.color.chat_delimiters")))
    reset = w.color("reset")
    return f" {white}* {delim}({reset}{target[0]}{delim}){nickc}{nick}{reset} {text}"
Beispiel #36
0
def nick_color(nick):
    '''Randomizes color for nicks'''
    # Get the colors
    colors = weechat.config_get_plugin('colors').split(',')

    if nick in users and 'color' in users[nick]:
        pass
    else:
        users[nick] = {}
        users[nick]['color'] = ''.join(colors[randint(0, len(colors) - 1)])

    nick = ''.join(
        [weechat.color(users[nick]['color']), nick,
         weechat.color('reset')])
    return nick
Beispiel #37
0
def notify(data, buf, date, tags, displayed, hilight, prefix, msg):
    color = weechat.color(weechat.config_get_plugin('color'))
    reset = weechat.color('reset')

    my_nick = weechat.buffer_get_string(buf, 'localvar_nick')
    prefix = re.sub(r'^[@%+~]', r'', prefix)
    if prefix != my_nick:
        urls = find_and_process_urls(msg)

        for url, short_url in urls:
            weechat.prnt(
                buf, '%(color)s[ %(url)s ]%(reset)s' %
                dict(color=color, url=short_url, reset=reset))

    return weechat.WEECHAT_RC_OK
Beispiel #38
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)
        localvar_aspell_suggest = "dummy:%s" % aspell_suggest_items


#        return aspell_suggest_items

    else:
        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 position == "-1":
            return aspell_suggestions_orig
        if int(position) < len(aspell_suggestion_list):
            reset_color = weechat.color('reset')
            color = weechat.color(
                weechat.config_color(
                    weechat.config_get("%s.color.misspelled" % plugin_name)))
            new_word = aspell_suggestion_list[int(position)].replace(
                aspell_suggestion_list[int(position)], '%s%s%s' %
                (color, aspell_suggestion_list[int(position)], reset_color))
            aspell_suggestion_list[int(
                position)] = new_word  # replace word with colored word
            aspell_suggestions_orig = ','.join(map(str,
                                                   aspell_suggestion_list))
    else:
        return ''
    return aspell_suggestions_orig
Beispiel #39
0
def process_complete(data, command, rc, stdout, stderr):
    url = stdout.strip()
    if url:
        color = weechat.color(weechat.config_get_plugin("color"))
        weechat.prnt(data, '%s[%s]' % (color, url))

    return weechat.WEECHAT_RC_OK
Beispiel #40
0
 def prnt(self, buffer = '', prefix = '') :
     hcolor = weechat.color('separator')
     ncolor = weechat.color('chat_nick')
     prefix = prefix+hcolor
     weechat.prnt(buffer, "%s%s=============== %s[%s] (%s) %s===============\n" % (prefix, hcolor, ncolor, self.login, self.fd, hcolor))
     weechat.prnt(buffer, '%s   Host . . . . . . . . : %s\n' % (prefix, self.ip))
     weechat.prnt(buffer, "%s   Machine type . . . . : %s\n" % (prefix, self.machtype))
     weechat.prnt(buffer, "%s   Group. . . . . . . . : %s\n" % (prefix, self.group))
     weechat.prnt(buffer, "%s   State. . . . . . . . : %s\n" % (prefix, self.state))
     weechat.prnt(buffer, "%s   Data . . . . . . . . : %s\n" % (prefix, self.data))
     weechat.prnt(buffer, "%s   Location . . . . . . : %s\n" % (prefix, self.location))
     weechat.prnt(buffer, "%s   Connected at . . . . : %s\n" % (prefix, datetime.datetime.fromtimestamp(self.connection_time).strftime('%d/%m/%Y %H:%M:%S')))
     weechat.prnt(buffer, "%s   Last Activity. . . . : %s\n" % (prefix, datetime.datetime.fromtimestamp(self.lastseen_time).strftime('%d/%m/%Y %H:%M:%S')))
     weechat.prnt(buffer, "%s   Last status change . : %s\n" % (prefix, datetime.datetime.fromtimestamp(self.state_time).strftime('%d/%m/%Y %H:%M:%S')))
     weechat.prnt(buffer, "%s   Trust (User/client). : (%d/%d)\n" % (prefix, self.user_trust, self.client_trust))
     weechat.prnt(buffer, "%s%s==============================================" % (prefix, hcolor))
Beispiel #41
0
def urlserver_display_url_detail(key, return_url=False):
    global urlserver
    url = urlserver['urls'][key]
    nick = url[1]
    if nick:
        nick += ' @ '

    if return_url:
        return urlserver_short_url(key)

    weechat.prnt_date_tags(
        urlserver['buffer'], 0, 'notify_none',
        '{}, {}{}{}{}: {}{}{} -> {}'.format(
            url[0], nick, weechat.color('chat_buffer'), url[2],
            weechat.color('reset'), weechat.color(urlserver_settings['color']),
            urlserver_short_url(key), weechat.color('reset'), url[3]))
Beispiel #42
0
def colorize_nick_color(nick, my_nick):
    if nick == my_nick:
        return weechat.color(
            weechat.config_string(
                weechat.config_get('weechat.color.chat_nick_self')))
    else:
        return weechat.info_get('irc_nick_color', nick)
Beispiel #43
0
 def render(self):
     for y in self.screen.dirty:
         line = self.display_line(self.screen.buffer[y])
         message = self.render_line(y, line) + weechat.color("reset")
         weechat.prnt_y(self.buffer, y, message.encode("utf-8"))
         
     self.screen.dirty.clear()
Beispiel #44
0
def theme_config_color(color):
    """Get a color from configuration."""
    global theme_config_option
    option = theme_config_option.get('color_%s' % color, '')
    if not option:
        return ''
    return weechat.color(weechat.config_string(option))
Beispiel #45
0
def substitute_colors(text,window):
    if int(version) >= 0x00040200:
        bufpointer = weechat.window_get_pointer(window,"buffer")
        return weechat.string_eval_expression(text, {"buffer": bufpointer}, {}, {})
#        return weechat.string_eval_expression(text,{},{},{})
    # substitute colors in output
    return re.sub(regex_color, lambda match: weechat.color(match.group(1)), text)
Beispiel #46
0
def show_link_qr(uri):
    logger.debug("encoding as QR code: %s", uri)
    prnt(
        "Open Signal on your phone and navigate to Settings > Linked devices. Tap the button to add a new device, "
        "then scan the code above.")
    code = qrcode.QRCode()
    code.add_data(uri)
    matrix = code.get_matrix()
    lastline = len(matrix) - 1
    for y in range(0, len(matrix), 2):
        line = ""
        for x in range(0, len(matrix[y])):
            if matrix[y][x]:
                # This line is black
                if lastline > y and matrix[y + 1][x]:
                    # The next line is also black
                    line += "█"
                else:
                    # The next line is white or non existant
                    line += "▀"
            else:
                # This line is white
                if lastline > y and matrix[y + 1][x]:
                    # The next line is black
                    line += "▄"
                else:
                    # The next line is also white or non-existant
                    line += " "
        prnt("%s%s" % (weechat.color("black,white"), line))
Beispiel #47
0
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
Beispiel #48
0
def wg_check_scripts():
    """
    Check status of local script(s).
    For each script found, display status (unknown/running/new version available).
    For example:
       r   python/autoload/vdm.py
      ?r   python/autoload/dummy.py
       rN  python/shell.py
           perl/buffers.pl
    """
    local_scripts_status = wg_get_local_scripts_status()
    if len(local_scripts_status) == 0:
        return
    weechat.prnt("", "")
    weechat.prnt("", "Local scripts:")
    for file, status in local_scripts_status:
        str_unknown = " "
        str_running = " "
        str_obsolete = " "
        if status["unknown"]:
            str_unknown = "?"
        if status["running"]:
            str_running = "r"
        if status["obsolete"]:
            str_obsolete = "N"
        weechat.prnt(
            "", "%s%s%s%s%s%s%s  %s%s%s%s" %
            (wg_config_color("unknown"), str_unknown,
             wg_config_color("running"), str_running,
             wg_config_color("obsolete"), str_obsolete, weechat.color("chat"),
             os.path.dirname(file), os.sep, wg_config_color("script"),
             os.path.basename(file)))
Beispiel #49
0
 def send(self, message):
     weechat.prnt(
         self.buffer,
         '%s%s\t%s' % (weechat.color("chat_nick_self"),
                       self.server.get_option('login'), message))
     recipient = self.login if self.fd is None else (':' + self.fd)
     self.server._ns_user_cmd_msg_user(recipient, message)
Beispiel #50
0
 def colorized_name(self):
     if colorize_nicks:
         color = w.info_get('irc_nick_color', self.name)
         def_color = w.color('default')
         return color + self.name + def_color
     else:
         return self.name
Beispiel #51
0
def wg_config_color(color):
    """ Get a color from configuration. """
    global wg_config_option
    option = wg_config_option.get("color_" + color, "")
    if option == "":
        return ""
    return weechat.color(weechat.config_string(option))
Beispiel #52
0
def list_bots():
    bots = file_read(FILE_BOTS)
    if bots == {}:
        weechat.prnt(
            "", "%sThere are no added bots to watch for updates on." %
            (weechat.color("red")))
    else:
        weechat.prnt(
            "", "-- %sList of the watched bots %s--------" %
            (weechat.color("yellow"), weechat.color("chat")))
        for bot_name, regex in bots.iteritems():
            weechat.prnt(
                "", "  %s%-24s %s%s" % (weechat.color("green"), bot_name,
                                        weechat.color("chat"), regex))
        weechat.prnt("", "------------------------------------")
    return weechat.WEECHAT_RC_OK
Beispiel #53
0
def urlserver_print_cb(data, buffer, time, tags, displayed, highlight, prefix,
                       message):
    """
    Callback for message printed in buffer: display short URLs after message.
    """
    global urlserver, urlserver_settings

    if urlserver_settings['display_urls'] == 'on':
        buffer_full_name = '%s.%s' % (weechat.buffer_get_string(
            buffer, 'plugin'), weechat.buffer_get_string(buffer, 'name'))
        if urlserver_settings['buffer_short_name'] == 'on':
            buffer_short_name = weechat.buffer_get_string(buffer, 'short_name')
        else:
            buffer_short_name = buffer_full_name
        urls_short = urlserver_update_urllist(buffer_full_name,
                                              buffer_short_name, tags, prefix,
                                              message)
        if urls_short:
            if urlserver_settings['separators'] and \
                    len(urlserver_settings['separators']) == 3:
                separator = ' %s ' % (urlserver_settings['separators'][1])
                urls_string = separator.join(urls_short)
                urls_string = '%s %s %s' % (
                    urlserver_settings['separators'][0], urls_string,
                    urlserver_settings['separators'][2])
            else:
                urls_string = ' | '.join(urls_short)
                urls_string = '[ ' + urls_string + ' ]'
            weechat.prnt_date_tags(
                buffer, 0, 'no_log,notify_none', '%s%s' %
                (weechat.color(urlserver_settings['color']), urls_string))

    return weechat.WEECHAT_RC_OK
Beispiel #54
0
def wg_remove_scripts(names):
    """ Remove scripts. """
    if len(wg_scripts) == 0:
        return
    list_names = names.split(" ")
    scripts_to_remove = {}
    for language in SCRIPT_EXTENSION.keys():
        scripts_to_remove[language] = []
    for name in list_names:
        script = wg_search_script_by_name(name)
        if script == None:
            weechat.prnt(
                "", "%s: script \"%s%s%s\" not found" %
                (SCRIPT_NAME, wg_config_color("script"), name,
                 weechat.color("chat")))
        else:
            if script["full_name"] not in scripts_to_remove[
                    script["language"]]:
                scripts_to_remove[script["language"]].append(
                    script["full_name"])
    for language in SCRIPT_EXTENSION.keys():
        if len(scripts_to_remove[language]) > 0:
            # ask C plugin to remove script file(s)
            weechat.hook_signal_send(language + "_script_remove",
                                     weechat.WEECHAT_HOOK_SIGNAL_STRING,
                                     ",".join(scripts_to_remove[language]))
Beispiel #55
0
def wg_install_next_script():
    """
    Install first script in list wg_scripts_to_install and remove it from
    list.
    """
    global wg_scripts, wg_scripts_to_install, wg_current_script_install
    global wg_hook_process
    if len(wg_scripts) == 0:
        return
    # be sure weeget is ALWAYS last script to install/update
    # otherwise we'll lose end of list when weeget is unloaded by WeeChat
    if SCRIPT_NAME in wg_scripts_to_install:
        wg_scripts_to_install.remove(SCRIPT_NAME)
        wg_scripts_to_install.append(SCRIPT_NAME)
    # loop until a script is installed, or end if list is empty
    while len(wg_scripts_to_install) > 0:
        name = wg_scripts_to_install.pop(0)
        script = wg_search_script_by_name(name)
        if script == None:
            weechat.prnt(
                "", "%s: script \"%s%s%s\" not found" %
                (SCRIPT_NAME, wg_config_color("script"), name,
                 weechat.color("chat")))
        else:
            status = wg_get_local_script_status(script)
            if status["installed"] and not status["obsolete"]:
                weechat.prnt(
                    "", "%s: script \"%s%s%s\" is already "
                    "installed and up to date" %
                    (SCRIPT_NAME, wg_config_color("script"),
                     script["full_name"], weechat.color("chat")))
            else:
                weechat.prnt(
                    "", "%s: downloading \"%s%s%s\"..." %
                    (SCRIPT_NAME, wg_config_color("script"),
                     script["full_name"], weechat.color("chat")))
                if wg_hook_process["script"] != "":
                    weechat.unhook(wg_hook_process["script"])
                    wg_hook_process["script"] = ""
                wg_current_script_install = script
                filename = wg_config_get_dir() + os.sep + script["full_name"]
                wg_hook_process["script"] = wg_download_file(
                    script["url"], filename, TIMEOUT_SCRIPT,
                    "wg_process_script_cb", "")
                # this function will be called again when script will be
                # downloaded
                return
Beispiel #56
0
def twitch_clearchat(data, modifier, modifier_data, string):
    mp = weechat.info_get_hashtable('irc_message_parse', {"message": string})
    server = modifier_data
    user = mp['text']
    channel = mp['channel']
    try:
        tags = dict([s.split('=') for s in mp['tags'].split(';')])
    except:
        tags = ''
    buffer = weechat.buffer_search("irc", "%s.%s" % (server, channel))
    if buffer:
        pcolor = weechat.color('chat_prefix_network')
        ccolor = weechat.color('chat')
        ul = weechat.color("underline")
        rul = weechat.color("-underline")
        if user:
            if 'ban-duration' in tags:
                if tags['ban-reason']:
                    bn = tags['ban-reason'].replace('\s', ' ')
                    weechat.prnt(
                        buffer,
                        "%s--%s %s has been timed out for %s seconds %sReason%s: %s"
                        % (pcolor, ccolor, user, tags['ban-duration'], ul, rul,
                           bn))
                else:
                    weechat.prnt(
                        buffer, "%s--%s %s has been timed out for %s seconds" %
                        (pcolor, ccolor, user, tags['ban-duration']))
            elif 'ban-reason' in tags:
                if tags['ban-reason']:
                    bn = tags['ban-reason'].replace('\s', ' ')
                    weechat.prnt(
                        buffer, "%s--%s %s has been banned %sReason%s: %s" %
                        (pcolor, ccolor, user, ul, rul, bn))
                else:
                    weechat.prnt(
                        buffer,
                        "%s--%s %s has been banned" % (pcolor, ccolor, user))
            else:
                weechat.prnt(
                    buffer, "%s--%s %s's Chat Cleared By Moderator" %
                    (pcolor, ccolor, user))
        else:
            weechat.prnt(
                buffer,
                "%s--%s Entire Chat Cleared By Moderator" % (pcolor, ccolor))
    return ""
Beispiel #57
0
def nameday_build_item():
    """Build nameday item."""
    global nameday_settings, nameday_item
    nameday_item = ''
    display_date_today = nameday_settings['item_date_today'].lower() == 'on'
    display_date_next = nameday_settings['item_date_next'].lower() == 'on'
    display_gender = nameday_settings['item_name_gender'].lower() == 'on'
    color_date_today = weechat.color(nameday_settings['item_color_date_today'])
    color_name_today = weechat.color(nameday_settings['item_color_name_today'])
    color_date_next = weechat.color(nameday_settings['item_color_date_next'])
    color_name_next = weechat.color(nameday_settings['item_color_name_next'])
    color_default = weechat.color('default')
    today = date.today()
    if display_date_today:
        nameday_item += '%s%02d/%02d%s: ' % (color_date_today,
                                             today.day, today.month,
                                             color_default)
    nameday_item += '%s%s' % (color_name_today,
                              nameday_get_date(today, gender=display_gender,
                                               colorMale='item_color_male_today',
                                               colorFemale='item_color_female_today'))
    days = 0
    try:
        days = int(nameday_settings['days'])
    except:
        days = 0
    if days < 0:
        days = 0
    if days > 10:
        days = 10
    if days > 0:
        nameday_item += '%s (' % color_default
        current_time = time.time()
        for i in range(1, days + 1):
            if i > 1:
                nameday_item += ', '
            date2 = date.fromtimestamp(current_time + ((3600 * 24) * i))
            if display_date_next:
                nameday_item += '%s%02d/%02d%s: ' % (color_date_next,
                                                     date2.day, date2.month,
                                                     color_default)
            nameday_item += '%s%s' % (color_name_next,
                                      nameday_get_date(date2, gender=display_gender,
                                                       colorMale='item_color_male_next',
                                                       colorFemale='item_color_female_next'))
        nameday_item += '%s)' % color_default
    return nameday_item
Beispiel #58
0
def bar_item_cb(data, item, window, buffer, extra_info):
	"""
	Build the bar item's content for "buffer".
	"""

	buffers = ",".join(get_merged_buffers(buffer))
	name = "%s_%s" % (SCRIPT_NAME, buffers)

	if filter_exists(name):
		warn = int(weechat.buffer_get_string(buffer, "localvar_%s_warn" % SCRIPT_LOCALVAR))

		return "%s%s%s" % (
			weechat.color("input_text_not_found" if warn else "bar_fg"),
			weechat.config_get_plugin("bar_item"),
			weechat.color("reset"))
	else:
		return ""
Beispiel #59
0
def list_filters():
    filters_h = file_read(FILE_FILTERS)
    if filters_h == {} or filters_h == {"filters": []}:
        weechat.prnt(
            "", "%sThere are no added file filters." % (weechat.color("red")))
    else:
        weechat.prnt(
            "", "-- %sList of the file filters %s--------" %
            (weechat.color("yellow"), weechat.color("chat")))
        i = 0
        for fltr in filters_h["filters"]:
            i += 1
            weechat.prnt(
                "", "%4s  %s%s%s" % (str(i), weechat.color("green"), fltr,
                                     (weechat.color("chat"))))
        weechat.prnt("", "------------------------------------")
    return weechat.WEECHAT_RC_OK
Beispiel #60
0
def cron_list(debug=False):
    """ Display list of jobs in crontab. """
    global crontab
    if len(crontab) == 0:
        weechat.prnt("", "cron: empty crontab")
    else:
        weechat.prnt("", "crontab:")
        for i, job in enumerate(crontab):
            if debug:
                str_job = "%s" % job.str_debug()
            else:
                str_job = "%s" % job
            weechat.prnt("", "  %s[%s%03d%s]%s %s"
                         % (weechat.color("chat_delimiters"), weechat.color("chat"),
                            i + 1,
                            weechat.color("chat_delimiters"), weechat.color("chat"),
                            str_job))