Beispiel #1
0
    def _universe(self, data, connection):
        """
        Universal chat. Sends a message that everyone can see.

        :param data: The packet containing the command.
        :param connection: The connection from which the packet came.
        :return: Null
        """
        if self.plugins['chat_manager'].mute_check(connection.player):
            send_message(connection, "You are muted and cannot chat.")
            return False
        if data:
            yield from self._send_to_server(data,
                                            ChatSendMode.UNIVERSE,
                                            connection)
            if link_plugin_if_available(self, "irc_bot"):
                # Try sending it to IRC if we have that available.
                asyncio.ensure_future(
                    self.plugins["irc_bot"].bot_write(
                        "<{}> {}".format(connection.player.alias,
                                         " ".join(data))))
            if link_plugin_if_available(self, "discord_bot"):
                discord = self.plugins['discord_bot']
                asyncio.ensure_future(discord.bot.send_message(
                    discord.bot.get_channel(discord.channel),
                    "**<{}>** {}".format(connection.player.alias, " ".join(
                        data))))
            return True
Beispiel #2
0
 def _readmail(self, data, connection):
     if connection.player.uuid not in self.storage['mail']:
         self.storage['mail'][connection.player.uuid] = []
     mailbox = self.storage['mail'][connection.player.uuid]
     if data:
         try:
             index = int(data[0]) - 1
             mail = mailbox[index]
             mail.unread = False
             yield from send_message(connection, "From {} on {}: \n{}"
                                     .format(mail.author.alias,
                                             mail.time.strftime("%d %b "
                                                                "%H:%M"),
                                             mail.message))
         except ValueError:
             yield from send_message(connection, "Specify a valid number.")
         except IndexError:
             yield from send_message(connection, "No mail with that "
                                                 "number.")
     else:
         unread_mail = False
         for mail in mailbox:
             if mail.unread:
                 unread_mail = True
                 mail.unread = False
                 yield from send_message(connection, "From {} on {}: \n{}"
                                         .format(mail.author.alias,
                                                 mail.time
                                                 .strftime("%d %b %H:%M"),
                                                 mail.message))
         if not unread_mail:
             yield from send_message(connection, "No unread mail to "
                                                 "display.")
Beispiel #3
0
 def _sendmail(self, data, connection):
     if data:
         target = self.find_player(data[0])
         if not target:
             raise SyntaxWarning("Couldn't find target.")
         if not data[1]:
             raise SyntaxWarning("No message provided.")
         uid = target.uuid
         if uid not in self.storage['mail']:
             self.storage['mail'][uid] = []
         mailbox = self.storage['mail'][uid]
         if len(mailbox) >= self.max_mail:
             yield from send_message(
                 connection, "{}'s mailbox is full!".format(target.alias))
         else:
             mail = Mail(" ".join(data[1:]), connection.player)
             mailbox.insert(0, mail)
             yield from send_message(
                 connection, "Mail delivered to {}.".format(target.alias))
             if target.logged_in:
                 yield from send_message(
                     target.connection, "New mail from "
                     "{}!".format(connection.player.alias))
     else:
         raise SyntaxWarning("No target provided.")
Beispiel #4
0
 def _delmail(self, data, connection):
     uid = connection.player.uuid
     if uid not in self.storage['mail']:
         self.storage['mail'][uid] = []
     mailbox = self.storage['mail'][uid]
     if data:
         if data[0] == "all":
             self.storage['mail'][uid] = []
             yield from send_message(connection, "Deleted all mail.")
         elif data[0] == "unread":
             for mail in mailbox:
                 if mail.unread:
                     self.storage['mail'][uid].remove(mail)
             yield from send_message(connection, "Deleted all unread mail.")
         elif data[0] == "read":
             for mail in mailbox:
                 if not mail.unread:
                     self.storage['mail'][uid].remove(mail)
             yield from send_message(connection, "Deleted all read mail.")
         else:
             try:
                 index = int(data[0]) - 1
                 self.storage['mail'][uid].pop(index)
                 yield from send_message(connection,
                                         "Deleted mail {}.".format(data[0]))
             except ValueError:
                 raise SyntaxWarning("Argument must be a category or "
                                     "number. Valid categories: \"read\","
                                     " \"unread\", \"all\"")
             except IndexError:
                 yield from send_message(connection, "No message at "
                                         "that index.")
     else:
         raise SyntaxWarning("No argument provided.")
