def setprefix(message, args): if len(args) > 1: message.message.reply("One argument (prefix) needed!") return None if len(args) == 0: PREFS.set("global", "command_delimiter", "!!/") WolfUtils.CMD_DELIM = "!!/" message.message.reply("Prefix globally reset to default of `!!/`.") for room in SESSION_STORAGE.get("in_rooms"): if room != message.data['room_id']: room.send_message("The bot prefix has been set to `!!/` by " + WolfUtils.getName(message.data['user_id']) + ".") else: PREFS.set("global", "command_delimiter", args[0]) WolfUtils.CMD_DELIM = args[0] message.message.reply("Prefix globally set to `" + args[0] + "`.") for room in SESSION_STORAGE.get("in_rooms"): if room != message.data['room_id']: room.send_message("The bot prefix has been set to `" + args[0] + "` by " + WolfUtils.getName(message.data['user_id']) + ".")
def setprefix(message, args): if len(args) > 1: message.message.reply("One argument (prefix) needed!") return None if len(args) == 0: PREFS.set("global", "reply_delimiter", "%") WolfUtils.REPLY_DELIM = "%" message.message.reply("Prefix reset to default of `%`.") for room in SESSION_STORAGE.get("in_rooms"): if room.id != message.data['room_id']: room.send_message("The reply prefix has been set to `%` by " + WolfUtils.getName(message.data['user_id']) + ".") else: PREFS.set("global", "reply_delimiter", args[0]) WolfUtils.REPLY_DELIM = args[0] message.message.reply("Prefix set to `" + args[0] + "`.") for room in SESSION_STORAGE.get("in_rooms"): if room.id != message.data['room_id']: room.send_message("The reply prefix has been set to `" + args[0] + "` by " + WolfUtils.getName(message.data['user_id']) + ".")
def addfilter(message, args): if len(args) != 1: message.message.reply("One argument (url) needed!") return None FILTER_URL = args[0] PREFS.set(message.data['room_id'], "word_filter_source", FILTER_URL) message.message.reply("Filter Source URL set to " + args[0])
def lockdown(message, args): room = message.data['room_id'] lockdownState = PREFS.get(room, "lockdown", False) if len(args) == 1: if args(0) == "false" or args(0) == "off": if not lockdownState: message.message.reply("Lockdown mode is already disabled.") else: PREFS.set(room, "lockdown", False) message.message.reply( "Room no longer lockdown. Commands may be freely given, and tasks will run once again." ) elif args(0) == "true" or args(0) == "on": if lockdownState: message.message.reply("Lockdown mode is already enabled.") else: PREFS.set(room, "lockdown", True) message.message.reply( "Room under lockdown. Only admins may give commands to the bot, and tasks will not run." ) return if not lockdownState: PREFS.set(room, "lockdown", True) message.message.reply( "Room under lockdown. Only admins may give commands to the bot, and tasks will not run." ) else: PREFS.set(room, "lockdown", False) message.message.reply( "Room no longer under lockdown. Commands may be freely given, and tasks will run once again." )
def setprefix(message, args): if len(args) > 1: message.message.reply("One argument (prefix) needed!") return None if len(args) == 0: PREFS.set("command_delimiter", "!!/") WolfUtils.CMD_DELIM = "!!/" message.message.reply("Prefix reset to default of `!!/`.") else: PREFS.set("command_delimiter", args[0]) WolfUtils.CMD_DELIM = args[0] message.message.reply("Prefix set to `" + args[0] + "`.")
def setprefix(message, args): if len(args) > 1: message.message.reply("One argument (prefix) needed!") return None if len(args) == 0: PREFS.set("reply_delimiter", "%") WolfUtils.REPLY_DELIM = "%" message.message.reply("Prefix reset to default of `%`.") else: PREFS.set("reply_delimiter", args[0]) WolfUtils.REPLY_DELIM = args[0] message.message.reply("Prefix set to `" + args[0] + "`.")
def reload(message, args): if len(args) > 1: message.message.reply( "Zero or one argument (reloadtype (prefs)) needed!") return None if len(args) == 0: reloadType = "all" else: reloadType = args[0] if reloadType == "prefs": PREFS.load() message.message.reply("**Preference reload complete.**")
def joinRoom(message, args): if (len(args) == 0): message.message.reply("Needs one argument: room_id") return rid = args[0] if PREFS.get(rid, "banned", False) == True: message.message.reply( "The bot has been banned from joining that room!") return PREFS.set(rid, "active", True) message.message.reply("The bot has joined the given room.") restart("1", "1")
def execute(self, message, commandName, args): # Make sure the user isn't blacklisted from executing commands if str(message.data['user_id']) in PREFS.get("blacklist", {}): return None # Verify that the command exists. try: command = self._commands[commandName.lower()] except KeyError: message.message.reply("The command " + WolfUtils.CMD_DELIM + commandName + " does not exist.") return None # Make sure the user is a superuser for superuser commands if command["permset"].get("superuserNeeded", False): if not WolfUtils.isDeveloper(message.data['user_id']): message.message.reply( "This command needs to be run by a Superuser.") return None # Make sure the user is privileged enough to run this command if command["permset"].get("adminNeeded", False): if not WolfUtils.isAdmin(message.data['user_id']): message.message.reply( "This command needs to be run by a Bot Admin.") return None command["function"](message, args)
def unblacklistUser(message, args): if len(args) != 1: message.message.reply("Needs one argument (user_id)") return None user_to_unbl = args[0] current_blacklist = PREFS.get("blacklist", []) if user_to_unbl in current_blacklist: current_blacklist.remove(user_to_unbl) PREFS.set("blacklist", current_blacklist) message.message.reply( WolfUtils.getName(user_to_unbl) + " (ID " + user_to_unbl + ") is now permitted to use WolfBot commands.") else: message.message.reply("User is already blacklisted!")
def addadmin(message, args): if len(args) == 0 or len(args) > 1: message.message.reply("One argument (user_id) needed!") return None currentAdmins = PREFS.get("admins", []) if args[0] not in currentAdmins: currentAdmins.append(args[0]) PREFS.set("admins", currentAdmins) message.message.reply( WolfUtils.getName(args[0]) + " (ID " + args[0] + ") added as bot admin.") return None else: message.message.reply("User is already a declared admin!") return None
def isAdmin(user_id): if str(user_id) in PREFS.get("admins", []): return True elif isDeveloper(user_id): return True else: return isRoomOwner(user_id)
def addshortcut(message, args): if len(args) != 2: message.message.reply("Two arguments (name, url) needed!") return None currentShortcuts = PREFS.get("post-shortcuts", {}) if args[0] in currentShortcuts: message.message.reply(args[0] + " is already a shortcut! Can't add.") return None args[1] = args[1].decode('ascii', 'ignore') currentShortcuts[args[0]] = args[1] PREFS.set("post-shortcuts", currentShortcuts) message.message.reply("From now on, the shortcut `" + args[0] + "` will return [this link](" + args[1] + ").")
def addadmin(message, args): if len(args) == 0 or len(args) > 1: message.message.reply("One argument (user_id) needed!") return None currentAdmins = PREFS.get("admins", []) if args[0] in currentAdmins: currentAdmins.remove(args[0]) PREFS.set("admins", currentAdmins) message.message.reply( WolfUtils.getName(args[0]) + " removed from bot admin.") return None else: message.message.reply( "User is not a declared admin! (This command may not be used to remove inherited rights)" ) return None
def runTasks(self): for room in PREFS.all(): if room == "global": continue # Skip room if we're in lockdown mode. if PREFS.get(room, "lockdown", False): continue for task in self._tasks: if str(task) in PREFS.get(room, "enabled_tasks", []): taskEntry = self._tasks[task] if (int(time.time()) - taskEntry["lastRun"]) >= taskEntry["runDelay"]: # print("Running task " + task) taskEntry["function"](room) taskEntry["lastRun"] = calendar.timegm(time.gmtime())
def execute(self, message, commandName, args): room = str(message.data['room_id']) # Make sure the user isn't blacklisted from executing commands in that room if str(message.data['user_id']) in PREFS.get(room, "user_blacklist", []): return None # Make sure the user isn't blacklisted from executing commands globally if str(message.data['user_id']) in PREFS.get("global", "user_blacklist", []): return None # Verify that the command exists. try: command = self._commands[commandName.lower()] except KeyError: message.message.reply("The command " + WolfUtils.CMD_DELIM + commandName + " does not exist.") return None # Make sure the command isn't disabled in the room at hand. if commandName in PREFS.get(room, "disabled_commands", []): return None # Make sure the user is a superuser for superuser commands if command["permset"].get("superuserNeeded", False): if not WolfUtils.isDeveloper(message.data['user_id']): message.message.reply( "This command needs to be run by a Superuser.") return None # Make sure the user is privileged enough to run this command if command["permset"].get("adminNeeded", False): if not WolfUtils.isAdmin(message.data['user_id'], room): message.message.reply( "This command needs to be run by a Bot Admin.") return None # Make sure the room isn't on admin lockdown if (PREFS.get(room, "lockdown") and (not WolfUtils.isAdmin(message.data['user_id'], room))): return None command["function"](message, args)
def setroom(message, args): if len(args) != 1: message.message.reply("Needs one argument (room_id)") return None newRoom = str(args[0]) PREFS.set("chat_id", args[0]) newRoomName = json.load( urllib2.urlopen("https://chat.stackexchange.com/rooms/thumbs/" + newRoom))["name"] message.message.reply( "The bot will reload soon, and will use the new room upon restart. The bot will be moved to [" + newRoomName + "](https://chat.stackexchange.com/rooms/" + newRoom + ").") time.sleep(3) os.execl(sys.executable, sys.executable, *sys.argv)
def taskRunFilter(room): global LAST_PULL_TIME FILTER_URL = PREFS.get(room.id, "word_filter_source") WORD_BLACKLIST = PREFS.get(room.id, "word_filter_blacklist", []) WORD_WHITELIST = PREFS.get(room.data, "word_filter_whitelist", []) if FILTER_URL is None: print("[E] Unable to run task! Filter URL is empty.") return None results = [] post_timestamps = [] data = feedparser.parse(FILTER_URL).entries for entry in data: post_timestamps.append(seTimeToUnixTime(entry['published'])) if seTimeToUnixTime(entry['published']) > LAST_PULL_TIME: for word in WORD_BLACKLIST: if word.lower() in entry['summary'].lower() and not any( oword.lower() in entry['summary'].lower() for oword in WORD_WHITELIST): results.append({ "trigger": word, "title": entry['title'], "url": entry['id'] }) try: LAST_PULL_TIME = max(post_timestamps) except ValueError: LAST_PULL_TIME = LAST_PULL_TIME if len(results) == 1: room.send_message("[**" + SESSION_STORAGE.get("bot_username") + "**] Found filtered post, matches word `" + results[0]["trigger"] + \ "`: [" + results[0]["title"] + "](" + results[0]["url"] + ")") elif len(results) > 1: s = "" for result in results: s += "[" + result["title"] + "](" + result[ "url"] + "), matches word `" + result["trigger"] + "`\n" room.send_message("[**" + SESSION_STORAGE.get("bot_username") + "**] Found multiple filtered posts:\n" + s)
def blacklistUser(message, args): if len(args) != 1: message.message.reply("Needs one argument (user_id)") return None user_to_bl = args[0] current_blacklist = PREFS.get("blacklist", []) if user_to_bl not in current_blacklist: if not WolfUtils.isAdmin(user_to_bl): current_blacklist.append(user_to_bl) PREFS.set("blacklist", current_blacklist) message.message.reply( WolfUtils.getName(user_to_bl) + " (ID " + user_to_bl + ") is no longer permitted to use WolfBot commands.") else: message.message.reply( "Admins and Superusers may not be blacklisted.") else: message.message.reply("User is already blacklisted!")
def reload(message, args): if len(args) > 1: message.message.reply( "Zero or one argument (reloadtype (prefs, commands, all)) needed!") return None if len(args) == 0: reloadType = "all" else: reloadType = args[0] if reloadType == "prefs": PREFS.load() message.message.reply("**Preference reload complete.**") elif reloadType == "plugins": reload(WolfCore) message.message.reply("**Plugin reload complete.**") elif reloadType == "all": PREFS.load() os.execl(sys.executable, sys.executable, *sys.argv) message.message.reply("**Full reload complete.**")
def listshortcuts(message, args): currentShortcuts = PREFS.get("post-shortcuts", None) if currentShortcuts is None: message.message.reply("No shortcuts are present in the system.") return None; qMessage = "I have the following shortcuts in my registry: \n\n" for s in currentShortcuts: qMessage += "`" + s + "`: " + currentShortcuts[s] message.message.reply(qMessage)
def remfilter(message, args): if len(args) < 2: message.message.reply("Two arguments [bl|wl] (words) needed!") return None if args[0] == "bl": WORD_LIST = WORD_BLACKLIST LIST_NAME = "blacklist" elif args[0] == "wl": WORD_LIST = WORD_WHITELIST LIST_NAME = "whitelist" else: message.message.reply("First argument must be either `bl` (modify blacklist) or `wl` (modify whitelist)!") return None if len(args) == 2: word = args[1] if word in WORD_LIST: WORD_LIST.remove(word) PREFS.set("word_filter_" + LIST_NAME, WORD_LIST) message.message.reply("`" + word + "` has been removed from the filter " + LIST_NAME + ".") else: message.message.reply("`" + word + "` is not in the filter " + LIST_NAME + "!") return None else: merge_fail = [] for word in args: if word in WORD_LIST: WORD_LIST.remove(word) else: merge_fail.append(word) PREFS.set("word_filter_" + LIST_NAME, WORD_BLACKLIST) if len(merge_fail) == 0: message.message.reply("All words were removed from the " + LIST_NAME + "successfully.") elif len(merge_fail) == len(args): message.message.reply("No words could be removed from the " + LIST_NAME + " (not there?).") else: message.message.reply(str(len(merge_fail)) + " words could not be removed from the the " + LIST_NAME + " (not there?):\n" + " ".join(merge_fail))
def addfilter(message, args): if len(args) < 2: message.message.reply("Two arguments [bl|wl] (words) needed!") return None if args[0] == "bl": WORD_LIST = WORD_BLACKLIST LIST_NAME = "blacklist" elif args[0] == "wl": WORD_LIST = WORD_WHITELIST LIST_NAME = "whitelist" else: message.message.reply("First argument must be either bl or wl!") return None if len(args) == 2: word = args[1] if word not in WORD_LIST: WORD_LIST.append(word) PREFS.set("word_filter_" + LIST_NAME, WORD_LIST) message.message.reply("`" + word + "` has been added to the filter " + LIST_NAME + ".") else: message.message.reply("`" + word + "` is already in the filter" + LIST_NAME + "!") return None else: merge_fail = [] for word in args[1:]: if word not in WORD_LIST: WORD_LIST.append(word) else: merge_fail.append(word) PREFS.set("word_filter_" + LIST_NAME, WORD_LIST) if len(merge_fail) == 0: message.message.reply("All words were added to " + LIST_NAME + " successfully.") elif len(merge_fail) == len(args): message.message.reply("No words could be added to the " + LIST_NAME + " (already there?).") else: message.message.reply(str(len(merge_fail)) + " words could not be added to the " + LIST_NAME + " (already there?):\n" + " ".join(merge_fail))
def execListeners(self, message): eventId = int(message.data['event_type']) room = message.data['room_id'] # Handle potential lockdown if (PREFS.get(room, "lockdown") and (not WolfUtils.isAdmin(message.data['user_id'], room))): return None for listenerName in self._listeners: listener = self._listeners[listenerName] if listener["eventId"] == eventId: listener["function"](message)
def getshortcut(message, args): if len(args) != 1: message.message.reply("Hey, silly! I need a shortcut to check!") return None currentShortcuts = PREFS.get("post-shortcuts", {}) if args[0] not in currentShortcuts: message.message.reply(args[0] + " is not a shortcut. Go away.") return None soup = BeautifulSoup(urllib2.urlopen(currentShortcuts[args[0]])) message.message.reply("Hey! I've got this link for you: [" + soup.title.string + "](" + currentShortcuts[args[0]] +")")
def delshortcut(message, args): if len(args) != 1: message.message.reply("Two arguments (name) needed!") return None currentShortcuts = PREFS.get("post-shortcuts", {}) if args[0] not in currentShortcuts: message.message.reply(args[0] + " is not a shortcut. Can't remove.") return None del currentShortcuts[args[0]] message.message.reply("From now on, the shortcut `" + args[0] + "` will no longer resolve to anything.")
def deltask(message, args): currentTasks = PREFS.get(message.data['room_id'], "enabled_tasks", []) if (len(args) == 0): message.message.reply("Expected one argument: task_name") return if (args(0) not in currentTasks): message.message.reply("This task is not listed as enabled!") else: currentTasks.remove(args(0)) message.message.reply( "The task `" + args(0) + "` is now disabled for this room. Note that it may still need configuration." )
def leaveRoom(message, args): if len(args) == 0: mode = "normal" else: mode = args[0] if mode == "purge": PREFS.purgeChat(message.data['room_id']) restart("1", "1") elif mode == "ban": PREFS.purgeChat(message.data['room_id']) PREFS.set(message.data['room_id'], "banned", True) restart("1", "1") elif mode == "normal": PREFS.set(message.data['room_id'], "active", False) restart("1", "1") else: message.message.reply( "Command expects a mode: normal, purge, ban (No argument implies normal)" )
def takeRoot(message, args): if len(args) != 1: message.message.reply("Needs one argument (captain_key)") return None currentDevs = PREFS.get("devs", []) if currentDevs == []: if args[0].lower() == PREFS.get("captain_key").lower(): currentDevs.append(str(message.data['user_id'])) PREFS.set("devs", currentDevs) message.message.reply("https://i.imgur.com/2oNMYD3.jpg") PREFS.delete("captain_key") PREFS.save() else: message.message.reply( "You are by far the worst captain I've ever heard of.") else: message.message.reply( "You are by far the worst captain I've ever heard of.")
def on_message(message, client): if not PREFS.get(message.data['room_id'], "active", False): return try: LISTENERS.execListeners(message) if not isinstance(message, chatexchange6.events.MessagePosted): return content = HTMLParser.HTMLParser().unescape(message.content) user = message.user if WolfUtils.isCommand(content): cmd = WolfUtils.parseCommand(content)[0] args = WolfUtils.parseCommand(content)[1] print("Got command " + cmd + " with args " + str(args)) COMMANDS.execute(message, cmd, args) #message.message.reply("User " + user.name + " sent command " + command + " with args " + " ".join(args)) except Exception: print("Ow! Ran into a problem. Log follows:") traceback.print_exc() message.message.reply("Uh oh! I ran into a problem :(. See the console for more details.")