Exemple #1
0
def send_push(title, body):
    api_key = get_api_key()
    apiurl = 'https://{}@api.pushbullet.com/v2/pushes'.format(api_key)
    timeout = int(w.config_get_plugin('api_timeout')) * 1000
    if len(title) != 0 or len(body) != 0:
        deviceiden = w.config_get_plugin('devices')
        if deviceiden == 'all':
            payload = urllib.parse.urlencode({
                'type': 'note',
                'title': title,
                'body': body.encode('utf-8')
            })
        else:
            payload = urllib.parse.urlencode({
                'type': 'note',
                'title': title,
                'body': body.encode('utf-8'),
                'devices': deviceiden,
            })

        w.hook_process_hashtable(
            'url:' + apiurl,
            {
                'postfields': payload,
                'header': '1',
            },
            timeout,
            'process_pushbullet_cb',
            '',
        )
Exemple #2
0
def pastero_cmd_cb(data, buffer, args):
    global Ext
    command = 'curl -sSF c=@- ' + url

    if args.count('.') > 0:
        Ext = args.split('.')
        Ext.reverse()
    else:
        Ext = ' '  # Ugly hack so Ext[0] doesn't complain in case is empty :>

    if args != '':
        sargs = args.split()

        if sargs[0] == '--clip':
            f_input(get_clip_cmd().strip())

        elif sargs[0] == '--cmd':
            if len(sargs) == 1:
                w.prnt(w.current_buffer(),
                       '%s\tPlease specify a command to run.' % PREFIX)
            else:
                sargs = ' '.join(sargs[1:])
                command = ' '.join((sargs, '|', command))
                w.hook_process_hashtable('sh', {
                    'arg1': '-c',
                    'arg2': command
                }, 5 * 1000, 'printer_cb', '')
        else:
            f_input(open(sargs[0], 'r').read())
    else:
        w.prnt(w.current_buffer(),
               '%s\tPlease, specify a file to upload.' % PREFIX)

    return WEECHAT_RC_OK
def post_prowl(label, title, message):
    opt_dict = urllib.urlencode(
        {"apikey": API_KEY, "priority": PRIORITY, "application": label, "event": title, "description": message}
    )
    weechat.hook_process_hashtable(
        "url:https://api.prowlapp.com/publicapi/add?", {"postfields": opt_dict}, 30 * 1000, "prowl_response", ""
    )
Exemple #4
0
def callGV(buf=None, number=None, input_data=None, msg_id=None, send=False):
    if send:
        send_hook = weechat.hook_process_hashtable(
            weechat_dir + '/python/wtsend.py', {'stdin': ''}, 0, 'sentCB',
            weechat.buffer_get_string(buf, 'name'))
        proc_data_fmt_str = ("{email}{sep}{passwd}{sep}{number}{sep}"
                             "{input_data}{sep}{msg_id}{sep}{api_key}{sep}")

        proc_data = proc_data_fmt_str.format(email=email,
                                             passwd=passwd,
                                             number=number,
                                             input_data=input_data,
                                             msg_id=msg_id,
                                             api_key=api_key,
                                             sep="\n")
        weechat.hook_set(send_hook, 'stdin', proc_data)
    else:
        proc_data_fmt_str = (
            "{email}{sep}{passwd}{sep}{api_key}{sep}{poll_interval}{sep}")
        proc_data = proc_data_fmt_str.format(
            email=email,
            passwd=passwd,
            api_key=api_key,
            poll_interval=weechat.config_get_plugin('poll_interval'),
            sep="\n")

        recv_hook = weechat.hook_process_hashtable(
            weechat_dir + '/python/wtrecv.py', {'stdin': ''}, 0,
            'renderConversations', '')
        weechat.hook_set(recv_hook, 'stdin', proc_data)
Exemple #5
0
def current_version_cb(action, command, rc, out, err):
    logger.debug("%s exited with %s", command, rc)
    version = out.split(" ")[-1].strip()
    if action == "install":
        prnt("Current version of signal-cli is %s" % version)
        weechat.hook_process_hashtable(
            'url:%s' % options.get('signal_cli_update_url'),
            {"useragent": useragent}, 10000, 'update_url_cb', version)
    if action == "installIfMissing":
        if version == "":
            prnt("signal-cli not found, downloading...")
            current_version_cb("install", command, rc, out, err)
        else:
            prnt(
                "signal-cli is already installed. Run %s/signal upgrade%s to get the latest version"
                % (weechat.color("bold"), weechat.color("reset")))
    elif action == "welcome":
        prnt("")
        prnt("")
        if version != "":
            prnt("Welcome to Signal Weechat! You're running signal-cli %s." %
                 version)
            prnt("To begin, you must register or link to an existing device:")
            prnt("To register a new number: %s/signal register +12024561414" %
                 weechat.color("bold"))
            prnt("To link to an existing device: %s/signal link" %
                 weechat.color("bold"))
        else:
            prnt(
                "You don't have signal-cli! Run %s/signal install%s first to get it!"
                % (weechat.color("bold"), weechat.color("reset")))
        prnt("")
        prnt("")
    return weechat.WEECHAT_RC_OK
