def __init__(self): self.room = None self.client = None self.privileged_users = [] self.owners = [] self.owner_name = "" self.chatbot_name = "" self.enabled = True self.suspended_until = -1 self.running = True self.site = "" self.owner_ids = [] self.privileged_user_ids = [] self.save_subdirs = ['main'] self.modules = MetaModule(ModuleManifest.module_file_names, self, 'all') try: SaveIO.set_subdirs(self.save_subdirs) except DuplicateDirectoryException as e: if "-q" not in sys.argv: print("[Chatbot] WARNING: there are modules with the same save directory: " + str(e)) SaveIO.create_if_not_exists(SaveIO.data_dir) del self.save_subdirs duplicates = self.get_duplicate_commands() if duplicates and "-q" not in sys.argv: print('[Chatbot] WARNING: there are commands with the same name: ' + str(duplicates))
def on_bot_load(bot): global command_banned_users global banned_users bot.command = command_ban_deco(bot.command) bot.on_event = ban_deco(bot.on_event, bot) command_banned_users = SaveIO.load(save_subdir, 'command_banned_users') banned_users = SaveIO.load(save_subdir, 'banned_users')
def __init__(self): self.room = None self.client = None self.privileged_users = [] self.owners = [] self.owner_name = "" self.chatbot_name = "" self.enabled = True self.running = True self.site = "" self.owner_ids = [] self.privileged_user_ids = [] self.save_subdirs = ['main'] self.modules = MetaModule(ModuleManifest.module_file_names, self, 'all') try: SaveIO.set_subdirs(self.save_subdirs) except DuplicateDirectoryException as e: if "-q" not in sys.argv: print( "[Chatbot] WARNING: there are modules with the same save directory: " + str(e)) SaveIO.create_if_not_exists(SaveIO.data_dir) del self.save_subdirs duplicates = self.get_duplicate_commands() if duplicates and "-q" not in sys.argv: print( '[Chatbot] WARNING: there are commands with the same name: ' + str(duplicates))
def unstar(cmd, bot, args, msg, event): global Stars is_admin = False for i in bot.owners: if event.user.id == i["stackexchange.com"]: is_admin = True else: continue if len(args) < 1: return "Not enough arguments." id_ = args[0] user = event.user.name try: id_ = int(id_) except: return "Invalid arguments." message = bot.client.get_message(id_) if not message.starred_by_you: if id_ in Stars: del Stars[id_] return "The stars on that message have been removed by a moderator. I had previously starred it, and I can't star it again." return "This message isn't starred." if not Stars[id_] == user and not is_admin: return "You cannot unstar a message someone else starred." message.star(False) del Stars[id_] SaveIO.save(Stars, save_subdir, 'Stars_Data') return "Message unstarred."
def on_bot_load(bot): global Points global Stars global Pins Points = SaveIO.load(save_subdir, 'Points_Data') Stars = SaveIO.load(save_subdir, 'Stars_Data') Pins = SaveIO.load(save_subdir, 'Pins_Data')
def unpin(cmd, bot, args, msg, event): global Pins is_admin = False for i in bot.owners: if event.user.id == i["stackexchange.com"]: is_admin = True else: continue if len(args) < 1: return "Not enough arguments." id_ = args[0] user = event.user.name try: id_ = int(id_) except: return "Invalid arguments." message = bot.client.get_message(id_) if not message.pinned: if id_ in Pins: del Pins[id_] return "The pins on that message have been removed by a moderator. I had previously pinned it, and I can't do so again." return "This message isn't pinned." if not Pins[id_] == user and not is_admin: return "You cannot unpin a message someone else pinned." message.pin(False) del Pins[id_] SaveIO.save(Pins, save_subdir, 'Pins_Data') return "Message unpinned."
def on_bot_load(bot): global data global auth_handler data = SaveIO.load(save_subdir, "keys_data") if data == {}: defaults['consumer_secret'] = get_secret() data = defaults SaveIO.save(data, save_subdir, "keys_data") auth_handler = tweepy.OAuthHandler(data['consumer_key'], data['consumer_secret']) if "access_token" in data and "access_token_secret" in data: auth_handler.set_access_token(data['access_token'], data['access_token_secret']) else: try: redirect_url = auth_handler.get_authorization_url() except tweepy.TweepError: print("[oauth] [tweepy] FATAL: Failed to get authorization URL.") sys.exit(503) webbrowser.open_new_tab(redirect_url) verifier = input("[oauth] Type the verification code from Twitter: ") try: access_token, access_token_secret = auth_handler.get_access_token(verifier) except tweepy.TweepError: print("[oauth] [tweepy] FATAL: Could not fetch access token with provided verifier code.") sys.exit(504) data['access_token'], data['access_token_secret'] = access_token, access_token_secret SaveIO.save(data, save_subdir, "keys_data") auth_handler.set_access_token(access_token, access_token_secret)
def command_unban(cmd, bot, args, msg, event): global banned_users global command_banned_users if len(args) == 0: return "Not enough arguments" try: banned_user = int(args[0]) except ValueError: return "Invalid arguments." try: user_name = bot.client.get_user(banned_user).name.replace(" ", "") except: return "Could not fetch user; please check whether the user exists." if len(args) > 1: command = args[1] if command in command_banned_users and banned_user in command_banned_users[command]: command_banned_users[command].remove(banned_user) if len(command_banned_users[command]) == 0: del command_banned_users[command] SaveIO.save(command_banned_users, save_subdir, "command_banned_users") return "User @%s has been unbanned from using $PREFIX%s." % (user_name, command) else: return "Not banned" else: if bot.site not in banned_users: return "Not banned." if banned_user not in banned_users[bot.site]: return "Not banned." banned_users[bot.site].remove(banned_user) SaveIO.save(banned_users, save_subdir, "banned_users") return "User @%s has been unbanned." % user_name
def on_bot_load(bot): global command_banned_users global banned_users bot.command = command_ban_deco(bot.command) bot.on_event = ban_deco(bot.on_event, bot) command_banned_users = SaveIO.load(save_subdir, "command_banned_users") banned_users = SaveIO.load(save_subdir, "banned_users")
def command_unban(cmd, bot, args, msg, event): global banned_users global command_banned_users if len(args) == 0: return "Not enough arguments" try: banned_user = int(args[0]) except ValueError: return "Invalid arguments." try: user_name = bot.client.get_user(banned_user).name.replace(" ", "") except: return "Could not fetch user; please check whether the user exists." if len(args) > 1: command = args[1] if command in command_banned_users and banned_user in command_banned_users[ command]: command_banned_users[command].remove(banned_user) if len(command_banned_users[command]) == 0: del command_banned_users[command] SaveIO.save(command_banned_users, save_subdir, 'command_banned_users') return "User @%s has been unbanned from using $PREFIX%s." % ( user_name, command) else: return "Not banned" else: if bot.site not in banned_users: return "Not banned." if banned_user not in banned_users[bot.site]: return "Not banned." banned_users[bot.site].remove(banned_user) SaveIO.save(banned_users, save_subdir, 'banned_users') return "User @%s has been unbanned." % user_name
def command_link(cmd, bot, args, msg, event): if len(args) != 2: return "2 arguments expected, %i given." % len(args) if links_contain((args[0].replace("_", " "), args[1].replace("_", " "))): return "Link is already added." Data.links.append((args[0].replace("_", " "), args[1].replace("_", " "))) SaveIO.save(Data.links, save_subdir, "linkedWords") return "Link added."
def command_joingame(cmd, bot, args, msg, event): if event.user.id in Data.game_banned[bot.site]: return "You're game banned and can't join." if event.user.id in Data.joined_game[bot.site]: return "You're already in the game." Data.joined_game[bot.site].append(event.user.id) SaveIO.save(Data.joined_game, save_subdir, "usersInGame") return "You joined the Word Association Game! Run `>>quitgame` to leave."
def remove_link(item0, item1): for i, link in enumerate(Data.links): lowercase_link = (link[0].lower(), link[1].lower()) if item0.lower() in lowercase_link and item1.lower() in lowercase_link: Data.links.pop(i) SaveIO.save(Data.links, save_subdir, "linkedWords") return "Link removed." return "No link found."
def give_medal(cmd, bot, args, msg, event): global Medals if len(args) < 1: return "Not enough arguments." username = args[0] if username not in Medals: Medals[username] = 0 Medals[username] += 1 SaveIO.save(Medals, save_subdir, "Medals_Data") return str.format("Given {0} a genius medal. Total: {1}", username, Medals[username])
def on_bot_load(bot): waiting_time = SaveIO.load(save_subdir, "waitingtime") if len(waiting_time) == 0: waiting_time = 20 else: waiting_time = waiting_time[0] Data.waiting_time = waiting_time Data.links = SaveIO.load(save_subdir, "linkedWords") if Data.links == {}: Data.links = [] SaveIO.save(Data.links, save_subdir, "linkedWords") Data.link_explanations = SaveIO.load(save_subdir, "linkExplanations") if Data.link_explanations == {}: Data.link_explanations = [] SaveIO.save(Data.link_explanations, save_subdir, "linkExplanations") Data.game_banned = SaveIO.load(save_subdir, "gameBannedUsers") Data.spell_manager.load() if Data.game_banned == {}: Data.game_banned = {"stackexchange.com": [], "meta.stackexchange.com": [], "stackoverflow.com": []} Data.joined_game = SaveIO.load(save_subdir, "usersInGame") if Data.joined_game == {} or Data.joined_game is None: Data.joined_game = {"stackexchange.com": [], "meta.stackexchange.com": [], "stackoverflow.com": []} Data.spell_manager.c = bot.client t = Thread(target=scheduled_empty_queue, args=(bot,)) t.start()
def removelinkexplanation(link): to_remove = [] ret = False for exp in Data.link_explanations: l = exp[0] if (l[0] == link[0] and l[1] == link[1]) or (l[0] == link[1] and l[1] == link[0]): to_remove.append(exp) ret = True for r in to_remove: Data.link_explanations.remove(r) SaveIO.save(Data.link_explanations, save_subdir, "linkExplanations") return ret
def command_addlinkexplanation(cmd, bot, args, msg, event): if len(args) != 3: return "3 arguments expected, %i given" % len(args) w1 = args[0].replace("_", " ").lower() w2 = args[1].replace("_", " ").lower() removelinkexplanation((w1, w2)) # remove any older explanations if not links_contain((w1, w2)): return "That link does not exist." if re.compile(r"[^a-zA-Z0-9_%*/:.#()\[\]?&=-]").search(args[2]): return "Sorry, your explanation can only contain the chars `a-zA-Z_*%/:.#()[]-`." Data.link_explanations.append(((w1, w2), args[2])) SaveIO.save(Data.link_explanations, save_subdir, "linkExplanations") return "Explanation added."
def command_time(cmd, bot, args, msg, event): if len(args) > 0: try: new_time = int(args[0]) if new_time > 600: return "Waiting time cannot be greater than 10 minutes (= 600 seconds)." if new_time > -1: Data.waiting_time = new_time SaveIO.save([Data.waiting_time], save_subdir, "waitingtime") return "Waiting time set to %s %s." % (args[0], ("seconds" if new_time != 1 else "second")) else: return "Given argument has to be a positive integer." except ValueError: return "Given argument is not a valid integer." else: return "Command does not have enough arguments."
def command_gameban(cmd, bot, args, msg, event): if len(args) != 1: return "1 argument expected." if not args[0].isdigit(): return "Invalid arguments." uid = int(args[0]) try: user_name = bot.client.get_user(uid).name.replace(" ", "") except: return "Could not fetch user; please check whether the user exists." if uid not in Data.game_banned[bot.site]: Data.game_banned[bot.site].append(uid) SaveIO.save(Data.game_banned, save_subdir, "gameBannedUsers") else: return "User %s has already been banned from playing the game." return "User @%s has been banned from playing the game." % user_name
def get_random_line(file): file = SaveIO.load(save_subdir,file,'txt') list_lines = file.splitlines() n_lines = len(list_lines) if n_lines>0: message = list_lines[randint(0,n_lines-1)] else: message = "I am at loss for words. Contact my owner" return message
def on_bot_stop(bot): global Points global Stars global Pins SaveIO.save(Points, save_subdir, 'Points_Data') SaveIO.save(Stars, save_subdir, 'Stars_Data') SaveIO.save(Pins, save_subdir, 'Pins_Data')
def pin(cmd, bot, args, msg, event): global Pins if len(args) < 1: return "Not enough arguments." id_ = args[0] user = event.user.name try: id_ = int(id_) except: return "Invalid arguments." message = bot.client.get_message(id_) if not message.pinned and id_ in Pins: return "This message cannot be pinned because a moderator has removed votes." if message.pinned or id_ in Pins: return "This message has already been pinned." if message.owner.name == 'KarmaBot': return "I can't pin my own messages. This is a design decision because of a bug in chat." result = change_points(user, -500, True) if not result: return "You don't have enough points to pin a message." message.pin() Pins[id_] = user SaveIO.save(Pins, save_subdir, 'Pins_Data') return "Message pinned. You have been charged 500 points."
def star(cmd, bot, args, msg, event): global Stars if len(args) < 1: return "Not enough arguments." id_ = args[0] user = event.user.name try: id_ = int(id_) except: return "Invalid arguments." message = bot.client.get_message(id_) if not message.starred_by_you and id_ in Stars: return "This message cannot be starred because a moderator has removed votes." if message.starred_by_you or id_ in Stars: return "This message has already been starred by someone else." if message.owner.name == "KarmaBot": return "I can't star my own messages." result = change_points(user, -100, True) if not result: return "You don't have enough points to pin a message." message.star() Stars[id_] = user SaveIO.save(Stars, save_subdir, 'Stars_Data') return "Message starred. You have been charged 100 points."
def change_points(user, amount, is_admin=False): global Points if user.lower() not in Points: Points[user.lower()] = 200 if not is_admin: if Points[user.lower()] + amount < 0: return False Points[user.lower()] += amount try: SaveIO.save(Points, save_subdir, 'Points_Data') return "Changed points for " + user + " by " + str(amount) + ". New total: " + str(Points[user.lower()]) except: SaveIO.save(Points, save_subdir, 'Points_Data') return "An error occurred, but the points transfer *has* taken place." else: Points[user.lower()] += amount try: SaveIO.save(Points, save_subdir, 'Points_Data') return "Changed points for " + user + " by " + str(amount) + ". New total: " + str(Points[user.lower()]) except: SaveIO.save(Points, save_subdir, 'Points_Data') return "An error occurred, but the points transfer *has* taken place."
def get_token(): return SaveIO.load(save_subdir, "SphereEngineKey", "txt")
def on_bot_stop(bot): global data SaveIO.save(data, save_subdir, "keys_data")
def save(self): SaveIO.save(self.earnedSpells, "shadowsden", "earnedSpells")
def load(self): self.earnedSpells = SaveIO.load("shadowsden", "earnedSpells")
def on_bot_stop(bot): global Medals SaveIO.save(Medals, save_subdir, "Medals_Data")
def on_bot_load(bot): global Medals Medals = SaveIO.load(save_subdir, "Medals_Data")
def command_quitgame(cmd, bot, args, msg, event): if event.user.id not in Data.joined_game[bot.site]: return "You didn't join the game." Data.joined_game[bot.site].remove(event.user.id) SaveIO.save(Data.joined_game, save_subdir, "usersInGame") return "You left the Word Association Game. Run `>>joingame` to join again."
def put_tweet(tweet_id, dt, tweet_text): tweets = SaveIO.load(save_subdir, 'tweets') tweets[tweet_id] = [dt, tweet_text] SaveIO.save(tweets, save_subdir, 'tweets')