Beispiel #5
0
 def ban_by_name(self, name, reason, protocol):
     p = self.get_player_by_name(name)
     if p is not None:
         self.ban_by_ip(p.ip, reason, protocol)
     else:
         send_message(protocol,
                      "Couldn't find a player by the name %s" % name)
Beispiel #6
0
 def _readmail(self, data, connection):
     if connection.player.uuid not in self.storage['mail']:
         self.storage['mail'][connection.player.uuid] = []
     mailbox = self.storage['mail'][connection.player.uuid]
     if data:
         try:
             index = int(data[0]) - 1
             mail = mailbox[index]
             mail.unread = False
             yield from send_message(
                 connection, "From {} on {}: \n{}".format(
                     mail.author.alias, mail.time.strftime("%d %b "
                                                           "%H:%M"),
                     mail.message))
         except ValueError:
             yield from send_message(connection, "Specify a valid number.")
         except IndexError:
             yield from send_message(connection, "No mail with that "
                                     "number.")
     else:
         unread_mail = False
         for mail in mailbox:
             if mail.unread:
                 unread_mail = True
                 mail.unread = False
                 yield from send_message(
                     connection, "From {} on {}: \n{}".format(
                         mail.author.alias,
                         mail.time.strftime("%d %b %H:%M"), mail.message))
         if not unread_mail:
             yield from send_message(connection, "No unread mail to "
                                     "display.")
Beispiel #7
0
    def _protect_ship(self, connection):
        """
        Add protection to a ship.

        :param connection: Connection of player to have ship protected.
        :return: Null.
        """
        yield from asyncio.sleep(3)
        try:
            if connection.player.location.locationtype() is "ShipWorld":
                ship = connection.player.location
                uuid = connection.player.uuid
                if ship.uuid.decode("utf-8") == uuid:
                    if not self.planet_protect.check_protection(ship):
                        self.planet_protect.add_protection(
                            ship, connection.player)
                        send_message(
                            connection, "Your ship has been auto-claimed in "
                            "your name.")
                        if uuid not in self.storage["owners"]:
                            self.storage["owners"][uuid] = []
                        self.storage["owners"][uuid].append(str(ship))
                    if uuid not in self.storage["owners"]:
                        self.storage["owners"][uuid] = [str(ship)]
                    elif str(ship) not in self.storage["owners"][uuid]:
                        self.storage["owners"][uuid].append(str(ship))
        except AttributeError:
            pass
Beispiel #8
0
    def _move_ship(self, connection, location):
        """
        Generate packet that moves ship.

        :param connection: Player being moved.
        :param location: The intended destination of the player.
        :return: Null.
        :raise: NotImplementedError when POI does not exist.
        """
        if location not in self.storage["pois"]:
            send_message(connection, "That POI does not exist!")
            raise NotImplementedError
        else:
            location = self.storage["pois"][location]
            destination = data_parser.FlyShip.build(dict(
                world_x=location.x,
                world_y=location.y,
                world_z=location.z,
                location=dict(
                    type=SystemLocationType.COORDINATE,
                    world_x=location.x,
                    world_y=location.y,
                    world_z=location.z,
                    world_planet=location.planet,
                    world_satellite=location.satellite
                )
            ))
            flyship_packet = pparser.build_packet(packets.packets["fly_ship"],
                                                  destination)
            yield from connection.client_raw_write(flyship_packet)
Beispiel #9
0
def waiting_message(user_id):
    if user_id:
        utilities.send_message(user_id, {"text": "It is coming!"})
        time.sleep(1.5)
        utilities.send_message(user_id,
                               {"text": "I beg you few more seconds."})
    return
Beispiel #10
0
def handle_debug(text, id):
    if text[3:] == "waitlist":
        log_waitlisted_users()
    elif text[3:] == "update":
        update_users()
    elif text[3:] == "campaign":
        send_campaign()
    elif text[3:] == "emoticon":
        send_emoticon(id)
    elif text[3:] == "webview":
        message = {
            "attachment": {
                "type": "template",
                "payload": {
                    "template_type":
                    "button",
                    "text":
                    "Test Webview?",
                    "buttons": [{
                        "type": "web_url",
                        "url": APP_URL + "webview/",
                        "title": "Show page",
                        "webview_height_ratio": "compact"
                    }]
                }
            }
        }
        send_message(message=message, id=id)
