Exemple #1
0
def whois(username):
    if len(username) == 0:
        return weechat.WEECHAT_RC_ERROR

    response = statusnet_handler.handle_request(
        statusnet_handler.build_request('users', 'show', username))

    if response == None:
        pass
    elif response == False:
        weechat.prnt(weechat.current_buffer(),
                     ('%sCan\'t retrieve information about %s' %
                      (weechat.prefix('error'), username)))
    else:
        whois = json.load(response)

        whois['summary'] = ' '.join([
            u'\u00B5',
            str(whois['statuses_count']), u'\u2764',
            str(whois['favourites_count']), 'subscribers',
            str(whois['followers_count']), 'subscriptions',
            str(whois['friends_count'])
        ])

        for property in [
                'name', 'description', 'url', 'location', 'profile_image_url',
                'summary'
        ]:
            if whois[property] != None:
                weechat.prnt(weechat.current_buffer(),
                             ('%s[%s] %s' %
                              (weechat.prefix('network'), username,
                               whois[property].encode('utf-8'))))

    return weechat.WEECHAT_RC_OK
Exemple #2
0
def groups(username):
    '''Shows groups a user is in'''
    if len(username) == 0:
        return weechat.WEECHAT_RC_ERROR

    response = statusnet_handler.handle_request(
        statusnet_handler.build_request('statusnet/groups', 'list', username))

    if response == None:
        pass
    elif response == False:
        weechat.prnt(
            weechat.current_buffer(),
            '%sCan\'t show %s\'s groups' % (weechat.prefix('error'), username))
    else:
        groups = json.load(response)
        group_list = ' '.join(
            [group['nickname'].encode('utf-8') for group in groups])

        weechat.prnt(
            weechat.buffer_search('', weechat.config_get_plugin('channel')),
            '%sGroups %s is in: %s' %
            (weechat.prefix('network'), nick_color(username), group_list))

    return weechat.WEECHAT_RC_OK
Exemple #3
0
def opall(data, buffer, args):
    channel = weechat.buffer_get_string(buffer, 'localvar_channel')
    server = weechat.buffer_get_string(buffer, 'localvar_server')

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

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

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

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

    return weechat.WEECHAT_RC_OK
Exemple #4
0
def get_autojoin_list(buffer, server):
    ptr_config_autojoin = weechat.config_get('irc.server.%s.autojoin' % server)
    # option not found! server does not exist
    if not ptr_config_autojoin:
        weechat.prnt(
            "", "%s%s: server '%s' does not exist." %
            (weechat.prefix('error'), SCRIPT_NAME, server))
        return 1, 1

    # get value from autojoin option
    channels = weechat.config_string(ptr_config_autojoin)
    if not channels:
        return 1, 1

    # check for keys
    if len(re.findall(r" ", channels)) == 0:
        list_of_channels = channels.split(",")
        list_of_keys = []
    elif len(re.findall(r" ", channels)) == 1:
        list_of_channels2, list_of_keys = channels.split(" ")
        list_of_channels = list_of_channels2.split(",")
    else:
        weechat.prnt(
            "", "%s%s: irc.server.%s.autojoin not valid..." %
            (weechat.prefix('error'), SCRIPT_NAME, server))
        return 1, 1

    return list_of_channels, list_of_keys
Exemple #5
0
def populate_subscriptions():
    '''Populates users dict with subscriptions'''
    response = statusnet_handler.handle_request(
        statusnet_handler.build_request('statuses', 'friends',
                                        weechat.config_get_plugin('username')))

    if response == None:
        pass
    elif response == False:
        weechat.prnt(
            weechat.current_buffer(),
            ('%sCan\'t obtain subscription list ' % weechat.prefix('error')))
    else:
        subscriptions = json.load(response)
        for profile in subscriptions:
            populate = nick_color(profile['screen_name'].encode('utf-8'))

        weechat.prnt(
            weechat.buffer_search('', weechat.config_get_plugin('channel')),
            ' '.join([
                weechat.prefix('network'), 'Subscriptions',
                '(%d)' % len(users)
            ] + [username for username in users]))

    return weechat.WEECHAT_RC_OK
Exemple #6
0
 def connect(self):
     self.create_buffer()
     self.disconnect()
     weechat.prnt(
         self.buffer, 'Connecting to %s:%s' %
         (self.get_option('host'), self.get_option('port')))
     try:
         hints = socket.getaddrinfo(self.get_option('host'),
                                    self.get_option('port'),
                                    socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
                                    socket.AI_PASSIVE)
     except socket.error as e:
         weechat.prnt(self.buffer,
                      '%s%s' % (weechat.prefix('error'), e.args[1]))
     else:
         for res in hints:
             af, socktype, proto, canonname, sa = res
             try:
                 self.socket = socket.socket(af, socktype, proto)
                 self.socket.connect(sa)
             except socket.error:
                 self.socket = None
                 continue
             break
     if self.socket is None:
         weechat.prnt(self.buffer,
                      '%sCould not connect' % (weechat.prefix('error'), ))
     else:
         self.hook_fd = weechat.hook_fd(self.socket.fileno(), 1, 0, 0,
                                        'wee_ns_hook_fd_cb', '')
Exemple #7
0
def wg_parse_xml():
    """
    Parse XML scripts list and return dictionary with list, with key 'id'.
    Example of item return in dictionary :
      '119': { 'name'        : 'weeget',
               'version'     : '0.1',
               'url'         : 'http://www.weechat.org/files/scripts/weeget.py',
               'language'    : 'python',
               'license'     : 'GPL3',
               'md5sum'      : 'd500714fc19b0e10cc4e339e70739e4ad500714fc19b0e10cc4e339e70739e4a',
               'tags'        : 'scripts',
               'desc_en'     : 'Scripts manager.',
               'requirements': 'python 2.5',
               'min_weechat' : '0.3.0',
               'max_weechat' : '',
               'author'      : 'FlashCode',
               'mail'        : 'flashcode [at] flashtux [dot] org',
               'added'       : '2009-04-05 22:39:18',
               'updated'     : '0000-00-00 00:00:00' }
    """
    global wg_scripts, wg_action, wg_action_args
    wg_scripts = {}
    try:
        f = gzip.open(wg_config_get_cache_filename(), "rb")
        string = f.read()
        f.close()
    except:
        weechat.prnt(
            "", "%s%s: unable to read xml file" %
            (weechat.prefix("error"), SCRIPT_NAME))
    else:
        try:
            dom = xml.dom.minidom.parseString(string)
        except:
            weechat.prnt(
                "", "%s%s: unable to parse xml list of scripts" %
                (weechat.prefix("error"), SCRIPT_NAME))
            # discard action
            wg_action = ""
            wg_action_args = ""
        else:
            for scriptNode in dom.getElementsByTagName("plugin"):
                id = scriptNode.getAttribute("id")
                script = {}
                for node in scriptNode.childNodes:
                    if node.nodeType == node.ELEMENT_NODE:
                        if node.firstChild != None:
                            nodename = node.nodeName
                            value = node.firstChild.data
                            if sys.version_info < (3, ):
                                # python 2.x: convert unicode to str (in python 3.x, id and text are already strings)
                                nodename = nodename.encode("utf-8")
                                value = value.encode("utf-8")
                            script[nodename] = value
                if script["language"] in SCRIPT_EXTENSION:
                    script["full_name"] = script[
                        "name"] + "." + SCRIPT_EXTENSION[script["language"]]
                    if wg_check_version(script):
                        wg_scripts[id] = script
            wg_execute_action()
Exemple #8
0
def group(group):
    '''Shows information about a group'''
    if len(group) == 0:
        return weechat.WEECHAT_RC_ERROR

    response = statusnet_handler.handle_request(
        statusnet_handler.build_request('statusnet/groups', 'show', group))

    if response == None:
        pass
    elif response == False:
        weechat.prnt(weechat.current_buffer(),
                     ('%sCan\'t show %s' % (weechat.prefix('error'), group)))
    else:
        group_info = json.load(response)
        for property in [
                'fullname', 'description', 'homepage_url', 'location',
                'original_logo'
        ]:
            if property in group_info and group_info[property] != None:
                weechat.prnt(weechat.current_buffer(),
                             ('%s[%s] %s' %
                              (weechat.prefix('network'), group,
                               group_info[property].encode('utf-8'))))

    return weechat.WEECHAT_RC_OK
Exemple #9
0
def fish_secure_error():
    """print error message if secdata not decrypted"""

    message = (
        "\n%s%sblowkey:%s unable to recover key from sec.conf\n"
        "%s%sblowkey:%s fish.py %sNOT LOADED\n"
        "%s%sblowkey:%s decrypt secured data first\n"
        "%s%sblowkey:%s then reload fish.py\n\n"
    ) % (
        weechat.prefix("error"),
        weechat.color("underline"),
        weechat.color("reset"),
        weechat.prefix("error"),
        weechat.color("underline"),
        weechat.color("reset"),
        weechat.color("*red"),
        weechat.prefix("error"),
        weechat.color("underline"),
        weechat.color("reset"),
        weechat.prefix("error"),
        weechat.color("underline"),
        weechat.color("reset"),
    )

    weechat.prnt("", "%s" % message)
