def whois_data_bitlbee(data, signal, signal_data): nick = signal_data.split()[3] ind = signal_data.decode("utf8").rindex(':') realname = signal_data[ind+1:] if nick in nicksToRename: nicksToRename.remove(nick) namespl = realname.split() namejoin = "" firstname = namespl[0].decode("utf8") lastname = namespl[-1].decode("utf8") for s in namespl: s = s.decode("utf8") namejoin += s ircname = utf8Replace(namejoin) if len(ircname) > 24: namejoin = "" for s in namespl: s = s.decode("utf8") if s == firstname or s == lastname: namejoin += s else: namejoin += s[0] ircname = utf8Replace(namejoin)[:24] if ircname != nick: weechat.command(weechat.buffer_search("irc", bitlbeeBuffer), "/msg %s rename %s %s" % (bitlbeeChannel, nick, ircname)) weechat.command(weechat.buffer_search("irc", bitlbeeBuffer), "/msg %s save" % (bitlbeeChannel)) return weechat.WEECHAT_RC_OK
def renderConversations(unused, command, return_code, out, err): global conversation_map global conv if return_code == weechat.WEECHAT_HOOK_PROCESS_ERROR: weechat.prnt("", "Error with command '%s'" % command) return weechat.WEECHAT_RC_OK if return_code > 0: weechat.prnt("", "return_code = %d" % return_code) if out != '': conv += out if return_code == weechat.WEECHAT_HOOK_PROCESS_RUNNING: weechat.prnt('', 'getting more data') return weechat.WEECHAT_RC_OK if err != "": weechat.prnt("", "stderr: %s" % err) return weechat.WEECHAT_RC_OK try: conversations = reversed(cPickle.loads(conv)) except EOFError: weechat.prnt('', 'wtrecv returned garbage') return weechat.WEECHAT_RC_OK for conversation in conversations: if not conversation.conv_id in conversation_map: conversation_map[conversation.conv_id] = conversation msgs = conversation.messages else: old = conversation_map[conversation.conv_id] conversation_map[conversation.conv_id] = conversation msgs = old.new_messages(conversation) for msg in msgs: if not conversation.number in number_map and msg['from'] != 'Me:': number_map[conversation.number] = msg['from'] for msg in msgs: if conversation.number in number_map: buf = weechat.buffer_search('python', number_map[conversation.number][:-1]) if not buf: buf = weechat.buffer_new(number_map[conversation.number][:-1], "textOut", "", "buffer_close_cb", "") else: buf = weechat.buffer_search('python', 'Me') if not buf: buf = weechat.buffer_new('Me', "textOut", "", "buffer_close_cb", "") if weechat.config_get_plugin('encrypt_sms') == 'True': msg['text'] = decrypt(msg['text'], buf) nick = msg['from'][:-1].strip() tags = 'notify_private,nick_' + msg['from'][:-1].strip() tags += ',log1,prefix_nick_' + weechat.info_get('irc_nick_color_name', nick) nick = msg['from'][:-1].strip() weechat.prnt_date_tags(buf, 0, tags, '\x03' + weechat.info_get('irc_nick_color', nick) + nick + '\t' + msg['text']) conv = '' callGV() return weechat.WEECHAT_RC_OK
def gvOut(data, buf, input_data): if input_data[:4] == 'text' and buf == weechat.buffer_search('python', 'weeText'): buffer = weechat.buffer_new("+1"+input_data[5:], "textOut", "", "buffer_close_cb", "") if input_data[:5] == 'multi' and buf == weechat.buffer_search('python', 'weeText'): num_list = input_data[6:].split(',') nums = '' for num in num_list: nums += '+' + num[-4:] nums = nums[1:] buffer = weechat.buffer_new('m:' + nums, "multiText", input_data[6:], "buffer_close_cb", "") return weechat.WEECHAT_RC_OK
def parseTinyurl( file ): turl = None for line in file: if( line.startswith("http://tinyurl.com") ): turl = line break if turl is None: weechat.prnt( weechat.buffer_search("",""), "-TinyUrl- Error: Unrecognized response from server" ) weechat.prnt( weechat.buffer_search("",""), " Maybe tinyurl.com changed their format again." ) weechat.prnt( weechat.buffer_search("",""), " Try '/tinyurl service ln-s' to use ln-s.net instead" ) return turl
def tinyurlShutdown(): """Cleanup - Kills any leftover child processes""" if len(tinyurlProcessList.keys()) > 0: weechat.prnt( weechat.buffer_search("",""), "-TinyUrl- Cleaning up unfinished processes:" ) for pid in tinyurlProcessList.keys(): weechat.prnt( weechat.buffer_search("",""), " Process %d" % pid ) try: os.kill(pid, 9) os.waitpid( pid, 0 ) except: weechat.prnt( weechat.buffer_search("",""), " Cleanup failed, skipping" ) return weechat.WEECHAT_RC_OK
def whois_data_bitlbee(data, signal, signal_data): nick = signal_data.split()[3] realname = signal_data[signal_data.rindex(':')+1:] if nick in nicksToRename: nicksToRename.remove(nick) ircname = re.sub("[^A-Za-z0-9]", "", realname)[:24] if ircname != nick: weechat.command(weechat.buffer_search("irc", bitlbeeBuffer), "/msg %s rename %s %s" % (bitlbeeChannel, nick, ircname)) weechat.command(weechat.buffer_search("irc", bitlbeeBuffer), "/msg %s save" % (bitlbeeChannel)) return weechat.WEECHAT_RC_OK
def whois_cb(data, signal, signal_data): """function for /WHOIS""" if not get_config_boolean('show_in_whois') or not check_database(): return WEECHAT_RC_OK nick, user, host = signal_data.split()[3:6] server = signal[:signal.find(',')] #debug('%s | %s | %s' %(data, signal, signal_data)) buffer = weechat.buffer_search('irc', '%s.%s' %(server, nick)) if weechat.config_string(weechat.config_get('irc.msgbuffer.whois')) != "private" or buffer == "": buffer = weechat.buffer_search('irc', 'server.%s' %server) host = get_ip_from_userhost(user, host) print_country(host, buffer, quiet=True, broken=True, nick=nick) return WEECHAT_RC_OK
def parseLns( file ): turl = None for line in file: (code, message) = line.split(" ", 2) if code == "200": return message.rstrip() elif code == "503": # Try again, respawn curl weechat.prnt( weechat.buffer_search("",""), "-TinyUrl- Warning: ln-s.net is busy, trying again shortly" ) raise TryAgain(line) else: weechat.prnt( weechat.buffer_search("",""), "-TinyUrl- Error: Error response from server: %s" % (line) ) return None
def tinyurlGet( name = "" ): """Gets a variable value""" if name == "": weechat.prnt( weechat.buffer_search("",""), "-TinyUrl- Get all:" ) for name in tinyurlParams: weechat.prnt( weechat.buffer_search("",""), " %s = %s" % (name, weechat.config_get_plugin(name)) ) else: weechat.prnt( weechat.buffer_search("",""), "-TinyUrl- Get:" ) if name in tinyurlParams: weechat.prnt( weechat.buffer_search("",""), " %s = %s" % (name, weechat.config_get_plugin(name)) ) else: weechat.prnt( weechat.buffer_search("",""), " Unknown parameter \"%s\", try '/help tinyurl'" % name ) return
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 kickban_callback(data, times_left): details = data.split(":") buffer_ptr = weechat.buffer_search("irc", details[0]) if buffer_ptr: weechat.command(buffer_ptr, "/unban " + details[1]) return weechat.WEECHAT_RC_OK
def send_messages(server, channel, nick): buffer = w.buffer_search("", "%s.%s" % (server, channel)) messages = postpone_data[server][channel][nick] for time, msg in messages: tstr = strftime("%Y-%m-%d %H:%M:%S", time.timetuple()) w.command(buffer, msg + " (This message has been postponed on " + tstr + ".)") messages[:] = []
def _getBuffer(self): # we need to always search the buffer, since there's no close callback we can't know if the # buffer was closed. buffer = weechat.buffer_search('python', self.__name__) if not buffer: buffer = self.create() return buffer
def jmh_cmd_jabber_echo_message(data, buffer, args=None): """ Command /jabber_echo_message """ argv = [] try: argv = args.split(None, 1) except: pass if not args or len(argv) < 2: weechat.prnt("", 'jabber_echo_message - ERROR: Invalid usage.') weechat.prnt("", ' See /help jabber_echo_message') return weechat.WEECHAT_RC_OK server = argv[0] message = ' '.join(argv[1:]) jabber_buffer = weechat.buffer_search("python", 'jabber.server.{s}'.format(s=server)) if not jabber_buffer: weechat.prnt("", 'jabber_echo_message - ERROR: Server "{s}" not found.'.format( s=server)) weechat.prnt("", ' For list of servers, use /jabber') return weechat.WEECHAT_RC_OK weechat.prnt_date_tags(jabber_buffer, int(time.time()), "notify_private", message) return weechat.WEECHAT_RC_OK
def my_modifier_cb(data, modifier, modifier_data, string): if w.buffer_get_string(w.buffer_search('irc',modifier_data.split(";")[1]),"localvar_noirccolors") == "true": try: nick, message = string.split("\t") except ValueError, e: return string return "%s\t%s" % (nick, w.string_remove_color(message,""))
def attach_buffer(self): channel_buffer = w.buffer_search("", "%s.%s" % (self.server.domain, self.name)) if channel_buffer != main_weechat_buffer: self.channel_buffer = channel_buffer # w.buffer_set(self.channel_buffer, "highlight_words", self.server.nick) else: self.channel_buffer = None
def minesweeper_init(): """Init minesweeper: create buffer, adjust zoom, new game.""" global minesweeper if minesweeper['buffer']: return minesweeper['buffer'] = weechat.buffer_search('python', 'minesweeper') if not minesweeper['buffer']: minesweeper['buffer'] = weechat.buffer_new('minesweeper', 'minesweeper_input_buffer', '', 'minesweeper_close_buffer', '') if minesweeper['buffer']: weechat.buffer_set(minesweeper['buffer'], 'type', 'free') weechat.buffer_set(minesweeper['buffer'], 'title', 'Minesweeper! | alt-space or mouse-b1: explore, alt-f or mouse-b2: flag, alt-n: new game, ' 'alt-+/-: adjust board zoom | ' 'Command line: (n)ew, +/-: change size, (q)uit') weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta2-A', '/minesweeper up') weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta2-B', '/minesweeper down') weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta2-D', '/minesweeper left') weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta2-C', '/minesweeper right') weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta-f', '/minesweeper flag') weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta- ', '/minesweeper explore') weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta-n', '/minesweeper new') weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta-+', '/minesweeper zoom') weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta--', '/minesweeper dezoom') weechat.buffer_set(minesweeper['buffer'], 'key_bind_meta-c', '/minesweeper cheat') if minesweeper['buffer']: minesweeper_adjust_zoom() minesweeper_new_game()
def process_presence_change(message_json): buffer_name = "%s.%s" % (domain, message_json["user"]) buf_ptr = w.buffer_search("", buffer_name) if message_json["presence"] == 'active': users.find(message_json["user"]).set_active() else: users.find(message_json["user"]).set_inactive()
def customize_join_cb_signal(data, signal, signal_data): weechat.prnt("", "data: %s signal: %s signal_data: %s" % (data, signal, signal_data)) message = weechat.config_get_plugin("join_message") if message == "": return weechat.WEECHAT_RC_OK parsed = get_hashtable(signal_data) if parsed["nick"] == own_nick(signal.split(",", 1)[0]): return weechat.WEECHAT_RC_OK parsed["message"] = "" # dummy. no message for JOIN parsed["kicked_nick"] = "" # dummy. no KICK here message = create_output(message, parsed, "join") buffer_ptr = weechat.buffer_search("irc", "%s.%s" % (signal.split(",", 1)[0], parsed["channel"])) prefix = weechat.config_string(weechat.config_get("weechat.look.prefix_join")) prefix_color = weechat.color(weechat.config_color(weechat.config_get("weechat.color.chat_prefix_join"))) message_tags = "" if weechat.config_get_plugin("no_log").lower() == "on": message_tags = "no_log" weechat.prnt_date_tags(buffer_ptr, 0, message_tags, "%s%s\t%s" % (prefix_color, prefix, message)) return weechat.WEECHAT_RC_OK
def customize_join_cb(data, modifier, modifier_data, string): message = weechat.config_get_plugin("join_message") if message == "": return string parsed = get_hashtable(string) if parsed["nick"] == own_nick(modifier_data): return string parsed["message"] = "" # dummy. no message for irc_JOIN parsed["kicked_nick"] = "" # dummy. no irc_KICK here message = create_output(message, parsed, "join") if OPTIONS["debug"] == "on": weechat.prnt("", string) weechat.prnt("", parsed["channel"]) weechat.prnt("", parsed["message"]) buffer_ptr = weechat.buffer_search("irc", "%s.%s" % (modifier_data, parsed["channel"])) prefix = weechat.config_string(weechat.config_get("weechat.look.prefix_join")) prefix_color = weechat.color(weechat.config_color(weechat.config_get("weechat.color.chat_prefix_join"))) prefix = substitute_colors(prefix) message_tags = "" if weechat.config_get_plugin("no_log").lower() == "on": message_tags = "no_log" weechat.prnt_date_tags(buffer_ptr, 0, message_tags, "%s%s\t%s" % (prefix_color, prefix, message)) return string
def customize_kick_cb(data, modifier, modifier_data, string): message = weechat.config_get_plugin("kick_message") if message == "": return string parsed = get_hashtable(string) try: parsed["kicked_nick"] = parsed["arguments"].split(" ", 1)[1] parsed["kicked_nick"] = parsed["kicked_nick"].split(" :", 1)[0] except: parsed["kicked_nick"] = "" message = create_output(message, parsed, "kick") if OPTIONS["debug"] == "on": weechat.prnt("", string) weechat.prnt("", parsed["channel"]) weechat.prnt("", parsed["message"]) buffer_ptr = weechat.buffer_search("irc", "%s.%s" % (modifier_data, parsed["channel"])) if not (buffer_ptr): return string prefix = weechat.config_string(weechat.config_get("weechat.look.prefix_quit")) prefix_color = weechat.color(weechat.config_color(weechat.config_get("weechat.color.chat_prefix_quit"))) message_tags = "" if weechat.config_get_plugin("no_log").lower() == "on": message_tags = "no_log" weechat.prnt_date_tags(buffer_ptr, 0, message_tags, "%s%s\t%s" % (prefix_color, prefix, message)) return string
def bas_timer_buffer_opened_cb(data, remaining_calls): full_name = data buffer = weechat.buffer_search("==", full_name) if not buffer: return weechat.WEECHAT_RC_OK bas_apply_options_for_buffer(buffer) return weechat.WEECHAT_RC_OK
def customize_privmsg_cb(data, modifier, modifier_data, string): weechat.prnt("",data) weechat.prnt("",modifier) weechat.prnt("",modifier_data) weechat.prnt("",string) parsed = get_hashtable(string) message = parsed['message'].strip() # Filter out non-CTCP messages and non ACTION messages if not message or ord(message[0]) != 1 or not message[1:].startswith("ACTION"): return string text = message[8:-1] parsed['kicked_nick'] = '' # dummy. no irc_KICK here parsed['message'] = text message = create_output("${*blue}%N %M",parsed,'action') buffer_ptr = weechat.buffer_search('irc',"%s.%s" % (modifier_data,parsed['channel'])) prefix = weechat.config_string(weechat.config_get('weechat.look.prefix_action')) prefix_color = weechat.color(weechat.config_color(weechat.config_get('weechat.color.chat_prefix_action'))) prefix = substitute_colors(prefix) message_tags = '' if weechat.config_get_plugin('no_log').lower() == 'on': message_tags = 'no_log' weechat.prnt_date_tags(buffer_ptr,0,message_tags,'%s%s\t%s' % (prefix_color,prefix,message)) return string
def grabnick(servername, nick): if nick and servername: if OPTIONS['text']: t = Template( string_eval_expression(OPTIONS['text']) ) text = t.safe_substitute(server=servername, nick=nick) weechat.prnt(weechat.current_buffer(), text) weechat.command(weechat.buffer_search('irc','%s.%s' % ('server',servername)), OPTIONS['command'] % nick)
def customize_kick_cb(data, modifier, modifier_data, string): message = weechat.config_get_plugin('kick_message') if message == '': return string parsed = get_hashtable(string) try: parsed['kicked_nick'] = parsed['arguments'].split(' ', 1)[1] parsed['kicked_nick'] = parsed['kicked_nick'].split(' :', 1)[0] except: parsed['kicked_nick'] = '' message = create_output(message,parsed,'kick') if OPTIONS['debug'] == 'on': weechat.prnt("",string) weechat.prnt("",parsed['channel']) weechat.prnt("",parsed['message']) buf_pointer = weechat.buffer_search('irc',"%s.%s" % (modifier_data,parsed['channel'])) prefix = weechat.config_string(weechat.config_get('weechat.look.prefix_quit')) prefix_color = weechat.color(weechat.config_color(weechat.config_get('weechat.color.chat_prefix_quit'))) message_tags = '' if weechat.config_get_plugin('no_log').lower() == 'on': message_tags = 'no_log' weechat.prnt_date_tags(buf_pointer,0,message_tags,'%s%s\t%s' % (prefix_color,prefix,message)) return string
def customize_join_cb_signal(data, signal, signal_data): weechat.prnt("","data: %s signal: %s signal_data: %s" % (data,signal,signal_data)) message = weechat.config_get_plugin('join_message') if message == '': return weechat.WEECHAT_RC_OK parsed = get_hashtable(signal_data) if parsed['nick'] == own_nick(signal.split(',', 1)[0]): return weechat.WEECHAT_RC_OK parsed['message'] = "" # dummy. no message for JOIN parsed['kicked_nick'] = '' # dummy. no KICK here message = create_output(message,parsed,'join') buf_pointer = weechat.buffer_search('irc',"%s.%s" % (signal.split(',', 1)[0],parsed['channel'])) prefix = weechat.config_string(weechat.config_get('weechat.look.prefix_join')) prefix_color = weechat.color(weechat.config_color(weechat.config_get('weechat.color.chat_prefix_join'))) message_tags = '' if weechat.config_get_plugin('no_log').lower() == 'on': message_tags = 'no_log' weechat.prnt_date_tags(buf_pointer,0,message_tags,'%s%s\t%s' % (prefix_color,prefix,message)) return weechat.WEECHAT_RC_OK
def reorder_buffers(): """Reorders the buffers once the whitelist has changed """ count = 2 chan = "" ilist = weechat.infolist_get("buffer", "", "") for chan in whitelist: if -1 == chan.find(".#"): #network name is not set, matching by short_name weechat.infolist_reset_item_cursor(ilist) while weechat.infolist_next(ilist): if weechat.infolist_string(ilist, "short_name") == chan: chan = weechat.infolist_string(ilist, "name") break buff = weechat.buffer_search("irc", chan) if buff: weechat.buffer_set(buff, "number", str(count)) count += 1 weechat.infolist_free(ilist) return weechat.WEECHAT_RC_OK
def customize_part_cb(data, modifier, modifier_data, string): message = weechat.config_get_plugin('part_message') if message == '': return string parsed = get_hashtable(string) if parsed['nick'] == own_nick(modifier_data): return string parsed['kicked_nick'] = '' # dummy. no irc_KICK here message = create_output(message,parsed,'part') if OPTIONS['debug'] == 'on': weechat.prnt("","debug mode: irc_part") weechat.prnt("","string: %s" % string) weechat.prnt("",parsed['channel']) weechat.prnt("",parsed['message']) buf_pointer = weechat.buffer_search('irc',"%s.%s" % (modifier_data,parsed['channel'])) prefix = weechat.config_string(weechat.config_get('weechat.look.prefix_quit')) prefix_color = weechat.color(weechat.config_color(weechat.config_get('weechat.color.chat_prefix_quit'))) prefix = substitute_colors(prefix) message_tags = '' if weechat.config_get_plugin('no_log').lower() == 'on': message_tags = 'no_log' weechat.prnt_date_tags(buf_pointer,0,message_tags,'%s%s\t%s' % (prefix_color,prefix,message)) return string
def twitch_roomstate(data, modifier, server, string): message = weechat.info_get_hashtable( 'irc_message_parse', {"message": string}) buffer = weechat.buffer_search( "irc", "%s.%s" % (server, message['channel'])) for tag in message['tags'].split(';'): if tag == 'subs-only=0': weechat.buffer_set(buffer, 'localvar_set_subs', '') if tag == 'subs-only=1': weechat.buffer_set(buffer, 'localvar_set_subs', '1') if tag == 'r9k=0': weechat.buffer_set(buffer, 'localvar_set_r9k', '') if tag == 'r9k=1': weechat.buffer_set(buffer, 'localvar_set_r9k', '1') if tag == 'emote-only=0': weechat.buffer_set(buffer, 'localvar_set_emote', '') if tag == 'emote-only=1': weechat.buffer_set(buffer, 'localvar_set_emote', '1') if tag.startswith('slow='): value = tag.split('=')[-1] if value == '0': weechat.buffer_set(buffer, 'localvar_set_slow', '') if value > '0': weechat.buffer_set(buffer, 'localvar_set_slow', value) twitch_main('', buffer, 'bs') return ''
def unhighlight_cb(data, modifier, modifier_data, message): """Check if the line matches the unhighlight regular expression, and if it does, clear the message and reprint it with the no_highlight tag added.""" # Buffer names can have ; in them, but not plugins or tags (I HOPE), # so just split(';') would have weird edgecases with channels that have a ; # in the name. m = re.match("^(?P<plugin>\S+);(?P<full_name>\S+);(?P<tags>\S*)$", modifier_data) tags = m.group('tags') if 'no_highlight' in tags or 'notify_none' in tags: return message plugin = m.group('plugin') full_name = m.group('full_name') buffer = weechat.buffer_search(plugin, full_name) unhighlight_regex = weechat.buffer_get_string(buffer, 'localvar_unhighlight_regex') if not matches_unhighlight_strings(message, unhighlight_regex): return message # inspired by https://weechat.org/scripts/source/mass_hl_blocker.pl.html/ # this is terrible and gross but afaik there is no way to change the # highlight message once it's set and no way to interact with a message's # tags before highlights are checked. weechat.prnt_date_tags(buffer, 0, "%s,no_highlight" % tags, message) return ''
elif action == "add": add_to_nick_colours(arg_string) elif action == "colours": enter_buffer_screen('weechat_colours') elif action == "list": enter_buffer_screen('list') else: create_script_buffer() enter_buffer_screen('list') return weechat.WEECHAT_RC_OK def set_default_settings(): global config_settings, script_buff # Set default settings for option, default_value, description in config_settings: if not weechat.config_is_set_plugin(option): weechat.config_set_plugin(option, default_value) version = weechat.info_get("version_number", "") or 0 if int(version) >= 0x00030500: weechat.config_set_desc_plugin(option, description) if __name__ == "__main__" and import_ok: if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, "buffer_close_cb", ""): set_default_settings() script_buff = weechat.buffer_search("python", SCRIPT_BUFFERNAME) weechat.hook_command(SCRIPT_COMMAND, "Nick Colours", "", "", "", "buffer_command_main", "")
def grabnick(servername, nick): if nick: weechat.prnt(weechat.current_buffer(), OPTIONS['text'] % servername) weechat.command( weechat.buffer_search('irc', '%s.%s' % ('server', servername)), OPTIONS['command'] % nick)
def playback_cb(data, modifier, modifier_data, string): global COLOR_RESET, COLOR_CHAT_DELIMITERS, COLOR_CHAT_NICK, COLOR_CHAT_HOST, \ COLOR_CHAT_CHANNEL, COLOR_CHAT, COLOR_MESSAGE_JOIN, COLOR_MESSAGE_QUIT, \ COLOR_REASON_QUIT, SMART_FILTER global send_signals, znc_timestamp if modifier_data.startswith('0x'): buffer, tags = modifier_data.split(';', 1) plugin = weechat.buffer_get_string(buffer, 'plugin') buffer_name = weechat.buffer_get_string(buffer, 'name') else: plugin, buffer_name, tags = modifier_data.split(';', 2) buffer = weechat.buffer_search(plugin, buffer_name) if plugin != 'irc' or buffer_name == 'irc_raw': return string if tags: tags = set(tags.split(',')) else: tags = set() global buffer_playback if 'nick_***' in tags: line = string.partition('\t')[2] if line in ['Buffer Playback...', 'Backlog playback...']: weechat.hook_signal_send("znc-playback-start", WEECHAT_HOOK_SIGNAL_STRING, buffer_name) debug("* buffer playback for %s", buffer_name) get_config_options() nick_talked.clear() buffer_playback.add(buffer) elif line == 'Playback Complete.': buffer_playback.remove(buffer) debug("* end of playback for %s", buffer_name) weechat.hook_signal_send("znc-playback-stop", WEECHAT_HOOK_SIGNAL_STRING, buffer_name) tags.discard('notify_message') tags.discard('irc_privmsg') prnt_date_tags(buffer, 0, ','.join(tags), string) return '' elif buffer not in buffer_playback: return string #debug(string) def strip_timestamp(s): words = znc_timestamp.count(' ') + 1 p = 0 for i in range(words): p = s[p:].find(' ') + p + 1 return s[:p - 1], s[p:] prefix, s, line = string.partition('\t') if 'irc_action' in tags or 'irc_notice' in tags: _prefix, _, line = line.partition(' ') timestamp, line = strip_timestamp(line) line = '%s %s' % (_prefix, line) else: timestamp, line = strip_timestamp(line) try: t = time.strptime(timestamp, znc_timestamp) except ValueError as e: # bad time format. error(e) debug("Timestamp error: %s\n%s" % (modifier_data, string)) return string else: if t[0] == 1900: # only hour information, complete year, month and day with today's date # might be incorrect though if day changed during playback. t = datetime.time(*t[3:6]) d = datetime.datetime.combine(datetime.date.today(), t) else: d = datetime.datetime(*t[:6]) time_epoch = int(time.mktime(d.timetuple())) if 'nick_*buffextras' not in tags: # not a line coming from ZNC buffextras module. nick_talked.add((buffer, weechat.string_remove_color(prefix, ''))) prnt_date_tags(buffer, time_epoch, ','.join(tags), "%s\t%s" % (prefix, line)) return '' tags.discard('notify_message') tags.discard('irc_privmsg') tags.discard('nick_*buffextras') hostmask, s, line = line.partition(' ') nick = hostmask[:hostmask.find('!')] host = hostmask[len(nick) + 1:] server = weechat.buffer_get_string(buffer, 'localvar_server') channel = weechat.buffer_get_string(buffer, 'localvar_channel') s = None if line == 'joined': tags.add('irc_join') s = weechat.gettext("%s%s%s%s%s%s%s%s%s%s has joined %s%s%s") s = s % ( weechat.prefix('join'), COLOR_CHAT_NICK, # TODO there's a function for use nick's color nick, COLOR_CHAT_DELIMITERS, ' (', COLOR_CHAT_HOST, # TODO host can be hidden in config host, COLOR_CHAT_DELIMITERS, ')', COLOR_MESSAGE_JOIN, COLOR_CHAT_CHANNEL, channel, COLOR_MESSAGE_JOIN) if send_signals: weechat.hook_signal_send(server + ",irc_in_JOIN", WEECHAT_HOOK_SIGNAL_STRING, ":%s JOIN :%s" % (hostmask, channel)) elif line.startswith('parted with message:'): tags.add('irc_part') reason = line[line.find('[') + 1:-1] if reason: s = weechat.gettext( "%s%s%s%s%s%s%s%s%s%s has left %s%s%s %s(%s%s%s)") s = s % (weechat.prefix('quit'), COLOR_CHAT_NICK, nick, COLOR_CHAT_DELIMITERS, ' (', COLOR_CHAT_HOST, host, COLOR_CHAT_DELIMITERS, ')', COLOR_MESSAGE_QUIT, COLOR_CHAT_CHANNEL, channel, COLOR_MESSAGE_QUIT, COLOR_CHAT_DELIMITERS, COLOR_REASON_QUIT, reason, COLOR_CHAT_DELIMITERS) if send_signals: weechat.hook_signal_send( server + ",irc_in_PART", WEECHAT_HOOK_SIGNAL_STRING, ":%s PART %s :%s" % (hostmask, channel, reason)) else: s = weechat.gettext("%s%s%s%s%s%s%s%s%s%s has left %s%s%s") s = s % (weechat.prefix('quit'), COLOR_CHAT_NICK, nick, COLOR_CHAT_DELIMITERS, ' (', COLOR_CHAT_HOST, host, COLOR_CHAT_DELIMITERS, ')', COLOR_MESSAGE_QUIT, COLOR_CHAT_CHANNEL, channel, COLOR_MESSAGE_QUIT) if send_signals: weechat.hook_signal_send(server + ",irc_in_PART", WEECHAT_HOOK_SIGNAL_STRING, ":%s PART %s" % (hostmask, channel)) elif line.startswith('quit with message:'): tags.add('irc_quit') reason = line[line.find('[') + 1:-1] s = weechat.gettext("%s%s%s%s%s%s%s%s%s%s has quit %s(%s%s%s)") s = s % (weechat.prefix('quit'), COLOR_CHAT_NICK, nick, COLOR_CHAT_DELIMITERS, ' (', COLOR_CHAT_HOST, host, COLOR_CHAT_DELIMITERS, ')', COLOR_MESSAGE_QUIT, COLOR_CHAT_DELIMITERS, COLOR_REASON_QUIT, reason, COLOR_CHAT_DELIMITERS) # QUIT messages should be sent only once, but since there's # one quit per channel, use PART instead. if send_signals: if not reason: weechat.hook_signal_send(server + ",irc_in_PART", WEECHAT_HOOK_SIGNAL_STRING, ":%s PART %s" % (hostmask, channel)) else: weechat.hook_signal_send( server + ",irc_in_PART", WEECHAT_HOOK_SIGNAL_STRING, ":%s PART %s :%s" % (hostmask, channel, reason)) elif line.startswith('is now known as '): tags.add('irc_nick') new_nick = line.rpartition(' ')[-1] s = weechat.gettext("%s%s%s%s is now known as %s%s%s") s = s % (weechat.prefix('network'), COLOR_CHAT_NICK, nick, COLOR_CHAT, COLOR_CHAT_NICK, new_nick, COLOR_CHAT) # NICK messages should be sent only once, but since there's one # per every channel, we fake it with a PART/JOIN if send_signals: new_hostmask = new_nick + hostmask[hostmask.find('!'):] weechat.hook_signal_send(server + ",irc_in_PART", WEECHAT_HOOK_SIGNAL_STRING, ":%s PART %s" % (hostmask, channel)) weechat.hook_signal_send(server + ",irc_in_JOIN", WEECHAT_HOOK_SIGNAL_STRING, ":%s JOIN :%s" % (new_hostmask, channel)) elif line.startswith('set mode: '): tags.add('irc_mode') modes = line[line.find(':') + 2:] s = weechat.gettext("%sMode %s%s %s[%s%s%s]%s by %s%s") s = s % (weechat.prefix('network'), COLOR_CHAT_CHANNEL, channel, COLOR_CHAT_DELIMITERS, COLOR_CHAT, modes, COLOR_CHAT_DELIMITERS, COLOR_CHAT, COLOR_CHAT_NICK, nick) if send_signals: # buffextras can send an invalid hostmask "nick!@" sometimes # fix it so at least is valid. if not is_hostmask(hostmask): nick = hostmask[:hostmask.find('!')] hostmask = nick + '!unknow@unknow' weechat.hook_signal_send( server + ",irc_in_MODE", WEECHAT_HOOK_SIGNAL_STRING, ":%s MODE %s %s" % (hostmask, channel, modes)) elif line.startswith('kicked'): tags.add('irc_kick') _, nick_kicked, reason = line.split(None, 2) reason = reason[reason.find('[') + 1:-1] s = weechat.gettext("%s%s%s%s has kicked %s%s%s %s(%s%s%s)") s = s % (weechat.prefix('quit'), COLOR_CHAT_NICK, nick, COLOR_MESSAGE_QUIT, COLOR_CHAT_NICK, nick_kicked, COLOR_MESSAGE_QUIT, COLOR_CHAT_DELIMITERS, COLOR_CHAT, reason, COLOR_CHAT_DELIMITERS) if send_signals: weechat.hook_signal_send( server + ",irc_in_KICK", WEECHAT_HOOK_SIGNAL_STRING, ":%s KICK %s %s :%s" % (hostmask, channel, nick_kicked, reason)) elif line.startswith('changed the topic to: '): tags.add('irc_topic') topic = line[line.find(':') + 2:] s = weechat.gettext( "%s%s%s%s has changed topic for %s%s%s to \"%s%s\"") s = s % (weechat.prefix('network'), COLOR_CHAT_NICK, nick, COLOR_CHAT, COLOR_CHAT_CHANNEL, channel, COLOR_CHAT, topic, COLOR_CHAT) # crude smart filter if SMART_FILTER and (buffer, nick) not in nick_talked \ and ('irc_join' in tags \ or 'irc_part' in tags \ or 'irc_quit' in tags \ or 'irc_nick' in tags): tags.add('irc_smart_filter') if s is None: error('Unknown message from ZNC: %r' % string) return string else: prnt_date_tags(buffer, time_epoch, ','.join(tags), s) return ''
weechat.config_set_desc_plugin( ttt_option, '%s (default: "%s")' % (ttt_value[1], ttt_value[0])) # mouse support weechat.key_bind('mouse', tictactoe_mouse_keys) weechat.hook_hsignal('tictactoe_mouse', 'tictactoe_mouse_cb', '') # detect config changes weechat.hook_config('plugins.var.python.%s.*' % SCRIPT_NAME, 'tictactoe_config_cb', '') # add command weechat.hook_command( SCRIPT_COMMAND, 'Tic-tac-toe game.', '', 'Instructions:\n' ' - enter one digit, or click with mouse in an empty cell to ' 'play\n' ' - you must align 3 symbols: horizontally, vertically or ' 'diagonally\n' ' - you win if you align the symbols before the computer\n' ' - there is a draw game if 3 symbols are not aligned at the end ' '(for you or computer).\n' '\n' 'Keys:\n' ' alt-n: new game, you start\n' ' alt-c: new game, computer begins', '', 'tictactoe_cmd_cb', '') # if buffer already exists (after /upgrade), initialize tictactoe if weechat.buffer_search('python', 'tictactoe'): tictactoe_init()
option, '%s (default: "%s")' % (value[2], value[0])) minesweeper_set_colors() # mouse support if int(version) >= 0x00030600: weechat.key_bind('mouse', minesweeper_mouse_keys) weechat.hook_hsignal('minesweeper_mouse', 'minesweeper_mouse_cb', '') # detect config changes weechat.hook_config('plugins.var.python.%s.*' % SCRIPT_NAME, 'minesweeper_config_cb', '') # add command weechat.hook_command( SCRIPT_COMMAND, 'Minesweeper game.', '[16col|256col]', '16col: set colors using basic colors (if your terminal or your WeeChat does not support 256 colors)\n' '256col: set colors using 256 colors mode (default)\n\n' '256 colors mode is highly recommended (WeeChat >= 0.3.5).\n' 'Mouse is recommended (WeeChat >= 0.3.6).\n\n' 'Instructions:\n' '- use mouse left button (or alt-space) to explore a square, if you think there is no mine under ' '(if there is a mine, you lose!)\n' '- use mouse right button (or alt-f) to put/remove flag on square, if you think there is a mine under\n' '- you win if you put all flags on mines, of if all squares without mine are explored.\n\n' 'Good luck!', '16col|256col', 'minesweeper_cmd_cb', '') # if buffer already exists (after /upgrade), init minesweeper if weechat.buffer_search('python', 'minesweeper'): minesweeper_init()
def channel_has_nick(server, channel, nick): buffer = w.buffer_search("", "%s.%s" % (server, channel)) return bool(w.nicklist_search_nick(buffer, "", nick))
def renderConversations(unused, command, return_code, out, err): global conversation_map global conv if return_code == weechat.WEECHAT_HOOK_PROCESS_ERROR: weechat.prnt("", "Error with command '%s'" % command) return weechat.WEECHAT_RC_OK if return_code > 0: weechat.prnt("", "return_code = %d" % return_code) if out != '': conv += out if return_code == weechat.WEECHAT_HOOK_PROCESS_RUNNING: weechat.prnt('', 'getting more data') return weechat.WEECHAT_RC_OK if err != "": weechat.prnt("", "stderr: %s" % err) return weechat.WEECHAT_RC_OK try: conversations = reversed(cPickle.loads(conv)) except EOFError: weechat.prnt('', 'wtrecv returned garbage') return weechat.WEECHAT_RC_OK for conversation in conversations: if not conversation.conv_id in conversation_map: conversation_map[conversation.conv_id] = conversation msgs = conversation.messages else: old = conversation_map[conversation.conv_id] conversation_map[conversation.conv_id] = conversation msgs = old.new_messages(conversation) for msg in msgs: if not conversation.number in number_map and msg['from'] != 'Me:': number_map[conversation.number] = msg['from'] for msg in msgs: if conversation.number in number_map: buf = weechat.buffer_search( 'python', number_map[conversation.number][:-1]) if not buf: buf = weechat.buffer_new( number_map[conversation.number][:-1], "textOut", "", "buffer_close_cb", "") else: buf = weechat.buffer_search('python', 'Me') if not buf: buf = weechat.buffer_new('Me', "textOut", "", "buffer_close_cb", "") if weechat.config_get_plugin('encrypt_sms') == 'True': msg['text'] = decrypt(msg['text'], buf) nick = msg['from'][:-1].strip() tags = 'notify_private,nick_' + msg['from'][:-1].strip() tags += ',log1,prefix_nick_' + weechat.info_get( 'irc_nick_color_name', nick) nick = msg['from'][:-1].strip() weechat.prnt_date_tags( buf, 0, tags, '\x03' + weechat.info_get('irc_nick_color', nick) + nick + '\t' + msg['text']) conv = '' callGV() return weechat.WEECHAT_RC_OK
' /set plugins.var.python.urlserver.http_auth "user:password"\n' ' - if you do not like the default HTML formatting, you can override the CSS:\n' ' /set plugins.var.python.urlserver.http_css_url "http://example.com/sample.css"\n' ' See https://raw.github.com/FiXato/weechat_scripts/master/urlserver/sample.css\n' ' - don\'t like the built-in HTTP server to start automatically? Disable it:\n' ' /set plugins.var.python.urlserver.http_autostart "off"\n' ' - have external port 80 or 443 (https) forwarded to your internal server port? Remove :port with:\n' ' /set plugins.var.python.urlserver.http_port_display "80" or "443" respectively\n' '\n' 'Tip: use URL without key at the end to display list of all URLs in your browser.', 'start|restart|stop|status|clear', 'urlserver_cmd_cb', '') if urlserver_settings['http_autostart'] == 'on': # start mini HTTP server urlserver_server_start() # load urls from file urlserver_read_urls() # catch URLs in buffers weechat.hook_print('', '', '://', 1, 'urlserver_print_cb', '') # modify URLS in irc messages (for relay) weechat.hook_modifier('irc_in2_privmsg', 'urlserver_modifier_irc_cb', '') weechat.hook_modifier('irc_in2_notice', 'urlserver_modifier_irc_cb', '') # search buffer urlserver['buffer'] = weechat.buffer_search('python', SCRIPT_BUFFER)
global urlbuf_buffer urlbuf_buffer = None return weechat.WEECHAT_RC_OK if __name__ == "__main__" and import_ok: if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, "urlbuf2_close_cb", ""): version = weechat.info_get('version_number', '') or 0 # Set default settings for option, default_value in urlbuf_settings.items(): if not weechat.config_is_set_plugin(option): weechat.config_set_plugin(option, default_value[0]) if int(version) >= 0x00030500: weechat.config_set_desc_plugin(option, default_value[1]) urlbuf_buffer = weechat.buffer_search("python", "urlbuf") if not urlbuf_buffer: # Create urlbuf. Sets notify to 0 as this buffer does not need to # be in hotlist. urlbuf_buffer = weechat.buffer_new("urlbuf", "urlbuf_input_cb", \ "", "urlbuf_close_cb", "") weechat.buffer_set(urlbuf_buffer, "title", "URL buffer") weechat.buffer_set(urlbuf_buffer, "notify", "0") weechat.buffer_set(urlbuf_buffer, "nicklist", "0") # Hook all public and private messages (some may think this is too limiting) weechat.hook_print("", "notify_message", "", 1, "urlbuf_print_cb", "") weechat.hook_print("", "notify_private", "", 1, "urlbuf_print_cb", "")
for option, value in samegame_settings_default.items(): if weechat.config_is_set_plugin(option): samegame_settings[option] = weechat.config_get_plugin(option) else: weechat.config_set_plugin(option, value[0]) samegame_settings[option] = value[0] weechat.config_set_desc_plugin( option, '%s (default: "%s")' % (value[1], value[0])) samegame_set_colors() # mouse support weechat.key_bind('mouse', samegame_mouse_keys) weechat.hook_hsignal('samegame_mouse', 'samegame_mouse_cb', '') # detect config changes weechat.hook_config('plugins.var.python.%s.*' % SCRIPT_NAME, 'samegame_config_cb', '') # add command weechat.hook_command( SCRIPT_COMMAND, 'Samegame.', '', 'Instructions:\n' '- click on a group of adjoining blocks of the same color to remove them from the screen\n' '- blocks that are no longer supported will fall down, and a column without any blocks will be trimmed away by other columns sliding to the left\n' '- your score is increased by (N-1)², where N is the number of blocks removed by your click\n' '- the game ends when you can not play any more.', '', 'samegame_cmd_cb', '') # if buffer already exists (after /upgrade), init samegame if weechat.buffer_search('python', 'samegame'): samegame_init()
def fn_command(data, buffer, args): global bfList global muted args = args.split() myStatus = "on" mySound = "" myBuffer = "" if len(args) > 0: try: # set a valid buffer and soundfile myArg = args[1] myBuffer = w.buffer_search("irc", myArg) if myBuffer == "": # no buffer with that name, so so assume it's the soundfile mySound = myArg myBuffer = w.current_buffer() else: # we have a buffer, now look for a soundfile try: mySound = args[2] except: mySound = "" except: # no further arguments, so set valid buffer + sound myBuffer = w.current_buffer() mySound = settings["psound"] myBuffer = w.buffer_get_string(myBuffer, "name") if args[0] == "test": if settings["psound"] == "": errMsg("No sound defined! Please set 'psound'-option!") else: s.Popen([settings["player"], expanduser(mySound)], stderr=s.STDOUT, stdout=s.PIPE) elif args[0] == "list": for lEntry in bfList: alert("BUFFER: " + lEntry["buffer"] + " | " + "STATUS: " + lEntry["status"] + " | " + "SOUND: " + lEntry["sound"]) if len(bfList) == 0: errMsg("No buffers configured!") elif args[0] == "muteall": muted = True alert("All buffers are muted") elif args[0] == "demuteall": muted = False alert("Sounds will be played") elif args[0] == "add": for listIndex in range(len(bfList)): if bfList[listIndex]["buffer"] == myBuffer: bfList.pop(listIndex) break bfList += [{ "buffer": myBuffer, "status": myStatus, "sound": mySound }] if settings["psound"] == "": settings["psound"] = mySound w.config_set_plugin("psound", mySound) w.config_set_plugin("buffers", fn_createBufferString()) elif args[0] == "remove": for listIndex in range(len(bfList)): if bfList[listIndex]["buffer"] == myBuffer: bfList.pop(listIndex) break w.config_set_plugin("buffers", fn_createBufferString()) elif args[0] == "on": for listIndex in range(len(bfList)): if bfList[listIndex]["buffer"] == myBuffer: bfList[listIndex]["status"] = "on" w.config_set_plugin("buffers", fn_createBufferString()) break elif args[0] == "off": for lIndex in range(len(bfList)): if bfList[lIndex]["buffer"] == myBuffer: bfList[lIndex]["status"] = "off" w.config_set_plugin("buffers", fn_createBufferString()) break return w.WEECHAT_RC_OK
def create_local_buffer(self): if not w.buffer_search("", self.domain): self.buffer = w.buffer_new(self.domain, "buffer_input_cb", "", "", "") w.buffer_set(self.buffer, "nicklist", "1")
def cs_set_default_settings(): global cs_settings # Set default settings for option, default_value, description in cs_settings: if not weechat.config_is_set_plugin(option): weechat.config_set_plugin(option, default_value) version = weechat.info_get("version_number", "") or 0 if int(version) >= 0x00030500: weechat.config_set_desc_plugin(option, description) if __name__ == "__main__" and import_ok: if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, SCRIPT_CLOSE_CB, ""): cs_set_default_settings() cs_buffer = weechat.buffer_search("python", "clone_scanner") weechat.hook_signal("*,irc_in2_join", "on_join_scan_cb", "") weechat.hook_command( SCRIPT_COMMAND, SCRIPT_DESC, "[scan] [[plugin.][network.]channel] | [help]", "the target_buffer can be: \n" "- left out, so the current channel buffer will be scanned.\n" "- a plain channel name, such as #weechat, in which case it will prefixed with the current network name\n" "- a channel name prefixed with network name, such as Freenode.#weechat\n" "- a channel name prefixed with plugin and network name, such as irc.freenode.#weechat\n" "See /set plugins.var.python.clone_scanner.* for all possible configuration options", " || scan %(buffers_names)" " || help", "cs_command_main", "")
def update_nicklist(buffer_name): buffer_pointer = weechat.buffer_search('irc', buffer_name) if not buffer_pointer: return group_pointers = {} infolist = weechat.infolist_get('nicklist', buffer_pointer, '') infolist_string = weechat.infolist_string infolist_next = weechat.infolist_next while infolist_next(infolist): if not infolist_string(infolist, 'type') == 'nick': continue nick = infolist_string(infolist, 'name') if nick not in ident_nick: continue group = infolist_string(infolist, 'group_name') color = infolist_string(infolist, 'color') prefix = infolist_string(infolist, 'prefix') prefix_color = infolist_string(infolist, 'prefix_color') if ident_nick[nick]: prefix_new = ' ' group_new = '080|ident' color_new = 'green' else: prefix_new = '~' group_new = '081|unident' color_new = 'brown' prefix_color = 'cyan' if prefix[0] != prefix_new[0]: if prefix == ' ': prefix = prefix_new prefix_new = '' elif prefix_new != ' ': prefix = prefix_new + prefix prefix_new = '' if color == 'bar_fg': color = color_new color_new = '' if group[:2] == '08': group = group_new group_new = '' try: group_pointer = group_pointers[group] except KeyError: group_pointer = weechat.nicklist_search_group( buffer_pointer, '', group) if not group_pointer: group_pointer = weechat.nicklist_add_group( buffer_pointer, '', group, 'weechat.color.nicklist_group', 1) group_pointers[group] = group_pointer else: group_pointer = weechat.nicklist_search_group( buffer_pointer, '', group) if prefix_new and group_new and color_new: # nothing to change continue #debug('adding nick: %s%s to %s' %(prefix, nick, group)) nick_pointer = weechat.nicklist_search_nick(buffer_pointer, '', nick) if nick_pointer: weechat.nicklist_remove_nick(buffer_pointer, nick_pointer) nick_pointer = weechat.nicklist_add_nick(buffer_pointer, group_pointer, nick, color, prefix, prefix_color, 1) nicklist[buffer_name, nick] = (buffer_pointer, nick_pointer) weechat.infolist_free(infolist)
def timer_cb(data, remaining_calls): return w.command(w.buffer_search("irc", data.split(' ')[0]), "/say %s" % ' '.join(data.split(' ')[1:]))
def buf_get(pssName, typ, name, known): haveBzz = False # \todo integrity check of input data bufname = buf_generate_name(pssName, typ, name) wOut( PSS_BUFPFX_DEBUG, [], "!!!", "generated bufname " + bufname + " for " + pssName + " / " + typ + " / " + name) try: buf = weechat.buffer_search("python", bufname) # \todo re-evaluate why exception can occur here, and which one specifically except Exception as e: return "" if pssName in bzzs: haveBzz = True elif typ == "room": raise RuntimeException("gateway needed for multiuser chats over swarm") if buf == "": shortname = "" # chat is DM between two parties if typ == "chat": ispubkey = False if known: shortname = "pss:" + name else: shortname = "pss:" + name[:8] ispubkey = True buf = weechat.buffer_new(bufname, "buf_in", pssName, "buf_close", pssName) weechat.buffer_set(buf, "short_name", shortname) weechat.buffer_set( buf, "title", name + " @ PSS '" + pssName + "' | node: " + weechat.config_get_plugin(psses[pssName].host + "_url") + ":" + weechat.config_get_plugin(psses[pssName].port + "_port") + " | key " + pss.label(psses[pssName].key) + " | address " + pss.label(psses[pssName].base)) weechat.buffer_set(buf, "hotlist", weechat.WEECHAT_HOTLIST_PRIVATE) weechat.buffer_set(buf, "display", "1") plugin = weechat.buffer_get_pointer(buf, "plugin") bufs[bufname] = buf debugstr = "have " + repr( psses[pssName].have_account()) + " + " + repr(haveBzz) wOut(PSS_BUFPFX_DEBUG, [], "have", debugstr) if psses[pssName].have_account() and haveBzz: pubkey = "" if ispubkey: pubkey = name.decode("hex") else: pubkey = remotekeys[name].decode("hex") pubkey = "\x04" + pubkey try: feeds[bufname] = pss.Feed( bzzs[pssName].agent, psses[pssName].get_account(), PSS_BUFTYPE_CHAT + pss.publickey_to_account(pubkey)) wOut( PSS_BUFPFX_DEBUG, [], "", "added feed with topic " + feeds[bufname].topic.encode("hex")) except ValueError as e: wOut(PSS_BUFPFX_ERROR, [], "???", "could not set up feed: " + str(e)) # room is multiuser conversation elif typ == "room": shortname = "pss#" + name buf = weechat.buffer_new(bufname, "buf_in", pssName, "buf_close", pssName) weechat.buffer_set(buf, "short_name", shortname) weechat.buffer_set( buf, "title", "#" + name + " @ PSS '" + pssName + "' | node: " + weechat.config_get_plugin(psses[pssName].host + "_url") + ":" + weechat.config_get_plugin(psses[pssName].port + "_port") + " | key " + pss.label(psses[pssName].key) + " | address " + pss.label(psses[pssName].base)) weechat.buffer_set(buf, "hotlist", weechat.WEECHAT_HOTLIST_PRIVATE) weechat.buffer_set(buf, "nicklist", "1") weechat.buffer_set(buf, "display", "1") #weechat.nicklist_add_group(buf, "", "me", "weechat.color.nicklist_group", 1) #weechat.nicklist_add_nick(buf, "me", psses[pssName].name, "bar_fg", "", "bar_fg", 1) plugin = weechat.buffer_get_pointer(buf, "plugin") bufs[bufname] = buf if len(rooms) == 0: hookTimers.append( weechat.hook_timer(roomPeriod, 0, 0, "roomRead", psses[pssName].name)) rooms[bufname] = pss.Room(bzzs[pssName], name, psses[pssName].get_account()) # \todo test load first, only init if not found try: roomhsh = rooms[bufname].get_state_hash() rooms[bufname].load(roomhsh, psses[pssName].get_account()) wOut( PSS_BUFPFX_DEBUG, [], "", "loaded room with topic " + rooms[bufname].feed_out.topic.encode("hex") + " account " + rooms[bufname].feed_out.account.address.encode("hex") + " roomfeed " + rooms[bufname].feed_room.topic.encode("hex")) for k, p in rooms[bufname].participants.iteritems(): nick = "" if p.key == selfs[pssName].key: nick = selfs[pssName].nick else: if not p.key in nicks: nicks[p.nick] = pss.PssContact( p.nick, p.key, p.addr, p.src) remotekeys[p.key] = p.nick nick = nicks[p.key].nick buf_room_add(buf, nick) # \todo correct expect to disambiguate unexpected fails except Exception as e: wOut(PSS_BUFPFX_DEBUG, [], "", "fail room load: " + str(e)) rooms[bufname].start(PSS_DEFAULT_NICK) wOut( PSS_BUFPFX_DEBUG, [], "", "added room with topic " + rooms[bufname].feed_out.topic.encode("hex") + " account " + rooms[bufname].feed_out.account.address.encode("hex") + " roomfeed " + rooms[bufname].feed_room.topic.encode("hex")) else: raise RuntimeError("invalid buffer type") return buf
def dlog(message): dlog_buffer = weechat.buffer_search('python', 'WeeChatBot') for ln in message.split("\n"): weechat.prnt(dlog_buffer, 'bot | ' + ln) return weechat.WEECHAT_RC_OK
def lb_set_default_settings(): global lb_settings # Set default settings for option, default_value, description in lb_settings: if not weechat.config_is_set_plugin(option): weechat.config_set_plugin(option, default_value) version = weechat.info_get("version_number", "") or 0 if int(version) >= 0x00030500: weechat.config_set_desc_plugin(option, description) def lb_reset_stored_sort_order(): global lb_current_sort, lb_sort_inverted lb_current_sort = weechat.config_get_plugin('sort_order') lb_sort_inverted = (True if weechat.config_get_plugin('sort_inverted') == 'on' else False) if __name__ == "__main__" and import_ok: if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, "lb_close_cb", ""): lb_set_default_settings() lb_reset_stored_sort_order() lb_buffer = weechat.buffer_search("python", "listbuffer") weechat.hook_signal("*,irc_in_321", "lb_list_start", "") weechat.hook_signal("*,irc_in_322", "lb_list_chan", "") weechat.hook_signal("*,irc_in_323", "lb_list_end", "") weechat.hook_command(SCRIPT_COMMAND, "List Buffer", "", "", "", "lb_command_main", "")
def buf_node_in(pssName, buf, args): global psses ctx = {} currentPss = None argv = "" argc = 0 bufname = "" # parse cmd input # \todo remove consecutive whitespace argv = args.split(" ") argc = len(argv) # first we handle commands that are node independent # the connect command is the same for any context if argv[0] == "connect": host = "127.0.0.1" port = "8546" pssName = "" if argc < 2: wOut(PSS_BUFPFX_ERROR, [], "!!!", "invalid command <TODO insert help text>") pssName = argv[1] if argc > 2: host = argv[2] if argc > 3: port = argv[3] if pssName in psses: existingBuf = weechat.buffer_search("python", "pss.node." + pssName) if existingBuf != "": wOut( PSS_BUFPFX_DEBUG, [], "", "pss " + pssName + " already exists, changing to that buffer") weechat.buffer_set(bufs[pssName], "display", "1") return weechat.WEECHAT_RC_OK if host == "": host = weechat.config_get_plugin(pssName + "_url", host) if port == "": port = weechat.config_get_plugin(pssName + "_port", port) wOut(PSS_BUFPFX_DEBUG, [], "", "pss " + pssName + " already exists") else: psses[pssName] = pss.Pss(pssName, host, port) wOut(PSS_BUFPFX_OK, [], "+++", "added pss " + pssName) # regardless of if we have the node already, store the connection parameters for later for this node name weechat.config_set_plugin(pssName + "_url", host) weechat.config_set_plugin(pssName + "_port", port) # if we made it here we don't have a buffer for this node already # so create it and merge the node buffer with core so we can do the neat ctrl-x trick bufs[pssName] = weechat.buffer_new("pss.node." + pssName, "buf_node_in", pssName, "buf_node_close", pssName) weechat.buffer_set(bufs[pssName], "short_name", "pss." + pssName) weechat.buffer_set(bufs[pssName], "title", "PSS '" + pssName + "' | not connected") weechat.buffer_merge(bufs[pssName], weechat.buffer_search_main()) weechat.buffer_set(bufs[pssName], "display", "1") # now that we have the buffer up we have somewhere to write output relevant to this connection # we can proceed with connection in the pss instance wOut(PSS_BUFPFX_WARN, [bufs[pssName]], "0-> 0", "connecting to '" + pssName + "'") if not psses[pssName].connect(): wOut( PSS_BUFPFX_ERROR, [bufs[pssName]], "0-x 0", "connect to '" + pssName + "' failed: " + psses[pssName].error()['description']) return weechat.WEECHAT_RC_ERROR wOut(PSS_BUFPFX_OK, [bufs[pssName]], "0---0", "connected to '" + pssName + "'") # \todo temporary solution, swarm gateway should be set explicitly or at least we need to be able to choose port hookSocks.append( weechat.hook_connect("", host, 8500, 0, 0, "", "sock_connect", pssName)) # start processing inputs on the websocket hookFds[pssName] = weechat.hook_fd(psses[pssName].get_fd(), 1, 0, 0, "msgPipeRead", pssName) hookTimers.append( weechat.hook_timer(feedBoxPeriod, 0, 0, "processFeedBox", pssName)) # set own nick for this node # \todo use configurable global default nick # \todo clean up messy pubkey slicing (should be binary format in pss obj) pubkey = psses[pssName].key[2:] selfs[pssName] = pss.PssContact( PSS_DEFAULT_NICK, psses[pssName].key, pss.publickey_to_account(pubkey.decode("hex")).encode("hex"), psses[pssName].key) wOut(PSS_BUFPFX_OK, [bufs[pssName]], pssName, "nick is " + selfs[pssName].nick) return weechat.WEECHAT_RC_OK # get the context we're getting the command in # if we are not in pss context, # the we assume that the first argument is the name of the node # /pss oc add someone key addr # becomes # /pss add someone key addr # and "oc" is set to pssName # \todo consider exception for connect-command ctx = buf_get_context(buf) wOut(PSS_BUFPFX_DEBUG, [], "", "ctx: " + repr(ctx['t']) + " n " + ctx['n'] + " h " + ctx['h']) shiftArg = False # t 0 means any non-pss buffer if ctx['t'] == 0 and argv[0] != "connect": pssName = argv[0] argv = argv[1:] argc -= 1 else: pssName = ctx['n'] wOut(PSS_BUFPFX_DEBUG, [], "!!!", "after ctx " + pssName) # see if we already have this node registered if not pssName in psses: wOut(PSS_BUFPFX_ERROR, [], "!!!", "unknown pss connection '" + pssName + "'") return weechat.WEECHAT_RC_ERROR currentPss = psses[pssName] # set configuation values if argv[0] == "set": if argc < 3: wOut(PSS_BUFPFX_ERROR, [], "!!!", "insufficient number of arguments <TODO help output") return weechat.WEECHAT_RC_ERROR k = argv[1] v = argv[2] # for now we handle privkeys directly # we will read keystore jsons in near future instead, though if k == "pk": try: privkey = pss.clean_privkey(v) except: wOut(PSS_BUFPFX_ERROR, [], "!!!", "invalid key format") return weechat.WEECHAT_RC_ERROR try: currentPss.set_account_write(privkey.decode("hex")) except ValueError as e: wOut(PSS_BUFPFX_ERROR, [], "!!!", "set account fail: " + str(e)) return weechat.WEECHAT_RC_ERROR else: wOut(PSS_BUFPFX_ERROR, [], "!!!", "unknown config key") return weechat.WEECHAT_RC_ERROR wOut(PSS_BUFPFX_DEBUG, [], "!!!", "set pk to " + v + " for " + pssName) weechat.WEECHAT_RC_OK # add a recipient to the address books of plugin and node # \todo currently overwritten if same pubkey and different addr, should be possible to have both, maybe even one-shots special command with dark address where entry is deleted after message sent!!! elif argv[0] == "add": nick = "" key = "" addr = "" # input sanity check if argc < 3: wOut(PSS_BUFPFX_ERROR, [bufs[currentPssName]], "!!!", "not enough arguments for add <TODO: help output>") return weechat.WEECHAT_RC_ERROR # puny human varnames nick = argv[1] key = argv[2] if argc == 4: addr = argv[3] else: addr = "0x" # backend add recipient call if not currentPss.add(nick, key, addr): wOut(PSS_BUFPFX_ERROR, [bufs[pssName]], "!!!", "add contact error: " + currentPss.error()['description']) return weechat.WEECHAT_RC_ERROR # refresh the plugin memory map version of the recipient wOut(PSS_BUFPFX_DEBUG, [], "!!!", "added key " + key + " to nick " + nick) nicks[key] = currentPss.get_contact(nick) remotekeys[nick] = key # append recipient to file for reinstating across sessions storeFile.write(nick + "\t" + key + "\t" + addr + "\t" + currentPss.key + "\n") # open the buffer if it doesn't exist buf_get(pssName, "chat", nick, True) wOut( PSS_BUFPFX_INFO, [bufs[pssName]], "!!!", "added contact '" + nicks[key].nick + "' to '" + pssName + "' (key: " + pss.label(key) + ", addr: " + pss.label(addr) + ")") # send a message to a recipient elif argv[0] == "send" or argv[0] == "msg": nick = "" msg = "" if argc < 2: wOut(PSS_BUFPFX_ERROR, [bufs[pssName]], "!!!", "not enough arguments for send") return weechat.WEECHAT_RC_ERROR nick = argv[1] if argc > 2: msg = " ".join(argv[2:]) # \todo handle hex address only if not currentPss.have_nick(nick): wOut(PSS_BUFPFX_ERROR, [bufs[pssName]], "!!!", "invalid nick " + nick) return weechat.WEECHAT_RC_ERROR buf = buf_get(pssName, "chat", nick, True) # \todo remove the bufs dict, since we can use weechat method for getting it bufs[weechat.buffer_get_string(buf, "name")] = buf # if no message body we've just opened the chat window if msg != "": if not pss.is_message(msg): wOut(PSS_BUFPFX_DEBUG, [bufs[pssName]], "", "invalid message " + msg) return weechat.WEECHAT_RC_ERROR return buf_in(pssName, buf, msg) # create/join existing chat room elif argv[0] == "join": room = "" if argc < 2: wOut(PSS_BUFPFX_ERROR, [bufs[pssName]], "!!!", "not enough arguments for join") return weechat.WEECHAT_RC_ERROR room = argv[1] wOut(PSS_BUFPFX_DEBUG, [], "!!!", "in join " + pssName) buf = buf_get(pssName, "room", room, True) # invite works in context of chat rooms, and translates in swarm terms to # adding one separate feed encoded with the invited peer's key # room argument can be omitted if command is issued om channel to invite to # note feeds are currently unencrypted elif argv[0] == "invite": nick = "" roomname = "" if argc < 2: wOut(PSS_BUFPFX_ERROR, [bufs[pssName]], "!!!", "not enough arguments for invite") # if missing channel argument get bufname command was issued in # and derive channel name from it if we can (fail if not) elif argc < 3: if ctx['t'] != PSS_BUFTYPE_ROOM: wOut(PSS_BUFPFX_ERROR, [bufs[pssName]], "!!!", "unknown channel '" + ctx['t'] + "'") return weechat.WEECHAT_RC_ERROR roomname = ctx['h'] else: roomname = argv[2] nick = argv[1] # check if room exists # if it does, perform invitation try: roombufname = buf_generate_name(pssName, "room", roomname) room = rooms[roombufname] pss_invite(pssName, nick, room) wOut(PSS_BUFPFX_DEBUG, [], "!!!", "added " + nick + " to " + roomname) # if neither the previous fail, add the nick to the buffer roombuf = weechat.buffer_search("python", roombufname) buf_room_add(roombuf, nick) except KeyError as e: # keyerror catches both try statements wOut(PSS_BUFPFX_ERROR, [buf], "!!!", "Unknown room or nick: " + str(e)) # output node key elif argv[0] == "key" or argv[0] == "pubkey": wOut(PSS_BUFPFX_INFO, [bufs[pssName]], pssName + ".key", currentPss.key) # output node base address elif argv[0] == "addr" or argv[0] == "address": wOut(PSS_BUFPFX_INFO, [bufs[pssName]], pssName + ".addr", currentPss.base) # set nick for pss node elif argv[0] == "nick": try: if len(argv) > 1: nick = pss.clean_nick(argv[1]) selfs[pssName].nick = nick wOut(PSS_BUFPFX_INFO, [bufs[pssName]], pssName, "nick is '" + selfs[pssName].nick + "'") except ValueError as e: wOut(PSS_BUFPFX_ERROR, [bufs[pssName]], "!!!", "Invalid nick: " + argv[1]) # stop connection # \todo also kill the subprocess # \todo ensure clean shutdown so conncet can be called over elif argv[0] == "stop": weechat.unhook(hookFds[pssName]) wOut(PSS_BUFPFX_INFO, [bufs[pssName]], "!!!", "disconnected from " + pssName) currentPss.close() #del psses[currentPssName] # invalid input else: return weechat.WEECHAT_RC_ERROR # all good return weechat.WEECHAT_RC_OK
def ircrypt_decrypt_hook(data, msgtype, server, args): '''Hook for incomming PRVMSG commands. This method will parse the input, check if it is an encrypted message and call the appropriate decryption methods if necessary. :param data: :param msgtype: :param server: IRC server the message comes from. :param args: IRC command line- ''' info = weechat.info_get_hashtable('irc_message_parse', {'message': args}) # Check if channel is own nick and if change channel to nick of sender if info['channel'][0] not in '#&': info['channel'] = info['nick'] # Get key key = ircrypt_keys.get(('%s/%s' % (server, info['channel'])).lower()) # Return everything as it is if we have no key if not key: return args if not '>CRY-' in args: # if key exisits and no >CRY not part of message flag message as unencrypted pre, message = args.split(' :', 1) marker = weechat.config_string(ircrypt_config_option['unencrypted']) return '%s :%s %s' % (pre, marker, message) # if key exists and >CRY part of message start symmetric encryption pre, message = args.split('>CRY-', 1) number, message = message.split(' ', 1) # Get key for the message memory catchword = '%s.%s.%s' % (server, info['channel'], info['nick']) # Decrypt only if we got last part of the message # otherwise put the message into a global memory and quit if int(number) != 0: if not catchword in ircrypt_msg_memory: ircrypt_msg_memory[catchword] = MessageParts() ircrypt_msg_memory[catchword].update(int(number), message) return '' # Get whole message try: message = message + ircrypt_msg_memory[catchword].message del ircrypt_msg_memory[catchword] except KeyError: pass # Get message buffer in case we need to print an error buf = weechat.buffer_search('irc', '%s.%s' % (server, info['channel'])) # Decode base64 encoded message try: message = base64.b64decode(message) except: ircrypt_error('Could not Base64 decode message.', buf) return args # Decrypt try: message = (key).encode('utf-8') + b'\n' + message except: # For Python 2.x message = key + b'\n' + message (ret, out, err) = ircrypt_gnupg(message, '--passphrase-fd', '-', '-q', '-d') # Get and print GPG errors/warnings if ret: ircrypt_error(err.decode('utf-8'), buf) return args if err: ircrypt_warn(err.decode('utf-8')) return pre + out.decode('utf-8')
if int(version) >= 0x00030600: weechat.key_bind('mouse', floodit_mouse_keys) weechat.hook_hsignal('floodit_mouse', 'floodit_mouse_cb', '') # detect config changes weechat.hook_config('plugins.var.python.%s.*' % SCRIPT_NAME, 'floodit_config_cb', '') # add command weechat.hook_command( SCRIPT_COMMAND, 'Flood' 'it game.', '[single|versus]', 'single: play in single mode (default)\n' 'versus: play versus computer\n\n' 'Single mode:\n' '- Choose a color for the upper left square, this will paint ' 'this square and all squares next to this one (having same color) ' 'with your color.\n' '- You win if all squares are same color.\n' '- Maximum number of floods is 25, 35 or 50 (according to size).\n\n' 'Versus mode:\n' '- You paint the upper left square, WeeChat paints bottom right.\n' '- You can not paint with last color used by WeeChat.\n' '- Game ends when neither you nor WeeChat can paint new squares any more.\n' '- You win if you have more squares of your color than WeeChat.', 'single|versus', 'floodit_cmd_cb', '') # if buffer already exists (after /upgrade), init floodit if weechat.buffer_search('python', 'floodit'): floodit_init()
def get_pointer(self): buf = weechat.buffer_search("==", self.full_name) if not buf: weechat.prnt("", "[WUI] ERROR: POINTER TO BUFFER: %s NOT FOUND" % self.short_name) return buf
def colorize_cb(data, modifier, modifier_data, line): global colored_nicks full_name = modifier_data.split(';')[1] channel = '.'.join(full_name.split('.')[1:]) buffer = weechat.buffer_search('', full_name) if buffer not in colored_nicks: return line reset = weechat.color('reset') tags_line = modifier_data.rsplit(';') if len(tags_line) >= 3: tags_line = tags_line[2].split(',') for i in ('irc_join', 'irc_part', 'irc_quit'): if i in tags_line: return line for words in valid_nick_re.findall(line): nick = words[1] if len(nick) < 2: continue if nick not in colored_nicks[buffer]: if not nick[-1].isalpha() and not nick[0].isalpha(): if nick[1:-1] in colored_nicks[buffer]: nick = nick[1:-1] elif not nick[0].isalpha(): if nick[1:] in colored_nicks[buffer]: nick = nick[1:] elif not nick[-1].isalpha(): if nick[:-1] in colored_nicks[buffer]: nick = nick[:-1] if nick in colored_nicks[buffer]: nick_color = colored_nicks[buffer][nick] try: cnt = 0 for word in line.split(): cnt += 1 assert cnt < 20 if word.startswith(('http://', 'https://')): continue if nick in word: biggest_nick = '' for i in colored_nicks[buffer]: cnt += 1 assert cnt < 20 if nick in i and nick != i and len(i) > len(nick): if i in word: biggest_nick = i if len(biggest_nick) > 0 and biggest_nick in word: pass elif len(word) < len(biggest_nick) or len( biggest_nick) == 0: new_word = word.replace( nick, '{0}{1}{2}'.format(nick_color, nick, reset)) line = line.replace(word, new_word) except AssertionError: nick_color = colored_nicks[buffer][nick] regex = r'(\A|\s).?({0}).?(\Z|\s)'.format(re.escape(nick)) match = re.search(regex, line) if match is not None: new_line = line[:match.start( 2)] + nick_color + nick + reset + line[match.end(2):] line = new_line return line