Beispiel #11
0
    def _protect_ship(self, connection):
        """
        Add protection to a ship.

        :param connection: Connection of player to have ship protected.
        :return: Null.
        """
        yield from asyncio.sleep(.5)
        try:
            if connection.player.location.locationtype() is "ShipWorld":
                ship = connection.player.location
                alias = connection.player.alias
                if ship.player == alias:
                    if not self.planet_protect.check_protection(ship):
                        self.planet_protect. add_protection(ship,
                                                            connection.player)
                        send_message(connection,
                                     "Your ship has been auto-claimed in "
                                     "your name.")
                        if alias not in self.storage["owners"]:
                            self.storage["owners"][alias] = []
                        self.storage["owners"][alias].append(str(ship))
                    if alias not in self.storage["owners"]:
                        self.storage["owners"][alias] = [str(ship)]
                    elif str(ship) not in self.storage["owners"][alias]:
                        self.storage["owners"][alias].append(str(ship))
        except AttributeError:
            pass
 def ban_by_name(self, name, reason, protocol):
     p = self.get_player_by_name(name)
     if p is not None:
         self.ban_by_ip(p.ip, reason, protocol)
     else:
         send_message(protocol,
                      "Couldn't find a player by the name %s" % name)
 def planetary_broadcast(self, player, message):
     for p in self.players.values():
         if p.logged_in and p.location is player.location:
             send_message(p.protocol,
                          message,
                          name=p.name)
     return None
Beispiel #14
0
    def _delete_player(self, data, connection):
        """
        Removes a player from the player database. By default. you cannot
        remove a logged-in player, so either they need to be removed from
        the server first, or you have to apply the *force operation.

        :param data: The packet containing the command.
        :param connection: The connection from which the packet came.
        :return: Null.
        :raise: NameError if is not available. ValueError if player is
                currently logged in.
        """
        if data[-1] == "*force":
            force = True
            data.pop()
        else:
            force = False
        alias = " ".join(data)
        player = self.get_player_by_alias(alias)
        if player is None:
            raise NameError
        if (not force) and player.logged_in:
            raise ValueError(
                "Can't delete a logged-in player; please kick them first. If "
                "absolutely necessary, append *force to the command.")
        self.players.pop(player.uuid)
        del player
        send_message(connection, "Player {} has been deleted.".format(alias))
Beispiel #15
0
    def _here(self, data, connection):
        """
        Displays all players on the same planet as the user.

        :param data: The packet containing the command.
        :param connection: The connection from which the packet came.
        :return: Null.
        """
        ret_list = []
        location = str(connection.player.location)
        for uid in self.plugins.player_manager.players_online:
            p = self.plugins.player_manager.get_player_by_uuid(uid)
            if str(p.location) == location:
                if connection.player.perm_check(
                        "general_commands.who_clientids"):
                    ret_list.append(
                        "[^red;{}^reset;] {}{}^reset;"
                            .format(p.client_id,
                                    p.chat_prefix,
                                    p.alias))
                else:
                    ret_list.append("{}{}^reset;".format(
                        p.chat_prefix, p.alias))
        send_message(connection,
                     "{} players on planet:\n{}".format(len(ret_list),
                                                        ", ".join(ret_list)))
Beispiel #16
0
def send_pref_prompt(id):
    message = TextTemplate(
        text=
        "Whom do you want to chat with? We will notify when someone of the selected gender is waiting to chat."
    ).get_message()
    replies = [{
        "title": "Men",
        "payload": json.dumps({
            "keyword": "subscribe",
            "ans": "male"
        })
    }, {
        "title": "Women",
        "payload": json.dumps({
            "keyword": "subscribe",
            "ans": "female"
        })
    }]
    message = add_quick_reply(message,
                              title=replies[0]["title"],
                              payload=replies[0]["payload"])
    message = add_quick_reply(message,
                              title=replies[1]["title"],
                              payload=replies[1]["payload"])
    send_message(message, id)
Beispiel #17
0
 def _sendmail(self, data, connection):
     if data:
         target = self.find_player(data[0])
         if not target:
             raise SyntaxWarning("Couldn't find target.")
         if not data[1]:
             raise SyntaxWarning("No message provided.")
         uid = target.uuid
         if uid not in self.storage['mail']:
             self.storage['mail'][uid] = []
         mailbox = self.storage['mail'][uid]
         if len(mailbox) >= self.max_mail:
             yield from send_message(connection, "{}'s mailbox is full!"
                                     .format(target.alias))
         else:
             mail = Mail(" ".join(data[1:]), connection.player)
             mailbox.insert(0, mail)
             yield from send_message(connection, "Mail delivered to {}."
                                     .format(target.alias))
             if target.logged_in:
                 yield from send_message(target.connection, "New mail from "
                                                            "{}!"
                                         .format(connection.player.alias))
     else:
         raise SyntaxWarning("No target provided.")
Beispiel #18
0
    def _delete_player(self, data, connection):
        """
        Removes a player from the player database. By default. you cannot
        remove a logged-in player, so either they need to be removed from
        the server first, or you have to apply the *force operation.

        :param data: The packet containing the command.
        :param connection: The connection from which the packet came.
        :return: Null.
        :raise: NameError if is not available. ValueError if player is
                currently logged in.
        """
        if data[-1] == "*force":
            force = True
            data.pop()
        else:
            force = False
        alias = " ".join(data)
        player = self.get_player_by_alias(alias)
        if player is None:
            raise NameError
        if (not force) and player.logged_in:
            raise ValueError(
                "Can't delete a logged-in player; please kick them first. If "
                "absolutely necessary, append *force to the command.")
        self.players.pop(player.uuid)
        del player
        send_message(connection, "Player {} has been deleted.".format(alias))
Beispiel #19
0
    def _protect_ship(self, connection):
        """
        Add protection to a ship.

        :param connection: Connection of player to have ship protected.
        :return: Null.
        """
        if not hasattr(connection, "player"):
            return
        try:
            if connection.player.location.locationtype() is "ShipWorld":
                ship = connection.player.location
                uuid = connection.player.uuid
                if ship.uuid.decode("utf-8") == uuid:
                    if not self.planet_protect.check_protection(ship):
                        self.planet_protect. add_protection(ship,
                                                            connection.player)
                        send_message(connection,
                                     "Your ship has been auto-claimed in "
                                     "your name.")
                        if uuid not in self.storage["owners"]:
                            self.storage["owners"][uuid] = []
                        self.storage["owners"][uuid].append(str(ship))
                    if uuid not in self.storage["owners"]:
                        self.storage["owners"][uuid] = [str(ship)]
                    elif str(ship) not in self.storage["owners"][uuid]:
                        self.storage["owners"][uuid].append(str(ship))
        except AttributeError:
            pass
Beispiel #20
0
 def _delmail(self, data, connection):
     uid = connection.player.uuid
     if uid not in self.storage['mail']:
         self.storage['mail'][uid] = []
     mailbox = self.storage['mail'][uid]
     if data:
         if data[0] == "all":
             self.storage['mail'][uid] = []
             yield from send_message(connection, "Deleted all mail.")
         elif data[0] == "unread":
             for mail in mailbox:
                 if mail.unread:
                     self.storage['mail'][uid].remove(mail)
             yield from send_message(connection, "Deleted all unread mail.")
         elif data[0] == "read":
             for mail in mailbox:
                 if not mail.unread:
                     self.storage['mail'][uid].remove(mail)
             yield from send_message(connection, "Deleted all read mail.")
         else:
             try:
                 index = int(data[0]) - 1
                 self.storage['mail'][uid].pop(index)
                 yield from send_message(connection, "Deleted mail {}."
                                         .format(data[0]))
             except ValueError:
                 raise SyntaxWarning("Argument must be a category or "
                                     "number. Valid categories: \"read\","
                                     " \"unread\", \"all\"")
             except IndexError:
                 yield from send_message(connection, "No message at "
                                                     "that index.")
     else:
         raise SyntaxWarning("No argument provided.")
Beispiel #21
0
def send_campaign():
    message = TextTemplate(
        text="NEW FEATURE: SUBSCRIPTIONS \n\n" +
        "Hi there, this week a new feature is coming out and that is SUBSCRIPTIONS.\n\n"
        +
        "How it works: When someone gets into the Waiting List due to non availability of "
        +
        "partners, we will send out a message to our subscribed users. For example, if you "
        +
        "subscribe for women, we will notify you when a woman is looking for a partner even "
        +
        "when you are not active and hence you'll gain the chance to chat if you are free. \n\n"
        +
        "The feature will be made available to every user after one month but some users will "
        +
        "be given access to it within 1-2 days. To be eligible for getting access, LIKE our "
        +
        "page and leave a REVIEW on our page within 36 hours. Just to emphasize, please "
        +
        "complete both to be eligible. \n\nIf you have any question, post it on our page. "
        +
        "We'll guide you, but make it within the 36 hours because after that, the feature will be out."
    )
    print("IN CAMPAIGN")
    message = TextTemplate(text="F*****G TEST")
    #users = User.query.all()
    #for user in users:
    #    id = user.id
    #send_message(message, id=id)
    users = ["1708022462556195", "1145959985508112"]
    for user in users:
        send_message(message, id=user)