def add_regex(data, buffer, argList):
    intRequiredArgs = 2
    split_args = argList.split(" ", 1)
    num_of_args = len(split_args)
    
    if not argList:
        #print_help()
        w.prnt("", w.prefix("error") + "No arguments supplied.")
        return w.WEECHAT_RC_ERROR
        
    if num_of_args != intRequiredArgs:
        #print_help()
        w.prnt("", w.prefix("error") + "Wrong number of arguments. Supplied: " + str(num_of_args) + ", required: " + str(intRequiredArgs) +".")
        return w.WEECHAT_RC_ERROR
    
    GroupName = split_args[0]
    regex = split_args[1]
    
    ####w.prnt("", "Group Name: " + GroupName)
    ####w.prnt("", "Regex: " + regex)
    ####w.prnt("", "Option count: " + str(num_of_args))
    
    w.config_set_plugin(GroupName + ".regex", regex)
    
    return w.WEECHAT_RC_OK
Exemple #11
0
def shell_process_cb(data, command, rc, stdout, stderr):
    """Callback for hook_process()."""
    global cmd_hook_process, cmd_buffer, cmd_stdout, cmd_stderr, cmd_send_to_buffer
    cmd_stdout += stdout
    cmd_stderr += stderr
    if int(rc) >= 0:
        if cmd_stdout:
            lines = cmd_stdout.rstrip().split('\n')
            if cmd_send_to_buffer == 'current':
                for line in lines:
                    weechat.command(cmd_buffer, '%s' % line)
            else:
                weechat.prnt(cmd_buffer, '')
                if cmd_send_to_buffer != 'new':
                    weechat.prnt(cmd_buffer, '%sCommand "%s" (rc %d), stdout:'
                                 % (SHELL_PREFIX, data, int(rc)))
                for line in lines:
                    weechat.prnt(cmd_buffer, ' \t%s' % line)
        if cmd_stderr:
            lines = cmd_stderr.rstrip().split('\n')
            if cmd_send_to_buffer == 'current':
                for line in lines:
                    weechat.command(cmd_buffer, '%s' % line)
            else:
                weechat.prnt(cmd_buffer, '')
                if cmd_send_to_buffer != 'new':
                    weechat.prnt(cmd_buffer, '%s%sCommand "%s" (rc %d), stderr:'
                                 % (weechat.prefix('error'), SHELL_PREFIX, data, int(rc)))
                for line in lines:
                    weechat.prnt(cmd_buffer, '%s%s' % (weechat.prefix('error'), line))
        cmd_hook_process = ''
        shell_set_title()
    return weechat.WEECHAT_RC_OK
def remove_group_options(data, buffer, argList):
    intRequiredArgs = 1
    split_args = argList.split(" ")
    num_of_args = len(split_args)
    
    if not argList:
        #print_help()
        w.prnt("", w.prefix("error") + "No arguments supplied.")
        return w.WEECHAT_RC_ERROR
        
    if num_of_args != intRequiredArgs:
        #print_help()
        w.prnt("", w.prefix("error") + "Wrong number of arguments. Supplied: " + str(num_of_args) + ", required: " + intRequiredArgs + ".")
        return w.WEECHAT_RC_ERROR
    
    GroupName = split_args[0]
    
    infolist = w.infolist_get("option", "", SETTINGS_PREFIX + GroupName + ".*")

    counter = 0
    
    if infolist:
        while w.infolist_next(infolist):
            name = w.infolist_string(infolist, "option_name")
            name = name.replace("python." + SCRIPT_NAME + ".", "")
            w.prnt("", "Removing option: " + name)
            w.config_unset_plugin(name)
            counter += 1

    w.infolist_free(infolist)
            
    if counter == 0:
        w.prnt("", w.prefix("error") + "No group name found called '" + GroupName + "'.")
    
    return w.WEECHAT_RC_OK
Exemple #13
0
def cron_at_cmd_cb(data, buffer, args):
    """ Command /at. """
    global crontab, cron_commands
    if args in ["", "list"]:
        cron_list()
        return weechat.WEECHAT_RC_OK
    if args == "debug":
        cron_list(debug=True)
        return weechat.WEECHAT_RC_OK
    argv = args.split(None, 3)
    if len(argv) >= 4:
        if argv[2] not in cron_commands:
            weechat.prnt("", "%scron: unknown keyword \"%s\""
                         % (weechat.prefix("error"), argv[2]))
            return weechat.WEECHAT_RC_ERROR
        hour_min = cron_at_time(argv[0])
        if hour_min == None:
            weechat.prnt("", "%scron: invalid time \"%s\""
                         % (weechat.prefix("error"), argv[0]))
            return weechat.WEECHAT_RC_OK
        cron_add(str(hour_min[1]), str(hour_min[0]), "*", "*", "*",
                 "1", argv[1], argv[2] + " " + argv[3])
        return weechat.WEECHAT_RC_OK
    weechat.prnt("", "%scron: invalid arguments" % weechat.prefix("error"))
    return weechat.WEECHAT_RC_OK
Exemple #14
0
def game_api(data, command, rc, stdout, stderr):
    try:
        jsonDict = json.loads(stdout.strip())
    except Exception as e:
        weechat.prnt(
            data, '%stwitch.py: error communicating with twitch api' %
            weechat.prefix('error'))
        if OPTIONS['debug']:
            weechat.prnt(
                data,
                '%stwitch.py: return code: %s' % (weechat.prefix('error'), rc))
            weechat.prnt(
                data,
                '%stwitch.py: stdout: %s' % (weechat.prefix('error'), stdout))
            weechat.prnt(
                data,
                '%stwitch.py: stderr: %s' % (weechat.prefix('error'), stderr))
            weechat.prnt(
                data,
                '%stwitch.py: exception: %s' % (weechat.prefix('error'), e))
        return weechat.WEECHAT_RC_OK

    if 'data' in jsonDict.keys():
        if not jsonDict['data']:
            return weechat.WEECHAT_RC_OK
        if len(jsonDict['data']) == 1:
            jsonDict['data'] = jsonDict['data'][0]
        old_title = weechat.buffer_get_string(data, "title")
        id = jsonDict['data']['id']
        name = makeutf8(jsonDict['data']['name'])
        new_title = old_title.replace('<{}>'.format(id), '<{}>'.format(name))
        weechat.buffer_set(data, "title", new_title)
        gameid_cache[id] = name
    return weechat.WEECHAT_RC_OK
Exemple #15
0
def theme_unpack():
    """Unpack theme file (themes.tar.bz2)."""
    filename = theme_config_get_tarball_filename()
    if not os.path.isfile(filename):
        weechat.prnt('',
                     '{0}{1}: file not found: {1}'
                     ''.format(weechat.prefix('error'),
                               SCRIPT_NAME,
                               filename))
        return False
    try:
        tar = tarfile.open(filename, 'r:bz2')
        tar.extractall(path=theme_config_get_dir())
        tar.close()
    except (tarfile.ReadError, tarfile.CompressionError, IOError):
        weechat.prnt('',
                     '{0}{1}: invalid file (format .tar.bz2 expected): {2}'
                     ''.format(weechat.prefix('error'),
                               SCRIPT_NAME,
                               filename))
        weechat.prnt('',
                     '{0}{1}: try /unset theme.themes.url'
                     ''.format(weechat.prefix('error'), SCRIPT_NAME))
        return False
    return True
Exemple #16
0
def purgelogs_cb(data, buffer, args):
  global basedir,purgelogs_commands,check_only, i
  basedir = get_path()
  if basedir == "":
    return w.WEECHAT_RC_OK
  argv = args.split(None, 2)
  """ argument "check" is set? """
  if len(argv) == 3:
    if argv[2] == "delete":
      check_only = False      # delete
      w.command("","/mute /plugin unload logger")
  else:
    check_only = True         # show only
    w.prnt("", "weechat-logs:")

  if len(argv) >= 1:
    if argv[0] not in purgelogs_commands:
      w.prnt("", "%s %s: unknown keyword \"%s\""
                         % (w.prefix("error"), SCRIPT_NAME, argv[0]))
    if is_number(argv[1]) is False:
      w.prnt("", "%s %s: wrong value \"%s\""
                         % (w.prefix("error"), SCRIPT_NAME, argv[1]))
    if argv[0] in ["", "age"]:
      i = 0
      dellog_by_date(argv[1])
    if argv[0] in ["", "size"]:
      i = 0
      dellog_by_size(argv[1])
  if check_only is False:
    w.command("","/mute /plugin load logger")
  return w.WEECHAT_RC_OK
