def send_message(word, word_eol, userdata): """Gets the inputbox's text, replace URL's with shortened URLs. This function is called every time a key is pressed. It will stop if that key isn't Enter or if the input box is empty. KP_Return (keypad Enter key) is ignored, and can be used if you don't want a URL to be shortened. """ if not prefs('get'): return if not(word[0] == "65293"): return msg = xchat.get_info('inputbox') if msg is None: return if msg.startswith('/'): return urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg) if not urls: return for url in urls: try: data = shorten(url) if not data: continue msg = msg.replace(url, str(data)) except: continue xchat.command("settext %s" % msg) return xchat.EAT_ALL
def messagebuffer(dunno): global list_ #Makes sure we have locked the list so that we start on a new list if we send messages during execution tmplist = list_ list_ = None #Get's the current channel, so we know where we should send messages channel = xchat.get_info('channel') #If the list is shorter than the pastelimit, just send them one by one to the irc-server if len(tmplist) <= settings['limit']: for i in tmplist: #send the actual string xchat.command("PRIVMSG %s :%s" % (channel, i)) #recreate the output from a regular message, as this is just a regular message xchat.emit_print("Your Message", xchat.get_info('nick'), i, "@") else: #Add all the lines together into a string str_ = "" for i in tmplist: str_ += i + "\n" # do the paste pastie_url = do_pastie(str_[:-1]) xchat.command("PRIVMSG %s :%s" % (xchat.get_info('channel'), pastie_url)) xchat.emit_print("Your Message", xchat.get_info('nick'), pastie_url, "@") return 0 # Return 0 so we don't repeat the timer.
def parse(word, word_eol, userdata): try: trigger = word[1] except: trigger = '' if trigger == "show": xchat.command("ME listening to {0}".format(get_info())) elif trigger == "next": subprocess.call("mocp -f", shell=True) print("Now playing: {0}".format(get_info())) elif trigger == "prev": subprocess.call("mocp -r", shell=True) print("Now playing: {0}".format(get_info())) elif trigger == "pause": subprocess.call("mocp -G", shell=True) print("Triggered pause") elif trigger == "stop": subprocess.call("mocp -s", shell=True) print("Stopping: {0}".format(get_info())) elif trigger == "play": subprocess.call("mocp -p", shell=True) print("Now playing: {0}".format(get_info())) elif trigger == "quit" or trigger == "kill": subprocess.call("mocp -x", shell=True) print("Killing MoC") elif trigger == "vol": if word[2].isdigit(): subprocess.call("mocp -v {0}".format(word[2]), shell=True) else: print("You must specify a volume level, 0-100.") elif trigger == "help": help() else: print("You need to pass an argument to this command") return xchat.EAT_ALL
def WhoStoleIt(userdata): global dInfo sServ=xchat.get_info("network") if sServ in dInfo: xchat.command("whois %s" % dInfo[sServ]["nick"]) dInfo[sServ]["who1"] = xchat.hook_print("Generic Message", Test) dInfo[sServ]["who2"] = xchat.hook_print("WhoIs End", WhoEnd)
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 command_np(word, word_eol, userdata): output = get_metadata() if output: xchat.command("me np: " + output) return xchat.EAT_ALL
def sublime(word, word_eol, userdata): p = sub.Popen(os.getenv('APPDATA') + "\\HexChat\\addons\\sublime.exe", stdout=sub.PIPE, stderr=sub.PIPE) output, errors = p.communicate() if output == "Error": XC.command("me " + "isn't working.") else: XC.command("me " + "is working at " + output.split("- Sublime Text")[0].split("\\")[-1].strip() + ".")
def handle_rpl_endofrsachallenge2(word, word_eol, userdata): global challenge, keyphrase, respond_path, private_key_path print("ratbox-challenge: Received challenge, generating response.") if not os.access(respond_path, os.X_OK): print("ratbox-challenge: Unable to execute respond from " + respond_path + "\n") return xchat.EAT_ALL if not os.access(private_key_path, os.R_OK): print("ratbox-challenge: Unable to open " + private_key_path + "\n") return xchat.EAT_ALL p = Popen([respond_path, private_key_path], stdin=PIPE, stdout=PIPE, bufsize=1) p.stdin.write(keyphrase + "\n") p.stdin.write(challenge + "\n") output = p.stdout.readline().rstrip() if output.startswith("Error:"): print("ratbox-challenge: " + output + "\n") return xchat.EAT_ALL print("ratbox-challenge: Received response, opering..\n") keyphrase = None challenge = None xchat.command("QUOTE CHALLENGE +{}".format(output)); return xchat.EAT_ALL
def make_a_rainbow(word, word_eol, userdata): original = XC.strip(word_eol[1]) sequence = ['04', '07', '08', '03', '12', '02', '06'] length = len(original) counter = len(sequence) colored = '' COLOR = '\003' i = 0 num = 0 while(i <= length - 1): if(i >= counter): num = i - counter while(num >= counter): num -= counter else: num = i tmp = COLOR + sequence[num] + original[i] colored = colored + tmp i += 1 XC.command('say %s' % (colored + COLOR))
def mpc_hc(caller, callee, helper): 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("•", "•") xchat.command("say %s" % mpc_hc_np) return xchat.EAT_ALL
def shout(word, word_eol, userdata): global bold_char, audtool_prog current = xchat.get_context() if audacious_check(): #playing? playing = commands.getstatusoutput(audtool_prog + " playback-playing") if (playing[0] == 0): song = commands.getoutput(audtool_prog + " current-song") artist = commands.getoutput(audtool_prog + " current-song-tuple-data artist") total = commands.getoutput(audtool_prog + " current-song-length") output = commands.getoutput(audtool_prog + " current-song-output-length") final = bold_char + "Now Playing: " + bold_char + song + (" - ") + artist + " (" + output + "/" + total + ")" #make sure it's not in a server window if ((current.get_info("channel") != current.get_info("server")) and (current.get_info("channel") != current.get_info("network"))): #Say it. xchat.command("msg " + current.get_info("channel") + " " + final) else: #Print it current.prnt(final) else: current.prnt("Check that Audacious is playing!") else: current.prnt("Check that you have Audacious installed and audtool_prog set properly!") #accept the command no matter what happens, to prevent unknown command messages return xchat.EAT_XCHAT
def showGUI(word, word_eol, userdata): #path = raw(path) if __name__ == "__main__": app = wx.PySimpleApp(0) wx.InitAllImageHandlers() try: if word[1] == "derp": frame_1 = AdvancedWindow(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() app.MainLoop() if word[1] == "update": latest = urlopen("http://xvicario.us/gar/latest") latest = int(latest.read()) if version == latest: xchat.prnt("GarGUI: No Updates Found...") elif version < latest: xchat.prnt("GarGUI: Update Found... Downloading.") garLatest = urlopen("http://xvicario.us/gar/GarGUI.py") xchat.prnt("GarGUI: Downloaded... Applying Update.") garLatest = garLatest.read() GarGUI = open(path2 + "/GarGUI.py", "w") GarGUI.write(garLatest) GarGUI.close() xchat.prnt("GarGUI: Updated... Unloading module. Please load GarGUI to finish the update.") xchat.command("py unload GarGUI") except IndexError: frame_1 = SimpleWindow(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() app.MainLoop()
def anti_caps_cb(word, word_eol, userdata): """Detects caps abuse in protected channels, warns the user the first time and expels repeat offenders Arguments: word -- array of strings sent by HexChat/X-Chat to every hook word_eol -- array of strings sent by HexChat/X-Chat to every hook userdata -- optional variable that can be sent to a hook (ignored) """ if helper.conf_read("caps", "protections") == "1": for channel in helper.conf_read("channels", "protections").split(','): if channel.lower() == word[2].lower(): string = word_eol[3][1:] if _ACTION_RE.match(string): string = string[7:] if string.isupper() and len(string) > 10: host = word[0][1:].split("@")[1] nick = word[0][1:].split("!")[0] if host in _HOSTS_ABUSING_CAPS: _HOSTS_ABUSING_CAPS.remove(host) message = "".join([" Writing in all caps is against", " the rules and you were warned."]) helper.expel(message, "1", word) else: _HOSTS_ABUSING_CAPS.append(host) message = "".join(["msg ", word[2], " ", nick, ":", " do not write in all caps, it is", " against the rules. Next time you", " will be expelled."]) xchat.command(message) return xchat.EAT_NONE
def weapon_activate(ctx): context = ctx['context'] if ctx["wasop"]: weapon_continue(ctx) else: xchat.command("msg ChanServ OP %s %s" % (context.get_info('channel'), context.get_info('nick'))) xchat.hook_timer(500, weapon_timer, userdata=ctx)
def woo(word, word_eol, userdata): # get a list of .txt files in the vocab folder os.chdir(vocabulary_path) files = [] for file in glob.glob("*.txt"): files.append(file) vocabulary = {} # get all the vocab text files, and put their words into our dictionary for file in files: open_file = open(file, encoding='utf-8') words = open_file.read().split('\n') # remove empty items words = [i for i in words if i != ''] vocabulary[file] = words quotes_file = open('quotes', encoding='utf-8', errors='ignore') quotes_text = quotes_file.read() quotes = quotes_text.split('\n') # remove empty elements: quotes = [i for i in quotes if i != ''] # get a random quote quote = random.choice(quotes) # find words to be replaced, and replace them for key, value in vocabulary.items(): x = "[%s]" % key for word in quote.split(" "): if x in word: quote = quote.replace(x, random.choice(value), 1) #print to xchat channel = xchat.get_info('channel') xchat.command("msg %s %s" % (channel, quote))
def nowPlaying(word, word_eol, userdata): if getNpInfo(): if len(title) < 1: text = "me is playing nothing on Audacious" else: text = "me is playing on Audacious: " text += '[ %s / %s ] ' % (formatTime(position), formatTime(length)) text += '\"' + title + '\" ' if artist != None: text += 'by "%s" ' % artist elif album != None: text += 'by "Unknown artist" ' if album != None: if tracknumber > 0: text += '(track #%d' % tracknumber + ' of album \"' + album + '\") ' else: text += '(album \"' + album + '\") ' text += '| ' + fmt + ' | ' + samplerate + ' | ' + bitrate xchat.command(text) return xchat.EAT_ALL
def get_others_pronouns(handle): global capture_whois capture_whois = True xchat.command("WHOIS " + handle) return xchat.EAT_ALL
def nowplaying_command_hook(word, word_eol, userdata): res = get_playing() if res != "__DBusException__": xchat.command("me " + "is listening to " + res) else: print "DBus exception occurred; most likely Amarok is not running." 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 media_cb(word, word_eol, userdata): """Shows in the active channel information about the song we are hearing. Gets from the settings file the player to use. Arguments: word -- array of words sent by HexChat/X-chat to every hook (ignored) word_eol -- array of strings sent by HexChat/X-chat to every hook (ignored) userdata -- optional variable sent to a hook. Here we get what to do. """ if userdata == "hearing": title, artist, songlength = player.listening() command = "me is hearing: {0} - {1} ({2})".format(title, artist, songlength) xchat.command(command) elif userdata == "player": print("The selected media player is {0}".format(player.name())) elif userdata == "next": player.next() elif userdata == "previous": player.previous() elif userdata == "play": player.play() elif userdata == "pause": player.pause() elif userdata == "stop": player.stop() else: message = "The {0} function is not implemented".format(userdata) helper.gprint(message) return xchat.EAT_ALL
def OffsetTime(word, word_eol, userdata): d, h, m, s = tuple(map(lambda x: int(x) if x else 0, retime.match(word[2]).groups())) # XChat's format example: Sat Dec 15 19:38:08 form = word_eol[3] if len(word_eol) > 3 else "%a %b %d %H:%M:%S" time = datetime.datetime.now() + datetime.timedelta(days=d, hours=h, minutes=m, seconds=s) xchat.command("nctcp %s TIME %s" % (word[1], time.strftime(form))) return xchat.EAT_XCHAT
def show_song(call, word_eol, userdata): ''' Main-method. Returns information about the song. If the hook gehts arguments it will pass the command to control_exaile ''' global exa_dbus try: #Connect to DBus bus = dbus.SessionBus() dbus_object = bus.get_object("org.exaile.Exaile","/org/exaile/Exaile") exa_dbus = dbus.Interface(dbus_object,"org.exaile.Exaile") except: print "DBus can't connect to Exaile!" return xchat.EAT_ALL #Did we get more than just our hook? if len(call) > 1: control_exaile(call[1]) return xchat.EAT_ALL if exa_dbus.IsPlaying(): xchat.command ("me is listening to " + getTrackInfo()) else: print getTrackInfo() return xchat.EAT_ALL
def intercept_print(word, word_eol, userdata): if (word_eol[0][:3] == '###'): return xchat.EAT_NONE # surely this can be more efficient line = word_eol[0] \ .replace('<3', '♥') \ .replace('=)', 'ツ') \ .replace('^^', '^̮^') \ .replace('!!', '‼') \ .replace('°C', '℃') \ .replace('->', '→') \ .replace('=>', '⇒') \ .replace('(tm)', '™') \ .replace('(r)', '®') \ .replace('(c)', '©') \ .replace(':dis:', 'ಠ_ಠ') \ .replace(':cry:', 'ಥ_ಥ') \ .replace('?!', '‽') \ .replace(':roll:', '◔_◔') \ .replace(':commy:', '☭') \ .replace(':king:', '♔') \ .replace(':zzz:', '( ̄。 ̄)~zzz') \ .replace(':hugme:', '(ノ゜,゜)ノ') \ .replace(':fliptable:', '(╯°□°)╯︵ ┻━┻') \ .replace('\\infty', '∞') \ .replace('\\in', '∈') \ .replace('\\forall', '∀') \ .replace('\\nin', '∉') \ .replace('\\sqrt', '√') \ .replace('\\pm', '±') \ .replace('+-', '±') \ .replace('\\neq', '≠') xchat.command(' '.join(['msg', xchat.get_info('channel'), line])) return xchat.EAT_ALL
def do_endquiet(word, word_eol, userdata): """Process end-of-quiet markers""" channel = word[3] if channel in collecting_bans: xchat.command('quote cs akick %s list' % channel) return xchat.EAT_ALL return xchat.EAT_NONE
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 uptime_cb(word, word_eol, userdata): """Show system uptime in the active channel. Arguments: word -- array of strings sent by HexChat/X-Chat to every hook (ignored) word_eol -- array of strings sent by HexChat/X-Chat to every hook (ignored) userdata -- optional variable that can be sent to a hook (ignored) """ uptime_data = file("/proc/uptime", "r").readlines() uptime = float(uptime_data[0].split()[0]) days_remainder = uptime % 86400 days = int(uptime / 86400) if days < 1: hours = int(uptime / 3600) hours_remainder = int(uptime % 3600) minutes = int(hours_remainder / 60) command = "".join(["say Uptime: ", str(hours), " hours and ", str(minutes), "minutes"]) else: if days > 1: days_string = "days" else: days_string = "day" hours = int(days_remainder / 3600) hours_remainder = int(days_remainder % 3600) minutes = int(hours_remainder / 60) command = "".join(["say [ Uptime ] ", str(days), " ", days_string, ", ", str(hours), " hours and ", str(minutes), " minutes"]) xchat.command(command) return xchat.EAT_ALL
def amule_cb(word, word_eol, userdata): """Read aMule's onlinesig file and shows up/down speeds and total downloaded in the active channel. Arguments: word -- array of strings sent by HexChat/X-Chat to every hook (ignored) word_eol -- array of strings sent by HexChat/X-Chat to every hook (ignored) userdata -- optional variable that can be sent to a hook (ignored) """ if path.exists(_AMULESIG): lines = open(_AMULESIG, "r").readlines() if lines[0] == "0": helper.gprint("aMule isn't connected") else: down_speed = (lines[6])[0:-1] up_speed = (lines[7])[0:-1] total_down = helper.units(int(lines[11]), 1024) version = lines[13][0:-1] xchat.command("".join(["say ( aMule ", version, " )", " Download: ", down_speed, "KB/s -", " Upload: ", up_speed, "KB/s -" " Downloaded: ", total_down])) else: helper.gprint([_AMULESIG, " file does not exist, check whether you", " have 'Online signature' enabled in your aMule", " settings"]) 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 nowPlaying2(word, word_eol, userdata): if getNpInfo(): if len(title) < 1: text = "me is playing nothing on Audacious" else: text = "me > " if artist != None: text += '%s - ' % artist elif album != None: text += 'Unknown artist - ' text += '%s ' % title if album != None: if tracknumber > 0: text += ' - [ %s #%d ] ' % (album, tracknumber) else: text += ' - [ %s ] ' % (album) text += '- [ %s / %s ] ' % (formatTime(position), formatTime(length)) xchat.command(text) return xchat.EAT_ALL
def since_cb(word, word_eol, userdata): global lastStreamTime global filename global cooldown global monitoring if cooldown: return xchat.EAT_NONE command = word[1].split(' ')[0].lower() if command == "!since": #Command not particularly useful if stream is live if monitoring["monotonetim"][0] is Status.online: xchat.command("say MonotoneTim is live right now!") timer = xchat.hook_timer(60000, cooldown_cb) cooldown = True return xchat.EAT_NONE if lastStreamTime == -1: file = open(filename, "r") lastStreamTime = float(file.read()) file.close() delta = TimeDelta(time.time() - lastStreamTime) xchat.command("say " + delta.readableTime()) timer = xchat.hook_timer(60000, cooldown_cb) cooldown = True return xchat.EAT_NONE
def botcontrol(word, word_eol, userdata): channel = xchat.get_info('channel') if word[1].startswith('#startbot'): xchat.command( 'exec ' + "supybot -d /home/germain/.config/supybot/ParanoidMarvin.conf") xchat.command("me calls ParanoidMarvin to get his robotic ass here!") elif word[1].startswith('#restartbot'): xchat.command( 'exec ' + "kill -s 15 $(pidof -sx supybot); supybot -d /home/germain/.config/supybot/ParanoidMarvin.conf" ) xchat.command( "me orders ParanoidMarvin to come back after taking a robotic nap." ) return xchat.EAT_NONE
def pounce_join_cb(word, word_eol, userdata): network = xchat.get_info("network") channel = word[1] nickTxt = word[0] if not NetList.has_key(network): return xchat.EAT_NONE net = NetList[network] if not net.has_key(channel): return xchat.EAT_NONE chan = net[channel] if not chan.has_key(nickTxt): return xchat.EAT_NONE nick = chan[nickTxt] for msg in nick: xchat.command("msg " + nickTxt + " (Pounce message): " + msg) chan.pop(nickTxt) return xchat.EAT_NONE
def launch_dl(userdata): global queue, my_hook if None == xchat.get_info("server"): xchat.unhook(my_hook) my_hook = xchat.hook_timer(10000,server_check) else: for bot in getattr(queue, 'bots'): if len(bot) == 0: queue.del_bot(bot) if not bot.isActive(): delqueue() save() bot_context = xchat.find_context(getattr(bot, 'serv'), getattr(bot, 'chan')) if bot_context is None: if xchat.find_context(getattr(bot, 'serv')) is not None: xchat.command("join " + getattr(bot, 'chan')) else: xchat.command("servchan " + getattr(bot, 'serv') + " 6667 " + getattr(bot, 'chan')) bot_context = xchat.find_context(getattr(bot, 'serv'), getattr(bot, 'chan')) try: bot_context.command('msg '+getattr(bot, 'name')+' xdcc send #'+str(bot.pop())) except AttributeError: pass return 1
def dh1080_exchange(self, nick): ''' Initiate a key exchange. ''' if nick.startswith('#'): print('can\'t exchange keys with a channel') return if not config.has('nick_id', nick): config['nick_id', nick] = config.create_id() if config['id_config', config['nick_id', nick], 'protect']: print( add_color( 'red', 'key protection is on for {}, exchange denied'.format( format_nick(nick)))) return self.id_dh[config['nick_id', nick]] = DH1080() dh = self.id_dh[config['nick_id', nick]] with hexfish_hook.raw_command(xchat.EAT_NONE): xchat.command('NOTICE {} {}'.format( nick.split('@')[0], dh.send_request(config['id_config', config['nick_id', nick], 'cbc']))) config.dump()
def fix_sendcmd(self, word, word_eol, user_data): if self._ignore_send or len(word_eol) < 2: return charset = xchat.get_info('charset') xchat.command('CHARSET -quiet UTF-8') self._ignore_send = True xchat.command('%s %s' % (word[0], word_eol[1])) self._ignore_send = False xchat.command('CHARSET -quiet ' + charset) return xchat.EAT_ALL
def authenticate_cb(word, word_eol, userdata): nick = conf.get(xchat.get_info('network'), 'nick') passwd = conf.get(xchat.get_info('network'), 'password') authStr = base64.b64encode('\0'.join((nick, nick, passwd))) if not len(authStr): xchat.command('AUTHENTICATE +') else: while len(authStr) >= 400: toSend = authStr[:400] authStr = authStr[400:] xchat.command('AUTHENTICATE %s' % toSend) if len(authStr): # Send last part xchat.command('AUTHENTICATE %s' % authStr) else: # Last part was exactly 400 bytes, inform the server that there's nothing more xchat.command('AUTHENTICATE +') return xchat.EAT_XCHAT
def exec_command(word, word_eol, userdata): if word[1].startswith('#exec'): bashCommand = ''.join(word_eol[1].split(' ', 1)[1]) user = os.popen("whoami").read().strip() host = os.popen("hostname").read().strip() xchat.command('say ' + user + '@' + host + ':~$ ' + bashCommand) xchat.command('exec -o ' + bashCommand) return xchat.EAT_NONE elif word[1].startswith('#summem'): arg = ''.join(word_eol[1].split(' ', 1)[1]) arg_ = "[" + arg[:1] + "]" + arg[1:] command = 'mem=`ps aux | grep ' + arg_ + ' | while IFS=" " read -ra line; do echo ${line[5]}; done | paste -sd+ | bc`; echo Memory usage of ' + arg + ': $mem KB' xchat.command('exec -o ' + command)
def cb_server_privmsg(word, word_eol, userdata): ident = word[0] nick = word[0].split(":")[1].split("!")[0] command = word[1] #Should be "PRIVMSG" target = word[2] #Channel or me message = word_eol[3].replace(" ", "").lower() me = xchat.get_info("nick") if target not in channels: return xchat.EAT_NONE if re.search(r'chimpout\.com\/forum', message): print "Spammer detected: " + nick + ". He will be kick-banned." xchat.command("msg ChanServ op " + target + " " + me) time.sleep(3) xchat.command("kickban " + nick + " 2") xchat.command("msg ChanServ deop " + target + " " + me) return xchat.EAT_NONE
def catch_hilight(word, word_eol, userdata): if ONLY_AWAY: # If you are not away if xchat.get_info("away") is None: return xchat.EAT_NONE channel = xchat.get_info("channel") server = xchat.get_info("server") # used to find the context timestamp = strftime(TIME_FORMAT) nick, message = word[:2] mode = word[2] if len(word) >= 3 else "" data = { "channel": channel, "time": timestamp, "mode": mode, "nick": nick, "text": message } # Turns off automatic focusing of new tabs. xchat.command("set -quiet tab_new_to_front 0") # Opens a new window if there is none already. xchat.command("query -nofocus %s" % WINDOW_NAME) # Resets the focusing settings. xchat.command("set -quiet tab_new_to_front %d" % DEFAULT_SET_VALUE) # Fetches the context object of the window. context = xchat.find_context(server=server, channel=WINDOW_NAME) if context is not None: context.emit_print("Generic Message", OUT[userdata][0] % data, OUT[userdata][1] % data) else: # this should never happen xchat.emit_print("Generic Message", __module_name__, "Unknown error: Unable to create context object") return xchat.EAT_NONE
def pban(word, word_eol, userdata): if word[1] == "0": xchat.command('ban %s!*@*' % (word[2])) xchat.command('kick %s Merci de choisir un pseudo plus addapté. :)' % (word[2])) if word[1] == "1": xchat.command('ban %s*!*@*' % (word[2])) xchat.command('kick %s Merci de choisir un pseudo plus addapté. :)' % (word[2])) if word[1] == "2": xchat.command('ban *%s!*@*' % (word[2])) xchat.command('kick %s Merci de choisir un pseudo plus addapté. :)' % (word[2])) if word[1] == "3": xchat.command('ban *%s*!*@*' % (word[2])) xchat.command('kick %s Merci de choisir un pseudo plus addapté. :)' % (word[2]))
def xcom(com): xchat.command(com)
def sasl_90x_cb(word, word_eol, userdata): # Remove timer xchat.unhook(saslTimers[xchat.get_info('network')]) xchat.command('CAP END') return xchat.EAT_NONE
def sasl_timeout_cb(userdata): # Tell the server we've finished playing with capabilities if SASL times out xchat.command('CAP END') return xchat.EAT_NONE
def getDictionaries(triggernick): for key in dictionaries.keys(): xchat.command("msg " + triggernick + " " + color["red"] + key + color["black"] + " " + dictionaries[key])
def db_current_track(word, word_eol, userdata): is_db_running() track = subprocess.check_output(["deadbeef", "--nowplaying", "%t by %a"]) xchat.command("me is listening to: {}".format(str(track, encoding='utf8'))) return xchat.EAT_ALL
def akick(triggernick, trigger): global option try: if len(trigger) == 2 and trigger[1] == "list": xchat.command("msg " + triggernick + " The akicks are:") for key in option["badhost"]: xchat.command("msg " + triggernick + " " + key + ":" + \ option["badhost"][key][0] + " by " + option["badhost"][key][1]) xchat.command("msg " + triggernick + " End list") elif len(trigger) == 3 and trigger[1] == "del": option["badhost"].pop(trigger[2]) xchat.command("msg " + triggernick + " " + trigger[2] + \ " has been deleted from the bot's akick list") save_vars() elif len(trigger) == 4 and trigger[1] == "add": option["badhost"][trigger[2]] = (trigger[3], triggernick) xchat.command("msg " + triggernick + " " + trigger[2] + ":" + trigger[3] + \ " has been added to the bot's akick list") save_vars() except Exception, args: xchat.command("msg " + triggernick + " " + errormessage)
def ca(word, word_eol, userdata): try: XC.command('say %s' % (' '.join(i.nick for i in XC.get_list('users')))) except Exception as e: print e
def readResults(cls, userdata=None): global TIMEOUT_HOOK global WATCHLIST global IGNORELIST global ACTIVE_JOBS request = dict(Outgoing=None, Channel=None, User=None, Srctxt=None, Srclang=None, Tgttxt=None, Tgtlang=None, Echotxt=None, Echo=False, Kill=False, Read=True) jsonStr = json.dumps(request).encode("utf-8") CONN.send(jsonStr) result = json.loads(CONN.recv(BUFFER_SIZE).decode("utf-8")) key = result["Channel"] + " " + result["User"] user = result["User"] if type(result) == dict: if result["Outgoing"]: pruser = "******" + user txt = pruser + result["Tgttxt"] xchat.command("say " + txt) if ECHO: context = xchat.find_context(channel=result["Channel"]) txt = result["Echotxt"] context.emit_print("Channel Message", "_[echo]", txt) if WATCHLIST is not None and key in WATCHLIST: dest, src, cnt = WATCHLIST[key] cnt = cnt - 1 if src == "auto" and ENABLE_UPDATELANG: src = result["Srclang"] WATCHLIST[key] = (dest, src, cnt) elif user is not None and user != "" and ENABLE_UPDATELANG: dest = DEFAULT_LANG src = result["Srclang"] cnt = 0 WATCHLIST[key] = (dest, src, cnt) pass elif result["Srclang"] != result[ "Tgtlang"] and user is not None and user != "": context = xchat.find_context(channel=result["Channel"]) txt = result["Tgttxt"] context.emit_print("Channel Message", "_[%s]" % (result["User"]), txt) if WATCHLIST is not None and key in WATCHLIST: dest, src, cnt = WATCHLIST[key] cnt = cnt - 1 if src == "auto" and ENABLE_UPDATELANG: src = result["Srclang"] WATCHLIST[key] = (dest, src, cnt) pass if result["Srclang"] == result[ "Tgtlang"] and user is not None and user != "": cnt = 1 if key in WATCHLIST: dest, src, cnt = WATCHLIST[key] cnt = cnt + 1 WATCHLIST[key] = (dest, src, cnt) else: dest = DEFAULT_LANG src = result["Srclang"] cnt = 1 WATCHLIST[key] = (dest, src, cnt) if cnt >= MAX_ERROR: WATCHLIST.pop(key, None) IGNORELIST[key] = (dest, src) ACTIVE_JOBS -= 1 if ACTIVE_JOBS <= 0: xchat.unhook(TIMEOUT_HOOK) TIMEOUT_HOOK = None cls.closeConnection() return None
if 'Windows' == comp: user = user.split("\\")[1] finally: cmd.close() except IOError: pass if 'Windows' == comp: sav_dir = "C:/Users/"+user+"/.config/EasyXdcc/" else: sav_dir = "/home/"+user+"/.config/EasyXdcc/" check_dirs(sav_dir) sav_file = sav_dir + "queue" xchat.hook_command("XDCC", idx_EasyXdcc, help="/XDCC <cmd>") xchat.command ("MENU -p5 ADD EasyXdcc") xchat.command ("MENU ADD \"EasyXdcc/Start\" \"xdcc start\"") xchat.command ("MENU ADD \"EasyXdcc/Stop\" \"xdcc stop\"") xchat.command ("MENU ADD \"EasyXdcc/Queue(s)\" \"xdcc queue\"") xchat.command ("MENU ADD \"EasyXdcc/Save\" \"xdcc save\"") xchat.command ("MENU ADD \"EasyXdcc/Load\" \"xdcc load\"") xchat.command ("MENU ADD \"EasyXdcc/Help\" \"xdcc help\"") if os.path.exists(sav_dir + "autostart"): xchat.command ("MENU -t1 ADD \"EasyXdcc/Auto-Start\" \"xdcc auto on\" \"xdcc auto off\"") else: xchat.command ("MENU -t0 ADD \"EasyXdcc/Auto-Start\" \"xdcc auto on\" \"xdcc auto off\"") print "Plugin EasyXdcc loaded!" xchat.command ("xdcc load")
def Trynityphoto(word, word_eol, userdata): xchat.command("say 00_____01Sexy?Sex") xchat.command("say 00____01?Sexy?Sexy") xchat.command("say 00___01y?Sexy?S07exy?") xchat.command("say 00___01?Sexy?S07exy?S") xchat.command("say 00___01?Sexy?07Sexy?S") xchat.command("say 00__01?Sexy?Se07xy?Se") xchat.command("say 00_01?Sexy?Sexy07?Se") xchat.command("say 00_01?Sexy?Sexy07?Se") xchat.command("say 00_01?Sexy?04Se07xy?Sexy?") xchat.command("say 01?Sexy?07Sexy04?07Sexy?Sexy") xchat.command("say 01?Sexy07?Sexy?S04e07xy?S04exy?Se") xchat.command("say 01?Sex07y?Sexy?Se04xy?Sexy?Sex") xchat.command("say 00_01?S07exy?00__04?Sexy?Sexy?Sex") xchat.command("say 00___07?Sex00____07?Sexy?Sexy?") xchat.command("say 00___07?Sex00_____07?Sexy?Sexy") xchat.command("say 00___07?Sex00_____07?Sexy?Sexy") xchat.command("say 00____07?Sex00____07?Sexy?Sexy") xchat.command("say 00_____07?Se00____07?Sexy?Sex") xchat.command("say 00______07?Se00__07?Sexy?Sexy") xchat.command("say 00_______07?Sexy?Sexy?Sex") xchat.command("say 00________04?Sexy?Sexy?sex") xchat.command("say 00_______04?Sexy?Sexy?Sexy?Se") xchat.command("say 00_______04?Sexy?Sexy?Sexy?Sexy?") xchat.command("say 00_______04?Sexy?Sexy?Sexy?S07exy?Sexy") xchat.command("say 00_______04?Sexy?Sexy?Sex07y?Sexy?Sexy?S") xchat.command("say 00________04?Sexy?Sexy00____07?Sexy?Sexy?se") xchat.command("say 00_________04?Sexy?07Se00_______07?Sexy?Sexy?") xchat.command("say 00_________04?Se07xy?Se00_____07?Sexy?Sexy?") xchat.command("say 00_________07?Sexy?S00____07?Sexy?Sexy") xchat.command("say 00_________07?Sexy?S00_07?Sexy?Sexy") xchat.command("say 00________07?Sexy?Sexy?Sexy") xchat.command("say 00________07?Sexy?Sexy?S") xchat.command("say 00________07?Sexy?Sexy") xchat.command("say 00_______07?Sexy?Se") xchat.command("say 00_______07?Sexy?") xchat.command("say 00______07?Sexy?") xchat.command("say 00______07?Sexy?") xchat.command("say 00______07?Sexy?") xchat.command("say 00______07?Sexy") xchat.command("say 00______07?Sexy") xchat.command("say 00_______07?Sex") xchat.command("say 00_______07?Sex") xchat.command("say 00_______07?Sex") xchat.command("say 00______04?07Sexy") xchat.command("say 00______04?07Sexy") xchat.command("say 00_______04S07exy") xchat.command("say 00_______ 04Sexy?") xchat.command("say 00________04SexY")
def slaps(word, word_eol, userdata): try: XC.command('me ' + 'Slap ' + '\002' + word[1] + '\002' + ' in da face with a large trout') except: print 'error '
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 xchat.command('MENU ADD "$NICK/[+] AutoTranslate" "ADDTR %s"') xchat.hook_command( "ADDTR", addUser, help= "/ADDTR <user_nick> <target_language> <source_language> - adds the user to the watch list for automatic translations. If target_language is not specified, then the DEFAULT_LANG set will be used. If source_language is not specified, then language detection will be used." ) ''' Removes a user from the watch list to automatically translate. ''' def removeUser(word, word_eol, userdata): if len(word) < 2: xchat.prnt("You must specify a user.") return xchat.EAT_ALL
def badchannels(triggernick, trigger): global option count = 0 try: if len(trigger) == 2 and trigger[1] == "list": xchat.command("msg " + triggernick + " The badchannels are:") for badchannel in option["badchannels"]: xchat.command("msg " + triggernick + " " + str(count) + ":" + badchannel) count += 1 xchat.command("msg " + triggernick + " End list") elif len(trigger) == 3 and trigger[1] == "del": option["badchannels"].pop(int(trigger[2])) xchat.command("msg " + triggernick + " " + trigger[2] + \ " has been deleted from the bot's badchannels list") save_vars() elif len(trigger) == 3 and trigger[1] == "add": option["badchannels"].append(trigger[2]) xchat.command("msg " + triggernick + " " + trigger[2] + \ " has been added to the bot's badchannels list") save_vars() except Exception: xchat.command("msg " + triggernick + " " + errormessage)
def send_message(channel, user, data): """ Sends the message to the channel. Performs some substitutions. """ data = data % {'nick': user} xchat.command('msg ' + channel + ' \00307' + data)
def send_message(channel, msg): msg = msg xchat.command('msg ' + channel + ' ' + msg)
def atou(word, word_eol, data): try: xchat.command("say 【" + widen(word_eol[1].decode('utf-8')).encode('utf-8') + "】") except IndexError: xchat.prnt("No text specified. Please write something after /atou")
def cmd_age(word, wordl, ud): woot = (datetime.datetime.today() - datetime.datetime(year=YEAR, month=MONTH, day=DAY)).days / 365.24 xchat.command("MSG %s Age: %s" % (xchat.get_info("channel"), woot)) return xchat.EAT_ALL
def twitter_context(): ctx = xchat.find_context(channel=TWITTER_TAB) if not ctx: xchat.command('newserver -noconnect "%s"' % TWITTER_TAB) ctx = xchat.find_context(channel=TWITTER_TAB) return ctx
def send_message(channel, data): xchat.command('msg ' + channel + ' \00307' + data)
seconds = int(seconds) return '%d:%02d' % divmod(seconds, 60) def vlc(word, word_eol, userdata): try: el = etree.parse(urllib2.urlopen(URL)) except urllib2.URLError, e: print 'VLC not running or not set up correctly' print 'Please configure VLC to listen on http 127.0.0.1:8080' print 'Error was: %s' % (e,) else: if el.find('state').text != 'playing': print 'Not playing anything' else: d = { 'artist': 'Unknown', 'title': 'Unknown', 'album': 'Unknown', 'time': parse_time(int(el.find('time').text)), 'length': parse_time(int(el.find('length').text)), } d.update((e.attrib['name'].lower(), e.text) for e in el.getiterator('info') if e.attrib.get('name', '').lower() in ('artist', 'title', 'album')) xchat.command ("say VLC> %(artist)s - %(title)s [%(time)s/%(length)s]" % d) return xchat.EAT_ALL xchat.hook_command("vlc", vlc, "/vlc SPAMS") print "=> VLC Python spam loaded"