Beispiel #22
0
    def _move_ship(self, connection):
        """
        Generate packet that moves ship.

        :param connection: Player being moved to spawn.
        :return: Null.
        :raise: NotImplementedError when spawn planet not yet set.
        """
        if "spawn_location" not in self.storage["spawn"]:
            send_message(connection, "Spawn planet not currently set.")
            raise NotImplementedError
        else:
            spawn_location = self.storage["spawn"]["spawn_location"]
            destination = data_parser.FlyShip.build(dict(
                world_x=spawn_location.x,
                world_y=spawn_location.y,
                world_z=spawn_location.z,
                location=dict(
                    type=SystemLocationType.COORDINATE,
                    world_x=spawn_location.x,
                    world_y=spawn_location.y,
                    world_z=spawn_location.z,
                    world_planet=spawn_location.planet,
                    world_satellite=spawn_location.satellite
                )
            ))
            flyship_packet = pparser.build_packet(packets.packets["fly_ship"],
                                                  destination)
            yield from connection.client_raw_write(flyship_packet)
Beispiel #23
0
    def _nick(self, data, connection):
        """
        Change your name as it is displayed in the chat window.

        :param data: The packet containing the command.
        :param connection: The connection from which the packet came.
        :return: Null.
        """
        if len(data) > 1 and connection.player.perm_check(
                "general_commands.nick_others"):
            target = self.plugins.player_manager.find_player(data[0])
            alias = " ".join(data[1:])
        else:
            alias = " ".join(data)
            target = connection.player
        if len(data) == 0:
            alias = connection.player.name
        conflict = self.plugins.player_manager.get_player_by_alias(alias)
        if conflict and target != conflict:
            raise ValueError("There's already a user by that name.")
        else:
            clean_alias = self.plugins['player_manager'].clean_name(alias)
            if clean_alias is None:
                send_message(connection,
                             "Nickname contains no valid characters.")
                return
            old_alias = target.alias
            target.alias = clean_alias
            broadcast(connection, "{}'s name has been changed to {}".format(
                old_alias, clean_alias))
Beispiel #24
0
    def _move_ship(self, connection, location):
        """
        Generate packet that moves ship.

        :param connection: Player being moved.
        :param location: The intended destination of the player.
        :return: Null.
        :raise: NotImplementedError when POI does not exist.
        """
        if location not in self.storage["pois"]:
            send_message(connection, "That POI does not exist!")
            raise NotImplementedError
        else:
            location = self.storage["pois"][location]
            destination = data_parser.FlyShip.build(
                dict(world_x=location.x,
                     world_y=location.y,
                     world_z=location.z,
                     location=dict(type=SystemLocationType.COORDINATE,
                                   world_x=location.x,
                                   world_y=location.y,
                                   world_z=location.z,
                                   world_planet=location.planet,
                                   world_satellite=location.satellite)))
            flyship_packet = pparser.build_packet(packets.packets["fly_ship"],
                                                  destination)
            yield from connection.client_raw_write(flyship_packet)
Beispiel #25
0
    def run_command(self, command, connection, to_parse):
        """
        Evaluate the command passed in, passing along the arguments. Raise
        various errors depending on what might have gone wrong.

        :param command: Command to be executed. Looked up in commands dict.
        :param connection: Connection which is calling the command.
        :param to_parse: Arguments to provide to the command.
        :return: Null.
        :raise: SyntaxWarning on improper syntax usage. NameError when object
                could not be found. ValueError when improper input is provided.
                General Exception error as a last-resort catch-all.
        """
        try:
            yield from self.commands[command](extractor(to_parse),
                                              connection)
        except SyntaxWarning as e:
            self._send_syntax_error(command, e, connection)
        except NameError as e:
            self._send_name_error(e, connection)
        except ValueError as e:
            send_message(connection, str(e))
        except SystemExit as e:
            raise SystemExit
        except:
            self.logger.exception("Unknown exception encountered. Ignoring.",
                                  exc_info=True)
Beispiel #26
0
    def _move_ship(self, connection):
        """
        Generate packet that moves ship.

        :param connection: Player being moved to spawn.
        :return: Null.
        :raise: NotImplementedError when spawn planet not yet set.
        """
        if "spawn_location" not in self.storage["spawn"]:
            send_message(connection, "Spawn planet not currently set.")
            raise NotImplementedError
        else:
            spawn_location = self.storage["spawn"]["spawn_location"]
            destination = data_parser.FlyShip.build(
                dict(world_x=spawn_location.x,
                     world_y=spawn_location.y,
                     world_z=spawn_location.z,
                     location=dict(type=SystemLocationType.COORDINATE,
                                   world_x=spawn_location.x,
                                   world_y=spawn_location.y,
                                   world_z=spawn_location.z,
                                   world_planet=spawn_location.planet,
                                   world_satellite=spawn_location.satellite)))
            flyship_packet = pparser.build_packet(packets.packets["fly_ship"],
                                                  destination)
            yield from connection.client_raw_write(flyship_packet)
