def urlserver_server_status(): """Display status of server.""" global urlserver if urlserver['socket']: weechat.prnt('', 'URL server listening on %s' % str(urlserver['socket'].getsockname())) else: weechat.prnt('', 'URL server not running')
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 write_history(filename): global history_list filename = get_filename_with_path(filename) if OPTIONS['number'] != '' and OPTIONS['number'].isdigit(): if int(OPTIONS['number']) < 0: save_from_position = len(history_list) - abs(int(OPTIONS['number'])) if save_from_position == len(history_list) or save_from_position < 0: save_from_position = 0 elif int(OPTIONS['number']) > 0: save_to_position = int(OPTIONS['number']) if save_to_position > len(history_list): save_to_position = len(history_list) else: save_from_position = 0 try: f = open(filename, 'w') if int(OPTIONS['number']) <= 0: i = save_from_position # for i in range(len(a)): while i < len(history_list): f.write('%s\n' % history_list[i]) i = i + 1 if int(OPTIONS['number']) > 0: i = 0 while i < save_to_position: f.write('%s\n' % history_list[i]) i = i + 1 f.close() except: weechat.prnt('','%s%s: Error writing history to "%s"' % (weechat.prefix('error'),SCRIPT_NAME,filename)) raise
def jmh_cmd(data, buffer, args=None): """ Command /jabber_message_handler """ if args: argv = args.split(None, 1) if len(argv) > 0: if argv[0] == "on": weechat.config_option_set( jmh_config_option["enabled"], "on", 1) elif argv[0] == "off": weechat.config_option_set( jmh_config_option["enabled"], "off", 1) elif argv[0] == "verbose": if len(argv) > 1: weechat.config_option_set( jmh_config_option["verbose"], argv[1], 1) else: weechat.config_option_set( jmh_config_option["verbose"], "toggle", 1) elif argv[0] == "log": if len(argv) > 1: weechat.config_option_set( jmh_config_option["log"], argv[1], 1) else: weechat.prnt("", "jabber_message_handler: unknown action") print_settings() return weechat.WEECHAT_RC_OK
def unread_cb(data, buffer, command): global all_channels channels = [] if command.find("set_unread_current_buffer") >= 0: if w.buffer_get_string(buffer, "localvar_server") == "slack" and \ w.buffer_get_string(buffer, "localvar_type") in ["channel", "private"]: channels.append(w.buffer_get_string(buffer, "localvar_channel")) else: channels = _channels() for c in channels: cs = c.lstrip("#") if cs in all_channels: try: if c.startswith("#"): if cs in private_groups: r = slack.groups.mark(all_channels[cs], time.time()) else: r = slack.channels.mark(all_channels[cs], time.time()) else: r = slack.im.mark(all_channels[cs], time.time()) #w.prnt("", "%s: %s" % (c, r.body["ok"] and "ok" or "not ok")) except: w.prnt("", "Error while setting unread marker on %s" % c) w.prnt("", "%d channels marked as read" % len(channels)) return w.WEECHAT_RC_OK
def wg_update_cache(): """ Download list of scripts and update local cache. """ global wg_config_option, wg_hook_process, wg_stdout # get data from website, via hook_process if wg_hook_process["update"] != "": weechat.unhook(wg_hook_process["update"]) wg_hook_process["update"] = "" weechat.prnt("", "%s: downloading list of scripts..." % SCRIPT_NAME) wg_stdout["update"] = "" wg_config_create_dir() url = weechat.config_string(wg_config_option["scripts_url"]) filename = wg_config_get_cache_filename() wg_hook_process["update"] = weechat.hook_process( "python -c \"import urllib, urllib2\n" "req = urllib2.Request('" + url + "')\n" "try:\n" " response = urllib2.urlopen(req)\n" " file = open('" + filename + "', 'w')\n" " file.write(response.read())\n" " response.close()\n" " file.close()\n" "except urllib2.URLError, e:\n" " print 'error:%s' % e.code\n" "\"", TIMEOUT_UPDATE, "wg_process_update_cb", "")
def wg_cmd(data, buffer, args): """ Callback for /weeget command. """ global wg_action, wg_action_args if args == "": weechat.command("", "/help %s" % SCRIPT_COMMAND) return weechat.WEECHAT_RC_OK argv = args.strip().split(" ", 1) if len(argv) == 0: return weechat.WEECHAT_RC_OK wg_action = "" wg_action_args = "" # check arguments if len(argv) < 2: if argv[0] == "show" or \ argv[0] == "install" or \ argv[0] == "remove": weechat.prnt("", "%s: too few arguments for action \"%s\"" % (SCRIPT_NAME, argv[0])) return weechat.WEECHAT_RC_OK # execute asked action if argv[0] == "update": wg_update_cache() else: wg_action = argv[0] wg_action_args = "" if len(argv) > 1: wg_action_args = argv[1] wg_read_scripts() return weechat.WEECHAT_RC_OK
def wg_remove_scripts(names): """ Remove scripts. """ if len(wg_scripts) == 0: return list_names = names.split(" ") scripts_to_remove = {} for language in SCRIPT_EXTENSION.keys(): scripts_to_remove[language] = [] for name in list_names: script = wg_search_script_by_name(name) if script == None: weechat.prnt("", "%s: script \"%s%s%s\" not found" % (SCRIPT_NAME, wg_config_color("script"), name, weechat.color("chat"))) else: if script["full_name"] not in scripts_to_remove[script["language"]]: scripts_to_remove[script["language"]].append(script["full_name"]) for language in SCRIPT_EXTENSION.keys(): if len(scripts_to_remove[language]) > 0: # ask C plugin to remove script file(s) weechat.hook_signal_send(language + "_script_remove", weechat.WEECHAT_HOOK_SIGNAL_STRING, ",".join(scripts_to_remove[language]))
def wg_execute_action(): """ Execute action. """ global wg_action, wg_action_args, wg_loaded_scripts if wg_action != "": wg_get_loaded_scripts() if wg_action == "list": wg_list_scripts(wg_action_args) elif wg_action == "listinstalled": wg_list_scripts(wg_action_args, installed=True) elif wg_action == "show": wg_show_script(wg_action_args) elif wg_action == "install": wg_install_scripts(wg_action_args) elif wg_action == "check": wg_check_scripts() elif wg_action == "upgrade": wg_upgrade_scripts() elif wg_action == "remove": wg_remove_scripts(wg_action_args) else: weechat.prnt("", "%s%s: unknown action \"%s\"" % (weechat.prefix("error"), SCRIPT_NAME, wg_action)) # reset action wg_action = "" wg_action_args = "" wg_loaded_scripts = {}
def print_matches(target, matches, data): """Print all matching masks to the target channel""" verbose = w.config_get_plugin("verbose") in ["true", "yes"] limit = int(w.config_get_plugin("limit")) if limit < 1: limit = 1 total = len(matches) if total == 0: if verbose or data["mode"] == "special": w.prnt(target, "{}\tNo matches for {}".format(fmt_prefix(data).replace("_target_", ""), fmt_banmask(data["mask"]))) return sorting = w.config_get_plugin("sorting") if sorting == "alpha": matches = sorted(matches) elif sorting == "alpha_ignore_case": matches = sorted(matches, key=str.lower) if w.config_get_plugin("print_as_list") in ["true", "yes"]: print_as_list(target, matches, data, limit, total) else: print_as_lines(target, matches, data, limit, total)
def get_char (c): try: with open( weechat.info_get('weechat_dir', '') + '/python/asciiwrite/font/' + str(ord(c)), 'r' ) as f: return f.read().split('\n') except: weechat.prnt('', 'Did not found char %s [%d]. Replacing by NULL.' % (c, ord(c))) return []
def summarize(respList, buffer): cmd = respList[0] weechat.prnt(buffer, "\nSummary for command \"" + cmd + "\":") if cmd in summaryFunctions: summaryFunctions[cmd](respList[1:], buffer) else: weechat.prnt(buffer, "Warning: No summary function for \"" + cmd + "\"!")
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 whitelist_config_option_change_cb(userdata, option): """Callback when a config option was changed.""" weechat.prnt( "", "Whitelisted {type} now: {values}".format( type=userdata, values=", ".join(config.get_value('whitelists', userdata).split()))) return weechat.WEECHAT_RC_OK
def whitelist_cmd(userdata, buf, args): """Parse whitelist commands and take action.""" (cmd, listtype, arg) = whitelist_cmd_split(3, args) if cmd in (None, '', 'list'): whitelist_list() return weechat.WEECHAT_RC_OK if listtype in VALID_OPTION_TYPES: try: listtype = WHITELIST_TYPE_ALIAS[listtype] except KeyError: pass if arg is not None: if cmd == 'add': whitelist_add(listtype, arg) if cmd == 'del': whitelist_del(listtype, arg) else: weechat.prnt( "", "Error. Must supply an argument to '{type}'.".format( type=listtype)) else: weechat.prnt( "", "Error. Valid whitelist types are: {types}.".format( types=", ".join(VALID_OPTION_TYPES))) return weechat.WEECHAT_RC_OK
def fish_alert(buffer, message): mark = "%s%s%s\t" % ( weechat.color(weechat.config_color(fish_config_option["alert"])), weechat.config_string(fish_config_option["marker"]), weechat.color("chat")) weechat.prnt(buffer, "%s%s" % (mark, message))
def nicklist_cmd_cb(data, buffer, args): ''' Command /nicklist ''' if args == '': display_action() display_buffers() else: current_buffer_name = w.buffer_get_string(buffer, 'plugin') + '.' + w.buffer_get_string(buffer, 'name') if args == 'show': w.config_set_plugin('action', 'show') #display_action() w.command('', '/window refresh') elif args == 'hide': w.config_set_plugin('action', 'hide') #display_action() w.command('', '/window refresh') elif args == 'add': list = get_buffers_list() if current_buffer_name not in list: list.append(current_buffer_name) w.config_set_plugin('buffers', ','.join(list)) #display_buffers() w.command('', '/window refresh') else: w.prnt('', '%s: buffer "%s" is already in list' % (SCRIPT_NAME, current_buffer_name)) elif args == 'remove': list = get_buffers_list() if current_buffer_name in list: list.remove(current_buffer_name) w.config_set_plugin('buffers', ','.join(list)) #display_buffers() w.command('', '/window refresh') else: w.prnt('', '%s: buffer "%s" is not in list' % (SCRIPT_NAME, current_buffer_name)) return w.WEECHAT_RC_OK
def playlistinfo(self, sortkey='pos'): """Shows playlist information sorted by key """ new_buf = wc.buffer_search("", "mpc: playlist") if len(new_buf) == 0: new_buf = wc.buffer_new('mpc: playlist', "", "", "", "") pl = self._mpdc.playlistinfo() try: # Numerical sort spl = sorted(pl, cmp=lambda x,y: cmp(int(x), int(y)), key=itemgetter(sortkey)) except ValueError: # Alpha sort lcmp = lambda x,y: cmp(x.lower(), y.lower()) spl = sorted(pl, cmp=lambda x,y: cmp(x.lower(), y.lower()), key=itemgetter(sortkey)) t = Template(wc.config_get_plugin("playinfo")) for line in spl: wc.prnt(new_buf, t.safe_substitute(line)) return pl
def fish_secure_key_cb(data, option, value): global fish_secure_key, fish_secure_cipher fish_secure_key = weechat.config_string( weechat.config_get("fish.secure.key") ) if fish_secure_key == "": fish_secure_cipher = None return weechat.WEECHAT_RC_OK if fish_secure_key[:6] == "${sec.": decrypted = weechat.string_eval_expression( fish_secure_key, {}, {}, {} ) if decrypted: fish_secure_cipher = Blowfish(decrypted) return weechat.WEECHAT_RC_OK else: weechat.config_option_set(fish_config_option["key"], "", 0) weechat.prnt("", "Decrypt sec.conf first\n") return weechat.WEECHAT_RC_OK if fish_secure_key != "": fish_secure_cipher = Blowfish(fish_secure_key) 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 send(self, message): weechat.prnt(self.buffer, '%s%s\t%s' % (weechat.color("chat_nick_self"), self.server.get_option('login'), message)) recipient = self.login if self.fd is None else (':' + self.fd) self.server._ns_user_cmd_msg_user(recipient, message)
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 get_validated_key_from_config(setting): key = weechat.config_get_plugin(setting) if key != 'mask' and key != 'nick': weechat.prnt("", "Key %s not found. Valid settings are 'nick' and 'mask'. Reverted the setting to 'mask'" % key) weechat.config_set_plugin("clone_report_key", "mask") key = "mask" return key
def screen_away_timer_cb(buffer, args): '''Check if screen is attached, update awayness''' global AWAY, SOCK suffix = w.config_get_plugin('away_suffix') attached = os.access(SOCK, os.X_OK) # X bit indicates attached if attached and AWAY: w.prnt('', '%s: Screen attached. Clearing away status' % SCRIPT_NAME) for server, nick in get_servers(): w.command(server, "/away") if suffix and nick.endswith(suffix): nick = nick[:-len(suffix)] w.command(server, "/nick %s" % nick) AWAY = False elif not attached and not AWAY: w.prnt('', '%s: Screen detached. Setting away status' % SCRIPT_NAME) for server, nick in get_servers(): if suffix: w.command(server, "/nick %s%s" % (nick, suffix)); w.command(server, "/away %s" % w.config_get_plugin('message')); AWAY = True if w.config_get_plugin("command_on_detach"): w.command("", w.config_get_plugin("command_on_detach")) return w.WEECHAT_RC_OK
def process_complete(data, command, rc, stdout, stderr): url = stdout.strip() if url: color = weechat.color(weechat.config_get_plugin("color")) weechat.prnt(data, '%s[%s]' % (color, url)) return weechat.WEECHAT_RC_OK
def vdm_display(vdm): """ Display VDMs in buffer. """ global vdm_buffer weechat.buffer_set(vdm_buffer, "unread", "1") if weechat.config_get_plugin("number_as_prefix") == "on": separator = "\t" else: separator = " > " colors = weechat.config_get_plugin("colors").split(";"); vdm2 = vdm[:] if weechat.config_get_plugin("reverse") == "on": vdm2.reverse() for index, item in enumerate(vdm2): item_id = item["id"] item_text = item["text"] if sys.version_info < (3,): # python 2.x: convert unicode to str (in python 3.x, id and text are already strings) item_id = item_id.encode("UTF-8") item_text = item_text.encode("UTF-8") weechat.prnt_date_tags(vdm_buffer, 0, "notify_message", "%s%s%s%s%s" % (weechat.color(weechat.config_get_plugin("color_number")), item_id, separator, weechat.color(colors[0]), item_text)) colors.append(colors.pop(0)) if index == len(vdm) - 1: weechat.prnt(vdm_buffer, "------") elif weechat.config_get_plugin("blank_line") == "on": weechat.prnt(vdm_buffer, "")
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 wu_autoc(data, command, return_code, out, err): """ weather underground auto search """ global jname if return_code == w.WEECHAT_HOOK_PROCESS_ERROR: w.prnt("", "Error with command `%s'" % command) return w.WEECHAT_RC_OK if return_code > 0: w.prnt("", "return_code = %d" % return_code) if err != "": w.prnt("", "stderr: %s" % err) if out != "": i = json.loads(out) try: loc = next((l for l in i["RESULTS"] if l["type"] == "city"), None) if loc is None: weebuffer("Unable to locate query.") return w.WEECHAT_RC_OK except: weebuffer("Invalid query. Try again.") return w.WEECHAT_RC_OK jname = loc["name"] location = loc["l"] prefix = "[weatherbot] mode:" if mode == "conditions": cond_url = "url:http://api.wunderground.com/api/{}/conditions{}.json".format(options["apikey"], location) w.prnt("", '{} {} {}'.format(prefix, mode, location)) w.hook_process(cond_url, 30 * 1000, "wu_cond", "") if mode == "forecast": fore_url = "url:http://api.wunderground.com/api/{}/forecast{}.json".format(options["apikey"], location) w.prnt("", '{} {} {}'.format(prefix, mode, location)) w.hook_process(fore_url, 30 * 1000, "wu_fore", "") return w.WEECHAT_RC_OK
def message_private_irc(data, signal, signal_data): if jmh_verbose(): weechat.prnt('', 'private irc message received') message = parse_message(signal_data) message['type'] = 'highlight' log_event(message) return weechat.WEECHAT_RC_OK
def get_autojoin_list(server): ptr_config_autojoin = weechat.config_get("irc.server.%s.autojoin" % server) # option not found! server does not exist if not ptr_config_autojoin: weechat.prnt(buffer, "%s%s: server '%s' does not exist." % (weechat.prefix("error"), SCRIPT_NAME, server)) return weechat.WEECHAT_RC_OK # get value from autojoin option channels = weechat.config_string(ptr_config_autojoin) if not channels: return 1, 1 # check for keys if len(re.findall(r" ", channels)) == 0: list_of_channels = channels.split(",") list_of_keys = [] elif len(re.findall(r" ", channels)) == 1: list_of_channels2, list_of_keys = channels.split(" ") list_of_channels = list_of_channels2.split(",") else: weechat.prnt("", "%s%s: irc.server.%s.autojoin not valid..." % (weechat.prefix("error"), SCRIPT_NAME, server)) return 0, 0 return list_of_channels, list_of_keys
def prnt_error(self, message): try: weechat.prnt('', '%s%s' % (weechat.prefix('error'), message)) except: print(message)
import weechat import time import telegram bot = telegram.Bot(token='ADD YOUR TOKEN HERE') weechat.register("jackPing", "FlashCode", "1.0", "GPL3", "OH NO", "", "") weechat.prnt("", "Use without jack2 permition is not allowed") def i_am_author_of_message(buffer, nick): """Am I (the current WeeChat user) the author of the message?""" return weechat.buffer_get_string(buffer, 'localvar_nick') == nick def nick_that_sent_message(tags, prefix): for tag in tags: if tag.startswith('nick_'): return tag[5:] if prefix.startswith(('~', '&', '@', '%', '+', '-', ' ')): return prefix[1:] return prefix #process messages def message(data, bufferp, tm, tags, display, is_hilight, prefix, msg): nick = nick_that_sent_message(tags.split(','), prefix) if (is_hilight or weechat.buffer_get_string(bufferp, 'localvar_type') == 'private') and not(i_am_author_of_message(bufferp, nick)): mes = '<' + nick_that_sent_message(tags.split(','), prefix) + '>: ' +msg if weechat.buffer_get_string(bufferp, 'localvar_type') != 'private': mes = weechat.buffer_get_string(bufferp, 'short_name') + ': ' + mes bot.send_message(chat_id=SET CHAT ID, text=mes) return weechat.WEECHAT_RC_OK
def bad_command(buf): """Print an error message about the command.""" weechat.prnt(buf, ("[" + NAME + "] Bad option for /" + NAME + " " "command, try '/help " + NAME + "' for more info.")) return weechat.WEECHAT_RC_OK
def print_error(message): weechat.prnt('', '%s%s: %s' % (weechat.prefix("error"), SCRIPT_NAME, message))
cmd_buffer = buffer cmd_stdout = "" cmd_stderr = "" cmd_hook_process = weechat.hook_process( "url:http://dominick.p.elu.so/fun/kaomoji/get.php", 10000, "smile_cb", "") return weechat.WEECHAT_RC_OK def smile_cb(data, command, rc, stdout, stderr): global cmd_hook_process, cmd_buffer, cmd_stdout, cmd_stderr cmd_stdout += stdout cmd_stderr += stderr if int(rc) >= 0: if cmd_stderr != "": weechat.prnt(cmd_buffer, "%s" % cmd_stderr) if cmd_stdout != "": h = HTMLParser.HTMLParser() sm = h.unescape(cmd_stdout) weechat.command(cmd_buffer, sm.encode('utf-8')) cmd_hook_process = "" return weechat.WEECHAT_RC_OK if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, "", ""): if import_error: weechat.prnt("", "You need to run this script inside weechat.") weechat.hook_command(SCRIPT_NAME, SCRIPT_DESC, "༼つ ◕_◕ ༽つ", "", "", "smile_cmd", "")
SCRIPT_DESC, "", ""): for option, default_value in settings.items(): if not w.config_is_set_plugin(option): w.config_set_plugin(option, default_value) w.hook_command( "fileaway", "Set away status based on presense or absense of a file.", "check, msg [status], interval [time], file [filepath], or enable|disable", "check - manually checks for file rather than waiting for interval.\n" "msg [status] - sets the away message" "interval [time] - sets the interval to check for the file.\n" "file [filepath] - sets the file to be watched.\n" "enable|disable - enables or disables plugin.\n", "check" " || msg" " || interval" " || file %(filename)" " || enable" " || disable", "fileaway_cb", "") check_timer() if (w.config_get_plugin('status') == '0'): w.prnt( '', "fileaway is currently disabled. Type /fileaway enable to enable it." ) else: w.prnt( '', "fileaway is currently enabled. Type /fileaway disable to disable it." )
def theme_cmd(data, buffer, args): """Callback for /theme command.""" if args == '': weechat.command('', '/help %s' % SCRIPT_COMMAND) return weechat.WEECHAT_RC_OK argv = args.strip().split(' ', 1) if len(argv) == 0: return weechat.WEECHAT_RC_OK if argv[0] in ('list', 'install'): weechat.prnt('', '%s: action "%s" not developed' % (SCRIPT_NAME, argv[0])) return weechat.WEECHAT_RC_OK # check arguments if len(argv) < 2: if argv[0] in ('install', 'installfile', 'save', 'export'): weechat.prnt( '', '%s: too few arguments for action "%s"' % (SCRIPT_NAME, argv[0])) return weechat.WEECHAT_RC_OK # execute asked action if argv[0] == 'info': filename = None if len(argv) >= 2: filename = argv[1] theme = Theme(filename) if filename: theme.info('Info about theme "%s":' % filename) else: theme.info('Info about current theme:') elif argv[0] == 'show': filename = None if len(argv) >= 2: filename = argv[1] theme = Theme(filename) if filename: theme.show('Content of theme "%s":' % filename) else: theme.show('Content of current theme:') elif argv[0] == 'installfile': theme = Theme() theme.save(theme_config_get_undo()) theme = Theme(argv[1]) if theme.isok(): theme.install() elif argv[0] == 'undo': theme = Theme(theme_config_get_undo()) if theme.isok(): theme.install() elif argv[0] == 'save': theme = Theme() theme.save(argv[1]) elif argv[0] == 'backup': theme = Theme() theme.save(theme_config_get_backup()) elif argv[0] == 'restore': theme = Theme(theme_config_get_backup()) if theme.isok(): theme.install() elif argv[0] == 'export': htheme = HtmlTheme() whitebg = False htmlfile = argv[1] argv2 = args.strip().split(' ', 2) if len(argv2) >= 3 and argv2[1] == 'white': whitebg = True htmlfile = argv2[2] htheme.save_html(htmlfile, whitebg) return weechat.WEECHAT_RC_OK
def say(s, buffer=''): """normal msg""" prnt(buffer, '%s\t%s' % (script_nick, s))
def docgen_cmd_cb(data, buf, args): """Callback for /docgen command.""" if args: locales = args.split(' ') else: locales = LOCALE_LIST commands = get_commands() options = get_options() infos = get_infos() infos_hashtable = get_infos_hashtable() infolists = get_infolists() hdata = get_hdata() completions = get_completions() url_options = get_url_options() irc_colors = get_irc_colors() plugins_priority = get_plugins_priority() # get path and replace ~ by home if needed path = weechat.config_get_plugin('path') if path.startswith('~'): path = os.environ['HOME'] + path[1:] # write to doc files, by locale num_files = defaultdict(int) num_files_updated = defaultdict(int) # pylint: disable=undefined-variable translate = lambda s: (s and _(s)) or s escape = lambda s: s.replace('|', '\\|') for locale in locales: for key in num_files: if key != 'total2': num_files[key] = 0 num_files_updated[key] = 0 trans = gettext.translation('weechat', weechat.info_get('weechat_localedir', ''), languages=[locale + '.UTF-8'], fallback=True) trans.install() directory = path + '/' + locale[0:2] + '/autogen' if not os.path.isdir(directory): weechat.prnt('', '{0}docgen error: directory "{1}" does not exist' ''.format(weechat.prefix('error'), directory)) continue # write commands for plugin in commands: filename = directory + '/user/' + plugin + '_commands.asciidoc' tmpfilename = filename + '.tmp' _file = open(tmpfilename, 'w') for command in sorted(commands[plugin]): _cmd = commands[plugin][command] args = translate(_cmd['args']) args_formats = args.split(' || ') desc = translate(_cmd['description']) args_desc = translate(_cmd['args_description']) _file.write('[[command_{0}_{1}]]\n'.format(plugin, command)) _file.write('[command]*`{0}`* {1}::\n\n'.format(command, desc)) _file.write('----\n') prefix = '/' + command + ' ' if args_formats != ['']: for fmt in args_formats: _file.write(prefix + fmt + '\n') prefix = ' ' * len(prefix) if args_desc: _file.write('\n') for line in args_desc.split('\n'): _file.write(line + '\n') _file.write('----\n\n') _file.close() update_file(filename, tmpfilename, num_files, num_files_updated, 'commands') # write config options for config in options: filename = directory + '/user/' + config + '_options.asciidoc' tmpfilename = filename + '.tmp' _file = open(tmpfilename, 'w') for section in sorted(options[config]): for option in sorted(options[config][section]): _opt = options[config][section][option] opt_type = _opt['type'] string_values = _opt['string_values'] default_value = _opt['default_value'] opt_min = _opt['min'] opt_max = _opt['max'] null_value_allowed = _opt['null_value_allowed'] desc = translate(_opt['description']) type_nls = translate(opt_type) values = '' if opt_type == 'boolean': values = 'on, off' elif opt_type == 'integer': if string_values: values = string_values.replace('|', ', ') else: values = '{0} .. {1}'.format(opt_min, opt_max) elif opt_type == 'string': if opt_max <= 0: values = _('any string') elif opt_max == 1: values = _('any char') elif opt_max > 1: values = '{0} ({1}: {2})'.format(_('any string'), _('max chars'), opt_max) else: values = _('any string') default_value = '"{0}"'.format( default_value.replace('"', '\\"')) elif opt_type == 'color': values = _('a WeeChat color name (default, black, ' '(dark)gray, white, (light)red, ' '(light)green, brown, yellow, (light)blue, ' '(light)magenta, (light)cyan), a terminal ' 'color number or an alias; attributes are ' 'allowed before color (for text color ' 'only, not background): \"*\" for bold, ' '\"!\" for reverse, \"/\" for italic, ' '\"_\" for underline') _file.write('* [[option_{0}.{1}.{2}]] *{3}.{4}.{5}*\n' ''.format(config, section, option, config, section, option)) _file.write('** {0}: `{1}`\n'.format(_('description'), desc)) _file.write('** {0}: {1}\n'.format(_('type'), type_nls)) _file.write('** {0}: {1} ({2}: `{3}`)\n' ''.format(_('values'), values, _('default value'), default_value)) if null_value_allowed: _file.write('** {0}\n' ''.format( _('undefined value allowed (null)'))) _file.write('\n') _file.close() update_file(filename, tmpfilename, num_files, num_files_updated, 'options') # write infos hooked filename = directory + '/plugin_api/infos.asciidoc' tmpfilename = filename + '.tmp' _file = open(tmpfilename, 'w') _file.write('[width="100%",cols="^1,^2,6,6",options="header"]\n') _file.write('|===\n') _file.write('| {0} | {1} | {2} | {3}\n\n' ''.format(_('Plugin'), _('Name'), _('Description'), _('Arguments'))) for plugin in sorted(infos): for info in sorted(infos[plugin]): _inf = infos[plugin][info] desc = translate(_inf['description']) args_desc = translate(_inf['args_description'] or '-') _file.write('| {0} | {1} | {2} | {3}\n\n' ''.format(escape(plugin), escape(info), escape(desc), escape(args_desc))) _file.write('|===\n') _file.close() update_file(filename, tmpfilename, num_files, num_files_updated, 'infos') # write infos (hashtable) hooked filename = directory + '/plugin_api/infos_hashtable.asciidoc' tmpfilename = filename + '.tmp' _file = open(tmpfilename, 'w') _file.write('[width="100%",cols="^1,^2,6,6,6",options="header"]\n') _file.write('|===\n') _file.write('| {0} | {1} | {2} | {3} | {4}\n\n' ''.format(_('Plugin'), _('Name'), _('Description'), _('Hashtable (input)'), _('Hashtable (output)'))) for plugin in sorted(infos_hashtable): for info in sorted(infos_hashtable[plugin]): _inh = infos_hashtable[plugin][info] desc = translate(_inh['description']) args_desc = translate(_inh['args_description']) output_desc = translate(_inh['output_description']) or '-' _file.write('| {0} | {1} | {2} | {3} | {4}\n\n' ''.format(escape(plugin), escape(info), escape(desc), escape(args_desc), escape(output_desc))) _file.write('|===\n') _file.close() update_file(filename, tmpfilename, num_files, num_files_updated, 'infos_hashtable') # write infolists hooked filename = directory + '/plugin_api/infolists.asciidoc' tmpfilename = filename + '.tmp' _file = open(tmpfilename, 'w') _file.write('[width="100%",cols="^1,^2,5,5,5",options="header"]\n') _file.write('|===\n') _file.write('| {0} | {1} | {2} | {3} | {4}\n\n' ''.format(_('Plugin'), _('Name'), _('Description'), _('Pointer'), _('Arguments'))) for plugin in sorted(infolists): for infolist in sorted(infolists[plugin]): _inl = infolists[plugin][infolist] desc = translate(_inl['description']) pointer_desc = translate(_inl['pointer_description']) or '-' args_desc = translate(_inl['args_description']) or '-' _file.write('| {0} | {1} | {2} | {3} | {4}\n\n' ''.format(escape(plugin), escape(infolist), escape(desc), escape(pointer_desc), escape(args_desc))) _file.write('|===\n') _file.close() update_file(filename, tmpfilename, num_files, num_files_updated, 'infolists') # write hdata hooked filename = directory + '/plugin_api/hdata.asciidoc' tmpfilename = filename + '.tmp' _file = open(tmpfilename, 'w') for plugin in sorted(hdata): for hdata_name in sorted(hdata[plugin]): _hda = hdata[plugin][hdata_name] desc = translate(_hda['description']) variables = _hda['vars'] variables_update = _hda['vars_update'] lists = _hda['lists'] _file.write('* \'{0}\': {1}\n'.format(escape(hdata_name), escape(desc))) _file.write('** {0}: {1}\n'.format(_('plugin'), escape(plugin))) _file.write('** {0}:\n{1}'.format(_('variables'), escape(variables))) if variables_update: _file.write('** {0}:\n{1}'.format( _('update allowed'), escape(variables_update))) if lists: _file.write('** {0}:\n{1}'.format(_('lists'), escape(lists))) _file.close() update_file(filename, tmpfilename, num_files, num_files_updated, 'hdata') # write completions hooked filename = directory + '/plugin_api/completions.asciidoc' tmpfilename = filename + '.tmp' _file = open(tmpfilename, 'w') _file.write('[width="65%",cols="^1,^2,8",options="header"]\n') _file.write('|===\n') _file.write('| {0} | {1} | {2}\n\n' ''.format(_('Plugin'), _('Name'), _('Description'))) for plugin in sorted(completions): for completion_item in sorted(completions[plugin]): _cmp = completions[plugin][completion_item] desc = translate(_cmp['description']) _file.write('| {0} | {1} | {2}\n\n' ''.format(escape(plugin), escape(completion_item), escape(desc))) _file.write('|===\n') _file.close() update_file(filename, tmpfilename, num_files, num_files_updated, 'completions') # write url options filename = directory + '/plugin_api/url_options.asciidoc' tmpfilename = filename + '.tmp' _file = open(tmpfilename, 'w') _file.write('[width="100%",cols="2,^1,7",options="header"]\n') _file.write('|===\n') _file.write('| {0} | {1} | {2}\n\n' ''.format(_('Option'), _('Type'), _('Constants') + ' ^(1)^')) for option in url_options: constants = option['constants'] if constants: constants = ' ' + constants _file.write('| {0} | {1} |{2}\n\n' ''.format(escape(option['name']), escape(option['type']), escape(constants))) _file.write('|===\n') _file.close() update_file(filename, tmpfilename, num_files, num_files_updated, 'url_options') # write IRC colors filename = directory + '/user/irc_colors.asciidoc' tmpfilename = filename + '.tmp' _file = open(tmpfilename, 'w') _file.write('[width="30%",cols="^2m,3",options="header"]\n') _file.write('|===\n') _file.write('| {0} | {1}\n\n' ''.format(_('IRC color'), _('WeeChat color'))) for color in irc_colors: _file.write('| {0} | {1}\n' ''.format(escape(color['color_irc']), escape(color['color_weechat']))) _file.write('|===\n') _file.close() update_file(filename, tmpfilename, num_files, num_files_updated, 'irc_colors') # write plugins priority filename = directory + '/plugin_api/plugins_priority.asciidoc' tmpfilename = filename + '.tmp' _file = open(tmpfilename, 'w') for priority in sorted(plugins_priority, reverse=True): plugins = ', '.join(sorted(plugins_priority[priority])) _file.write('. {0} ({1})\n'.format(escape(plugins), priority)) _file.close() update_file(filename, tmpfilename, num_files, num_files_updated, 'plugins_priority') # write counters weechat.prnt('', 'docgen: {0}: {1} files, {2} updated' ''.format(locale, num_files['total1'], num_files_updated['total1'])) weechat.prnt('', 'docgen: total: {0} files, {1} updated' ''.format(num_files['total2'], num_files_updated['total2'])) return weechat.WEECHAT_RC_OK
def prnt(self, message): try: weechat.prnt('', message) except: print(message)
def sprint(message, buffer=""): weechat.prnt(buffer, "%s: %s" % (SCRIPT_NAME, message))
def debug(s, *args): if not isinstance(s, basestring): s = str(s) if args: s = s % args prnt('', '%s\t%s' % (script_nick, s))
def options_cb(data, buffer, args): """ Script configuration callback """ if not args: weechat.command("", "/help %s" % SCRIPT_COMMAND) args = args.strip().split(' ') opt = args[0] opt_args = args[1:] if opt == 'otp': if opt_args: servers = [opt_args[0]] else: servers = enabled_servers() for server in servers: otp = generate_totp(server, buffer=buffer) if otp: sprint("%s = %s" % (server, otp), buffer) elif opt == 'list': sprint("List of configured servers", buffer) for server in enabled_servers(): weechat.prnt(buffer, " - %s [enabled]" % server) for server in disabled_servers(): weechat.prnt(buffer, " - %s [disabled]" % server) elif opt == 'add': if len(opt_args) >= 2: if opt_args[0] not in enabled_servers( ) and opt_args[0] in get_irc_servers(): #weechat.command("", "/secure set %s_seed %s" % (opt_args[0], opt_args[1])) try: add_server(opt_args[0], opt_args[1:]) sprint("server '%s' was successfully added" % opt_args[0], buffer) except Exception as ex: sprint("invalid TOTP seed provided", buffer) elif opt_args[0] not in get_irc_servers(): sprint( "No server named '%s' was found, see /help server" % opt_args[0], buffer) else: sprint( "OTP already configured for '%s', to change <seed> remove the existing one first." % opt_args[0], buffer) else: sprint( "/uotp -- invalid argument, valid command is /uotp add <server> <seed>", buffer) elif opt == 'remove': if opt_args[0] in enabled_servers() or opt_args[0] in disabled_servers( ): remove_server(opt_args[0], True) sprint("server '%s' was successfully removed" % opt_args[0], buffer) else: sprint("failed to remove server, '%s' not found" % opt_args[0], buffer) elif opt == 'enable': if opt_args and opt_args[0] not in enabled_servers(): if opt_args[0] in get_irc_servers(): add_server(opt_args[0]) sprint("server '%s' was successfully enabled" % opt_args[0], buffer) else: sprint( "No server named '%s' was found, see /help server" % opt_args[0], buffer) else: sprint("OTP is already enabled for the server '%s'." % opt_args[0], buffer) elif opt == 'disable': if opt_args and opt_args[0] in enabled_servers(): remove_server(opt_args[0]) else: sprint("OTP does not seem to be enabled for '%s'" % opt_args[0], buffer) elif opt: sprint("/uotp: invalid option -- '%s'" % opt, buffer) weechat.command("", "/help %s" % SCRIPT_COMMAND) return weechat.WEECHAT_RC_OK
elif list_args[0] == "list": print_excemptions() else: weechat.command("", "/help " + SCRIPT_COMMAND) return WEECHAT_RC_OK if (__name__ == '__main__' and import_ok and weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, '', '')): weechat_version = weechat.info_get("version_number", "") or 0 if int(weechat_version) >= 0x01000000: config_init() CURRENT_BUFFER = weechat.current_buffer() weechat.hook_signal("buffer_switch", "switch_buffer_cb", "") weechat.hook_signal("*,irc_in2_*", "unhide_buffer_cb", "") weechat.hook_command( SCRIPT_NAME, SCRIPT_DESC, "add $buffer_name | del { $buffer_name | $list_position } | list", " add : Add $buffer_name to the list of excemptions\n" " $buffer_name can be either #channel or server_name.#channel" " del : Delete $buffer_name from the list of excemptions\n" " list : Return a list of all buffers that should not become hidden.", "add|del|list", "command_cb", "") else: weechat.prnt( "", "{}{} requires WeeChat version 1.0 or higher".format( weechat.prefix('error'), SCRIPT_NAME))
def _debug(text): if w.config_string_to_boolean(w.config_get_plugin("debug")): w.prnt("", text)
def print_debug(message): if weechat.config_get_plugin('debug') == 'on': weechat.prnt("", "%s DEBUG: %s" % (SCRIPT_NAME, message))
def out(string): w.prnt('', '{}'.format(string))
def server_completion_cb(data, completion_item, buffer, completion): """ Enabled or disabled server completion callback. """ print_debug("completion " + ', '.join(globals()[data]())) for server in globals()[data](): weechat.hook_completion_list_add(completion, server, 0, weechat.WEECHAT_LIST_POS_SORT) return weechat.WEECHAT_RC_OK if __name__ == "__main__" and import_ok: if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, "", ""): version = weechat.info_get("version_number", "") or 0 if int(version) < 0x00040200: weechat.prnt( "", "%s requires WeeChat >= 0.4.2 for secure_data support." % SCRIPT_NAME) weechat.command("", "/wait 1ms /python unload %s" % SCRIPT_NAME) weechat.hook_command( SCRIPT_COMMAND, "Generate a One-Time Password (TOTP) for service authentication or login on connect.", "otp [server] || list || add <server> <seed> || remove <server> || enable <server> || disable <server>", " otp: generate one-time password for one or all servers\n" + " list: list configured servers\n" + " add: add one-time password (TOTP) seed for an existing irc server\n" + " remove: delete one-time password configuration for a server\n" + " enable: re-enable one-time password authentication for a server\n" + "disable: disable one-time password authentiction without removing the seed for a server\n\n"
def urlserver_server_fd_cb(data, fd): """Callback for server socket.""" global urlserver, urlserver_settings if not urlserver['socket']: return weechat.WEECHAT_RC_OK conn, addr = urlserver['socket'].accept() if urlserver_settings['debug'] == 'on': weechat.prnt('', 'urlserver: connection from %s' % str(addr)) if urlserver_settings['http_allowed_ips'] and \ not re.match(urlserver_settings['http_allowed_ips'], addr[0]): if urlserver_settings['debug'] == 'on': weechat.prnt('', 'urlserver: IP not allowed') conn.close() return weechat.WEECHAT_RC_OK data = None try: conn.settimeout(0.3) data = conn.recv(4096).decode('utf-8') data = data.replace('\r\n', '\n') except: return weechat.WEECHAT_RC_OK replysent = False sort = '-time' referer = re.search('^Referer:', data, re.MULTILINE | re.IGNORECASE) m = re.search('^GET /(.*) HTTP/.*$', data, re.MULTILINE) if m: url = m.group(1) if urlserver_settings['debug'] == 'on': weechat.prnt('', 'urlserver: %s' % m.group(0)) if 'favicon.' in url: urlserver_server_reply(conn, '200 OK', '', urlserver_server_favicon(), mimetype='image/x-icon') replysent = True else: # check if prefix is ok (if prefix defined in settings) prefixok = True if urlserver_settings['http_url_prefix']: if url.startswith(urlserver_settings['http_url_prefix']): url = url[len(urlserver_settings['http_url_prefix']):] if url.startswith('/'): url = url[1:] else: prefixok = False # prefix ok, go on with url if prefixok: if url.startswith('sort='): # sort asked for list of urls sort = url[5:] url = '' if url: # short url, read base62 key and redirect to page number = -1 try: number = base62_decode(url) except: pass if number >= 0 and number in urlserver['urls']: authok = ( urlserver_settings['http_auth_redirect'] != 'on' or urlserver_check_auth(data)) if authok: # if we have a referer in request, use meta for # redirection (so that referer is not sent) # otherwise, we can make redirection with HTTP 302 if referer: urlserver_server_reply( conn, '200 OK', '', '<meta name="referrer" content="never">\n' '<meta http-equiv="refresh" content="0; ' 'url=%s">' % urlserver['urls'][number][3]) else: conn.sendall('HTTP/1.1 302\r\n' 'Location: {}\r\n\r\n'.format( urlserver['urls'][number] [3]).encode('utf-8')) else: urlserver_server_reply_auth_required(conn) replysent = True else: # page with list of urls if urlserver_check_auth(data): urlserver_server_reply_list(conn, sort) else: urlserver_server_reply_auth_required(conn) replysent = True else: if urlserver_settings['debug'] == 'on': weechat.prnt('', 'urlserver: prefix missing') if not replysent: urlserver_server_reply( conn, '404 Not found', '', '<html>\n' '<head><title>Page not found</title></head>\n' '<body><h1>Page not found</h1></body>\n' '</html>') conn.close() return weechat.WEECHAT_RC_OK
# "moderate" : -1, # "low": -2 #} """ Init """ for option, (default_value, description) in settings.items(): if w.config_get_plugin(option) == "": w.config_set_plugin(option, default_value) if description: w.config_set_desc_plugin(option, description) if w.config_get_plugin("apikey") == "": w.prnt( "", "You haven't set your API key. Use /set " "plugins.var.python.nma.apikey \"you_nma_api_token\" to fix that.") """ Hooks """ # Hook command w.hook_command( "nma", "Activate NotifyMyAndroid notifications", "on | off", """ on : Activate notifications off : Deactivate notifications\n """, "on || off", "nma_cmd_cb", "") # Hook privmsg/hilights w.hook_print("", "irc_privmsg", "", 1, "priv_msg_cb", "") from pynma import PyNMA
def prnt(self, name, verbose=True): weechat.prnt("", " %s = %s" % (name.ljust(11), self.data[name]))
def error(string): w.prnt('', '{} ERROR: {}'.format(CMD, string))
def printc(msg): weechat.prnt("", msg)
global version if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, '', ''): version = weechat.info_get('version_number', '') or 0 # get weechat version (1.0) and store it if int(version) >= 0x01000000: weechat.hook_command(SCRIPT_NAME,SCRIPT_DESC, 'enable|on||' 'disable|off||' 'toggle||' 'show', ' enable/on: enable logging on current buffer, with default log-level (note: log-level from localvar will be used, if possible)\n' 'disable/off: disable logging on current buffer (note: log-level is stored in localvar)\n' ' toggle: will toggle logging on current buffer\n' ' show: will print current log-level to buffer (default)\n' '\n' 'Examples:\n' ' /log toggle', 'enable||' 'disable||' 'on||' 'off||' 'toggle||' 'show', 'log_cmd_cb', '') else: weechat.prnt('','%s%s %s' % (weechat.prefix('error'),SCRIPT_NAME,': needs version 1.0 or higher')) weechat.command('','/wait 1ms /python unload %s' % SCRIPT_NAME)
# sending notifications when channel or private buffer is # already opened import weechat, string, urllib, urllib2 weechat.register( "notifo", "ochameau", "0.1", "GPL", "notifo: Send push notifications to your iPhone/Android about your private messages and highlights.", "", "") credentials = {"username": "", "api_secret": ""} for option, default_value in credentials.items(): if weechat.config_get_plugin(option) == "": weechat.prnt( "", weechat.prefix("error") + "notifo: Please set option: %s" % option) weechat.prnt( "", "notifo: /set plugins.var.python.notifo.%s STRING" % option) # Hook privmsg/hilights weechat.hook_print("", "irc_privmsg", "", 1, "notify_show", "") # Functions def notify_show(data, bufferp, uber_empty, tagsn, isdisplayed, ishilight, prefix, message): if (bufferp == weechat.current_buffer()): pass
def urlGrabPrint(message): bufferd = weechat.current_buffer() if urlGrabSettings['output_main_buffer'] == 1: weechat.prnt("", "[%s] %s" % (SCRIPT_NAME, message)) else: weechat.prnt(bufferd, "[%s] %s" % (SCRIPT_NAME, message))
def wg_show_script(name): """ Show detailed info about a script (in repository). For example: Script: weeget.py, version 0.7, license: GPL3 Author: Sebastien Helleu <flashcode [at] flashtux [dot] org> Status: installed, running Date: added: 2009-04-05, updated: 2009-09-07 URL: http://www.weechat.org/files/scripts/weeget.py MD5: 4b0458dd5cc5c9a09ba8078f89830869 Desc: Scripts manager. Tags: scripts Requires: python 2.5 Min: 0.3.0 """ if len(wg_scripts) == 0: return script = wg_search_script_by_name(name) if script == None: weechat.prnt( "", "%s: script \"%s%s%s\" not found" % (SCRIPT_NAME, wg_config_color("script"), name, weechat.color("chat"))) else: weechat.prnt("", "") weechat.prnt( "", " Script: %s%s%s, version %s, license: %s" % (wg_config_color("script"), script["full_name"], weechat.color("chat"), script["version"], script["license"])) weechat.prnt("", " Author: %s <%s>" % (script["author"], script["mail"])) status = wg_get_local_script_status(script) str_status = "not installed" if status["installed"]: str_status = "installed" if status["running"]: str_status += ", running" else: str_status += ", not running" if status["obsolete"]: str_status += " (new version available)" weechat.prnt("", " Status: %s" % str_status) date_added = script.get("added", "")[:10] str_updated = script.get("updated", "") if str_updated != "": date_updated = script["updated"][:10] if date_updated == "0000-00-00" or date_updated == date_added: str_updated = "" if str_updated != "": weechat.prnt( "", " Date: added: %s, updated: %s" % (date_added, date_updated)) else: weechat.prnt("", " Date: added: %s" % date_added) weechat.prnt("", " URL: %s" % script.get("url", "")) weechat.prnt("", " MD5: %s" % script.get("md5sum", "")) weechat.prnt("", " Desc: %s" % script.get("desc_en", "")) weechat.prnt("", " Tags: %s" % script.get("tags", "")) str_requires = script.get("requirements", "") if str_requires == "": str_requires = "(nothing)" weechat.prnt("", "Requires: %s" % str_requires) vmin = script.get("min_weechat", "") vmax = script.get("max_weechat", "") if vmin != "": weechat.prnt("", " Min: %s" % vmin) if vmax != "": weechat.prnt("", " Max: %s" % vmax)
def say(s, prefix=None, buffer=''): """normal msg""" prefix = prefix or script_nick weechat.prnt(buffer, '%s\t%s' % (prefix, s))
def wg_list_scripts(search, installed=False): """ List all scripts (with optional search string). If installed == True, then list only installed scripts. For each script, display status (installed/running/new version available), name of script, language and description. For example: ir buffers pl Sidebar with list of buffers. i N go py Quick jump to buffers. i weetris pl Tetris-like game. """ global wg_scripts search = search.strip().lower() scripts_matching = wg_search_scripts(search) if len(scripts_matching) == 0: weechat.prnt("", "%s: no script found" % SCRIPT_NAME) else: weechat.prnt("", "") if search != "": if installed: weechat.prnt("", "Scripts installed matching \"%s\":" % search) else: weechat.prnt( "", "Scripts for WeeChat %s matching \"%s\":" % (weechat.info_get("version", ""), search)) else: if installed: weechat.prnt("", "Scripts installed:") else: weechat.prnt( "", "Scripts for WeeChat %s:" % weechat.info_get("version", "")) sorted_scripts = sorted(scripts_matching.items(), key=lambda s: s[1]["name"]) length_max_name = 0 for item in sorted_scripts: length = len(item[1]["name"]) if length > length_max_name: length_max_name = length str_format = "%%s%%s%%s%%s%%s%%s%%s %%s%%-%ds %%s%%-3s %%s%%s" \ % length_max_name for item in sorted_scripts: script = item[1] str_installed = " " str_running = " " str_obsolete = " " status = wg_get_local_script_status(script) if installed and not status["installed"]: continue if status["installed"]: str_installed = "i" if status["running"]: str_running = "r" if status["obsolete"]: str_obsolete = "N" weechat.prnt( "", str_format % (wg_config_color("installed"), str_installed, wg_config_color("running"), str_running, wg_config_color("obsolete"), str_obsolete, weechat.color("chat"), wg_config_color("script"), script["name"], wg_config_color("language"), SCRIPT_EXTENSION[script["language"]], weechat.color("chat"), script["desc_en"]))
def list_signature_line(data, buffer, args): weechat.prnt("", "Items in signature list:") for each in signature_list: weechat.prnt("", " " + each) return weechat.WEECHAT_RC_OK