Exemple #6
0
def pastero_cmd_cb(data, buffer, args):
    global Ext
    command = 'curl -sSF c=@- ' + url

    if args.count('.') > 0:
        Ext = args.split('.')
        Ext.reverse()
    else:
        Ext = ' ' # Ugly hack so Ext[0] doesn't complain in case is empty :>

    if args != '':
        sargs = args.split()

        if sargs[0] == '--clip':
            f_input(get_clip_cmd().strip())

        elif sargs[0] == '--cmd':
            if len(sargs) == 1:
                w.prnt(w.current_buffer(),
                       '%s\tPlease specify a command to run.' % PREFIX)
            else:
                sargs = ' '.join(sargs[1:])
                command = ' '.join((sargs, '|', command))
                w.hook_process_hashtable('sh',
                                         {'arg1':'-c',
                                          'arg2':command},
                                         5 * 1000, 'printer_cb', '')
        else:
            f_input(open(sargs[0], 'r').read())
    else:
        w.prnt(w.current_buffer(),
                     '%s\tPlease, specify a file to upload.' % PREFIX)

    return WEECHAT_RC_OK
Exemple #7
0
def send_push(title, body):
    global last_notification

    interval = w.config_get_plugin("min_notify_interval")
    if interval is not None and interval != "" and int(interval) != 0:
        interval = int(interval)

        earliest_notification = last_notification + int(interval)

        if last_notification is not None and time.time(
        ) <= earliest_notification:
            debug("Too soon since last notification, skipping")
            return w.WEECHAT_RC_OK

    last_notification = time.time()

    # check to see if the relay is connected, ignore if so
    check_relays = w.config_string_to_boolean(
        w.config_get_plugin('ignore_on_relay'))
    CONNECTED_RELAY = False
    if check_relays:
        infolist = w.infolist_get('relay', '', '')
        if infolist:
            while w.infolist_next(infolist):
                status = w.infolist_string(infolist, 'status_string')
                if status == 'connected':
                    CONNECTED_RELAY = True
                    break
            w.infolist_free(infolist)

    if CONNECTED_RELAY is True:
        # we have a relay conected, don't notify
        debug("Relay is connected, not sending push.")
        return w.WEECHAT_RC_OK

    debug("Sending push.  Title: [%s], body: [%s]" % (title, body))

    apikey = w.string_eval_expression(w.config_get_plugin("api_key"), {}, {},
                                      {})
    apiurl = "https://%[email protected]/v2/pushes" % (apikey)
    timeout = 20000  # FIXME - actually use config
    if len(title) is not 0 or len(body) is not 0:
        deviceiden = w.config_get_plugin("device_iden")
        if deviceiden == "all":
            payload = urllib.parse.urlencode({
                'type': 'note',
                'title': title,
                'body': body
            })
        else:
            payload = urllib.parse.urlencode({
                'type': 'note',
                'title': title,
                'body': body,
                'device_iden': deviceiden
            })
        w.hook_process_hashtable("url:" + apiurl, {
            "postfields": payload,
            "header": "1"
        }, timeout, "process_pushbullet_cb", "")
Exemple #8
0
def tts(text):
    """Pronounce the text"""
    engine = weechat.config_get_plugin('tts_engine')
    lang = weechat.config_get_plugin('language')
    if engine == 'espeak':
        args = {'arg1':text}
        if lang:
            args['arg2'] = '-v'
            args['arg3'] = lang
        hook = weechat.hook_process_hashtable('espeak',args,0,'my_process_cb','')
    elif engine == 'festival':
        args = {'stdin':'1', 'arg1':'festival', 'arg2':'--tts'}
        if lang:
            args['arg3'] = '--language'
            args['arg4'] = lang
        hook = weechat.hook_process_hashtable('festival',args,0,'my_process_cb','')
        weechat.hook_set(hook, "stdin", text)
        weechat.hook_set(hook, "stdin_close", "")
    elif engine == 'picospeaker':
        args = {'stdin':'1'}
        if lang:
            args['arg1'] = '-l'
            args['arg2'] = lang
        hook = weechat.hook_process_hashtable('picospeaker',args,0,'my_process_cb','')
        weechat.hook_set(hook, "stdin", text)
        weechat.hook_set(hook, "stdin_close", "")
def notify(data, buffer, timestamp, tags, displayed, highlighted, prefix, message):
    buffer_name = weechat.buffer_get_string(buffer, 'name')
    buffer_type = weechat.buffer_get_string(buffer, 'localvar_type')
    server      = weechat.buffer_get_string(buffer, 'localvar_server')

    message     = None

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

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

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

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

    if message == None:
        return weechat.WEECHAT_RC_OK

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

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

    return weechat.WEECHAT_RC_OK
def setup_from_url():
    """Download replacements and store them in weechat home directory."""

    log("downloading XML...")
    weechat.hook_process_hashtable(
        "url:https://www.w3.org/Math/characters/unicode.xml",
        {"file_out": xml_path}, 30000, "download_cb", "")