Beispiel #27
0
 def _socialspy(self, data, connection):
     if connection.player in self.social_spies:
         self.social_spies.remove(connection.player)
         yield from send_message(connection, "Social spy disabled.")
     else:
         self.social_spies.add(connection.player)
         yield from send_message(connection, "Social spy enabled.")
Beispiel #28
0
 def who(self, data, protocol):
     ret_list = []
     for player in self.plugins['player_manager'].players.values():
         if player.logged_in:
             ret_list.append(player.name)
     send_message(protocol,
                  "%d players online: %s" % (len(ret_list),
                                             ", ".join(ret_list)))
Beispiel #29
0
 def _purge_claims(self, data, connection):
     target = self.plugins.player_manager.find_player(" ".join(data))
     if target.uuid in self.storage['owners']:
         self.storage['owners'][target.uuid] = []
         yield from send_message(connection, "Purged claims of {}"
                                 .format(target.alias))
     else:
         yield from send_message(connection, "Target has no claims.")
Beispiel #30
0
 def send_name_error(self, player_name, protocol):
     """
     Sends an error about an incorrect player name.
     :param player_name: The non-existent player's name
     :param protocol: The active player protocol.
     :return: None
     """
     send_message(protocol, "Unknown player %s" % player_name)
     return None
Beispiel #31
0
def invite_new_user(r):
    content = request.get_json()
    necessary_values = ['phone', 'contacted', 'inviter_identifier']
    isGoodRequest = check_for_values_in_request(necessary_values, content)
    if (isGoodRequest[0] == False):
        return make_response(
            {
                'response':
                'bad request, please try again and specify the ' +
                str(isGoodRequest[1]) +
                ' parameter(s) in the JSON request body.'
            }, status.HTTP_400_BAD_REQUEST)

    phone = content['phone']
    contacted = content['contacted']
    inviter_identifier = content['inviter_identifier']

    invite_message = "You've been invited to download Exposeure, an app that helps you track your exposure to COVID-19! Find out more at getmyexposure.com"
    if (contacted == "False"):
        didSend = send_message(invite_message, phone)
        if didSend:
            return make_response(
                {
                    'response':
                    'sent messsage to' + str(phone) + 'successfully!'
                }, status.HTTP_200_OK)
        else:
            return make_response(
                {
                    'response':
                    'did not send messsage to' + str(phone) + 'successfully.'
                }, status.HTTP_200_OK)
    else:
        proto_user = retrieve_or_create_protouser_from_number(phone)
        current_proto_user_contacts = proto_user.contactedIds
        current_proto_user_contacts.append(inviter_identifier)
        proto_user.contactedIds = current_proto_user_contacts
        proto_user.save()
        proto_user_id = proto_user.identifier
        #link this identifier in redis to the push notification feature.
        r.set(str(proto_user_id), phone)

        didSend = send_message(invite_message, phone)
        if didSend:
            return make_response(
                {
                    'response':
                    'sent messsage to' + str(phone) + 'successfully!',
                    'new_identifier': proto_user_id
                }, status.HTTP_200_OK)
        else:
            return make_response(
                {
                    'response':
                    'did not send messsage to' + str(phone) + 'successfully.',
                    'new_identifier': proto_user_id
                }, status.HTTP_200_OK)
Beispiel #32
0
 def list_builders(self, data, protocol):
     if not self.check_protection(protocol.player.location):
         send_message(protocol, "This location has never been" "protected.")
     else:
         protection = self.get_protection(protocol.player.location)
         players = ", ".join(protection.get_builders())
         send_message(
             protocol, "Players allowed to build at location "
             "'%s': %s" % (protocol.player.location, players))
 def send_name_error(self, player_name, protocol):
     """
     Sends an error about an incorrect player name.
     :param player_name: The non-existent player's name
     :param protocol: The active player protocol.
     :return: None
     """
     send_message(protocol, "Unknown player %s" % player_name)
     return None
