def ircrypt_public_key_send(server, nick): '''This function sends away own public key''' global ircrypt_gpg_homedir, ircrypt_gpg_id, ircrypt_key_ex_memory # Export own public key and b64encode the public key. Print error if # necessary. if not ircrypt_gpg_id: ircrypt.ircrypt_error('Error in IRCrypt key exchange', weechat.current_buffer()) weechat.command('','/mute -all notice -server %s %s ' '>UCRY-INTERNAL-ERROR' % (server, info['nick'])) return '' (ret, out, err) = ircrypt.ircrypt_gnupg(b'', '--homedir', ircrypt_gpg_homedir, '--export', ircrypt_gpg_id) if ret: ircrypt.ircrypt_error(err.decode('utf-8'), weechat.current_buffer()) weechat.command('','/mute -all notice -server %s %s ' '>UCRY-INTERNAL-ERROR' % (server, info['nick'])) try: del ircrypt_key_ex_memory[target] except KeyError: pass return '' elif err: ircrypt.ircrypt_warn(err.decode('utf-8')) pub_key = base64.b64encode(out) # Partition the public key and send it away for i in range(1 + (len(pub_key) // MAX_PART_LEN))[::-1]: msg = '>PUB-EX-%i %s' % (i, pub_key[i*MAX_PART_LEN:(i+1)*MAX_PART_LEN]) weechat.command('','/mute -all notice -server %s %s %s' % (server, nick, msg)) return ''
def command_main(data, buffer, args): args = args.split() curr_buffer = weechat.current_buffer() curr_buffer_number = weechat.buffer_get_integer(curr_buffer, "number") if len(args) != 1 and len(args) != 2: weechat.prnt("", "You need to specify 1 or 2 buffers") return weechat.WEECHAT_RC_ERROR if len(args) == 2: weechat.command("", "/buffer %s" % args[0]) first_buffer = weechat.current_buffer() first_buffer_number = weechat.buffer_get_integer(first_buffer, "number") weechat.command("", "/buffer %s" % args[1]) second_buffer = weechat.current_buffer() second_buffer_number = weechat.buffer_get_integer(second_buffer, "number") else: first_buffer = weechat.current_buffer() first_buffer_number = weechat.buffer_get_integer(first_buffer, "number") weechat.command("", "/buffer %s" % args[0]) second_buffer = weechat.current_buffer() second_buffer_number = weechat.buffer_get_integer(second_buffer, "number") weechat.buffer_set(first_buffer, "number", str(second_buffer_number)) weechat.buffer_set(second_buffer, "number", str(first_buffer_number)) weechat.command("", "/buffer %s" % str(curr_buffer_number)) return weechat.WEECHAT_RC_OK
def translate_process_cb(data, command, rc, stdout, stderr): """Callback reading HTML data from website.""" global translate if stdout != '': translate['stdout'] += stdout if int(rc) >= 0: translated = translate['stdout'].split('"')[1] translate['input_before'][0] = weechat.buffer_get_string(weechat.current_buffer(), 'input') translate['input_before'][1] = weechat.buffer_get_integer(weechat.current_buffer(), 'input_pos') if translate['options']['word']: # translate last word of input str_input = translate['input_before'][0] if str_input: pos = str_input.rfind(' ') if pos < 0: str_input = translated else: str_input = '%s %s' % (str_input[0:pos], translated) else: str_input = translated translate['input_after'][0] = str_input else: if translate['options']['before_marker']: translated = '%s%s' % (translate['options']['before_marker'], translated) translate['input_after'][0] = translated # set input with translation translate['input_after'][1] = len(translate['input_after'][0]) weechat.buffer_set(weechat.current_buffer(), 'input', translate['input_after'][0]) weechat.buffer_set(weechat.current_buffer(), 'input_pos', '%d' % translate['input_after'][1]) translate['hook_process'] = '' elif int(rc) == WEECHAT_HOOK_PROCESS_ERROR: translate['hook_process'] = '' return weechat.WEECHAT_RC_OK
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 update_title(data, signal, signal_data): ''' The callback that adds title. ''' if w.config_get_plugin('short_name') == 'on': title = w.buffer_get_string(w.current_buffer(), 'short_name') else: title = w.buffer_get_string(w.current_buffer(), 'name') hotlist = w.infolist_get('hotlist', '', '') hot_text = '' while w.infolist_next(hotlist): priority = w.infolist_integer(hotlist, 'priority') if priority >= int(w.config_get_plugin('title_priority')): number = w.infolist_integer(hotlist, 'buffer_number') thebuffer = w.infolist_pointer(hotlist, 'buffer_pointer') name = w.buffer_get_string(thebuffer, 'short_name') hot_text += ' %s' % number if hot_text: title += ' [A:%s]' % hot_text w.infolist_free(hotlist) w.window_set_title(title) return w.WEECHAT_RC_OK
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
def get_nicklist(server, channel): global options regex_flags = 0 if options['ignore_case']: regex_flags = re.IGNORECASE ignore_list = w.config_get_plugin('ignore_list') if ignore_list == '': ignore_match = lambda x: False else: ignore_match = re.compile('(%s)$' % ignore_list.replace(',', '|'), regex_flags).match server = w.buffer_get_string(w.current_buffer(), 'localvar_server') my_nick = w.info_get('irc_nick', server) nicklist = {} infolist_nicklist = w.infolist_get('nicklist', w.current_buffer(), '') while w.infolist_next(infolist_nicklist): nick = w.infolist_string(infolist_nicklist, 'name') prefix = w.infolist_string(infolist_nicklist, 'prefix') nick_type = w.infolist_string(infolist_nicklist, 'type') if nick_type != 'nick' or (options['ignore_self'] and nick == my_nick) or ignore_match(nick): pass else: if not nicklist.has_key(prefix): nicklist[prefix]=[] nicklist[prefix].append(nick) w.infolist_free(infolist_nicklist) return nicklist
def prism_cmd_cb(data, buffer, args): global color_index input = args.decode("UTF-8") input_method = "command" if not input: input = w.buffer_get_string(buffer, "input") input = input.decode("UTF-8") input_method = "keybinding" # select a tokenizer and increment mode regex = regex_chars inc = 1 mepfx = 0 bs = 0 m = re.match('-[rwmbe]* ', input) if m and input_method == "command": opts = m.group(0) input = input[len(opts):] if 'w' in opts: regex = regex_words if 'r' in opts: inc = 0 if 'm' in opts: mepfx = 1 if 'b' in opts: input = input[::-1] if 'e' in opts: bs = 1 output = u"" tokens = re.findall(regex, input) for token in tokens: # prefix each token with a color code color_code = unicode(colors[color_index % color_count]).rjust(2, "0") if bs == 1: output += u'\x03' + color_code + ',' + find_another_color(color_code) + token else: output += u"\x03" + color_code + token # select the next color or another color at # random depending on the options specified if inc == 0: color_index += random.randint(1, color_count - 1) else: color_index += inc # output starting with a / will be executed as a # command unless we escape it with a preceding / if len(output) > 0 and output[0] == "/": output = "/" + output if mepfx == 1: output = "/me " + output if input_method == "keybinding": w.buffer_set(w.current_buffer(), "input", output.encode("UTF-8")) else: w.command(w.current_buffer(), output.encode("UTF-8")) return w.WEECHAT_RC_OK
def execbot_command_del(server,nicknames): '''Remove nicknames.''' for x in nicknames: try: del execbot_allows['%s.%s'%(server,x.lower())] weechat.prnt(weechat.current_buffer(),'Deleted permission of %s' % '%s.%s'%(server,x.lower())) except KeyError: weechat.prnt(weechat.current_buffer(),'No existing %s.%s'%(server,x.lower())) return weechat.WEECHAT_RC_OK
def np(self): """Pushes result of np template substitution to current buffer. """ ds = self.currentsong() if len(ds) == 0: wc.prnt(wc.current_buffer(), "MPC: ERROR: mpd is stopped") return wc.command(wc.current_buffer(), Template(wc.config_get_plugin("format")).safe_substitute(ds))
def weather_cb(server, buffer, argList): """ Callback for the Google weather bar item. """ global last_run, last_city, current_city global gweather_output, gweather_hook_process if argList.partition(" ")[0] == "default": weechat.config_set_plugin("city", argList.partition(" ")[2]) current_city = weechat.config_get_plugin("city") weechat.prnt(weechat.current_buffer(), "Saving new location as: %s" % current_city) if argList == "" and weechat.config_get_plugin("city") == "": weechat.prnt(weechat.current_buffer(), "Error: no default city, provide one with command") return weechat.WEECHAT_RC_ERROR if len(argList) > 0: if weechat.config_get_plugin("city") == "": weechat.config_set_plugin("city", argList) current_city = argList else: current_city = weechat.config_get_plugin("city") location_id, hl = map(quote, (current_city, weechat.config_get_plugin("language"))) url = GOOGLE_WEATHER_URL % (location_id, hl) # Use cached copy if it is updated recently enough if current_city == last_city and (time() - last_run) < (int(weechat.config_get_plugin("interval")) * 60): weechat.command(weechat.current_buffer(), gweather_output) return weechat.WEECHAT_RC_OK last_city = current_city command = "urllib2.urlopen('%s')" % (url) if gweather_hook_process != "": weechat.unhook(gweather_hook_process) gweather_hook_process = "" # Fire up the weather informationg fetching python2_bin = weechat.info_get("python2_bin", "") or "python" gweather_hook_process = weechat.hook_process( python2_bin + ' -c "import urllib2;\ handler = ' + command + ";\ print handler.info().dict['content-type'];\ print handler.read();\ handler.close();\"", int(weechat.config_get_plugin("timeout")) * 1000, "weather_data_cb", "", ) # The old cached string is returned here. gweather_data_cb() will # request a new update after the data is fetched and parsed. return weechat.WEECHAT_RC_OK
def wake_room(data, buffer, args): server = weechat.buffer_get_string(weechat.current_buffer(), 'localvar_server') channel = weechat.buffer_get_string(weechat.current_buffer(), 'localvar_channel') infolist = weechat.infolist_get('irc_nick', '', server + ',' + channel) nicklist = '' while weechat.infolist_next(infolist): nicklist += weechat.infolist_string(infolist, 'name') + ' ' weechat.command(weechat.current_buffer(), nicklist) weechat.infolist_free(infolist) return weechat.WEECHAT_RC_OK
def process_complete(data, command, rc, stdout, stderr): global process_output process_output += stdout.strip() if len(process_output) > 40: weechat.prnt(weechat.current_buffer(), weechat.prefix("error") + 'whatismyip: [%s]' % "Service Unavailable") return weechat.WEECHAT_RC_OK if int(rc) == 0: weechat.prnt(weechat.current_buffer(), '[%s]' % process_output) return weechat.WEECHAT_RC_OK
def ircrypt_receive_key_ex_ping(server, args, info): '''This function handles incomming >KEY-EX-PING notices''' global ircrypt_gpg_id, ircrypt_key_ex_memory # Check for ircrypt plugin if not ircrypt_check_ircrypt: weechat.command('','/mute -all notice -server %s %s ' '>UCRY-INTERNAL-ERROR' % (server, info['nick'])) return '' # Check if own gpg key exists if not ircrypt_gpg_id: ircrypt.ircrypt_error('Error in IRCrypt key exchange', weechat.current_buffer()) weechat.command('','/mute -all notice -server %s %s ' '>UCRY-INTERNAL-ERROR' % (server, info['nick'])) return '' # Get fingerprint from message try: fingerprint = args.split('>KEY-EX-PING')[-1].split(' (')[0].lstrip(' ') except: ircrypt.ircrypt_error('Error in IRCrypt key exchange', weechat.current_buffer()) weechat.command('','/mute -all notice -server %s %s ' '>UCRY-INTERNAL-ERROR' % (server, info['nick'])) return '' # Wrong fingerprint: Error if fingerprint and fingerprint != ircrypt_gpg_id: ircrypt.ircrypt_error('%s tries key exchange with wrong fingerprint' \ % info['nick'], weechat.current_buffer()) weechat.command('','/mute -all notice -server %s %s ' '>UCRY-PING-WITH-INVALID-FINGERPRINT' % (server, info['nick'])) return '' # Send back a >KEY-EX-PONG with optional fingerprint and create an instance # of the class KeyExchange target = '%s/%s' % (server, info['nick']) gpg_id = ircrypt_asym_id.get(target.lower()) if gpg_id: weechat.command('','/mute -all notice -server %s %s >KEY-EX-PONG %s' \ % (server, info['nick'], gpg_id)) if fingerprint: ircrypt_key_ex_memory[target] = KeyExchange(False, False) else: ircrypt_key_ex_memory[target] = KeyExchange(False, True) else: weechat.command('','/mute -all notice -server %s %s >KEY-EX-PONG' \ % (server, info['nick'])) if fingerprint: ircrypt_key_ex_memory[target] = KeyExchange(True, False) else: ircrypt_key_ex_memory[target] = KeyExchange(True, True) return ''
def flip_cmd_cb(data, buffer, args): ''' Command /flip ''' translate_input = args if not translate_input: translate_input = w.buffer_get_string(w.current_buffer(), "input") outstring = '' for char in translate_input: if char in replacements: char = replacements[char] outstring += char outstring = outstring.encode('UTF-8') w.buffer_set(w.current_buffer(), 'input', outstring) return w.WEECHAT_RC_OK
def find_nick(data, buffer, args): ''' print out the last nick ''' user_input = args if not user_input: user_input = weechat.buffer_get_string(weechat.current_buffer(), "input") weechat.prnt(weechat.current_buffer(), "got content for user_input") # reset outstring outstring = '' # Capture the nicks used # for the sake of testing, we will use "BOING" # Need a function that will string the nicks and assign them to the outstring # Encode the outstring as UTF outstring = outstring.encode('UTF-8')
def weather_cb(server, buffer, argList): ''' Callback for the Google weather bar item. ''' global last_run, last_city, current_city global gweather_output, gweather_hook_process if(argList.partition(" ")[0] == "default"): weechat.config_set_plugin('city', argList.partition(" ")[2]) current_city = weechat.config_get_plugin('city') weechat.prnt(weechat.current_buffer(), "Saving new location as: %s" % current_city) if(argList == '' and weechat.config_get_plugin('city') == ''): weechat.prnt(weechat.current_buffer(), "Error: no default city, provide one with command") return weechat.WEECHAT_RC_ERROR if(len(argList)>0): if(weechat.config_get_plugin('city') == ''): weechat.config_set_plugin('city', argList) current_city = argList else: current_city = weechat.config_get_plugin('city') location_id, hl = map(quote, (current_city, \ weechat.config_get_plugin('language'))) url = GOOGLE_WEATHER_URL % (location_id, hl) # Use cached copy if it is updated recently enough if current_city == last_city and \ (time() - last_run) < (int(weechat.config_get_plugin('interval')) * 60): weechat.command(weechat.current_buffer(), gweather_output) return weechat.WEECHAT_RC_OK last_city = current_city command = 'urllib2.urlopen(\'%s\')' % (url) if gweather_hook_process != "": weechat.unhook(gweather_hook_process) gweather_hook_process = '' # Fire up the weather informationg fetching gweather_hook_process = weechat.hook_process(\ "python -c \"import urllib2;\ handler = " + command + ";\ print handler.info().dict['content-type'];\ print handler.read();\ handler.close();\"", int(weechat.config_get_plugin('timeout')) * 1000, "weather_data_cb", "") # The old cached string is returned here. gweather_data_cb() will # request a new update after the data is fetched and parsed. return weechat.WEECHAT_RC_OK
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
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
def cowchat(data, command, return_code, out, err): if return_code != 0: weechat.prnt(weechat.current_buffer(), "Cowchat error: {0}".format(return_code)) for line in err.split("\n")[:-1]: weechat.prnt(weechat.current_buffer(), line) return weechat.WEECHAT_RC_ERROR lines = out.split("\n") cowchat_line("{}\n{}".format(data, out), len(lines) - 1) weechat.hook_timer(2000, 0, len(lines) - 1, "cowchat_line", "{}\n{}".format(data, out)) # for line in out.split("\n"): # if len(line) > 1 and line[0] == '/': # line = '/' + line # weechat.hook_signal_send("irc_input_send", weechat.WEECHAT_HOOK_SIGNAL_STRING, # "{};2;;{}".format(data, line)) return weechat.WEECHAT_RC_OK
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
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
def notification_callback(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight, prefix, message): is_away = weechat.buffer_get_string(bufferp, 'localvar_away') is_focused = bufferp == weechat.current_buffer() do_prowl = True # If set to False depending on state and settings, no Prowl notification will be sent if (is_away): if (is_focused and weechat.config_get_plugin('notify_focused_away') != 'on'): do_prowl = False elif (not is_focused and weechat.config_get_plugin('notify_unfocused_away') != 'on'): do_prowl = False else: if (is_focused and weechat.config_get_plugin('notify_focused_active') != 'on'): do_prowl = False elif (not is_focused and weechat.config_get_plugin('notify_unfocused_active') != 'on'): do_prowl = False if (do_prowl): if (weechat.buffer_get_string(bufferp, 'localvar_type') == 'private' and weechat.config_get_plugin('show_priv_msg') == 'on' and prefix != weechat.buffer_get_string(bufferp, 'localvar_nick')): send_prowl_notification(prefix, message, True) elif (ishilight == '1' and weechat.config_get_plugin('show_hilights') == 'on'): buffer = (weechat.buffer_get_string(bufferp, 'short_name') or weechat.buffer_get_string(bufferp, 'name')) send_prowl_notification(buffer, prefix + weechat.config_get_plugin('nick_separator') + message, False) return weechat.WEECHAT_RC_OK
def ircrypt_info(msg, buf=None): '''Print ifo message to specified buffer. If no buffer is set, the current foreground buffer is used to print the message. ''' if buf is None: buf = weechat.current_buffer() weechat.prnt(buf, msg)
def input_set(data, remaining_calls): """Set the input line's content.""" buf = weechat.current_buffer() weechat.buffer_set(buf, "input", data) # move the cursor back to its position prior to setting the content weechat.command('', "/input move_next_char") return weechat.WEECHAT_RC_OK
def get_recent_track(data, command, rc, out, err): """Get last track played (artist - name)""" if rc == weechat.WEECHAT_HOOK_PROCESS_ERROR: weechat.prnt('', "Error with command '{}'".format(command)) elif rc > 0: weechat.prnt('', "rc = {}".format(rc)) try: data = json.loads(out) if data.has_key('error'): weechat.prnt('', "Last.fm API error: '{}'".format(data['message'])) else: artist = data['recenttracks']['track'][0]['artist']['#text'] name = data['recenttracks']['track'][0]['name'] track = "{} - {}".format(artist, name) user = data['recenttracks']['@attr']['user'].lower() # print username or not, depending on config/arg if user == weechat.config_get_plugin('user').lower(): cmd = weechat.config_get_plugin('command') else: cmd = weechat.config_get_plugin('command_arg') # format isn't picky, ignores {user} if not present cmd = cmd.format(user=user, track=track) weechat.command(weechat.current_buffer(), cmd) except IndexError, KeyError: weechat.prnt('', "Error parsing Last.fm data")
def ccflx_cb(data, buffer, args): nick = weechat.buffer_get_string(weechat.current_buffer(), 'localvar_nick') repl = { 'a': 'â', 'c': 'ĉ', 'e': 'ê', 'g': 'ĝ', 'h': 'ĥ', 'i': 'î', 'j': 'ĵ', 'o': 'ô', 's': 'ŝ', 'u': 'û', 'w': 'ŵ', 'y': 'ŷ', 'z': 'ẑ' } for key, value in repl.iteritems(): args = args.replace(key, value) weechat.command("", args) return weechat.WEECHAT_RC_OK
def process_complete(data, command, rc, stdout, stderr): global process_output process_output += stdout.strip() if int(rc) >= 0: weechat.prnt(weechat.current_buffer(), '[%s]' % process_output) return weechat.WEECHAT_RC_OK
def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight, prefix, message): """Sends highlighted message to be printed on notification""" # string for show_notification return snreturn = None # smart_notification if (weechat.config_get_plugin('smart_notification') == "on" and bufferp == weechat.current_buffer()): pass # are we away and want highlights? check: w.infolist_integer(infolist, 'is_away') elif (weechat.config_get_plugin('notify_when_away') == "off" and weechat.buffer_get_string(bufferp, 'localvar_away')): pass elif (weechat.buffer_get_string(bufferp, "localvar_type") == "private" and weechat.config_get_plugin('show_priv_msg') == "on"): # should we ignore messages from something like ZNC with * prefix? ignprefix = weechat.config_get_plugin('ignore_nicks_startwith') if ignprefix != '' and prefix.startswith(ignprefix): # if not empty.. pass # if im sending a message to someone, don't pop up a notification. elif weechat.buffer_get_string(bufferp, "localvar_nick") != prefix: snreturn = show_notification(prefix, message) elif (ishilight == "1" and weechat.config_get_plugin('show_hilights') == "on"): buffer = (weechat.buffer_get_string(bufferp, "short_name") or weechat.buffer_get_string(bufferp, "name")) snreturn = show_notification(buffer, prefix + weechat.config_get_plugin('nick_separator') + message) # check to see if we had an error showing notification and return to user if snreturn: weechat.prnt(bufferp, snreturn) return weechat.WEECHAT_RC_OK
def close_time_cb(buffer, args): """ Callback for check for inactivity and close """ for buffer in get_all_buffers(): name = w.buffer_get_string(buffer, "name") date = get_last_line_date(buffer) date = time.mktime(time.strptime(date, "%Y-%m-%d %H:%M:%S")) now = time.time() seconds_old = now - date if seconds_old > int(w.config_get_plugin("age_limit")) * 60: if is_in_hotlist(buffer): # w.prnt('', '%s: Not closing buffer: %s: it is in hotlist' %(SCRIPT_NAME, name)) continue if name in w.config_get_plugin("ignore").split(","): # w.prnt('', '%s: Not closing buffer: %s: it is in ignore list' %(SCRIPT_NAME, name)) continue if buffer == w.current_buffer(): # Never close current buffer # w.prnt('', '%s: Not closing buffer: %s: it is in currently active' %(SCRIPT_NAME, name)) continue if len(w.buffer_get_string(buffer, "input")): # Don't close buffers with text on input line # w.prnt('', '%s: Not closing buffer: %s: it has input' %(SCRIPT_NAME, name)) continue w.prnt("", "%s: Closing buffer: %s" % (SCRIPT_NAME, name)) w.command(buffer, "/buffer close") # else: # w.prnt('', '%s: Not closing buffer: %s: it is too new: %s' %(SCRIPT_NAME, name, seconds_old)) return w.WEECHAT_RC_OK
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'] currentbuf = weechat.current_buffer() url = 'https://api.twitch.tv/kraken/channels/' + username url_hook = weechat.hook_process( "url:" + url+params, 7 * 1000, "channel_api", currentbuf) return ""
def command_run_cb (data, signal, signal_data): if tc_options['warn_command'] == '': return w.WEECHAT_RC_OK global length, cursor_pos, tc_input_text current_buffer = w.current_buffer() start_pos = int(tc_options['start_cursor_pos_at_zero'].lower() == 'off') cursor_pos = w.buffer_get_integer(current_buffer,'input_pos') + start_pos if (cursor_pos -1) == 0: tc_action_cb() return w.WEECHAT_RC_OK
def encryption_statusbar(data, item, window): if window: buf = weechat.window_get_pointer(window, 'buffer') else: buf = weechat.current_buffer() if os.path.exists(weechat_dir + "/cryptkey." + weechat.buffer_get_string(buf, "short_name")): return weechat.config_get_plugin("statusbar_indicator") else: return ""
def fish_modifier_input_text(data, modifier, server_name, string): if weechat.string_is_command_char(string): return string buffer = weechat.current_buffer() name = weechat.buffer_get_string(buffer, "name") target = name.replace(".", "/") targetl = target.lower() if targetl not in fish_keys: return string return "%s" % (fish_msg_w_marker(string))
def current_buffer_name(short=False): buffer = w.current_buffer() #number = w.buffer_get_integer(buffer, "number") name = w.buffer_get_string(buffer, "name") if short: try: name = name.split('.')[-1] except: pass return name
def minimal_bar_item(data, item, window): if not window: window = w.current_window() ptr_buffer = w.window_get_pointer(window, "buffer") if ptr_buffer == "" or ptr_buffer == w.current_buffer(): return "" length = w.window_get_integer(window, 'win_width') - w.buffer_get_integer( ptr_buffer, 'input_length') s = length * " " return s
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
def notify(data, buffer, date, tags, displayed, highlight, prefix, message): # ignore if it's yourself own_nick = weechat.buffer_get_string(buffer, 'localvar_nick') if prefix == own_nick or prefix == ('@%s' % own_nick): return weechat.WEECHAT_RC_OK # ignore messages from the current buffer if weechat.config_get_plugin( 'ignore_current_buffer_messages' ) == 'on' and buffer == weechat.current_buffer(): return weechat.WEECHAT_RC_OK # ignore messages older than the configured theshold (such as ZNC logs) if enabled if weechat.config_get_plugin('ignore_old_messages') == 'on': message_time = datetime.datetime.utcfromtimestamp(int(date)) now_time = datetime.datetime.utcnow() # ignore if the message is greater than 5 seconds old if (now_time - message_time).seconds > 5: return weechat.WEECHAT_RC_OK # passing `None` or `''` still plays the default sound so we pass a lambda instead sound = weechat.config_get_plugin( 'sound_name') if weechat.config_get_plugin( 'sound') == 'on' else lambda: _ activate_bundle_id = weechat.config_get_plugin('activate_bundle_id') if weechat.config_get_plugin('show_highlights') == 'on' and int(highlight): channel = weechat.buffer_get_string(buffer, 'localvar_channel') if weechat.config_get_plugin('show_message_text') == 'on': Notifier.notify(message, title='%s %s' % (prefix, channel), sound=sound, appIcon=WEECHAT_ICON, activate=activate_bundle_id) else: Notifier.notify('In %s by %s' % (channel, prefix), title='Highlighted Message', sound=sound, appIcon=WEECHAT_ICON, activate=activate_bundle_id) elif weechat.config_get_plugin( 'show_private_message') == 'on' and 'notify_private' in tags: if weechat.config_get_plugin('show_message_text') == 'on': Notifier.notify(message, title='%s [private]' % prefix, sound=sound, appIcon=WEECHAT_ICON, activate=activate_bundle_id) else: Notifier.notify('From %s' % prefix, title='Private Message', sound=sound, appIcon=WEECHAT_ICON, activate=activate_bundle_id) return weechat.WEECHAT_RC_OK
def autoaway_cmd(data, buffer, args): ''' /autoaway command, what to do with the arguments ''' if args: value = args.strip(' ').partition(' ') w.config_set_plugin('idletime', value[0]) if value[2]: w.config_set_plugin('message', value[2]) if val_idletime() > 0: w.prnt( w.current_buffer(), "%sauto-away%s settings:\n" " Time: %s%s%s minute(s)\n" " Message: %s%s\n" % (w.color("bold"), w.color("-bold"), w.color("bold"), w.config_get_plugin('idletime'), w.color("-bold"), w.color("bold"), w.config_get_plugin('message'))) else: w.prnt( w.current_buffer(), "%sauto-away%s is disabled.\n" % (w.color("bold"), w.color("-bold"))) return w.WEECHAT_RC_OK
def subscribe(username): '''Subscribes to a user''' 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
def my_modifier_cb(data, modifier, modifier_data, string): if unwanted_pattern.match(string): if options['warning_buffer'] == 'current': output = w.current_buffer() elif options['warning_buffer'] == 'server': server = w.buffer_get_string(w.current_buffer(), 'localvar_server') plugin = w.buffer_get_string(w.current_buffer(), 'plugin') output = w.buffer_search(plugin, 'server.' + server) elif options['warning_buffer'] == '': output = None else: output = '' # if invalid option set to weechat buffer if not output == None: w.prnt_date_tags( output, 0, 'no_log', '%sunwanted message deleted: "%s"' % (w.prefix('error'), string)) w.buffer_set(w.current_buffer(), 'input', string) return '' else: return string
def allquery_command_cb(data, buffer, args): """ Callback for /allquery command """ args = args.strip() if args == "": weechat.command("", "/help %s" % SCRIPT_COMMAND) return weechat.WEECHAT_RC_OK argv = args.split(" ") exclude_nick = None current_server = None if '-current' in argv: current_server = weechat.buffer_get_string(weechat.current_buffer(), "localvar_server") # remove "-current" + whitespace from argumentlist args = args.replace("-current", "") args = args.lstrip() argv.remove("-current") # search for "-exclude" in arguments i = 0 for entry in argv[0:]: if entry.startswith("-exclude="): exclude_nick = make_list(argv[i]) command = " ".join(argv[i + 1::]) break i += 1 else: command = args # no command found. if not command: return weechat.WEECHAT_RC_OK if not command.startswith("/"): command = "/%s" % command infolist = weechat.infolist_get("buffer", "", "") while weechat.infolist_next(infolist): if weechat.infolist_string(infolist, "plugin_name") == "irc": ptr = weechat.infolist_pointer(infolist, "pointer") server = weechat.buffer_get_string(ptr, "localvar_server") query = weechat.buffer_get_string(ptr, "localvar_channel") execute_command = re.sub(r'\$nick', query, command) if weechat.buffer_get_string(ptr, "localvar_type") == "private": if current_server is not None: if server == current_server: exclude_nick_and_server(ptr, query, server, exclude_nick, execute_command) else: exclude_nick_and_server(ptr, query, server, exclude_nick, execute_command) weechat.infolist_free(infolist) return weechat.WEECHAT_RC_OK
def modifier_cb(data, modifier, modifier_data, string): finals = string match = re.search('((\s|\:)[0-9]{8}(\s|$))', string) if match: ipcenter = "https://ipcenter.ipsoft.com/IPim/Ticket/Display.html?id=" + match.group( ).strip() weechat.prnt( weechat.current_buffer(), "%s[IPCenter] %s%s" % (weechat.color("red"), weechat.color("reset"), ipcenter)) return "%s%s" % (string, "")
def mplayer_msg(world, world_eol, userdata): fn = getFilename() ver = getVersion() if type(fn) == str: # we've got a string for fn all = '/me is now watching: ' + fn + ' [' + ver + ']' weechat.command(weechat.current_buffer(), all) return 0 else: # we've got None (or something went very-very wrong) return 1
def unsubscribe(username): '''Drops a subscription''' 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
def handle_msg(data, pbuffer, date, tags, displayed, highlight, prefix, message): highlight = bool(highlight) and cfg["highlight"] query = true[cfg["query"]] notify_away = true[cfg["notify_away"]] buffer_type = weechat.buffer_get_string(pbuffer, "localvar_type") away = weechat.buffer_get_string(pbuffer, "localvar_away") x_focus = False window_name = "" my_nickname = "nick_" + weechat.buffer_get_string(pbuffer, "localvar_nick") team = weechat.buffer_get_string(pbuffer, "name") ignore_nicks = cfg["ignore_nicks"].split(",") # Check to make sure we're in X and xdotool exists. # This is kinda crude, but I'm no X master. if (environ.get('DISPLAY') != None) and path.isfile("/bin/xdotool"): window_name = subprocess.check_output( ["xdotool", "getwindowfocus", "getwindowname"]) if "WeeChat" in window_name: x_focus = True if pbuffer == weechat.current_buffer() and x_focus: return weechat.WEECHAT_RC_OK for ignore_team in cfg["ignore_teams"].split(","): if ignore_team.lower() in team.lower(): return weechat.WEECHAT_RC_OK if team in cfg["ignore_teams"].split(","): return weechat.WEECHAT_RC_OK if away and not notify_away: return weechat.WEECHAT_RC_OK if my_nickname in tags and my_nickname != 'nick_': return weechat.WEECHAT_RC_OK if 'nick_unknown' in tags: return weechat.WEECHAT_RC_OK if 'no_highlight' in tags: return weechat.WEECHAT_RC_OK buffer_name = weechat.buffer_get_string(pbuffer, "short_name") if buffer_type == "private" and query: notify_user(buffer_name, message) elif buffer_type == "channel": notify_user( '{} @ {}'.format(buffer_name, tags.split(',')[0].replace('nick_', '')), message) return weechat.WEECHAT_RC_OK
def pf(self, *args, **kwargs): robj = f(self, *args, **kwargs) if not self.verbose: return robj # Show the status in the current buffer csong = self._mpdc.currentsong() csong.update( {'state': self.state_chars[self._get_status('state')]}) wc.prnt(self.wcb or wc.current_buffer(), Template(self.shortstats).safe_substitute(csong)) return robj
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
def translate_process_cb(data, command, rc, stdout, stderr): """Callback reading HTML data from website.""" global translate if stdout != '': translate['stdout'] += stdout if int(rc) >= 0: translated = ''.join( [x['trans'] for x in json.loads(translate['stdout'])['sentences']]) if sys.version_info < (3, ): translated = translated.encode('utf-8') translate['input_before'][0] = weechat.buffer_get_string( weechat.current_buffer(), 'input') translate['input_before'][1] = weechat.buffer_get_integer( weechat.current_buffer(), 'input_pos') if translate['options']['word']: # translate last word of input str_input = translate['input_before'][0] if str_input: pos = str_input.rfind(' ') if pos < 0: str_input = translated else: str_input = '%s %s' % (str_input[0:pos], translated) else: str_input = translated translate['input_after'][0] = str_input else: if translate['options']['before_marker']: translated = '%s%s' % (translate['options']['before_marker'], translated) translate['input_after'][0] = translated # set input with translation translate['input_after'][1] = len(translate['input_after'][0]) weechat.buffer_set(weechat.current_buffer(), 'input', translate['input_after'][0]) weechat.buffer_set(weechat.current_buffer(), 'input_pos', '%d' % translate['input_after'][1]) translate['hook_process'] = '' elif int(rc) == WEECHAT_HOOK_PROCESS_ERROR: translate['hook_process'] = '' return weechat.WEECHAT_RC_OK
def remove_from_nick_colours(colour): colours = nick_colours() if not colour in colours: weechat.prnt( weechat.current_buffer(), '%sThe colour \"%s\" is not present in weechat.color.chat_nick_colors' % (weechat.prefix("error"), colour)) return colours.remove(colour) wc_nick_colours = ','.join(colours) weechat.config_option_set(wc_nick_colours_pointer(), wc_nick_colours, 1) load_buffer_items()
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
def np(data, buffer, args): """ Send information about the currently played song to the channel. """ spacer = wc.config_get_plugin("spacer") msg_head = wc.config_get_plugin("msg_head") tempinfo = popen('mpc').readline().rstrip() if tempinfo.find("volume:") == -1: all = '/me ' + msg_head + spacer + tempinfo wc.command(wc.current_buffer(), all) return 0
def add_to_nick_colours(colour): colours = nick_colours() if colour in colours: weechat.prnt( weechat.current_buffer(), '%sThe colour \"%s\" is already present in weechat.color.chat_nick_colors' % (weechat.prefix("error"), colour)) return colours.append(colour) wc_nick_colours = ','.join(colours) weechat.config_option_set(wc_nick_colours_pointer(), wc_nick_colours, 1) load_buffer_items()
def set_mode(arg): """Set the current mode and update the bar mode indicator.""" global mode mode = arg # If we're going to Normal mode, the cursor must move one character to the # left. if mode == "NORMAL": buf = weechat.current_buffer() input_line = weechat.buffer_get_string(buf, "input") cur = weechat.buffer_get_integer(buf, "input_pos") set_cur(buf, input_line, cur - 1, False) weechat.bar_item_update("mode_indicator")
def toggle_refresh(pointer, name, value): global OPTIONS option = name[len('plugins.var.python.' + SCRIPT_NAME + '.'):] # get optionname OPTIONS[option] = value # save new value # TODO how about matrix script or other non-irc channel buffer? no idea! help is welcome server = weechat.buffer_get_string(weechat.current_buffer(), 'localvar_server') server_ptr = weechat.buffer_search('irc', 'server.%s' % server) buffer_switch_cb('', '', server_ptr) return weechat.WEECHAT_RC_OK
def tweet_share_cb(data, buffer, args): """Share tweet with current IRC channel.""" global twitter try: tweet = twitter.get_tweet(args) except TwitterError as error: print_error(error) return wc.WEECHAT_RC_OK message = '<@%s> %s [https://twitter.com/#!/%s/status/%s]' % \ (tweet.screen_name, tweet.txt, tweet.screen_name, tweet.tid) wc.command(wc.current_buffer(), '/say %s' % message) return wc.WEECHAT_RC_OK
def get_logfile(): logfilename = "" current_buffer = weechat.current_buffer() infolist = weechat.infolist_get('logger_buffer', '', '') while weechat.infolist_next(infolist): bpointer = weechat.infolist_pointer(infolist, 'buffer') if current_buffer == bpointer: logfilename = weechat.infolist_string(infolist, 'log_filename') log_enabled = weechat.infolist_integer(infolist, 'log_enabled') log_level = weechat.infolist_integer(infolist, 'log_level') weechat.infolist_free(infolist) # free infolist() return logfilename
def hide_buffer_cb(data, signal, signal_data): """Hide the previous IRC buffer when switching buffers. If configuration option ``hide_private`` is enabled, private buffers will become hidden as well. If the previous buffer name matches any of the exemptions defined in ``exemptions``, it will not become hidden. :param data: Pointer :param signal: Signal sent by Weechat :param signal_data: Data sent with signal :returns: callback return value expected by Weechat. """ global CURRENT_BUFFER previous_buffer = CURRENT_BUFFER CURRENT_BUFFER = weechat.current_buffer() plugin = weechat.buffer_get_string(previous_buffer, "plugin") full_name = weechat.buffer_get_string(previous_buffer, "full_name") server = weechat.buffer_get_string(previous_buffer, "localvar_server") channel = weechat.buffer_get_string(previous_buffer, "localvar_channel") if full_name.startswith("irc.server"): return WEECHAT_RC_OK buffer_type = weechat.buffer_get_string( weechat.info_get("irc_buffer", "{},{}".format(server, channel)), "localvar_type") if (buffer_type == "private" and weechat.config_get_plugin("hide_private") == "off"): return WEECHAT_RC_OK if weechat.config_get_plugin("hide_inactive") == "off": nicks_count = 0 infolist = weechat.infolist_get("irc_channel", "", "{},{}".format(server, channel)) if infolist: weechat.infolist_next(infolist) nicks_count = weechat.infolist_integer(infolist, "nicks_count") weechat.infolist_free(infolist) if nicks_count == 0: return WEECHAT_RC_OK for entry in list_exemptions(): if entry in full_name: return WEECHAT_RC_OK weechat.buffer_set(previous_buffer, "hidden", "1") return WEECHAT_RC_OK
def priv_msg_cb(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight, prefix, message): """Sends highlighted message to be printed on notification""" if not w.config_string_to_boolean(w.config_get_plugin('activated')): _debug('Plugin not activated. Not sending.') return w.WEECHAT_RC_OK if (w.config_string_to_boolean(w.config_get_plugin('smart_notification')) and bufferp == w.current_buffer()): _debug( '"smart_notification" option set but you are on this buffer already. Not sending.' ) return w.WEECHAT_RC_OK if (w.config_string_to_boolean(w.config_get_plugin('only_away')) and not w.buffer_get_string(bufferp, 'localvar_away')): _debug('"only_away" option set but you are not away. Not sending.') return w.WEECHAT_RC_OK ret = None notif_body = u"%s%s%s%s" % ( w.config_get_plugin('nick_separator_left').decode('utf-8'), prefix.decode('utf-8'), w.config_get_plugin('nick_separator_right').decode('utf-8'), message.decode('utf-8')) # Check that it's in a "/q" buffer and that I'm not the one writing the msg is_pm = w.buffer_get_string(bufferp, "localvar_type") == "private" is_notify_private = re.search(r'(^|,)notify_private(,|$)', tagsn) is not None # PM (query) if (is_pm and is_notify_private and w.config_string_to_boolean( w.config_get_plugin('notify_priv_msg'))): ret = send_notification("IRC private message", notif_body, int(w.config_get_plugin("emergency_priv_msg"))) _debug("Message sent: %s. Return: %s." % (notif_body, ret)) # Highlight (your nick is quoted) elif (ishilight == "1" and w.config_string_to_boolean( w.config_get_plugin('notify_hilights'))): bufname = (w.buffer_get_string(bufferp, "short_name") or w.buffer_get_string(bufferp, "name")) ret = send_notification(bufname.decode('utf-8'), notif_body, int(w.config_get_plugin("emergency_hilights"))) _debug("Message sent: %s. Return: %s." % (notif_body, ret)) if ret is not None: _debug(str(ret)) return w.WEECHAT_RC_OK
def input_modifier_cb(data, modifier, modifier_data, string): """Modifier that will add help on command line (for display only).""" global cmdhelp_settings line = weechat.string_remove_color(string, '') if line == '': return string command = '' arguments = '' if weechat.string_input_for_buffer(line) != '': return string items = line.split(' ', 1) if len(items) > 0: command = items[0] if len(command) < 2: return string if len(items) > 1: arguments = items[1] if command[1:].lower() in cmdhelp_settings['ignore_commands'].split(','): return string current_buffer = weechat.current_buffer() current_window = weechat.current_window() plugin = weechat.buffer_get_pointer(current_buffer, 'plugin') msg_help = get_help_command(plugin, command[1:], arguments) or get_list_commands( plugin, command[1:], arguments) if not msg_help: if cmdhelp_settings['display_no_help'] != 'on': return string msg_help = weechat.color(cmdhelp_settings['color_no_help']) if command: msg_help += 'No help for command %s' % command else: msg_help += 'No help' if cmdhelp_settings['right_align'] == 'on': win_width = weechat.window_get_integer(current_window, 'win_width') input_length = weechat.buffer_get_integer(current_buffer, 'input_length') help_length = len(weechat.string_remove_color(msg_help, "")) min_space = int(cmdhelp_settings['space']) padding = int(cmdhelp_settings['right_padding']) space = win_width - input_length - help_length - padding if space < min_space: space = min_space else: space = int(cmdhelp_settings['space']) color_delimiters = cmdhelp_settings['color_delimiters'] return '%s%s%s%s%s%s%s' % ( string, space * ' ', weechat.color(color_delimiters), cmdhelp_settings['prefix'], msg_help, weechat.color(color_delimiters), cmdhelp_settings['suffix'])