def post_prowl(label, title, message):
    opt_dict = urllib.urlencode({
        'apikey': API_KEY,
        'application': label,
        'event': title,
        'description': message
    });
    weechat.hook_process_hashtable("url:https://api.prowlapp.com/publicapi/add?", { "postfields": opt_dict }, 30 * 1000, "prowl_response", "")
def call(command, options):
    options = "\n".join(options).encode("utf-8")

    w.hook_process_hashtable(
        "sh", {
            "arg1": "-c",
            "arg2": 'echo "{0}" | {1}'.format(options, command)
        }, 10 * 1000, "launch_process_cb", "")
Exemple #13
0
def share(sharers, file):
    matching = find_matching_sharer(sharers, file.path)
    timeout = int(wc.config_get_plugin("timeout")) * 1000
    if matching:
        args = {"arg1": file.path}
        wc.hook_process_hashtable(matching.program, args, timeout,
                                  "process_hook", wc.current_buffer())
    else:
        error("Failed to share \"%s\": no matching sharer" % file.display)
Exemple #14
0
def call(command, options):
	options = "\n".join(options).encode("utf-8")

	w.hook_process_hashtable("sh"
		,{"arg1": "-c","arg2": 'echo "{0}" | {1}'.format(options, command)}
		,10 * 1000
		,"launch_process_cb"
		,""
	)
def postProwl(label, title, message):
    if api_key != "":
        opt_dict = "apikey=" + api_key + "&application=" + label + "&event=" + title + "&description=" + message
        weechat.hook_process_hashtable("url:https://api.prowlapp.com/publicapi/add?",
            { "postfields": opt_dict },
            30 * 1000, "", "")
    else:
        weechat.prnt("", "API Key is missing!")
        return weechat.WEECHAT_RC_OK
def async_http_get_request(domain, token, request):
    url = 'url:http://{token}:nopass@{domain}/{request}'.format(
        domain=domain,
        request=request,
        token=token,
    )
    context = pickle.dumps({"request": request, "token": token})
    params = {'useragent': 'weechat-letschat 0.0'}
    w.hook_process_hashtable(url, params, 20000, "url_processor_cb", context)
Exemple #17
0
def setup_from_url():
	"""Download replacements and store them in weechat home directory."""

	log("downloading XML...")
	weechat.hook_process_hashtable("url:https://www.w3.org/Math/characters/unicode.xml",
		{
			"file_out": xml_path
		},
		30000, "download_cb", "")
Exemple #18
0
def img_dl_cb(data, command, rc, out, err):
    weechat.hook_process_hashtable('img2txt', {
        'arg1': data,
        'arg2': '-f',
        'arg3': 'ansi',
        'arg4': '-y',
        'arg5': '12'
    }, 5000, 'img_cb', '')
    return weechat.WEECHAT_RC_OK
Exemple #19
0
def post_prowl(label, title, message):
    opt_dict = urllib.urlencode({
        'apikey': API_KEY,
        'application': label,
        'event': title,
        'description': message
    })
    weechat.hook_process_hashtable(
        "url:https://api.prowlapp.com/publicapi/add?",
        {"postfields": opt_dict}, 30 * 1000, "prowl_response", "")
Exemple #20
0
def send_push(title, body):
    apikey = w.config_get_plugin("api_key")
    apiurl = "https://%[email protected]/v2/pushes" % (apikey)
    timeout = 20000 # FIXME - actually use config
    if len(title) is not 0 or len(body) is not 0:
        deviceiden = w.config_get_plugin("device_iden")
        if deviceiden == "all":
            payload = urllib.urlencode({'type': 'note', 'title': title, 'body': body.encode('utf-8')})
        else:
            payload = urllib.urlencode({'type': 'note', 'title': title, 'body': body.encode('utf-8'), 'device_iden':deviceiden})
        w.hook_process_hashtable("url:" + apiurl, { "postfields": payload, "header":"1" }, timeout, "process_pushbullet_cb", "")
Exemple #21
0
def send_push(title, body):
    push_token = script_options["push_token"]
    if push_token == "":
        return

    post_body = {"to": push_token, "title": title, "body": body}
    options = {
        "httpheader": "Content-Type: application/json",
        "postfields": json.dumps(post_body)
    }
    weechat.hook_process_hashtable("url:https://exp.host/--/api/v2/push/send",
                                   options, 20000, "process_expo_cb", "")
Exemple #22
0
def notify_user(origin, message):
    weechat.hook_process_hashtable(
        "notify-send", {
            "arg1": "-i",
            "arg2": cfg["icon"],
            "arg3": "-a",
            "arg4": "WeeChat",
            "arg5": origin,
            "arg6": message
        }, 20000, "process_cb", "")

    return weechat.WEECHAT_RC_OK