Beispiel #34
0
 def protect_ship(self, protocol):
     yield from asyncio.sleep(.5)
     if isinstance(protocol.player.location, Ship):
         ship = protocol.player.location
         if not self.check_protection(ship):
             if ship.player == protocol.player.name:
                 self.add_protection(ship, protocol.player)
                 send_message(protocol,
                              "Your ship has been auto-protected.")
 def protect_ship(self, protocol):
     yield from asyncio.sleep(.5)
     if isinstance(protocol.player.location, Ship):
         ship = protocol.player.location
         if not self.check_protection(ship):
             if ship.player == protocol.player.name:
                 self.add_protection(ship, protocol.player)
                 send_message(protocol,
                              "Your ship has been auto-protected.")
Beispiel #36
0
 def whois(self, data, protocol):
     if len(data) == 0:
         raise SyntaxWarning
     name = " ".join(data)
     info = self.plugins['player_manager'].get_player_by_name(name)
     if info is not None:
         send_message(protocol, self.generate_whois(info))
     else:
         send_message(protocol, "Player not found!")
Beispiel #37
0
 def list_bans(self, data, protocol):
     if len(self.shelf['bans'].keys()) == 0:
         send_message(protocol, "There are no active bans.")
     else:
         res = ["Active bans:"]
         for ban in self.shelf['bans'].values():
             res.append("IP: %(ip)s - "
                        "Reason: %(reason)s - "
                        "Banned by: %(banned_by)s" % ban.__dict__)
         send_message(protocol, "\n".join(res))
 def list_builders(self, data, protocol):
     if not self.check_protection(protocol.player.location):
         send_message(protocol, "This location has never been"
                                "protected.")
     else:
         protection = self.get_protection(protocol.player.location)
         players = ", ".join(protection.get_builders())
         send_message(protocol, "Players allowed to build at location "
                                "'%s': %s" % (protocol.player.location,
                                              players))
 def del_builder(self, data, protocol):
     p = self.plugins.player_manager.get_player_by_name(" ".join(data))
     if p is not None:
         protection = self.get_protection(protocol.player.location)
         protection.del_builder(p)
         send_message(protocol,
                      "Removed player from build list for this location.")
     else:
         send_message(protocol, "Couldn't find a player with name "
                                "%s" % " ".join(data))
 def list_bans(self, data, protocol):
     if len(self.shelf['bans'].keys()) == 0:
         send_message(protocol, "There are no active bans.")
     else:
         res = ["Active bans:"]
         for ban in self.shelf['bans'].values():
             res.append("IP: %(ip)s - "
                        "Reason: %(reason)s - "
                        "Banned by: %(banned_by)s" % ban.__dict__)
         send_message(protocol, "\n".join(res))
Beispiel #41
0
    def _whoami(self, data, connection):
        """
        Displays your current nickname and connection information.

        :param data: The packet containing the command.
        :param connection: The connection from which the packet came.
        :return: Null.
        """
        send_message(connection,
                     self.generate_whois(connection.player))
Beispiel #42
0
    def _send_name_error(self, player_name, connection):
        """
        Sends an error about an incorrect player name.

        :param player_name: The non-existent player's name
        :param connection: The active player connection.
        :return: None
        """
        send_message(connection, "Unknown player {}".format(player_name))
        return None
Beispiel #43
0
 def _add_helper(self, data, connection):
     location = connection.player.location
     alias = connection.player.alias
     target = self.plugins.player_manager.get_player_by_alias(
         " ".join(data))
     if target is not None:
         if not self.is_owner(alias, location):
             send_message(connection, "You don't own this planet!")
         else:
             protection = self.planet_protect.get_protection(location)
             protection.add_builder(target)
             try:
                 send_message(
                     connection, "Granted build access to player"
                     " {}.".format(target.alias))
                 yield from send_message(
                     target.connection, "You've been "
                     "granted build "
                     "access on {}.".format(location))
             except AttributeError:
                 send_message(
                     connection, "Player {} isn't online, granted "
                     "build access anyways.".format(target.alias))
     else:
         send_message(
             connection,
             "Player {} could not be found.".format(" ".join(data)))
Beispiel #44
0
 def del_builder(self, data, protocol):
     p = self.plugins.player_manager.get_player_by_name(" ".join(data))
     if p is not None:
         protection = self.get_protection(protocol.player.location)
         protection.del_builder(p)
         send_message(protocol,
                      "Removed player from build list for this location.")
     else:
         send_message(
             protocol, "Couldn't find a player with name "
             "%s" % " ".join(data))