Exemple #17
0
def opall(data, buffer, args):
    channel = weechat.buffer_get_string(buffer, 'localvar_channel')
    server = weechat.buffer_get_string(buffer, 'localvar_server')

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

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

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

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

    return weechat.WEECHAT_RC_OK
Exemple #18
0
def emojis_cb(data, bufferptr, args):
    args = args.split(" ")
    if not args:
        weechat.prnt("", "%s%s: invalid arguments (help on command: /help %s)" % (weechat.prefix("error"), SCRIPT_NAME, SCRIPT_NAME))
        return weechat.WEECHAT_RC_OK
    if args[0] == "reload":
        # reload emoji database from file
        reload_emojis()
        return weechat.WEECHAT_RC_OK
    if args[0] == "add" and len(args) == 3:
        # add new emoji to database
        name, emoji = args[1:3]
        colonized_name = ":{}:".format(name)
        if ":" in name:
            weechat.prnt("", "%s%s: name may not contain ':'" % (weechat.prefix("error"), SCRIPT_NAME))
            return weechat.WEECHAT_RC_OK
        if colonized_name in EMOJIS:
            weechat.prnt("", "%s%s: emoji with name \"%s\" already exists" % (weechat.prefix("error"), SCRIPT_NAME, name))
            return weechat.WEECHAT_RC_OK
        add_emoji(name, emoji)
        weechat.prnt("", "%s: emoji %s added: %s" % (SCRIPT_NAME, name, emoji))
        return weechat.WEECHAT_RC_OK
    if args[0] == "show" and len(args) == 2:
        name = args[1]
        colonized_name = ":{}:".format(name)
        if colonized_name not in EMOJIS:
            weechat.prnt("", "%s%s: emoji with name \"%s\" does not exist" % (weechat.prefix("error"), SCRIPT_NAME, name))
            return weechat.WEECHAT_RC_OK
        emoji = EMOJIS[colonized_name]
        weechat.prnt("", "%s: %s: %s" % (SCRIPT_NAME, name, emoji))
        return weechat.WEECHAT_RC_OK
    weechat.prnt("", "%s%s: invalid arguments (help on command: /help %s)" % (weechat.prefix("error"), SCRIPT_NAME, SCRIPT_NAME))
    return weechat.WEECHAT_RC_OK
Exemple #19
0
def send_sms(text, number):
    # Create SMS info structure
    smsinfo = {
        'Class': 1,
        'Unicode': True,
        'Entries': [{
            'ID': 'ConcatenatedAutoTextLong',
            'Buffer': text
        }]
    }

    # Encode messages
    encoded = gammu.EncodeSMS(smsinfo)

    # Send messages
    for message in encoded:
        message['SMSC'] = {'Location': 1}
        message['Number'] = number

        # Actually send the message
        try:
            sm.SendSMS(message)
        except gammu.ERR_GETTING_SMSC as e:
            weechat.prnt('', "%s%s" % (weechat.prefix("error"), e))
        except gammu.ERR_TIMEOUT as e:
            weechat.prnt('', "%s%s" % (weechat.prefix("error"), e))
def get_autojoin_list(server):
    ptr_config_autojoin = weechat.config_get("irc.server.%s.autojoin" % server)

    # option not found! server does not exist
    if not ptr_config_autojoin:
        weechat.prnt(buffer, "%s%s: server '%s' does not exist." % (weechat.prefix("error"), SCRIPT_NAME, server))
        return weechat.WEECHAT_RC_OK

    # get value from autojoin option
    channels = weechat.config_string(ptr_config_autojoin)
    if not channels:
        return 1, 1

    # check for keys
    if len(re.findall(r" ", channels)) == 0:
        list_of_channels = channels.split(",")
        list_of_keys = []
    elif len(re.findall(r" ", channels)) == 1:
        list_of_channels2, list_of_keys = channels.split(" ")
        list_of_channels = list_of_channels2.split(",")
    else:
        weechat.prnt("", "%s%s: irc.server.%s.autojoin not valid..." % (weechat.prefix("error"), SCRIPT_NAME, server))
        return 0, 0

    return list_of_channels, list_of_keys
Exemple #21
0
def cron_at_cmd_cb(data, buffer, args):
    """ Command /at. """
    global crontab, cron_commands
    if args in ["", "list"]:
        cron_list()
        return weechat.WEECHAT_RC_OK
    if args == "debug":
        cron_list(debug=True)
        return weechat.WEECHAT_RC_OK
    argv = args.split(None, 3)
    if len(argv) >= 4:
        if argv[2] not in cron_commands:
            weechat.prnt("", "%scron: unknown keyword \"%s\""
                         % (weechat.prefix("error"), argv[2]))
            return weechat.WEECHAT_RC_ERROR
        hour_min = cron_at_time(argv[0])
        if hour_min == None:
            weechat.prnt("", "%scron: invalid time \"%s\""
                         % (weechat.prefix("error"), argv[0]))
            return weechat.WEECHAT_RC_OK
        cron_add(str(hour_min[1]), str(hour_min[0]), "*", "*", "*",
                 "1", argv[1], argv[2] + " " + argv[3])
        return weechat.WEECHAT_RC_OK
    weechat.prnt("", "%scron: invalid arguments" % weechat.prefix("error"))
    return weechat.WEECHAT_RC_OK
Exemple #22
0
def send_prowl_notification(chan, message, isPrivate):

    # Error checking - we need a valid prowl API key to be set in order to send a Prowl notification
    prowl_api_key = weechat.config_get_plugin('prowl_api_key')
    if (prowl_api_key == ''):
        show_config_help()
        weechat.prnt('', '%sweeprowl - Could not send Prowl notification.' % weechat.prefix('error'))
        return

    # Build the Prowl API request
    params = urllib.urlencode({
        'apikey': prowl_api_key,
        'application': 'weechat',
        'event': 'IRC ' + 'Private Message' if isPrivate else 'Mention/Hilight',
        'description': 'Channel: ' + chan + '\n' + message
    })

    # Make the Prowl API request
    conn = httplib.HTTPSConnection('api.prowlapp.com')
    conn.request('POST', '/publicapi/add?' + params)

    # Error checking - make sure the Prowl API request was successful
    response = conn.getresponse()

    if (response.status != 200):
        weechat.prnt('', '%sweeprowl - Error: There was a problem communicating with the Prowl API!' % weechat.prefix('error'))
        weechat.prnt('', '%sweeprowl - Prowl API response information:' % weechat.prefix('error'))
        weechat.prnt('', '%sweeprowl -     Response status code = %s' % (weechat.prefix('error'), response.status))
        weechat.prnt('', '%sweeprowl -     Response reason phrase = %s' % (weechat.prefix('error'), response.reason))
        weechat.prnt('', '%sweeprowl - Could not send Prowl notification.' % weechat.prefix('error'))

    conn.close()
def add_server_channel_botnicks_nicklength(data, buffer, argList):
    intRequiredArgs = 5
    split_args = argList.split(" ")
    num_of_args = len(split_args)
    
    if not argList:
        #print_help()
        w.prnt("", w.prefix("error") + "No arguments supplied.")
        return w.WEECHAT_RC_ERROR
        
    if num_of_args != intRequiredArgs:
        #print_help()
        w.prnt("", w.prefix("error") + "Wrong number of arguments. Supplied: " + str(num_of_args) + ", required: " + str(intRequiredArgs) +".")
        return w.WEECHAT_RC_ERROR
    
    GroupName = split_args[0]
    server = split_args[1]
    channel = split_args[2]
    bot_nicks = split_args[3]
    nick_display_max_length = split_args[4]
    
    ####w.prnt("", "Group Name: " + GroupName)
    ####w.prnt("", "Server: " + server)
    ####w.prnt("", "Channel: " + channel)
    ####w.prnt("", "Bot_Nicks: " + bot_nicks)
    ####w.prnt("", "Nick_Display_Max_Length: " + nick_display_max_length)
    ####w.prnt("", "Option count: " + str(num_of_args))
    
    w.config_set_plugin(GroupName + ".server", server)
    w.config_set_plugin(GroupName + ".channel", channel)
    w.config_set_plugin(GroupName + ".bot_nicks", bot_nicks)
    w.config_set_plugin(GroupName + ".nick_display_max_length", nick_display_max_length)
    
    return w.WEECHAT_RC_OK