Exemple #23
0
def twitch_main(data, buffer, args):
    if not args == 'bs':
        weechat.buffer_set(buffer, 'localvar_set_tstatus', '')
    username = weechat.buffer_get_string(buffer, 'short_name').replace('#', '')
    server = weechat.buffer_get_string(buffer, 'localvar_server')
    type = weechat.buffer_get_string(buffer, 'localvar_type')
    if not (server in OPTIONS['servers'].split() and type == 'channel'):
        return weechat.WEECHAT_RC_OK
    url = 'https://api.twitch.tv/kraken/streams/' + username
    weechat.hook_process_hashtable(
        "url:" + url+params, curlopt, 7 * 1000, "stream_api", buffer)
    return weechat.WEECHAT_RC_OK
Exemple #24
0
def twitch_main(data, buffer, args):
    if not args == 'bs':
        weechat.buffer_set(buffer, 'localvar_set_tstatus', '')
    username = weechat.buffer_get_string(buffer, 'short_name').replace('#', '')
    server = weechat.buffer_get_string(buffer, 'localvar_server')
    type = weechat.buffer_get_string(buffer, 'localvar_type')
    if not (server in OPTIONS['servers'].split() and type == 'channel'):
        return weechat.WEECHAT_RC_OK
    url = 'https://api.twitch.tv/helix/streams?user_login=' + username
    weechat.hook_process_hashtable(
        "url:" + url, curlopt, 7 * 1000, "stream_api", buffer)
    return weechat.WEECHAT_RC_OK
Exemple #25
0
def callGV(buf=None, number=None, input_data=None, msg_id=None, send=False):
    if send:
        send_hook = weechat.hook_process_hashtable(weechat_dir + '/python/wtsend.py',
                    { 'stdin': '' }, 0, 'sentCB', weechat.buffer_get_string(buf, 'name'))
        proc_data = email + '\n' + passwd + '\n' + number + '\n' +\
                    input_data + '\n' + msg_id + '\n'
        weechat.hook_set(send_hook, 'stdin', proc_data)
    else:
        proc_data = email + '\n' + passwd + '\n' +\
                    weechat.config_get_plugin('poll_interval') + '\n'
        recv_hook = weechat.hook_process_hashtable(weechat_dir + '/python/wtrecv.py',
                { 'stdin': '' }, 0, 'renderConversations', '')
        weechat.hook_set(recv_hook, 'stdin', proc_data)
def async_http_post_request(domain, token, request, post_data=None):
    url = 'http://{token}:nopass@{domain}/{request}'.format(
        domain=domain,
        request=request,
        token=token,
    )
    context = pickle.dumps({"request": request, "token": token, "post_data": post_data})
    params = {'useragent': 'weechat-letschat 0.0'}
    command = 'curl -X POST {url} -H "Content-Type: application/json" --data \'{post_data}\''.format(
        url=url,
        post_data=json.dumps(post_data)
    )
    w.hook_process_hashtable(command, params, 20000, "url_processor_cb", context)
Exemple #27
0
def callGV(buf=None, number=None, input_data=None, msg_id=None, send=False):
    if send:
        send_hook = weechat.hook_process_hashtable(weechat_dir + '/python/wtsend.py',
                    { 'stdin': '' }, 0, 'sentCB', weechat.buffer_get_string(buf, 'name'))
        proc_data = email + '\n' + passwd + '\n' + number + '\n' +\
                    input_data + '\n' + msg_id + '\n'
        weechat.hook_set(send_hook, 'stdin', proc_data)
    else:
        proc_data = email + '\n' + passwd + '\n' +\
                    weechat.config_get_plugin('poll_interval') + '\n'
        recv_hook = weechat.hook_process_hashtable(weechat_dir + '/python/wtrecv.py',
                { 'stdin': '' }, 0, 'renderConversations', '')
        weechat.hook_set(recv_hook, 'stdin', proc_data)
Exemple #28
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 #29
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)
Exemple #30
0
def wg_download_file(url, filename, timeout, callback, callback_data):
    """Download a file with an URL. Return hook_process created."""
    version = weechat.info_get("version_number", "") or 0
    if int(version) >= 0x00030700:
        return weechat.hook_process_hashtable("url:%s" % url,
                                              { "file_out": filename },
                                              timeout,
                                              callback, callback_data)
    else:
        script = [ "import sys",
                   "try:",
                   "    if sys.version_info >= (3,):",
                   "        import urllib.request",
                   "        response = urllib.request.urlopen('%s')" % url,
                   "    else:",
                   "        import urllib2",
                   "        response = urllib2.urlopen(urllib2.Request('%s'))" % url,
                   "    f = open('%s', 'wb')" % filename,
                   "    f.write(response.read())",
                   "    response.close()",
                   "    f.close()",
                   "except Exception as e:",
                   "    print('error:' + str(e))" ]
        return weechat.hook_process("python -c \"%s\"" % "\n".join(script),
                                    timeout,
                                    callback, callback_data)
Exemple #31
0
 def message(self, data, buffer, date, tags, isdisplayed, ishighlight,
             prefix, message):
     """Send message to IrssiNotifier."""
     if int(ishighlight):
         channel = weechat.buffer_get_string(buffer, 'sort_name') or \
             weechat.buffer_get_string(buffer, 'name')
         post = urlencode({
             'apiToken': self.token,
             'channel': self.encrypt(self.password, channel),
             'nick': self.encrypt(self.password, prefix),
             'message': self.encrypt(self.password, message),
             'version': self.version
         })
         weechat.hook_process_hashtable('url:' + self.url,
                                        {'postfields': post}, 10000, '', '')
     return weechat.WEECHAT_RC_OK
