def load_users(filename): global nicknames, voice, voice_pitch, voice_speed if os.path.exists(filename): user_data = [] for line in open(filename,'r'): user_data.append(line) if len(user_data)%4 == 0: ctr = 0 while ctr < len(user_data): nicknames.append(user_data[ctr].rstrip()) voice.append(user_data[ctr+1]) voice_pitch.append(user_data[ctr+2]) voice_speed.append(user_data[ctr+3]) ctr = ctr + 4 else: os.remove(filename) if ((len(voice) != len(nicknames)) or (len(voice_pitch) != len(nicknames)) or (len(voice_speed) != len(nicknames))): del nicknames[:] del voice[:] del voice_pitch[:] del voice_speed[:] os.remove(filename) xchat.prnt('No users loaded.') else: xchat.prnt('%s Users loaded.' % len(nicknames)) return None
def crypto_cb(word, word_eol, userdata): ''' Callback for /crypto command ''' global m global t0 if len(word) < 2: print "\nAvailable actions:" print " auth - initiate crypto session and authenticate participants" elif word[1] == "auth": m.SetUsers(xchat.get_list("users")) setup() if '-p2p' in word_eol: bcast(xchat.get_list("users"), 1) else: synchronize() elif word[1] == "y": m.SetUsers(xchat.get_list("users")) acknowledge() elif word[1] == "shutdown": digest = GetChatDigest(m.path) m.digestTable.update({xchat.get_prefs("irc_nick1"):digest}) bcast(xchat.get_list("users"), 0, "shutdown") bcast(xchat.get_list("users"), 0, '0x16' + str(digest)) else: xchat.prnt("Unknown action") return xchat.EAT_ALL
def addUser(word, word_eol, userdata): global WATCHLIST if len(word) < 2: return xchat.EAT_ALL user = word[1] src = "auto" dest = DEFAULT_LANG if len(word) > 2 : src = findLangCode(word[2]) if src is None: xchat.prnt("The specified language is invalid.") return xchat.EAT_ALL pass if len(word) > 3: lang = findLangCode(word[3]) if lang is not None: dest = lang pass key = xchat.get_info("channel") + " " + user.lower() WATCHLIST[key] = (dest, src, 0) xchat.prnt("Now watching user: "******", source: " + src + ", target: " + dest) return xchat.EAT_ALL
def add_keyword(cmd_msg, cmd_slice, xchat_data): if len(cmd_msg) < 2: xchat.prnt('Usage: /ADDKW <keyword>, adds a keyword to highlight.') else: for kw in cmd_msg[1:]: KEYWORDS.append(kw) return xchat.EAT_ALL
def hwmon(word, word_eol, userdata): lm_sensors_info, gpu_temp = sysinfo_hwmon() output = [] if lm_sensors_info is None and gpu_temp is None: xchat.prnt('No monitoring sensors detected') return xchat.EAT_ALL if gpu_temp is not None: output.append(u'gpu:: temp0: %d\xb0C' % gpu_temp) if lm_sensors_info is not None: for device_name in lm_sensors_info: temps = lm_sensors_info[device_name]['temps'] temp_output = [] i = 0 if len(temps): for temp in temps: add = ('temp%d: %s' % (i, temp)).decode('utf-8') temp_output.append(add) i += 1 output.append(device_name + ':: ' + ', '.join(temp_output)) output = '; '.join(output) if output: dest = xchat.get_context() output = 'say %s' % wrap('sensor', output) dest.command(output) else: xchat.prnt('No monitoring sensors detected') return xchat.EAT_ALL
def speechon(word, word_eol, userdata): "/speechon hook" global SPEAK SPEAK=True XCHAT_FESTIVAL.say('speech activated') xchat.prnt("speech activated") return xchat.EAT_ALL
def rkick(word, word_eol, userdata): #try: reason = select(( 'Goodbye!','See you later.','Cya.','Bye.','Later!', 'Kindergarden is elsewhere!','Ugh. BYE!','G\'day', 'Seeya later!','Be gone!','This is awkward. Bye.', 'I didn\'t do it!' )) if len(word) == 2: # Assume they supplied a username return xchat.command('kick %s %s' % (word[1], reason)) elif len(word) == 1: # Assume they want a random user list = xchat.get_list("users") if not list: return xchat.prnt(help) user = select((list)) return xchat.command('kick %s %s' % (user.nick, reason)) else: # Assume they entered some weird stuff return xchat.prnt(help) #except: # xchat.prnt(help) return xchat.EAT_ALL
def isPlayerSpecified(): if player == None: xchat.prnt("No player specified.") xchat.prnt("Use /player <player name> to specify a default media player.") return False else: return True
def speechoff(word, word_eol, userdata): "/speechoff hook" global SPEAK SPEAK=False XCHAT_FESTIVAL.say('speech disabled') xchat.prnt("speech disabled") return xchat.EAT_ALL
def mpcSpam(word, word_eol, userdata): req = urllib.request.Request('http://'+mpc_host+':'+mpc_port+'/variables.html') try: response = urllib.request.urlopen(req,timeout=2) except urllib.error.URLError as e: xchat.prnt('Server did not respond, maybe mpc-hc isn\'t running: '+str(e.reason)) return xchat.EAT_ALL parser = MyHTMLParser() parser.feed(response.read().decode('utf-8')) filename = args["filepath"] size = os.path.getsize(filename) size = int(math.floor(size/1048576)) filename = os.path.basename(filename) state = args["statestring"] current_time = args["positionstring"] total_time = args["durationstring"] position = float(args["position"]) duration = float(args["duration"]) loops = math.floor(((position/duration)*20)) progress = "6" for i in range(20): if loops < i: progress = progress + "12" loops = 21 progress = progress + '|' #variables: size, filename, state, current_time, total_time #xchat.command("ME 13»»6 MPC-HC 13«»6 ["+progress+"6] " + filename + " 13«»6 " + current_time + "/" + total_time + " 13«»6 "+str(size)+"MB 13«»6 [" + state + "]") xchat.command("ME 01 MPC-HC 04 " + filename + " 04 " + current_time + "01/04" + total_time + " 04 "+str(size)+"MB") return xchat.EAT_ALL
def remove_keyword(cmd_msg, cmd_slice, xchat_data): if len(cmd_msg) < 2: xchat.prnt('Usage: /RMKW <keyword>, removes a keyword from list of highlighted keywords.') else: if cmd_msg[1] in KEYWORDS: KEYWORDS.remove(cmd_msg[1]) return xchat.EAT_ALL
def colourwheel(word, word_eol, userdata): colours = '\k01,0000\k00,0101\k00,0202\k01,0303\k01,0404' \ '\k01,0505\k01,0606\k01,0707\k01,0808\k01,0909\k01,1010' \ '\k01,1111\k01,1212\k01,1313\k01,1414\k01,1515' colours = colours.replace('\\k', chr(3)) xchat.prnt(colours) return xchat.EAT_ALL
def msg(word, word_eol, userdata): if xchat.nickcmp(word[1], pirate_host) == 0: xchat.prnt("They are the same!") #xchat.prnt(', '.join(word_eol)) #userlist = context.get_list("users") #xchat.prnt(word) return xchat.EAT_NONE
def setcooldown_cb(word, word_eol, userdata): global conn global global_commands mod = check_mod(word) if not mod: return xchat.EAT_NONE words = word[1].split(' ') #Will always have at least one element of words if words[0].lower() == "!setcooldown": if words[1].lower() in global_commands: return xchat.EAT_NONE command = words[1].lower() try: cooldown = int(words[2]) update = (cooldown, command) c = conn.cursor() c.execute('UPDATE commands SET cooldown=? WHERE command=?', update) xchat.command('say Cooldown change for ' + command + ' successful') conn.commit() except: xchat.prnt("Unexpected error:" + sys.exc_info()[0]) return xchat.EAT_NONE return xchat.EAT_NONE
def ircrypt_init(): global ircrypt_keys, ircrypt_options, ircrypt_ciphers # Open config file f = None try: f = open('%s/ircrypt.conf' % xchat.get_info('xchatdirfs'), 'r') except: pass if not f : xchat.prnt('Could not open ircrypt.conf.') return xchat.EAT_ALL for line in f: # Read keys if line[0:4] == 'key:': (prefix, target, key) = line.split(':',2) ircrypt_keys[target] = key[0:-1] else: # Read options if line[0:7] == 'option:': (prefix, option, value) = line.split(':',2) ircrypt_options[option] = value[0:-1] else: # Read special cipher if line[0:7] == 'cipher:': (prefix, target, cipher) = line.split(':',2) ircrypt_ciphers[target] = cipher[0:-1] xchat.prnt('IRCrypt re(loaded)') return xchat.EAT_ALL
def UnVoiceChannel(word,word_eol,userdata): global okChannels context = xchat.get_context() cn = context.get_info("channel") del okChannels[cn] xchat.prnt("No longer automatically voicing newcomers in "+cn) return xchat.EAT_ALL
def gcalc(word, word_eol, userdata): baseurl = 'http://www.google.com/search?q=%s' query = word_eol[1] debug = False if word[1] == '--debug': debug = True query = word_eol[2] # TODO: Fix freeze while loading. opener = MyURL() content = opener.open(baseurl % query).read() if debug: for i in range(len(content)/1000): print content[i*1000:(i+1)*1000] return xchat.EAT_ALL lindex = content.find('<h2 class=r style="font-size:138%">') if lindex == -1: xchat.prnt('Nothing found. If this seems wrong, please debug.') return xchat.EAT_ALL lindex = lindex + len('<h2 class=r style="font-size:138%"><b>') rindex = content.find('</b></h2>', lindex) result = content[lindex:rindex] result = " ".join(result.split()) result = result.replace(' ', ' ') result = result.replace('×', '×') result = re.sub(r'<sup>(\d+)<\/sup>⁄<sub>(\d+)</sub>', r' \1⁄\2', result) result = result.replace('<sup>', '^') result = result.replace('</sup>', '') result = result.replace('<font size=-2> </font>', ',') xchat.prnt("Google Calculator: %s" % result) return xchat.EAT_ALL
def chk_wiki(cmd_req, query, xchat_data=None): if len(cmd_req) < 2: xchat.prnt('Usage: /WIKI <query>, checks wikipedia for information on <query>.') else: query = '_'.join(i for i in query[1].split()) make_request(query) return xchat.EAT_ALL
def ether(word, word_eol, userdata): # TODO Add iPhone hotspot (find ipheth) def get_ethernet_devices(): devices = pci_find_by_class(PCI_CLASS_NETWORK_ETHERNET) devices += pci_find_by_class(PCI_CLASS_NETWORK_ETHERNET_WIFI) usb_devices = usb_find_by_class(USB_CLASS_NETWORK) usb_devices += usb_find_by_class(USB_CLASS_NETWORK_GENERIC) usb_devices += usb_find_by_class(USB_CLASS_BLUETOOTH) names = [] for device_id, vendor_id in devices: names.append(pci_find_fullname(device_id, vendor_id)) for device_id, vendor_id in usb_devices: names.append(usb_find_fullname(device_id, vendor_id)) return names names = get_ethernet_devices() output = ', '.join(names) if output: dest = xchat.get_context() dest.command('say %s' % wrap('ether', output)) else: xchat.prnt('No ethernet devices found') return xchat.EAT_ALL
def channeloff(word, word_eol, userdata): "/channeloff hook" global SPEAK_CHANNEL SPEAK_CHANNEL=False XCHAT_FESTIVAL.say('speaking all channels') xchat.prnt("speaking all channels") return xchat.EAT_ALL
def yt_cb(word, word_eol, userdata): global YT_enabled chan = xchat.find_context(channel="#commie-subs") if not YT_enabled: return xchat.EAT_NONE if chan is None: return xchat.EAT_NONE for url in word[1].split(' '): o = urlparse(url) if o.netloc is '': continue else: s = o.netloc.lower().split('.') for part in s: if part == "youtube" or part == "youtu": # vid = url[url.find('v=')+2:] # if vid.find('&') != -1 # vid = vid[:vid.find('&')] vid = url[url.find('v=')+2:url.find('v=')+13] service = gdata.youtube.service.YouTubeService() try: entry = service.GetYouTubeVideoEntry(video_id=vid) except gdata.service.RequestError: xchat.prnt("Invalid Video ID") return xchat.EAT_NONE title = entry.media.title.text chan.command("say YouTube video title: " + title) return xchat.EAT_NONE return xchat.EAT_NONE
def new_msg(word, word_eol, userdata): """Handles normal messages. Unless this is the first user's message since he joined, the message will not be altered. Otherwise, a '(logged in Xs ago)' message will be appended. """ user = xchat.strip(word[0]) # If the user logged in before we did (which means the Join part of # filter_msg didn't take effect), add him to the dict. if user not in last_seen: last_seen[user]= [time(), 1] # If the user has never spoken before, let us know when he logged in. if last_seen[user][1] == 0: time_diff = time() - last_seen[user][0] # Bold the username and color the text if it's a hilight if "Hilight" in userdata: s_user = "******" + word[0] s_msg = "\017\00319" + word[1] else: s_user = word[0] s_msg = "\017" + word[1] if "Action" in userdata: s_user = "******" % s_user else: s_user += '\t' xchat.prnt("%s%s \00307(logged in %ss ago)" % (s_user, s_msg, int(time_diff))) last_seen[user]= [time(), 1] return xchat.EAT_XCHAT else: last_seen[user]= [time(), 1]
def removeChannel(word, word_eol, userdata): channel = xchat.get_info("channel") if CHANWATCHLIST.pop(channel + " " + channel, None) is not None: xchat.prnt("Channel %s has been removed from the watch list." %channel) return xchat.EAT_ALL
def channelon(word, word_eol, userdata): "/channelon hook" global SPEAK_CHANNEL SPEAK_CHANNEL = xchat.get_info('channel') XCHAT_FESTIVAL.say('speaking %s channel only' % SPEAK_CHANNEL) xchat.prnt("speaking %s channel only" % SPEAK_CHANNEL) return xchat.EAT_ALL
def VersionCond(word, word_eol, userdata): if word_eol[3] != ":\x01VERSION\x01": return xchat.EAT_NONE if CheckCondition(*verCond): return xchat.EAT_NONE xchat.prnt("Prevented version request by %s" % word[0].split("!")[0].lstrip(":")) return xchat.EAT_ALL
def rainbow_trigger(word, word_eol, userdata): channel = xchat.get_info('channel') try: xchat.command("msg %s %s" % (channel, rainbow(word_eol[1]))) except IndexError: xchat.prnt("/RAINBOW <message> %s" % (rainbow_desc)) return xchat.EAT_ALL
def printExaileVersion(word, word_eol, userdata): try: remote_object = bus.get_object("org.exaile.Exaile","/org/exaile/Exaile") iface = dbus.Interface(remote_object, "org.exaile.Exaile") xchat.command("me is listening to his awesome tunes using Exaile " + str(iface.GetVersion())) except dbus.exceptions.DBusException as Err: xchat.prnt("An error occured, but xchat crashes when it gets printed.")
def print_watching_users(word,word_eol,userdata): """print the users in the a2tr list of the channel. """ global AUTOUSER channel=xchat.get_info('channel') users=[ cu.split(' ')[1] for cu in AUTOUSER.keys() ] xchat.prnt('A2TR: %s'%(' '.join(users))) xchat.EAT_ALL
def getAuIFace(): from dbus import Bus, DBusException bus = Bus(Bus.TYPE_SESSION) try: return bus.get_object('org.mpris.audacious', '/Player') except: # DBusException: # catch all exceptions xchat.prnt("Either Audacious is not running or you have something wrong with your D-Bus setup.") return None
def ResetChannel(word,word_eol,userdata): global hostsThatJoined context = xchat.get_context() del hostsThatJoined hostsThatJoined = {} cn = context.get_info("channel") xchat.prnt("Everyone is now a newcomer in "+cn) return xchat.EAT_ALL
def addIgnore(word, word_eol, userdata): global IGNORELIST if len(word) < 2: return xchat.EAT_ALL channel = xchat.get_info("channel") user = word[1] IGNORELIST[channel + " " + user] = (DEFAULT_LANG, "auto") xchat.prnt("Now ignoring user: " + user) return xchat.EAT_ALL
def translateNoDetect(word, word_eol, userdata): srcLang = word[1] destLang = word[2] message = word_eol[3] src, text = Translator.translate(message, destLang, srcLang) if src is None or text is None: xchat.prnt("Error occurred during translation.") else: xchat.prnt("Translated from " + Translator.findLangName(srcLang) + " to " + Translator.findLangName(destLang) + ": " + text) return xchat.EAT_ALL
def removeUser(word, word_eol, userdata): if len(word) < 2: xchat.prnt("You must specify a user.") return xchat.EAT_ALL user = word[1] if AUTOUSER.pop(xchat.get_info('channel') + ' ' + user.lower(), None) is not None: xchat.prnt("User %s has been removed from the watch list." % user) return xchat.EAT_ALL
def translateDetectLang(word, word_eol, userdata): destLang = word[1] message = unicode(word_eol[2], "utf-8") src, text = Translator.translate(word_eol[2], destLang, None) if src is None or text is None: xchat.prnt("Error occurred during translation.") else: xchat.command("say " + text) return xchat.EAT_ALL
def mpc_hc(caller, callee, helper): try: data = urllib2.urlopen(MPC_HC_URL).read() mpc_hc_np = MPC_HC_REGEXP.findall(data)[0].replace("«", "«") mpc_hc_np = mpc_hc_np.replace("»", "»") mpc_hc_np = mpc_hc_np.replace("•", "•") except: xchat.prnt("Error: MPC-HC not detected") return xchat.EAT_ALL else: xchat.command("say %s" % mpc_hc_np) return xchat.EAT_ALL
def translateAndSay(word, word_eol, userdata): if len(word) < 3: return xchat.EAT_ALL lang = findLangCode(word[1]) if lang is None: xchat.prnt("Invalid language name or code. Aborting translation.") return xchat.EAT_ALL addTranslationJob(word_eol[2], lang, "auto", xchat.get_info("channel"), None, ECHO, True) return xchat.EAT_ALL
def process_youtube_urls(msg, nick, dest=None): # TODO: do a findall() on word_eol and loop in the returned list to process all urls m = re.match("^.*(https?://(www.)?((youtube.com/)|(youtu.be/))[?&=a-zA-Z0-9_-]*).*$",xchat.strip(msg),re.I) if m != None: DEBUG and xchat.prnt("msg: "+xchat.strip(msg)) url = m.group(1) DEBUG and xchat.prnt("url: "+url) task = Thread() #TODO: task.daemon = True def task_func(): decipher_youtube_url(url,nick,msg,dest) task.run = task_func task.start() return xchat.EAT_NONE
def add_regex(word, word_eol, userdata): """Adds a regex pattern / replacement.""" try: arg_pattern, arg_repl = get_regex(word_eol[1]) except TypeError: return xchat.EAT_ALL except IndexError: xchat.prnt("/RE_ADD <PATTERN> <REPLACEMENT>") return xchat.EAT_ALL re_pattern.append(arg_pattern) re_repl.append(arg_repl) save_pref() return xchat.EAT_ALL
def unload_plugin(userdata): global TIMEOUT_HOOK global CONN if TIMEOUT_HOOK is not None: xchat.unhook(TIMEOUT_HOOK) TIMEOUT_HOOK = None if CONN is not None: Translator.closeConnection() xchat.prnt("Translator is unloaded.") return None
def setup(self): self._process = self._create_pipe() # Register timed check of screensaver status. self._hook = self._register_hook() xchat.hook_unload(self.unload_cb) # Register some commands. xchat.hook_command("xs_start_polling", self.on_start) xchat.hook_command("xs_stop_polling", self.on_stop) xchat.prnt('%s version %s by %s loaded' % (__module_name__, __module_version__, __author__))
def audacious(word, word_eol, userdata): try: player = session_bus.get_object('org.mpris.audacious', '/Player') song = player.GetMetadata() except (dbus.exceptions.DBusException, TypeError): xchat.prnt('Audacious: Could not find player.') return xchat.EAT_XCHAT try: msg = 'me is now playing %s by %s on %s.' % ( song['title'], song['artist'], song['album']) except KeyError: xchat.prnt('Audacious: Could not find song info.') return None if len(word) > 1: if word[1] == 'info': xchat.prnt(msg[18:]) else: xchat.prnt( 'Audacious: Valid commands are: info, or without args to announce' ) else: xchat.command(msg) return xchat.EAT_ALL
def setup(self): # Register contact events raised by minbif. xchat.hook_print('Channel DeVoice', self.replicate_event, (1, 'is away')) xchat.hook_print('Channel Voice', self.replicate_event, (1, 'is back')) xchat.hook_print('Join', self.replicate_event, (0, 'has joined')) # The following is already notified. #xchat.hook_print('Quit', self.replicate_event, (0, 'has quit')) xchat.hook_unload(self.unload_cb) xchat.prnt('%s version %s by %s loaded' % (__module_name__, __module_version__, __author__))
def flag(word, word_eol, userdata): channel = xchat.get_info('channel') modes = xchat.get_info('modes') if isinstance(modes, basestring): modes = modes.partition(' ')[0] if channel[0] == '#' and ('S' in modes or 'c' in modes): xchat.prnt('ERROR: Detected channel mode S or c') return xchat.EAT_ALL try: flag = country_to_flag(word[1]).split('\n') for line in flag: xchat.command('say ' + line) except LookupError: xchat.prnt('ERROR: No such country code') return xchat.EAT_ALL
def do_track_info(word, word_eol, user_data): """/me the current track info.""" try: banshee = Banshee() except DBusException: # Banshee not launched xchat.prnt("Cannot comply: Banshee is not running.") else: track_data = banshee.current_track() template = "say np: %(artist)s - %(name)s " # TODO Figure out what character encoding X-Chat is using and encode to it. # Defaulting to UTF-8 in the meantime. xchat.command((template % track_data).encode("utf-8")) # X-Chat doesn't know the command. return xchat.EAT_XCHAT
def remove_regex(word, word_eol, userdata): """Removes a regex pattern / replacement couple by their index.""" try: index = int(word[1]) except ValueError: xchat.prnt("Argument must be an index. Use /RE_LIST to find it.") return xchat.EAT_ALL try: re_pattern.pop(index) re_repl.pop(index) except IndexError: xchat.prnt("Entry doesn't exist. Use /RE_LIST to list all entries.") return xchat.EAT_ALL save_pref() return xchat.EAT_ALL
def printSong(word, word_eol, userdata): songInfo = getSongInfo() if songInfo == 0: xchat.prnt("Banshee is not playing") elif songInfo == 1: xchat.prnt("Banshee is not running") else: if not userdata: xchat.command("me is listening to %s - %s [%s] (%s/%s)" % songInfo) else: xchat.command( "me is listening to \x0303%s\x03 - \x0303%s\x03 [\x0303%s\x03] (\x0305%s\x03/\x0305%s\x03)" % songInfo) return xchat.EAT_ALL
def nonotify(word, word_eol, userdata): if word[1] == 'show': return show_nonotify() if word[1] == 'remove': return remove_nonotify(word[2]) channels = re.split('(?:,|\s)+', word_eol[1]) for channel in channels: if channel not in channel_list: xchat.prnt('%sNoNotify - Adding %s to NoNotify channel list.' % (green, channel)) channel_list.append(channel) else: xchat.prnt( '%sNoNotify - Not adding %s, already in NoNotify channel list.' % (green, channel)) return xchat.EAT_ALL
def otcauth_unload_cb(userdata): # Remove our MENU's xchat.command('MENU DEL "OTC Toolkit/GPG EAuth" "otctk eauth"') xchat.command('MENU DEL "OTC Toolkit/-"') xchat.command('MENU DEL "OTC Toolkit/Get Voice"') xchat.command('MENU DEL "OTC Toolkit"') # Remove nicklist popup menus xchat.command('MENU DEL "$NICK/OTC Toolkit/Get WoT Rating"') xchat.command('MENU DEL "$NICK/OTC Toolkit/GPG Information"') xchat.command('MENU DEL "$NICK/OTC Toolkit"') # Print out our unloaded message. xchat.prnt("\002\00302%s:\00302 \00304[[[UNLOADED]]]\00304\002" % __module_name__) return xchat.EAT_XCHAT
def monitorchannel(word, word_eol, userdata): """ No input: show all, 1 input: add/delete input depending on first character""" if len(word) == 1: show_channels() elif len(word) > 2: xchat.prnt("Too much input!") elif word[1] == "--help": xchat.prnt( "/monitorchannel to show all currently monitored\n" + "/monitorchannel #channel to start monitoring the channel\n" + "/monitorchannel -#channel to stop monitoring the channel") elif word[1][0] == "-": remove_channel(word[1][1:]) else: add_channel(word[1]) return xchat.EAT_ALL
def chooseSong(word, word_eol, next): if next: if os.system("banshee-1 --next") == 0: xchat.prnt("Song changed") else: xchat.prnt("Song changing failed") else: if os.system("banshee-1 --prev") == 0: xchat.prnt("Song changed") else: xchat.prnt("Song changing failed")
def inspect(word, word_eol, userdata): methods = xchat.__dict__ xchat.prnt('xchat module:') for key in sorted(methods.iterkeys()): xchat.prnt('%s%s%s: %s' % (chr(2), key, chr(2), methods[key])) context = xchat.get_context() methods = dir(context) xchat.prnt('context:') for key in sorted(methods): xchat.prnt('%s%s%s' % (chr(2), key, chr(2))) return xchat.EAT_NONE
def initialize(word, word_eol, userdata): global CONN global ACTIVE_JOBS global WATCHLIST global TIMEOUT_HOOK if TIMEOUT_HOOK is not None: xchat.unhook(TIMEOUT_HOOK) TIMEOUT_HOOK = None if CONN is not None: CONN.close() CONN = None ACTIVE_JOBS = 0 WATCHLIST = {} xchat.prnt("Translator reinitialized") return xchat.EAT_ALL
def updateUserNick(word, word_eol, userdata): channel = xchat.get_info("channel") userOld = word[0] userNew = word[1] if userOld is None or userNew is None: return xchat.EAT_NONE userOld = userOld.lower() userNew = userNew.lower() key = channel + " " + userOld if key in WATCHLIST: dest, src, cnt = WATCHLIST[key] if WATCHLIST.pop(key, None) is not None: WATCHLIST[xchat.get_info("channel") + " " + userNew.lower()] = (dest, src, cnt) xchat.prnt("Watching " + userNew + ", fomerly " + userOld) return xchat.EAT_NONE
def addUser(word, word_eol, userdata): if len(word) < 2: xchat.prnt("You must specify a user.") return xchat.EAT_ALL user = word[1] dest = DEFAULT_LANG src = None if len(word) > 2 and Translator.findLangCode(word[2]) is not None: dest = word[2] if len(word) > 3 and Translator.findLangCode(word[3]) is not None: src = word[3] AUTOUSER[xchat.get_info('channel') + ' ' + user.lower()] = (dest, src) xchat.prnt("Added user %s to the watch list." % user) return xchat.EAT_ALL
def SetMessage(word, word_eol, userdata): global banOpts if "*" not in banOpts: banOpts["*"] = {} if word[1] == "irc_kick_message": if len(word_eol) > 2: # Set banOpts["*"]["irc_kick_message"] = word_eol[2] xchat.prnt("%s set to: %s" % (word[1], word_eol[2])) else: dots = 29 - len(word[1]) try: irc_kick_message = banOpts["*"]["irc_kick_message"] except KeyError: irc_kick_message = None xchat.prnt(word[1] + "\00318" + ("." * dots) + "\00319:\x0f " + irc_kick_message) #endif return xchat.EAT_XCHAT #endif return xchat.EAT_NONE
def UnbanNick(word, word_eol, userdata): context = xchat.get_context() servChan = context.get_info("host") + "/" + context.get_info("channel") nick = word[1] if reNick.match(nick): if nick in bannedNicks[servChan]: context.command("mode -b " + bannedNicks[servChan][nick]) else: # TODO: Retrieve ban list, find all matches to a certain nick's mask, # unban all of those xchat.prnt( "You didn't ban this nick. (Condition not supported yet)") #endif elif reMask.match(nick): context.command("mode -b " + nick) mask = nick else: xchat.prnt("No one to unban.") return xchat.EAT_ALL #endif return xchat.EAT_ALL
def pithos(word, word_eol, userdata): try: player = session_bus.get_object('net.kevinmehall.Pithos', '/net/kevinmehall/Pithos') except (dbus.exceptions.DBusException, TypeError): xchat.prnt('Pithos: Could not find player.') return xchat.EAT_XCHAT song = player.GetCurrentSong() # to be configurable msg = 'me is now playing %s by %s on %s.'%(song['title'], song['artist'], song['album']) if len(word) > 1: # not very useful? if word[1] == 'info': xchat.prnt(msg[18:]) elif word[1] == 'next': player.SkipSong() elif word[1] == 'love': player.LoveCurrentSong() elif word[1] == 'hate': player.BanCurrentSong() else: xchat.prnt('Pithos: Valid commands are: info, next, love, hate, or without args to announce') else: xchat.command(msg) return xchat.EAT_ALL
def otcauth_cb(word, word_eol, userdata): if len(word) < 2: switch = "help" else: switch = str(word[1]).lower() if switch == "help": otcauth_help(word[1:]) elif switch == "version": otcauth_ver() elif switch == "eauth": nick = xchat.get_info('nick') xchat.command("MSG gribble eauth %s" % (nick)) global eauthCheck eauthCheck = True elif switch == "bauth": xchat.prnt("RESERVED FOR FUTURE FUNCTIONALITY") else: xchat.prnt("\002\00304Invalid Option:\00304\002 %s not defined" % (word[1])) return xchat.EAT_XCHAT
def get_playing_song(username): try: raw_page = urllib2.urlopen(API_ROOT + "/?method=user.getrecenttracks&user="******"&api_key=" + API_KEY) page_data = BeautifulStoneSoup(raw_page) current_track = page_data.track artist = current_track.artist.text song = current_track.find( "name").text #because .name returns other things album = current_track.album.text #let's make a status :3 status = song + " - " + artist if album != "": status = status + " (" + album + ")" if username == xchat.get_info("nick"): xchat.command("me last listened to %s" % (status.encode('utf-8'))) else: xchat.command("say " + username + " last listened to %s" % (status.encode('utf-8'))) except: xchat.prnt("An error ocurred, probably a wrong Username")
def screenshot(word, word_eol, userdata): try: Image("clipboard:").write("PNG32:clipmage.png") except RuntimeError: xchat.prnt('no image in the clipboard') return xchat.EAT_ALL response = cStringIO.StringIO() c = pycurl.Curl() values = [("key", "37c8847d8ce46eb4bb4175ad4573441b"), ("image", (c.FORM_FILE, "clipmage.png"))] c.setopt(c.URL, "http://api.imgur.com/2/upload.xml") c.setopt(c.HTTPPOST, values) c.setopt(c.WRITEFUNCTION, response.write) c.perform() c.close() os.remove('clipmage.png') try: xchat.command( 'say %s' % response.getvalue().split('<original>')[1].split('</original>')[0]) except IndexError: xchat.prnt('couldn\'t upload the image') return xchat.EAT_ALL