def send_notification(data): if is_debug(): weechat.prnt(weechat.buffer_search_main(), "irssinotifier: sending notification") api_token = weechat.config_get_plugin("api_token") url = "https://irssinotifier.appspot.com/API/Message" nick = data['cryptdata']['nick']['value'] chan = data['cryptdata']['chan']['value'] message = data['cryptdata']['message']['value'] postdata = urllib.urlencode({'apiToken':api_token,'nick':nick,'channel':chan,'message':message,'version':13}) if is_debug(): weechat.prnt(weechat.buffer_search_main(), "irssinotifier: postdata: %s" % postdata) hook1 = weechat.hook_process_hashtable("url:"+url, { "postfields": postdata}, 30000, "send_notification_cb", "")
def server_switch(signal_data, servername_from_current_buffer, name): global look_server SERVER = {} bufpointer = weechat.window_get_pointer(weechat.current_window(), "buffer") servername_current_buffer = servername_from_current_buffer if look_server == "merge_with_core": # merge_with_core SERVER["weechat"] = "core.weechat" # get ALL server buffers and save them infolist = weechat.infolist_get( "buffer", "", "*server.*") # we are only interest in server-buffers while weechat.infolist_next(infolist): bufpointer = weechat.infolist_pointer(infolist, "pointer") server = weechat.infolist_string( infolist, "name") # full servername (server.<servername>) servername = weechat.infolist_string( infolist, "short_name" ) # get servername from server (without prefix "server") active = weechat.infolist_integer(infolist, "active") SERVER[servername] = server if (active == 1) and (servername_current_buffer != servername ): # buffer active but not correct server buffer? weechat.command( bufpointer, "/input switch_active_buffer") # switch server buffer weechat.infolist_free(infolist) # do not forget to free infolist! # switch though all server and stop at server from current buffer i = 0 while i <= len(SERVER): for servername, full_name in list(SERVER.items()): bufpointer = weechat.buffer_search( "irc", "%s" % full_name) # search pointer from server buffer if bufpointer == "": # core buffer if weechat.buffer_get_integer(weechat.buffer_search_main(), 'active') == 1: weechat.command(weechat.buffer_search_main(), "/input switch_active_buffer") else: # server buffer! if (servername != servername_current_buffer) and ( weechat.buffer_get_integer(bufpointer, 'active') == 1): weechat.command(bufpointer, "/input switch_active_buffer") elif (servername == servername_current_buffer) and ( weechat.buffer_get_integer(bufpointer, 'active') == 1): i = len(SERVER) break i += 1
def find_buffer(server, nick, message_type='whois'): # See if there is a target msgbuffer set for this server msgbuffer = weechat.config_string( weechat.config_get('irc.msgbuffer.%s.%s' % (server, message_type))) # No whois msgbuffer for this server; use the global setting if msgbuffer == '': msgbuffer = weechat.config_string( weechat.config_get('irc.msgbuffer.%s' % message_type)) # Use the fallback msgbuffer setting if private buffer doesn't exist if msgbuffer == 'private': buffer = weechat.buffer_search('irc', '%s.%s' % (server, nick)) if buffer != '': return buffer else: msgbuffer = weechat.config_string( weechat.config_get('irc.look.msgbuffer_fallback')) # Find the appropriate buffer if msgbuffer == "current": return weechat.current_buffer() elif msgbuffer == "weechat": return weechat.buffer_search_main() else: return weechat.buffer_search('irc', 'server.%s' % server)
def test_plugins(): """Test plugins functions.""" check(weechat.plugin_get_name('') == 'core') check( weechat.plugin_get_name( weechat.buffer_get_pointer(weechat.buffer_search_main(), 'plugin')) == 'core')
def hipchat_cmd(data, buffer, args): bitlbee_server = weechat.buffer_get_string(buffer, 'name').split('.')[0] if buffer == weechat.buffer_search_main(): weechat.prnt('', 'Hipchat commands must be run in IRC buffer') return weechat.WEECHAT_RC_ERROR if args.startswith('rooms'): room_args = args.split(' ', 1) if room_args[-1].startswith('**'): keyEvent(data, buffer, room_args[-1][2:]) return weechat.WEECHAT_RC_OK rooms_initialise_list(bitlbee_server) weechat.hook_process("url:https://api.hipchat.com/v2/room?auth_token=%s&max-results=1000" % get_token(), 30 * 1000, "room_list_cb", "") elif args == 'autojoin': rooms_initialise_list(bitlbee_server) nick = weechat.info_get('irc_nick', bitlbee_server) weechat.hook_process('url:https://api.hipchat.com/v2/user/@%s/preference/auto-join?' 'auth_token=%s&max-results=500' % (nick, get_token()), 30 * 1000, 'room_list_cb', '') elif args.startswith('whois'): whois_start(args[5:].strip()) elif args == 'fullnames': update_fullnames(buffer) elif args.startswith('nicks'): show_nicks(args.split(' ', 1)[-1]) return weechat.WEECHAT_RC_OK
def wsl_notify_command_cb(data, buffer, args): if args == 'silent_mode': toggle_silent() elif args == 'gen_appid_script': gen_appid_script() else: wc.prnt(wc.buffer_search_main(), f'{wc.prefix("error")}wsl_notify: specify a valid command') return wc.WEECHAT_RC_OK
def filter_addreplace(name, buffers, tags, regex): """ Add (or replace if already exists) a filter named "name" with specified argumets. """ if filter_exists(name): filter_del(name) weechat.command(weechat.buffer_search_main(), "/mute filter add %s %s %s %s" % (name, buffers, tags, regex))
def link_cb(data, buf, date, tags, displayed, hilight, prefix, message): # don't look at own output or output in core buffer if prefix == SCRIPT_PREFIX or buf == weechat.buffer_search_main(): return weechat.WEECHAT_RC_OK # only fetch link titles for http|https schemas # no need for full RFC regex (RFC 3986); urllib2 takes care of the rest for link in re.findall('https?://[^ ">]+', message, re.I): print_link_title(buf, link) return weechat.WEECHAT_RC_OK
def prepare_notifications_cb(data, remaining_calls): global notifications if is_debug(): weechat.prnt(weechat.buffer_search_main(), "irssinotifier: Preparing notifications...") # Make sure we have an API token to begin with if not weechat.config_get_plugin("api_token"): weechat.prnt(weechat.buffer_search_main(), "irssinotifier: plugin option 'api_token' is not set, not sending notifications...") return weechat.WEECHAT_RC_OK # Assume that within the 'group message time' only one person caused a notification. message = "" for notification in notifications: chan = notification['chan'] nick = notification['nick'] if len(message) == 0: message = notification['message'] else: message = message + "\n" + notification['message'] # Log that we combined messages if is_debug() and len(notifications) > 1: weechat.prnt(weechat.buffer_search_main(), "irssinotifier: more than one notification within grouping time, combined %d notifications into chan: %s, nick: %s, message: %s" % (len(notifications), chan, nick, message)) # Make a new object with all the values that we need encrypted notificationdata = { 'tmpfile': "", 'password': weechat.config_get_plugin("encryption_password"), 'cryptdata': { 'chan': {'value': chan, 'isencrypted': False}, 'nick': {'value': nick, 'isencrypted': False}, 'message': {'value': message, 'isencrypted': False} } } # Clear the notifications notifications = [] # Start the async encrypting encrypt_notification_cb(pickle.dumps(notificationdata), "", 0, "", "") return weechat.WEECHAT_RC_OK
def parse_wslpath(): global image wslpath_cmd = ['wslpath', '-w', wc.config_get_plugin('icon_path')] p = subprocess.run(wslpath_cmd, capture_output=True, text=True) if p.stdout: image = p.stdout.strip('\n') if p.stderr: image = 'noicon' # reset Windows image path so user notices something is wrong without having to check core buffer wc.prnt( wc.buffer_search_main(), f'{wc.prefix("error")}wsl_notify: Image file not found - check path' ) return image
def hdata_update_history_cmd(data, buffer, args): hdata = weechat.hdata_get('history') # add to global history weechat.hdata_update(hdata, '', { 'text': 'test global 1' }) weechat.hdata_update(hdata, '', { 'text': 'test global 2' }) # add to history of core buffer core_buffer = weechat.buffer_search_main() weechat.hdata_update(hdata, '', { 'buffer': core_buffer, 'text': 'test core buffer 1' }) weechat.hdata_update(hdata, '', { 'buffer': core_buffer, 'text': 'test core buffer 2' }) return weechat.WEECHAT_RC_OK
def notify(notif_data): global last_notification_time if time.time() - last_notification_time < notif_delay_time: wc.prnt( wc.buffer_search_main(), f'wsl_notify: notification from buffer "{notif_data[2]}" suppressed - sending notifications too fast!' ) return wc.WEECHAT_RC_OK sound = wc.config_get_plugin('sound') if sound not in valid_sounds: wc.prnt( wc.buffer_search_main(), f'{wc.prefix("error")}wsl_notify: Invalid sound, valid sounds are: {valid_sounds}' ) sound = 'Default' if true[wc.config_get_plugin('silent_mode')]: audio_cmd = 'New-BTAudio -Silent' else: if fnmatch.fnmatch(sound, 'Alarm*') or fnmatch.fnmatch(sound, 'Call*'): audio_cmd = f"New-BTAudio -Source 'ms-winsoundevent:Notification.Looping.{sound}'" else: audio_cmd = f"New-BTAudio -Source 'ms-winsoundevent:Notification.{sound}'" appID = "-AppId 'weechat.wsl_notify'" if true[wc.config_get_plugin( 'use_custom_AppID')] else '' command = ( f"$Text1 = New-BTText -Content '{notif_data[0]}';" f"$Text2 = New-BTText -Content '{notif_data[1]}';" f"$ImagePath = '{parse_wslpath()}';" "$AppLogo = New-BTImage -Source $ImagePath -AppLogoOverride;" f"$Audio = {audio_cmd};" "$Binding = New-BTBinding -Children $Text1, $Text2 -AppLogoOverride $AppLogo;" "$Visual = New-BTVisual -BindingGeneric $Binding;" "$Content = New-BTContent -Visual $Visual -Audio $Audio;" f"Submit-BTNotification -Content $Content {appID};") subprocess.Popen(['powershell.exe', '-command', command], stdout=subprocess.DEVNULL) last_notification_time = time.time() return wc.WEECHAT_RC_OK
def server_switch(signal_data,servername_from_current_buffer,name): global look_server SERVER = {} bufpointer = weechat.window_get_pointer(weechat.current_window(),"buffer") servername_current_buffer = servername_from_current_buffer if look_server == "merge_with_core": # merge_with_core SERVER["weechat"] = "core.weechat" # get ALL server buffers and save them infolist = weechat.infolist_get("buffer","","*server.*") # we are only interest in server-buffers while weechat.infolist_next(infolist): bufpointer = weechat.infolist_pointer(infolist,"pointer") server = weechat.infolist_string(infolist, "name") # full servername (server.<servername>) servername = weechat.infolist_string(infolist, "short_name") # get servername from server (without prefix "server") active = weechat.infolist_integer(infolist,"active") SERVER[servername] = server if (active == 1) and (servername_current_buffer != servername): # buffer active but not correct server buffer? weechat.command(bufpointer,"/input switch_active_buffer") # switch server buffer weechat.infolist_free(infolist) # do not forget to free infolist! # switch though all server and stop at server from current buffer i = 0 while i <= len(SERVER): for servername,full_name in SERVER.items(): bufpointer = weechat.buffer_search("irc","%s" % full_name) # search pointer from server buffer if bufpointer == "": # core buffer if weechat.buffer_get_integer(weechat.buffer_search_main(),'active') == 1: weechat.command(weechat.buffer_search_main(),"/input switch_active_buffer") else: # server buffer! if (servername != servername_current_buffer) and (weechat.buffer_get_integer(bufpointer,'active') == 1): weechat.command(bufpointer,"/input switch_active_buffer") elif (servername == servername_current_buffer) and (weechat.buffer_get_integer(bufpointer,'active') == 1): i = len(SERVER) break i += 1
def find_target_buffer(server, nick): """Return the buffer the user most likely wants their data printed to""" targets = { "current": w.current_buffer(), "weechat": w.buffer_search_main(), "server": w.buffer_search("irc", "server.{}".format(server)), "private": w.buffer_search("irc", "{}.{}".format(server, nick)) } opt = w.config_string(w.config_get("irc.msgbuffer.whois")) target = "" if opt.lower() in targets: target = targets[opt] return target
def get_buffer(server, nick): msgbuffer = weechat.config_string(weechat.config_get('irc.msgbuffer.%s.%s' % (server, 'whois'))) if msgbuffer == '': msgbuffer = weechat.config_string(weechat.config_get('irc.msgbuffer.%s' % 'whois')) if msgbuffer == 'private': buffer = weechat.buffer_search('irc', '%s.%s' %(server, nick)) if buffer != '': return buffer else: msgbuffer = weechat.config_string(weechat.config_get('irc.look.msgbuffer_fallback')) if msgbuffer == "current": return weechat.current_buffer() elif msgbuffer == "weechat": return weechat.buffer_search_main() else: return weechat.buffer_search('irc', 'server.%s' % server)
def gen_appid_script(*args, **kwargs): image = parse_wslpath() script = """ if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {{ $arguments = "& '" +$myinvocation.mycommand.definition + "'" Start-Process powershell -Verb runAs -ArgumentList $arguments Break }} $AppID = 'weechat.wsl_notify' $AppDisplayName = 'WeeChat (via wsl_notify)' $AppImage = '{}' $HKCR = Get-PSDrive -Name HKCR -ErrorAction SilentlyContinue If (!($HKCR)) {{ New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT -Scope Script }} $AppRegPath = "HKCR:\\AppUserModelId" $RegPath = "$AppRegPath\\$AppID" If (!(Test-Path $RegPath)) {{ New-Item -Path $AppRegPath -Name $AppID -Force }} $DisplayName = Get-ItemProperty -Path $RegPath -Name DisplayName -ErrorAction SilentlyContinue | Select -ExpandProperty DisplayName -ErrorAction SilentlyContinue If ($DisplayName -ne $AppDisplayName) {{ New-ItemProperty -Path $RegPath -Name DisplayName -Value $AppDisplayName -PropertyType String -Force }} $ShowInSettingsValue = Get-ItemProperty -Path $RegPath -Name ShowInSettings -ErrorAction SilentlyContinue | Select -ExpandProperty ShowInSettings -ErrorAction SilentlyContinue If ($ShowInSettingsValue -ne $ShowInSettings) {{ New-ItemProperty -Path $RegPath -Name ShowInSettings -Value 1 -PropertyType Dword -Force }} $IconUriValue = Get-ItemProperty -Path $RegPath -Name IconUri -ErrorAction SilentlyContinue | Select -ExpandProperty IconUri -ErrorAction SilentlyContinue If ($IconUriValue -ne $AppImage) {{ New-ItemProperty -Path $RegPath -Name IconUri -Value $AppImage -PropertyType ExpandString -Force }} Remove-PSDrive -Name HKCR -Force """.format(image) file_name = 'AddUpdateWeechatAppID.ps1' userprofile = subprocess.check_output(['wslvar', 'USERPROFILE'], text=True) profile_path = subprocess.check_output(['wslpath', userprofile], text=True).strip('\n') with open(f'{profile_path}/{file_name}', 'w') as file: file.writelines(script) wc.prnt(wc.buffer_search_main(), f'wsl_notify: appid script written to {profile_path}/{file_name}') return wc.WEECHAT_RC_OK
def hdata_update_history_cmd(data, buffer, args): hdata = weechat.hdata_get('history') # add to global history weechat.hdata_update(hdata, '', {'text': 'test global 1'}) weechat.hdata_update(hdata, '', {'text': 'test global 2'}) # add to history of core buffer core_buffer = weechat.buffer_search_main() weechat.hdata_update(hdata, '', { 'buffer': core_buffer, 'text': 'test core buffer 1' }) weechat.hdata_update(hdata, '', { 'buffer': core_buffer, 'text': 'test core buffer 2' }) return weechat.WEECHAT_RC_OK
def get_buffer(server, nick): msgbuffer = weechat.config_string( weechat.config_get('irc.msgbuffer.%s.%s' % (server, 'whois'))) if msgbuffer == '': msgbuffer = weechat.config_string( weechat.config_get('irc.msgbuffer.%s' % 'whois')) if msgbuffer == 'private': buffer = weechat.buffer_search('irc', '%s.%s' % (server, nick)) if buffer != '': return buffer else: msgbuffer = weechat.config_string( weechat.config_get('irc.look.msgbuffer_fallback')) if msgbuffer == "current": return weechat.current_buffer() elif msgbuffer == "weechat": return weechat.buffer_search_main() else: return weechat.buffer_search('irc', 'server.%s' % server)
def find_buffer(server, nick, message_type='whois'): # See if there is a target msgbuffer set for this server msgbuffer = weechat.config_string(weechat.config_get('irc.msgbuffer.%s.%s' % (server, message_type))) # No whois msgbuffer for this server; use the global setting if msgbuffer == '': msgbuffer = weechat.config_string(weechat.config_get('irc.msgbuffer.%s' % message_type)) # Use the fallback msgbuffer setting if private buffer doesn't exist if msgbuffer == 'private': buffer = weechat.buffer_search('irc', '%s.%s' %(server, nick)) if buffer != '': return buffer else: msgbuffer = weechat.config_string(weechat.config_get('irc.look.msgbuffer_fallback')) # Find the appropriate buffer if msgbuffer == "current": return weechat.current_buffer() elif msgbuffer == "weechat": return weechat.buffer_search_main() else: return weechat.buffer_search('irc', 'server.%s' % server)
def upgrade_ended_cb(data, signal, signal_data): weechat.buffer_set(weechat.buffer_search_main(), 'localvar_set_histman', 'on') return weechat.WEECHAT_RC_OK
' text: save text only (text sent to a channel buffer)\n' ' all: save commands and text\n' '\n' 'Examples:\n' ' save the command history manually (for example with /cron script or with an /trigger):\n' ' /' + SCRIPT_NAME + ' save\n' ' save and restore command history for buffer #weechat on freenode (text only):\n' ' /buffer_autoset add irc.freenode.#weechat localvar_set_save_history text\n' ' save and restore command history for weechat core buffer (commands only):\n' ' /buffer_autoset add core.weechat localvar_set_save_history command\n', 'save %-' '|| list %-', 'histman_cmd_cb', '') if int(version) >= 0x00040000: if weechat.buffer_get_string(weechat.buffer_search_main(),'localvar_histman') == 'on': init_options() create_hooks() weechat.prnt('','%s%s: do not start this script two times. command history was already restored, during this session!' % (weechat.prefix('error'),SCRIPT_NAME)) else: init_options() # create dir, if not exist config_create_dir() # look for global_history if OPTIONS['save_global'].lower() != 'off': read_history(filename_global_history,'') # core buffer is already open on script startup. Check manually! filename = get_filename_with_path('core.weechat') read_history('core.weechat',weechat.buffer_search_main())
# Plugin entry method if __name__ == "__main__": weechat.register("irssinotifier", "Caspar Clemens Mierau <*****@*****.**>, Martijn Stolk <*****@*****.**>", "0.6", "GPL3", "irssinotifier: Send push notifications to Android's IrssiNotifier about your private message and highligts.", "", "") # Initialize some variables settings = { "api_token": "", "encryption_password": "", "debug": "off", "group_messages_time_ms": "1000" } notifications = [] sendtimer = None # Set initial plugin values so they can be found in /set for option, default_value in settings.items(): if not weechat.config_get_plugin(option): weechat.config_set_plugin(option, default_value) # Check mandatory settings if not weechat.config_get_plugin("api_token"): weechat.prnt(weechat.buffer_search_main(), weechat.prefix("error") + "irssinotifier: Please configure your API token: /set plugins.var.python.irssinotifier.api_token <token>") if not weechat.config_get_plugin("encryption_password"): weechat.prnt(weechat.buffer_search_main(), weechat.prefix("error") + "irssinotifier: Please configure your encryption password: /set plugins.var.python.irssinotifier.encryption_password <password>") # Hook privmsg/hilights weechat.hook_print("", "irc_privmsg", "", 1, "notify_show", "") # vim: autoindent expandtab smarttab shiftwidth=4
def encrypt_notification_cb(data, command, return_code, out, err): if is_debug(): weechat.prnt(weechat.buffer_search_main(), "irssinotifier: encryption callback, out: %s, err: %s" % (out, err)) # Deserialize the data data = pickle.loads(data) if is_debug(): weechat.prnt(weechat.buffer_search_main(), "irssinotifier: current data: %s" % repr(data)) # Bail out if something went wrong if return_code != 0: if is_debug(): weechat.prnt(weechat.buffer_search_main(), "irssinotifier: openssl returned unexpected status code: %d" % return_code) return weechat.WEECHAT_RC_OK # Process the output if we have an output (first call doesn't have an output) if len(out) > 0: out = string.replace(out,"/","_") out = string.replace(out,"+","-") out = string.replace(out,"=","") for k, v in data['cryptdata'].iteritems(): if v['isencrypted'] == False: if is_debug(): weechat.prnt(weechat.buffer_search_main(), "irssinotifier: encrypted '%s' from '%s' to '%s'" % (k, v['value'], out)) v['value'] = out v['isencrypted'] = True break # Determine if anything is left unencrypted unencryptedValue = "" for k, v in data['cryptdata'].iteritems(): if v['isencrypted'] == False: unencryptedValue = v['value'] break # Something is left unencrypted, do another pass if len(unencryptedValue) > 0: # See if we have a tmpfile to work with yet, as we cannot send stdin to hook_process() if len(data['tmpfile']) == 0: f = tempfile.NamedTemporaryFile(delete=False) data['tmpfile'] = f.name if is_debug(): weechat.prnt(weechat.buffer_search_main(), "irssinotifier: created temp file: %s" % data['tmpfile']) else: f = open(data['tmpfile'], 'w') if is_debug(): weechat.prnt(weechat.buffer_search_main(), "irssinotifier: opened temp file: %s" % data['tmpfile']) # Write the unencrypted value to this file f.write(unencryptedValue + "\n") f.flush() # Encrypt it command="openssl enc -aes-128-cbc -salt -base64 -A -pass pass:%s -in %s" % (data['password'], f.name) if is_debug(): weechat.prnt(weechat.buffer_search_main(), "irssinotifier: more encrypting to do, starting openssl process") weechat.hook_process(command, 30000, "encrypt_notification_cb", pickle.dumps(data)) # There are no unencrypted values anymore else: if is_debug(): weechat.prnt(weechat.buffer_search_main(), "irssinotifier: done encrypting, cleaning up and moving on") # Cleanup if len(data['tmpfile']) > 0 and os.path.exists(data['tmpfile']): if is_debug(): weechat.prnt(weechat.buffer_search_main(), "irssinotifier: deleting temp file: %s" % data['tmpfile']) os.unlink(data['tmpfile']) # Send it send_notification(data) return weechat.WEECHAT_RC_OK
def filter_del(name): """ Delete a filter named "name". """ weechat.command(weechat.buffer_search_main(), "/mute filter del %s" % name)
def test_plugins(): """Test plugins functions.""" check(weechat.plugin_get_name('') == 'core') check(weechat.plugin_get_name(weechat.buffer_get_pointer(weechat.buffer_search_main(), 'plugin')) == 'core')
def buf_node_in(pssName, buf, args): global psses ctx = {} currentPss = None argv = "" argc = 0 bufname = "" # parse cmd input # \todo remove consecutive whitespace argv = args.split(" ") argc = len(argv) # first we handle commands that are node independent # the connect command is the same for any context if argv[0] == "connect": host = "127.0.0.1" port = "8546" pssName = "" if argc < 2: wOut(PSS_BUFPFX_ERROR, [], "!!!", "invalid command <TODO insert help text>") pssName = argv[1] if argc > 2: host = argv[2] if argc > 3: port = argv[3] if pssName in psses: existingBuf = weechat.buffer_search("python", "pss.node." + pssName) if existingBuf != "": wOut( PSS_BUFPFX_DEBUG, [], "", "pss " + pssName + " already exists, changing to that buffer") weechat.buffer_set(bufs[pssName], "display", "1") return weechat.WEECHAT_RC_OK if host == "": host = weechat.config_get_plugin(pssName + "_url", host) if port == "": port = weechat.config_get_plugin(pssName + "_port", port) wOut(PSS_BUFPFX_DEBUG, [], "", "pss " + pssName + " already exists") else: psses[pssName] = pss.Pss(pssName, host, port) wOut(PSS_BUFPFX_OK, [], "+++", "added pss " + pssName) # regardless of if we have the node already, store the connection parameters for later for this node name weechat.config_set_plugin(pssName + "_url", host) weechat.config_set_plugin(pssName + "_port", port) # if we made it here we don't have a buffer for this node already # so create it and merge the node buffer with core so we can do the neat ctrl-x trick bufs[pssName] = weechat.buffer_new("pss.node." + pssName, "buf_node_in", pssName, "buf_node_close", pssName) weechat.buffer_set(bufs[pssName], "short_name", "pss." + pssName) weechat.buffer_set(bufs[pssName], "title", "PSS '" + pssName + "' | not connected") weechat.buffer_merge(bufs[pssName], weechat.buffer_search_main()) weechat.buffer_set(bufs[pssName], "display", "1") # now that we have the buffer up we have somewhere to write output relevant to this connection # we can proceed with connection in the pss instance wOut(PSS_BUFPFX_WARN, [bufs[pssName]], "0-> 0", "connecting to '" + pssName + "'") if not psses[pssName].connect(): wOut( PSS_BUFPFX_ERROR, [bufs[pssName]], "0-x 0", "connect to '" + pssName + "' failed: " + psses[pssName].error()['description']) return weechat.WEECHAT_RC_ERROR wOut(PSS_BUFPFX_OK, [bufs[pssName]], "0---0", "connected to '" + pssName + "'") # \todo temporary solution, swarm gateway should be set explicitly or at least we need to be able to choose port hookSocks.append( weechat.hook_connect("", host, 8500, 0, 0, "", "sock_connect", pssName)) # start processing inputs on the websocket hookFds[pssName] = weechat.hook_fd(psses[pssName].get_fd(), 1, 0, 0, "msgPipeRead", pssName) hookTimers.append( weechat.hook_timer(feedBoxPeriod, 0, 0, "processFeedBox", pssName)) # set own nick for this node # \todo use configurable global default nick # \todo clean up messy pubkey slicing (should be binary format in pss obj) pubkey = psses[pssName].key[2:] selfs[pssName] = pss.PssContact( PSS_DEFAULT_NICK, psses[pssName].key, pss.publickey_to_account(pubkey.decode("hex")).encode("hex"), psses[pssName].key) wOut(PSS_BUFPFX_OK, [bufs[pssName]], pssName, "nick is " + selfs[pssName].nick) return weechat.WEECHAT_RC_OK # get the context we're getting the command in # if we are not in pss context, # the we assume that the first argument is the name of the node # /pss oc add someone key addr # becomes # /pss add someone key addr # and "oc" is set to pssName # \todo consider exception for connect-command ctx = buf_get_context(buf) wOut(PSS_BUFPFX_DEBUG, [], "", "ctx: " + repr(ctx['t']) + " n " + ctx['n'] + " h " + ctx['h']) shiftArg = False # t 0 means any non-pss buffer if ctx['t'] == 0 and argv[0] != "connect": pssName = argv[0] argv = argv[1:] argc -= 1 else: pssName = ctx['n'] wOut(PSS_BUFPFX_DEBUG, [], "!!!", "after ctx " + pssName) # see if we already have this node registered if not pssName in psses: wOut(PSS_BUFPFX_ERROR, [], "!!!", "unknown pss connection '" + pssName + "'") return weechat.WEECHAT_RC_ERROR currentPss = psses[pssName] # set configuation values if argv[0] == "set": if argc < 3: wOut(PSS_BUFPFX_ERROR, [], "!!!", "insufficient number of arguments <TODO help output") return weechat.WEECHAT_RC_ERROR k = argv[1] v = argv[2] # for now we handle privkeys directly # we will read keystore jsons in near future instead, though if k == "pk": try: privkey = pss.clean_privkey(v) except: wOut(PSS_BUFPFX_ERROR, [], "!!!", "invalid key format") return weechat.WEECHAT_RC_ERROR try: currentPss.set_account_write(privkey.decode("hex")) except ValueError as e: wOut(PSS_BUFPFX_ERROR, [], "!!!", "set account fail: " + str(e)) return weechat.WEECHAT_RC_ERROR else: wOut(PSS_BUFPFX_ERROR, [], "!!!", "unknown config key") return weechat.WEECHAT_RC_ERROR wOut(PSS_BUFPFX_DEBUG, [], "!!!", "set pk to " + v + " for " + pssName) weechat.WEECHAT_RC_OK # add a recipient to the address books of plugin and node # \todo currently overwritten if same pubkey and different addr, should be possible to have both, maybe even one-shots special command with dark address where entry is deleted after message sent!!! elif argv[0] == "add": nick = "" key = "" addr = "" # input sanity check if argc < 3: wOut(PSS_BUFPFX_ERROR, [bufs[currentPssName]], "!!!", "not enough arguments for add <TODO: help output>") return weechat.WEECHAT_RC_ERROR # puny human varnames nick = argv[1] key = argv[2] if argc == 4: addr = argv[3] else: addr = "0x" # backend add recipient call if not currentPss.add(nick, key, addr): wOut(PSS_BUFPFX_ERROR, [bufs[pssName]], "!!!", "add contact error: " + currentPss.error()['description']) return weechat.WEECHAT_RC_ERROR # refresh the plugin memory map version of the recipient wOut(PSS_BUFPFX_DEBUG, [], "!!!", "added key " + key + " to nick " + nick) nicks[key] = currentPss.get_contact(nick) remotekeys[nick] = key # append recipient to file for reinstating across sessions storeFile.write(nick + "\t" + key + "\t" + addr + "\t" + currentPss.key + "\n") # open the buffer if it doesn't exist buf_get(pssName, "chat", nick, True) wOut( PSS_BUFPFX_INFO, [bufs[pssName]], "!!!", "added contact '" + nicks[key].nick + "' to '" + pssName + "' (key: " + pss.label(key) + ", addr: " + pss.label(addr) + ")") # send a message to a recipient elif argv[0] == "send" or argv[0] == "msg": nick = "" msg = "" if argc < 2: wOut(PSS_BUFPFX_ERROR, [bufs[pssName]], "!!!", "not enough arguments for send") return weechat.WEECHAT_RC_ERROR nick = argv[1] if argc > 2: msg = " ".join(argv[2:]) # \todo handle hex address only if not currentPss.have_nick(nick): wOut(PSS_BUFPFX_ERROR, [bufs[pssName]], "!!!", "invalid nick " + nick) return weechat.WEECHAT_RC_ERROR buf = buf_get(pssName, "chat", nick, True) # \todo remove the bufs dict, since we can use weechat method for getting it bufs[weechat.buffer_get_string(buf, "name")] = buf # if no message body we've just opened the chat window if msg != "": if not pss.is_message(msg): wOut(PSS_BUFPFX_DEBUG, [bufs[pssName]], "", "invalid message " + msg) return weechat.WEECHAT_RC_ERROR return buf_in(pssName, buf, msg) # create/join existing chat room elif argv[0] == "join": room = "" if argc < 2: wOut(PSS_BUFPFX_ERROR, [bufs[pssName]], "!!!", "not enough arguments for join") return weechat.WEECHAT_RC_ERROR room = argv[1] wOut(PSS_BUFPFX_DEBUG, [], "!!!", "in join " + pssName) buf = buf_get(pssName, "room", room, True) # invite works in context of chat rooms, and translates in swarm terms to # adding one separate feed encoded with the invited peer's key # room argument can be omitted if command is issued om channel to invite to # note feeds are currently unencrypted elif argv[0] == "invite": nick = "" roomname = "" if argc < 2: wOut(PSS_BUFPFX_ERROR, [bufs[pssName]], "!!!", "not enough arguments for invite") # if missing channel argument get bufname command was issued in # and derive channel name from it if we can (fail if not) elif argc < 3: if ctx['t'] != PSS_BUFTYPE_ROOM: wOut(PSS_BUFPFX_ERROR, [bufs[pssName]], "!!!", "unknown channel '" + ctx['t'] + "'") return weechat.WEECHAT_RC_ERROR roomname = ctx['h'] else: roomname = argv[2] nick = argv[1] # check if room exists # if it does, perform invitation try: roombufname = buf_generate_name(pssName, "room", roomname) room = rooms[roombufname] pss_invite(pssName, nick, room) wOut(PSS_BUFPFX_DEBUG, [], "!!!", "added " + nick + " to " + roomname) # if neither the previous fail, add the nick to the buffer roombuf = weechat.buffer_search("python", roombufname) buf_room_add(roombuf, nick) except KeyError as e: # keyerror catches both try statements wOut(PSS_BUFPFX_ERROR, [buf], "!!!", "Unknown room or nick: " + str(e)) # output node key elif argv[0] == "key" or argv[0] == "pubkey": wOut(PSS_BUFPFX_INFO, [bufs[pssName]], pssName + ".key", currentPss.key) # output node base address elif argv[0] == "addr" or argv[0] == "address": wOut(PSS_BUFPFX_INFO, [bufs[pssName]], pssName + ".addr", currentPss.base) # set nick for pss node elif argv[0] == "nick": try: if len(argv) > 1: nick = pss.clean_nick(argv[1]) selfs[pssName].nick = nick wOut(PSS_BUFPFX_INFO, [bufs[pssName]], pssName, "nick is '" + selfs[pssName].nick + "'") except ValueError as e: wOut(PSS_BUFPFX_ERROR, [bufs[pssName]], "!!!", "Invalid nick: " + argv[1]) # stop connection # \todo also kill the subprocess # \todo ensure clean shutdown so conncet can be called over elif argv[0] == "stop": weechat.unhook(hookFds[pssName]) wOut(PSS_BUFPFX_INFO, [bufs[pssName]], "!!!", "disconnected from " + pssName) currentPss.close() #del psses[currentPssName] # invalid input else: return weechat.WEECHAT_RC_ERROR # all good return weechat.WEECHAT_RC_OK
def pss_handle(pssName, buf, args): # context is only used for acvie nodes ctx = EventContext() # parse cmd input # \todo remove consecutive whitespace argv = args.split(" ") argc = len(argv) # first we handle commands that are node independent # the connect command is the same for any context # \todo rollback on connect fail if argv[0] == "connect": host = "127.0.0.1" port = "8546" if argc < 2: wOut(PSS_BUFPFX_ERROR, [], "!!!", "invalid command <TODO insert help text>") ctx.set_node(argv[1]) if argc > 2: host = argv[2] if argc > 3: port = argv[3] if cache.have_node_name(ctx.get_node()): existingBuf = weechat.buffer_search("python", "pss.node." + ctx.get_node()) if existingBuf != "": wOut(PSS_BUFPFX_DEBUG, [], "", "pss " + ctx.get_node() + " already exists, changing to that buffer") weechat.buffer_set(bufs[ctx.get_node()], "display", "1") return weechat.WEECHAT_RC_OK if host == "": host = weechat.config_get_plugin(ctx.get_node() + "_url", host) if port == "": port = weechat.config_get_plugin(ctx.get_node() + "_port", port) wOut(PSS_BUFPFX_DEBUG, [], "", "pss " + ctx.get_node() + " already exists") # regardless of if we have the node already, store the connection parameters for later for this node name weechat.config_set_plugin(ctx.get_node() + "_url", host) weechat.config_set_plugin(ctx.get_node() + "_port", port) # if we made it here we don't have a buffer for this node already # so create it and merge the node buffer with core so we can do the neat ctrl-x trick bufs[ctx.get_node()] = weechat.buffer_new("pss.node." + ctx.get_node(), "buf_node_in", ctx.get_node(), "buf_close", ctx.get_node()) weechat.buffer_set(bufs[ctx.get_node()], "short_name", "pss."+ ctx.get_node()) weechat.buffer_set(bufs[ctx.get_node()], "title", "PSS '" + ctx.get_node() + "' | not connected") weechat.buffer_merge(bufs[ctx.get_node()], weechat.buffer_search_main()) weechat.buffer_set(bufs[ctx.get_node()], "display", "1") # now that we have the buffer up we have somewhere to write output relevant to this connection # we can proceed with connection in the pss instance wOut( PSS_BUFPFX_WARN, [bufs[ctx.get_node()]], "0-> 0", "connecting to '" + ctx.get_node() + "'" ) pssnode = pss.Pss(ctx.get_node(), host, port) if not pssnode.connect(): wOut(PSS_BUFPFX_ERROR, [bufs[ctx.get_node()]], "-1-x 0", "connect to '" + ctx.get_node() + "' failed: " + cache.get_pss(ctx.get_node()).error()['description']) return weechat.WEECHAT_RC_ERROR wOut(PSS_BUFPFX_OK, [bufs[ctx.get_node()]], "0---0", "connected to '" + ctx.get_node() + "'") _tmp_chat_queue_hash[ctx.get_node()] = "" cache.add_node(pssnode) wOut(PSS_BUFPFX_OK, [], "+++", "added pss " + ctx.get_node()) # save what we've accomplished so far in the context, to be passed to the hook ctx.parse_buffer(bufs[ctx.get_node()]) ctx.set_pss(cache.get_pss(ctx.get_node())) ctx.set_bzz(cache.get_active_bzz()) # \todo temporary solution, swarm gateway should be set explicitly or at least we need to be able to choose port ctxid = ctxstore.put(ctx) hookSocks.append(weechat.hook_connect("", host, 8500, 0, 0, "", "pss_connect", ctxid)) # start processing inputs on the websocket hookFds[ctx.get_node()] = weechat.hook_fd(cache.get_pss(ctx.get_node()).get_fd(), 1, 0, 0, "msgPipeRead", ctx.get_node()) hookTimers.append(weechat.hook_timer(PSS_FEEDBOX_PERIOD, 0, 0, "processFeedOutQueue", ctx.get_node())) # set own nick for this node # \todo use configurable global default nick # \todo clean up messy pubkey slicing (should be binary format in pss obj) cache.set_nodeself(ctx.get_node(), PSS_DEFAULT_NICK) return weechat.WEECHAT_RC_OK # get the context we're getting the command in # if we are not in pss context, # the we assume that the first argument is the name of the node # /pss oc add someone key addr # becomes # /pss add someone key addr # and "oc" is set to pssName # \todo consider exception for connect-command ctx.parse_buffer(buf) if ctx.is_root(): ctx.set_node(argv[0]) argv = argv[1:] argc -= 1 try: ctx.set_pss(cache.get_pss(ctx.get_node())) ctx.set_bzz(cache.get_active_bzz()) except: wOut( PSS_BUFPFX_ERROR, [], "!!!", "unknown pss connection '" + ctx.get_node() + "'" ) return weechat.WEECHAT_RC_ERROR # set configuation values if argv[0] == "set": if argc < 3: wOut(PSS_BUFPFX_ERROR, [], "!!!", "insufficient number of arguments <TODO help output") return weechat.WEECHAT_RC_ERROR k = argv[1] v = argv[2] # for now we handle privkeys directly # we will read keystore jsons in near future instead, though if k == "pk": try: privkey = pss.clean_privkey(v) except: wOut(PSS_BUFPFX_ERROR, [], "!!!", "invalid key format") return weechat.WEECHAT_RC_ERROR try: pssnode = cache.get_pss(ctx.get_node()) pssnode.set_account_write(privkey.decode("hex")) cache.update_node_contact_feed(pssnode) except KeyError as e: pass except ValueError as e: wOut(PSS_BUFPFX_ERROR, [], "!!!", "set account fail: " + str(e)) return weechat.WEECHAT_RC_ERROR else: wOut(PSS_BUFPFX_ERROR, [], "!!!", "unknown config key") return weechat.WEECHAT_RC_ERROR wOut(PSS_BUFPFX_DEBUG, [], "!!!", "set pk to " + v + " for " + ctx.get_node()) weechat.WEECHAT_RC_OK # add a recipient to the address books of plugin and node # \todo currently overwritten if same pubkey and different addr, should be possible to have both, maybe even one-shots special command with dark address where entry is deleted after message sent!!! elif argv[0] == "add": nick = "" pubkeyhx = "" overlayhx = "" # input sanity check if argc < 3: wOut( PSS_BUFPFX_ERROR, [ctx.get_buffer()], "!!!", "not enough arguments for add <TODO: help output>" ) return weechat.WEECHAT_RC_ERROR # puny human varnames nick = argv[1] pubkeyhx = argv[2] if argc == 4: overlayhx = argv[3] else: overlayhx = "0x" # backend add recipient call pubkey = pss.clean_pubkey(pubkeyhx).decode("hex") overlay = pss.clean_overlay(overlayhx).decode("hex") try: newcontact = pss.PssContact(nick, ctx.get_pss().get_public_key()) newcontact.set_public_key(pubkey) newcontact.set_overlay(overlay) ctx.get_pss().add(newcontact) cache.add_contact(newcontact, True) except Exception as e: wOut( PSS_BUFPFX_ERROR, [ctx.get_buffer()], "!!!", "add contact error: " + repr(e) ) return weechat.WEECHAT_RC_ERROR ctx.reset(PSS_BUFTYPE_CHAT, ctx.get_node(), nick) # refresh the plugin memory map version of the recipient wOut( PSS_BUFPFX_DEBUG, [], "!!!", "added key " + pubkeyhx + " to nick " + nick + " node " + ctx.get_node() ) # retrieve the buffer (create if it doesn't exist) buf_get(ctx, True) wOut( PSS_BUFPFX_INFO, [ctx.get_buffer()], "!!!", "added contact '" + ctx.get_name() + "' to '" + ctx.get_node() + "' (key: " + pss.label(pubkeyhx) + ", addr: " + pss.label(overlayhx) + ")" ) # send a message to a recipient elif argv[0] == "send" or argv[0] == "msg": nick = "" msg = "" # verify input if argc < 2: wOut( PSS_BUFPFX_ERROR, [ctx.get_buffer()], "!!!", "not enough arguments for send" ) return weechat.WEECHAT_RC_ERROR nick = pss.clean_nick(argv[1]) if argc > 2: msg = " ".join(argv[2:]) # check that the contact is known in the cache contact = None try: contact = cache.get_contact_by_nick(nick) except: wOut( PSS_BUFPFX_ERROR, [ctx.get_buffer()], "!!!", "invalid nick " + nick ) return weechat.WEECHAT_RC_ERROR ctx.reset(PSS_BUFTYPE_CHAT, ctx.get_node(), nick) buf = buf_get(ctx, True) # if no message body we've just opened the chat window if msg != "": if not pss.is_message(msg): wOut( PSS_BUFPFX_DEBUG, [ctx.get_buffer()], "", "invalid message " + msg ) return weechat.WEECHAT_RC_ERROR return buf_in(ctx.get_node(), buf, msg) # create/join existing chat room # \todo broken elif argv[0] == "join": room = "" if argc < 2: wOut( PSS_BUFPFX_ERROR, [ctx.get_buffer()], "!!!", "not enough arguments for join" ) return weechat.WEECHAT_RC_ERROR room = argv[1] ctx.reset(PSS_BUFTYPE_ROOM, ctx.get_node(), room) if not ctx.get_name() in _tmp_room_queue_hash: _tmp_room_queue_hash[ctx.get_name()] = pss.zerohsh # start buffer for room buf_get(ctx, True) # invite works in context of chat rooms, and translates in swarm terms to # adding one separate feed encoded with the invited peer's key # room argument can be omitted if command is issued om channel to invite to # note feeds are currently unencrypted # \todo broken elif argv[0] == "invite": nick = "" roomname = "" if argc < 2: wOut( PSS_BUFPFX_ERROR, [ctx.get_buffer()], "!!!", "not enough arguments for invite" ) # if missing channel argument get bufname command was issued in # and derive channel name from it if we can (fail if not) elif argc < 3: if not ctx.is_room(): wOut( PSS_BUFPFX_ERROR, [ctx.get_buffer()], "!!!", "unknown channel '" + ctx.get_name() + "'" ) return weechat.WEECHAT_RC_ERROR else: ctx.set_name(argv[2]) nick = pss.clean_nick(argv[1]) # check if room exists # if it does, perform invitation try: #roombufname = buf_generate_name(pssName, "room", roomname) roombufname = ctx.to_buffer_name() room = cache.get_room(ctx.get_name()) #roombufname) pss_invite(pssName, nick, room) wOut( PSS_BUFPFX_DEBUG, [], "!!!", "added " + nick + " to " + ctx.get_name() ) # if neither the previous fail, add the nick to the buffer roombuf = weechat.buffer_search("python", roombufname) buf_room_add(roombuf, nick) except KeyError as e: # keyerror catches both try statements wOut( PSS_BUFPFX_ERROR, [ctx.get_buffer()], "!!!", "Unknown room or nick: " + str(e) ) # output node key elif argv[0] == "key" or argv[0] == "pubkey": wOut( PSS_BUFPFX_INFO, [ctx.get_buffer()], ctx.get_node() + ".key", ctx.get_pss().get_public_key().encode("hex") ) # output node base address elif argv[0] == "addr" or argv[0] == "address": wOut( PSS_BUFPFX_INFO, [ctx.get_buffer()], ctx.get_node() + ".addr", ctx.get_pss().get_overlay().encode("hex") ) # set nick for pss node elif argv[0] == "nick": try: if len(argv) > 1: nick = pss.clean_nick(argv[1]) cache.set_nodeself(ctx.get_node(), nick) wOut( PSS_BUFPFX_INFO, [ctx.get_buffer()], ctx.get_node(), "nick is '" + cache.get_nodeself(ctx.get_node()) + "'" ) except ValueError as e: wOut( PSS_BUFPFX_ERROR, [ctx.get_buffer()], "!!!", "Invalid nick: " + argv[1] ) # stop connection # \todo also kill the subprocess # \todo ensure clean shutdown so conncet can be called over elif argv[0] == "stop": weechat.unhook(hookFds[ctx.get_node()]) wOut( PSS_BUFPFX_INFO, [ctx.get_buffer()], "!!!", "disconnected from " + ctx.get_node() ) cache.close_node(ctx.get_node()) # invalid input else: return weechat.WEECHAT_RC_ERROR # all good return weechat.WEECHAT_RC_OK
"%(buffer_autoset_current_buffer) " "%(buffer_properties_set)" " || del %(buffer_autoset_options)", "bas_cmd", "") weechat.hook_completion( "buffer_autoset_current_buffer", "current buffer name for buffer_autoset", "bas_completion_current_buffer_cb", "") weechat.hook_completion( "buffer_autoset_options", "list of options for buffer_autoset", "bas_completion_options_cb", "") weechat.hook_signal("9000|buffer_opened", "bas_signal_buffer_opened_cb", "") weechat.hook_config("%s.buffer.*" % CONFIG_FILE_NAME, "bas_config_option_cb", "") # core buffer is already open on script startup, check manually! bas_signal_buffer_opened_cb("", "", weechat.buffer_search_main()) # ==================================[ end ]=================================== def bas_unload_script(): """ Function called when script is unloaded. """ global bas_config_file if bas_config_file: bas_config_write() return weechat.WEECHAT_RC_OK
" /" + SCRIPT_COMMAND + " add irc.freenode.* " "hotlist_max_level_nicks_add bot:-1", "add %(buffers_plugins_names)|" "%(buffer_autoset_current_buffer) " "%(buffer_properties_set)" " || del %(buffer_autoset_options)", "bas_cmd", "") weechat.hook_completion("buffer_autoset_current_buffer", "current buffer name for buffer_autoset", "bas_completion_current_buffer_cb", "") weechat.hook_completion("buffer_autoset_options", "list of options for buffer_autoset", "bas_completion_options_cb", "") weechat.hook_signal("9000|buffer_opened", "bas_signal_buffer_opened_cb", "") weechat.hook_config("%s.buffer.*" % CONFIG_FILE_NAME, "bas_config_option_cb", "") # core buffer is already open on script startup, check manually! bas_signal_buffer_opened_cb("", "", weechat.buffer_search_main()) # ==================================[ end ]=================================== def bas_unload_script(): """ Function called when script is unloaded. """ global bas_config_file if bas_config_file: bas_config_write() return weechat.WEECHAT_RC_OK
' command: save commands only\n' ' text: save text only (text sent to a channel buffer)\n' ' all: save commands and text\n' '\n' 'Examples:\n' ' save the command history manually (for example with /cron script):\n' ' /' + SCRIPT_NAME + ' save\n' ' save and restore command history for buffer #weechat on freenode (text only):\n' ' /buffer_autoset add irc.freenode.#weechat localvar_set_save_history text\n' ' save and restore command history for weechat core buffer (commands only):\n' ' /buffer_autoset add core.weechat localvar_set_save_history command\n', 'save %-' '|| list %-', 'histman_cmd_cb', '') if int(version) >= 0x00040000: if weechat.buffer_get_string(weechat.buffer_search_main(), 'localvar_histman') == 'on': init_options() create_hooks() weechat.prnt( '', '%s%s: do not start this script two times. command history was already restored, during this session!' % (weechat.prefix('error'), SCRIPT_NAME)) else: init_options() # create dir, if not exist config_create_dir() # look for global_history if OPTIONS['save_global'].lower() != 'off': read_history(filename_global_history, '')
def send_notification_cb(data, command, return_code, out, err): if is_debug(): weechat.prnt(weechat.buffer_search_main(), "irssinotifier: sent notification, return_code: %d" % return_code) return weechat.WEECHAT_RC_OK
def toggle_silent(): toggled_value = wc.config_get_plugin('silent_mode') toggled_value = 'on' if toggled_value == 'off' else 'off' wc.config_set_plugin('silent_mode', toggled_value) wc.prnt(wc.current_buffer(), f'wsl_notify: Silent mode is now {toggled_value}') return wc.WEECHAT_RC_OK def parse_key_combos(data, signal, signal_data): # this method sometimes works unreliably when minimising terminal window by clicking on its icon in taskbar but I blame windows global is_focused if signal_data == '\x01[[I': is_focused = True elif signal_data == '\x01[[O': is_focused = False return wc.WEECHAT_RC_OK wc.register(NAME, AUTHOR, VERSION, LICENSE, DESCRIPTION, '', '') wc.command( wc.buffer_search_main(), "/print -stdout \033[?1004h" ) # as weechat.prnt cannot print to stdout which is required to enable focus events wc.hook_config('plugins.var.python.' + NAME + '.*', 'config', '') config() wc.hook_command('wsl_notify', DESCRIPTION, 'silent_mode, gen_appid_script', cmd_help, 'silent_mode || gen_appid_script', 'wsl_notify_command_cb', '') wc.hook_print('', '', '', 1, 'parse_message', '') wc.hook_signal('key_combo_default', 'parse_key_combos', '')