def send_command(command):
    API_TOKEN = weechat.config_get_plugin("api_token")
    if API_TOKEN != "":
        url = "https://irssinotifier.appspot.com/API/Message"
        postdata = urllib.urlencode({'apiToken':API_TOKEN,'command':encrypt(command)})
        #TODO irssinotifier.pl retries 2 times and I think we should also retry (unless we know that the error is permanent)
        hook1 = weechat.hook_process_hashtable("url:"+url, { "postfields":  postdata}, 10000, "", "")
Exemple #33
0
def send_push(title, message):
    postfields = {
        'token': w.config_get_plugin('token'),
        'user': w.config_get_plugin('user'),
        'title': title,
        'message': message,
        'url': 'https://glowing-bear.org',
    }

    w.hook_process_hashtable(
        'url:https://api.pushover.net/1/messages.json',
        {'postfields': urllib.urlencode(postfields)},
        20*1000,
        'http_request_callback',
        '',
    )
Exemple #34
0
    def __init__(self, options):
        self.status_name = options['server_name']
        self.nick_name = options['nickname']
        global debug
        if options['debug'] == "true":
            debug = True
        else:
            debug = False
        self.private_chans = {}
        self.private_chans_ptr = {}
        self.status = weechat.buffer_new(self.status_name, "status_input_cb",
                                         "", "status_close_cb", "")
        weechat.buffer_set(self.status, "localvar_set_type", "server")
        weechat.buffer_set(self.status, "localvar_set_server", "keybase")
        self.init_chats()
        #self.get_history()
        self.reader = weechat.hook_process_hashtable("keybase chat api-listen",
                                                     {"buffer_flush": "1"}, 0,
                                                     "start_reading", "")
        weechat.hook_command(
            "download", "Download an attachment", "<msg_id> <outputh_path>",
            "<msg_id>: ID of the message\n<output_path>: Path to store file",
            "", "download_message", "")
        weechat.hook_command("open",
                             "Open (with default application) an attachment",
                             "<msg_id>", "<msg_id>: ID of the message\n", "",
                             "open_attachment", "")
        ## Hooking to classic weechat command
        weechat.hook_command_run("/msg", "send_new_message", "")
        weechat.hook_command_run("/reply", "reply_to_message", "")

        weechat.hook_signal("buffer_switch", "buffer_switched", "")
        weechat.hook_signal("window_scrolled", "window_scrolled", "")
        weechat.hook_command("test", "", "", "", "", "test12", "")
def show_notification(chan, nick, message):
    API_TOKEN = weechat.config_get_plugin("api_token")
    if API_TOKEN != "":
        url = "https://irssinotifier.appspot.com/API/Message"
        postdata = urllib.urlencode({'apiToken':API_TOKEN,'nick':encrypt(nick),'channel':encrypt(chan),'message':encrypt(message),'version':13})
        version = weechat.info_get("version_number", "") or 0
        hook1 = weechat.hook_process_hashtable("url:"+url, { "postfields":  postdata}, 2000, "", "")
Exemple #36
0
def show_notification(chan, nick, message):
    API_TOKEN = weechat.config_get_plugin("api_token")
    if API_TOKEN != "":
        url = "https://irssinotifier.appspot.com/API/Message"
        postdata = urllib.urlencode({'apiToken':API_TOKEN,'nick':encrypt(nick),'channel':encrypt(chan),'message':encrypt(message),'version':13})
        version = weechat.info_get("version_number", "") or 0
        hook1 = weechat.hook_process_hashtable("url:"+url, { "postfields":  postdata}, 2000, "", "")
def show_notification(chan, nick, message):
    API_TOKEN = weechat.config_get_plugin("api_token")
    if API_TOKEN != "":
        url = "https://irssinotifier.appspot.com/API/Message"
        postdata = urllib.urlencode({'apiToken':API_TOKEN,'nick':encrypt(nick),'channel':encrypt(chan),'message':encrypt(message),'version':VERSION})
        version = weechat.info_get("version_number", "") or 0
        #TODO irssinotifier.pl retries 2 times and I think we should also retry (unless we know that the error is permanent)
        hook1 = weechat.hook_process_hashtable("url:"+url, { "postfields":  postdata}, 10000, "", "")
Exemple #38
0
def notify_user(origin, message):
    hook = weechat.hook_process_hashtable("notify-send",
        { "arg1": "-i", "arg2": cfg["icon"],
          "arg3": "-a", "arg4": "WeeChat",
          "arg5": origin, "arg6": message },
        20000, "process_cb", "")

    return weechat.WEECHAT_RC_OK
