async def wrapper(msg: Message) -> None: if msg.room: # (1) msg.parametrized_room = msg.room else: # (2) # User didn't supply any parameters if not msg.arg: await msg.user.send("Specifica il nome della room") return # Check if user supplied a non-empty roomid target_roomid = utils.to_room_id(msg.args[0], fallback=RoomId("")) msg.args = msg.args[1:] if not target_roomid: await msg.user.send("Specifica il nome della room") return msg.parametrized_room = Room.get(msg.conn, target_roomid) # Check if the room is valid if ( target_roomid not in msg.conn.rooms # bot in room or msg.user not in msg.parametrized_room # user in room ): # Send the same message for both errors to avoid leaking private rooms await msg.user.send("Sei nella room?") return # Every check passed: wrap the original function await func(msg)
async def add_user_leave(self, room: str, user: str) -> None: roomid = utils.to_room_id(room) userid = utils.to_user_id(user) await self.add_messages([ f">{roomid}", f"|l|{userid}", ])
async def add_user_join( self, room: str, user: str, rank: str = " ", *, group: str = " ", ) -> None: roomid = utils.to_room_id(room) userid = utils.to_user_id(user) await self.add_messages([ f">{roomid}", f"|j|{rank}{userid}", ]) await self.add_queryresponse_userdetails(user, group=group, rooms={roomid: rank})
def get(cls, conn: Connection, room: str) -> Room: """Safely retrieves a Room instance, if it exists, or creates a new one. Args: conn (Connection): Used to access the websocket. room (str): The room to retrieve. Returns: Room: Existing instance associated with roomid or newly created one. """ if conn not in cls._instances: cls._instances[conn] = WeakValueDictionary() roomid = utils.to_room_id(room) try: instance = cls._instances[conn][roomid] except KeyError: instance = cls._instances[conn][roomid] = cls(conn, roomid) return instance
async def make_connection( enable_commands: bool = False, *, username: str | None = None, password: str = "", avatar: str = "", statustext: str = "", rooms: list[str] | None = None, main_room: str = "lobby", command_character: str = ".", administrators: list[str] | None = None, webhooks: dict[str, str] | None = None, ) -> AsyncGenerator[Any, None]: if username is None: # Create and yield two default connections if no username is passed bot_username = env.str("USERNAME") bot_password = env.str("PASSWORD") mod_username = env.str("TESTS_MOD_USERNAME") mod_password = env.str("TESTS_MOD_PASSWORD") bot_userid = utils.to_user_id(bot_username) mod_userid = utils.to_user_id(mod_username) async with make_connection( True, username=bot_username, password=bot_password ) as bot, make_connection( username=mod_username, password=mod_password ) as mod: await bot.await_message( f'|queryresponse|userdetails|{{"id":"{mod_userid}"', startswith=True ) await mod.await_message( f'|queryresponse|userdetails|{{"id":"{bot_userid}"', startswith=True ) yield bot, mod return url = f"ws://localhost:{showdown_server}/showdown/websocket" if rooms is None: rooms = ["lobby"] if administrators is None: administrators = ["parnassius"] if webhooks is None: webhooks = {"room1": "https://discord.com/api/webhooks/00000/aaaaa"} conn = TestConnection( url=url, username=username, password=password, avatar=avatar, statustext=statustext, rooms=rooms, main_room=main_room, command_character=command_character, administrators=administrators, webhooks=webhooks, unittesting=True, ) if not enable_commands: conn.commands = {} asyncio.create_task(conn._start_websocket()) rooms_to_join = {utils.to_room_id(room) for room in rooms} while rooms_to_join: msg = await conn.recv_queue.get() msg_parts = msg.split("\n") roomname = "" if msg_parts[0][0] == ">": roomname = msg_parts[0] roomid = utils.to_room_id(roomname) if roomid not in rooms_to_join: continue if any(x.startswith("|init|") for x in msg_parts): rooms_to_join.remove(roomid) try: yield conn finally: if conn.websocket is not None: for task in asyncio.all_tasks(): if not task.get_coro().__name__.startswith("test_"): # type: ignore task.cancel() await conn.websocket.close()