def init_options(): """Initialize global options dict from client.""" global OPTIONS for opt, attr in DEFAULT_OPTIONS.items(): xchat_opt = '_'.join((__module_name__, opt)) if isinstance(attr[1], str): value = attr[1] else: value = ' '.join(attr[1]) desc = '{} (default: "{}")'.format(attr[0], value) if WEECHAT: weechat.config_set_desc_plugin(opt, desc) plugin_pref = weechat.config_is_set_plugin(opt) else: cmd_name = ''.join(('WVM', opt.upper())) xchat.hook_command(cmd_name, xchat_update_option_cb, userdata=opt, help='/{} -- {}'.format(cmd_name, desc)) plugin_pref = xchat.get_pluginpref(xchat_opt) if plugin_pref: value = weechat.config_get_plugin(opt) if WEECHAT else \ xchat.get_pluginpref(xchat_opt) if not isinstance(DEFAULT_OPTIONS[opt][1], str): value = list(map(str.strip, value.split())) set_option(opt, value) else: if WEECHAT: weechat.config_set_plugin(opt, value) else: xchat.set_pluginpref(xchat_opt, value) set_option(opt, attr[1])
def test_jsonpluginpref(): prefs = JSONPluginPref("json_prefs_test") other_pref_keys = hexchat.list_pluginpref() # perform core tests too core_pluginpref_tests(prefs) # additional tests a_list = list(range(10)) a_dict = {chr(ord('A') + i): i for i in range(10)} prefs['a_list'] = a_list assert hexchat.get_pluginpref(prefs.prefix + prefs.prefix_sep + "a_list") == json.dumps(a_list) prefs['a_dict'] = a_dict assert hexchat.get_pluginpref(prefs.prefix + prefs.prefix_sep + "a_dict") == json.dumps(a_dict) prefs['null'] = None assert hexchat.get_pluginpref(prefs.prefix + prefs.prefix_sep + "null") == 'null' assert dict(prefs.items()) == dict([('a_list', a_list), ('a_dict', a_dict), ('null', None)]) for key in prefs: prefs.delete(key) assert not prefs assert other_pref_keys == hexchat.list_pluginpref() print("test_jsonpluginpref passed")
def cleanOldVer(): if hexchat.get_pluginpref('lfmnwo_user'): hexchat.set_pluginpref('lastfm_user', hexchat.get_pluginpref('lfmnwo_user')) hexchat.del_pluginpref('lfmnwo_user') if hexchat.get_pluginpref('lfmnwo_apikey'): hexchat.del_pluginpref('lfmnwo_apikey') return
def find_sound_directory(self): if hexchat.get_pluginpref("soundalert_dir") != None: return hexchat.get_pluginpref("soundalert_dir") else: if os.name == "nt": paths = [ "C:\Program Files\HexChat\share\sounds", "C:\Program Files (x86)\HexChat\share\sounds", "%appdata%\HexChat\sounds" ] elif os.name == "posix": paths = [ "/sbin/HexChat/share/sounds", "/usr/sbin/HexChat/share/sounds", "/usr/local/bin/HexChat/share/sounds" ] else: return False for path in paths: if os.path.isdir(path): hexchat.set_pluginpref("soundalert_dir", path) return path return False
def __init__(self, name, default, **kwargs): self.name = name self.statusmsg = kwargs if hexchat.get_pluginpref("queercraft_{}".format(name)): self.setter(hexchat.get_pluginpref("queercraft_{}".format(name)) == "True") else: self.setter(default)
def nowPlaying(word, word_eol, userdata): USER = hexchat.get_pluginpref('lastfm_user') if USER: try: r=requests.get(r'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=%s&api_key=%s&format=json' % (USER, KEY)) data = r.json() try: nowplaying = data['recenttracks']['track'][0]['@attr']['nowplaying'] track = data['recenttracks']['track'][0]['name'] artist = data['recenttracks']['track'][0]['artist']['#text'] album = data['recenttracks']['track'][0]['album']['#text'] if len(word) > 1 and word[1].lower() == 'plain': if album: hexchat.command('me now playing %s by %s from %s' % (track, artist, album)) else: hexchat.command('me now playing %s by %s' % (track, artist)) else: bCol = '\003%s' % COLORS[hexchat.get_pluginpref('lastfm_base_color')] track = '\003%s%s%s' % (COLORS[hexchat.get_pluginpref('lastfm_track_color')], track, bCol) artist = '\003%s%s%s' % (COLORS[hexchat.get_pluginpref('lastfm_artist_color')], artist, bCol) if album: album = '\003%s%s%s' % (COLORS[hexchat.get_pluginpref('lastfm_album_color')], album, bCol) hexchat.command('me %snow playing %s by %s from %s' % (bCol, track, artist, album)) else: hexchat.command('me %snow playing %s by %s' % (bCol, track, artist)) except: print('LastFM: No song playing') except: print('LastFM: Cannot connect to Last.fm') else: print('LastFM: Username not found. %s' % HELPTEXT) return hexchat.EAT_ALL
def loadlist(): global ignorelist global botlist try: ignorelist = eval(hexchat.get_pluginpref('ignorelist')) botlist = eval(hexchat.get_pluginpref('botlist')) except Exception as e: hexchat.prnt(str(e))
def __init__(self, name, default, **kwargs): self.name = name self.statusmsg = kwargs if hexchat.get_pluginpref("queercraft_{}".format(name)): self.setter( hexchat.get_pluginpref("queercraft_{}".format(name)) == "True") else: self.setter(default)
def __enter__(self): self.threshold = int( hexchat.get_pluginpref("hcaway_autoback__threshold")) self.enabled = bool( hexchat.get_pluginpref("hcaway_autoback__enabled")) self.talk_count += int( hexchat.get_pluginpref("hcaway_autoback__talk_count")) return self
def chgcooldown(word, word_eol, userdata): if len(word) == 1: hexchat.emit_print("Notice", "AutoUB [PL]", "Current cooldown is %s seconds." % str( hexchat.get_pluginpref('aub_cooldown'))) return hexchat.EAT_ALL hexchat.set_pluginpref('aub_cooldown', word[1]) hexchat.emit_print("Notice", "AutoUB [PL]", "Cooldown set to %s seconds." % str( hexchat.get_pluginpref('aub_cooldown')))
def loadlist(): global ignorelist global botlist global typelist try: ignorelist = eval(hexchat.get_pluginpref('ignorelist')) botlist = eval(hexchat.get_pluginpref('botlist')) typelist = eval(hexchat.get_pluginpref('typelist')) except Exception as e: hexchat.prnt(str(e))
def __init__(self): hexchat.prnt("Razer Alert plugin loaded.") if hexchat.get_pluginpref("razeralert_active") is None: hexchat.set_pluginpref("razeralert_active", True) if not hexchat.get_pluginpref("razeralert_active"): hexchat.prnt("Alerts are currently disabled. Re-enable them with /alertson") self.blink = False
def defaultColors(): if not hexchat.get_pluginpref('lastfm_base_color'): hexchat.set_pluginpref('lastfm_base_color', 'purple') if not hexchat.get_pluginpref('lastfm_track_color'): hexchat.set_pluginpref('lastfm_track_color', 'lightcyan') if not hexchat.get_pluginpref('lastfm_artist_color'): hexchat.set_pluginpref('lastfm_artist_color', 'pink') if not hexchat.get_pluginpref('lastfm_album_color'): hexchat.set_pluginpref('lastfm_album_color', 'lightgreen') return
def __init__(self): hexchat.prnt("Razer Alert plugin loaded.") if hexchat.get_pluginpref("razeralert_active") is None: hexchat.set_pluginpref("razeralert_active", True) if not hexchat.get_pluginpref("razeralert_active"): hexchat.prnt( "Alerts are currently disabled. Re-enable them with /alertson") self.blink = False
def __init__(self): hexchat.prnt("Sound Alert plugin loaded.") self.sound_directory = self.find_sound_directory() self.file_list = self.find_sounds() if hexchat.get_pluginpref("soundalert_active") == None: hexchat.set_pluginpref("soundalert_active", True) if hexchat.get_pluginpref("soundalert_active") == False: hexchat.prnt("Alerts are currently disabled. Re-enable them with /alertson")
def unban(): global locked if locked == 0: hexchat.command('RAW PRIVMSG ChanServ :unban ' + chan) hexchat.command('timer 1.5 RAW JOIN ' + chan) if hexchat.get_pluginpref("aub_alertsenabled") == 1: hexchat.emit_print("Notice", "AutoUB [PL]", "Unbanning yourself from %s. Won't auto-unban for the next %s seconds. [To turn these alerts off, /noaubalerts]" % ( chan, str(hexchat.get_pluginpref('aub_cooldown')))) locked = 1 cooldown = hexchat.get_pluginpref('aub_cooldown') + 1.5 hexchat.command('timer %s unlockautounban' % str(cooldown)) return hexchat.EAT_ALL
def np(word, word_eol, userdata): output = subprocess.check_output([ 'rhythmbox-client', '--print-playing-format' if hexchat.get_pluginpref('np_format') else '--print-playing', hexchat.get_pluginpref('np_format') if hexchat.get_pluginpref('np_format') else '' ]) output = output.strip() # Has a trailing newline hexchat.command('me {0} "{1}"'.format( hexchat.get_pluginpref('np_message') if hexchat.get_pluginpref('np_message') else 'is listening to', output)) return hexchat.EAT_ALL
def __init__(self): hexchat.prnt("Sound Alert plugin loaded.") self.sound_directory = self.find_sound_directory() self.file_list = self.find_sounds() if hexchat.get_pluginpref("soundalert_active") == None: hexchat.set_pluginpref("soundalert_active", True) if hexchat.get_pluginpref("soundalert_active") == False: hexchat.prnt( "Alerts are currently disabled. Re-enable them with /alertson")
def loadScores(self): self.players = [] name = '' i=0 while True: name = hexchat.get_pluginpref('gbquizz_player' + str(i) + '_name') score = hexchat.get_pluginpref('gbquizz_player' + str(i) + '_score') beststreak = hexchat.get_pluginpref('gbquizz_player' + str(i) + '_beststreak') i = i+1 if name != None and score != None: self.players.append(Player(name, score, beststreak)) else: break
def loadScores(self): self.players = [] name = '' i = 0 while True: name = hexchat.get_pluginpref('gbquizz_player' + str(i) + '_name') score = hexchat.get_pluginpref('gbquizz_player' + str(i) + '_score') beststreak = hexchat.get_pluginpref('gbquizz_player' + str(i) + '_beststreak') i = i + 1 if name != None and score != None: self.players.append(Player(name, score, beststreak)) else: break
def shign_load_list(word=None,word_eol=None,userdata=None): global shign_prefix global shign_pluginpref_list global shign_list global shign_list_last_idx All_Prefs = hexchat.list_pluginpref() shign_pluginpref_list = [] shign_list = [] shign_list_last_idx = 0 if len(All_Prefs) == 0: #print('empty') #list is empty shign_list = [['shign1','All']] hexchat.set_pluginpref('shign1','All') shign_list_last_idx = 1 return for Prefs in All_Prefs: if Prefs.find(shign_prefix) != -1: #if the prefix is found shign_pluginpref_list.append(Prefs) #append to the list of prefs if int(Prefs[5:]) > shign_list_last_idx: shign_list_last_idx = int(Prefs[5:]) #print(shignpreflist) for shign_pluginpref in shign_pluginpref_list: temp_list = hexchat.get_pluginpref(shign_pluginpref).split() temp_list.insert(0, shign_pluginpref) shign_list.append(temp_list) print(__module_name__+'\tList loaded!')
def get_option(key): hkey = "{}_{}".format(__module_name__, key) configsetting = hexchat.get_pluginpref(hkey) if configsetting is not None: return configsetting else: return default_config.get(key)
def commands(self, word, word_eol, userdata): if len(word) < 2: hexchat.prnt("Not enough arguments given. See /help soundalert") else: if word[1] == "set": if len(word) < 3: hexchat.prnt("No directory specified.") if os.path.isdir(word_eol[2]): hexchat.set_pluginpref("soundalert_dir", word_eol[2]) self.sound_directory = self.find_sound_directory() self.file_list = self.find_sounds() else: hexchat.prnt("Not a valid directory.") elif word[1] == "on": self.enable() elif word[1] == "off": self.disable() elif word[1] == "get": hexchat.prnt("Currently set sound directory: {}".format(hexchat.get_pluginpref("soundalert_dir"))) elif word[1] == "test": self.debug = True self.spawn(None, None, None) else: hexchat.prnt("No such command exists.") return hexchat.EAT_ALL
def play_sound(self): sound = random.choice(self.file_list) active = hexchat.get_pluginpref("soundalert_active") if self.debug == True: hexchat.prnt("Playing: {}".format(os.path.abspath(sound))) else: if not active: return if sound == False: hexchat.prnt("Could not find default share/sounds directory, and no sounds directory is specified. See /help soundalert.") if os.name == "nt": winsound.PlaySound(sound, winsound.SND_FILENAME ^ winsound.SND_ASYNC) elif os.name == "posix": xine = pyxine.Xine() stream = xine.stream_new() stream.open(sound) stream.Play() self.debug = False return True
def find_sound_directory(self): current_directory = hexchat.get_pluginpref("soundalert_dir") if current_directory and os.path.isdir(current_directory): return current_directory else: if os.name == "nt": paths = [ "C:\\Program Files\\HexChat\\share\\sounds", "C:\\Program Files (x86)\\HexChat\\share\\sounds", os.path.join(os.getenv('appdata'), "HexChat\\sounds") ] elif os.name == "posix": paths = [ "/sbin/HexChat/share/sounds", "/usr/sbin/HexChat/share/sounds", "/usr/local/bin/HexChat/share/sounds" ] else: return False for path in paths: if os.path.isdir(path): hexchat.set_pluginpref("soundalert_dir", path) return path return False
def commands(self, word, word_eol, userdata): if len(word) < 2: hexchat.prnt("Not enough arguments given. See /help soundalert") else: if word[1] == "set": if len(word) < 3: hexchat.prnt("No directory specified.") if os.path.isdir(word_eol[2]): hexchat.set_pluginpref("soundalert_dir", word_eol[2]) self.sound_directory = self.find_sound_directory() self.file_list = self.find_sounds() else: hexchat.prnt("Not a valid directory.") elif word[1] == "on": self.enable() elif word[1] == "off": self.disable() elif word[1] == "get": hexchat.prnt("Currently set sound directory: {}".format( hexchat.get_pluginpref("soundalert_dir"))) elif word[1] == "test": self.debug = True self.spawn(None, None, None) else: hexchat.prnt("No such command exists.") return hexchat.EAT_ALL
def play_sound(self): sound = random.choice(self.file_list) active = hexchat.get_pluginpref("soundalert_active") if self.debug == True: hexchat.prnt("Playing: {}".format(os.path.abspath(sound))) else: if not active: return if sound == False: hexchat.prnt( "Could not find default share/sounds directory, and no sounds directory is specified. See /help soundalert." ) if os.name == "nt": winsound.PlaySound(sound, winsound.SND_FILENAME ^ winsound.SND_ASYNC) elif os.name == "posix": xine = pyxine.Xine() stream = xine.stream_new() stream.open(sound) stream.Play() self.debug = False return True
def load(): global alerts alerts = OrderedDict() data = hexchat.get_pluginpref("python_alerts_saved") if data is None: return try: result = json.loads(data) except Exception as ex: print("Failed to load:", str(ex)) return False if not isinstance(result, list): result = [result] for ix, chunk in enumerate(result): try: alert = Alert.import_dict(chunk) except Exception as ex: print("Failed to load entry {}:".format(ix), str(ex)) ok = False continue key = alert.name.lower() if key in alerts: print( "Failed to load entry {}: Alert '{}' duplicated in save data.". format(ix, alert.name)) ok = False continue alerts[key] = alert
def loadconf(): global ignores ign = hexchat.get_pluginpref(__module_name__+'_ignores') if ign: ignores = ign.split(',') else: ignores = []
def pushb(word, word_eol, userdata): """ Hook for /pushb command in HexChat""" api_key = hexchat.get_pluginpref(CONFIG_APIKEY) if word[1] == 'CONFIG': if len(word_eol) > 2: set_config(word_eol[2]) else: hexchat.prnt( 'Pushbullet API key currently set to "{}"'.format(api_key)) return hexchat.EAT_HEXCHAT if not api_key: hexchat.prnt('\037\00304Pushbullet API key not specified.', ' Use /pushb CONFIG <api_key> to set one.') return hexchat.EAT_HEXCHAT try: pb = pushbullet.Pushbullet(api_key) except pushbullet.errors.InvalidKeyError: hexchat.prnt('\037\00304Invalid API key!') return hexchat.EAT_HEXCHAT push(word, word_eol) return hexchat.EAT_HEXCHAT
def __getitem__(self, key): if not isinstance(key, str): raise TypeError("Key must be a string") val = hexchat.get_pluginpref(self._keyname(key)) if val is None: raise KeyError(key) return val
def channel_msg(word, word_eol, userdata): # only show when not focused on hexchat # if hexchat.get_info("win_status") == "active": # return None # get the channel info for where the message came from for ch in hexchat.get_list("channels"): # handle only channel if ch.type != 2: continue whitelist = hexchat.get_pluginpref('hxnotify_whitelist').split(',') # only show for whitelisted channels if word[2] in whitelist: # check if the chanopt is set if bool(ch.flags & blink_tray): my_nick = hexchat.get_info('nick') from_user = get_usrname(word[0]) # fix getting notifcations from self when # a bouncer playback is running if hexchat.nickcmp(from_user, my_nick) != 0: header = "Message ({0}/{1})".format(ch.network, ch.channel) body = "{0}: {1}".format(from_user, hexchat.strip(word_eol[3][1:], MESSAGE_LIMIT, 3)) # send the notification notification(header, body) return None return None
def autoback_cb(word, word_eol, userdata): with AutobackConfig() as autoback: enabled = autoback.enabled if enabled: current_network = hexchat.get_info("network") with NetworkList() as networks: away_networks = list(networks._get_away()) if current_network in away_networks: # "AutobackConfig(1)", 1 to increment .talk_count with AutobackConfig(1) as autoback: hexchat.prnt(str_prefix + \ "\002warning:\002 you've talked " + \ "\002{}\002/\002{}\002 times while away.".format( autoback.talk_count, autoback.threshold)) if autoback.talk_count >= autoback.threshold: hexchat.prnt(str_prefix + \ "You will be set back on network \002{}\002".format( current_network)) autoback.talk_count = 0 suffix = hexchat.get_pluginpref("hcaway_suffix") context = hexchat.find_context(server=current_network) context.command("nick {}".format( context.get_info("nick").replace(suffix, ""))) context.command("back") return hexchat.EAT_NONE
def get_version(self): """Retrieve the currently stored preferences' version. Returns an integer or a tuple of integers, depending on what was set. Returns `None` if not set. Returns `NotImplemented` if parsing the version failed. Set the version with `set_version`. """ version_str = hexchat.get_pluginpref(self._version_pref_name) if not version_str: return None elif version_str == 0: # yes, that's a number # `0` was implicitly set by hexchat # with earlier versions of this code. # Since we have no idea what it should have been, # just say that there is no version at all. # See also `set_version` below. return None elif not version_str.startswith("v"): raise ValueError("Unexpected version value: %s" % version_str) version_split = version_str[1:].split('.') try: if len(version_split) == 1: return int(version_split[0]) else: return tuple(map(int, version_split)) except ValueError: return NotImplemented
def hcaway_cb(word, word_eol, userdata): away_time, reason = time.strftime("%H:%M (%b %d %Y) %z"), "" suffix = hexchat.get_pluginpref("hcaway_suffix") away_string = "'{}' at {}".format(__module_fullname__, away_time) if len(word) > 1: away_string = "'{}' at {}".format(word_eol[1], away_time) reason = " reason: \"{}\"".format(word_eol[1]) with NetworkList() as networks: # networks that the user is not away on whitelist = list(networks._get_back()) for network in whitelist: context = hexchat.find_context(server=network) context.command("nick {}{}".format( context.get_info("nick"), suffix)) context.command("away " + away_string) if len(whitelist) >= 1: hexchat.prnt(str_prefix + "you're now away on \002{}\002.{}".format( ("\002, \002".join(whitelist[0:-1]) + "\002 and \002" + \ whitelist[-1]) if len(whitelist) > 1 else (whitelist[0]), reason)) else: error("either you've no networks added to your whitelist, " "or you're already away on one or more of them.") return hexchat.EAT_ALL
def load(): global alerts alerts = OrderedDict() data = hexchat.get_pluginpref("python_alerts_saved") if data is None: return try: result = json.loads(data) except Exception as ex: print("Failed to load:", str(ex)) return False if not isinstance(result, list): result = [result] for ix, chunk in enumerate(result): try: alert = Alert.import_dict(chunk) except Exception as ex: print("Failed to load entry {}:".format(ix), str(ex)) ok = False continue key = alert.name.lower() if key in alerts: print("Failed to load entry {}: Alert '{}' duplicated in save data.".format(ix, alert.name)) ok = False continue alerts[key] = alert
def loadconf(): global ignores ign = hexchat.get_pluginpref(__module_name__ + '_ignores') if ign: ignores = ign.split(',') else: ignores = []
def soakerlistremove(word, word_eol, userdata): ignoreList = hexchat.get_pluginpref('soakbotignorelist').split(' ') for user in ignoreList: for removal in word: if removal != word[1] and ignoreList.count(removal) >= 1: ignoreList.remove(removal) return hexchat.EAT_ALL
def passchange(word, word_eol, userdata): if len(word) == 1: if hexchat.get_pluginpref('mpdnp_pass') == '+-+nopassword+-+': formattedprint('Password protection is disabled.') else: formattedprint('Current mpd password is \'%s\'. To disable password protection, type /mpdpass disable' % hexchat.get_pluginpref('mpdnp_pass')) if len(word) == 2: if word[1].lower() == 'disable': formattedprint('Password protection disabled.') hexchat.set_pluginpref('mpdnp_pass', '+-+nopassword+-+') else: formattedprint( 'Password changed to \'%s\'. To disable password protection, type /mpdpass disable' % word[1]) hexchat.set_pluginpref('mpdnp_pass', word[1])
def load(): """ Loads the config. """ global dirty global words keys = hexchat.get_pluginpref(PLUGIN_PREF_KEYS) if keys == None: return keys = keys.split(KEY_SEPARATOR) for key in keys: x = hexchat.get_pluginpref(PLUGIN_PREF_VAL % key) if x: words[key] = x
def __init__(self, pluginpref, defaultvalue, command, commandhelp = ''): self.pluginpref = pluginpref hexchat.hook_command(command, self.command, help=commandhelp) self.value = None if pluginpref: self.value = hexchat.get_pluginpref(pluginpref) if not self.value: self.value = defaultvalue
def soakerlistadd(word, word_eol, userdata): ignoreList = hexchat.get_pluginpref('soakbotignorelist') if ignoreList != 'None': hexchat.set_pluginpref('soakbotignorelist', '%s %s' % (ignoreList, word_eol[1].lower())) else: hexchat.set_pluginpref('soakbotignorelist', '%s' % word_eol[1].lower()) print('%s added to the ignore list' % ', '.join(word_eol[1].split(' '))) return hexchat.EAT_ALL
def __init__(self, pluginpref, defaultvalue, command, commandhelp=''): self.pluginpref = pluginpref hexchat.hook_command(command, self.command, help=commandhelp) self.value = None if pluginpref: self.value = hexchat.get_pluginpref(pluginpref) if not self.value: self.value = defaultvalue
def load_pref(): resp_list = [] for pref in hexchat.list_pluginpref(): if pref.startswith(ELEM_PREFIX + "name"): name = hexchat.get_pluginpref(pref) resp_list.append(Respoon.loadFromPref(name, hexchat.get_pluginpref)) return resp_list
def __getattr__(self, name): value = hexchat.get_pluginpref('_'.join((self.prefix, name))) if value is None: return self.defaults[name] # HexChat attempts to automatically convert strings to integers return json.loads(str(value))
def np(word, word_eol, userdata): server = hexchat.get_pluginpref('mpdnp_server') port = hexchat.get_pluginpref('mpdnp_port') password = hexchat.get_pluginpref('mpdnp_pass') client = MPDClient() client.timeout = None try: client.connect(server, port) if password != '+-+nopassword+-+': client.password(password) except: formattedprint("Could not connect to mpd. unloading.") hexchat.command('py unload %s' % __module_name__) np = client.currentsong() st = client.status() title = np.get('title') artist = np.get('artist') album = np.get('album') try: elapsed = time.strftime("%M:%S", time.gmtime( int(st.get('time').split(':')[0]))) duration = time.strftime("%M:%S", time.gmtime( int(st.get('time').split(':')[1]))) except: pass bitrate = st.get('bitrate') playbackstatus = st.get('state') if playbackstatus == 'pause': if not album: hexchat.command('me np:\00306 %s \017by\00307 %s \017 [\00306%s\017/\00310%s\017] [\00302%s\00313kbps\017] [\00304paused\017] [\00325mpd %s\017]' % ( title, artist, elapsed, duration, bitrate, client.mpd_version)) if album: hexchat.command('me np:\00306 %s \017by\00307 %s\017 from\00310 %s\017 [\00306%s\017/\00310%s\017] [\00302%s\00313kbps\017] [\00304paused\017] [\00325mpd %s\017]' % ( title, artist, album, elapsed, duration, bitrate, client.mpd_version)) elif playbackstatus == 'play': if not album: hexchat.command('me np:\00306 %s \017by\00307 %s \017 [\00306%s\017/\00310%s\017] [\00302%s\00313kbps\017] [\00325mpd %s\017]' % ( title, artist, elapsed, duration, bitrate, client.mpd_version)) if album: hexchat.command('me np:\00306 %s \017by\00307 %s\017 from\00310 %s\017 [\00306%s\017/\00310%s\017] [\00302%s\00313kbps\017] [\00325mpd %s\017]' % ( title, artist, album, elapsed, duration, bitrate, client.mpd_version)) elif playbackstatus == 'stop': hexchat.command( 'me np: [\00304playback stopped\017] [\00325mpd %s\017]' % client.mpd_version) return hexchat.EAT_ALL
def serverchange(word, word_eol, userdata): if len(word) == 1: formattedprint('Current mpd hostname is \'%s\'.' % hexchat.get_pluginpref('mpdnp_server')) if len(word) == 2: formattedprint('mpd host changed to \'%s\'.' % word[1]) hexchat.set_pluginpref('mpdnp_server', word[1])
def portchange(word, word_eol, userdata): if len(word) == 1: formattedprint('Current mpd port is %s.' % hexchat.get_pluginpref('mpdnp_port')) if len(word) == 2: formattedprint('mpd port changed to %s.' % word[1]) hexchat.set_pluginpref('mpdnp_port', word[1])
def get_option(key): default = default_config.get(key) if default is not None: return default else: hkey = "{}_{}".format(__module_name__, key) return hexchat.get_pluginpref(hkey)
def get_whitelist(): whitelist = hexchat.get_pluginpref('hxnotify_whitelist') # ensure we got something back if whitelist is None: return [] # remove blanks return [w for w in whitelist.split(',') if w.strip()]
def loadpm_cb(word, word_eol, userdata): #TODO: save dialogs to a single user across multiple networks for pref in hexchat.list_pluginpref(): if pref[:10] == "persistpm_": saved_network = hexchat.get_pluginpref(pref) if saved_network == hexchat.get_info("network"): saved_nick = pref[10:] network_context = hexchat.find_context(channel=saved_network) network_context.command("QUERY {}".format(saved_nick))
def __init__(self, prefix, defaults, write_defaults=True): self.prefix = prefix self.defaults = defaults self._initialized = True if write_defaults: for name, default in defaults.items(): key = '_'.join((prefix, name)) if hexchat.get_pluginpref(key) is None: hexchat.set_pluginpref(key, json.dumps(default))
def upload_file(file): if file != '': # Get current config values apiUrl = hexchat.get_pluginpref('teknik_url') apiUsername = hexchat.get_pluginpref('teknik_username') apiToken = hexchat.get_pluginpref('teknik_auth_token') # Try to upload the file results = teknik.UploadFile(apiUrl, file, apiUsername, apiToken) # Either print the result to the input box, or write the error message to the window if 'error' in results: hexchat.prnt('Error: ' + results['error']['message']) elif 'result' in results: hexchat.command("settext " + results['result']['url']) else: hexchat.prnt('Unknown Error') else: hexchat.prnt('Error: Invalid File')
def onChannelMessage(params, data, userdata): global emitting parse_incoming = hexchat.get_pluginpref(config_prefix + 'parse_incoming') parse_incoming = True if parse_incoming == None else parse_incoming in positive_input if emitting or not parse_incoming: return hexchat.EAT_NONE emitting = True params[1] = parse(params[1]) hexchat.emit_print('Channel Message', params[0], params[1]) emitting = False return hexchat.EAT_ALL
def onSendingMessage(words, words_eol, userdata): global emitting parse_outgoing = hexchat.get_pluginpref(config_prefix + 'parse_outgoing') parse_outgoing = True if parse_outgoing == None else parse_outgoing in positive_input if emitting or not parse_outgoing: return hexchat.EAT_NONE emitting = True result = parse(words_eol[0]) hexchat.command('say ' + result) emitting = False return hexchat.EAT_ALL
def set_option(word): if len(word) == 2: for l in [x for x in hexchat.list_pluginpref() if x.startswith("privacy_")]: print(l, "=", hexchat.get_pluginpref(l)) elif len(word) == 4: k, v = word[2], word[3] hexchat.set_pluginpref(k, v) configure_hexchat() print(k, "=", v) else: do_help()
def find_sound_directory(self): if hexchat.get_pluginpref("soundalert_dir") != None: return hexchat.get_pluginpref("soundalert_dir") else: if os.name == "nt": paths = ["C:\Program Files\HexChat\share\sounds", "C:\Program Files (x86)\HexChat\share\sounds", "%appdata%\HexChat\sounds"] elif os.name == "posix": paths = ["/sbin/HexChat/share/sounds", "/usr/sbin/HexChat/share/sounds", "/usr/local/bin/HexChat/share/sounds"] else: return False for path in paths: if os.path.isdir(path): hexchat.set_pluginpref("soundalert_dir", path) return path return False
def get_tab_data(): # Returns a dict of network=[channels]. Uses addon_python.conf: # session_freenode = #test,#foo # list_pluginpref() returns the key 'session_freenode' # get_pluginpref('session_freenode') returns the comma delimited channel list tab_data = {} for pref in hexchat.list_pluginpref(): if len(pref) > 8 and pref[:8] == 'session_': network = pref[8:] channels = hexchat.get_pluginpref('session_' + network).split(',') if len(channels): tab_data[network] = channels else: tab_data[network] = None return tab_data