def setUp(self): """ Sets up testing environment """ self.account = create.create_account("TestAccount", email="*****@*****.**", password="******", typeclass=self.account_typeclass) self.account2 = create.create_account("TestAccount2", email="*****@*****.**", password="******", typeclass=self.account_typeclass) self.room1 = create.create_object(self.room_typeclass, key="Room", nohome=True) self.room1.db.desc = "room_desc" settings.DEFAULT_HOME = "#%i" % self.room1.id # we must have a default home # Set up fake prototype module for allowing tests to use named prototypes. settings.PROTOTYPE_MODULES = "evennia.utils.tests.data.prototypes_example" self.room2 = create.create_object(self.room_typeclass, key="Room2") self.exit = create.create_object(self.exit_typeclass, key='out', location=self.room1, destination=self.room2) self.obj1 = create.create_object(self.object_typeclass, key="Obj", location=self.room1, home=self.room1) self.obj2 = create.create_object(self.object_typeclass, key="Obj2", location=self.room1, home=self.room1) self.char1 = create.create_object(self.character_typeclass, key="Char", location=self.room1, home=self.room1) self.char1.permissions.add("Developer") self.char2 = create.create_object(self.character_typeclass, key="Char2", location=self.room1, home=self.room1) self.char1.account = self.account self.account.db._last_puppet = self.char1 self.char2.account = self.account2 self.account2.db._last_puppet = self.char2 self.script = create.create_script(self.script_typeclass, key="Script") self.account.permissions.add("Developer") # set up a fake session dummysession = ServerSession() dummysession.init_session("telnet", ("localhost", "testmode"), SESSIONS) dummysession.sessid = 1 SESSIONS.portal_connect(dummysession.get_sync_data()) # note that this creates a new Session! session = SESSIONS.session_from_sessid(1) # the real session SESSIONS.login(session, self.account, testmode=True) self.session = session
def test_password_validation(self): "Check password validators deny bad passwords" self.account = create.create_account("TestAccount%s" % randint(0, 9), email="*****@*****.**", password="******", typeclass=DefaultAccount) for bad in ('', '123', 'password', 'TestAccount', '#', 'xyzzy'): self.assertFalse(self.account.validate_password(bad, account=self.account)[0]) "Check validators allow sufficiently complex passwords" for better in ('Mxyzptlk', "j0hn, i'M 0n1y d4nc1nG"): self.assertTrue(self.account.validate_password(better, account=self.account)[0])
def test_password_change(self): "Check password setting and validation is working as expected" self.account = create.create_account("TestAccount%s" % randint(0, 9), email="*****@*****.**", password="******", typeclass=DefaultAccount) from django.core.exceptions import ValidationError # Try setting some bad passwords for bad in ('', '#', 'TestAccount', 'password'): self.assertRaises(ValidationError, self.account.set_password, bad) # Try setting a better password (test for False; returns None on success) self.assertFalse(self.account.set_password('Mxyzptlk'))
def test_puppet_object_no_permission(self): "Check puppet_object method called, no permission" import evennia.server.sessionhandler account = create.create_account("TestAccount%s" % randint(0, 999999), email="*****@*****.**", password="******", typeclass=DefaultAccount) self.s1.uid = account.uid evennia.server.sessionhandler.SESSIONS[self.s1.uid] = self.s1 self.s1.data_out = MagicMock() obj = Mock() obj.access = Mock(return_value=False) account.puppet_object(self.s1, obj) self.assertTrue(self.s1.data_out.call_args[1]['text'].startswith("You don't have permission to puppet")) self.assertIsNone(obj.at_post_puppet.call_args)
def test_puppet_object_already_puppeting(self): "Check puppet_object method called, already puppeting this" import evennia.server.sessionhandler account = create.create_account("TestAccount%s" % randint(0, 999999), email="*****@*****.**", password="******", typeclass=DefaultAccount) self.s1.uid = account.uid evennia.server.sessionhandler.SESSIONS[self.s1.uid] = self.s1 self.s1.logged_in = True self.s1.data_out = Mock(return_value=None) obj = Mock() self.s1.puppet = obj account.puppet_object(self.s1, obj) self.s1.data_out.assert_called_with(options=None, text="You are already puppeting this object.") self.assertIsNone(obj.at_post_puppet.call_args)
def test_puppet_object_joining_other_session(self): "Check puppet_object method called, joining other session" import evennia.server.sessionhandler account = create.create_account("TestAccount%s" % randint(0, 999999), email="*****@*****.**", password="******", typeclass=DefaultAccount) self.s1.uid = account.uid evennia.server.sessionhandler.SESSIONS[self.s1.uid] = self.s1 self.s1.puppet = None self.s1.logged_in = True self.s1.data_out = Mock(return_value=None) obj = Mock() obj.access = Mock(return_value=True) obj.account = account account.puppet_object(self.s1, obj) # works because django.conf.settings.MULTISESSION_MODE is not in (1, 3) self.assertTrue(self.s1.data_out.call_args[1]['text'].endswith("from another of your sessions.")) self.assertTrue(obj.at_post_puppet.call_args[1] == {})
def test_puppet_object_already_puppeted(self): "Check puppet_object method called, already puppeted" import evennia.server.sessionhandler account = create.create_account("TestAccount%s" % randint(0, 999999), email="*****@*****.**", password="******", typeclass=DefaultAccount) self.s1.uid = account.uid evennia.server.sessionhandler.SESSIONS[self.s1.uid] = self.s1 self.s1.puppet = None self.s1.logged_in = True self.s1.data_out = Mock(return_value=None) obj = Mock() obj.access = Mock(return_value=True) obj.account = Mock() obj.at_post_puppet = Mock() account.puppet_object(self.s1, obj) self.assertTrue(self.s1.data_out.call_args[1]['text'].endswith("is already puppeted by another Account.")) self.assertIsNone(obj.at_post_puppet.call_args)
def create_player(playername, password, permissions=None, typeclass=None): """ Helper function, creates a player of the specified typeclass. """ if not permissions: permissions = settings.PERMISSION_ACCOUNT_DEFAULT new_player = create.create_account(playername, None, password, permissions=permissions, typeclass=typeclass) # This needs to be set so the engine knows this player is # logging in for the first time. (so it knows to call the right # hooks during login later) new_player.db.FIRST_LOGIN = True # join the new player to the public channel pchannel = ChannelDB.objects.get_channel(settings.DEFAULT_CHANNELS[0]["key"]) if not pchannel.connect(new_player): string = "New player '%s' could not connect to public channel!" % new_player.key logger.log_err(string) return new_player
def _create_account(session, accountname, password, permissions, typeclass=None, email=None): """ Helper function, creates an account of the specified typeclass. """ try: new_account = create.create_account(accountname, email, password, permissions=permissions, typeclass=typeclass) except Exception as e: session.msg("There was an error creating the Account:\n%s\n If this problem persists, contact an admin." % e) logger.log_trace() return False # This needs to be set so the engine knows this account is # logging in for the first time. (so it knows to call the right # hooks during login later) new_account.db.FIRST_LOGIN = True # join the new account to the public channel pchannel = ChannelDB.objects.get_channel(settings.DEFAULT_CHANNELS[0]["key"]) if not pchannel or not pchannel.connect(new_account): string = "New account '%s' could not connect to public channel!" % new_account.key logger.log_err(string) return new_account
def func(self): """Setup the rss-channel mapping""" # checking we have all we need if not settings.RSS_ENABLED: string = """RSS is not enabled. You need to activate it in game/settings.py.""" self.msg(string) return try: import feedparser assert feedparser # to avoid checker error of not being used except ImportError: string = "RSS requires python-feedparser (https://pypi.python.org/pypi/feedparser)." \ " Install before continuing." self.msg(string) return if 'list' in self.switches: # show all connections rssbots = [ bot for bot in AccountDB.objects.filter( db_is_bot=True, username__startswith="rssbot-") ] if rssbots: from evennia.utils.evtable import EvTable table = EvTable("|wdbid|n", "|wupdate rate|n", "|wev-channel", "|wRSS feed URL|n", border="cells", maxwidth=_DEFAULT_WIDTH) for rssbot in rssbots: table.add_row(rssbot.id, rssbot.db.rss_rate, rssbot.db.ev_channel, rssbot.db.rss_url) self.msg(table) else: self.msg("No rss bots found.") return if 'disconnect' in self.switches or 'remove' in self.switches or 'delete' in self.switches: botname = "rssbot-%s" % self.lhs matches = AccountDB.objects.filter(db_is_bot=True, db_key=botname) if not matches: # try dbref match matches = AccountDB.objects.filter(db_is_bot=True, id=self.args.lstrip("#")) if matches: matches[0].delete() self.msg("RSS connection destroyed.") else: self.msg( "RSS connection/bot could not be removed, does it exist?") return if not self.args or not self.rhs: string = "Usage: @rss2chan[/switches] <evennia_channel> = <rss url>" self.msg(string) return channel = self.lhs url = self.rhs botname = "rssbot-%s" % url # create a new bot bot = AccountDB.objects.filter(username__iexact=botname) if bot: # re-use existing bot bot = bot[0] if not bot.is_bot: self.msg("Account '%s' already exists and is not a bot." % botname) return else: bot = create.create_account(botname, None, None, typeclass=bots.RSSBot) bot.start(ev_channel=channel, rss_url=url, rss_rate=10) self.msg("RSS reporter created. Fetching RSS.")
def setUp(self): self.account = create.create_account("TestAccount%s" % randint(0, 999999), email="*****@*****.**", password="******", typeclass=DefaultAccount) self.handler = AccountSessionHandler(self.account)
def test_cmd_attack(self, mock_dice_check, mock_randint, mock_char_inform_staff, mock_inform_staff): self.setup_cmd(combat.CmdAttack, self.char1) from evennia.utils import create self.account3 = create.create_account("TestAccount3", email="*****@*****.**", password="******", typeclass=self.account_typeclass) self.char3 = create.create_object(self.character_typeclass, key="Char3", location=self.room1, home=self.room1) self.char3.account = self.account3 self.account3.db._last_puppet = self.char3 self.char1.db.defenders = [self.char3] self.char3.db.guarding = self.char1 self.char3.combat.autoattack = True fight = self.start_fight(self.char1) self.call_cmd("", "Could not find ''.|Attack who?") self.call_cmd("Emerald", "Could not find 'Emerald'.|Attack who?") self.char2.tags.add("unattackable") self.call_cmd("Char2", "Char2 is not attackable and cannot enter combat.") self.char2.tags.remove("unattackable") self.call_cmd("Char2", "They are not in combat.") fight.add_combatant(self.char2, adder=self.char1) self.char1.db.sleep_status = "unconscious" self.call_cmd("Char2", "You are not conscious.") self.caller = self.char2 self.call_cmd( "Char", "Char is incapacitated. To kill an incapacitated character, you must use the " "+coupdegrace command.") self.char1.db.sleep_status = "awake" self.call_cmd("/critical/accuracy Char", "These switches cannot be used together.") self.call_cmd("/critical Char=lipstick", "Modifier must be a number between 1 and 50.") self.call_cmd( "/accuracy Char", "You have marked yourself as ready to proceed.|\n" "Combatant Damage Fatigue Action Ready? \n" "Char2 no 0 attack Char3 yes " "Char no 0 None no " "Char3 no 0 None no \n" "Current Round: 0|" "Queuing action for your turn: You attack Char. It was interfered with, " "forcing you to target Char3 instead. Attempting to make your attack more " "accurate.") self.assertTrue(self.char2.combat.state.queued_action) char2_q = self.char2.combat.state.queued_action self.assertEqual(char2_q.qtype, "attack") self.assertEqual(char2_q.targ, self.char3) self.assertEqual( char2_q.msg, "{rYou attack Char.{n It was interfered with, forcing you to target " "{cChar3{n instead. Attempting to make your attack more accurate.") self.assertEqual(char2_q.attack_penalty, -15) self.assertEqual(char2_q.dmg_penalty, 15) self.call_cmd( "/critical/only Char", "Queuing action for your turn: You attack Char. " "Attempting a critical hit.") char2_q = self.char2.combat.state.queued_action self.assertEqual(char2_q.targ, self.char1) self.assertEqual(char2_q.msg, "{rYou attack Char.{n Attempting a critical hit.") self.assertEqual(char2_q.attack_penalty, 30) self.assertEqual(char2_q.dmg_penalty, -15) # phase 2 attack self.caller = self.char1 self.char3.combat.state.setup_attacks() # bodyguard's autoattack self.char1.combat.state.ready, self.char3.combat.state.ready = True, True fight.build_initiative_list = Mock() fight.ndb.initiative_list = [ self.char2.combat.state, self.char3.combat.state ] fight.ndb.phase = 2 fight.ndb.active_character = self.char1 mock_dice_check.return_value = 10 mock_randint.return_value = 5 self.char1.armor = 1 # 8 mitigation self.char2.armor = 5 # 10 mitigation self.char1.combat.state.damage_modifier = 100 # 32--> -mit = 22--> *dmgmult 0.5 self.char2.combat.state.damage_modifier = 30 # 15--> -mit = 7--> *dmgmult 0.5 self.call_cmd( "Char2", "You attack Char2. |YOU attack Char2 10 vs 10: graze for severe damage (11).|" "Char attacks Char2 (graze for severe damage).|It is now Char2's turn.|" "Char2 attacks YOU and rolled 10 vs 10: graze for moderate damage (3). " "Your armor mitigated 8 of the damage.|" "Char2 attacks Char (graze for moderate damage).|It is now Char3's turn.|" "Char3 attacks Char2 (graze for no damage).|Setup Phase|\n" "Combatant Damage Fatigue Action Ready? \n" "Char moderate 0 None no " "Char2 severe 0 None no " "Char3 no 0 attack Char2 no \n" "Current Round: 1") self.assertEqual(self.char1.damage, 3) self.assertEqual(self.char2.damage, 11) self.call_cmd( "/flub Char2", "You must specify both a to-hit and damage penalty, though they can be 0." ) self.call_cmd( "/flub Char2=5,6,7", "You must specify both a to-hit and damage penalty, though they can be 0." ) self.call_cmd("/flub Char2=200,-2000", "Maximum flub value is 500.") self.call_cmd( "/flub Char2=200,-200", 'You have marked yourself as ready to proceed.|\n' 'Combatant Damage Fatigue Action Ready? \n' 'Char moderate 0 attack Char2 yes ' 'Char2 severe 0 None no ' 'Char3 no 0 attack Char2 no \n' 'Current Round: 1|' 'Queuing action for your turn: You attack Char2. ' 'Adjusting your attack with a to-hit penalty of 200 and' ' damage penalty of 200.') last_action = self.char1.combat.state.queued_action self.assertEqual(last_action.attack_penalty, 200) self.assertEqual(last_action.dmg_penalty, 200) fight.ndb.phase = 2 self.char1.combat.state.do_turn_actions() self.assertEqual(last_action, self.char1.combat.state.last_action) attack = last_action.finished_attack self.assertEqual(attack.dmg_penalty, 200) self.assertEqual(attack.attack_penalty, 200)
def func(self): """Setup the irc-channel mapping""" if not settings.IRC_ENABLED: string = "IRC is not enabled. Activate it in game/settings.py." self.msg(string) return # If no args: list bots. if not self.args: # show all connections ircbots = [ bot for bot in AccountDB.objects.filter( db_is_bot=True, username__startswith="ircbot-") ] if ircbots: from evennia.utils.evtable import EvTable table = EvTable("|w#dbref|n", "|wbotname|n", "|wev-channel/location|n", "|wirc-channel|n", "|wSSL|n", maxwidth=_DEFAULT_WIDTH) for ircbot in ircbots: ircinfo = "%s (%s:%s)" % (ircbot.db.irc_channel, ircbot.db.irc_network, ircbot.db.irc_port) table.add_row( "#%i" % ircbot.id, ircbot.db.irc_botname, ircbot.attributes.get("ev_channel", ircbot.db.ev_location.key), ircinfo, ircbot.db.irc_ssl) self.msg(table) self.msg("Use 'help @puppetbot' for more infomation.") else: self.msg("No irc bots found.") return # Switch options available only if valid bot is given. if self.switches: botname = "ircbot-%s" % self.lhs matches = AccountDB.objects.filter(db_is_bot=True, username=botname) dbref = utils.dbref(self.lhs) if not matches and dbref: # try dbref match matches = AccountDB.objects.filter(db_is_bot=True, id=dbref) if not matches: self.msg("No valid bot given. Consult 'help @irc2puppet'") return # @irc2puppet/delete <bot> - Delete bot. if any(i in ['disconnect', 'remove', 'delete'] for i in self.switches): matches[0].delete() self.msg("IRC link/bot destroyed.") return # @irc2puppet/ping <bot> - ping bot. if "ping" in self.switches: matches[0].ping(self.caller) self.msg("Pinging " + self.lhs) return # @irc2puppet/who <bot> - Get IRC user list.. if "who" in self.switches: # retrieve user list. The bot must handles the echo since it's # an asynchronous call. self.caller.msg( "Requesting nicklist from %s (%s:%s)." % (matches[0].db.irc_channel, matches[0].db.irc_network, matches[0].db.irc_port)) matches[0].get_nicklist(self.caller) return # @irc2puppet/reconnect <bot> - reconnect bot. if "reconnect" in self.switches: matches[0].reconnect() self.msg("Reconnecting " + self.lhs) return # @irc2puppet/reload <bot> - Delete all bots, recreates bots from new user list. if "reload" in self.switches: matches[0].db.ev_location.msg_contents( "Puppet reload in progress.") puppetlist = [ puppet for puppet in search.search_tag(matches[0].key + "-puppet") ] for puppet in puppetlist: puppet.delete() matches[0].get_nicklist() return # Create Bot. location = self.caller.location self.args = self.args.replace('#', ' ') # Avoid Python comment issues try: irc_network, irc_port, irc_channel, irc_botname = \ [part.strip() for part in self.args.split(None, 4)] irc_channel = "#%s" % irc_channel except Exception: string = "IRC bot definition '%s' is not valid." % self.args self.msg(string) return botname = "ircbot-%s" % irc_botname # create a new bot bot = AccountDB.objects.filter(username__iexact=botname) if bot: # re-use an existing bot bot = bot[0] if not bot.is_bot: self.msg("'%s' already exists and is not a bot." % botname) return else: password = "******" try: bot = create.create_account(botname, None, password, typeclass=AccountBot) except Exception as err: self.msg("|rError, could not create the bot:|n '%s'." % err) return bot.start(ev_location=location, irc_botname=irc_botname, irc_channel=irc_channel, irc_network=irc_network, irc_port=irc_port) self.msg("Connection created. Starting IRC bot.")
def func(self): """Setup the rss-channel mapping""" # checking we have all we need if not settings.RSS_ENABLED: string = """RSS is not enabled. You need to activate it in game/settings.py.""" self.msg(string) return try: import feedparser assert feedparser # to avoid checker error of not being used except ImportError: string = "RSS requires python-feedparser (https://pypi.python.org/pypi/feedparser)." \ " Install before continuing." self.msg(string) return if 'list' in self.switches: # show all connections rssbots = [bot for bot in AccountDB.objects.filter(db_is_bot=True, username__startswith="rssbot-")] if rssbots: from evennia.utils.evtable import EvTable table = EvTable("|wdbid|n", "|wupdate rate|n", "|wev-channel", "|wRSS feed URL|n", border="cells", maxwidth=_DEFAULT_WIDTH) for rssbot in rssbots: table.add_row(rssbot.id, rssbot.db.rss_rate, rssbot.db.ev_channel, rssbot.db.rss_url) self.msg(table) else: self.msg("No rss bots found.") return if 'disconnect' in self.switches or 'remove' in self.switches or 'delete' in self.switches: botname = "rssbot-%s" % self.lhs matches = AccountDB.objects.filter(db_is_bot=True, db_key=botname) if not matches: # try dbref match matches = AccountDB.objects.filter(db_is_bot=True, id=self.args.lstrip("#")) if matches: matches[0].delete() self.msg("RSS connection destroyed.") else: self.msg("RSS connection/bot could not be removed, does it exist?") return if not self.args or not self.rhs: string = "Usage: @rss2chan[/switches] <evennia_channel> = <rss url>" self.msg(string) return channel = self.lhs url = self.rhs botname = "rssbot-%s" % url # create a new bot bot = AccountDB.objects.filter(username__iexact=botname) if bot: # re-use existing bot bot = bot[0] if not bot.is_bot: self.msg("Account '%s' already exists and is not a bot." % botname) return else: bot = create.create_account(botname, None, None, typeclass=bots.RSSBot) bot.start(ev_channel=channel, rss_url=url, rss_rate=10) self.msg("RSS reporter created. Fetching RSS.")
def func(self): """Setup the irc-channel mapping""" if not settings.IRC_ENABLED: string = """IRC is not enabled. You need to activate it in game/settings.py.""" self.msg(string) return if 'list' in self.switches: # show all connections self.msg(_list_bots()) return if 'disconnect' in self.switches or 'remove' in self.switches or 'delete' in self.switches: botname = "ircbot-%s" % self.lhs matches = AccountDB.objects.filter(db_is_bot=True, username=botname) dbref = utils.dbref(self.lhs) if not matches and dbref: # try dbref match matches = AccountDB.objects.filter(db_is_bot=True, id=dbref) if matches: matches[0].delete() self.msg("IRC connection destroyed.") else: self.msg("IRC connection/bot could not be removed, does it exist?") return if not self.args or not self.rhs: string = "Usage: @irc2chan[/switches] <evennia_channel> =" \ " <ircnetwork> <port> <#irchannel> <botname>[:typeclass]" self.msg(string) return channel = self.lhs self.rhs = self.rhs.replace('#', ' ') # to avoid Python comment issues try: irc_network, irc_port, irc_channel, irc_botname = \ [part.strip() for part in self.rhs.split(None, 4)] irc_channel = "#%s" % irc_channel except Exception: string = "IRC bot definition '%s' is not valid." % self.rhs self.msg(string) return botclass = None if ":" in irc_botname: irc_botname, botclass = [part.strip() for part in irc_botname.split(":", 2)] botname = "ircbot-%s" % irc_botname # If path given, use custom bot otherwise use default. botclass = botclass if botclass else bots.IRCBot irc_ssl = "ssl" in self.switches # create a new bot bot = AccountDB.objects.filter(username__iexact=botname) if bot: # re-use an existing bot bot = bot[0] if not bot.is_bot: self.msg("Account '%s' already exists and is not a bot." % botname) return else: password = hashlib.md5(str(time.time())).hexdigest()[:11] try: bot = create.create_account(botname, None, password, typeclass=botclass) except Exception as err: self.msg("|rError, could not create the bot:|n '%s'." % err) return bot.start(ev_channel=channel, irc_botname=irc_botname, irc_channel=irc_channel, irc_network=irc_network, irc_port=irc_port, irc_ssl=irc_ssl) self.msg("Connection created. Starting IRC bot.")
def setUp(self): super(TestDefaultAccountAuth, self).setUp() self.password = "******" self.account.delete() self.account = create.create_account("TestAccount%s" % randint(100000, 999999), email="*****@*****.**", password=self.password, typeclass=DefaultAccount)
def func(self): """Setup the irc-channel mapping""" if not settings.IRC_ENABLED: string = """IRC is not enabled. You need to activate it in game/settings.py.""" self.msg(string) return if 'list' in self.switches: # show all connections self.msg(_list_bots()) return if 'disconnect' in self.switches or 'remove' in self.switches or 'delete' in self.switches: botname = "ircbot-%s" % self.lhs matches = AccountDB.objects.filter(db_is_bot=True, username=botname) dbref = utils.dbref(self.lhs) if not matches and dbref: # try dbref match matches = AccountDB.objects.filter(db_is_bot=True, id=dbref) if matches: matches[0].delete() self.msg("IRC connection destroyed.") else: self.msg( "IRC connection/bot could not be removed, does it exist?") return if not self.args or not self.rhs: string = "Usage: @irc2chan[/switches] <evennia_channel> =" \ " <ircnetwork> <port> <#irchannel> <botname>[:typeclass]" self.msg(string) return channel = self.lhs self.rhs = self.rhs.replace('#', ' ') # to avoid Python comment issues try: irc_network, irc_port, irc_channel, irc_botname = \ [part.strip() for part in self.rhs.split(None, 4)] irc_channel = "#%s" % irc_channel except Exception: string = "IRC bot definition '%s' is not valid." % self.rhs self.msg(string) return botclass = None if ":" in irc_botname: irc_botname, botclass = [ part.strip() for part in irc_botname.split(":", 2) ] botname = "ircbot-%s" % irc_botname # If path given, use custom bot otherwise use default. botclass = botclass if botclass else bots.IRCBot irc_ssl = "ssl" in self.switches # create a new bot bot = AccountDB.objects.filter(username__iexact=botname) if bot: # re-use an existing bot bot = bot[0] if not bot.is_bot: self.msg("Account '%s' already exists and is not a bot." % botname) return else: try: bot = create.create_account(botname, None, None, typeclass=botclass) except Exception as err: self.msg("|rError, could not create the bot:|n '%s'." % err) return bot.start(ev_channel=channel, irc_botname=irc_botname, irc_channel=irc_channel, irc_network=irc_network, irc_port=irc_port, irc_ssl=irc_ssl) self.msg("Connection created. Starting IRC bot.")
def func(self): """Setup the Grapevine channel mapping""" if not settings.GRAPEVINE_ENABLED: self.msg("Set GRAPEVINE_ENABLED=True in settings to enable.") return if "list" in self.switches: # show all connections gwbots = [ bot for bot in AccountDB.objects.filter( db_is_bot=True, username__startswith="grapevinebot-" ) ] if gwbots: table = self.styled_table( "|wdbid|n", "|wev-channel", "|wgw-channel|n", border="cells", maxwidth=_DEFAULT_WIDTH, ) for gwbot in gwbots: table.add_row(gwbot.id, gwbot.db.ev_channel, gwbot.db.grapevine_channel) self.msg(table) else: self.msg("No grapevine bots found.") return if "disconnect" in self.switches or "remove" in self.switches or "delete" in self.switches: botname = "grapevinebot-%s" % self.lhs matches = AccountDB.objects.filter(db_is_bot=True, db_key=botname) if not matches: # try dbref match matches = AccountDB.objects.filter(db_is_bot=True, id=self.args.lstrip("#")) if matches: matches[0].delete() self.msg("Grapevine connection destroyed.") else: self.msg("Grapevine connection/bot could not be removed, does it exist?") return if not self.args or not self.rhs: string = "Usage: grapevine2chan[/switches] <evennia_channel> = <grapevine_channel>" self.msg(string) return channel = self.lhs grapevine_channel = self.rhs botname = "grapewinebot-%s-%s" % (channel, grapevine_channel) bot = AccountDB.objects.filter(username__iexact=botname) if bot: # re-use existing bot bot = bot[0] if not bot.is_bot: self.msg("Account '%s' already exists and is not a bot." % botname) return else: self.msg("Reusing bot '%s' (%s)" % (botname, bot.dbref)) else: # create a new bot bot = create.create_account(botname, None, None, typeclass=bots.GrapevineBot) bot.start(ev_channel=channel, grapevine_channel=grapevine_channel) self.msg(f"Grapevine connection created {channel} <-> {grapevine_channel}.")
def func(self): """ Guest is a child of Player typeclass. """ session = self.caller num_guests = 1 playerlist = AccountDB.objects.typeclass_search(GUEST) guest = None bans = ServerConfig.objects.conf("server_bans") addr = session.address if bans and (any(tup[2].match(session.address) for tup in bans if tup[2])): # this is a banned IP or name! string = ( "{rYou have been banned and cannot continue from here." "\nIf you feel this ban is in error, please email an admin.{x") self.dc_session(string) return try: check_vpn = settings.CHECK_VPN except AttributeError: check_vpn = False if check_vpn: # check if IP is in our whitelist white_list = ServerConfig.objects.conf("white_list") or [] if addr not in white_list: qname = (addr[::-1] + "." + str(settings.TELNET_PORTS[0]) + "." + settings.TELNET_INTERFACES[0][::-1]) try: query(qname) msg = "Guest connections from TOR are not permitted, sorry." self.dc_session(msg) return except NXDOMAIN: # not inside TOR pass api_key = getattr(settings, "HOST_BLOCKER_API_KEY", "") url = "http://tools.xioax.com/networking/v2/json/%s/%s" % ( addr, api_key, ) try: response = requests.get(url=url) data = response.json() print("Returned from xiaox: %s" % str(data)) if data["host-ip"]: self.dc_session( "Guest connections from VPNs are not permitted, sorry." ) return # the address was safe, add it to our white_list white_list.append(addr) ServerConfig.objects.conf("white_list", white_list) except Exception as err: import traceback traceback.print_exc() print("Error code on trying to check VPN:", err) for pc in playerlist: if pc.is_guest(): # add session check just to be absolutely sure we don't connect to a guest in-use if pc.is_connected or pc.sessions.all(): num_guests += 1 else: guest = pc break # create a new guest account if not guest: session.msg("All guests in use, creating a new one.") key = "Guest" + str(num_guests) playerlist = [ob.key for ob in playerlist] while key in playerlist: num_guests += 1 key = "Guest" + str(num_guests) # maximum loop check just in case if num_guests > 5000: break guest = create.create_account( key, "*****@*****.**", "DefaultGuestPassword", typeclass=GUEST, is_superuser=False, locks=None, permissions="Guests", report_to=session, ) # now connect the player to the guest account session.msg("Logging in as %s" % guest.key) session.sessionhandler.login(session, guest)
def setUp(self): self.account = create.create_account( "TestAccount%s" % randint(0, 999999), email="*****@*****.**", password="******", typeclass=DefaultAccount) self.handler = AccountSessionHandler(self.account)