Exemple #24
0
 def connect(self):
     self.create_buffer()
     self.disconnect()
     weechat.prnt(self.buffer,
                  'Connecting to %s:%s'
                  % (self.get_option('host'), self.get_option('port')))
     try:
         hints = socket.getaddrinfo(self.get_option('host'),
                                    self.get_option('port'),
                                    socket.AF_UNSPEC, socket.SOCK_STREAM,
                                    0, socket.AI_PASSIVE)
     except socket.error as e:
         weechat.prnt(self.buffer,
                      '%s%s' % (weechat.prefix('error'), e.args[1]))
     else:
         for res in hints:
             af, socktype, proto, canonname, sa = res
             try:
                 self.socket = socket.socket(af, socktype, proto)
                 self.socket.connect(sa)
             except socket.error:
                 self.socket = None
                 continue
             break
     if self.socket is None:
         weechat.prnt(self.buffer,
                      '%sCould not connect' % (weechat.prefix('error'),))
     else:
         self.hook_fd = weechat.hook_fd(self.socket.fileno(), 1, 0, 0,
                                        'wee_ns_hook_fd_cb', '')
Exemple #25
0
def wg_parse_xml():
    """
    Parse XML scripts list and return dictionary with list, with key 'id'.
    Example of item return in dictionary :
      '119': { 'name'        : 'weeget',
               'version'     : '0.1',
               'url'         : 'http://www.weechat.org/files/scripts/weeget.py',
               'language'    : 'python',
               'license'     : 'GPL3',
               'md5sum'      : 'd500714fc19b0e10cc4e339e70739e4ad500714fc19b0e10cc4e339e70739e4a',
               'tags'        : 'scripts',
               'desc_en'     : 'Scripts manager.',
               'desc_fr'     : 'Gestionnaire de scripts.',
               'requirements': 'python 2.5',
               'min_weechat' : '0.3.0',
               'max_weechat' : '',
               'author'      : 'FlashCode',
               'mail'        : 'flashcode [at] flashtux [dot] org',
               'added'       : '2009-04-05 22:39:18',
               'updated'     : '0000-00-00 00:00:00' }
    """
    global wg_scripts, wg_action, wg_action_args
    wg_scripts = {}
    try:
        f = gzip.open(wg_config_get_cache_filename(), "rb")
        string = f.read()
        f.close()
    except:
        weechat.prnt("", "%s%s: unable to read xml file"
                     % (weechat.prefix("error"), SCRIPT_NAME))
    else:
        try:
            dom = xml.dom.minidom.parseString(string)
        except:
            weechat.prnt("",
                         "%s%s: unable to parse xml list of scripts"
                         % (weechat.prefix("error"), SCRIPT_NAME))
            # discard action
            wg_action = ""
            wg_action_args = ""
        else:
            for scriptNode in dom.getElementsByTagName("plugin"):
                id = scriptNode.getAttribute("id")
                script = {}
                for node in scriptNode.childNodes:
                    if node.nodeType == node.ELEMENT_NODE:
                        if node.firstChild != None:
                            nodename = node.nodeName
                            value = node.firstChild.data
                            if sys.version_info < (3,):
                                # python 2.x: convert unicode to str (in python 3.x, id and text are already strings)
                                nodename = nodename.encode("utf-8")
                                value = value.encode("utf-8")
                            script[nodename] = value
                if script["language"] in SCRIPT_EXTENSION:
                    script["full_name"] = script["name"] + "." + SCRIPT_EXTENSION[script["language"]]
                    if wg_check_version(script):
                        wg_scripts[id] = script
            wg_execute_action()
Exemple #26
0
def gweather_data_cb(data, command, rc, stdout, stderr):
    '''
    Callback for the data fetching process.
    '''
    global last_city, last_lang, last_run, last_format
    global gweather_hook_process, gweather_stdout, gweather_output

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

    if stdout:
        gweather_stdout += stdout

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

    # Update status variables for succesful run
    last_run = time()
    last_city = weechat.config_get_plugin('city')
    last_lang = weechat.config_get_plugin('language')
    last_format = weechat.config_get_plugin('format')
    gweather_hook_process = ''

    if not gweather_stdout:
        return weechat.WEECHAT_RC_OK

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

    gweather_stdout = ''

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

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

    # Feed the respose to parser and parsed data to formatting
    weather_data = parse_google_weather(xml_response)
    gweather_output = format_weather(weather_data)

    # Request bar item to update to the latest "gweather_output"
    weechat.bar_item_update('gweather')

    return weechat.WEECHAT_RC_OK
Exemple #27
0
def read_history(filename, ptr_buffer):
    global_history = 0

    # get buffer_autoset_option as a fallback. could happen that the localvar is not already set to buffer
    plugin = weechat.buffer_get_string(ptr_buffer, 'localvar_plugin')
    name = weechat.buffer_get_string(ptr_buffer, 'localvar_name')
    buffer_autoset_option = (
        'buffer_autoset.buffer.%s.%s.localvar_set_save_history' %
        (plugin, name))
    buffer_autoset_option = weechat.config_get(buffer_autoset_option)

    # global history does not use buffer pointers!
    if filename == filename_global_history:
        global_history = 1

    filename = get_filename_with_path(filename)

    # filename exists?
    if not os.path.isfile(filename):
        return

    # check for buffer history (0, global = 1)
    if global_history == 0 and OPTIONS['save_buffer'].lower() == 'off':
        # localvar_save_history exists for buffer?
        if not ptr_buffer and not buffer_autoset_option and not weechat.buffer_get_string(
                ptr_buffer, 'localvar_save_history'):
            return
    hdata = weechat.hdata_get('history')
    if not hdata:
        return

    try:
        f = open(filename, 'r')
        #        for line in f.xreadlines():    # old python 2.x
        for line in f:  # should also work with python 2.x
            #            line = line.decode('utf-8')
            line = str(line.strip())
            if ptr_buffer:
                # add to buffer history
                weechat.hdata_update(hdata, '', {
                    'buffer': ptr_buffer,
                    'text': line
                })
            else:
                # add to global history
                weechat.hdata_update(hdata, '', {'text': line})
        f.close()
    except:
        if global_history == 1:
            weechat.prnt(
                '', '%s%s: Error loading global history from "%s"' %
                (weechat.prefix('error'), SCRIPT_NAME, filename))
        else:
            name = weechat.buffer_get_string(ptr_buffer, 'localvar_name')
            weechat.prnt(
                '',
                '%s%s: Error loading buffer history for buffer "%s" from "%s"'
                % (weechat.prefix('error'), SCRIPT_NAME, name, filename))
        raise
def add_key_to_list(server, channel, new_key):
    autojoin_list = get_autojoin(server)

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

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

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

        sec_data = check_key_for_secure(argv_keys, channel_pos_in_list)

        # check weechat version and if secure option is on and secure data will be used for this key?
        if int(version) >= 0x00040200 and OPTIONS['secure'].lower(
        ) == 'on' and sec_data == 1:
            sec_data_name = argv_keys[channel_pos_in_list][11:-1]
            weechat.command(
                '',
                '%s/secure set %s %s' % (use_mute(), sec_data_name, new_key))
        else:
            if sec_data == 1:
                weechat.prnt(
                    '',
                    '%s%s: key for channel "%s.%s" not changed! option "plugins.var.python.%s.secure" is off and you are using secured data for key.'
                    % (weechat.prefix('error'), SCRIPT_NAME, server, channel,
                       SCRIPT_NAME))
                return weechat.WEECHAT_RC_OK
            argv_keys[channel_pos_in_list] = new_key
            if not autojoin_list:  # autojoin option is empty!
                new_joined_option = '%s %s' % (channel, new_key)
            else:
                new_joined_option = '%s %s' % (','.join(argv_channels),
                                               ','.join(argv_keys))
            save_autojoin_option(server, new_joined_option)
    return weechat.WEECHAT_RC_OK
