def upsert(self, player_object, save=False): try: self.players_dict[player_object.steamid] = player_object if save: self.save(player_object) except Exception as e: logger.error(e)
def check_if_player_is_on_whitelist(self, player_object=None): try: if player_object is None: player_object = self.bot.players.get(self.player_steamid) else: called_by_trigger = True self.bot = self try: player_object = self.bot.players.load(player_object.steamid) except KeyError as e: logger.error("{} encountered the error '{}'".format( player_object.name, e)) if self.bot.whitelist.is_active(): if not self.bot.whitelist.player_is_allowed(player_object): logger.info( "kicked player {} for not being on the whitelist".format( player_object.name)) self.tn.say("{} has been kicked. This is VIP Only!".format( player_object.name), color=self.bot.chat_colors['alert']) self.tn.kick( player_object, "You are not on our whitelist. Visit chrani.net/chrani-bot to find out what that means and if / what options are available to you!" ) except Exception as e: logger.error("{} encountered the error '{}'".format( player_object.name, e)) pass
def fix_players_legs(self): """Fixes the legs of the player issuing this action Keyword arguments: self -- the bot expected bot command: /fix my legs please example: /fix my legs please notes: does not check if the player is injured at all """ try: player_object = self.bot.players.get(self.player_steamid) self.tn.debuffplayer(player_object, "brokenLeg") self.tn.debuffplayer(player_object, "sprainedLeg") self.tn.send_message_to_player(player_object, "your legs have been taken care of ^^", color=self.bot.chat_colors['success']) except Exception as e: logger.error(e) pass
def player_is_outside_boundary(self): try: player_object = self.bot.players.get(self.player_steamid) try: location_object = self.bot.locations.get('system', "lobby") except KeyError: return False if player_object.authenticated is not True: if not location_object.player_is_inside_boundary(player_object): if self.tn.teleportplayer(player_object, location_object): player_object.set_coordinates(location_object) self.bot.players.upsert(player_object) logger.info("{} has been ported to the lobby!".format( player_object.name)) self.tn.send_message_to_player( player_object, "You have been ported to the lobby! Authenticate with /password <password>", color=self.bot.chat_colors['alert']) self.tn.send_message_to_player( player_object, "see https://chrani.net/chrani-bot for more information!", color=self.bot.chat_colors['warning']) if self.tn.muteplayerchat(player_object, True): self.tn.send_message_to_player( player_object, "Your chat has been disabled!", color=self.bot.chat_colors['warning']) except Exception as e: logger.error(e) pass
def password(self, command): try: try: location_object = self.bot.locations.get('system', "lobby") except KeyError: return False player_object = self.bot.players.get(self.player_steamid) p = re.search(r"password\s(\w+)$", command) if p: pwd = p.group(1) if pwd in self.bot.passwords.values(): try: location_object = self.bot.locations.get( player_object.steamid, 'spawn') # if the spawn is enabled, do port the player and disable it. if location_object.enabled is True: self.tn.send_message_to_player( player_object, "You have been ported back to your original spawn!", color=self.bot.chat_colors['success']) if self.tn.teleportplayer(player_object, location_object): location_object.enabled = False self.bot.locations.upsert(location_object, save=True) else: return False except KeyError: return False except Exception as e: logger.error(e) pass
def set_up_lobby_inner_perimeter(self): try: player_object = self.bot.players.get(self.player_steamid) try: location_object = self.bot.locations.get('system', 'lobby') except KeyError: self.tn.send_message_to_player( player_object, "you need to set up a lobby first silly: /set up lobby", color=self.bot.chat_colors['warning']) return False if location_object.set_warning_boundary(player_object): self.bot.locations.upsert(location_object, save=True) self.tn.send_message_to_player( player_object, "The lobby-warnings will be issued from this point on", color=self.bot.chat_colors['success']) else: self.tn.send_message_to_player( player_object, "Is this inside the lobby perimeter?", color=self.bot.chat_colors['warning']) except Exception as e: logger.error(e) pass
def set_up_lobby_teleport(self): try: player_object = self.bot.players.get(self.player_steamid) try: location_object = self.bot.locations.get('system', 'lobby') except KeyError: self.tn.send_message_to_player( player_object, "coming from the wrong end... set up the lobby first!", color=self.bot.chat_colors['warning']) return False if location_object.set_teleport_coordinates(player_object): self.bot.locations.upsert(location_object, save=True) self.tn.send_message_to_player( player_object, "the teleport for {} has been set up!".format('lobby'), color=self.bot.chat_colors['success']) else: self.tn.send_message_to_player( player_object, "your position seems to be outside of the location", color=self.bot.chat_colors['warning']) except Exception as e: logger.error(e) pass
def set_up_lobby_outer_perimeter(self): try: player_object = self.bot.players.get(self.player_steamid) try: location_object = self.bot.locations.get('system', 'lobby') except KeyError: self.tn.send_message_to_player( player_object, "you need to set up a lobby first silly: /set up lobby", color=self.bot.chat_colors['warning']) return False if location_object.set_radius(player_object): self.bot.locations.upsert(location_object, save=True) self.tn.send_message_to_player( player_object, "The lobby ends here and spans {} meters ^^".format( int(location_object.radius * 2)), color=self.bot.chat_colors['success']) else: self.tn.send_message_to_player( player_object, "Your given range ({}) seems to be invalid ^^".format( int(location_object.radius * 2)), color=self.bot.chat_colors['warning']) except Exception as e: logger.error(e) pass
def run_demo(): """ Starts a command-line based demo request loop for debugging. """ logger.info('Starting request loop') previous_pattern = None while True: try: text = input('User input: ') request = Request(text=text, previous_pattern=previous_pattern, mood=0.0, affection=0.0, bot_gender=Gender.FEMALE, bot_name='Lana', bot_birthdate=date(1995, 10, 5), bot_favorite_color='grün', father_name='Georg', father_age=49, mother_name='Agathe', mother_age=47) response = handle_request(request) print('Response: ', response.text) previous_pattern = response.pattern except KeyboardInterrupt: # Interrupt requested by user logger.info('Keyboard interrupt detected, aborting request loop') return except Exception as ex: logger.error('{}: {}'.format(type(ex).__name__, str(ex))) continue
def set_up_home(self): try: player_object = self.bot.players.get(self.player_steamid) # if you know what you are doing, yuo can circumvent all checks and set up a location by dictionary location_dict = dict( name='My Home', identifier='home', owner=player_object.steamid, pos_x=player_object.pos_x, pos_y=player_object.pos_y, pos_z=player_object.pos_z, tele_x=player_object.pos_x, tele_y=player_object.pos_y, tele_z=player_object.pos_z, description="{}\'s home".format(player_object.name), messages_dict={ "leaving_core": "you are leaving {}\'s private area".format(player_object.name), "leaving_boundary": "you are leaving {}\'s estate".format(player_object.name), "entering_boundary": "you are entering {}\'s estate".format(player_object.name), "entering_core": "you are entering {}\'s private area".format(player_object.name) }, shape='sphere', radius=10, warning_boundary=6, list_of_players_inside=[player_object.steamid] ) location_object = Location(**location_dict) self.bot.locations.upsert(location_object, save=True) self.tn.say("{} has decided to settle down!".format(player_object.name), color=self.bot.chat_colors['background']) self.tn.send_message_to_player(player_object, "Home is where your hat is!", color=self.bot.chat_colors['success']) except Exception as e: logger.error(e) pass
def set_up_lobby(self): try: player_object = self.bot.players.get(self.player_steamid) location_object = Location() location_object.set_owner('system') name = 'The Lobby' location_object.set_name(name) identifier = location_object.set_identifier('lobby') location_object.set_description('The \"there is no escape\" Lobby') location_object.set_shape("sphere") location_object.set_coordinates(player_object) # location_object.set_region([player_object.region]) messages_dict = location_object.get_messages_dict() messages_dict["entering_core"] = None messages_dict["leaving_core"] = None messages_dict["entering_boundary"] = None messages_dict["leaving_boundary"] = None location_object.set_messages(messages_dict) location_object.set_list_of_players_inside([player_object.steamid]) self.bot.locations.upsert(location_object, save=True) self.tn.send_message_to_player(player_object, "You have set up a lobby", color=self.bot.chat_colors['success']) self.tn.send_message_to_player( player_object, "Set up the perimeter with /set lobby outer perimeter, while standing on the edge of it." .format(player_object.name), color=self.bot.chat_colors['warning']) except Exception as e: logger.error(e) pass
def check_if_player_has_url_name(self, player_object=None): try: if player_object is None: player_object = self.bot.players.get(self.player_steamid) else: called_by_trigger = True self.bot = self if not self.bot.whitelist.player_is_allowed(player_object): p = re.search( r"[-A-Z0-9+&@#/%?=~_|!:,.;]{3,}\.[A-Z0-9+&@#/%=~_|]{2,3}$", player_object.name, re.IGNORECASE) if p: logger.info( "kicked player {} for having an URL in the name.".format( player_object.name)) self.tn.say( "{} has been kicked. we do not allow url-names!".format( player_object.steamid), color=self.bot.chat_colors['alert']) self.tn.kick( player_object, "We do not allow urls in names. Visit chrani.net/chrani-bot to find out what that means and if / what options are available to you!" ) except Exception as e: logger.error("{} encountered the error '{}'".format( player_object.name, e)) pass
def on_player_join(self): try: player_object = self.bot.players.get(self.player_steamid) except Exception as e: logger.error(e) raise KeyError self.tn.send_message_to_player(player_object, "{} is ready and listening (v{})".format(self.bot.bot_name, self.bot.bot_version), color=self.bot.chat_colors['info']) try: location = self.bot.locations.get(player_object.steamid, 'spawn') except KeyError: location_dict = dict( identifier='spawn', name='Place of Birth', owner=player_object.steamid, shape='point', radius=None, region=None ) location_object = Location(**location_dict) location_object.set_coordinates(player_object) try: self.bot.locations.upsert(location_object, save=True) except: return False self.tn.send_message_to_player(player_object, "your place of origin has been recorded ^^", color=self.bot.chat_colors['background']) return True
def list_online_players(self): """Lists all currently online players Keyword arguments: self -- the bot expected bot command: /online players example: /online players notes: Will list players and show their entityId """ try: active_players_dict = self.bot.players.players_dict players_to_list = [] for steamid, player_object in active_players_dict.iteritems(): players_to_list.append(player_object) for player_object in players_to_list: self.tn.send_message_to_player( player_object, "{} ([ffffff]{}[-]) / authenticated: {}".format( player_object.name, player_object.entityid, str(player_object.authenticated)), color=self.bot.chat_colors['success']) except Exception as e: logger.error(e) pass
def obliterate_player(self): """Kicks the player and removes all bot-accessible datafor the player issuing this action Keyword arguments: self -- the bot expected bot command: /obliterate me example: /obliterate me notes: it will delete all locations and all playerdata plus the whitelist entry. Currently it does NOT remove references, like if the player is inside a location while obliterated, the location file will not be purged. YET. """ try: player_object = self.bot.players.get(self.player_steamid) player_object.switch_off("suicide") self.tn.kick(player_object, "You wanted it! Time to be born again!!") location_objects_dict = self.bot.locations.get(player_object.steamid) locations_to_remove = [] for name, location_object in location_objects_dict.iteritems(): locations_to_remove.append(location_object) for location_object in locations_to_remove: self.bot.locations.remove(player_object.steamid, location_object.identifier) self.bot.players.remove(player_object) self.bot.whitelist.remove(player_object) except Exception as e: logger.error(e) pass
def set_up_location_name(self, command): try: player_object = self.bot.players.get(self.player_steamid) p = re.search( r"edit\slocation\sname\s(?P<identifier>[\W\w\s]{1,19})\s=\s(?P<name>[\W\w\s]{1,19})$", command) if p: identifier = p.group("identifier") name = p.group("name") try: location_object = self.bot.locations.get( player_object.steamid, identifier) location_object.set_name(name) messages_dict = location_object.get_messages_dict() messages_dict[ "entering_core"] = "entering {}'s core area ".format(name) messages_dict[ "leaving_core"] = "leaving {}'s core area ".format(name) messages_dict["entering_boundary"] = "entering {} ".format( name) messages_dict["leaving_boundary"] = "leaving {} ".format(name) location_object.set_messages(messages_dict) self.bot.locations.upsert(location_object, save=True) self.tn.send_message_to_player( player_object, "You called your location {}".format(name), color=self.bot.chat_colors['background']) except KeyError: self.tn.send_message_to_player( player_object, "You can not name that which you do not have!!", color=self.bot.chat_colors['warning']) except Exception as e: logger.error(e) pass
def set_up_location_teleport(self, command): try: player_object = self.bot.players.get(self.player_steamid) p = re.search( r"edit\slocation\steleport\s(?P<identifier>[\W\w\s]{1,19})$", command) if p: identifier = p.group("identifier") try: location_object = self.bot.locations.get( player_object.steamid, identifier) except KeyError: self.tn.send_message_to_player( player_object, "coming from the wrong end... set up the location first!", color=self.bot.chat_colors['warning']) return False if location_object.set_teleport_coordinates(player_object): self.bot.locations.upsert(location_object, save=True) self.tn.send_message_to_player( player_object, "the teleport for {} has been set up!".format(identifier), color=self.bot.chat_colors['success']) else: self.tn.send_message_to_player( player_object, "your position seems to be outside the location", color=self.bot.chat_colors['warning']) except Exception as e: logger.error(e) pass
def remove_location(self, command): try: player_object = self.bot.players.get(self.player_steamid) p = re.search(r"remove\slocation\s([\w\s]{1,19})$", command) if p: identifier = p.group(1) if identifier in ["teleport", "lobby", "spawn", "home", "death"]: self.tn.send_message_to_player( player_object, "{} is a reserved name. Aborted!.".format(identifier), color=self.bot.chat_colors['warning']) raise KeyError try: location_object = self.bot.locations.get( player_object.steamid, identifier) self.bot.locations.remove(player_object.steamid, identifier) self.tn.say("{} deleted location {}".format( player_object.name, identifier), color=self.bot.chat_colors['background']) except KeyError: self.tn.send_message_to_player( player_object, "I have never heard of a location called {}".format( identifier), color=self.bot.chat_colors['warning']) except Exception as e: logger.error(e) pass
def apply_first_aid(self): """Applies the 'firstAidLarge' buff to the player issuing this action Keyword arguments: self -- the bot expected bot command: /heal me up scotty example: /heal me up scotty notes: does not check if the player is injured at all """ try: player_object = self.bot.players.get(self.player_steamid) self.tn.buffplayer(player_object, "firstAidLarge") self.tn.send_message_to_player( player_object, "feel the power flowing through you!! ^^", color=self.bot.chat_colors['success']) except Exception as e: logger.error(e) pass
def on_player_death(self): try: player_object = self.bot.players.get(self.player_steamid) except Exception as e: logger.error(e) raise KeyError try: location = self.bot.locations.get(player_object.steamid, 'death') except KeyError: location_dict = dict(identifier='death', name='Place of Death', owner=player_object.steamid, shape='point', radius=None, region=None) location_object = Location(**location_dict) location_object.set_coordinates(player_object) try: self.bot.locations.upsert(location_object, save=True) except: return False self.tn.send_message_to_player( player_object, "your place of death has been recorded ^^", color=self.bot.chat_colors['background']) return True
def set_up_home_name(self, command): try: player_object = self.bot.players.get(self.player_steamid) p = re.search(r"edit\shome\sname\s([\W\w\s]{1,19})$", command) if p: description = p.group(1) try: location_object = self.bot.locations.get(player_object.steamid, "home") except KeyError: self.tn.send_message_to_player(player_object, "{} can not name that which you do not have!".format(player_object.name), color=self.bot.chat_colors['warning']) raise KeyError except Exception as e: logger.error(e) return False location_object.set_description(description) messages_dict = { "leaving_core": "you are leaving {}\'s core".format(description), "leaving_boundary": "you are leaving {}".format(description), "entering_boundary": "you are entering {}".format(description), "entering_core": "you are entering {}\'s core".format(description) } location_object.set_messages(messages_dict) self.bot.locations.upsert(location_object, save=True) self.tn.send_message_to_player(player_object, "Your home is called {} now \o/".format(location_object.description), color=self.bot.chat_colors['background']) return True
def shutdown_bot(self): """Shuts down the bot Keyword arguments: self -- the bot expected bot command: /shut down the matrix example: /shut down the matrix notes: Together with a cronjob starting the bot every minute, this can be used for restarting it from within the game """ try: player_object = self.bot.players.get(self.player_steamid) self.tn.send_message_to_player(player_object, "bot is shutting down...", color=self.bot.chat_colors['success']) self.bot.shutdown_bot() except Exception as e: logger.error(e) pass
def remove_player_from_permission_group(self, command): """Removes player from permission-group Keyword arguments: self -- the bot command -- the entire chatline (bot command) expected bot command: /remove player <steamid/entityid> from group <group_name> example: /remove player 76561198040658370 from group admin notes: the group must exist """ try: player_object = self.bot.players.get(self.player_steamid) except Exception as e: logger.error(e) raise KeyError p = re.search( r"remove\splayer\s(?P<steamid>([0-9]{17}))|(?P<entityid>[0-9]+)\sfrom\sgroup\s(?P<group_name>\w+)$", command) if p: steamid_to_modify = p.group("steamid") entityid_to_modify = p.group("entityid") if steamid_to_modify is None: steamid_to_modify = self.bot.players.entityid_to_steamid( entityid_to_modify) if steamid_to_modify is False: raise KeyError group = str(p.group("group_name")) if group not in self.bot.permission_levels_list: self.tn.send_message_to_player( player_object, "the group {} does not exist!".format(group), color=self.bot.chat_colors['success']) return False try: player_object_to_modify = self.bot.players.get(steamid_to_modify) player_object_to_modify.remove_permission_level(group) self.tn.send_message_to_player( player_object, "{} has been removed from the group {}".format( player_object.name, group), color=self.bot.chat_colors['success']) except Exception: self.tn.send_message_to_player( player_object, "could not find a player with steamid {}".format( steamid_to_modify), color=self.bot.chat_colors['warning']) return self.bot.players.upsert(player_object_to_modify, save=True)
def player_crossed_boundary(self): try: player_object = self.bot.players.get(self.player_steamid) for location_owner_steamid in self.bot.locations.locations_dict: """ go through each location and check if the player is inside locations are stored on a player-basis so we can have multiple 'home' and 'spawn' location and whatnot so we have to loop through every player_location_dict to get to the actual locations """ for location_name, location_object in self.bot.locations.locations_dict[ location_owner_steamid].iteritems(): """ different status-conditions for a player None = do nothing is inside has entered has entered core has left core has left """ get_player_status = location_object.get_player_status( player_object) if get_player_status is None: pass if get_player_status == "is inside": pass if get_player_status == "has left": if location_object.messages_dict[ "leaving_boundary"] is not None: self.tn.send_message_to_player( player_object, location_object.messages_dict["leaving_boundary"], color=self.bot.chat_colors['background']) self.bot.locations.upsert(location_object, save=True) if get_player_status == "has entered": if location_object.messages_dict[ "entering_boundary"] is not None: self.tn.send_message_to_player( player_object, location_object.messages_dict["entering_boundary"], color=self.bot.chat_colors['warning']) self.bot.locations.upsert(location_object, save=True) if get_player_status == "has left core": if location_object.messages_dict[ "leaving_core"] is not None: self.tn.send_message_to_player( player_object, location_object.messages_dict["leaving_core"], color=self.bot.chat_colors['warning']) self.bot.locations.upsert(location_object, save=True) if get_player_status == "has entered core": if location_object.messages_dict[ "entering_core"] is not None: self.tn.send_message_to_player( player_object, location_object.messages_dict["entering_core"], color=self.bot.chat_colors['warning']) self.bot.locations.upsert(location_object, save=True) except Exception as e: logger.error(e) pass
def activate_whitelist(self): try: self.bot.whitelist.activate() self.tn.say("Whitelist is in effect! Feeling safer already :)", color=self.bot.chat_colors['alert']) except Exception as e: logger.error(e) pass
def deactivate_whitelist(self): try: self.bot.whitelist.deactivate() self.tn.say( "Whitelist has been disabled. We are feeling adventureous :)", color=self.bot.chat_colors['alert']) except Exception as e: logger.error(e) pass
def remove(self, player_object): try: filename = "{}/{}_{}.{}".format(self.root, self.prefix, player_object.steamid, self.extension) if os.path.exists(filename): try: os.remove(filename) except OSError, e: logger.error("Error: {} - {}.".format(e.filename, e.strerror)) else:
def record_time_of_last_activity(self): try: player_object = self.bot.players.get(self.player_steamid) if player_object.is_responsive is True: player_object.last_seen = time() self.bot.players.upsert(player_object, save=True) except Exception as e: logger.error(e) pass
def polling(self): try: apihelper.proxy = proxies() logger.info('Bot is polling') self.bot.polling() except (ConnectionError, RemoteDisconnected, ConnectTimeout, ReadTimeout): self.bot.stop_polling() logger.error('Caught exception, restarting bot') self.polling()
def check_ip_country(self, player_object=None): try: if self.bot.settings_dict['ipinfo.io_password'] is None: return if player_object is None: player_object = self.bot.players.get(self.player_steamid) else: # the scope changes when called by the bots main-loop called_by_trigger = True self.bot = self # check if we already know the country code and check against whitelist and banned list users_country = player_object.get_country_code() if self.bot.whitelist.player_is_allowed(player_object) or ( users_country is not None and users_country not in self.bot.banned_countries_list): return False try: if users_country is None: f = urllib.urlopen( "https://ipinfo.io/" + player_object.ip + "/country?token=" + str(self.bot.settings_dict['ipinfo.io_password'])) users_country = f.read().rstrip() except Exception: logger.debug( "something went wrong in fetching the ipinfo dataset for player {}" .format(player_object.name)) try: player_object.set_country_code(users_country) self.bot.players.upsert(player_object, save=True) except Exception as e: logger.error("{} encountered the error '{}'".format( player_object.name, e)) if users_country in self.bot.banned_countries_list: if self.tn.kick( player_object, "Your IP seems to be from a blacklisted country. Visit chrani.net/chrani-bot to find out what that means and if / what options are available to you!" ): logger.info("kicked player {} for being from {}".format( player_object.name, users_country)) self.tn.say( "{} has been kicked. Blacklisted Country ({})!".format( player_object.name, users_country), color=self.bot.chat_colors['alert']) except Exception as e: logger.error("{} encountered the error '{}'".format( player_object.name, e)) pass
def start_qq( no_gui=False, new_user=False, debug=False, vpath="./v.jpg", smart_qq_refer="http://d1.web2.qq.com/proxy.html?v=20030916001&callback=1&id=2", cookie_file="cookie.data", plugin_setting={ "plugin_root": "./plugins", "plugins": [ "pluginmanage", "test1" ], "timers": [ "timer_weather" ] }, dbhandler='sqlite:///message-record.db', ): bot = QQBot(vpath, smart_qq_refer, cookie_file) # update the modules and enbale utf-8 decoding. reload(sys) sys.setdefaultencoding("utf-8") # set the mode for logger. if debug: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) # login bot.login(no_gui) # initialze the handler handler = SuperHandler(dbhandle=dbhandler, workers=5) handler.update_group_list(bot) logger.info("Update group list...") # dbhandler = DBHandler() # initialize the plugin manager plmanager = PluginManager(plugin_setting["plugin_root"]) timermanager = PluginManager(plugin_setting["plugin_root"]) # load the plugins for plugin_name in plugin_setting["plugins"]: # plmanager.add_plugin(plugin_name) try: plmanager.add_plugin(plugin_name) except Exception, e: print(e) logger.error("Failed to load plugin: %s" % plugin_name)
plmanager = PluginManager(plugin_setting["plugin_root"]) timermanager = PluginManager(plugin_setting["plugin_root"]) # load the plugins for plugin_name in plugin_setting["plugins"]: # plmanager.add_plugin(plugin_name) try: plmanager.add_plugin(plugin_name) except Exception, e: print(e) logger.error("Failed to load plugin: %s" % plugin_name) for timer_name in plugin_setting["timers"]: try: timermanager.add_plugin(timer_name) except Exception, e: print(e) logger.error("Failed to load plugin: %s" % plugin_name) # register the plugins to the message handlers for (name, plugin) in plmanager.plugins.items(): handler.add_handler(name, plugin) timers = {} for (name, plugin) in timermanager.plugins.items(): t = PluginTimer(plugin, args=(bot, ), sleep=2) t.start() timers[name] = t logger.info("plugin available: %s" % plmanager.plugins.keys()) # main loop, query new messages and handle them. while True: # query the plugins to be updated. try: