def search_whois_cb(data, signal, hashtable): ht = hashtable["output"] # string ret = re.search(r"(\S+) \* :(.+)$", ht, re.M) if ret: masked_ip = ret.group(1) w.prnt_date_tags("", 0, "no_log", "RESULT about {}{}".format(w.color("*lightblue"), masked_ip)) lst = stick(masked_ip) for dic in lst: w.prnt_date_tags( "", 0, "no_log", "\n ".join( [ "{}#{}: {}".format(w.color("_lightgreen"), dic["number"], dic["login_time"]), "names: {}{}{} / {} / {}".format( w.color("*lightred"), dic["login_nick"][0], w.color("chat"), dic["login_nick"][1], dic["login_nick"][2], ), "channels: {}".format(dic["login_channels"]), ] ), ) # else: # w.prnt_date_tags("", 0, "no_log", "error: Not Found MASKED_IP") return w.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 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 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_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 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 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 ''
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 search_urls_cb(data, buffer, date, tags, displayed, highlight, prefix, message): """ searching for the url function message is the line that matched '://' buffer needs buffer_get_string for the short name prefix is nick """ database = sqlite3.connect(DBFILE) database.text_factory = str cursor = database.cursor() nick = prefix full_uri = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', message) # i didn't write this. close enough is good enough for now. channel = w.buffer_get_string(buffer, 'name') # current channel. for olde in full_uri: # iterate over each URI we get in the list from full_uri regex uri = urlparse(olde).hostname + urlparse(olde).path.rstrip("/)") # strip the final / and lesser-seen ) new_entry = [] # create an ordered list of the following values we want to INSERT -> sql later on new_entry.append(uri) new_entry.append(time.time()) new_entry.append(nick) new_entry.append(channel) cursor.execute("SELECT date,uri,nick,channel from urls WHERE uri LIKE ?", (uri,)) result=cursor.fetchone() if result is None: """ a new URL is seen! """ #w.command(buffer, "/notice %s" % (new_entry)) #debug cursor.execute("INSERT INTO urls(uri, date, nick, channel) VALUES (?,?,?,?)", new_entry) database.commit() else: """ we've got a match from sqlite """ date, uri, nick, channel = result timestamp = time.strftime('%Y-%m-%d', time.localtime(date)) # convert it to YYYY-MM-DD #w.command(buffer, "/notice DING %s" % str(result)) # debug w.prnt_date_tags(buffer, 0, 'no_log,notify_none', 'olde!! already posted by %s in %s on %s' % (nick, channel, timestamp)) return w.WEECHAT_RC_OK
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 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 nameday_reminder(month=0, day=0, tag='notify_highlight'): """Display reminder for given date (or nothing if no reminder defined for today).""" global namedays, nameday_settings country = nameday_get_country() if month < 1 or day < 1: today = date.today() month = today.month day = today.day nameday = nameday_remove_accents(namedays[country][month - 1][day - 1]).lower() nameday_words = re.sub('[^a-z ]', '', nameday.replace(',', ' ')).split() reminder = False for name in nameday_settings['reminder'].split(','): if name: pos = name.find('/') if pos >= 0: if day == int(name[:pos]) and month == int(name[pos+1:]): reminder = True break else: wordsfound = True for word in name.strip().lower().split(): if word and word not in nameday_words: wordsfound = False if wordsfound: reminder = True break if reminder: weechat.prnt_date_tags('', 0, tag, '*\tReminder: %02d/%02d: %s' % (day, month, nameday_get_month_day(month - 1, day - 1, gender=True, colorMale='color_male', colorFemale='color_female')))
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 print_tweet_data(buffer,tweets,data): for message in tweets: nick = message[1] text = message[3] reply_id = "" if script_options['tweet_nicks']: parse_for_nicks(text,buffer) add_to_nicklist(buffer,nick,tweet_nicks_group[buffer]) if script_options['print_id']: t_id = weechat.color('reset') + ' ' + dict_tweet(message[2]) else: t_id = '' if len(message) == 5: #This is a reply to a tweet arrow_col = weechat.color('chat_prefix_suffix') reset_col = weechat.color('reset') reply_id = arrow_col + "<" + reset_col + dict_tweet(message[4]) + arrow_col + "> " + reset_col temp_text = text text = reply_id reply_id = temp_text weechat.prnt_date_tags(buffer, message[0], "notify_message", "%s%s\t%s%s" % (nick, t_id, text,reply_id)) if data == "id": try: if script_options['last_id'] < tweets[-1][2]: script_options['last_id'] = tweets[-1][2] # Save last id weechat.config_set_plugin("last_id",script_options["last_id"]) except: pass
def buffer_prnt(self, user='******', message='no message', time=0, backlog=False): set_read_marker = False time = float(time) message = message.encode('ascii', 'ignore') if time != 0 and self.last_read >= time: tags = "no_highlight,notify_none,logger_backlog_end" set_read_marker = True elif message.find(self.server.nick) > -1: tags = "notify_highlight" elif user != self.server.nick and self.name in self.server.users: tags = "notify_private,notify_message" else: tags = "notify_message" time = int(float(time)) if self.channel_buffer: if self.server.users.find(user) and user != self.server.nick: name = self.server.users.find(user).colorized_name() else: name = user if message != self.previous_prnt_message: if message.startswith(self.previous_prnt_message): message = message[len(self.previous_prnt_message):] message = HTMLParser.HTMLParser().unescape(message) w.prnt_date_tags(self.channel_buffer, time, tags, "%s\t%s" % (name, message)) #eventually maybe - doesn't reprint name if next message is same user #if name != self.previous_prnt_name: # w.prnt_date_tags(self.channel_buffer, time, tags, "%s\t%s" % (name, message)) # self.previous_prnt_name = name #else: # w.prnt_date_tags(self.channel_buffer, time, tags, "%s\t%s" % ("", message)) self.previous_prnt_message = message if set_read_marker: self.mark_read(False) else: self.open(False)
def add_message(self, message): text = message['text'].encode('UTF-8', 'replace') name = users_by_id[message['owner']].encode('UTF-8') # Format username with text data = "{}\t{}".format(name, text) room_buffer = w.buffer_search("", self.name) w.prnt_date_tags(room_buffer, int(time.time()), "", data) self.last_id = message['id']
def modifier_cb(data, modifier, modifier_data, string): if "irc_privmsg" in modifier_data and ("http://" in string or "https://" in string): buffer = weechat.buffer_search("irc", modifier_data.split(";")[1]) nick = weechat.buffer_get_string(buffer, "localvar_nick") highlighted = nick in string weechat.prnt_date_tags(buffer, 0, "urlwrap_filter_tag", string) weechat.prnt(buffer, "\t\t{}".format(_reconstruct_print(string, highlighted))) return "" return string
def my_process_cb(data, command, rc, out, err): if rc == weechat.WEECHAT_HOOK_PROCESS_ERROR: weechat.prnt("", "Error with command '%s'" % command.replace(script_options["oauth_token"],"").replace(script_options["oauth_secret"],"")) return weechat.WEECHAT_RC_OK data = ast.literal_eval(data) buffer = data[0] end_mes = data[1] if out != "": if out[0] != "[" and out[0] != "{": #If message is just a string print it weechat.prnt(buffer, "%s%s" % (weechat.prefix("network"), out)) return weechat.WEECHAT_RC_OK process_output = ast.literal_eval(out) #List message if len(end_mes) >= 1 and end_mes[0] == "L": if isinstance(process_output[-1], int): t_id = dict_tweet(str(process_output[-1])) + "\t" process_output = process_output[:-1] more = " ..." else: t_id = weechat.prefix("network") more = "" for nick in process_output: if end_mes == "LYFollowing": add_to_nicklist(buffer,nick) elif script_options['tweet_nicks']: add_to_nicklist(buffer,nick,tweet_nicks_group[buffer]) weechat.prnt_date_tags(buffer, 0, "no_highlight", "%s%s: %s%s" % (t_id, end_mes[1:], process_output, more)) return weechat.WEECHAT_RC_OK if end_mes == "About": weechat.prnt(buffer, "Nick: %s | Name: %s | Protected: %s" % (process_output['screen_name'], process_output['name'], process_output['protected'])) weechat.prnt(buffer, "Description: %s" % process_output['description']) weechat.prnt(buffer, "Location: %s | Time zone: %s" % (process_output['location'], process_output['time_zone'])) weechat.prnt(buffer, "Created at: %s | Verified user: %s" % (process_output['created_at'], process_output['verified'])) weechat.prnt(buffer, "Following: %s | Followers: %s | Favourites: %s | Tweets: %s" % (process_output['friends_count'], process_output['followers_count'], process_output['favourites_count'], process_output['statuses_count'])) weechat.prnt(buffer, "Are you currently following this person: %s" % (process_output['following'])) return weechat.WEECHAT_RC_OK print_tweet_data(buffer,process_output,end_mes) if end_mes != "id" and end_mes != "": weechat.prnt(buffer, "%s%s" % (weechat.prefix("network"), end_mes)) if err != "": weechat.prnt("", "stderr: %s" % err) return weechat.WEECHAT_RC_OK
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 topic(data, tags, msg): server = tags.split(",")[0] match = re.search(r':(\S+)\s+TOPIC\s+(\S+)\s+:(.*)', msg) if not match: return weechat.WEECHAT_RC_ERROR usermask, channel, newtopic = match.groups() nick, host = usermask.split("!", 1) buffer = weechat.buffer_search("irc", server + "." + channel) weechat.prnt("", server + "." + channel) if not buffer: return weechat.WEECHAT_RC_ERROR oldtopic = weechat.buffer_get_string(buffer, "title") if oldtopic == None: oldtopic = "" dmp = diff_match_patch.diff_match_patch() diff = dmp.diff_main(oldtopic, newtopic) dmp.diff_cleanupEfficiency(diff) topic = "" color_reset = weechat.color("reset") color_ins = weechat.color(weechat.config_get_plugin("color_ins")) color_del = weechat.color(weechat.config_get_plugin("color_del")) for chunk in diff: changed, text = chunk topic += "%s%s%s" % ( # 0 (unchanged), 1 (added), -1 (removed) ["", color_ins, color_del][changed], text, ["", color_reset, color_reset][changed] ) weechat.prnt_date_tags(buffer, 0, "irc_topicdiff", "%s%s%s%s has changed topic for %s%s%s: %s" % ( weechat.prefix("network"), weechat.color(weechat.info_get("irc_nick_color", nick)) \ if weechat.config_boolean("irc.look.color_nicks_in_server_messages") \ else weechat.color("chat_nick"), nick, color_reset, weechat.color("chat_channel"), channel, color_reset, topic )) return weechat.WEECHAT_RC_OK
def buffer_prnt(self, message='no message', user="******", backlog=False): message = message.encode('ascii', 'ignore') if backlog == True: tags = "no_highlight,notify_none,logger_backlog_end" else: tags = "" if self.buffer: w.prnt_date_tags(self.buffer, 0, tags, "%s\t%s" % (user, message)) else: pass
def replaylog(): global awaylog if awaylog: wc.prnt("", "-->\t") for a in awaylog: wc.prnt_date_tags("", a[0], "", a[1]) wc.prnt("", "<--\t") awaylog = []
def handle_message_cb(data, buffer, date, tags, disp, hl, nick, message): """ Callback that handles new messages. If the message is in the format of a regex find/replace (ex. 's/typo/replacement/', 'nick: s/typo/replacement') then the last print_limit messages for that nick are re-printed to the current buffer in their oringal order with the change applied. Otherwise the message is stored in LASTWORDS dictionary for this buffer > nick. """ # Don't do anything if the message isn't suppose to be displayed. if disp: # If the buffer or nick are not in LASTWORDS, add them. buffer_name = weechat.buffer_get_string(buffer, 'name') if buffer_name not in LASTWORDS: LASTWORDS[buffer_name] = {} if nick not in LASTWORDS[buffer_name]: LASTWORDS[buffer_name][nick] = [] log = LASTWORDS[buffer_name][nick] # Matches on both 's/typo/replacement' and 'nick: s/typo/replacement', # mainly because of bitlbee since it puts your nick in front of # incoming messages. # # Nick regex nicked from colorize_nicks available here: # http://www.weechat.org/scripts/source/stable/colorize_nicks.py.html/ valid_nick = r'([@~&!%+])?([-a-zA-Z0-9\[\]\\`_^\{|\}]+)' valid_correction = r's/[^/]*/[^/]*' correction_message_pattern = re.compile( r'(%s:\s*)?(%s)(/)?$' % (valid_nick, valid_correction)) match = re.match(correction_message_pattern, message) if match: # If message is a correction and we have previous messages from # this nick, print up to print_limit of the nick's previous # messages with corrections applied, in their original order. correction = match.group(4) if log and correction: printformat = weechat.config_get_plugin('print_format') for cm in corrected_messages(nick, log, correction): corrected_msg = printformat for k, v in cm.iteritems(): corrected_msg = corrected_msg.replace('[%s]' % k, v) weechat.prnt_date_tags(buffer, 0, 'no_log', corrected_msg) else: # If it's not a correction, store the message in LASTWORDS. log.insert(0, {'message': message, 'timestamp': date}) # If there's a per-nick limit, shorten the list to match. message_limit = get_option_int('message_limit') if message_limit: log = log[:message_limit] LASTWORDS[buffer_name][nick] = log return weechat.WEECHAT_RC_OK
def do_print(bufname, nick, text): if BUFFERNAMES[bufname]: open_buffer(bufname) # include nick in tags for possible formatting tags = "nick_{}".format(nick) ncolor = weechat.info_get("irc_nick_color_name", nick) printtext = "{}{}{}\t{}".format(weechat.color(ncolor), nick, weechat.color("reset"), text) weechat.prnt_date_tags(buffers[bufname], 0, tags, printtext)
def sentCB(buf_name, command, return_code, out, err): 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 != "": tags = 'notify_message' weechat.prnt_date_tags(weechat.buffer_search('python', buf_name), 0, tags, out) if err != "": weechat.prnt("", "stderr: %s" % err) return weechat.WEECHAT_RC_OK
def oauth_proc_cb(data, command, rc, out, err): global script_options buffer = twit_buf if rc == weechat.WEECHAT_HOOK_PROCESS_ERROR: weechat.prnt("", "Error with command '%s'" % command.replace(script_options["oauth_token"],"").replace(script_options["oauth_secret"],"")) return weechat.WEECHAT_RC_OK if out != "": if data == "nick": weechat.config_set_plugin('screen_name', out.strip()) finish_init() elif data == "friends": process_output = ast.literal_eval(out) if isinstance(process_output[-1], int): t_id = dict_tweet(str(process_output[-1])) + "\t" process_output = process_output[:-1] weechat.prnt_date_tags(buffer, 0, "no_highlight", t_id + "It sees like you are following more than 250 people. Due to twitter api limits " + "it is nearly impossible to get large groups of followers in one go. However the " + "nicks will be added when they tweet something so if you don't have to be able " + "autocomplete them from the start this is not a problem for you." + " If you want to get the rest of the nicks you can use the id of this text.") for nick in process_output: add_to_nicklist(buffer,nick) #Get latest tweets from timeline buffer_input_cb("silent", buffer, ":new") elif data == "auth1": #First auth step to request pin code oauth_token, oauth_token_secret = parse_oauth_tokens(out) script_options['oauth_token'] = oauth_token script_options['oauth_secret'] = oauth_token_secret weechat.prnt(buffer,""" Copy the PIN number that appears on the linked web page and type ":auth <pin>" in weechat. For example ":auth 123456" """) oauth_url = ('https://api.twitter.com/oauth/authorize?oauth_token=' + oauth_token) weechat.prnt(buffer," Please go here to get your PIN: " + oauth_url) elif data == "auth2": oauth_token, oauth_token_secret = parse_oauth_tokens(out) weechat.config_set_plugin('oauth_token', oauth_token) weechat.config_set_plugin('oauth_secret', oauth_token_secret) weechat.config_set_plugin('auth_complete', "on") weechat.prnt(buffer," Done! now you can begin using this script!") weechat.hook_process("python3 " + SCRIPT_FILE_PATH + " " + script_options["oauth_token"] + " " + script_options["oauth_secret"] + " " + "settings []", 10 * 1000, "oauth_proc_cb", "nick") return weechat.WEECHAT_RC_OK
def on_buffer_input(data, modifier, modifier_data, string): originalString = string if string.find("/") == 0: # We dont want to block commands from executing return originalString for word in words: word = word.lower() if not case_sensitive else word string = string.lower() if not case_sensitive else string if word in string: w.prnt_date_tags(w.current_buffer(), 0, 'no_log', '%sunwanted message deleted.' % (w.prefix('error'))) return '' return originalString
def urlserver_display_url_detail(key): global urlserver url = urlserver['urls'][key] nick = url[1] if nick: nick += ' @ ' weechat.prnt_date_tags(urlserver['buffer'], 0, 'notify_none', '%s, %s%s%s%s: %s%s%s -> %s' % (url[0], nick, weechat.color('chat_buffer'), url[2], weechat.color('reset'), weechat.color(urlserver_settings['color']), urlserver_short_url(key), weechat.color('reset'), url[3]))
def multi_line_cb(data,buffer,args): global ml_text,ml_flag if args == "test" or args=="": multi_line_text() if ml_flag: ml_text = re.sub("\s+$","",ml_text) if args == "test": w.prnt_date_tags(w.current_buffer(), 0, "no_log", ml_text.encode('utf-8')) elif args == "": w.command(w.current_buffer(), ml_text.encode('utf-8')) ml_text = "" ml_flag = False else: w.prnt_date_tags(w.current_buffer(), 0, "no_log", "%smultiline: args '%s' is not defined" % (w.prefix('error'),args)) return w.WEECHAT_RC_OK
def prnt_message(channel, nick, message): """Prints a message with proper colors and prefixes""" user = users[nick] prefix = prefix_for_user(channel, user) color = user.get("color") name = get_name(nick) if color is None: color = weechat.info_get("irc_nick_color_name", name) buffer = weechat.info_get("irc_buffer", twitch_settings["twitch_server"] + "," + channel) full_message = "{}{}{}{}\t{}".format(prefix, weechat.color(color), name, weechat.color("chat"), message) weechat.prnt_date_tags( buffer, 0, "irc_privmsg,notify_message,prefix_nick_{0},nick_{1}," "host_{1}@{1}.tmi.twitch.tv,log1".format(color, nick), full_message, ) return buffer
def urlserver_display_url_detail(key, return_url=False): global urlserver url = urlserver['urls'][key] nick = url[1] if nick: nick += ' @ ' if return_url: return urlserver_short_url(key) else: weechat.prnt_date_tags( urlserver['buffer'], 0, 'notify_none', '%s, %s%s%s%s: %s%s%s -> %s' % (url[0], nick, weechat.color('chat_buffer'), url[2], weechat.color('reset'), weechat.color( urlserver_settings['color']), urlserver_short_url(key), weechat.color('reset'), url[3]))
def search_urls_cb(data, buffer, date, tags, displayed, highlight, prefix, message): """ searching for the url function message is the line that matched '://' buffer needs buffer_get_string for the short name prefix is nick """ database = sqlite3.connect(DBFILE) database.text_factory = str cursor = database.cursor() nick = prefix full_uri = re.findall( 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', message) # i didn't write this. close enough is good enough for now. channel = w.buffer_get_string(buffer, 'name') # current channel. for olde in full_uri: # iterate over each URI we get in the list from full_uri regex uri = urlparse(olde).hostname + urlparse(olde).path.rstrip( "/)") # strip the final / and lesser-seen ) new_entry = [ ] # create an ordered list of the following values we want to INSERT -> sql later on new_entry.append(uri) new_entry.append(time.time()) new_entry.append(nick) new_entry.append(channel) cursor.execute( "SELECT date,uri,nick,channel from urls WHERE uri LIKE ?", (uri, )) result = cursor.fetchone() if result is None: """ a new URL is seen! """ #w.command(buffer, "/notice %s" % (new_entry)) #debug cursor.execute( "INSERT INTO urls(uri, date, nick, channel) VALUES (?,?,?,?)", new_entry) database.commit() else: """ we've got a match from sqlite """ date, uri, nick, channel = result timestamp = time.strftime( '%Y-%m-%d', time.localtime(date)) # convert it to YYYY-MM-DD #w.command(buffer, "/notice DING %s" % str(result)) # debug w.prnt_date_tags( buffer, 0, 'no_log,notify_none', 'olde!! already posted by %s in %s on %s' % (nick, channel, timestamp)) return w.WEECHAT_RC_OK
def receive_message(self, message): """ Receive a message from someone """ if 'text' in message and 'personEmail' in message: try: buddy_name, buddy_domain = message['personEmail'].split('@') if buddy_domain != self.server.domain: buddy_name = message['personEmail'] weechat.prnt_date_tags( self.buffer, 0, "notify_private,nick_%s,prefix_nick_%s,log1" % (buddy_name, weechat.config_string( weechat.config_get("weechat.color.chat_nick_other"))), "%s%s\t%s" % (weechat.color("chat_nick_other"), buddy_name, WebexParser.parse(message['text']))) except Exception as e: self.prnt(f"Error while receiving a message: {e}") else: self.server.debug('Not a message text')
def my_modifier_cb(data, modifier, modifier_data, string): if unwanted_pattern.match(string): if options['warning_buffer'] == 'current': output = w.current_buffer() elif options['warning_buffer'] == 'server': server = w.buffer_get_string(w.current_buffer(), 'localvar_server') plugin = w.buffer_get_string(w.current_buffer(), 'plugin') output = w.buffer_search(plugin, 'server.' + server) elif options['warning_buffer'] == '': output = None else: output = '' # if invalid option set to weechat buffer if not output == None: w.prnt_date_tags( output, 0, 'no_log', '%sunwanted message deleted: "%s"' % (w.prefix('error'), string)) w.buffer_set(w.current_buffer(), 'input', string) return '' else: return string
def get_last_history(self, conv_id, notify=""): api = { "method": "read", "params": { "options": { "conversation_id": conv_id } } } result = self.execute_api(api) mex = {} for i in result['messages']: date, body, n = handle_message(i['msg']) mex[n] = [date, body] od = collections.OrderedDict(sorted(mex.items())) for n, b in od.items(): weechat.prnt_date_tags(self.private_chans[conv_id], b[0], notify, b[1]) keys = list(od.keys()) return None, keys[0], keys[-1]
def exec_command(self, userExec=False): """ Execute job command. """ global cron_commands display_error = weechat.config_get_plugin("quiet_exec") == "off" buf = "" if self.buffer == "current": buf = weechat.current_buffer() else: items = self.buffer.split(".", 1) if len(items) >= 2: buf = weechat.buffer_search(items[0], items[1]) if buf: argv = self.command.split(None, 1) if len(argv) > 0 and argv[0] in cron_commands: if argv[0] == "print": weechat.prnt(buf, "%s" % argv[1]) elif argv[0] == "print_hl": weechat.prnt_date_tags(buf, 0, "notify_highlight", "%s" % argv[1]) elif argv[0] == "print_msg": weechat.prnt_date_tags(buf, 0, "notify_message", "%s" % argv[1]) elif argv[0] == "command": weechat.command(buf, "%s" % argv[1]) elif argv[0] == "commands": cmds = argv[1].split(";") for cmd in cmds: weechat.command(buf, "%s" % cmd) elif argv[0] == "python": eval(argv[1]) elif display_error: weechat.prnt( "", "%scron: unknown command (\"%s\")" % (weechat.prefix("error"), self.command)) else: if display_error: weechat.prnt( "", "%scron: buffer \"%s\" not found" % (weechat.prefix("error"), self.buffer)) if not userExec and self.repeat > 0: self.repeat -= 1
def urlserver_print_cb(data, buffer, time, tags, displayed, highlight, prefix, message): """ Callback for message printed in buffer: display short URLs after message. """ global urlserver, urlserver_settings if not displayed and urlserver_settings['msg_filtered'] != 'on': return weechat.WEECHAT_RC_OK if urlserver_settings['display_urls'] == 'on': buffer_full_name = '%s.%s' % ( weechat.buffer_get_string(buffer, 'plugin'), weechat.buffer_get_string(buffer, 'name')) if urlserver_settings['buffer_short_name'] == 'on': buffer_short_name = weechat.buffer_get_string(buffer, 'short_name') else: buffer_short_name = buffer_full_name urls_short = urlserver_update_urllist(buffer_full_name, buffer_short_name, tags, prefix, message) if urls_short: if urlserver_settings['separators'] and \ len(urlserver_settings['separators']) == 3: separator = ' %s ' % (urlserver_settings['separators'][1]) urls_string = separator.join(urls_short) urls_string = '%s %s %s' % ( urlserver_settings['separators'][0], urls_string, urlserver_settings['separators'][2]) else: urls_string = ' | '.join(urls_short) urls_string = '[ ' + urls_string + ' ]' weechat.prnt_date_tags( buffer, 0, 'no_log,notify_none', '%s%s' % (weechat.color(urlserver_settings['color']), urls_string)) return weechat.WEECHAT_RC_OK
def buffer_prnt(self, user='******', message='no message', time=0, backlog=False): set_read_marker = False time = float(time) message = message.encode('ascii', 'ignore') if time != 0 and self.last_read >= time: tags = "no_highlight,notify_none,logger_backlog_end" set_read_marker = True elif message.find(self.server.nick) > -1: tags = "notify_highlight" elif user != self.server.nick and self.name in self.server.users: tags = "notify_private,notify_message" else: tags = "notify_message" time = int(float(time)) if self.channel_buffer: if self.server.users.find(user) and user != self.server.nick: name = self.server.users.find(user).colorized_name() else: name = user if message != self.previous_prnt_message: if message.startswith(self.previous_prnt_message): message = message[len(self.previous_prnt_message):] #dbg([message, self.previous_prnt_message]) w.prnt_date_tags(self.channel_buffer, time, tags, "%s\t%s" % (name, message)) #eventually maybe - doesn't reprint name if next message is same user #if name != self.previous_prnt_name: # w.prnt_date_tags(self.channel_buffer, time, tags, "%s\t%s" % (name, message)) # self.previous_prnt_name = name #else: # w.prnt_date_tags(self.channel_buffer, time, tags, "%s\t%s" % ("", message)) self.previous_prnt_message = message if set_read_marker: self.mark_read(False) else: self.open(False)
def weemustfeed_update_feeds_cb(data, remaining_calls): global updating for feed in weechat.config_get_plugin("feeds").strip().split(";"): if weechat.config_is_set_plugin("feed." + feed.lower() + ".url"): if not (weechat.config_is_set_plugin("feed." + feed.lower() + ".enabled") and weechat.config_get_plugin("feed." + feed.lower() + ".enabled").lower() != "yes"): updating.add(feed) if not feed in fetch_hooks: fetch_hooks[feed] = weechat.hook_process( "url:" + weechat.config_get_plugin("feed." + feed.lower() + ".url"), 15000, "weemustfeed_update_single_feed_cb", feed) elif feed != "": weechat.prnt_date_tags( weemustfeed_buffer, 0, "irc_error,notify_message", weechat.prefix("error") + "Feed '" + feed + "' has no URL set.") return weechat.WEECHAT_RC_OK
def get_calendar_callback(data, command, return_code, out, err): result = json.loads(out) buffer = buffer_get() update_gcal_buffer(buffer, result) # Notify if any events are happening in 10 minutes! if data == CALLED_FROM_TIMER: for event in result: #weechat.prnt(buffer, 'Handling event!') dt = datetime_parse(event['date']) now = datetime.now(tz=dt.tzinfo) timediff = dt - now minutes_remaining = math.ceil(timediff.total_seconds() / 60) #weechat.prnt(buffer, '{} - {} = {} ({} mins)'.format(dt, now, timediff, minutes_remaining)) # TODO Make minutes_remaining threshold configurable if minutes_remaining in NOTIFICATION_THRESHOLDS: msg = '[{}m] {}'.format(minutes_remaining, event['summary']) weechat.prnt_date_tags(buffer, 0, 'notify_highlight', msg) return weechat.WEECHAT_RC_OK
def start_reading(data, command, return_code, out, err): #weechat.prnt("","Command:"+str(command)) ## Maybe we can check this to see if the program is crashed #weechat.prnt("","return_code:"+str(return_code)) weechat.prnt("", "out:" + str(out)) if out == "": return weechat.WEECHAT_RC_OK j = json.loads(out) if j['type'] != 'chat': weechat.prnt_date_tags("", "", "", str(j)) id = j['msg']['conversation_id'] date, body, n = handle_message(j['msg']) global status if id not in status.private_chans: status.open_conv_id(j['msg']) username = body.split('/t') priority = "notify_private" if len(username) == 2: if status.nick_name in username[1]: priority = "notify_highlight" if weechat.buffer_get_string(status.private_chans[id], "localvar_first_message") == "": r, f, l = status.get_last_history(id, priority) weechat.buffer_set(status.private_chans[id], "localvar_set_first_message", str(f)) weechat.buffer_set(status.private_chans[id], "localvar_set_last_message", str(l)) return weechat.WEECHAT_RC_OK weechat.prnt_date_tags(status.private_chans[id], date, priority, body) if debug: body = weechat.color('/darkgray') + "DEBUG\t" + weechat.color( '/darkgray') + str(j) weechat.prnt_date_tags(status.private_chans[id], date, "notify_none", body) #notify_none Buffer with line is not added to hotlist. #notify_message Buffer with line is added to hotlist with level "message". #notify_private Buffer with line is added to hotlist with level "private". #notify_highlight Buffer with line is added to hotlist with level "highlight". #weechat.prnt("","err:"+str(err)) return weechat.WEECHAT_RC_OK
def infolist_display(buffer, args): global infolist_var_type items = args.split(" ", 1) infolist_args = "" infolist_pointer = "" if len(items) >= 2: infolist_args = items[1] if infolist_args[:2] == "0x": infolist_pointer, sep, infolist_args = infolist_args.partition(" ") elif infolist_args[:3] == "\"\" ": infolist_args = infolist_args[3:] infolist = weechat.infolist_get(items[0], infolist_pointer, infolist_args) if infolist == "": weechat.prnt_date_tags( buffer, 0, "no_filter", "%sInfolist '%s' not found." % (weechat.prefix("error"), items[0])) return weechat.WEECHAT_RC_OK item_count = 0 weechat.buffer_clear(buffer) weechat.prnt_date_tags( buffer, 0, "no_filter", "Infolist '%s', with pointer '%s' and arguments '%s':" % (items[0], infolist_pointer, infolist_args)) weechat.prnt(buffer, "") count = 0 while weechat.infolist_next(infolist): item_count += 1 if item_count > 1: weechat.prnt(buffer, "") fields = weechat.infolist_fields(infolist).split(",") prefix = "%s[%s%d%s]\t" % (weechat.color("chat_delimiters"), weechat.color("chat_buffer"), item_count, weechat.color("chat_delimiters")) for field in fields: (type, name) = field.split(":", 1) value = "" quote = "" if type == "i": value = weechat.infolist_integer(infolist, name) elif type == "s": value = weechat.infolist_string(infolist, name) quote = "'" elif type == "p": value = weechat.infolist_pointer(infolist, name) elif type == "t": value = weechat.infolist_time(infolist, name) # since WeeChat 2.2, infolist_time returns a long integer # instead of a string if not isinstance(value, str): str_date = time.strftime('%F %T', time.localtime(int(value))) value = '%d (%s)' % (value, str_date) name_end = "." * (30 - len(name)) weechat.prnt_date_tags( buffer, 0, "no_filter", "%s%s%s: %s%s%s %s%s%s%s%s%s" % (prefix, name, name_end, weechat.color("brown"), infolist_var_type[type], weechat.color("chat"), weechat.color("chat"), quote, weechat.color("cyan"), value, weechat.color("chat"), quote)) prefix = "" count += 1 if count == 0: weechat.prnt_date_tags(buffer, 0, "no_filter", "Empty infolist.") weechat.infolist_free(infolist) return weechat.WEECHAT_RC_OK
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 ''
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: return weechat.WEECHAT_RC_OK if err != "": weechat.prnt("", "stderr: %s" % err) return weechat.WEECHAT_RC_OK try: conversations = [ Conversation(*args) for args in reversed(cPickle.loads(conv)) ] except EOFError: weechat.prnt('', 'wtrecv returned garbage') return weechat.WEECHAT_RC_OK for conversation in conversations: if conversation.number not in conversation_map: conversation_map[conversation.number] = conversation msgs = conversation.messages else: old = conversation_map[conversation.number] conversation_map[conversation.number] = conversation msgs = old.new_messages(conversation) for msg in msgs: if conversation.number not in number_map and msg['from'] != 'Me': if conversation.number.startswith("Group Message"): number_map[conversation.number] = conversation.number else: 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]) if not buf: buf = weechat.buffer_new(number_map[conversation.number], "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'].strip() tags = ('notify_private,nick_' + nick + ',log1,prefix_nick_' + weechat.info_get('irc_nick_color_name', nick)) 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 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 plugin, buffer_name, tags = modifier_data.split(';') 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 == 'Buffer 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 = weechat.buffer_search(plugin, buffer_name) buffer_playback[buffer_name] = buffer elif line == 'Playback Complete.': buffer = buffer_playback[buffer_name] del buffer_playback[buffer_name] 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 not (buffer_playback and buffer_name in buffer_playback): return string buffer = buffer_playback[buffer_name] #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, e: # bad time format. error(e) #debug("%s\n%s" % (modifier_data, string)) return string
#debug("%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, channel = buffer_name.split('.', 1) 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")
def show(self, msg): """Display a message in the buffer.""" weechat.prnt_date_tags(self.buf, unixtime(msg), "", msg.text)
def urlserver_print_cb(data, buffer, time, tags, displayed, highlight, prefix, message): """Callback for messages printed in buffers.""" global urlserver, urlserver_settings buffer_full_name = '%s.%s' % (weechat.buffer_get_string( buffer, 'plugin'), weechat.buffer_get_string(buffer, 'name')) if urlserver_settings['buffer_short_name'] == 'on': buffer_name = weechat.buffer_get_string(buffer, 'short_name') else: buffer_name = buffer_full_name listtags = tags.split(',') # skip ignored buffers if urlserver_settings['msg_ignore_buffers']: if buffer_full_name in urlserver_settings['msg_ignore_buffers'].split( ','): return weechat.WEECHAT_RC_OK # skip ignored tags if urlserver_settings['msg_ignore_tags']: for itag in urlserver_settings['msg_ignore_tags'].split(','): for tag in listtags: if tag.startswith(itag): return weechat.WEECHAT_RC_OK # exit if a required tag is missing if urlserver_settings['msg_require_tags']: for rtag in urlserver_settings['msg_require_tags'].split(','): tagfound = False for tag in listtags: if tag.startswith(rtag): tagfound = True break if not tagfound: return weechat.WEECHAT_RC_OK # ignore message is matching the "msg_ignore_regex" if urlserver_settings['msg_ignore_regex']: if re.search(urlserver_settings['msg_ignore_regex'], prefix + '\t' + message): return weechat.WEECHAT_RC_OK # extract nick from tags nick = '' for tag in listtags: if tag.startswith('nick_'): nick = tag[5:] break # get URL min length min_length = 0 try: min_length = int(urlserver_settings['url_min_length']) # Detect the minimum length based on shorten url length if min_length == -1: min_length = len(urlserver_short_url(urlserver['number'])) + 1 except: min_length = 0 # shorten URL(s) in message for url in urlserver['regex'].findall(message): if len(url) >= min_length: if urlserver_settings['msg_ignore_dup_urls'] == 'on': if [ key for key, value in urlserver['urls'].items() if value[3] == url ]: continue number = urlserver['number'] urlserver['urls'][number] = ( datetime.datetime.now().strftime('%d/%m/%y %H:%M'), nick, buffer_name, url, '%s\t%s' % (prefix, message)) if urlserver_settings['display_urls'] == 'on': weechat.prnt_date_tags( buffer, 0, 'no_log,notify_none', '%s%s' % (weechat.color(urlserver_settings['color']), urlserver_short_url(number))) if urlserver['buffer']: urlserver_display_url_detail(number) urlserver['number'] += 1 # remove old URLs if we have reach max list size urls_amount = 50 try: urls_amount = int(urlserver_settings['urls_amount']) if urls_amount <= 0: urls_amount = 50 except: urls_amount = 50 while len(urlserver['urls']) > urls_amount: keys = sorted(urlserver['urls']) del urlserver['urls'][keys[0]] return weechat.WEECHAT_RC_OK
def search_urls_cb(data, buffer, date, tags, displayed, highlight, prefix, message): """ searching for the url function message is the line that matched '://' buffer needs buffer_get_string for the short name prefix is nick """ database = sqlite3.connect(DBFILE) database.text_factory = str cursor = database.cursor() nick = prefix full_uri = re.findall( r'(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:/[^\s]*)?', message) channel = w.buffer_get_string(buffer, 'name') # current channel. # w.prnt(w.current_buffer(), 'full_uri: %s ' % (full_uri)) # debug for olde in full_uri: # iterate over each URI we get in the list from full_uri regex if '/#/' in olde: # run this routine on rails style apps url = olde uri = url.rstrip("/)") # strip the final / and lesser-seen ) new_entry = [ ] # create an ordered list of the following values we want to INSERT -> sql later on new_entry.append(uri) new_entry.append(time.time()) new_entry.append(nick) new_entry.append(channel) # w.prnt(w.current_buffer(), 'uri: %s ' % (uri)) # debug cursor.execute( "SELECT date,uri,nick,channel from urls WHERE uri = ?", (uri, )) result = cursor.fetchone() if channel in str(url_olde_settings['ignored_channels']): # w.prnt(w.current_buffer(), 'ignoring %s due to ignored_channels = %s' % (uri, str(url_olde_settings['ignored_channels']))) return w.WEECHAT_RC_OK if result is None: """ a new URL is seen! """ # w.command(buffer, "/notice %s" % (new_entry)) # debug cursor.execute( "INSERT INTO urls(uri, date, nick, channel) VALUES (?,?,?,?)", new_entry) database.commit() else: """ we've got a match from sqlite """ date, uri, nick, channel = result timestamp = time.strftime( '%Y-%m-%d %H:%M', time.localtime(date)) # convert it to YYYY-MM-DD # w.command(buffer, "/notice DING %s" % str(result)) # debug w.prnt_date_tags( buffer, 0, 'no_log,notify_none', 'olde!! already posted by %s in %s on %s' % (nick, channel, timestamp)) else: # strip anchors url, fragment = urldefrag(olde) uri = url.rstrip("/)") # strip the final / and lesser-seen ) new_entry = [ ] # create an ordered list of the following values we want to INSERT -> sql later on new_entry.append(uri) new_entry.append(time.time()) new_entry.append(nick) new_entry.append(channel) # w.prnt(w.current_buffer(), 'uri: %s ' % (uri)) # debug cursor.execute( "SELECT date,uri,nick,channel from urls WHERE uri = ?", (uri, )) result = cursor.fetchone() if channel in str(url_olde_settings['ignored_channels']): # w.prnt(w.current_buffer(), 'ignoring %s due to ignored_channels = %s' % (uri, str(url_olde_settings['ignored_channels']))) return w.WEECHAT_RC_OK if result is None: """ a new URL is seen! """ # w.command(buffer, "/notice %s" % (new_entry)) # debug cursor.execute( "INSERT INTO urls(uri, date, nick, channel) VALUES (?,?,?,?)", new_entry) database.commit() else: """ we've got a match from sqlite """ date, uri, nick, channel = result timestamp = time.strftime( '%Y-%m-%d %H:%M', time.localtime(date)) # convert it to YYYY-MM-DD # w.command(buffer, "/notice DING %s" % str(result)) # debug w.prnt_date_tags( buffer, 0, 'no_log,notify_none', 'olde!! already posted by %s in %s on %s' % (nick, channel, timestamp)) return w.WEECHAT_RC_OK
def weemustfeed_update_single_feed_cb(feed, command, return_code, out, err): global partial_feeds, updating if not feed in partial_feeds: partial_feeds[feed] = "" if return_code == weechat.WEECHAT_HOOK_PROCESS_RUNNING: # feed not done yet partial_feeds[feed] += out return weechat.WEECHAT_RC_OK elif return_code == weechat.WEECHAT_HOOK_PROCESS_ERROR: weechat.prnt_date_tags( weemustfeed_buffer, 0, "irc_error,notify_message", weechat.prefix("error") + "Hook process error for feed '" + feed + "'. === " + command + " === " + out + " === " + err) status = weechat.WEECHAT_RC_ERROR elif return_code == 1: weechat.prnt_date_tags( weemustfeed_buffer, 0, "irc_error,notify_message", weechat.prefix("error") + "Invalid URL for feed '" + feed + "'.") status = weechat.WEECHAT_RC_ERROR elif return_code == 2: weechat.prnt_date_tags( weemustfeed_buffer, 0, "irc_error,notify_message", weechat.prefix("error") + "Transfer error while fetching feed '" + feed + "'.") status = weechat.WEECHAT_RC_ERROR elif return_code == 3: weechat.prnt_date_tags( weemustfeed_buffer, 0, "irc_error,notify_message", weechat.prefix("error") + "Out of memory while fetching feed '" + feed + "'.") status = weechat.WEECHAT_RC_ERROR elif return_code == 4: weechat.prnt_date_tags( weemustfeed_buffer, 0, "irc_error,notify_message", weechat.prefix("error") + "Error with a file while fetching feed '" + feed + "'.") status = weechat.WEECHAT_RC_ERROR elif return_code == 0: # all good, and we have a complete feed if not weechat.config_is_set_plugin("feed." + feed.lower() + ".last_id"): weechat.config_set_plugin("feed." + feed.lower() + ".last_id", "") last_id = "" last_id = weechat.config_get_plugin("feed." + feed.lower() + ".last_id") parsed_feed = feedparser.parse(partial_feeds[feed] + out) entries = list(reversed(parsed_feed.entries)) for entry in entries: if not hasattr(entry, "id"): entry.id = entry.link if (last_id == "") and len(entries) > 0: last_id = entries[-1].id else: if last_id in [entry.id for entry in entries]: only_new = False else: only_new = True for entry in entries: if PY2: entrytitle = entry.title.encode("utf-8") entryurl = entry.link.encode("utf-8") else: entrytitle = entry.title entryurl = entry.link if only_new: weechat.prnt_date_tags( weemustfeed_buffer, 0, "notify_message", "{feed}\t{title} {url}".format(**{ "feed": feed, "title": entrytitle, "url": entryurl })) last_id = entry.id elif entry.id == last_id: only_new = True # everything else will be newer weechat.config_set_plugin("feed." + feed.lower() + ".last_id", last_id) status = weechat.WEECHAT_RC_OK else: # Unknown return code. Script must be updated. weechat.prnt_date_tags( weemustfeed_buffer, 0, "irc_error,notify_message", weechat.prefix("error") + "Unknown return code " + return_code + " for feed '" + feed + "'. Script must be updated.") status = weechat.WEECHAT_RC_ERROR partial_feeds[feed] = "" if feed in updating: updating.remove(feed) if feed in fetch_hooks: del fetch_hooks[feed] return status
def print_to_current(message, timestamp=0): """Prints a no logging message to the current buffer.""" wc.prnt_date_tags(wc.current_buffer(), timestamp, "nolog,notify_status_update", message)
def print_to_buffer(buf, message, timestamp=0): """Prints a message to the private buffer.""" wc.prnt_date_tags(buf, timestamp, "notify_message", message)