def my_process_cb(data, command, rc, out, err):

    if rc == weechat.WEECHAT_HOOK_PROCESS_ERROR:
        weechat.prnt("", "Error with command '%s'" %
                command.replace(script_options["oauth_token"],"").replace(script_options["oauth_secret"],""))
        return weechat.WEECHAT_RC_OK

    data = ast.literal_eval(data)
    buffer = data[0]
    end_mes = data[1]

    if out != "":
        if out[0] != "[" and out[0] != "{":
            #If message is just a string print it
            weechat.prnt(buffer, "%s%s" % (weechat.prefix("network"), out))
            return weechat.WEECHAT_RC_OK
        process_output = ast.literal_eval(out)
        #List message
        if len(end_mes) >= 1 and end_mes[0] == "L":
            if isinstance(process_output[-1], int):
                t_id = dict_tweet(str(process_output[-1])) + "\t"
                process_output = process_output[:-1]
                more = " ..."
            else:
                t_id = weechat.prefix("network")
                more = ""

            for nick in process_output:
                if end_mes == "LYFollowing":
                    add_to_nicklist(buffer,nick)
                elif script_options['tweet_nicks']:
                    add_to_nicklist(buffer,nick,tweet_nicks_group[buffer])
            weechat.prnt_date_tags(buffer, 0, "no_highlight",
                    "%s%s: %s%s" % (t_id, end_mes[1:], process_output, more))
            return weechat.WEECHAT_RC_OK

        if end_mes == "About":
            weechat.prnt(buffer, "Nick: %s | Name: %s | Protected: %s" % (process_output['screen_name'],
                                                                        process_output['name'],
                                                                        process_output['protected']))
            weechat.prnt(buffer, "Description: %s" % process_output['description'])
            weechat.prnt(buffer, "Location: %s | Time zone: %s" % (process_output['location'], process_output['time_zone']))
            weechat.prnt(buffer, "Created at: %s | Verified user: %s" % (process_output['created_at'], process_output['verified']))
            weechat.prnt(buffer, "Following: %s | Followers: %s | Favourites: %s | Tweets: %s" % (process_output['friends_count'],
                                                                                               process_output['followers_count'],
                                                                                               process_output['favourites_count'],
                                                                                               process_output['statuses_count']))
            weechat.prnt(buffer, "Are you currently following this person: %s" % (process_output['following']))
            return weechat.WEECHAT_RC_OK

        print_tweet_data(buffer,process_output,end_mes)

        if end_mes != "id" and end_mes != "":
            weechat.prnt(buffer, "%s%s" % (weechat.prefix("network"), end_mes))
    if err != "":
        weechat.prnt("", "stderr: %s" % err)
    return weechat.WEECHAT_RC_OK
Exemple #30
0
def gweather_data_cb(data, command, rc, stdout, stderr):
    '''
    Callback for the data fetching process.
    '''
    global last_city, last_lang, last_run, last_format
    global gweather_hook_process, gweather_stdout, gweather_output

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

    if stdout:
        gweather_stdout += stdout

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

    # Update status variables for succesful run
    last_run = time()
    last_city = weechat.config_get_plugin('city')
    last_lang = weechat.config_get_plugin('language')
    last_format = weechat.config_get_plugin('format')
    gweather_hook_process = ''

    if not gweather_stdout:
        return weechat.WEECHAT_RC_OK

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

    gweather_stdout = ''

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

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

    # Feed the respose to parser and parsed data to formatting
    weather_data = parse_google_weather(xml_response)
    gweather_output = format_weather(weather_data)

    # Request bar item to update to the latest "gweather_output" 
    weechat.bar_item_update('gweather')

    return weechat.WEECHAT_RC_OK
Exemple #31
0
def cron_cmd_cb(data, buffer, args):
    """ Command /cron. """
    global crontab, cron_commands
    if args in ["", "list"]:
        cron_list()
        return weechat.WEECHAT_RC_OK
    if args == "debug":
        cron_list(debug=True)
        return weechat.WEECHAT_RC_OK
    argv = args.split(None, 9)
    if len(argv) > 0:
        if argv[0] == "add":
            if len(argv) >= 10:
                if argv[8] not in cron_commands:
                    weechat.prnt(
                        "", "%scron: unknown keyword \"%s\"" %
                        (weechat.prefix("error"), argv[8]))
                    return weechat.WEECHAT_RC_ERROR
                cron_add(argv[1], argv[2], argv[3], argv[4], argv[5], argv[6],
                         argv[7], argv[8] + " " + argv[9])
                return weechat.WEECHAT_RC_OK
        elif argv[0] in ["del", "exec"]:
            if argv[0] == "del" and argv[1] == "-all":
                crontab = []
                weechat.prnt("", "cron: all jobs deleted")
                if weechat.config_get_plugin("auto_save") == "on":
                    cron_save()
                return weechat.WEECHAT_RC_OK
            try:
                number = int(argv[1])
                if number < 1 or number > len(crontab):
                    weechat.prnt(
                        "", "%scron: job number not found" %
                        weechat.prefix("error"))
                    return weechat.WEECHAT_RC_OK
                if argv[0] == "del":
                    job = crontab.pop(number - 1)
                    weechat.prnt("",
                                 "cron: job #%d deleted (%s)" % (number, job))
                    if weechat.config_get_plugin("auto_save") == "on":
                        cron_save()
                elif argv[0] == "exec":
                    job = crontab[number - 1]
                    job.exec_command(userExec=True)
            except:
                weechat.prnt(
                    "",
                    "%scron: job number not found" % weechat.prefix("error"))
            return weechat.WEECHAT_RC_OK
        elif argv[0] == "reload":
            cron_load(force_message=True)
            return weechat.WEECHAT_RC_OK
        elif argv[0] == "save":
            cron_save(force_message=True)
            return weechat.WEECHAT_RC_OK
    weechat.prnt("", "%scron: invalid arguments" % weechat.prefix("error"))
    return weechat.WEECHAT_RC_OK
Exemple #32
0
def owl_cmd(a, buff_ptr, c):
    # parse args
    buff_name = weechat.buffer_get_string(buff_ptr, 'name')
    buff_server = weechat.buffer_get_string(buff_ptr, 'localvar_server') + '.'
    buff_channel = weechat.buffer_get_string(buff_ptr, 'localvar_channel')
    args = c.split()
    buff_names = []
    if len(args) > 1:
        for name in args[1:]:
            m = re.match(r'^(?P<server>(\S+\.)?)(?P<channel>(#\S+)?)$', name)
            tmp_server = buff_server
            tmp_channel = buff_channel
            if m:
                if len(m.groupdict()['server']):
                    tmp_server = m.groupdict()['server']
                if len(m.groupdict()['channel']):
                    tmp_channel = m.groupdict()['channel']
                tmp_buff_name = '{}{}'.format(tmp_server, tmp_channel)
            buff_names.append(tmp_buff_name)
    else:
        buff_names.append(buff_name)
    # do stuff
    if DEBUG:
        weechat.prnt('', 'cmd: {}-{}-{}'.format(a, buff_name, c))
        weechat.prnt('', '  server: {}'.format(buff_server))
        weechat.prnt('', '  channel: {}'.format(buff_channel))
        weechat.prnt('', '  subcommand: {}'.format(args[0]))
        weechat.prnt('', '  args: {}'.format(buff_names))
    if args[0] == 'list':
        nothing_found = True
        for b in buff_names:
            if b in owl_state['buff_alerts']:
                nothing_found = False
                weechat.prnt(
                    buff_ptr, '{}owl found these dogs in {}:'.format(
                        weechat.prefix('action'), b))
                for rule in owl_state['buff_alerts'][b]:
                    nicks = []
                    for i in sorted(owl_state['buff_alerts'][b][rule]):
                        nicks.append(i.split('!')[0])
                    weechat.prnt(
                        buff_ptr,
                        '{}rule {}:  {}'.format(weechat.prefix('action'), rule,
                                                ' '.join(nicks)))
        if nothing_found:
            weechat.prnt(
                buff_ptr, '{}{}'.format(
                    weechat.prefix('action'),
                    'owl found no dogs in:  {}'.format(' '.join(buff_names))))
    elif args[0] == 'enable':
        pass
    elif args[0] == 'disable':
        pass
    else:
        weechat.prnt('', 'owl: unknown argument "{}"'.format(args[0]))
    return weechat.WEECHAT_RC_OK
def notify_cb(data, command, return_code, out, err):
  if return_code == weechat.WEECHAT_HOOK_PROCESS_ERROR:
    weechat.prnt("", "%s pushbullet.py got err command %s" % (weechat.prefix("error"), command))
    return weechat.WEECHAT_RC_OK

  # weechat.prnt("", "command:%s return_code:%s out:%s err:%s" % (command, return_code, out, err))
  j = json.loads(out)
  if "error" in j:
    weechat.prnt("", "%s weechat-pushbullet.py %s %s" % (weechat.prefix("error"), j["error"]["type"], j["error"]["message"]))

  return weechat.WEECHAT_RC_OK
Exemple #34
0
def add_key_to_list(server, channel, new_key):
    autojoin_list = get_autojoin(server)
    if not autojoin_list:
        return weechat.WEECHAT_RC_OK

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

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

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

        sec_data = check_key_for_secure(argv_keys, channel_pos_in_list)

        # check weechat version and if secure option is on and secure data will be used for this key?
        if int(version) >= 0x00040200 and OPTIONS["secure"].lower() == "on" and sec_data == 1:
            sec_data_name = argv_keys[channel_pos_in_list][11:-1]
            weechat.command("", "%s/secure set %s %s" % (use_mute(), sec_data_name, new_key))
        else:
            if sec_data == 1:
                weechat.prnt(
                    "",
                    '%s%s: key for channel "%s.%s" not changed! option "plugins.var.python.%s.secure" is off and you are using secured data for key.'
                    % (weechat.prefix("error"), SCRIPT_NAME, server, channel, SCRIPT_NAME),
                )
                return weechat.WEECHAT_RC_OK
            argv_keys[channel_pos_in_list] = new_key
            new_joined_option = "%s %s" % (",".join(argv_channels), ",".join(argv_keys))
            save_autojoin_option(server, new_joined_option)
    return weechat.WEECHAT_RC_OK