Exemple #39
0
def send_push(title, body):
    global last_notification

    interval = w.config_get_plugin("min_notify_interval")
    if interval is not None and interval != "" and int(interval) != 0:
        interval = int(interval)

        earliest_notification = last_notification + int(interval)

        if last_notification is not None and time.time() <= earliest_notification:
            debug("Too soon since last notification, skipping")
            return w.WEECHAT_RC_OK

    last_notification = time.time()

    # check to see if the relay is connected, ignore if so
    check_relays = w.config_string_to_boolean(w.config_get_plugin('ignore_on_relay'))
    CONNECTED_RELAY = False
    if check_relays:
        infolist = w.infolist_get('relay', '', '')
        if infolist:
            while w.infolist_next(infolist):
                status = w.infolist_string(infolist, 'status_string')
                if status == 'connected':
                    CONNECTED_RELAY = True
                    break
            w.infolist_free(infolist)

    if CONNECTED_RELAY is True:
        # we have a relay conected, don't notify
        debug("Relay is connected, not sending push.")
        return w.WEECHAT_RC_OK

    debug("Sending push.  Title: [%s], body: [%s]" % (title, body))

    apikey = w.config_get_plugin("api_key")
    apiurl = "https://%[email protected]/v2/pushes" % (apikey)
    timeout = 20000  # FIXME - actually use config
    if len(title) is not 0 or len(body) is not 0:
        deviceiden = w.config_get_plugin("device_iden")
        if deviceiden == "all":
            payload = urllib.urlencode({'type': 'note', 'title': title, 'body': body.encode('utf-8')})
        else:
            payload = urllib.urlencode({'type': 'note', 'title': title, 'body': body.encode('utf-8'), 'device_iden': deviceiden})
        w.hook_process_hashtable("url:" + apiurl, {"postfields": payload, "header": "1"}, timeout, "process_pushbullet_cb", "")
Exemple #40
0
def notify_user(origin, message):
    hook = weechat.hook_process_hashtable("notify-send", {
        "arg1": "WeeChat",
        "arg2": "",
        "arg3": origin + '\t',
        "arg4": message,
    }, 20000, "process_cb", "")

    return weechat.WEECHAT_RC_OK
Exemple #41
0
def fzf_tmux_command_cb(data: str, buffer: str, args: str) -> int:
    cmd = ("fzf-tmux -- --delimiter='\t' --with-nth=3.. "
           "--preview='tail -$LINES {2} 2>/dev/null'")
    hook = weechat.hook_process_hashtable(cmd, {"stdin": "1"}, 0,
                                          "fzf_process_cb", "")
    for buffer_info in buffers():
        weechat.hook_set(hook, "stdin", "\t".join(buffer_info) + "\n")
    weechat.hook_set(hook, "stdin_close", "")
    return weechat.WEECHAT_RC_OK
Exemple #42
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.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 #43
0
def twitch_whois(data, modifier, server_name, string):
    if not server_name in OPTIONS['servers'].split():
        return string
    msg = weechat.info_get_hashtable("irc_message_parse", {"message": string})
    username = msg['nick'].lower()
    currentbuf = weechat.current_buffer()
    url = 'https://api.twitch.tv/kraken/channels/' + username
    url_hook = weechat.hook_process_hashtable(
        "url:" + url+params, curlopt, 7 * 1000, "channel_api", str({'buffer': currentbuf, 'name': username}))
    return ""
Exemple #44
0
def send_push(title, message):
    # encrypt the messages
    title_enc = encrypt(title)
    text_enc = encrypt(message)

    # Send the message to endpoint
    postfields = {
        'signature': encrypt(w.config_get_plugin('api_key')),
        'title': title_enc,
        'text': text_enc
    }

    w.hook_process_hashtable(
        'url: %s' % w.config_get_plugin('end_point_url'), {
            "httpheader":
            "\n".join(["Content-Type: application/x-www-form-urlencoded"]),
            "postFields":
            urlencode(postfields)
        }, 20 * 1000, 'http_request_callback', '')
    w.prnt('', '[weerestnotify] notification sent')
Exemple #45
0
def twitch_whois(data, modifier, server_name, string):
    if not server_name in OPTIONS['servers'].split():
        return string
    msg = weechat.info_get_hashtable("irc_message_parse", {"message": string})
    username = msg['nick'].lower()
    currentbuf = weechat.current_buffer()
    url = 'https://api.twitch.tv/kraken/users?login='******'&api_version=5'
    url_hook = weechat.hook_process_hashtable(
        "url:" + url+params, curlopt, 7 * 1000, "channel_api", currentbuf)
    return ""
Exemple #46
0
def on_receive(data, signal, signal_data):
    # Fetch server, msg and buffer
    server = signal.split(",")[0]
    msg = weechat.info_get_hashtable("irc_message_parse",
                                     {"message": signal_data})
    buffer = weechat.info_get("irc_buffer", "%s,%s" % (server, msg["channel"]))

    # Notify if we get the buffer
    if buffer and isNotifiable(server, msg["channel"]):
        notify_title = "On " + msg["channel"]
        notify_msg = msg["nick"] + "> " + msg["text"]
        weechat.hook_process_hashtable(
            "notify-send", {
                "arg1": "-i",
                "arg2": "weechat",
                "arg3": "-a",
                "arg4": "WeeChat",
                "arg5": notify_title,
                "arg6": notify_msg
            }, 20000, "", "")
    return weechat.WEECHAT_RC_OK
