def parse_buffextras(data, modifier, modifier_data, string): msg = w.info_get_hashtable('irc_message_parse', {'message': string}) # If message not from ZNC buffextras return unmodified message if msg['nick'] != '%sbuffextras' % w.config_get_plugin('module_prefix'): return string # This is a workaround to prevent crashes from malformed messages. # See: https://github.com/znc/znc/issues/1603 chan = msg['channel'] text = msg['text'].replace('set mode:', 'set mode %s' % chan) # Parse the forwarded message from buffextra orig = w.info_get_hashtable('irc_message_parse', {'message': ':%s' % text}) args = orig['arguments'] cmd = orig['command'].lower() if cmd.endswith(':'): cmd = cmd[:-1] # Parse buffextras customized messages to RFC conform messages if cmd == 'set': parsed = 'MODE %s %s' % (chan, orig['text']) elif cmd == 'joined': parsed = 'JOIN :%s' % chan elif cmd == 'parted': parsed = 'PART %s' % chan if args.startswith('with message: ['): parsed += ' :%s' % args[15:-1] elif cmd == 'is': parsed = 'NICK :%s' % args[13:] elif cmd == 'quit': parsed = 'QUIT' if args: parsed += ' :%s' % args elif cmd == 'kicked': # needs to be tested parsed = 'KICK %s' % args elif cmd == 'changed': # needs to be tested parsed = 'TOPIC %s' % args else: w.prnt( '', '%sUnhandled *buffextras event:\n%s' % (w.prefix('error'), args)) return string return '@%s :%s %s' % (msg['tags'], orig['host'], parsed)
def get_hashtable(string): parsed = weechat.info_get_hashtable("irc_message_parse", dict(message=string)) try: parsed["message"] = parsed["arguments"].split(" :", 1)[1] except: parsed["message"] = "" return parsed
def twitch_in_privmsg(data, modifier, server_name, string, prefix=''): if not OPTIONS['prefix_nicks']: return string if not server_name in OPTIONS['servers'].split(): return string mp = weechat.info_get_hashtable("irc_message_parse", {"message": string}) if not mp['tags']: return string if '#' + mp['nick'] == mp['channel']: return mp['message_without_tags'].replace(mp['nick'], '~' + mp['nick'], 1) tags = dict([s.split('=') for s in mp['tags'].split(';')]) if tags['user-type'] == 'mod': prefix += '@' #if query, not work if 'subscriber' in tags: if tags['subscriber'] == '1': prefix += '%' if prefix: msg = mp['message_without_tags'].replace( mp['nick'], prefix + mp['nick'], 1) return '@' + mp['tags'] + ' ' + msg else: return string
def do_unencrypt(data, signal, signal_data): #wc.prnt(wc.current_buffer(), "===>\tentered do_unencrypt") dict = wc.info_get_hashtable("irc_message_parse", { "message": signal_data } ) #for d in dict: # wc.prnt(wc.current_buffer(), "==>\t%s" % d) # wc.prnt(wc.current_buffer(), "===>\t%s" % dict[d]) # channel info nick = dict['nick'] server = signal.split(",")[0] channel = dict['channel'] buffer = wc.info_get("irc_buffer", "%s,%s" % (server, channel) ) # get and unencrypt dirty = dict['arguments'].split(':')[1] clean = dirty[2:] #clean = dirty[-2:] clean = enc(clean)[0] ## put the data back onto the screen if dirty[0]=='#' and dirty[1]=='#': if buffer: wc.prnt(buffer, "[%s]\t%s" % (nick, clean)) return wc.WEECHAT_RC_OK
def stop_typing(data, signal, signal_data): msg_hash = w.info_get_hashtable( "irc_message_parse", {"message": signal_data } ) if msg_hash["nick"] in typing: del typing[msg_hash["nick"]] w.bar_item_update("bitlbee_typing_notice") return w.WEECHAT_RC_OK
def get_hashtable(string): parsed = weechat.info_get_hashtable('irc_message_parse', dict(message=string)) try: parsed['message'] = parsed['arguments'].split(' :', 1)[1] except: parsed['message'] = "" match = regex_get_user.match(parsed['host']) result = match.groupdict() parsed['user'] = result['from_user'] parsed['host'] = result['from_host'] if OPTIONS['debug'] == 'on': weechat.prnt("","debug_mode: hashtable") weechat.prnt("","string: %s" % string) weechat.prnt("","nick: %s" % parsed['nick']) weechat.prnt("","from_user: %s" % parsed['user']) weechat.prnt("","from_host: %s" % parsed['host']) weechat.prnt("","channel: %s" % parsed['channel']) weechat.prnt("","message: %s" % parsed['message']) weechat.prnt("","arguments: %s" % parsed['arguments']) regex_get_channel=re.match(r'#(.*)',parsed['arguments']) if channel != '': weechat.prnt("",regex_get_channel.group()) weechat.prnt("","---end---") return parsed
def parse_message(server, signal_data): """ Parses an IRC PRIVMSG into a hash. Provides support for WeeChat < 0.3.4 Returns: { "arguments": arguments, (includes channel) "channel": channel, "command": command, "host": host, "message": message, "nick": nick, } """ details = {} if int(version) >= 0x00030400: # WeeChat >= 0.3.4, use the built-in irc_message_parse details = weechat.info_get_hashtable("irc_message_parse", { "message": signal_data, "server": server }) else: # This should build an identical hash for WeeChat < 0.3.4 (source, command, channel, message) = signal_data.split(" ", 3) details['arguments'] = "{} {}".format(channel, message) details['channel'] = channel details['command'] = command details['host'] = source.lstrip(":") details['nick'] = weechat.info_get("irc_nick_from_host", signal_data) # WeeChat leaves this step up to us for some reason, ugh. # Split out the actual PRIVMSG. You know, the part we actually care about. details['message'] = details['arguments'].split(" :", 1)[1] return details
def shutup_cb(data, modifier, modifier_data, string): dict_in = {"message": string} message_ht = weechat.info_get_hashtable("irc_message_parse", dict_in) hostmask = message_ht['host'] arguments = message_ht['arguments'] channel = message_ht['channel'] new_arguments = re.sub(r'^%s :.+' % channel, lambda x: '%s :%s' % (channel, replacement_line()), arguments) new_string = re.sub(r'%s$' % re.escape(arguments), lambda x: new_arguments, string) for key, [mask_regexp, channels] in muted_masks.iteritems(): # If there is one or more channels listed for this mask regexp, and none of them match the current channel, continue to the next mute mask if len(channels) > 0 and channel.lower() not in channels: debug("%s doesn't match any of the listed channels: %s" % (channel, channels)) continue # If the hostmask matches the mask regular expression, return the new, manipulated, string. debug("comparing %s to %s" % (mask_regexp.pattern, hostmask)) if mask_regexp.search(hostmask): debug(" %s matches %s" % (mask_regexp.pattern, hostmask)) return new_string # Nothing matches, so return the original, unmodified, string return string
def on_channel_mode(data, signal, signal_data): """Whenever a channel mode is set.""" if w.config_get_plugin("disabled") in ["true", "yes"]: return w.WEECHAT_RC_OK parsed = w.info_get_hashtable("irc_message_parse", {"message": signal_data}) server = signal.split(",")[0] channel = parsed["channel"] if not should_match(server, channel): return w.WEECHAT_RC_OK chars = w.config_get_plugin("matching_modes") modes_set = parsed["text"].split(" ")[0] found = False for c in chars: if c in modes_set: found = True break if not found: return w.WEECHAT_RC_OK modes = parse_modes(parsed["text"]) for mode in modes: mode["setter"] = parsed["nick"] match_mode(server, channel, mode) return w.WEECHAT_RC_OK
def privmsg(data, signal, signal_data): (server, signal) = signal.split(",") channels = wc.config_get_plugin('channels').replace(',', '|') api_key = wc.config_get_plugin('api_key') if re.match('^\${sec\.data\.(.*)}$', api_key): api_key = wc.string_eval_expression(api_key, {}, {}, {}) bots_list = wc.config_get_plugin('other_bots').split(",") details = wc.info_get_hashtable("irc_message_parse", {"message": signal_data, "server": server}) youtube_regex_match = re.compile(r'(.*https?://)?(www\.)?(youtube|youtu|youtube-nocookie)\.(com|be)/(watch\?v=|embed/|v/|.+\?v=)?([a-zA-Z0-9_-]{11})').match(details['text']) buffer_name = details['channel'] buffer_pointer = wc.info_get("irc_buffer", "%s,%s" % (server, buffer_name)) channels_regex = re.compile(r'(%s)' % (channels), re.I) bots_exist = False if channels_regex.match(buffer_name) and youtube_regex_match: if not bots_list == "not_set": for other_bots in bots_list: bots_test = wc.nicklist_search_nick(buffer_pointer, "", other_bots) if bots_test: bots_exist = True if not bots_exist: if not api_key == "not_set": vid_id = youtube_regex_match.group(6) rvt = requests.get('https://www.googleapis.com/youtube/v3/videos/?id={0}&part=snippet&key={1}'.format(vid_id, api_key)) rvc = requests.get('https://www.googleapis.com/youtube/v3/videos/?id={0}&part=statistics&key={1}'.format(vid_id, api_key)) try: vid_title = rvt.json()['items'][0]['snippet']['title'].encode('utf-8') vid_channel = rvt.json()['items'][0]['snippet']['channelTitle'].encode('utf-8') vid_views = rvc.json()['items'][0]['statistics']['viewCount'] wc.command("", r"/msg {0} [Youtube] {1} | Channel: {2} | Views: {3}".format(buffer_name, vid_title, vid_channel, vid_views)) except: wc.command("", r"/msg {0} [Youtube] Error getting video info.".format(buffer_name)) else: wc.command("", r"/msg {0} Youtube api key not set.".format(buffer_name)) return wc.WEECHAT_RC_OK
def _parse_message(self): """Parse the signal_data""" if int(WEECHAT_VERSION) >= 0x00030400: # Newer (>=0.3.4) versions of WeeChat can prepare a hash with most # of what we want. self.details = weechat.info_get_hashtable("irc_message_parse", { "message": self.signal_data(), "server": self.server() }) else: # WeeChat <0.3.4 we have to construct it ourselves. (source, command, channel, message) = ( self._signal_data.split(" ", 3) ) self.details = {} self.details['arguments'] = "{channel} {message}".format( channel=channel, message=message) self.details['channel'] = channel self.details['command'] = command self.details['host'] = source.lstrip(":") self.details['nick'] = weechat.info_get( "irc_nick_from_host", self.signal_data()) # WeeChat leaves this important part to us. Get the actual message. self.details['message'] = self.arguments().split(" :", 1)[1]
def get_hashtable(string): parsed = weechat.info_get_hashtable('irc_message_parse', dict(message=string)) try: parsed['message'] = parsed['arguments'].split(' :', 1)[1] except: parsed['message'] = "" return parsed
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 on_channel_mode(data, signal, signal_data): server = signal.split(",")[0] parsed = w.info_get_hashtable("irc_message_parse", {"message": signal_data}) channel = parsed["channel"] target = w.buffer_search("irc", f"{server}.{channel}") if _is_whitelisted(server, target): modes = parsed["text"] args = [] if " " in modes: modes, _, args = modes.partition(" ") args = list(filter(bool, args.split(" "))) casemap = _get_casemap(server) prefix = w.info_get("irc_server_isupport_value", f"{server},PREFIX").split(")", 1)[0][1:] chanmodes = w.info_get("irc_server_isupport_value", f"{server},CHANMODES").split(",", 3) mode_tokens = _mode_tokens(modes, args, prefix, chanmodes) unique_masks = _unique_mode_masks(casemap, mode_tokens) _match_for_buffer(True, casemap, target, server, channel, unique_masks) return w.WEECHAT_RC_OK
def unhide_buffer_cb(data, signal, signal_data): """Unhide a buffer on new activity. This callback unhides the buffer in which a new message has been received. If configuration option ``unhide_low`` is enabled, buffers with only low messages (like JOIN, PART, etc.) will be unhidden as well. """ server = signal.split(",")[0] message = weechat.info_get_hashtable( "irc_message_parse", {"message": signal_data}) channel = message["channel"] hotlist = hotlist_dict() buffer = weechat.info_get("irc_buffer", "{},{}".format(server, channel)) if not buffer in hotlist.keys(): # just some background noise return WEECHAT_RC_OK if (weechat.config_get_plugin("unhide_low") == "on" and hotlist[buffer]["count_low"] > 0 or hotlist[buffer]["count_message"] > 0 or hotlist[buffer]["count_private"] > 0 or hotlist[buffer]["count_highlight"] > 0): weechat.buffer_set(buffer, "hidden", "0") return WEECHAT_RC_OK
def print_cb(data, buffer, date, tags, displayed, highlight, prefix, message): global last is_private = w.buffer_get_string(buffer, 'localvar_type') == 'private' if (is_private or CONFIG['show_highlight'] == 'on' and highlight == 1) and \ (buffer not in last or time.time() - last[buffer] > CONFIG['rate_limit']) and \ not w.buffer_match_list(buffer, CONFIG['blacklist']): parsed = w.info_get_hashtable('irc_message_parse', {'message': message}) try: body = '<{}> {}'.format(prefix, message) if not is_private: body = '[{}] {}'.format(w.buffer_get_string(buffer, 'short_name'), body) data = json.dumps({ 'type': 'note', 'title': 'weechat', 'body': body, }) if CONFIG['access_token']: #w.prnt(buffer, '{}'.format(body)) urllib2.urlopen(urllib2.Request('https://api.pushbullet.com/v2/pushes', data=data, headers={'Access-Token': CONFIG['access_token'], 'Content-type': 'application/json'})) else: w.prnt('', 'Please get an Access Token at https://www.pushbullet.com/#settings/account and /set plugins.var.python.'+SCRIPT_NAME+'.access_token') except: return w.WEECHAT_RC_ERROR else: last[buffer] = time.time() return w.WEECHAT_RC_OK
def log_to_mongo(data, signal, raw_message): """ Parse a raw IRC message and insert it into a mongo collection """ global mongo_collection parsed_message = weechat.info_get_hashtable('irc_message_parse', { 'message': raw_message }) log_entry = { 'server': signal.split(',')[0], 'nick': parsed_message['nick'], 'host': parsed_message['host'], 'command': parsed_message['command'], 'channel': parsed_message['channel'], 'arguments': parsed_message['arguments'] } if 'text' in parsed_message and len(parsed_message['text']) > 0: log_entry['text'] = parsed_message['text'] elif log_entry['command'] == 'PRIVMSG': # fallback for pre-1.3 weechat log_entry['text'] = log_entry['arguments'].split(' :', 1)[-1] # denote any URLs if 'text' in log_entry and re.search(HTTP_PATTERN, log_entry['text']): log_entry['urls'] = re.findall(HTTP_PATTERN, log_entry['text']) mongo_collection.insert(log_entry) return weechat.WEECHAT_RC_OK
def get_hashtable(string): parsed = weechat.info_get_hashtable("irc_message_parse", dict(message=string)) try: parsed["message"] = parsed["arguments"].split(" :", 1)[1] except: parsed["message"] = "" match = regex_get_user.match(parsed["host"]) result = match.groupdict() parsed["user"] = result["from_user"] parsed["host"] = result["from_host"] if OPTIONS["debug"] == "on": weechat.prnt("", "debug_mode: hashtable") weechat.prnt("", "string: %s" % string) weechat.prnt("", "nick: %s" % parsed["nick"]) weechat.prnt("", "from_user: %s" % parsed["user"]) weechat.prnt("", "from_host: %s" % parsed["host"]) weechat.prnt("", "channel: %s" % parsed["channel"]) weechat.prnt("", "message: %s" % parsed["message"]) weechat.prnt("", "arguments: %s" % parsed["arguments"]) regex_get_channel = re.match(r"#(.*)", parsed["arguments"]) if channel != "": weechat.prnt("", regex_get_channel.group()) weechat.prnt("", "---end---") return parsed
def stop_typing(data, signal, signal_data): msg_hash = w.info_get_hashtable("irc_message_parse", {"message": signal_data}) if msg_hash["nick"] in typing: del typing[msg_hash["nick"]] w.bar_item_update("bitlbee_typing_notice") return w.WEECHAT_RC_OK
def parse_privmsg(message): weechat_result = weechat.info_get_hashtable('irc_message_parse', {'message': message}) if weechat_result['command'].upper() == 'PRIVMSG': args = weechat_result['arguments'].decode('utf-8', 'replace') target, text = args.split(' ', 1) if text.startswith(':'): text = text[1:] result = { 'from': weechat_result['host'].decode('utf-8', 'replace'), 'to': target, 'text': text, } if target[0] in ('#', '&', '!', '+'): result['to_channel'] = target result['to_nick'] = None else: result['to_channel'] = None result['to_nick'] = target return result else: raise Exception("Failed parsing PRIVMSG")
def seamless_cb(data, modifier, modifier_data, string): info = weechat.info_get_hashtable("irc_message_parse", {"message": string}) info["server"] = modifier_data channel = info["channel"] buf_p = weechat.buffer_search("==", "irc." + info["server"] + "." + channel) if not buf_p: debug("no buffer for %s" % "irc." + info["server"] + "." + info["channel"]) return string text = info.get("text", info["arguments"].split(" :", 1)[1]) action = re.match(r"^\x01.*\x01", text) if action: # CTCP if not re.match(r"^\x01ACTION\b", text): # A CTCP other than ACTION, do nothing. return string text = re.sub(r"^\x01ACTION |\x01$", "", text) prefix = "action_" else: # Regular PRIVMSG prefix = "privmsg_" for nick, servers in _nicks: if servers and not (info["server"] in servers): continue nick_re = r"^%s" % re.escape(nick) if not re.match(nick_re, info["nick"]): continue debug("%s is a valid server." % info["server"]) debug("%s matches %s" % (nick_re, nick)) debug(string) for bot in _bots: result = reformat(string, info, bot, prefix, text) if result: return result return string
def whowas_callback_timestamp(data, signal, signal_data): """When the WHOWAS date numeric comes by""" parsed = w.info_get_hashtable("irc_message_parse", {"message": signal_data}) server = signal.split(",")[0] nick = parsed["arguments"].split(" ")[1] timestamp = parsed["arguments"].split(":", 1)[1] buff = find_target_buffer(server, nick) n = fmt_nick(nick) t = fmt_time(timestamp) if not t: # This was most likely a WHOIS, and contained the server description. if w.config_get_plugin("show_errors") in ["true", "yes", "on"]: w.prnt(buff, ("error: Failed to parse timestamp '{}' for {}." " You can neglect this error if this was a WHOIS request." ).format(timestamp, nick)) w.prnt( buff, "error: Please report this issue to the maintainer of the {} script." .format(SCRIPT_NAME)) w.prnt( buff, "error: You can turn this notice off by setting `show_errors' to false." ) else: w.prnt(buff, "{} last seen {} ago".format(n, t)) return w.WEECHAT_RC_OK
def _parse(signal, signal_data): """Parse a signal.""" network = signal.split(',')[0] msg = info_get_hashtable('irc_message_parse', {'message': signal_data}) buf = info_get('irc_buffer', '{},{}'.format(network, msg['channel'])) return network, msg, buf
def handle_globaluserstate(data, modifier, modifier_data, string): """Handles a GLOBALUSERSTATE""" if modifier_data not in (twitch_settings["twitch_server"], twitch_settings["group_server"]): return string parsed = weechat.info_get_hashtable("irc_message_parse", {"message": string}) # All we're interested in are user tags update_user(user_self["name"], parse_tags(parsed["tags"])[1]) return ""
def getbuffer(modifier_data, string): msg = weechat.info_get_hashtable("irc_message_parse",{ "message": string }) if weechat.info_get('irc_is_channel', '{moddata},{channel}'.format(moddata=modifier_data, channel=msg['channel'])) == '1': name = msg['channel'] else: name = msg['nick'] buffer_full_name = '{moddata}.{name}'.format(moddata=modifier_data, name=name) return weechat.buffer_search("irc", buffer_full_name)
def twitch_privmsg(data, modifier, server_name, string): if not server_name in OPTIONS['servers'].split(): return string message = weechat.info_get_hashtable( 'irc_message_parse', {"message": string}) if message['channel'].startswith('#'): return string newmsg = 'PRIVMSG #%s :/w %s %s' % (message['nick'],message['nick'],message['text']) return newmsg
def twitch_whisper(data, modifier, modifier_data, string): message = weechat.info_get_hashtable( 'irc_message_parse', {"message": string}) if message['tags']: string = '@'+message['tags']+' ' else: string = '' string += ':'+message['host'] string += ' PRIVMSG' string += ' '+message['arguments'] return string
def parse_message(irc_message, server=None): # parse the message message_dict = {"message": irc_message} parsed = weechat.info_get_hashtable("irc_message_parse", message_dict) if server: parsed["server"] = server # remove the channel part from PRIVMSG arguments message = ":".join(parsed["arguments"].split(":")[1:]) return(parsed, message)
def handle_userstate(data, modifier, modifier_data, string): """Handles a USERSTATE""" if modifier_data not in (twitch_settings["twitch_server"], twitch_settings["group_server"]): return string parsed = weechat.info_get_hashtable("irc_message_parse", {"message": string}) # We're not interested in tags like emote-set etc. _, user_tags, channel_tags = parse_tags(parsed["tags"]) update_user(user_self["name"], user_tags, parsed["text"], channel_tags) return ""
def handle_bouncer_msg(data, signal, signal_data): server_name = signal.split(",")[0] msg = weechat.info_get_hashtable("irc_message_parse", {"message": signal_data}) args = msg["arguments"].split(" ") if args[0] != "NETWORK": return weechat.WEECHAT_RC_OK # Don't connect twice to the same network netid = args[1] if netid in added_networks: return weechat.WEECHAT_RC_OK_EAT # Retrieve the network name from the attributes net_name = None raw_attr_list = args[2].split(";") for raw_attr in raw_attr_list: k, v = raw_attr.split("=") if k == "name": net_name = v break check_char = lambda ch: ch.isalnum() or ch in ".-_" net_name = "".join(ch if check_char(ch) else "_" for ch in net_name) addr = weechat.config_string( weechat.config_get("irc.server." + server_name + ".addresses")) add_server = [ "/server", "add", net_name, addr, "-temp", "-ssl", ] # User name settings need to be adapted for new networks for k in ["username", "sasl_username"]: v = weechat.config_string( weechat.config_get("irc.server." + server_name + "." + k)) if not v: continue username = v.split("/", maxsplit=1)[0] + "/" + net_name add_server.append("-" + k + "=" + username) for k in ["password", "sasl_mechanism", "sasl_password"]: v = weechat.config_string( weechat.config_get("irc.server." + server_name + "." + k)) add_server.append("-" + k + "=" + v) weechat.command(weechat.buffer_search("core", "weechat"), " ".join(add_server)) weechat.command(weechat.buffer_search("core", "weechat"), "/connect " + net_name) return weechat.WEECHAT_RC_OK_EAT
def handle_query(data, signal, signal_data): global buffer_data # data: empty string # signal: <server>,irc_in_PRIVMSG # signal_data: whole message unparsed # parse the message parsed = weechat.info_get_hashtable("irc_message_parse", {"message": signal_data}) # where should we answer? server = signal.split(",")[0] channel = parsed["channel"] current_nick = weechat.info_get("irc_nick", server) user = parsed["nick"] message = parsed["text"] if channel == current_nick: # we got a message through a private query, refuse it buffer_out = weechat.info_get("irc_buffer", server + "," + user) # close private buffers, but not server buffers # localvar_type can assume five values: private, channel, server, weechat and "" if weechat.buffer_get_string(buffer_out,"localvar_type") == "private": weechat.command(buffer_out, "How about speaking to me in public?") weechat.buffer_close(buffer_out) else: # query came from public channel if message.startswith(current_nick + ":"): # it's a command to our bot query = message.split(":")[1].strip() # remove the part before the colon, and lead/trail whitespaces s = query.split(" ", 1) command = s[0].lower() # command is case-insensitive args = s[1] if len(s) == 2 else "" target = "{0},{1}".format(server, channel) # this is the key to the dict containing the lists if command == "coin": out_msg = _coin() elif command == "help": out_msg = _help(user) elif command == "dice": out_msg = _dice(args) elif command == "server": out_msg = _server() elif command == "about": out_msg = _about() elif command == "rps": out_msg = _rps(user, args) elif command == "list": out_msg = _list(target,user,args) elif command == "coffee": out_msg = _coffee() elif command == "eightball": out_msg = _8ball() else: out_msg = "Unrecognized command. Type '{0}: help' to get a list of commands".format(current_nick) buffer_out = weechat.info_get("irc_buffer", server + "," + channel) if weechat.buffer_get_string(buffer_out,"localvar_type") == "channel": weechat.command(buffer_out, out_msg) return weechat.WEECHAT_RC_OK # must always return this or WEECHAT_RC_ERROR
def mode_cb(data, signal, signal_data): weechat.prnt('', signal_data) global users server = signal.split(",")[0] msg = weechat.info_get_hashtable("irc_message_parse", {"message": signal_data}) if not any(msg['host'] in u for u in users): weechat.command('', 'bastard! ' + msg['nick']) return weechat.WEECHAT_RC_OK
def ircrypt_encrypt_hook(data, msgtype, server, args): '''Hook for outgoing PRVMSG commands. This method will call the appropriate methods for encrypting the outgoing messages either symmetric or asymmetric :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 this message is to be send as plain text plain = ircrypt_message_plain.get('%s/%s' % (server, info['channel'])) if plain: del ircrypt_message_plain['%s/%s' % (server, info['channel'])] if (plain[0] - time.time()) < 5 \ and args == 'PRIVMSG %s :%s' % (info['channel'], plain[1]): args = args.replace( 'PRIVMSG %s :%s ' % (info['channel'], weechat.config_string(ircrypt_config_option['unencrypted'])), 'PRIVMSG %s :' % info['channel']) return args # check symmetric key key = ircrypt_keys.get(('%s/%s' % (server, info['channel'])).lower()) if not key: # No key -> don't encrypt return args # Get cipher cipher = ircrypt_cipher.get( ('%s/%s' % (server, info['channel'])).lower(), weechat.config_string(ircrypt_config_option['sym_cipher'])) # Get prefix and message pre, message = args.split(':', 1) # encrypt message try: inp = key.encode('utf-8') + b'\n' + message.encode('utf-8') except: inp = key + b'\n' + message (ret, out, err) = ircrypt_gnupg(inp, '--symmetric', '--cipher-algo', cipher, '--passphrase-fd', '-') # Get and print GPG errors/warnings if ret: buf = weechat.buffer_search('irc', '%s.%s' % (server, info['channel'])) ircrypt_error(err.decode('utf-8'), buf) return args if err: ircrypt_warn(err.decode('utf-8')) # Ensure the generated messages are not too long and send them return ircrypt_split_msg(pre, 'CRY', base64.b64encode(out).decode('utf-8'))
def beinc_privmsg_handler(data, signal, signal_data): """Callback function the *PRIVMSG* IRC messages hooked by Weechat""" if not enabled: return weechat.WEECHAT_RC_OK prvmsg_dict = weechat.info_get_hashtable('irc_message_parse', {'message': signal_data}) # packing the privmsg handler values ph_values = {} ph_values['server'] = signal.split(',')[0] ph_values['own_nick'] = weechat.info_get('irc_nick', ph_values['server']) ph_values['channel'] = prvmsg_dict['arguments'].split(':')[0].strip() ph_values['source_nick'] = prvmsg_dict['nick'] ph_values['message'] = ':'.join( prvmsg_dict['arguments'].split(':')[1:]).strip() if ph_values['channel'] == ph_values['own_nick']: # priv messages are handled here if not global_values['global_private_messages_policy']: return weechat.WEECHAT_RC_OK for target in target_list: if not target.enabled: continue p_messages_policy = target.private_messages_policy if p_messages_policy == BEINC_POLICY_ALL or ( p_messages_policy == BEINC_POLICY_LIST_ONLY and '{0}.{1}'.format( ph_values['server'], ph_values['source_nick'].lower()) in target.nicks): target.send_private_message_notification(ph_values) elif ph_values['own_nick'].lower() in ph_values['message'].lower(): # notify messages are handled here if not global_values['global_notifications_policy']: return weechat.WEECHAT_RC_OK for target in target_list: if not target.enabled: continue if target.notifications_policy == BEINC_POLICY_ALL or ( target.notifications_policy == BEINC_POLICY_LIST_ONLY and '{0}.{1}'.format( ph_values['server'], ph_values['channel'].lower()) in target.chans): target.send_notify_message_notification(ph_values) elif global_values['global_channel_messages_policy']: # chan messages are handled here if not global_values['global_notifications_policy']: return weechat.WEECHAT_RC_OK for target in target_list: if not target.enabled: continue c_messages_policy = target.channel_messages_policy if c_messages_policy == BEINC_POLICY_ALL or ( c_messages_policy == BEINC_POLICY_LIST_ONLY and '{0}.{1}'.format( ph_values['server'], ph_values['channel'].lower()) in target.chans): target.send_channel_message_notification(ph_values) return weechat.WEECHAT_RC_OK
def parse_message(signal_data): hashtable = weechat.info_get_hashtable("irc_message_parse", {"message": signal_data}) # parse arguments string into usable pieces args = hashtable["arguments"].split(":", 1) hashtable["args"] = args[0].split() if len(args) > 1: hashtable["text"] = args[1] return hashtable
def parse_message(data, signal, signal_data): """ parse the data in the three strings and return a dict """ # info_get_hashtable docs: # http://www.weechat.org/files/doc/devel/weechat_scripting.en.html#irc_message_parse hm = weechat.info_get_hashtable("irc_message_parse", {"message":signal_data}) # servername where the message came from signal, for irc => " hm["server"] = signal.split(",")[0] # strip channel-name from arguments and then the leading colon hm["message"] = hm["arguments"].lstrip(hm["channel"]).lstrip()[1:] return hm
def twitch_whois(data, modifier, server_name, string): if not server_name in OPTIONS['servers'].split(): return string msg = weechat.info_get_hashtable("irc_message_parse", {"message": string}) username = msg['nick'] currentbuf = weechat.current_buffer() url = 'https://api.twitch.tv/kraken/channels/' + username url_hook = weechat.hook_process( "url:" + url+params, 7 * 1000, "channel_api", currentbuf) return ""
def twitch_whois(data, modifier, server_name, string): if not server_name in OPTIONS['servers'].split(): return string msg = weechat.info_get_hashtable("irc_message_parse", {"message": string}) username = msg['nick'].lower() currentbuf = weechat.current_buffer() url = 'https://api.twitch.tv/kraken/channels/' + username url_hook = weechat.hook_process_hashtable( "url:" + url+params, curlopt, 7 * 1000, "channel_api", str({'buffer': currentbuf, 'name': username})) return ""
def urlserver_modifier_irc_cb(data, modifier, modifier_data, string): """Modifier for IRC message: add short URLs at the end of IRC message.""" global urlserver, urlserver_settings if urlserver_settings['display_urls_in_msg'] != 'on': return string msg = weechat.info_get_hashtable( 'irc_message_parse', {'message': string, 'server': modifier_data}) if 'nick' not in msg or 'channel' not in msg or 'arguments' not in msg: return string try: message = msg['arguments'].split(' ', 1)[1] if message.startswith(':'): message = message[1:] except: return string info_name = '%s,%s' % (modifier_data, msg['channel']) if weechat.info_get('irc_is_channel', info_name) == '1': name = msg['channel'] else: name = msg['nick'] buffer_full_name = 'irc.%s.%s' % (modifier_data, name) if urlserver_settings['buffer_short_name'] == 'on': buffer_short_name = name else: buffer_short_name = buffer_full_name urls_short = urlserver_update_urllist(buffer_full_name, buffer_short_name, None, msg['nick'], message, msg['nick']) 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 + ' ]' if urlserver_settings['color_in_msg']: urls_string = '\x03%s%s' % (urlserver_settings['color_in_msg'], urls_string) string = "%s %s" % (string, urls_string) return string
def print_message_cb(data, signal, signal_data): """Parse raw IRC messages and extract the network, channel and message text from the message""" server = signal.split(",")[0] message = weechat.info_get_hashtable("irc_message_parse", {"message": signal_data}) message_text = message["arguments"][message["arguments"].find(':') + 1:] parse_url(server, channel=message["channel"], nick=message["nick"], message=message_text) return WEECHAT_RC_OK
def check_signal(signal, signal_data): msg_info = weechat.info_get_hashtable("irc_message_parse", { "message": signal_data}) content = msg_info["arguments"].split(":"); content = ":".join(content[1:len(content)]) nick = weechat.info_get("irc_nick", signal.split(",")[0]) qualifies = (msg_info["channel"] not in blacklist) or whitelist_nick and (nick in content) return (qualifies, msg_info, content)
def ircrypt_encrypt_hook(data, msgtype, server, args): '''Hook for outgoing PRVMSG commands. This method will call the appropriate methods for encrypting the outgoing messages either symmetric or asymmetric :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 this message is to be send as plain text plain = ircrypt_message_plain.get('%s/%s' % (server, info['channel'])) if plain: del ircrypt_message_plain['%s/%s' % (server, info['channel'])] if (plain[0] - time.time()) < 5 \ and args == 'PRIVMSG %s :%s' % (info['channel'], plain[1]): args = args.replace('PRIVMSG %s :%s ' % ( info['channel'], weechat.config_string(ircrypt_config_option['unencrypted'])), 'PRIVMSG %s :' % info['channel']) return args # check symmetric key key = ircrypt_keys.get(('%s/%s' % (server, info['channel'])).lower()) if not key: # No key -> don't encrypt return args # Get cipher cipher = ircrypt_cipher.get(('%s/%s' % (server, info['channel'])).lower(), weechat.config_string(ircrypt_config_option['sym_cipher'])) # Get prefix and message pre, message = args.split(':', 1) # encrypt message try: inp = key.encode('utf-8') + b'\n' + message.encode('utf-8') except: inp = key + b'\n' + message (ret, out, err) = ircrypt_gnupg(inp, '--symmetric', '--cipher-algo', cipher, '--passphrase-fd', '-') # Get and print GPG errors/warnings if ret: buf = weechat.buffer_search('irc', '%s.%s' % (server, info['channel'])) ircrypt_error(err.decode('utf-8'), buf) return args if err: ircrypt_warn(err.decode('utf-8')) # Ensure the generated messages are not too long and send them return ircrypt_split_msg(pre, 'CRY', base64.b64encode(out).decode('utf-8'))
def modifier_cb(data, modifier, modifier_data, string): global nsbuffer input = weechat.info_get_hashtable("irc_message_parse", { "message": string }) if modifier_data == NETWORK and _newserv_match(input["nick"]): if not nsbuffer: open_newserv_buffer() ncolor = weechat.info_get("irc_nick_color_name", input["nick"]) weechat.prnt(nsbuffer, "{}{}{}\t{}".format(weechat.color(ncolor), input["nick"], weechat.color("reset"), input["text"])) return "" return string
def privmsg_event(self,data, modifier, server, string): parsed = weechat.info_get_hashtable("irc_message_parse", { "message": string }) args = parsed['arguments'].split(None,1)[-1][1:] text = args.strip(chr(1)) nick = parsed['nick'] #data.split()[0].split('!')[0][1:] target = parsed['channel'] atype = self.isAdMessage(text,nick,'CHANNEL',target,server) if atype: if self.processAdMessage(atype,text,target,server,nick): return '' return string
def join_cb(data, signal, signal_data): server = signal.split(",")[0] msg = weechat.info_get_hashtable("irc_message_parse", {"message": signal_data}) buffer = weechat.info_get("irc_buffer", "%s,%s" % (server, msg["channel"])) if buffer: if debug: weechat.prnt( buffer, '%s (%s) has joined. Welcome!' % (msg['nick'], msg['host'])) weechat.command(buffer, 'для здоровья!') return weechat.WEECHAT_RC_OK
def join_cb(data, signal, signal_data): # signal is for example: "freenode,irc_in2_join" # signal_data is IRC message, for example: ":nick!user@host JOIN :#channel" server = signal.split(",")[0] msg = weechat.info_get_hashtable("irc_message_parse", {"message": signal_data}) buffer = weechat.info_get("irc_buffer", "%s,%s" % (server, msg["channel"])) if buffer: weechat.prnt( buffer, "%s (%s) has joined this channel jsfh sdjskjdf sf!" % (msg["nick"], msg["host"])) return weechat.WEECHAT_RC_OK
def twitch_usernotice(data, modifier, server, string): pcolor = weechat.color('chat_prefix_network') ccolor = weechat.color('chat') mp = weechat.info_get_hashtable('irc_message_parse', {"message": string}) buffer = weechat.buffer_search("irc", "%s.%s" % (server, mp['channel'])) if mp['tags']: tags = dict([s.split('=') for s in mp['tags'].split(';')]) msg = tags['system-msg'].replace('\s', ' ') if mp['text']: msg += ' [Comment] ' + mp['text'] weechat.prnt(buffer, '%s--%s %s' % (pcolor, ccolor, msg)) return ''
def check_message(data, signal, signal_data): dict = weechat.info_get_hashtable("irc_message_parse", {"message": signal_data}) nick = dict["nick"] channel = dict["channel"] if nick == "triggerbot": try: if channel.split("_")[1]: triggersafechannel = True except IndexError: triggersafechannel = False if triggersafechannel: buffer = weechat.info_get( "irc_buffer", "%s,%s" % (signal.split(",")[0], channel)) group = weechat.nicklist_search_group(buffer, "", "triggerbot") if not group: group = weechat.nicklist_add_group( buffer, "", "triggerbot", "weechat.color.nicklist_group", 1) triggerbotbuffers[buffer] = group # Is this a list of nicks? if dict["arguments"].find("Nicks %s: [" % channel) != -1: names = dict["arguments"].split( "Nicks %s: [" % channel)[1].split("]")[0].split(" ") set_nicklist(names, buffer, group) # Is this a join message? elif dict["arguments"].split(":")[1].startswith( "[INFO] ") and dict["arguments"].find(" has joined") != -1: name = dict["arguments"].split("[INFO] ")[1].split( " has joined")[0] add_nick(name, buffer, group) # A leave message? elif dict["arguments"].split(":")[1].startswith( "[INFO] ") and dict["arguments"].find(" has left") != -1: name = dict["arguments"].split("[INFO] ")[1].split( " has left")[0] remove_nick(name, buffer, group) # A quit message? (Don't search for the dot here because a reason may be displayed) elif dict["arguments"].split(":")[1].startswith( "[INFO] ") and dict["arguments"].find(" has quit") != -1: name = dict["arguments"].split("[INFO] ")[1].split( " has quit")[0] remove_nick(name, buffer, group) elif dict["arguments"].split(":")[1].startswith( "[INFO] " ) and dict["arguments"].find(" is now known as ") != -1: oldname = dict["arguments"].split("[INFO] ")[1].split( " is now known as ")[0] newname = dict["arguments"].split("[INFO] ")[1].split( " is now known as ")[1].split(".")[0] remove_nick(oldname, buffer, group) add_nick(newname, buffer, group) return weechat.WEECHAT_RC_OK
def ap_input_is_secured_data(input_text): """Check if input_text is any value of a secured data.""" check = ap_settings['check_secured_data'] if check == 'off': return False sec_data = weechat.info_get_hashtable('secured_data', {}) or {} if check == 'include': for value in sec_data.values(): if value and value in input_text: return True if check == 'equal': return input_text.strip() in sec_data.values() return False
def handle_bouncer_msg(data, signal, signal_data): server = signal.split(",")[0] msg = weechat.info_get_hashtable("irc_message_parse", {"message": signal_data}) args = msg["arguments"].split(" ") if args[0] != "NETWORK": return weechat.WEECHAT_RC_OK # Don't connect twice to the same network netid = args[1] if netid in added_networks: return weechat.WEECHAT_RC_OK_EAT # Retrieve the network name from the attributes net_name = None raw_attr_list = args[2].split(";") for raw_attr in raw_attr_list: k, v = raw_attr.split("=") if k == "name": net_name = v break addr = weechat.config_string( weechat.config_get("irc.server." + server + ".addresses")) username = weechat.config_string( weechat.config_get("irc.server." + server + ".username")) if "/" in username: username = username.split("/")[0] add_server = [ "/server", "add", net_name, addr, "-temp", "-ssl", "-username="******"/" + net_name, ] for k in ["password", "sasl_mechanism", "sasl_username", "sasl_password"]: v = weechat.config_string( weechat.config_get("irc.server." + server + "." + k)) add_server.append("-" + k + "=" + v) weechat.command(weechat.buffer_search("core", "weechat"), " ".join(add_server)) weechat.command(weechat.buffer_search("core", "weechat"), "/connect " + net_name) return weechat.WEECHAT_RC_OK_EAT