Exemple #35
0
def weather_data_cb(data, command, rc, stdout, stderr):
    """
    Callback for the data fetching process.
    """
    global last_city, last_run
    global gweather_hook_process, gweather_stdout, gweather_output

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

    if stdout:
        gweather_stdout += stdout

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

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

    if not gweather_stdout:
        return weechat.WEECHAT_RC_OK

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

    gweather_stdout = ""

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

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

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

    return weechat.WEECHAT_RC_OK
Exemple #36
0
def send_prowl_notification_callback(data, command, rc, stdout, stderr):

    # Show an error if the Prowl API request failed
    if (rc > 0):
        weechat.prnt('', '%sweeprowl - Error: There was a problem communicating with the Prowl API!' % weechat.prefix('error'))
        weechat.prnt('', '%sweeprowl - Prowl API response information:' % weechat.prefix('error'))
        weechat.prnt('', '%sweeprowl -     Response code = %s' % (weechat.prefix('error'), rc))
        weechat.prnt('', '%sweeprowl -     STDOUT = %s' % (weechat.prefix('error'), stdout))
        weechat.prnt('', '%sweeprowl -     STDERR = %s' % (weechat.prefix('error'), stderr))
        show_notification_error()

    return weechat.WEECHAT_RC_OK
Exemple #37
0
def read_history(filename, ptr_buffer):
    global_history = 0

    # global history does not use buffer pointers!
    if filename == filename_global_history:
        global_history = 1

    filename = get_filename_with_path(filename)

    # filename exists?
    if not os.path.isfile(filename):
        return

    # check for global history
    if global_history == 0:
        # localvar_save_history exists for buffer?
        if not ptr_buffer or not weechat.buffer_get_string(
                ptr_buffer, 'localvar_save_history'):
            return

    hdata = weechat.hdata_get('history')
    if not hdata:
        return

    try:
        f = open(filename, 'r')
        #        for line in f.xreadlines():    # old python 2.x
        for line in f:  # should also work with python 2.x
            #            line = line.decode('utf-8')
            line = str(line.strip())
            if ptr_buffer:
                # add to buffer history
                weechat.hdata_update(hdata, '', {
                    'buffer': ptr_buffer,
                    'text': line
                })
            else:
                # add to global history
                weechat.hdata_update(hdata, '', {'text': line})
        f.close()
    except:
        if global_history == 1:
            weechat.prnt(
                '', '%s%s: Error loading global history from "%s"' %
                (weechat.prefix('error'), SCRIPT_NAME, filename))
        else:
            name = weechat.buffer_get_string(ptr_buffer, 'localvar_name')
            weechat.prnt(
                '',
                '%s%s: Error loading buffer history for buffer "%s" from "%s"'
                % (weechat.prefix('error'), SCRIPT_NAME, name, filename))
        raise
Exemple #38
0
def cron_cmd_cb(data, buffer, args):
    """ Command /cron. """
    global crontab, cron_commands
    if args in ["", "list"]:
        cron_list()
        return weechat.WEECHAT_RC_OK
    if args == "debug":
        cron_list(debug=True)
        return weechat.WEECHAT_RC_OK
    argv = args.split(None, 9)
    if len(argv) > 0:
        if argv[0] == "add":
            if len(argv) >= 10:
                if argv[8] not in cron_commands:
                    weechat.prnt("", "%scron: unknown keyword \"%s\""
                                 % (weechat.prefix("error"), argv[8]))
                    return weechat.WEECHAT_RC_ERROR
                cron_add(argv[1], argv[2], argv[3], argv[4], argv[5],
                         argv[6], argv[7], argv[8] + " " + argv[9])
                return weechat.WEECHAT_RC_OK
        elif argv[0] in ["del", "exec"]:
            if argv[0] == "del" and argv[1] == "-all":
                crontab = []
                weechat.prnt("", "cron: all jobs deleted")
                if weechat.config_get_plugin("auto_save") == "on":
                    cron_save()
                return weechat.WEECHAT_RC_OK
            try:
                number = int(argv[1])
                if number < 1 or number > len(crontab):
                    weechat.prnt("", "%scron: job number not found" % weechat.prefix("error"))
                    return weechat.WEECHAT_RC_OK
                if argv[0] == "del":
                    job = crontab.pop(number - 1)
                    weechat.prnt("", "cron: job #%d deleted (%s)" % (number, job))
                    if weechat.config_get_plugin("auto_save") == "on":
                        cron_save()
                elif argv[0] == "exec":
                    job = crontab[number - 1]
                    job.exec_command(userExec=True)
            except:
                weechat.prnt("", "%scron: job number not found" % weechat.prefix("error"))
            return weechat.WEECHAT_RC_OK
        elif argv[0] == "reload":
            cron_load(force_message=True)
            return weechat.WEECHAT_RC_OK
        elif argv[0] == "save":
            cron_save(force_message=True)
            return weechat.WEECHAT_RC_OK
    weechat.prnt("", "%scron: invalid arguments" % weechat.prefix("error"))
    return weechat.WEECHAT_RC_OK
Exemple #39
0
def unsubscribe (username):
	if len(username) == 0:
		return weechat.WEECHAT_RC_ERROR

	response = statusnet_handler.handle_request(statusnet_handler.build_request('friendships', 'destroy', username))

	if response == None:
		pass
	elif response == False:
		weechat.prnt(weechat.current_buffer(), ('%sYou aren\'t suscribed to %s' % (weechat.prefix('error'), username)))
	else:
		weechat.prnt(weechat.current_buffer(), ('%sUnsuscribed from %s\'s updates' % (weechat.prefix('quit'), username)))
	
	return weechat.WEECHAT_RC_OK
Exemple #40
0
def subscribe (username):
	if len(username) == 0:
		return weechat.WEECHAT_RC_ERROR

	response = statusnet_handler.handle_request(statusnet_handler.build_request('friendships', 'create', username))

	if response == None:
		pass
	elif response == False:
		weechat.prnt(weechat.current_buffer(), ('%sYou\'re already suscribed to %s' % (weechat.prefix('error'), username)))
	else:
		weechat.prnt(weechat.current_buffer(), ('%sSuscribed to %s updates' % (weechat.prefix('join'), username)))

	return weechat.WEECHAT_RC_OK
Exemple #41
0
def send_prowl_notification(chan, message, isPrivate):

    # Make sure a Prowl API key has been configured
    prowl_api_key = weechat.config_get_plugin('prowl_api_key')
    if (prowl_api_key == ''):
        show_config_help()
        show_notification_error()
        return

    # Make sure a valid Prowl priority has been configured
    prowl_priority = weechat.config_get_plugin('prowl_priority')
    valid_prowl_priority = True
    try:
        if (int(prowl_priority) > 2 or int(prowl_priority) < -2):
            valid_prowl_priority = False
    except ValueError:
        valid_prowl_priority = False
    if (not valid_prowl_priority):
        weechat.prnt(
            '',
            '%sweeprowl - Current prowl_priority setting "%s" is invalid.' %
            (weechat.prefix('error'), prowl_priority))
        weechat.prnt(
            '',
            '%sweeprowl - Please set prowl_priority to an integer value ranging from [-2, 2].'
            % weechat.prefix('error'))
        show_notification_error()
        return

    # Build the Prowl API request parameters
    params = urllib.parse.urlencode({
        'apikey':
        prowl_api_key,
        'application':
        'weechat',
        'event':
        'IRC ' + 'Private Message' if isPrivate else 'Mention/Hilight',
        'description':
        'Channel: ' + chan + '\n' + message,
        'priority':
        prowl_priority
    })

    # Build the complete Prowl API request URL
    prowl_api_url = 'https://api.prowlapp.com/publicapi/add?' + params

    # Make the Prowl API request
    weechat.hook_process_hashtable('url:' + prowl_api_url, {'post': '1'},
                                   30 * 1000,
                                   'send_prowl_notification_callback', '')