Exemple #47
0
def show_notification(chan, nick, message):
    API_TOKEN = weechat.config_get_plugin("api_token")

    # decrypt the API token if it is stored as secured data
    if API_TOKEN.startswith("${sec."):
        API_TOKEN = weechat.string_eval_expression(API_TOKEN, {}, {}, {})

    if API_TOKEN != "":
        url = "https://irssinotifier.appspot.com/API/Message"
        postdata = urllib.urlencode({'apiToken':API_TOKEN,'nick':encrypt(nick),'channel':encrypt(chan),'message':encrypt(message),'version':13})
        version = weechat.info_get("version_number", "") or 0
        hook1 = weechat.hook_process_hashtable("url:"+url, { "postfields":  postdata}, 2000, "", "")
Exemple #48
0
def update_url_cb(current, _, rc, out, err):
    global downloads_in_progresss
    release = json.loads(out)
    latest = release['name'].split(" ")[-1]
    if latest != current:
        prnt("Latest release is %s, but we're running %s!" % (latest, current))
        for asset in release['assets']:
            url = asset['browser_download_url']
            filename = "/tmp/%s" % asset['name']
            downloads_in_progresss.append(asset['name'])
            prnt("Downloading %s" % url)
            weechat.hook_process_hashtable(
                'url:%s' % url, {
                    "useragent": useragent,
                    "file_out": filename
                }, 60000, 'update_download_cb',
                json.dumps({
                    "filename": asset['name'],
                    "version": latest
                }))
    return weechat.WEECHAT_RC_OK
Exemple #49
0
def notify_send(origin, message):
    weechat.hook_process_hashtable(
        "notify-send",
        {
            "arg1": "-u",
            "arg2": weechat.config_get_plugin("notification_urgency"),
            "arg3": "-t",
            "arg4": weechat.config_get_plugin("notification_timeout"),
            "arg5": "-a",
            "arg6": weechat.config_get_plugin("notification_application_name"),
            "arg7": "-i",
            "arg8": weechat.config_get_plugin("notification_icon"),
            "arg9": origin,
            "arg10": message,
        },
        5000,
        "notify_send_cb",
        "",
    )

    return weechat.WEECHAT_RC_OK
def send_notification(data):
    if is_debug():
        weechat.prnt(weechat.buffer_search_main(), "irssinotifier: sending notification")
    api_token = weechat.config_get_plugin("api_token")
    url = "https://irssinotifier.appspot.com/API/Message"
    nick = data['cryptdata']['nick']['value']
    chan = data['cryptdata']['chan']['value']
    message = data['cryptdata']['message']['value']
    postdata = urllib.urlencode({'apiToken':api_token,'nick':nick,'channel':chan,'message':message,'version':13})
    if is_debug():
        weechat.prnt(weechat.buffer_search_main(), "irssinotifier: postdata: %s" % postdata)
    hook1 = weechat.hook_process_hashtable("url:"+url, { "postfields":  postdata}, 30000, "send_notification_cb", "")
Exemple #51
0
def fzf_kitty_command_cb(data: str, buffer: str, args: str) -> int:
    # "kitty @ launch --type=overlay --keep-focus --hold --stdin-source=@last_cmd_output --stdin-add-formatting--stdin-add-line-wrap-markers \""
    cmd = ("kitty @ launch --type=overlay --keep-focus --hold "
           "fzf -- --delimiter='\t' --with-nth=3.. "
           "--preview='tail -$LINES {2} 2>/dev/null'")
    hook = weechat.hook_process_hashtable(cmd, {"stdin": "1"}, 0,
                                          "fzf_process_cb", "")
    print_log("Debugging.. hook: {}".format(hook))
    for buffer_info in buffers():
        weechat.hook_set(hook, "stdin", "\t".join(buffer_info) + "\n")
    weechat.hook_set(hook, "stdin_close", "")
    return weechat.WEECHAT_RC_OK
def show_notification(chan, nick, message, priority):
    PUSHOVER_USER = weechat.config_get_plugin("user")
    PUSHOVER_API_SECRET = weechat.config_get_plugin("token")
    if PUSHOVER_USER != "" and PUSHOVER_API_SECRET != "":
        url = "https://api.pushover.net/1/messages.json"
        message = '<'+nick+'> '+message
        postdata = urllib.urlencode({'token':PUSHOVER_API_SECRET,'user':PUSHOVER_USER,'message':message,'title':'weechat: '+chan,'priority':priority})
        version = weechat.info_get("version_number", "") or 0
        if int(version) >= 0x00030700: # use weechat.hook_process_hashtable only with weechat version >= 0.3.7
          hook1 = weechat.hook_process_hashtable("url:"+url, { "postfields":  postdata}, 2000, "", "")
        else:
          urllib2.urlopen(url,postdata)
