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 = PREFS.get(message.data['room_id'], "word_filter_blacklist", []) LIST_NAME = "blacklist" elif args[0] == "wl": WORD_LIST = PREFS.get(message.data['room_id'], "word_filter_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(message.data['room_id'], "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(message.data['room_id'], "word_filter_" + LIST_NAME, WORD_LIST) 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 = PREFS.get(message.data['room_id'], "word_filter_blacklist", []) LIST_NAME = "blacklist" elif args[0] == "wl": WORD_LIST = PREFS.get(message.data['room_id'], "word_filter_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(message.data['room_id'], "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(message.data['room_id'], "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 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 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 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 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 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 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 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 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 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 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 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 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] 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 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 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 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.")
#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.") print("WolfBot loading... please wait.") try: input = raw_input except NameError: pass # Handle setup first. __USER__ = PREFS.get("global", "username", None) __PASS__ = PREFS.get("global", "password", None) if __USER__ is None: __USER__ = input("Please enter the e-mail to use: ") PREFS.set("global", "username", __USER__) __PASS__ = getpass.getpass("Please enter the password to use: ") PREFS.set("global", "password", __PASS__) PREFS.save() if PREFS.get("global", "devs", []) == []: ckey = "%06x" % random.randint(0, 0xFFFFFF) PREFS.set("global", "captain_key", ckey) print("Please run this command to gain superuser privileges (single-use!):\n\n " + WolfUtils.CMD_DELIM + "iamthecaptainnow " + ckey.upper() + "\n\n")
def isDeveloper(user_id): if (str(user_id) in PREFS.get("devs", [])): return True else: return isSEModerator(user_id)
# -*- coding: utf-8 -*- from ChatExchange6 import chatexchange6 as chatexchange6 import json import shlex import sys import requests from urlparse import urlparse from urllib import urlopen from datetime import datetime import json from WolfPrefs import PREFS CMD_DELIM = PREFS.get("command_delimiter") REPLY_DELIM = PREFS.get("reply_delimiter") ROOM_ID = PREFS.get("chat_id") # Determine if a text is a command # Arg `message`: The text to check for commandiness def isCommand(message): return message.startswith(CMD_DELIM) def parseCommand(cmd): def newSplit(value): lex = shlex.shlex(value) lex.quotes = '"' lex.whitespace_split = True
def getfilter(message, args): message.message.reply("Words on the filter blacklist:\n" + ", ".join(PREFS.get(message.data['room_id'], "word_filter_blacklist", [])) + \ "\n\nWords on the filter whitelist:\n" + ", ".join(PREFS.get(message.data['room_id'], "word_filter_whitelist", [])))
traceback.print_exc() message.message.reply( "Uh oh! I ran into a problem :(. See the console for more details." ) #message.message.reply("User " + user.name + " sent command " + command + " with args " + " ".join(args)) print("WolfBot loading... please wait.") try: input = raw_input except NameError: pass # Handle setup first. __USER__ = PREFS.get("username", None) __PASS__ = PREFS.get("password", None) __CHATID__ = PREFS.get("chat_id", None) if __USER__ is None: __USER__ = input("Please enter the e-mail to use: ") PREFS.set("username", __USER__) __PASS__ = getpass.getpass("Please enter the password to use: ") PREFS.set("password", __PASS__) PREFS.save() if __CHATID__ is None: __CHATID__ = input("Please enter the Chat to join: ") PREFS.set("chat_id", __CHATID__) PREFS.save()
# -*- coding: utf-8 -*- from ChatExchange6 import chatexchange6 as chatexchange6 import json import shlex import sys import requests from urlparse import urlparse from urllib import urlopen from datetime import datetime import json from WolfPrefs import PREFS CMD_DELIM = PREFS.get("global", "command_delimiter", "!!/") REPLY_DELIM = PREFS.get("global", "reply_delimiter", "%") # Determine if a text is a command # Arg `message`: The text to check for commandiness def isCommand(message): return message.startswith(CMD_DELIM) def parseCommand(cmd): def newSplit(value): lex = shlex.shlex(value) lex.quotes = '"' lex.whitespace_split = True lex.commenters = '' return list(lex)
# -*- coding: utf-8 -*- import WolfUtils import feedparser import time import calendar import urllib2 from datetime import datetime from bs4 import BeautifulSoup from WolfPlugin import registerCommand, registerTask from WolfPrefs import PREFS WORD_BLACKLIST = PREFS.get("word_filter_blacklist", []) WORD_WHITELIST = PREFS.get("word_filter_whitelist", []) FILTER_URL = PREFS.get("word_filter_source") LAST_PULL_TIME = int(time.time()) @registerCommand("s", "Get a shortcutted post", "", {}) 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]]))