Beispiel #45
0
 def list_players(self, data, protocol):
     players = [player for player in self.players.values()]
     players.sort(key=attrgetter('name'))
     send_message(protocol, "%d players found:" % len(players))
     for x, player in enumerate(players):
         player_info = "  %d. %s%s"
         if player.logged_in:
             l = " (logged-in)"
         else:
             l = ""
         send_message(protocol, player_info % (x + 1, player.name, l))
 def list_players(self, data, protocol):
     players = [player for player in self.players.values()]
     players.sort(key=attrgetter('name'))
     send_message(protocol,
                  "%d players found:" % len(players))
     for x, player in enumerate(players):
         player_info = "  %d. %s%s"
         if player.logged_in:
             l = " (logged-in)"
         else:
             l = ""
         send_message(protocol, player_info % (x + 1, player.name, l))
    def _whoami(self, data, connection):
        """
        Displays your current nickname and connection information.

        :param data: The packet containing the command.
        :param connection: The connection from which the packet came.
        :return: Null.
        """
        # TODO: currently this is buggy, and will sometime not work...
        # instead, the Starbound version of /whoami will take over.
        send_message(connection,
                     self.generate_whois(connection.player))
Beispiel #48
0
 def _display_unread(self, connection):
     yield from asyncio.sleep(3)
     if connection.player.uuid not in self.storage['mail']:
         self.storage['mail'][connection.player.uuid] = []
     mailbox = self.storage['mail'][connection.player.uuid]
     unread_count = len([x for x in mailbox if x.unread])
     mail_count = len(mailbox)
     if unread_count > 0:
         yield from send_message(connection, "You have {} unread messages."
                                 .format(unread_count))
     if mail_count >= self.max_mail * 0.8:
         yield from send_message(connection, "Your mailbox is almost full!")
Beispiel #49
0
    def _unprotect(self, data, connection):
        """
        Unprotect a location. Location is taken for the player's current
        location.

        :param data: The packet containing the command.
        :param connection: The connection from which the packet came.
        :return: Null.
        """
        location = connection.player.location
        self.disable_protection(location)
        send_message(connection, "Unprotected location ()".format(location))
    def _give_item(self, data, connection):
        """
        Give item(s) to a player.

        :param data: The packet containing the command.
        :param connection: The connection from which the packet came.
        :return: Null.
        :raise: SyntaxWarning if too many arguments provided or item count
                cannot be properly converted. NameError if a target player
                cannot be resolved.
        """
        arg_count = len(data)
        target = self.plugins.player_manager.find_player(data[0])
        if arg_count == 1:
            target = connection.player
            item = data[0]
            count = 1
        elif arg_count == 2:
            if data[1].isdigit():
                target = connection.player
                item = data[0]
                count = int(data[1])
            else:
                item = data[1]
                count = 1
        elif arg_count == 3:
            item = data[1]
            if not data[2].isdigit():
                raise SyntaxWarning("Couldn't convert %s to an item count." %
                                    data[2])
            count = int(data[2])
        else:
            raise SyntaxWarning("Too many arguments")
        if target is None:
            raise NameError(target)
        target = target.connection
        if count > 10000 and item != "money":
            count = 10000
        item_base = data_parser.GiveItem.build(dict(name=item,
                                                    count=count,
                                                    variant_type=7,
                                                    description=""))
        item_packet = pparser.build_packet(packets.packets['give_item'],
                                           item_base)
        yield from target.raw_write(item_packet)
        send_message(connection,
                     "Gave {} (count: {}) to {}".format(
                         item,
                         count,
                         target.player.alias))
        send_message(target, "{} gave you {} (count: {})".format(
            connection.player.alias, item, count))
Beispiel #51
0
    def unban_by_ip(self, ip, connection):
        """
        Unban a player based on their IP address. Should be compatible with both
        IPv4 and IPv6.

        :param ip: String: IP of player to be unbanned.
        :param connection: Connection of target player to be unbanned.
        :return: Null
        """
        # ban = IPBan(ip, reason, connection.player.alias)
        del self.shelf["bans"][ip]
        send_message(connection,
                     "Ban removed: {}".format(ip))
Beispiel #52
0
    def _show_spawn(self, data, connection):
        """
        Display the coordinates of the current spawn location.

        :param data: The packet containing the command.
        :param connection: The connection from which the packet came.
        :return: Null.
        """
        if "spawn_location" not in self.storage["spawn"]:
            send_message(connection, "Spawn planet not currently set.")
        else:
            spawn_location = self.storage["spawn"]["spawn_location"]
            send_message(connection, "{}".format(spawn_location))