def choose_callback(word, word_eol, user_data): channel = hexchat.get_info("channel") if (channel in channels) and not (set(user.nick for user in hexchat.get_list("users")) & other_bots): option = None user = None input = None matches = choose_regex.match(word[1]) if matches: option = "CHOOSE" user = word[0] input = matches.group(1) else: matches = order_regex.match(word[1]) if matches: option = "ORDER" user = word[0] input = matches.group(1) if option == "CHOOSE" or option == "ORDER": for action in (try_choose, try_order): response = action(option, input) if response != None: context = hexchat.get_context() hexchat.hook_timer( 0, send_response, {"context": hexchat.get_context(), "user": user, "response": response} ) break return hexchat.EAT_NONE
def _cb(word, word_eol, userdata): if hexchat.strip(word[0]) in ["gonzobot"]: duckDetect = re.search("o<|o<", hexchat.strip(word[1])) if duckDetect is not None: print("quack") context = hexchat.get_context() hexchat.hook_timer(randint(3000,7000), duck, context)
def checkStreams(): global firstRun if(firstRun): hexchat.unhook(timerHook) hexchat.hook_timer(300000, checkStreams_cb) firstRun = False channels = hexchat.get_list("channels") realChannels = [] channelObjects = {} for channel in channels: if(channel.server == "tmi.twitch.tv" and channel.channel[0] == '#'): realChannels.append(channel.channel.strip('#')) channelObjects[channel.channel.strip('#')] = channel if len(realChannels) > 0: streams = ",".join(realChannels) obj = loadJSON('https://api.twitch.tv/kraken/streams?channel=' + streams) # Returns only streams that are currently live, but returns them all in one go. if (obj is not None): streamData = {} for stream in obj["streams"]: streamData[stream["channel"]["name"]] = stream for channel in realChannels: newTopic = "\00318{0}\00399 - \00320\002OFFLINE\002\00399 | \035Stream is offline\017".format(channel) if (channel in streamData): newTopic = "\00318{0}\00399 - \00319\002LIVE\002\00399 for {1} viewers | Now playing: \00318{2}\00399 | {3}".format(streamData[channel]["channel"]["display_name"], streamData[channel]["viewers"], streamData[channel]["channel"]["game"], streamData[channel]["channel"]["status"]) if (get_topic(channelObjects[channel]) is not None): if (hexchat.strip(newTopic) != hexchat.strip(get_topic(channelObjects[channel]))): set_topic(channelObjects[channel], newTopic) else: set_topic(channelObjects[channel], newTopic)
def checkStreams(): global firstRun if (firstRun): hexchat.unhook(timerHook) hexchat.hook_timer(300000, checkStreams_cb) firstRun = False channels = hexchat.get_list('channels') realChannels = [] for channel in channels: if (channel.server == 'tmi.twitch.tv' and channel.channel[0] == '#'): realChannels.append(channel.channel.strip('#')) for channel in realChannels: obj = loadJSON('https://api.twitch.tv/kraken/streams/' + channel) if (obj['stream'] == None and channel in liveChannels): liveChannels.remove(channel) format(channel.title() + ' is not live anymore.') elif (obj['stream'] != None and channel not in liveChannels): liveChannels.append(channel) format(channel.title() + ' is live!') format(obj['stream']['channel']['status'] + '(' + obj['stream']['game'] + ')') elif (obj['stream'] == None and channel not in liveChannels): format(channel.title() + ' is offline.')
def run(): """This is the logic on what packs actually get added to the queue. It's run just about any time there is an interaction with the queue (get, delete, dcc events, etc).""" global CommandQueue, Active, Watchdog if not MULTIQUEUE: # If there's an active transfer, we return if Active: return if not CommandQueue: return # If not, we start one and start a watchdog timer cmd = CommandQueue.get() Active.append(cmd) cmd.execute() if not Watchdog: Watchdog = hexchat.hook_timer(45000, transferCheck) return # We are in MULTIQUEUE mode ... aps = sorted(Active.getBotSet()) cps = sorted(CommandQueue.getBotSet()) missing = [bot for bot in cps if bot not in aps] print_debug('multiq: a: %s, q: %s, missing: %s' % (aps, cps, missing)) # if we have the same bots in each, we are already transfering at full.. if not missing: return for bot in missing: cmd = CommandQueue.getBotPackSet(bot) if not cmd: return cmd = cmd[0] Active.append(cmd) CommandQueue.remove(cmd) print_debug("/%s on %s@%s" % (cmd.s, cmd.channel, cmd.network)) cmd.execute() # set up a watchdog every 45 seconds if Active and not Watchdog: Watchdog = hexchat.hook_timer(45000, transferCheck)
def get_input_from_argparse(callback, parsed_args): print_debug(parsed_args) parsed_args = parsed_args.copy() source = parsed_args.get('source') print_debug("get_input args", parsed_args) if parsed_args.get("confirm"): del parsed_args['confirm'] def confirmed_cb(b): if b: get_input_from_argparse(callback, parsed_args) if is_mainthread(): send_getbool_to_callback(confirmed_cb) else: hexchat.hook_timer(20, send_getbool_to_callback, confirmed_cb) return if source == "inputbox": if not parsed_args['guard_inputbox_cmd']: callback(ibx.get()) else: callback(parsed_args['guard_inputbox_cmd'][1]) elif source == "clipboard" and HAVE_XEROX: callback(xerox.paste()) elif source == "window": # Ask main thread to getstr and then give it to our callback. if is_mainthread(): send_getstr_to_callback(callback) else: hexchat.hook_timer(20, send_getstr_to_callback, callback) else: raise FloodcontrolError("Could not get input. Requested source: {}".format(source))
def base_commands(word, word_eol, userdata): if hexchat.get_info("network") != "Twitch": if word[1] == "help": say("Valid commands: help, currenttime, eat, time, uptime, douptime, version, mail") elif word[1] == "time": say("blargcat was started at " + datetime.strftime(start_time, '%Y-%m-%d %H:%M:%S')) elif word[1] == "currenttime": say("The current time for blargcat is " + datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')) elif word[1] == "uptime": get_uptime(word) elif word[1] == "eat": eat() elif word[1] == "reload": reload_config() hexchat.unhook(notify_hook) hexchat.hook_timer(notif_timer_value, notify) # elif word[1] == ".tps": # say("TPS:\0033 19.97") # elif word[1] == ".list": # say("\00312Online (2/20): \0034[Admin] \00315blargcat\0031, \0039[Member] \00315FacePolice") elif word[1] == "version": say("blargcat is running \0039" + __module_name__ + "\0031 version\0039 " + __module_version__) elif word[1].startswith("mail"): mail(word) elif word[1] == "douptime": say(".uptime") elif word[1].startswith("raw "): global authed_user print(authed_user) print(word[0]) if authed_user == hexchat.strip(word[0], len(word[0]), 3): raw(word[1].replace("raw ", "")) else: say("You are not authed!")
def main(): if MODULE_DEBUG: hexchat.prnt("daychanged.py: DEBUG MODE") schedule.every(5).seconds.do(print_day_changed) schedule.every().day.at("00:00").do(print_day_changed) hexchat.hook_timer(1000, schedule_callback)
def statusCheck(): if not status["declareFailure"]: if hexchat.get_info("server") != None: status["connected"] = True if not status["connected"] and not status["connecting"]: if status["connectAttempt"] >= MAX_CONN_ATTEMPTS: # reset attempts, but don't try again for 10 minutes print(">>> Maximum connection attempts reached (%d), will try again later" % MAX_CONN_ATTEMPTS) status["connectAttempt"] = 0 hexchat.hook_timer(600000, delayedStatusCheck) else: print(">>> Attempting to connect to server") hexchat.command("server %s %s" % (serverName, portNum)) status["connecting"] = True status["connectAttempt"] += 1 elif not status["identified"] and not status["identifying"]: print(">>> Attempting to identify with server") hexchat.command("nick %s" % botName) identifyWithServer() status["identifying"] = True else: print(">>> Attempting to join channels") joinChannels()
def __init__(self, title, msg): message_map = { win32con.WM_DESTROY: self.OnDestroy, } # Register the Window class. wc = self.wc = WNDCLASS() hinst = wc.hInstance = GetModuleHandle(None) wc.lpszClassName = "PythonTaskbar" wc.lpfnWndProc = message_map # could also specify a wndproc. classAtom = self.classAtom = RegisterClass(wc) # Create the Window. style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU self.hwnd = CreateWindow( classAtom, "Taskbar", style, \ 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \ 0, 0, hinst, None) UpdateWindow(self.hwnd) iconPathName = hexchat.get_info('configdir') + "\\addons\\bubbles.ico" icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE try: self.hicon = LoadImage(hinst, iconPathName, \ win32con.IMAGE_ICON, 0, 0, icon_flags) except: self.hicon = LoadIcon(0, win32con.IDI_APPLICATION) self.flags = NIF_ICON | NIF_MESSAGE | NIF_TIP self.nid = (self.hwnd, 0, self.flags, win32con.WM_USER + 20, self.hicon, "Bubbles for HexChat.") Shell_NotifyIcon(NIM_ADD, self.nid) Shell_NotifyIcon(NIM_MODIFY, \ (self.hwnd, 0, NIF_INFO, win32con.WM_USER+20,\ self.hicon, "Balloon tooltip", msg, 200, title)) hexchat.hook_timer(5000, clearBubble)
def serverDisconnect(word, word_eol, userdata): if status["connected"]: status["connected"] = False status["connecting"] = False status["identified"] = False status["identifying"] = False hexchat.hook_timer(5000, delayedStatusCheck) # 5 second delay before reconnect attempt return hexchat.EAT_PLUGIN
def ScanNickMsg(word, word_eol, userdata): newName = word[1] nickChangeTimeout.append(newName) hexchat.hook_timer(10000, endNickTimeout) # 10 second timeout channel = hexchat.get_info("channel") checkForProxyMessage(newName, channel) # hexchat.command("msg ns status %s" % newName) return hexchat.EAT_PLUGIN
def ban_cb(word, word_eol, userdata): if len(word) > 1: mask = get_mask(word[1]) command = "" if mask: do_op() if word[0] == "ban": command = "mode +b {}".format(mask) elif word[0] == "kickban": nick = word[1] chan = hexchat.get_info("channel") message = "" if len(word_eol) > 2: message = word_eol[2] command = "mode +b {}\r\nKICK {} {} :{}".format(mask, chan, nick, message) elif word[0] == "kick": nick = word[1] chan = hexchat.get_info("channel") message = "" if len(word_eol) > 2: message = word_eol[2] command = "quote KICK {} {} :{}".format(chan, nick, message) elif word[0] == "remove": nick = word[1] chan = hexchat.get_info("channel") message = "" if len(word_eol) > 2: message = word_eol[2] command = "quote REMOVE {} {} :{}".format(chan, nick, message) elif word[0] == "quiet": command = "mode +q {}".format(mask) elif word[0] == "unban": command = "mode -b {}".format(mask) elif word[0] == "unquiet": command = "mode -q {}".format(mask) if command: hexchat.hook_timer(100, do_command, command) return hexchat.EAT_HEXCHAT else: return hexchat.EAT_NONE
def set(newtext, new_cursor_position=None): # HexChat seems to crash (sometimes? always?) when we change the inputbox # from outside the main thread. # We use HexChat's timers when we aren't on the main thread. def cb(*args): _set(newtext, new_cursor_position) return False if is_mainthread(): cb() else: hexchat.hook_timer(20, cb)
def set_user(username, count,message): global users, notice_cooldown tempuser={ "count" : count, "message": message, "time": time(), "timer": hexchat.hook_timer(notice_cooldown, del_user, username) } with lock: if username in users: hexchat.hook_timer(users[username]["timer"]) users[username] = tempuser
def set_timeout(callback, delay=0, args=(), kwargs={}): """Delay executiong of a function for `delay` ms. Useful for emitting print events in print event hooks that should occur after the hooked event has been printed. A delay of 0 (default) will suffice in most cases. """ def callback_handler(userdata): callback(*args, **kwargs) return False # remove hook hexchat.hook_timer(delay, callback_handler)
def kicked_check(word, word_eol, userdata): # This function rejoins channel def rejoin(userdata): # Check if the channel is not blacklisted if channel not in blacklist: hexchat.command("join " + channel) # Set the value of channel to the channel you were kicked from channel = word[1] # Run rejoin after <delay> millisecond hexchat.hook_timer(delay, rejoin)
def download(stuff): global apicallsleft script = stuff[0] verbose = True if len(stuff) >1 else False try: if verbose: pprefix("Downloading {}...".format(script)) urllib_request.urlretrieve(raw + script, os.path.join(ss_dir, script)) except urllib_error.HTTPError as err: pprefix("Error downloading {} ({})".format(script, err)) else: if verbose: pprefix("Download complete, loading script...") hexchat.hook_timer(0, pyload_timer, script) return False #For Timer
def paste(self): """ Continue pasting lines in this message context. """ if self.state == 'paste': raise HexPasteError('HexPaste: already pasting to: {}.'.format(self.context)) self.hook = hexchat.hook_timer(self.speed, self.tick) self.state = 'paste'
def xshun_cb(word,word_eol, _): global numerics xshun_timer_handle = None xshun_nick = None xshun_hooks = [] if os.name =="nt": xshun_nick = getclip() xshun_nick = str(xshun_nick) if(sys.version_info > (3, 0)): xshun_nick = xshun_nick[2:-1] #issue whois on nickname hexchat.command("whois " + str(xshun_nick)) #function to be called later to unhook all numeric hooks def xshun_unhook(): for hook in xshun_hooks: hexchat.unhook(hook) hexchat.unhook(xshun_timer_handle) def xshun_notice_cb(word, word_eol, _): if word[1] == '378': connecting_ip = str(word[8]) if(connecting_ip not in str (IRCCloud)): hexchat.command("shun +*@%s %s %s" % (str(connecting_ip),shun_time,shun_reason)) return hexchat.EAT_ALL def xshun_timeout_cb(_): xshun_unhook() xshun_hooks = [hexchat.hook_server(numeric, xshun_notice_cb) for numeric in numerics] xshun_timer_handle = hexchat.hook_timer(1000, xshun_timeout_cb) return hexchat.EAT_ALL
def startQuizz(self, word = None, word_eol = None, userdata = None): if self.loadQuizz(): if userdata: self.channel.setvalue(str(userdata)) if hexchat.get_info('channel')[0] == '#' and not self.channel.str()[0] == '#': self.channel.setvalue(hexchat.get_info('channel')) hexchat.prnt('Starting quizz on channel: ' + self.channel.str() + ' now on ' + hexchat.get_info('channel')) self.SendMessage(BOLD + COLORDEFAULT + 'Le quizz commence' + COLORDEFAULT + ' !') self.mode = 1 self.timer = 0 self.currentQuestion = None hexchat.hook_timer(1000, self.timerHook) self.currentStreak = 0 self.lastWinner = None self.currentStreak = 0 return hexchat.EAT_ALL
def on_notice(word, word_eol, userdata): global last_notice if word_eol[0] != last_notice: last_notice = word_eol[0] global timer_hook global block_time # If there is a timer currently running, replace it with a fresh one if timer_hook is not None: hexchat.unhook(timer_hook) timer_hook = hexchat.hook_timer(block_time, timer) else: timer_hook = hexchat.hook_timer(block_time, timer) return hexchat.EAT_NONE else: # Eat the event so other plugins/HexChat don't see it return hexchat.EAT_ALL
def setTimer(msg, botName, channel, db): lenDict = {'second': 1000,'minute': 60000, 'hour': 3600000} if msg.rawMatchRe('!timer (?P<num>\d+) (?P<unit>(hour|minute|second))s? ?(?P<other>.*)'): m = msg.getRegExpResult() ticks = int(m.group('num')) * lenDict[m.group('unit')] if ticks > 36000000: hexchat.command("msg %s That's way too much number to count to" % channel) return True message = m.group('other') if message == '': message = 'time' hexchat.hook_timer(ticks, generalTimer, "msg %s %s, %s" % (channel, msg.getUserName(), message)) hexchat.command("msg %s Maybe I'll remind you" % channel) return True return False
def keypress(w, we, u): global unmasked_command, old_cursor key, state, string, len_str = w key = int(key) len_str = int(len_str) if unmasked_command != None and key in [65293, 65421]: # [<Enter>, <Num-Enter>] reset_textbox(unmasked_command, old_cursor) unmasked_command = None old_cursor = None else: if len_str or key in [65288, 65535]: # [<Bksp>, <Del>] key_type = "edit" elif key in [65362, 65364]: # [<Up>, <Down>] key_type = "reset" else: key_type = "move" hexchat.hook_timer(0, update, key_type)
def freedom_alert_cb(word, word_eol, userdata): global fda_status if fda_status == False: return hexchat.EAT_NONE #optimize, if there is no f nor F no need to compute lower case if 0 == word_eol[1].find('f') and 0 == word_eol[1].find('F'): return hexchat.EAT_NONE internal = word_eol[1].lower() if "freedom" in internal: nickname = hexchat.get_info("nick") channel = hexchat.get_info("channel") if hexchat.nickcmp(nickname, word[0]) != 0: hexchat.hook_timer(1, fda_print, channel) return hexchat.EAT_NONE
def download(url): split = url.split("/") filename = split[len(split)-1].split(".")[0] extention = split[len(split)-1].split(".")[1] filention = filename + "." + extention if not extention == "py": hexchat.emit_print("Channel Message", __module_shortname__, "Not a python script!", "") return hexchat.emit_print("Channel Message", __module_shortname__, "Downloading {}...".format(filention), "") try: urllib_request.urlretrieve(url, os.path.join(addon_dir, filention)) except urllib_error.HTTPError as err: hexchat.emit_print("Channel Message", __module_shortname__, "Error downloading {} ({})".format(filention, err), "") else: hexchat.emit_print("Channel Message", __module_shortname__, "Download complete, loading script...", "") hexchat.hook_timer(0, loadpy_timer, filention) return
def download(script, unload): for site in addon_cache.keys(): if script in addon_cache[site]: script_file = expand_script(script) print('Script: Downloading {}...'.format(script)) try: urllib_request.urlretrieve(build_url(site, type='raw', script=script), script_file) except urllib_error.HTTPError as err: print('Script: Error downloading {} ({})'.format(script, err)) else: print('Script: Download complete, {}...'.format('reloading' if unload else 'loading')) if unload: # Updated # Threading causes odd timing issues, using timer fixes it. hexchat.hook_timer(0, unload_cb, script_file) hexchat.hook_timer(0, load_cb, script_file) return print('Script: Could not find {}'.format(script))
def time_cb(txt): global week global hook channel = hexchat.find_context(channel='#xshellz') channel.command('say {1} {0}'.format(username,txt)) update() if hook: hexchat.unhook(hook) hook = hexchat.hook_timer((week*1000),time_cb,userdata='!keep')
def keypress(w, we, u): global unmasked_command, old_cursor key, state, string, len_str = w key = int(key) len_str = int(len_str) if unmasked_command != None and key in [65293, 65421 ]: # [<Enter>, <Num-Enter>] reset_textbox(unmasked_command, old_cursor) unmasked_command = None old_cursor = None else: if len_str or key in [65288, 65535]: # [<Bksp>, <Del>] key_type = "edit" elif key in [65362, 65364]: # [<Up>, <Down>] key_type = "reset" else: key_type = "move" hexchat.hook_timer(0, update, key_type)
def handle_kick(word, word_eol, userdata): channel = hexchat.get_info("channel") if (hexchat.nickcmp(channel, userdata) == 0): if (hexchat.nickcmp(word[3], hexchat.get_info("nick")) == 0): print("Kicked from {}. Rejoining in {}ms…".format( channel, rejoin_delay)) rejoin_hooks[channel] = hexchat.hook_timer(rejoin_delay, rejoin, channel) return hexchat.EAT_NONE
def ss_cb(word, word_eol, userdata): if len(word) < 2: word.append("help") if word[1].lower() == "list": callCacheList() colourlist = [] for i in cache_list: if (i + ".py") in dlss_list: colourlist.append("\00303" + i + "\017") else: colourlist.append(i) pprefix("List of Scripts: " + ", ".join(colourlist)) elif word[1].lower() == "get": if not len(word) == 3: pprefix("Usage: /SS GET <script[.py]>") return hexchat.EAT_HEXCHAT script = word[2] if script[-3:] == ".py": script = script[:-3] if (script + ".py") in dlss_list: hexchat.hook_timer(0, pyunload_timer, script + ".py") callCacheList() if script in cache_list: dlss_list.append(script + ".py") hexchat.hook_timer(0, download, [script + ".py", True]) else: pprefix("\"{0}\" is not a known script!".format(word[2])) elif word[1].lower() == "startup": if not len(word) == 3: pprefix("Usage: /SS STARTUP <True/False>") return hexchat.EAT_HEXCHAT onstartload = bool(False if word[2].lower() == "false" else True) hexchat.set_pluginpref("ss_onstartload", onstartload) pprefix("On startup load plugins is set to\002\0030" + ("3" if onstartload else "4"), onstartload, "\017") elif word[1].lower() == "update": callCacheList() for i in dlss_list: if i[:-3] in cache_list: hexchat.hook_timer(0, pyunload_timer, i) hexchat.hook_timer(0, download, [i]) else: pprefix("/SS HELP -- Shows this help message") pprefix("/SS LIST -- Lists all SS Scripts you can get") pprefix("/SS GET <script[.py]> -- Downloads and loads <script>") pprefix("/SS STARTUP <True/False> -- Loads scripts on startup") pprefix("/SS UPDATE -- Updates all SS Scripts") pprefix("You have \00304{}\017 API Calls left!".format("~"+str(apicallsleft) if apicallsleft == 60 else apicallsleft)) return hexchat.EAT_HEXCHAT
def privmsg_cb(word, word_eol, msgtype): try: nick = twitch.normalize.nick((word[0][1:].split('!')[0])) chan = word[2] text = word_eol[3] if chan == '#jtv' and nick == 'jtv': hexchat.emit_print('Server Text', text[1:]) return hexchat.EAT_ALL elif nick == 'jtv': if chan[0] != '#': irc.emit_print(None, 'Server Text', text[1:]) return hexchat.EAT_ALL elif "You are banned" in text: chan = twitch.channel.get(chan) if not chan.areWeBanned: chan.areWeBanned = True match = ban_msg_regex.search(text) time = int(match.group(1)) def clear_ban(userdata): chan.areWeBanned = False chan.emit_print('Server Text', "You are (hopefully) no longer banned") hexchat.hook_timer(time * 1000, clear_ban) else: action = word[3][1:] param = word[4:] if action[0] != '_' and hasattr(twitch.jtvmsghandler, action): return getattr(twitch.jtvmsghandler, action)(chan, param) else: #log.warning("Unhandled JTV message: %s" % str(word)) ctxt = twitch.channel.get(chan).getContext() twitch.channel.get(chan).emit_print('Server Text', text[1:]) return hexchat.EAT_ALL elif nick == 'twitchnotify': twitch.channel.get(chan).emit_print('Server Text', text[1:]) return hexchat.EAT_ALL else: twitch.user.get(nick).joinChannel(chan) return hexchat.EAT_NONE except: log.exception("Unhandled exception in twitch.privmsg_cb") return hexchat.EAT_NONE
def startQuizz(self, word=None, word_eol=None, userdata=None): if self.loadQuizz(): if userdata: self.channel.setvalue(str(userdata)) if hexchat.get_info( 'channel')[0] == '#' and not self.channel.str()[0] == '#': self.channel.setvalue(hexchat.get_info('channel')) hexchat.prnt('Starting quizz on channel: ' + self.channel.str() + ' now on ' + hexchat.get_info('channel')) self.SendMessage(BOLD + COLORDEFAULT + 'Le quizz commence' + COLORDEFAULT + ' !') self.mode = 1 self.timer = 0 self.currentQuestion = None hexchat.hook_timer(1000, self.timerHook) self.currentStreak = 0 self.lastWinner = None self.currentStreak = 0 return hexchat.EAT_ALL
def download(script, unload): for site in addon_cache.keys(): if script in addon_cache[site]: script_file = expand_script(script) print('Script: Downloading {}...'.format(script)) try: urllib_request.urlretrieve( build_url(site, type='raw', script=script), script_file) except urllib_error.HTTPError as err: print('Script: Error downloading {} ({})'.format(script, err)) else: print('Script: Download complete, {}...'.format( 'reloading' if unload else 'loading')) if unload: # Updated # Threading causes odd timing issues, using timer fixes it. hexchat.hook_timer(0, unload_cb, script_file) hexchat.hook_timer(0, load_cb, script_file) return print('Script: Could not find {}'.format(script))
def checkStreams(): global firstRun if(firstRun): hexchat.unhook(timerHook) hexchat.hook_timer(300000, checkStreams_cb) firstRun = False channels = hexchat.get_list("channels") realChannels = [] for channel in channels: if(channel.server == "tmi.twitch.tv" and channel.channel[0] == '#'): realChannels.append(channel.channel.strip('#')) for channel in realChannels: obj = loadJSON('https://api.twitch.tv/kraken/streams/' + channel) if (obj["stream"] == None and channel in liveChannels): liveChannels.remove(channel) format(channel.title() + " is not live anymore.") elif (obj["stream"] != None and channel not in liveChannels): liveChannels.append(channel) format(channel.title() + " is live!")
def end_of_names_callback(word, word_eol, userdata): server = hexchat.get_info('server') if not server == TWITCH_IRC_SERVER or len(hexchat.get_list('users')) > 1: return current_channel = hexchat.get_info('channel') url = CHATTERS_URL_TEMPLATE % current_channel[1:] channel_key = server + current_channel hexchat.hook_timer(RETRIEVE_USERLIST_TIMEOUT, retrieve_userlist_update_callback, (url, channel_key)) start_new_thread(retrieve_userlist_update_thread, url, channel_key) channel = None for channel in hexchat.get_list('channels'): if channel.server == server and channel.channel == current_channel: break # This should never happen... assert channel # Initial userlist update, approximately 3 seconds after starting retrieve_userlist_update_thread. hexchat.hook_timer(INITIAL_UPDATE_USERLIST_TIMEOUT, initial_update_userlist_callback, channel) hexchat.hook_timer(UPDATE_USERLIST_TIMEOUT, update_userlist_callback, channel) return hexchat.EAT_NONE
def ScanChanMsg(word, word_eol, userdata): global msg channel = hexchat.get_info("channel") #create the message object msg.strUpdate(word, channel) #increment post count db.incPostCount(msg.getUserName()) #add message to log db.storeLog(msg.getUserName(), msg.rawStr, channel) #if the event occured in an active channel and user isn't banned or abusive if channel.lower() not in db.listChans([True]): print('>>> bot muted in %s' % channel) return hexchat.EAT_NONE elif msg.getUserName().lower() in db.listUserlist([BANNED]): print('>>> user %s is on banlist' % msg.getUserName()) return hexchat.EAT_NONE elif msg.getUserName() in abuseDict and abuseDict[msg.getUserName()] > 5: print('>>> user %s is temporarily banned for bot flood' % msg.getUserName()) return hexchat.EAT_NONE elif msg.getUserName() in nickChangeTimeout: print('>>> user %s is on timeout for nick change' % msg.getUserName()) return hexchat.EAT_NONE else: for function in chanMsgFunctions: result = function(msg, botName, channel, db) # if a function triggered if result: #update abuseDict if abuseDict == {}: hexchat.hook_timer(20000, handleAbuseDict) # only turn on the timer when necessary if msg.getUserName() in abuseDict: abuseDict[msg.getUserName()] += 1 else: abuseDict[msg.getUserName()] = 1 return hexchat.EAT_PLUGIN
def ban_cb(word, word_eol, userdata): if len(word) > 1: mask = get_mask(word[1]) if mask: do_op() if word[0] == 'ban': command = 'mode +b {}'.format(mask) elif word[0] == 'kickban': nick = word[1] chan = hexchat.get_info('channel') message = word_eol[2] if len(word_eol) > 2 else "" command = 'mode +b {}\r\nKICK {} {} :{}'.format(mask, chan, nick, message) elif word[0] == 'quiet': command = 'mode +q {}'.format(mask) hexchat.hook_timer(100, do_command, command) return hexchat.EAT_HEXCHAT else: return hexchat.EAT_NONE
def ban_cb(word, word_eol, userdata): if len(word) > 1: mask = get_mask(word[1]) if mask: do_op() if word[0] == 'ban': command = 'mode +b {}'.format(mask) elif word[0] == 'kickban': nick = word[1] chan = hexchat.get_info('channel') message = word_eol[2] if len(word_eol) > 2 else "" command = 'mode +b {}\r\nKICK {} {} :{}'.format( mask, chan, nick, message) elif word[0] == 'quiet': command = 'mode +q {}'.format(mask) hexchat.hook_timer(100, do_command, command) return hexchat.EAT_HEXCHAT else: return hexchat.EAT_NONE
def choose_callback(word, word_eol, user_data): channel = hexchat.get_info('channel') if (channel in channels ) and not (set(user.nick for user in hexchat.get_list('users')) & other_bots): option = None user = None input = None matches = choose_regex.match(word[1]) if matches: option = 'CHOOSE' user = word[0] input = matches.group(1) else: matches = order_regex.match(word[1]) if matches: option = 'ORDER' user = word[0] input = matches.group(1) if option == 'CHOOSE' or option == 'ORDER': for action in (try_choose, try_order): response = action(option, input) if response != None: context = hexchat.get_context() hexchat.hook_timer( 0, send_response, { 'context': hexchat.get_context(), 'user': user, 'response': response }) break return hexchat.EAT_NONE
def download_cb(word, word_eol, userdata): if isURL(word[1]): hexchat.hook_timer(0, download_timer, word[1]) else: print(__module_shortname__ + "\tNot a valid URL!") return hexchat.EAT_HEXCHAT