Exemple #42
0
def purgelogs_cb(data, buffer, args):
    global basedir, purgelogs_commands, check_only, i
    basedir = get_path()
    if basedir == "":
        return w.WEECHAT_RC_OK
    argv = args.split(None, 2)
    """ argument "check" is set? """
    if len(argv) == 0:  # no arguments given
        w.command("", "/help purgelogs")  # print help page
        return w.WEECHAT_RC_OK

    if len(argv) == 1:
        if argv[0] not in purgelogs_commands:
            w.prnt(
                "", "%s%s: unknown keyword \"%s\"" %
                (w.prefix("error"), SCRIPT_NAME, argv[0]))
            return w.WEECHAT_RC_OK
    if len(argv) < 2:
        w.prnt("", "%s%s: no value given" % (w.prefix("error"), SCRIPT_NAME))
        return w.WEECHAT_RC_OK
    if is_number(argv[1]) is False:
        w.prnt(
            "", "%s%s: wrong value \"%s\"" %
            (w.prefix("error"), SCRIPT_NAME, argv[1]))
        return w.WEECHAT_RC_OK

    if len(argv) == 3:
        if argv[2] == "delete":
            check_only = False  # delete
            w.command("", "/mute /plugin unload logger")
    else:
        w.prnt("", "weechat-logs:")
        check_only = True  # show only

    if argv[0] in ["", "age_ls"]:
        i = 0
        dellog_by_date_less(argv[1])
    if argv[0] in ["", "size_ls"]:
        i = 0
        dellog_by_size_less(argv[1])
    if argv[0] in ["", "age"]:
        i = 0
        dellog_by_date(argv[1])
    if argv[0] in ["", "size"]:
        i = 0
        dellog_by_size(argv[1])
    if check_only is False:
        w.command("", "/mute /plugin load logger")
    return w.WEECHAT_RC_OK
Exemple #43
0
def install_hooks():
    global HOOK,OPTIONS

    if HOOK['timer'] != '' or HOOK['redirect'] != '':                                     # should not happen, but...
        return

    if not OPTIONS['delay'] or not OPTIONS['timeout']:
        return
    HOOK['timer'] = weechat.hook_timer(int(OPTIONS['delay']) * 1000, 0, 0, 'checknicks', '')
    HOOK['redirect'] = weechat.hook_hsignal('irc_redirection_%s_ison' % SCRIPT_NAME, 'redirect_isonhandler', '' )

    if HOOK['timer'] == 0:
        weechat.prnt('',"%s: can't enable %s, hook_timer() failed" % (weechat.prefix('error'), SCRIPT_NAME))
    if HOOK['redirect'] == 0:
        weechat.prnt('',"%s: can't enable %s, hook_signal() failed" % (weechat.prefix('error'), SCRIPT_NAME))
Exemple #44
0
def unblock (username):
    '''Unblocks users'''
    if len(username) == 0:
        return weechat.WEECHAT_RC_ERROR

    response = statusnet_handler.handle_request(statusnet_handler.build_request('blocks', 'destroy', username))

    if response == None:
        pass
    elif response == False:
        weechat.prnt(weechat.current_buffer(), ('%sCan\'t unblock %s' % (weechat.prefix('error'), username)))
    else:
        weechat.prnt(weechat.current_buffer(), ('%sUnblocked %s' % (weechat.prefix('network'), username)))
        
    return weechat.WEECHAT_RC_OK
Exemple #45
0
def install_hooks():
    global HOOK, OPTIONS

    if HOOK["timer"] != "" or HOOK["redirect"] != "":  # should not happen, but...
        return

    if not OPTIONS["delay"] or not OPTIONS["timeout"]:
        return
    HOOK["timer"] = weechat.hook_timer(int(OPTIONS["delay"]) * 1000, 0, 0, "check_nicks", "")
    HOOK["redirect"] = weechat.hook_hsignal("irc_redirection_%s_ison" % SCRIPT_NAME, "redirect_isonhandler", "")

    if HOOK["timer"] == 0:
        weechat.prnt("", "%s: can't enable %s, hook_timer() failed" % (weechat.prefix("error"), SCRIPT_NAME))
    if HOOK["redirect"] == 0:
        weechat.prnt("", "%s: can't enable %s, hook_signal() failed" % (weechat.prefix("error"), SCRIPT_NAME))
Exemple #46
0
def purgelogs_cb(data, buffer, args):
  global basedir,purgelogs_commands,check_only, i
  basedir = get_path()
  if basedir == "":
    return w.WEECHAT_RC_OK
  argv = args.split(None, 2)
  """ argument "check" is set? """
  if len(argv) == 0:                    # no arguments given
    w.command("","/help purgelogs")     # print help page
    return w.WEECHAT_RC_OK

  if len(argv) == 1:
    if argv[0] not in purgelogs_commands:
      w.prnt("", "%s%s: unknown keyword \"%s\""
                         % (w.prefix("error"), SCRIPT_NAME, argv[0]))
      return w.WEECHAT_RC_OK
  if len(argv) < 2:
    w.prnt("", "%s%s: no value given"
                         % (w.prefix("error"), SCRIPT_NAME))
    return w.WEECHAT_RC_OK
  if is_number(argv[1]) is False:
    w.prnt("", "%s%s: wrong value \"%s\""
                         % (w.prefix("error"), SCRIPT_NAME, argv[1]))
    return w.WEECHAT_RC_OK

  if len(argv) == 3:
    if argv[2] == "delete":
      check_only = False      # delete
      w.command("","/mute /plugin unload logger")
  else:
    w.prnt("", "weechat-logs:")
    check_only = True         # show only

  if argv[0] in ["", "age_ls"]:
    i = 0
    getdirs(basedir,int(argv[1]),"ls_age")
  if argv[0] in ["", "size_ls"]:
    i = 0
    getdirs(basedir,int(argv[1]),"ls_size")
  if argv[0] in ["", "age"]:
    i = 0
    getdirs(basedir,int(argv[1]),"by_age")
  if argv[0] in ["", "size"]:
    i = 0
    getdirs(basedir,int(argv[1]),"by_size")
  if check_only is False:
    w.command("","/mute /plugin load logger")
  return w.WEECHAT_RC_OK
Exemple #47
0
def cron_str2set(str, min_value, max_value):
    """ Convert string with range to a set. """
    if str == "*":
        return alwaysMatch
    ret = set([])
    try:
        items = str.split(",")
        for item in items:
            values = item
            skip = 1
            pos = values.find("/")
            if pos > 0:
                try:
                    skip = int(values[pos+1:])
                except:
                    skip = 1
                values = values[0:pos]
            pos = values.find("-")
            if pos > 0:
                value1 = cron_str2int(values[0:pos])
                value2 = cron_str2int(values[pos+1:])
            else:
                if values == "*":
                    value1 = min_value
                    value2 = max_value
                else:
                    value1 = cron_str2int(values)
                    value2 = cron_str2int(values)
            ret = set.union(ret, set(range(value1, value2 + 1, skip)))
    except:
        weechat.prnt("", "%scron: error with time string \"%s\""
                     % (weechat.prefix("error"), str))
        return alwaysMatch
    return ret
Exemple #48
0
def write_history(filename):
    global history_list

    filename = get_filename_with_path(filename)

    if OPTIONS['number'] != '' and OPTIONS['number'].isdigit():
        if int(OPTIONS['number']) < 0:
            save_from_position = len(history_list) - abs(int(OPTIONS['number']))
            if save_from_position == len(history_list) or save_from_position < 0:
                save_from_position = 0
        elif int(OPTIONS['number']) > 0:
            save_to_position = int(OPTIONS['number'])
            if save_to_position > len(history_list):
                save_to_position = len(history_list)
        else:
            save_from_position = 0
    try:
        f = open(filename, 'w')

        if int(OPTIONS['number']) <= 0:
            i = save_from_position
            # for i in range(len(a)):
            while i < len(history_list):
                f.write('%s\n' % history_list[i])
                i = i + 1
        if int(OPTIONS['number']) > 0:
            i = 0
            while i < save_to_position:
                f.write('%s\n' % history_list[i])
                i = i + 1
        f.close()

    except:
        weechat.prnt('','%s%s: Error writing history to "%s"' % (weechat.prefix('error'),SCRIPT_NAME,filename))
        raise
Exemple #49
0
def wg_execute_action():
    """ Execute action. """
    global wg_action, wg_action_args, wg_loaded_scripts
    if wg_action != "":
        wg_get_loaded_scripts()
        if wg_action == "list":
            wg_list_scripts(wg_action_args)
        elif wg_action == "listinstalled":
            wg_list_scripts(wg_action_args, installed=True)
        elif wg_action == "show":
            wg_show_script(wg_action_args)
        elif wg_action == "install":
            wg_install_scripts(wg_action_args)
        elif wg_action == "check":
            wg_check_scripts()
        elif wg_action == "upgrade":
            wg_upgrade_scripts()
        elif wg_action == "remove":
            wg_remove_scripts(wg_action_args)
        else:
            weechat.prnt("", "%s%s: unknown action \"%s\""
                         % (weechat.prefix("error"), SCRIPT_NAME, wg_action))

    # reset action
    wg_action = ""
    wg_action_args = ""
    wg_loaded_scripts = {}
