def func(self): """returns the list of online characters""" count_accounts = (SESSIONS.account_count()) self.caller.msg("[%s] Through the fog you see:" % self.key) session_list = SESSIONS.get_sessions() table = evtable.EvTable(border='none') table.add_row('Character', 'On for', 'Idle', 'Location') for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time puppet = session.get_puppet() location = puppet.location.key if puppet and puppet.location else 'Nothingness' table.add_row(puppet.key if puppet else 'None', utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1), location) table.reformat_column(0, width=25, align='l') table.reformat_column(1, width=12, align='l') table.reformat_column(2, width=7, align='l') table.reformat_column(3, width=25, align='l') is_one = count_accounts == 1 string = '%s' % 'A' if is_one else str(count_accounts) string += ' single ' if is_one else ' unique ' plural = ' is' if is_one else 's are' string += 'account%s logged in.' % plural self.caller.msg(table) self.caller.msg(string)
def update_weather(self, *args, **kwargs): """ Called by the tickerhandler at regular intervals. Even so, we only update 20% of the time, picking a random weather message when we do. The tickerhandler requires that this hook accepts any arguments and keyword arguments (hence the *args, **kwargs even though we don't actually use them in this example) """ slow_room = True empty_room = True session_list = SESSIONS.get_sessions() for session in session_list: character = session.get_puppet() if not session.logged_in or not character or character.location != self: continue empty_room = False if session.cmd_last_visible > self.ndb.weather_time: slow_room = False break if empty_room: return if slow_room: self.attempt_weather_update( 0.05) # only attempt update 5% of the time else: self.attempt_weather_update(0.20)
def func(self): """returns the list of online characters""" count_accounts = (SESSIONS.account_count()) self.caller.msg('[%s] Through the fog you see:' % self.key) session_list = SESSIONS.get_sessions() table = evtable.EvTable(border='none') table.add_row('Character', 'On for', 'Idle', 'Location') for session in session_list: puppet = session.get_puppet() if not session.logged_in or not puppet: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time location = puppet.location.key if puppet and puppet.location else 'Nothingness' table.add_row(puppet.key if puppet else 'None', utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1), location) table.reformat_column(0, width=25, align='l') table.reformat_column(1, width=12, align='l') table.reformat_column(2, width=7, align='l') table.reformat_column(3, width=25, align='l') is_one = count_accounts == 1 string = '%s' % 'A' if is_one else str(count_accounts) string += ' single ' if is_one else ' unique ' plural = ' is' if is_one else 's are' string += 'account%s logged in.' % plural self.caller.msg(table) self.caller.msg(string)
def func(self): """ Get all connected players by polling session. """ player = self.player session_list = SESSIONS.get_sessions() session_list = sorted(session_list, key=lambda o: o.player.key) if self.cmdstring == "doing": show_session_data = False else: show_session_data = player.check_permstring( "Immortals") or player.check_permstring("Wizards") nplayers = (SESSIONS.player_count()) if show_session_data: # privileged info table = prettytable.PrettyTable([ "{wPlayer Name", "{wOn for", "{wIdle", "{wPuppeting", "{wRoom", "{wCmds", "{wProtocol", "{wHost" ]) for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time player = session.get_player() puppet = session.get_puppet() location = puppet.location.key if puppet else "None" table.add_row([ utils.crop(player.name, width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1), utils.crop(puppet.key if puppet else "None", width=25), utils.crop(location, width=25), session.cmd_total, session.protocol_key, isinstance(session.address, tuple) and session.address[0] or session.address ]) else: # unprivileged table = prettytable.PrettyTable( ["{wPlayer name", "{wOn for", "{wIdle"]) for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time player = session.get_player() table.add_row([ utils.crop(player.key, width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1) ]) isone = nplayers == 1 string = "{wPlayers:{n\n%s\n%s unique account%s logged in." % ( table, "One" if isone else nplayers, "" if isone else "s") self.msg(string)
def update_weather(self, *args, **kwargs): """ Called by the tickerhandler at regular intervals. Even so, we only update 20% of the time, picking a random weather message when we do. The tickerhandler requires that this hook accepts any arguments and keyword arguments (hence the *args, **kwargs even though we don't actually use them in this example) """ slow_room = True empty_room = True session_list = SESSIONS.get_sessions() for session in session_list: character = session.get_puppet() if not session.logged_in or not character or character.location != self: continue empty_room = False if session.cmd_last_visible > self.ndb.weather_time: slow_room = False break if empty_room: return if slow_room: self.attempt_weather_update(0.05) # only attempt update 5% of the time else: self.attempt_weather_update(0.20)
def func(self): "Implementing the function" caller = self.caller args = self.args if not args: caller.msg("Usage: @boot[/switches] <player> [:reason]") return if ':' in args: args, reason = [a.strip() for a in args.split(':', 1)] else: args, reason = args, "" boot_list = [] if 'sid' in self.switches: # Boot a particular session id. sessions = SESSIONS.get_sessions(True) for sess in sessions: # Find the session with the matching session id. if sess.sessid == int(args): boot_list.append(sess) break else: # Boot by player object pobj = search.player_search(args) if not pobj: caller.msg("Player %s was not found." % args) return pobj = pobj[0] if not pobj.access(caller, 'boot'): string = "You don't have the permission to boot %s." % ( pobj.key, ) caller.msg(string) return # we have a bootable object with a connected user matches = SESSIONS.sessions_from_player(pobj) for match in matches: boot_list.append(match) if not boot_list: caller.msg( "No matching sessions found. The Player does not seem to be online." ) return # Carry out the booting of the sessions in the boot list. feedback = None if not 'quiet' in self.switches: feedback = "You have been disconnected by %s.\n" % caller.name if reason: feedback += "\nReason given: %s" % reason for session in boot_list: session.msg(feedback) session.player.disconnect_session_from_player(session)
def func(self): """ Get all connected players by polling session. """ player = self.player session_list = SESSIONS.get_sessions() session_list = sorted(session_list, key=lambda o: o.player.key) if self.cmdstring == "doing": show_session_data = False else: show_session_data = player.check_permstring("Immortals") or player.check_permstring("Wizards") nplayers = (SESSIONS.player_count()) if show_session_data: # privileged info table = prettytable.PrettyTable(["{wИмя игрока", "{wВ игре", "{wIdle", "{wУправляет", "{wКомната", "{wCmds", "{wПротокол", "{wХост"]) for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time player = session.get_player() puppet = session.get_puppet() location = puppet.location.key if puppet and puppet.location else "None" table.add_row([utils.crop(player.name, width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1), utils.crop(puppet.key if puppet else "None", width=25), utils.crop(location, width=25), session.cmd_total, session.protocol_key, isinstance(session.address, tuple) and session.address[0] or session.address]) else: # unprivileged table = prettytable.PrettyTable(["{wИмя игрока", "{wВ игре", "{wIdle"]) for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time player = session.get_player() table.add_row([utils.crop(player.key, width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1)]) isone = nplayers == 1 string = "{wИгроков:{n\n%s\n%s уникальных аккаунтов%s залогинено." % (table, "Один" if isone else nplayers, "" if isone else "") self.msg(string)
def func(self): """ Get all connected players by polling session. """ player = self.player session_list = SESSIONS.get_sessions() session_list = sorted(session_list, key=lambda o: o.player.key) if self.cmdstring == "doing": show_session_data = False else: show_session_data = player.check_permstring("Immortals") or player.check_permstring("Wizards") nplayers = (SESSIONS.player_count()) if show_session_data: # privileged info table = prettytable.PrettyTable(["{wPlayer Name", "{wOn for", "{wIdle", "{wPuppeting", "{wRoom", "{wCmds", "{wProtocol", "{wHost"]) for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time player = session.get_player() puppet = session.get_puppet() location = puppet.location.key if puppet else "None" table.add_row([utils.crop(player.name, width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1), utils.crop(puppet.key if puppet else "None", width=25), utils.crop(location, width=25), session.cmd_total, session.protocol_key, isinstance(session.address, tuple) and session.address[0] or session.address]) else: # unprivileged table = prettytable.PrettyTable(["{wPlayer name", "{wOn for", "{wIdle"]) for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time player = session.get_player() table.add_row([utils.crop(player.key, width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1)]) isone = nplayers == 1 string = "{wPlayers:{n\n%s\n%s unique account%s logged in." % (table, "One" if isone else nplayers, "" if isone else "s") self.msg(string)
def func(self): """ Get all connected accounts by polling session. """ account = self.account session_list = SESSIONS.get_sessions() session_list = sorted(session_list, key=lambda o: o.account.key) if self.cmdstring == "doing": show_session_data = False else: show_session_data = account.check_permstring("Developer") or account.check_permstring("Admins") naccounts = (SESSIONS.account_count()) if show_session_data: # privileged info table = evtable.EvTable("|wAccount Name", "|wOn for", "|wIdle", "|wPuppeting", "|wRoom", "|wCmds", "|wProtocol", "|wHost") for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time account = session.get_account() puppet = session.get_puppet() location = puppet.location.key if puppet and puppet.location else "None" table.add_row(utils.crop(account.name, width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1), utils.crop(puppet.key if puppet else "None", width=25), utils.crop(location, width=25), session.cmd_total, session.protocol_key, isinstance(session.address, tuple) and session.address[0] or session.address) else: # unprivileged table = evtable.EvTable("|wAccount name", "|wOn for", "|wIdle") for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time account = session.get_account() table.add_row(utils.crop(account.key, width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1)) is_one = naccounts == 1 self.msg("|wAccounts:|n\n%s\n%s unique account%s logged in." % (table, "One" if is_one else naccounts, "" if is_one else "s"))
def func(self): """ Get all connected accounts by polling session. """ account = self.account session_list = SESSIONS.get_sessions() session_list = sorted(session_list, key=lambda o: o.account.key) if self.cmdstring == "doing": show_session_data = False else: show_session_data = account.check_permstring( "Developer") or account.check_permstring("Admins") naccounts = SESSIONS.account_count() if show_session_data: # privileged info table = self.styled_table("|wAccount Name", "|wOn for", "|wIdle", "|wPuppeting", "|wRoom", "|wCmds", "|wProtocol", "|wHost") for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time account = session.get_account() puppet = session.get_puppet() location = puppet.location.key if puppet and puppet.location else "None" table.add_row( utils.crop(account.get_display_name(account), width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1), utils.crop( puppet.get_display_name(account) if puppet else "None", width=25), utils.crop(location, width=25), session.cmd_total, session.protocol_key, isinstance(session.address, tuple) and session.address[0] or session.address) else: # unprivileged table = self.styled_table("|wAccount name", "|wOn for", "|wIdle") for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time account = session.get_account() table.add_row( utils.crop(account.get_display_name(account), width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1)) is_one = naccounts == 1 self.msg( "|wAccounts:|n\n%s\n%s unique account%s logged in." % (table, "One" if is_one else naccounts, "" if is_one else "s"))
def func(self): """Implementing the function""" caller = self.caller args = self.args if not args: caller.msg("Usage: @boot[/switches] <player> [:reason]") return if ':' in args: args, reason = [a.strip() for a in args.split(':', 1)] else: args, reason = args, "" boot_list = [] if 'sid' in self.switches: # Boot a particular session id. sessions = SESSIONS.get_sessions(True) for sess in sessions: # Find the session with the matching session id. if sess.sessid == int(args): boot_list.append(sess) break else: # Boot by player object pobj = search.player_search(args) if not pobj: caller.msg("Player %s was not found." % args) return pobj = pobj[0] if not pobj.access(caller, 'boot'): string = "You don't have the permission to boot %s." % (pobj.key, ) caller.msg(string) return # we have a bootable object with a connected user matches = SESSIONS.sessions_from_player(pobj) for match in matches: boot_list.append(match) if not boot_list: caller.msg("No matching sessions found. The Player does not seem to be online.") return # Carry out the booting of the sessions in the boot list. feedback = None if 'quiet' not in self.switches: feedback = "You have been disconnected by %s.\n" % caller.name if reason: feedback += "\nReason given: %s" % reason for session in boot_list: session.msg(feedback) session.player.disconnect_session_from_player(session)
def func(self): session_list = SESSIONS.get_sessions() table = evtable.EvTable(" |w|uName:|n", "|w|uIdle:|n", "|w|uConn:|n", "|w|uClearance:|n", table=None, border=None, width=78) for session in session_list: player = session.get_account() idle = time.time() - session.cmd_last_visible conn = time.time() - session.conn_time clearance = session.get_puppet().db.clearance flag = None if player.locks.check_lockstring(player, "dummy:perm(Admin)"): flag = "|y!|n" elif player.locks.check_lockstring(player, "dummy:perm(Builder)"): flag = "|g&|n" elif player.locks.check_lockstring(player, "dummy:perm(Helper)"): flag = "|r$|n" else: flag = " " table.add_row( flag + utils.crop(player.name), utils.time_format(idle, 0), utils.time_format(conn, 0), "|{}{}|n".format(clearance_color(CLEARANCE.get(clearance)), CLEARANCE.get(clearance))) table.reformat_column(0, width=24) table.reformat_column(1, width=12) table.reformat_column(2, width=12) table.reformat_column(3, width=30) self.caller.msg("|w_|n" * 78) title = ansi.ANSIString("|[002|w|u{}|n".format(settings.SERVERNAME)) self.caller.msg(title.center(78, '^').replace('^', "|[002|w_|n")) self.caller.msg(table) self.caller.msg("|w_|n" * 78) self.caller.msg("Total Connected: %s" % SESSIONS.account_count()) whotable = evtable.EvTable("", "", "", header=False, border=None) whotable.reformat_column(0, width=26) whotable.reformat_column(1, width=26) whotable.reformat_column(2, width=26) whotable.add_row("|y!|n - Administrators", "|g&|n - Storytellers", "|r$|n - Player Helpers") self.caller.msg(whotable) self.caller.msg("|w_|n" * 78 + "\n")
def func(self): # Build a list of touples using the same logic as the cmdWHO # from evennia itself. account = self.account session_list = SESSIONS.get_sessions() who_list = [] for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time account = session.get_account() puppet = session.get_puppet() location = puppet.location.key if puppet and puppet.location else "None" sex = puppet.db.sex if puppet.db.sex else "None" who_list.append( [account.name, sex, delta_cmd, delta_conn, location]) self.caller.msg(header("+who")) output = evtable.EvTable("Name", "Sex", "Idle", "Online", "Location", width=MAX_WIDTH, align="l", valign="t", border="none") output.reformat_column(0, width=18) output.reformat_column(1, width=5, align="c") output.reformat_column(2, width=8) output.reformat_column(3, width=8) output.reformat_column(4, width=(MAX_WIDTH - 39)) for who in who_list: output.add_row("|W" + str(who[0]) + "|n", csex(who[1], short=True), "|W" + timestring(who[2], short=True) + "|n", "|G" + timestring(who[3], short=True) + "|n", str(who[4])) self.caller.msg(output) self.caller.msg(footer()) return
def verify_online_player(caller, value): """ Example 'verify function' that matches player input to an online character or else rejects their input as invalid. Args: caller (obj): Player entering the form data. value (str): String player entered into the form, to be verified. Returns: matched_character (obj or False): dbref to a currently logged in character object - reference to the object will be stored in the form instead of a string. Returns False if no match is made. """ # Get a list of sessions session_list = SESSIONS.get_sessions() char_list = [] matched_character = None # Get a list of online characters for session in session_list: if not session.logged_in: # Skip over logged out characters continue # Append to our list of online characters otherwise char_list.append(session.get_puppet()) # Match player input to a character name for character in char_list: if value.lower() == character.key.lower(): matched_character = character # If input didn't match to a character if not matched_character: # Send the player an error message unique to this function caller.msg("No character matching '%s' is online." % value) # Returning False indicates the new value is not valid return False # Returning anything besides True or False will replace the player's input with the returned # value. In this case, the value becomes a reference to the character object. You can store data # besides strings and integers in the 'formdata' dictionary this way! return matched_character
def verify_online_player(caller, value): """ Example 'verify function' that matches player input to an online character or else rejects their input as invalid. Args: caller (obj): Player entering the form data. value (str): String player entered into the form, to be verified. Returns: matched_character (obj or False): dbref to a currently logged in character object - reference to the object will be stored in the form instead of a string. Returns False if no match is made. """ # Get a list of sessions session_list = SESSIONS.get_sessions() char_list = [] matched_character = None # Get a list of online characters for session in session_list: if not session.logged_in: # Skip over logged out characters continue # Append to our list of online characters otherwise char_list.append(session.get_puppet()) # Match player input to a character name for character in char_list: if value.lower() == character.key.lower(): matched_character = character # If input didn't match to a character if not matched_character: # Send the player an error message unique to this function caller.msg("No character matching '%s' is online." % value) # Returning False indicates the new value is not valid return False # Returning anything besides True or False will replace the player's input with the returned # value. In this case, the value becomes a reference to the character object. You can store data # besides strings and integers in the 'formdata' dictionary this way! return matched_character
def func(self): ch = self.caller who_msg = "\n|w|[r Players Online:{num_players:>4} |n\n" table = self.styled_table("Level", "Name", border='incols') num_players = 0 for ses in SESSIONS.get_sessions(): if not ses.logged_in: continue num_players += 1 vict = ses.get_account().puppet level = vict.attrs.level.value race = vict.attrs.race.name.capitalize() name = vict.name.capitalize() title = vict.attrs.title.value table.add_row(f"[{level:<3}{race:>10}]", f"{name}{title}") ch.msg(who_msg.format(num_players=num_players) + str(table))
def func(self): """Get all connected accounts by polling session.""" you = self.account session_list = SESSIONS.get_sessions() cmd = self.cmdstring show_session_data = you.check_permstring('Immortals') and not you.attributes.has('_quell') account_count = (SESSIONS.account_count()) table = evtable.EvTable(border='none', pad_width=0, border_width=0, maxwidth=79) if cmd == 'wa' or cmd == 'where': # Example output expected: # Occ, Location, Avg Time, Top 3 Active, Directions # #3 Park 5m Rulan, Amber, Tria Taxi, Park # Other possible sort methods: Alphabetical by name, by occupant count, by activity, by distance # Nick = Global Nick (no greater than five A/N or randomly created if not a Global Nick # # WA with name parameters to pull up more extensive information about the direction # Highest Occupants (since last reboot), Last Visited, Last Busy (3+) etc. (more ideas here) table.add_header('|wOcc', '|wLocation', '|wAvg Time', '|cTop 3 Active', '|gDirections') table.reformat_column(0, width=4, align='l') table.reformat_column(1, width=25, align='l') table.reformat_column(2, width=6, align='l') table.reformat_column(3, width=16, pad_right=1, align='l') table.reformat_column(4, width=20, align='l') locations = {} # Create an empty dictionary to gather locations information. for session in session_list: # Go through connected list and see who's where. if not session.logged_in: continue character = session.get_puppet() if not character: continue if character.location not in locations: locations[character.location] = [] locations[character.location].append(character) # Build the list of who's in a location for place in locations: location = place.get_display_name(you) if place else '|222Nothingness|n' table.add_row(len(locations[place]), location, '?', ', '.join(each.get_display_name(you) for each in locations[place]), 'Summon or walk') elif cmd == 'ws': my_character = self.caller.get_puppet(self.session) if not (my_character and my_character.location): self.msg("You can't see anyone here.") return table.add_header('|wCharacter', '|wOn for', '|wIdle') table.reformat_column(0, width=45, align='l') table.reformat_column(1, width=8, align='l') table.reformat_column(2, width=7, pad_right=1, align='r') for element in my_character.location.contents: if not element.has_account: continue delta_cmd = time.time() - max([each.cmd_last_visible for each in element.sessions.all()]) delta_con = time.time() - min([each.conn_time for each in element.sessions.all()]) name = element.get_display_name(you) type = element.attributes.get('species', default='') table.add_row(name + ', ' + type if type else name, utils.time_format(delta_con, 0), utils.time_format(delta_cmd, 1)) elif cmd == 'what' or cmd == 'wot': table.add_header('|wCharacter - Doing', '|wIdle') table.reformat_column(0, width=72, align='l') table.reformat_column(1, width=7, align='r') for session in session_list: if not session.logged_in or not session.get_puppet(): continue delta_cmd = time.time() - session.cmd_last_visible character = session.get_puppet() doing = character.get_display_name(you, pose=True) table.add_row(doing, utils.time_format(delta_cmd, 1)) else: # Default to displaying who if show_session_data: # privileged info shown to Immortals and higher only when not quelled table.add_header('|wCharacter', '|wAccount', '|wQuell', '|wCmds', '|wProtocol', '|wAddress') table.reformat_column(0, align='l') table.reformat_column(1, align='r') table.reformat_column(2, width=7, align='r') table.reformat_column(3, width=6, pad_right=1, align='r') table.reformat_column(4, width=11, align='l') table.reformat_column(5, width=16, align='r') session_list = sorted(session_list, key=lambda o: o.account.key) for session in session_list: if not session.logged_in: continue account = session.get_account() puppet = session.get_puppet() table.add_row(puppet.get_display_name(you) if puppet else 'None', account.get_display_name(you), '|gYes|n' if account.attributes.get('_quell') else '|rNo|n', session.cmd_total, session.protocol_key, isinstance(session.address, tuple) and session.address[0] or session.address) else: # unprivileged info shown to everyone, including Immortals and higher when quelled table.add_header('|wCharacter', '|wOn for', '|wIdle') table.reformat_column(0, width=40, align='l') table.reformat_column(1, width=8, align='l') table.reformat_column(2, width=7, align='r') for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time character = session.get_puppet() if not character: continue table.add_row(character.get_display_name(you), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1)) is_one = account_count == 1 string = '%s' % 'A' if is_one else str(account_count) string += ' single ' if is_one else ' unique ' plural = ' is' if is_one else 's are' string += 'account%s logged in.' % plural self.msg(table) self.msg(string)
def execute_cmd(self, session=None, txt=None, **kwargs): """ Take incoming data and send it to connected channel. This is triggered by the bot_data_in Inputfunc. Args: session (Session, optional): Session responsible for this command. Note that this is the bot. txt (str, optional): Command string. Keyword Args: user (str): The name of the user who sent the message. channel (str): The name of channel the message was sent to. type (str): Nature of message. Either 'msg', 'action', 'nicklist' or 'ping'. nicklist (list, optional): Set if `type='nicklist'`. This is a list of nicks returned by calling the `self.get_nicklist`. It must look for a list `self._nicklist_callers` which will contain all callers waiting for the nicklist. timings (float, optional): Set if `type='ping'`. This is the return (in seconds) of a ping request triggered with `self.ping`. The return must look for a list `self._ping_callers` which will contain all callers waiting for the ping return. """ if kwargs["type"] == "nicklist": # the return of a nicklist request if hasattr(self, "_nicklist_callers") and self._nicklist_callers: chstr = f"{self.db.irc_channel} ({self.db.irc_network}:{self.db.irc_port})" nicklist = ", ".join( sorted(kwargs["nicklist"], key=lambda n: n.lower())) for obj in self._nicklist_callers: obj.msg( _("Nicks at {chstr}:\n {nicklist}").format( chstr=chstr, nicklist=nicklist)) self._nicklist_callers = [] return elif kwargs["type"] == "ping": # the return of a ping if hasattr(self, "_ping_callers") and self._ping_callers: chstr = f"{self.db.irc_channel} ({self.db.irc_network}:{self.db.irc_port})" for obj in self._ping_callers: obj.msg( _("IRC ping return from {chstr} took {time}s.").format( chstr=chstr, time=kwargs["timing"])) self._ping_callers = [] return elif kwargs["type"] == "privmsg": # A private message to the bot - a command. user = kwargs["user"] if txt.lower().startswith("who"): # return server WHO list (abbreviated for IRC) global _SESSIONS if not _SESSIONS: from evennia.server.sessionhandler import SESSIONS as _SESSIONS whos = [] t0 = time.time() for sess in _SESSIONS.get_sessions(): delta_cmd = t0 - sess.cmd_last_visible delta_conn = t0 - session.conn_time account = sess.get_account() whos.append("%s (%s/%s)" % ( utils.crop("|w%s|n" % account.name, width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1), )) text = f"Who list (online/idle): {', '.join(sorted(whos, key=lambda w: w.lower()))}" elif txt.lower().startswith("about"): # some bot info text = f"This is an Evennia IRC bot connecting from '{settings.SERVERNAME}'." else: text = "I understand 'who' and 'about'." super().msg(privmsg=((text, ), {"user": user})) else: # something to send to the main channel if kwargs["type"] == "action": # An action (irc pose) text = f"{kwargs['user']}@{kwargs['channel']} {txt}" else: # msg - A normal channel message text = f"{kwargs['user']}@{kwargs['channel']}: {txt}" if not self.ndb.ev_channel and self.db.ev_channel: # cache channel lookup self.ndb.ev_channel = self.db.ev_channel if self.ndb.ev_channel: self.ndb.ev_channel.msg(text, senders=self)
def func(self): session_list = SESSIONS.get_sessions() session_list = sorted(session_list, key=lambda ses: ses.get_puppet().name) titles1 = ('Artisan GM', 'Assassin GM', 'Druid GM', 'Fighter GM', 'Harbinger GM', 'Helotyr GM', 'Mage GM', 'Merchant GM', 'Monk GM', 'Ranger GM', 'Samurai GM', 'Sarthoar GM', 'Shaman GM', 'Sorcerer GM', 'Templar GM', 'Thief GM', 'Trader GM', 'Warrior GM', 'Chief', 'Sherrif', 'Gumi Commander', 'Editor in Chief', 'Chief Justice', 'Tribune Prime', 'Head Magistrate') titles2 = ('Artisan AGM', 'Assassin AGM', 'Druid AGM', 'Fighter AGM', 'Harbinger AGM', 'Helotyr AGM', 'Mage AGM', 'Merchant AGM', 'Monk AGM', 'Ranger AGM', 'Samurai AGM', 'Sarthoar AGM', 'Shaman AGM', 'Sorcerer AGM', 'Templar AGM', 'Thief AGM', 'Trader AGM', 'Warrior AGM', 'Vice Chief', 'Under-Sheriff', 'Gumi Captain', 'Editor', 'Justice', 'Tribune', 'Magistrate') titles3 = ('Medjai', 'Gumi', 'Deputy', 'Reporter', 'Kingdom Attorney', 'Aedile', 'Champion') titles4 = ('Barrister', 'Advocari', 'Counseler') titles5 = ('Field Marshal', 'Legate', 'Gensui') titles6 = ('General', 'Prefect', 'Taisho') titles7 = ('Colonel', 'Captain', 'Lieutenant', 'First Sergeant', 'Sergent', 'Corporal', 'Private', 'Recruit', 'First Centurion', 'Centurion', 'Decurion', 'Optio', 'Tressario', 'Decanus', 'Legionaire', 'Discens', 'Taisa', 'Tai', 'Chui', 'Socho', 'Gunso', 'Heicho', 'Ittohei', 'Nitohei') self.caller.msg( "----------------------======] |CMercadia|n [======----------------------" ) self.caller.msg(datetime.datetime.now().strftime( " %a %b %d %H:%M:%S %Y Mercadian Time")) self.caller.msg(" Mercadia uptime: %s. " % utils.time_format(gametime.uptime(), 3)) self.caller.msg( "----------------------======] |315Admin|n [======----------------------" ) self.caller.msg(" Revrwn, |305Administrator|n ") self.caller.msg( "----------------------======] |115Staff|n [======----------------------" ) self.caller.msg(" Jennifer, |405Chief of Staff ") self.caller.msg(" Dominic, |045Administrative Staff ") self.caller.msg(" Tiffany, |045Administrative Staff ") self.caller.msg(" Corry, |045Administrative Staff ") self.caller.msg( "----------------------======] |550Characters|n [======----------------------" ) for session in session_list: puppet = session.get_puppet() name = puppet.name gender = puppet.db.gender race = puppet.db.race guild = puppet.db.guild owner = puppet.db.owner title = puppet.db.title slaveentry = ", %s of %s" % (guild, owner) guildentry = ", %s" % guild if title in titles1: title = ", |300%s|n" % title elif title in titles2: title = ", |500%s|n" % title elif title in titles3: title = ", |510%s|n" % title elif title in titles4: title = ", |152%s|n" % title elif title in titles5: title = ", |203%s|n" % title elif title in titles6: title = ", |213%s|n" % title elif title in titles7: title = ", |223%s|n" % title else: title = " " if guild: guild = guildentry else: guild = guild if owner: guild = slaveentry if name in ('Roy', 'Jennifer', 'Dominic', 'Tiffany', 'Corry'): continue else: self.caller.msg( " %s %s %s%s %s" % (name.capitalize(), gender, race, guild, title)) self.caller.msg( "----------------------======] |555Online|n [======----------------------" ) self.caller.msg(" There are currently %s Players Online" % (SESSIONS.account_count())) self.caller.msg( "----------------------======]|C***************|n[======----------------------" ) if self.args in ("kingdom", 'caliphate', 'empire'): self.caller.msg( "----------------------======] |CMercadia|n [======----------------------" ) self.caller.msg(datetime.datetime.now().strftime( " %a %b %d %H:%M:%S %Y Mercadian Time")) self.caller.msg(" Mercadia uptime: %s. " % utils.time_format(gametime.uptime(), 3)) self.caller.msg( "----------------------======] |315Admin|n [======----------------------" ) self.caller.msg(" Revrwn, |305Administrator|n ") self.caller.msg( "----------------------======] |115Staff|n [======----------------------" ) self.caller.msg(" Jennifer, |405Chief of Staff ") self.caller.msg(" Dominic, |045Administrative Staff ") self.caller.msg(" Tiffany, |045Administrative Staff ") self.caller.msg(" Corry, |045Administrative Staff ") self.caller.msg( "----------------------======] |550Characters|n [======----------------------" ) for session in session_list: puppet = session.get_puppet() name = puppet.name gender = puppet.db.gender race = puppet.db.race guild = puppet.db.guild owner = puppet.db.owner title = puppet.db.title nation = puppet.db.nation slaveentry = ", %s of %s" % (guild, owner) guildentry = ", %s" % guild if title in titles1: title = ", |300%s|n" % title elif title in titles2: title = ", |500%s|n" % title elif title in titles3: title = ", |510%s|n" % title elif title in titles4: title = ", |152%s|n" % title elif title in titles5: title = ", |203%s|n" % title elif title in titles6: title = ", |213%s|n" % title elif title in titles7: title = ", |223%s|n" % title else: title = " " if guild: guild = guildentry else: guild = guild if owner: guild = slaveentry if name in ('Roy', 'Jennifer', 'Dominic', 'Tiffany', 'Corry'): continue elif self.args.capitalize() not in nation: continue else: self.caller.msg( " %s %s %s%s %s" % (name.capitalize(), gender, race, guild, title)) self.caller.msg( "----------------------======] |555Online|n [======----------------------" ) self.caller.msg( " There are currently %s Players Online" % (SESSIONS.account_count())) self.caller.msg( "----------------------======]|C***************|n[======----------------------" ) if self.args in ('human', 'elf', 'dwarf', 'gnome', 'centaur', 'ogryn', 'drow', 'duergar', 'svirfneblin', 'wemic', 'drakkar', 'ursine', 'feline', 'lupine', 'vulpine', 'naga', 'wisp'): self.caller.msg( "----------------------======] |CMercadia|n [======----------------------" ) self.caller.msg(datetime.datetime.now().strftime( " %a %b %d %H:%M:%S %Y Mercadian Time")) self.caller.msg(" Mercadia uptime: %s. " % utils.time_format(gametime.uptime(), 3)) self.caller.msg( "----------------------======] |315Admin|n [======----------------------" ) self.caller.msg(" Revrwn, |305Administrator|n ") self.caller.msg( "----------------------======] |115Staff|n [======----------------------" ) self.caller.msg(" Jennifer, |405Chief of Staff ") self.caller.msg(" Dominic, |045Administrative Staff ") self.caller.msg(" Tiffany, |045Administrative Staff ") self.caller.msg(" Corry, |045Administrative Staff ") self.caller.msg( "----------------------======] |550Characters|n [======----------------------" ) for session in session_list: puppet = session.get_puppet() name = puppet.name gender = puppet.db.gender race = puppet.db.race guild = puppet.db.guild owner = puppet.db.owner title = puppet.db.title nation = puppet.db.nation slaveentry = ", %s of %s" % (guild, owner) guildentry = ", %s" % guild if title in titles1: title = ", |300%s|n" % title elif title in titles2: title = ", |500%s|n" % title elif title in titles3: title = ", |510%s|n" % title elif title in titles4: title = ", |152%s|n" % title elif title in titles5: title = ", |203%s|n" % title elif title in titles6: title = ", |213%s|n" % title elif title in titles7: title = ", |223%s|n" % title else: title = " " if guild: guild = guildentry else: guild = guild if owner: guild = slaveentry if name in ('Roy', 'Jennifer', 'Dominic', 'Tiffany', 'Corry'): continue elif self.args.capitalize() not in race: continue else: self.caller.msg( " %s %s %s%s %s" % (name.capitalize(), gender, race, guild, title)) self.caller.msg( "----------------------======] |555Online|n [======----------------------" ) self.caller.msg( " There are currently %s Players Online" % (SESSIONS.account_count())) self.caller.msg( "----------------------======]|C***************|n[======----------------------" )
def func(self): """Get all connected players by polling session.""" player = self.player session_list = SESSIONS.get_sessions() session_list = sorted(session_list, key=lambda o: o.player.key) show_session_data = player.check_permstring( 'Immortals') if 'f' in self.switches else False nplayers = (SESSIONS.player_count()) if 'f' in self.switches or 'full' in self.switches: if show_session_data: # privileged info - who/f by wizard or immortal table = prettytable.PrettyTable([ "|wPlayer Name", "|wOn for", "|wIdle", "|wCharacter", "|wRoom", "|wCmds", "|wProtocol", "|wHost" ]) for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time player = session.get_player() puppet = session.get_puppet() location = puppet.location.key if puppet else 'None' table.add_row([ utils.crop(player.name, width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1), utils.crop(puppet.key if puppet else 'None', width=25), utils.crop(location, width=25), session.cmd_total, session.protocol_key, isinstance(session.address, tuple) and session.address[0] or session.address ]) else: # unprivileged info - who/f by player table = prettytable.PrettyTable( ["|wCharacter", "|wOn for", "|wIdle", "|wLocation"]) for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time character = session.get_puppet() location = character.location.key if character and character.location else 'None' table.add_row([ utils.crop( character.key if character else '- Unknown -', width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1), utils.crop(location, width=25) ]) else: if 's' in self.switches or 'species' in self.switches or self.cmdstring == 'ws': my_character = self.caller.get_puppet(self.session) if not (my_character and my_character.location): self.msg("You can't see anyone here.") return table = prettytable.PrettyTable( ["|wCharacter", "|wOn for", "|wIdle", "|wSpecies"]) for session in session_list: character = session.get_puppet() # my_character = self.caller.get_puppet(self.session) if not session.logged_in or character.location != my_character.location: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time character = session.get_puppet() species = character.attributes.get('species', default='- None -') table.add_row([ utils.crop( character.key if character else '- Unknown -', width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1), utils.crop(species, width=25) ]) else: # unprivileged info - who table = prettytable.PrettyTable( ["|wCharacter", "|wOn for", "|wIdle"]) for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time character = session.get_puppet() table.add_row([ utils.crop( character.key if character else '- Unknown -', width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1) ]) isone = nplayers == 1 string = "%s\n%s " % (table, 'A' if isone else nplayers) string += 'single' if isone else 'unique' plural = '' if isone else 's' string += " account%s logged in." % plural self.msg(string)
def func(self): """Performs the summon, accounting for in-world conditions.""" char = self.character loc = char.location account = self.account args = self.args lhs, rhs = self.lhs, self.rhs # opt = self.switches # TODO - add code to make the switches work. if char and char.ndb.currently_moving: account.msg("You can not summon while moving. (|rstop|n, then try again.)") return if not args: char.msg("Could not find target to summon. Usage: summon <character or NPC>") return session_list = SESSIONS.get_sessions() target = [] for session in session_list: if not (session.logged_in and session.get_puppet()): continue puppet = session.get_puppet() if lhs.lower() in puppet.get_display_name(char, plain=True).lower(): target.append(puppet) if len(target) < 1: char.msg("Error: character not found.") return if len(target) > 1: # Too many partial matches, try exact matching. char.msg("Error: character not found.") return else: target[0].msg("You are being summoned to %s " % loc.get_display_name(target[0]) + "by %s" % char.get_display_name(target[0]) + ". A portal should appear soon that will take you to " + "%s." % char.get_display_name(target[0])) char.msg("You begin to summon a portal between %s" % target[0].get_display_name(char) + " and your location.") # Check the pool for objects to use. Filter a list of objects tagged "pool" by those located in None. obj_pool = [each for each in evennia.search_tag('pool', category='portal') if not each.location] print('Object pool total: %i' % len(obj_pool)) if len(obj_pool) < 2: char.msg('Portals are currently out of stock or in use elsewhere.') return portal_enter, portal_exit = obj_pool[-2:] def open_portal(): """Move inflatable portals into place.""" portal_enter.move_to(target[0].location) portal_exit.move_to(loc) delay(10, callback=open_portal) # 10 seconds later, the portal (exit pair) appears. def close_portal(): """Remove and store inflatable portals in Nothingness.""" for each in portal_enter.contents: each.move_to(target[0].location) for each in portal_exit.contents: each.move_to(loc) portal_enter.location.msg_contents("|r%s|n vanishes into |222Nothingness|n." % portal_enter) portal_exit.location.msg_contents("|r%s|n vanishes into |222Nothingness|n." % portal_exit) portal_enter.move_to(None, to_none=True) portal_exit.move_to(None, to_none=True) delay(180, callback=close_portal) # Wait, then move portal objects to the portal pool in Nothingness
def func(self): """Get all connected players by polling session.""" player = self.player session_list = SESSIONS.get_sessions() session_list = sorted(session_list, key=lambda o: o.player.key) show_session_data = player.check_permstring('Immortals') if 'f' in self.switches else False nplayers = (SESSIONS.player_count()) if 'f' in self.switches or 'full' in self.switches: if show_session_data: # privileged info - who/f by wizard or immortal table = prettytable.PrettyTable(["|wPlayer Name", "|wOn for", "|wIdle", "|wCharacter", "|wRoom", "|wCmds", "|wProtocol", "|wHost"]) for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time player = session.get_player() puppet = session.get_puppet() location = puppet.location.key if puppet else 'None' table.add_row([utils.crop(player.name, width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1), utils.crop(puppet.key if puppet else 'None', width=25), utils.crop(location, width=25), session.cmd_total, session.protocol_key, isinstance(session.address, tuple) and session.address[0] or session.address]) else: # unprivileged info - who/f by player table = prettytable.PrettyTable(["|wCharacter", "|wOn for", "|wIdle", "|wLocation"]) for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time character = session.get_puppet() location = character.location.key if character and character.location else 'None' table.add_row([utils.crop(character.key if character else '- Unknown -', width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1), utils.crop(location, width=25)]) else: if 's' in self.switches or 'species' in self.switches or self.cmdstring == 'ws': my_character = self.caller.get_puppet(self.session) if not (my_character and my_character.location): self.msg("You can't see anyone here.") return table = prettytable.PrettyTable(["|wCharacter", "|wOn for", "|wIdle", "|wSpecies"]) for session in session_list: character = session.get_puppet() # my_character = self.caller.get_puppet(self.session) if not session.logged_in or character.location != my_character.location: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time character = session.get_puppet() species = character.attributes.get('species', default='- None -') table.add_row([utils.crop(character.key if character else '- Unknown -', width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1), utils.crop(species, width=25)]) else: # unprivileged info - who table = prettytable.PrettyTable(["|wCharacter", "|wOn for", "|wIdle"]) for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time character = session.get_puppet() table.add_row([utils.crop(character.key if character else '- Unknown -', width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1)]) isone = nplayers == 1 string = "%s\n%s " % (table, 'A' if isone else nplayers) string += 'single' if isone else 'unique' plural = '' if isone else 's' string += " account%s logged in." % plural self.msg(string)
def func(self): """Implementing the function""" caller = self.caller args = self.args if not args: caller.msg("Usage: boot[/switches] <account> [:reason]") return if ":" in args: args, reason = [a.strip() for a in args.split(":", 1)] else: args, reason = args, "" boot_list = [] if "sid" in self.switches: # Boot a particular session id. sessions = SESSIONS.get_sessions(True) for sess in sessions: # Find the session with the matching session id. if sess.sessid == int(args): boot_list.append(sess) break else: # Boot by account object pobj = search.account_search(args) if not pobj: caller.msg("Account %s was not found." % args) return pobj = pobj[0] if not pobj.access(caller, "boot"): string = "You don't have the permission to boot %s." % ( pobj.key, ) caller.msg(string) return # we have a bootable object with a connected user matches = SESSIONS.sessions_from_account(pobj) for match in matches: boot_list.append(match) if not boot_list: caller.msg( "No matching sessions found. The Account does not seem to be online." ) return # Carry out the booting of the sessions in the boot list. feedback = None if "quiet" not in self.switches: feedback = "You have been disconnected by %s.\n" % caller.name if reason: feedback += "\nReason given: %s" % reason for session in boot_list: session.msg(feedback) session.account.disconnect_session_from_account(session) if pobj and boot_list: logger.log_sec("Booted: %s (Reason: %s, Caller: %s, IP: %s)." % (pobj, reason, caller, self.session.address))
def inner_func(self): """Get all connected accounts by polling session.""" account = self.account session_list = SESSIONS.get_sessions() session_list = sorted(session_list, key=lambda o: o.account.key) show_session_data = account.check_permstring( "Developer") or account.check_permstring("Admins") naccounts = SESSIONS.account_count() if show_session_data: # privileged info table = self.styled_table( "|wAccount Name", "|wOn for", "|wIdle", "|wPuppeting", "|wLevel", "|wClass", "|wRoom", "|wCmds", "|wProtocol", "|wHost", ) for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time account = session.get_account() puppet = session.get_puppet() location = puppet.location.key if puppet and puppet.location else "None" table.add_row( utils.crop(account.get_display_name(account), width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1), utils.crop( puppet.get_display_name(account) if puppet else "None", width=25), puppet.level if hasattr(puppet, "level") else 0, puppet.classname if hasattr(puppet, "classname") else "None", utils.crop(location, width=25), session.cmd_total, session.protocol_key, isinstance(session.address, tuple) and session.address[0] or session.address, ) else: # unprivileged table = self.styled_table( "|wUsername", "|wGame Name", "|wLevel", "|wClass", "|wWhere", ) for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time account = session.get_account() puppet = session.get_puppet() location = puppet.location.key if puppet and puppet.location else "None" table.add_row( utils.crop(account.get_display_name(account), width=25), utils.crop( puppet.get_display_name(account) if puppet else "None", width=25), puppet.level if hasattr(puppet, "level") else 0, puppet.classname if hasattr(puppet, "classname") else "None", utils.crop(location, width=25), ) self.msg( "|w Monster Status\n 26-FEB-1991 8:38pm\n * - Monster Operator|n\n%s" % table)
def func(self): """ Performs the summon, accounting for in-world conditions. join: Implies one way portal to target summon: Implies one way portal to summoner meet: Implies two-way portal, both can meet. """ char = self.character cmd = self.cmdstring loc = char.location account = self.account args = self.args lhs, rhs = self.lhs, self.rhs opt = self.switches message_private = ' in a private room that does not allow portals to form.' if char and char.ndb.currently_moving: account.msg( "You can not open a portal while moving. (|lcstop|lt|rStop|n|le, then try again.)" ) return if not args and 'vanish' not in opt: char.msg('Usage: {} <character or NPC>'.format(cmd)) return session_list = SESSIONS.get_sessions() target = [] # Check for private flag on source room. It must be controlled by summoner if private. if loc.tags.get('private', category='flags') and not loc.access(char, 'control'): char.msg('You are' + message_private) return # Check object pool filtered by tagged "pool" and located in None. obj_pool = [ each for each in evennia.search_tag('pool', category='portal') if not each.location ] print('Object pool total: %i' % len(obj_pool)) if len(obj_pool) < 2: char.msg('Portals are currently out of stock or in use elsewhere.') return portal_enter, portal_exit = obj_pool[-2:] for session in session_list: if not (session.logged_in and session.get_puppet()): continue puppet = session.get_puppet() if lhs.lower() in puppet.get_display_name(char, plain=True).lower(): target.append(puppet) if len(target) < 1: char.msg("Specific character name not found.") return elif len(target) > 1: # Too many partial matches, try exact matching. char.msg("Unique character name not found.") return first_target = target[0] target = list(set(target)) # Remove duplicate character sessions target = first_target # Check for private flag on destination room. If so, check for in/out locks. there = target.location if there and there.tags.get( 'private', category='flags') and not there.access(char, 'control'): char.msg('Destination of portal is' + message_private) return # Check if A can walk to B, or B to A depending on meet or summon, # because sometimes a portal might not be needed. meet_message = 'You are being invited to meet {summoner} in {loc}.' join_message = 'You are being joined by {summoner} from {loc}.' summon_message = 'You are being summoned to {loc} by {summoner}.' message = meet_message if 'meet' in cmd else ( summon_message if 'summon' in cmd else join_message) loc_name = loc.get_display_name(target) target_name = target.get_display_name(char) char_name = char.get_display_name(target) target.msg(message.format(summoner=char_name, loc=loc_name)) target.msg('A portal should appear soon.') char.msg("You begin to open a portal connecting %s" % target_name + " and your location.") def open_portal(): """Move inflatable portals into place.""" # If in or out, join or summon, lock portals, depending. enter_lock, exit_lock = 'all()', 'all()' if 'only' in opt: enter_lock = 'id({}) OR id({})'.format(target.id, char.id) exit_lock = 'id({}) OR id({})'.format(target.id, char.id) if 'in' in opt or 'join' in cmd: enter_lock = 'none()' if 'out' in opt or 'summon' in cmd: exit_lock = 'none()' portal_enter.locks.add('enter:' + enter_lock) portal_exit.locks.add('enter:' + exit_lock) quiet = True if ('quiet' in opt or 'silent' in opt) else False portal_enter.move_to(target.location, quiet=quiet) if quiet: target.msg('{} quietly appears in {}.'.format( portal_enter.get_display_name(target), loc_name)) char.msg('{} quietly appears in {}.'.format( portal_exit.get_display_name(char), loc.get_display_name(char))) portal_exit.move_to(loc, quiet=quiet) delay(10, callback=open_portal ) # 10 seconds later, the portal (exit pair) appears. def close_portal(): """Remove and store inflatable portals in Nothingness.""" vanish_message = '|r{}|n vanishes into ' + settings.NOTHINGNESS + '.' for every in portal_enter.contents: every.move_to(target.location) for every in portal_exit.contents: every.move_to(loc) # if not quiet: if portal_enter.location: portal_enter.location.msg_contents( vanish_message.format(portal_enter)) portal_enter.move_to(None, to_none=True) # , quiet=quiet) if portal_exit.location: portal_exit.location.msg_contents( vanish_message.format(portal_exit)) portal_exit.move_to(None, to_none=True) # , quiet=quiet) delay( 180, callback=close_portal ) # Wait, then move portal objects to the portal pool in Nothingness
def func(self): """Performs the summon, accounting for in-world conditions.""" char = self.character loc = char.location account = self.account args = self.args lhs, rhs = self.lhs, self.rhs # opt = self.switches # TODO - add code to make the switches work. if char and char.ndb.currently_moving: account.msg( "You can not summon while moving. (|rstop|n, then try again.)") return if not args: char.msg( "Could not find target to summon. Usage: summon <character or NPC>" ) return session_list = SESSIONS.get_sessions() target = [] for session in session_list: if not (session.logged_in and session.get_puppet()): continue puppet = session.get_puppet() if lhs.lower() in puppet.get_display_name(char, plain=True).lower(): target.append(puppet) if len(target) < 1: char.msg("Error: character not found.") return if len(target) > 1: # Too many partial matches, try exact matching. char.msg("Error: character not found.") return else: target[0].msg( "You are being summoned to %s " % loc.get_display_name(target[0]) + "by %s" % char.get_display_name(target[0]) + ". A portal should appear soon that will take you to " + "%s." % char.get_display_name(target[0])) char.msg("You begin to summon a portal between %s" % target[0].get_display_name(char) + " and your location.") # Check the pool for objects to use. Filter a list of objects tagged "pool" by those located in None. obj_pool = [ each for each in evennia.search_tag('pool', category='portal') if not each.location ] print('Object pool total: %i' % len(obj_pool)) if len(obj_pool) < 2: char.msg('Portals are currently out of stock or in use elsewhere.') return portal_enter, portal_exit = obj_pool[-2:] def open_portal(): """Move inflatable portals into place.""" portal_enter.move_to(target[0].location) portal_exit.move_to(loc) delay(10, callback=open_portal ) # 10 seconds later, the portal (exit pair) appears. def close_portal(): """Remove and store inflatable portals in Nothingness.""" for each in portal_enter.contents: each.move_to(target[0].location) for each in portal_exit.contents: each.move_to(loc) portal_enter.location.msg_contents( "|r%s|n vanishes into |222Nothingness|n." % portal_enter) portal_exit.location.msg_contents( "|r%s|n vanishes into |222Nothingness|n." % portal_exit) portal_enter.move_to(None, to_none=True) portal_exit.move_to(None, to_none=True) delay( 180, callback=close_portal ) # Wait, then move portal objects to the portal pool in Nothingness
def execute_cmd(self, session=None, txt=None, **kwargs): """ Take incoming data and make the appropriate action. This acts as a CommandHandler of sorts for the various "type" of actions the Portal bot returns to the Server. This is triggered by the bot_data_in Inputfunc. Args: session (Session, optional): Session responsible for this command. Note that this is the bot. txt (str, optional): Command string. Kwargs: user (str): The name of the user who sent the message. channel (str): The name of channel the message was sent to. nicklist (list, optional): Set if `type='nicklist'`. This is a list of nicks returned by calling the `self.get_nicklist`. It must look for a list `self._nicklist_callers` which will contain all callers waiting for the nicklist. timings (float, optional): Set if `type='ping'`. This is the return (in seconds) of a ping request triggered with `self.ping`. The return must look for a list `self._ping_callers` which will contain all callers waiting for the ping return. type (str): The type of response returned by the IRC bot. Including: "nicklist": Returned when first joining a channel. "joined": Returned when a new user joins a channel. "left": Returned when a user leaves a channel. "privmsg": Returned when the bot is directly messaged. "action": Returned when a user uses /me in IRC Everything else is assumed to be text to speak. """ if kwargs["type"] == "nicklist": """ Returned when first joining a channel. """ if hasattr(self, "_nicklist_callers") and self._nicklist_callers: chstr = "%s (%s:%s)" % (self.db.irc_channel, self.db.irc_network, self.db.irc_port) nicklist = ", ".join( sorted(kwargs["nicklist"], key=lambda n: n.lower())) for obj in self._nicklist_callers: obj.msg("Nicks at %s:\n %s" % (chstr, nicklist)) self._nicklist_callers = [] return else: # Prepare blank reference dictionary. self.db.puppetdict = {} # Prepare listener. self.prep_listener() # Prepare puppets. for nick in kwargs["nicklist"]: self.prep_puppet(ansi.strip_ansi(nick)) # Hide stale puppets. for puppet in search.search_tag(self.key + "-puppet"): if puppet.location is not None \ and puppet not in self.db.puppetdict.values(): puppet.move_to(None, to_none=True) return elif kwargs["type"] == "ping": """ Returned by the ping command. """ if hasattr(self, "_ping_callers") and self._ping_callers: chstr = "%s (%s:%s)" % (self.db.irc_channel, self.db.irc_network, self.db.irc_port) for obj in self._ping_callers: obj.msg("IRC ping return from %s took %ss." % (chstr, kwargs["timing"])) self._ping_callers = [] return elif kwargs["type"] == "joined": """ Returned when a new user joins a channel. """ # Prepare puppet. for nick in kwargs["nicklist"]: self.prep_puppet(ansi.strip_ansi(nick)) return elif kwargs["type"] == "renamed": """ Returned when IRC user changes nick. """ puppetdict = self.db.puppetdict newname = kwargs["newname"] oldname = kwargs["oldname"] newkey = self.db.puppetprefix + newname + self.db.puppetsuffix oldkey = self.db.puppetprefix + oldname + self.db.puppetsuffix # List of puppet objects matching newname. puppetlist = [ puppet for puppet in search.search_tag(self.key + "-puppet") if puppet.key == newkey ] # Use an existing puppet. if puppetlist: # Set up new puppet puppetdict[newname] = puppetlist[0] if not puppetdict[newname].location == self.db.ev_location: puppetdict[newname].move_to(self.db.ev_location, quiet=True) self.db.ev_location.msg_contents(oldkey + " has become " + newkey) # Pack up old puppet self.db.puppetdict[oldname].move_to(None, to_none=True) del self.db.puppetdict[oldname] # Else recycle old puppet. elif oldname in puppetdict: print('Reusing puppetbot from puppetdict: ', oldname, puppetdict[oldname]) puppetdict[oldname].key = newkey puppetdict[newname] = puppetdict.pop(oldname) self.db.ev_location.msg_contents(oldkey + " has become " + newkey) return elif kwargs["type"] == "left": """ Returned when a user leaves a channel. """ # Pack up puppet. for nick in kwargs["nicklist"]: nick = ansi.strip_ansi(nick) if nick in self.db.puppetdict: self.db.puppetdict[nick].move_to(None, to_none=True) self.db.ev_location.msg_contents( self.db.puppetdict[nick].key + self.db.puppetexitmsg) del self.db.puppetdict[nick] return elif kwargs["type"] == "privmsg": """ Returned when the bot is directly messaged. Users can issue commands to the Server bot through IRC PM. "Who" - Return a list of current users in the MUD "About" - Describes the bot and the connected MUD "Look" - Look at the Evennia location and those within it. "whisper" - Whisper in-game account "whisper user = msg" "Desc" - If empty, shows in-game bots description. Else, sets bots in-game bot description to given value. All other messages return a help message. """ user = kwargs["user"] # Who command - Returns online users in game. if txt.lower().startswith("who"): # return server WHO list (abbreviated for IRC) global _SESSIONS if not _SESSIONS: from evennia.server.sessionhandler import \ SESSIONS as _SESSIONS whos = [] t0 = time.time() for sess in _SESSIONS.get_sessions(): delta_cmd = t0 - sess.cmd_last_visible delta_conn = t0 - session.conn_time account = sess.get_account() whos.append("%s (%s/%s)" % (utils.crop("|w%s|n" % account.name, width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1))) text = "Who list (online/idle): %s" % ", ".join( sorted(whos, key=lambda w: w.lower())) # Return Message. super(ServerBot, self).msg(privmsg=((text, ), {"user": user})) # About command - Return a blurb explaining origin of bot. elif txt.lower().startswith("about"): # some bot info text = self.db.botdesc # Return Message. super(ServerBot, self).msg(privmsg=((text, ), {"user": user})) # Look command - Look at the Evennia location and those within it. elif txt.lower().startswith("look"): # Mirror in-game look command. txt = txt.partition(" ")[2] if not txt: target = self.db.ev_location else: result = search.object_search( txt, candidates=self.db.ev_location.contents) target = result[0] if len(result) > 0 else None if not target: text = "'%s' could not be located." % txt else: text = target.return_appearance( self.db.puppetdict[user]).replace('\n', ' ') # Return Message. super(ServerBot, self).msg(privmsg=((text, ), {"user": user})) # Desc command - If empty, shows in-game bots description. Else, # sets bots in-game bot description to given value. elif txt.lower().startswith("desc"): # Split text - set desc as text or return current desc if none. txt = txt.partition(" ")[2] if not txt: text = self.db.puppetdict[user].db.desc else: self.db.puppetdict[user].db.desc = txt text = "Desc changed to: " + txt # Return Message. super(ServerBot, self).msg(privmsg=((text, ), {"user": user})) # Whisper command - Whisper a user in game through a puppet. elif txt.lower().startswith("whisper"): # Parse input. Must be in form 'whisper nick = msg' txt = txt.split(" ", 1)[1] try: nick, msg = txt.split("=") except Exception: text = "Whisper Usage: 'Whisper Character = Msg'" super(ServerBot, self).msg(privmsg=((text, ), { "user": user })) return if not nick or not msg: text = "Whisper Usage: 'Whisper Character = Msg'" super(ServerBot, self).msg(privmsg=((text, ), { "user": user })) return puppet = self.db.puppetdict[ansi.strip_ansi(user)] target = puppet.search(nick) if not target: text = "Whisper Aborted: Character could not be found." # Return Message. super(ServerBot, self).msg(privmsg=((text, ), { "user": user })) return puppet.execute_cmd("whisper " + nick + "=" + msg) text = 'You whisper to ' + nick + ', "' + msg + '"' super(ServerBot, self).msg(privmsg=((text, ), {"user": user})) return # Default message - Acts as help information. else: text = ( "Command list: \n" ' "Who": Return a list of online users on %s.\n' ' "About": Returns information about %s.\n' ' "Look": Look at the Evennia location and those within it.\n' ' "Desc": If empty, shows in-game bots description. Else, sets\n' ' "whisper" - Whisper in-game account "whisper user = msg"\n' ' bots in-game bot description to given value.\n' ' All other messages return this help message.') % ( settings.SERVERNAME, settings.SERVERNAME) # Return Message. super(ServerBot, self).msg(privmsg=((text, ), {"user": user})) elif kwargs["type"] == "action": """ Returned when a user uses /me in IRC """ # Cause puppet to act out pose. if ansi.strip_ansi(kwargs["user"]) in self.db.puppetdict: user = ansi.strip_ansi(kwargs["user"]) self.db.puppetdict[user].execute_cmd("pose " + txt) return else: """ Everything else is assumed to be text to speak. """ # Cause the puppet to say the message. if ansi.strip_ansi(kwargs["user"]) in self.db.puppetdict: user = ansi.strip_ansi(kwargs["user"]) self.db.puppetdict[user].execute_cmd("say " + txt) return
def func(self): """Get all connected accounts by polling session.""" you = self.account session_list = SESSIONS.get_sessions() cmd = self.cmdstring show_session_data = you.check_permstring( 'Immortals') and not you.attributes.has('_quell') account_count = (SESSIONS.account_count()) table = evtable.EvTable(border='none', pad_width=0, border_width=0, maxwidth=79) if cmd == 'wa' or cmd == 'where': # Example output expected: # Occ, Location, Avg Time, Top 3 Active, Directions # #3 Park 5m Rulan, Amber, Tria Taxi, Park # Other possible sort methods: Alphabetical by name, by occupant count, by activity, by distance # Nick = Global Nick (no greater than five A/N or randomly created if not a Global Nick # # WA with name parameters to pull up more extensive information about the direction # Highest Occupants (since last reboot), Last Visited, Last Busy (3+) etc. (more ideas here) table.add_header('|wOcc', '|wLocation', '|wAvg Time', '|cTop 3 Active', '|gDirections') table.reformat_column(0, width=4, align='l') table.reformat_column(1, width=25, align='l') table.reformat_column(2, width=6, align='l') table.reformat_column(3, width=16, pad_right=1, align='l') table.reformat_column(4, width=20, align='l') locations = { } # Create an empty dictionary to gather locations information. for session in session_list: # Go through connected list and see who's where. if not session.logged_in: continue character = session.get_puppet() if not character: continue if character.location not in locations: locations[character.location] = [] locations[character.location].append( character) # Build the list of who's in a location for place in locations: location = place.get_display_name( you) if place else '|222Nothingness|n' table.add_row( len(locations[place]), location, '?', ', '.join( each.get_display_name(you) for each in locations[place]), 'Summon or walk') elif cmd == 'ws': my_character = self.caller.get_puppet(self.session) if not (my_character and my_character.location): self.msg("You can't see anyone here.") return table.add_header('|wCharacter', '|wOn for', '|wIdle') table.reformat_column(0, width=45, align='l') table.reformat_column(1, width=8, align='l') table.reformat_column(2, width=7, pad_right=1, align='r') for element in my_character.location.contents: if not element.has_account: continue delta_cmd = time.time() - max( [each.cmd_last_visible for each in element.sessions.all()]) delta_con = time.time() - min( [each.conn_time for each in element.sessions.all()]) name = element.get_display_name(you) type = element.attributes.get('species', default='') table.add_row(name + ', ' + type if type else name, utils.time_format(delta_con, 0), utils.time_format(delta_cmd, 1)) elif cmd == 'what' or cmd == 'wot': table.add_header('|wCharacter - Doing', '|wIdle') table.reformat_column(0, width=72, align='l') table.reformat_column(1, width=7, align='r') for session in session_list: if not session.logged_in or not session.get_puppet(): continue delta_cmd = time.time() - session.cmd_last_visible character = session.get_puppet() doing = character.get_display_name(you, pose=True) table.add_row(doing, utils.time_format(delta_cmd, 1)) else: # Default to displaying who if show_session_data: # privileged info shown to Immortals and higher only when not quelled table.add_header('|wCharacter', '|wAccount', '|wQuell', '|wCmds', '|wProtocol', '|wAddress') table.reformat_column(0, align='l') table.reformat_column(1, align='r') table.reformat_column(2, width=7, align='r') table.reformat_column(3, width=6, pad_right=1, align='r') table.reformat_column(4, width=11, align='l') table.reformat_column(5, width=16, align='r') session_list = sorted(session_list, key=lambda o: o.account.key) for session in session_list: if not session.logged_in: continue account = session.get_account() puppet = session.get_puppet() table.add_row( puppet.get_display_name(you) if puppet else 'None', account.get_display_name(you), '|gYes|n' if account.attributes.get('_quell') else '|rNo|n', session.cmd_total, session.protocol_key, isinstance(session.address, tuple) and session.address[0] or session.address) else: # unprivileged info shown to everyone, including Immortals and higher when quelled table.add_header('|wCharacter', '|wOn for', '|wIdle') table.reformat_column(0, width=40, align='l') table.reformat_column(1, width=8, align='l') table.reformat_column(2, width=7, align='r') for session in session_list: if not session.logged_in: continue delta_cmd = time.time() - session.cmd_last_visible delta_conn = time.time() - session.conn_time character = session.get_puppet() if not character: continue table.add_row(character.get_display_name(you), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1)) is_one = account_count == 1 string = '%s' % 'A' if is_one else str(account_count) string += ' single ' if is_one else ' unique ' plural = ' is' if is_one else 's are' string += 'account%s logged in.' % plural self.msg(table) self.msg(string)
def execute_cmd(self, session=None, txt=None, **kwargs): """ Take incoming data and send it to connected channel. This is triggered by the bot_data_in Inputfunc. Args: session (Session, optional): Session responsible for this command. Note that this is the bot. txt (str, optional): Command string. Kwargs: user (str): The name of the user who sent the message. channel (str): The name of channel the message was sent to. type (str): Nature of message. Either 'msg', 'action', 'nicklist' or 'ping'. nicklist (list, optional): Set if `type='nicklist'`. This is a list of nicks returned by calling the `self.get_nicklist`. It must look for a list `self._nicklist_callers` which will contain all callers waiting for the nicklist. timings (float, optional): Set if `type='ping'`. This is the return (in seconds) of a ping request triggered with `self.ping`. The return must look for a list `self._ping_callers` which will contain all callers waiting for the ping return. """ if kwargs["type"] == "nicklist": # the return of a nicklist request if hasattr(self, "_nicklist_callers") and self._nicklist_callers: chstr = "%s (%s:%s)" % (self.db.irc_channel, self.db.irc_network, self.db.irc_port) nicklist = ", ".join(sorted(kwargs["nicklist"], key=lambda n: n.lower())) for obj in self._nicklist_callers: obj.msg("Nicks at %s:\n %s" % (chstr, nicklist)) self._nicklist_callers = [] return elif kwargs["type"] == "ping": # the return of a ping if hasattr(self, "_ping_callers") and self._ping_callers: chstr = "%s (%s:%s)" % (self.db.irc_channel, self.db.irc_network, self.db.irc_port) for obj in self._ping_callers: obj.msg("IRC ping return from %s took %ss." % (chstr, kwargs["timing"])) self._ping_callers = [] return elif kwargs["type"] == "privmsg": # A private message to the bot - a command. user = kwargs["user"] if txt.lower().startswith("who"): # return server WHO list (abbreviated for IRC) global _SESSIONS if not _SESSIONS: from evennia.server.sessionhandler import SESSIONS as _SESSIONS whos = [] t0 = time.time() for sess in _SESSIONS.get_sessions(): delta_cmd = t0 - sess.cmd_last_visible delta_conn = t0 - session.conn_time player = sess.get_player() whos.append("%s (%s/%s)" % (utils.crop("|w%s|n" % player.name, width=25), utils.time_format(delta_conn, 0), utils.time_format(delta_cmd, 1))) text = "Who list (online/idle): %s" % ", ".join(sorted(whos, key=lambda w: w.lower())) elif txt.lower().startswith("about"): # some bot info text = "This is an Evennia IRC bot connecting from '%s'." % settings.SERVERNAME else: text = "I understand 'who' and 'about'." super(IRCBot, self).msg(privmsg=((text,), {"user": user})) else: # something to send to the main channel if kwargs["type"] == "action": # An action (irc pose) text = "%s@%s %s" % (kwargs["user"], kwargs["channel"], txt) else: # msg - A normal channel message text = "%s@%s: %s" % (kwargs["user"], kwargs["channel"], txt) if not self.ndb.ev_channel and self.db.ev_channel: # cache channel lookup self.ndb.ev_channel = self.db.ev_channel if self.ndb.ev_channel: self.ndb.ev_channel.msg(text, senders=self.id)