Exemple #53
0
def bootstrap_tray():
    BUF_SIZE = 65536
    weechat.mkdir_parents(plugin_dir, 0755)

    if weechat.config_get_plugin("icon") == "weechat":
        # Download icon
        icon = plugin_dir + "/icons/weechat.png"
        if not path.exists(icon):
            weechat.mkdir_parents(plugin_dir + "/icons", 0755)
            weechat.hook_process_hashtable("url:" + WEECHAT_ICON_URL,
                                           {"file_out": icon + ".tmp"},
                                           30 * 1000, "process_download_cb",
                                           "")
            time.sleep(0.5)
            sha512 = hashlib.sha512()
            f = open(icon + ".tmp", 'rb')
            sha512.update(f.read())
            if sha512.hexdigest() != WEECHAT_ICON_SHA512:
                printc("weechat icon failed sha512sum; got " +
                       sha512.hexdigest())
                return 1
            else:
                rename(icon + ".tmp", icon)

    if weechat.config_get_plugin("alt-icon") == "null":
        icon = plugin_dir + "/icons/null.png"
        if not path.exists(icon):
            weechat.mkdir_parents(plugin_dir + "/icons", 0755)
            weechat.hook_process_hashtable("url:" + NULL_ICON_URL,
                                           {"file_out": icon + ".tmp"},
                                           30 * 1000, "process_download_cb",
                                           "")
            time.sleep(0.5)
            sha512 = hashlib.sha512()
            f = open(icon + ".tmp", 'rb')
            sha512.update(f.read())
            if sha512.hexdigest() != NULL_ICON_SHA512:
                printc("null icon failed sha512sum; got " + sha512.hexdigest())
                return 1
            else:
                rename(icon + ".tmp", icon)

    # Download tray icon script
    script = plugin_dir + "/systray.py"
    if not path.exists(script):
        weechat.hook_process_hashtable("url:" + SYSTRAY_PY_URL,
                                       {"file_out": script + ".tmp"},
                                       30 * 1000, "process_download_cb", "")
        time.sleep(1)
        sha512 = hashlib.sha512()
        f = open(script + ".tmp", 'rb')
        sha512.update(f.read())
        if sha512.hexdigest() != SYSTRAY_PY_SHA512:
            printc("systray.py failed sha512sum; got " + sha512.hexdigest())
            return 1
        else:
            rename(script + ".tmp", script)

    state.BOOTSTRAPPED = True
Exemple #54
0
def send_notification(server, channel, nick, message):
    endpoint = weechat.config_get_plugin('endpoint')
    token = weechat.config_get_plugin('token')
    bot = weechat.config_get_plugin('bot')

    if channel == nick:
        output = '[{}@{}] {}'.format(nick, server, message)
    else:
        output = '[{}@{}] {}: {}'.format(nick, server, channel, message)

    data = urlencode({
        'message': output,
        'token': token,
        'bot': bot,
    })

    options = {
        'postfields': data,
        'ssl_verifypeer': '0',
        'ssl_verifyhost': '0',
    }

    weechat.hook_process_hashtable('url:' + endpoint, options, 2000, '', '')
Exemple #55
0
def whois_cb(data, command, rc, out, err):
    data = json.loads(out)
    if 'error' in data:
        weechat.prnt(weechat.current_buffer(), 'Failed to get user info: %s' %
                     data['error']['message'])
        return weechat.WEECHAT_RC_OK

    p = data.get('presence') or {}

    info = ('{bold}@{mention}{default} {name}, {title}\n{bold}{online}{default} ({status})\nEmail: '
            '{bold}{email}{default}\nXMPP: {xmpp}\nSince: {since}\nTimezone: {tz}').format(
        mention=encode(data['mention_name']), name=encode(data['name']), title=data['title'],
        xmpp=data['xmpp_jid'], email=data['email'],
        online='Online' if p.get('is_online') else 'Offline',
        status=p.get('status', 'unknown'),
        bold=weechat.color('bold'), default=weechat.color('reset'),
        since=data['created'],
        tz=data['timezone'])
    weechat.prnt(weechat.current_buffer(), info)

    file_name = '/tmp/hipchat_%s' % data['id']
    weechat.hook_process_hashtable('url:%s?%s' % (data['photo_url'], get_token()),
                                   {'file_out': file_name}, 15000, 'img_dl_cb', file_name)
    return weechat.WEECHAT_RC_OK
Exemple #56
0
def theme_update():
    """Download themes (themes.tar.bz2)."""
    global theme_hook_process, theme_stdout
    # get data from website, via hook_process
    if theme_hook_process:
        weechat.unhook(theme_hook_process)
        theme_hook_process = ''
    weechat.prnt('', SCRIPT_NAME + ': downloading themes...')
    theme_config_create_dir()
    theme_stdout = ''
    theme_hook_process = (
        weechat.hook_process_hashtable(
            'url:' + weechat.config_string(theme_cfg['themes_url']),
            {'file_out': theme_config_get_tarball_filename()},
            TIMEOUT_UPDATE,
            'theme_process_update_cb', ''))