Exemple #50
0
def urlserver_server_start():
    """Start mini HTTP server."""
    global urlserver, urlserver_settings
    if urlserver['socket']:
        weechat.prnt('', 'URL server already running')
        return
    port = 0
    try:
        port = int(urlserver_settings['http_port'])
    except:
        port = 0
    urlserver['socket'] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    urlserver['socket'].setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        urlserver['socket'].bind((urlserver_settings['http_hostname']
                                  or socket.getfqdn(), port))
    except Exception as e:
        weechat.prnt('', '%sBind error: %s' % (weechat.prefix('error'), e))
        urlserver['socket'] = None
        urlserver_server_status()
        return
    urlserver['socket'].listen(5)
    urlserver['hook_fd'] = weechat.hook_fd(urlserver['socket'].fileno(), 1, 0,
                                           0, 'urlserver_server_fd_cb', '')
    urlserver_server_status()
Exemple #51
0
def twitter_stream_cb(buffer,fd):
    #accept connection
    server = sock_fd_dict[sock_fd_dict[fd]]
    conn, addr = server.accept()
    error = False
    tweet = ""
    data = True
    while data:
        try:
            data = conn.recv(1024).decode('utf-8')
            tweet += data
        except:
            break

    try:
        tweet = ast.literal_eval(tweet)
    except:
        weechat.prnt(buffer, "Error resv stream message")
        return weechat.WEECHAT_RC_OK
    #Is this a text message (normal tweet)?
    if isinstance(tweet,list):
        if buffer == twit_buf:
            #Update last recv id
            print_tweet_data(buffer,tweet,"id")
        else:
            print_tweet_data(buffer,tweet,"")
    elif False:
        #https://dev.twitter.com/docs/streaming-apis/messages
        #TODO handle stream events
        weechat.prnt(buffer, "%s%s" % (weechat.prefix("network"),
        "recv stream data: " + str(tweet)))

    conn.close()
    return weechat.WEECHAT_RC_OK
Exemple #52
0
def maze_cmd_cb(data: str, buffer: str, args: str) -> int:
    """The /maze command."""
    global maze
    width: int
    height: int
    if args in ("s", "solve"):
        if maze:
            maze.solve()
    elif args in ("i", "isolve"):
        if maze:
            maze.solve(interactive=True)
    elif args in ("r", "reset"):
        if maze:
            maze.reset()
    else:
        if args == "+":
            width, height = maze_get_other_size(30)
        elif args == "-":
            width, height = maze_get_other_size(-30)
        elif args in ("d", "default"):
            width, height = maze_get_size(args)
        elif not args or args in ("n", "new"):
            width, height = maze_get_size()
        else:
            error = weechat.prefix("error")
            weechat.prnt("", f"{error}maze error: unknown option \"{args}\"")
            return weechat.WEECHAT_RC_OK
        maze_new(width, height)
    return weechat.WEECHAT_RC_OK
Exemple #53
0
def cron_str2set(str, min_value, max_value):
    """ Convert string with range to a set. """
    if str == "*":
        return alwaysMatch
    ret = set([])
    try:
        items = str.split(",")
        for item in items:
            values = item
            skip = 1
            pos = values.find("/")
            if pos > 0:
                try:
                    skip = int(values[pos+1:])
                except:
                    skip = 1
                values = values[0:pos]
            pos = values.find("-")
            if pos > 0:
                value1 = cron_str2int(values[0:pos])
                value2 = cron_str2int(values[pos+1:])
            else:
                if values == "*":
                    value1 = min_value
                    value2 = max_value
                else:
                    value1 = cron_str2int(values)
                    value2 = cron_str2int(values)
            ret = set.union(ret, set(range(value1, value2 + 1, skip)))
    except:
        weechat.prnt("", "%scron: error with time string \"%s\""
                     % (weechat.prefix("error"), str))
        return alwaysMatch
    return ret
Exemple #54
0
def wg_execute_action():
    """ Execute action. """
    global wg_action, wg_action_args, wg_loaded_scripts
    if wg_action != "":
        wg_get_loaded_scripts()
        if wg_action == "list":
            wg_list_scripts(wg_action_args)
        elif wg_action == "listinstalled":
            wg_list_scripts(wg_action_args, installed=True)
        elif wg_action == "show":
            wg_show_script(wg_action_args)
        elif wg_action == "install":
            wg_install_scripts(wg_action_args)
        elif wg_action == "check":
            wg_check_scripts()
        elif wg_action == "upgrade":
            wg_upgrade_scripts()
        elif wg_action == "remove":
            wg_remove_scripts(wg_action_args)
        else:
            weechat.prnt(
                "", "%s%s: unknown action \"%s\"" %
                (weechat.prefix("error"), SCRIPT_NAME, wg_action))

    # reset action
    wg_action = ""
    wg_action_args = ""
    wg_loaded_scripts = {}
Exemple #55
0
def updates(username, quantity):
    '''Shows user updates'''
    if len(username) == 0 or quantity > 20:
        return weechat.WEECHAT_RC_ERROR

    if quantity < 1:
        quantity = 1

    response = statusnet_handler.handle_request(
        statusnet_handler.build_request('statuses', 'user_timeline', username))

    if response == None:
        pass
    elif response == False:
        weechat.prnt(weechat.current_buffer(),
                     ('%sCan\'t retrieve %s\'s updates' %
                      (weechat.prefix('error'), username)))
    else:
        statuses = json.load(response)[:quantity]
        while quantity > 0:
            quantity -= 1
            weechat.prnt_date_tags(
                weechat.buffer_search('',
                                      weechat.config_get_plugin('channel')), 0,
                'irc_privmsg', 'update\t%s: %s' %
                (username, statuses[quantity]['text'].encode('utf-8')))

    return weechat.WEECHAT_RC_OK
Exemple #56
0
 def _ns_parse_user_cmd_who(self, arglist):
     r = re.compile(r"""
     who[ ]
     ([0-9]+)[ ]             # fd
     ([_a-z0-9-]+)[ ]        # login
     ([0-9.]+)[ ]            # ip
     ([0-9]+)[ ]             # connection_time
     ([0-9]+)[ ]             # lastseen_time
     ([0-9]+)[ ]             # user_trust
     ([0-9]+)[ ]             # client_trust
     ([^ ]+)[ ]              # machtype
     ([^ ]+)[ ]              # location
     ([^ ]+)[ ]              # group
     ([^ :]+)(:([^ ]+)?)?[ ] # state:state_time
     ([^ ]+)                 # data
     """, re.VERBOSE)
     match = re.match(r, ' '.join(arglist[3:]))
     if match is not None:
         groups = match.groups()
         user = WeeNSUser(fd=groups[0], login=groups[1], ip=groups[2],
                          connection_time=groups[3],
                          lastseen_time=groups[4],
                          user_trust=groups[5], client_trust=groups[6],
                          machtype=groups[7],
                          location=urllib.unquote(groups[8]),
                          group=groups[9],
                          state=urllib.unquote(groups[10]),
                          state_time=groups[12] or 0,
                          data=urllib.unquote(groups[13]))
         self.update_nick_list(user)
         user.prnt(self.buffer, weechat.prefix('network'))
Exemple #57
0
def whois (username):
    '''Shows profile information about a given user'''
    if len(username) == 0:
        return weechat.WEECHAT_RC_ERROR
    
    response = statusnet_handler.handle_request(statusnet_handler.build_request('users', 'show', username))

    if response == None:
        pass
    elif response == False:
        weechat.prnt(weechat.current_buffer(), ('%sCan\'t retrieve information about %s' % (weechat.prefix('error'), username)))
    else:
        whois = json.load(response)

        whois['summary'] = ' '.join([u'\u00B5', str(whois['statuses_count']),
                                     u'\u2764', str(whois['favourites_count']),
                                     'subscribers', str(whois['followers_count']),
                                     'subscriptions', str(whois['friends_count'])])

        for property in ['name', 'description', 'url', 'location', 'profile_image_url', 'summary']:
            if property in whois and whois[property] != None:
                weechat.prnt(weechat.current_buffer(), ('%s[%s] %s' % (weechat.prefix('network'),
                                                                       nick_color(username),
                                                                       whois[property].encode('utf-8'))))
        
    return weechat.WEECHAT_RC_OK
Exemple #58
0
def leave (group):
    '''Leaves a group'''
    if len(group) == 0:
        return weechat.WEECHAT_RC_ERROR
    
    response = statusnet_handler.handle_request(statusnet_handler.build_request('statusnet/groups', 'leave', group))

    if response == None:
        pass
    elif response == False:
        weechat.prnt(weechat.current_buffer(), ('%sCan\'t leave %s' % (weechat.prefix('error'), group)))
    else:
        group_info = json.load(response)
        weechat.prnt(weechat.current_buffer(), '%sYou left group %s (%s)' % (weechat.prefix('network'), group_info['fullname'].encode('utf-8'), group))

    return weechat.WEECHAT_RC_OK