Beispiel #1
0
    async def verify_member(self, member_id: str):
        """
        Verifies the member, adds him the role and marks him as verified in the database,
        also sends success messages.
        :param member_id: str member id to verify
        """
        try:
            member_id = int(member_id)
        except ValueError:
            raise EndpointBadArguments()

        none_checks = (self.tortoise_guild, self.verified_role,
                       self.unverified_role,
                       self.successful_verifications_channel)

        for check_none in none_checks:
            if check_none is None:
                raise DiscordIDNotFound()

        member = self.tortoise_guild.get_member(member_id)

        if member is None:
            raise DiscordIDNotFound()

        try:
            await member.remove_roles(self.unverified_role)
        except HTTPException:
            logger.debug(
                f"Bot could't remove unverified role {self.unverified_role}")

        await member.add_roles(self.verified_role)
        await self.successful_verifications_channel.send(
            f"{member} is now verified.")
        await member.send("You are now verified.")
Beispiel #2
0
    async def send(self, data: dict):
        """
        Makes the bot send requested message channel or user or both.
        :param data: dict in format
        {
        "channel_id": 123,
        "user_id": 123,
        "message": "Test"
        }

        Where both channel_id and user_id are optional but at least one has to be passed.
        Message is the message to send.
        """
        message = data.get("message")
        if message is None:
            raise EndpointBadArguments()

        channel_id = data.get("channel_id")
        user_id = data.get("user_id")

        if channel_id is None and user_id is None:
            raise EndpointBadArguments()

        channel = self.bot.get_channel(channel_id)
        user = self.bot.get_user(user_id)

        if channel is None and user is None:
            raise DiscordIDNotFound()

        if channel is not None:
            await channel.send(embed=thumbnail(message, self.bot.user))

        if user is not None:
            try:
                await user.send(embed=thumbnail(message, self.bot.user,
                                                "A message just for you!"))
            except Forbidden:
                logger.info(
                    f"Skipping send endpoint to {user} as he blocked DMs.")
Beispiel #3
0
 async def signal_update(self, signal: str):
     """
     Signals the bot it should update something locally like cache by fetching it from database.
     :param signal: can be:
                    'rules' signals updating rules
                    'server_meta' signals updating server meta
     """
     # Don not await here as API is waiting for response, (for some reason it sends signal and only updates db after
     # receiving any response). Use create_task instead.
     if signal == "rules":
         tortoise_server_cog = self.bot.get_cog("TortoiseServer")
         self.bot.loop.create_task(
             tortoise_server_cog.refresh_rules_helper())
     elif signal == "server_meta":
         self.bot.loop.create_task(self.bot.reload_tortoise_meta_cache())
     else:
         raise EndpointBadArguments()
Beispiel #4
0
    async def verify_member(self, member_id: str):
        """
        Adds verified role to the member and also sends success messages.
        :param member_id: str member id to verify
        """
        try:
            member_id = int(member_id)
        except ValueError:
            raise EndpointBadArguments()

        none_checks = (self.tortoise_guild, self.verified_role,
                       self.unverified_role,
                       self.successful_verifications_channel,
                       self.welcome_channel)

        for check_none in none_checks:
            if check_none is None:
                logger.info(
                    f"One of necessary IDs was not found {none_checks}")
                raise DiscordIDNotFound()

        member = self.tortoise_guild.get_member(member_id)

        if member is None:
            logger.critical(
                f"Can't verify, member is not found in guild {member} {member_id}"
            )
            raise DiscordIDNotFound()

        try:
            await member.remove_roles(self.unverified_role)
        except HTTPException:
            logger.warning(
                f"Bot could't remove unverified role {self.unverified_role}")

        await member.add_roles(self.verified_role)
        await self.successful_verifications_channel.send(
            embed=info(f"{member} is now verified.", member.guild.me, title="")
        )

        msg = (f"You are now verified {self.verified_emoji}\n\n"
               f"Make sure to read {self.welcome_channel.mention}")
        await member.send(embed=success(msg))
Beispiel #5
0
    async def process_request(self, request: dict) -> dict:
        """
        This should be called for each client request.

        Parses requests and deals with any errors and responses to client.
        :param request: dict which has to be formatted as follows:
            {
              "endpoint": "string which endpoint to use",
              "data": [optional] data to be used on endpoint function (list of member IDs etc)
            }
            Endpoint is available if it was decorated with @endpoint_register
        """
        if not isinstance(request, dict):
            logger.critical(
                "Error processing socket comm, request is not a dict.")
            return InternalServerError().response

        endpoint_key = request.get("endpoint")

        if not endpoint_key:
            return EndpointError(400, "No endpoint specified.").response
        elif not isinstance(endpoint_key, str):
            return EndpointError(400,
                                 "Endpoint name has to be a string.").response

        function = _endpoints_mapping.get(endpoint_key)

        if function is None:
            return EndpointNotFound().response

        endpoint_data = request.get("data")

        try:
            # Key data is optional
            if not endpoint_data:
                endpoint_returned_data = await function(self)
            else:
                endpoint_returned_data = await function(self, endpoint_data)
        except TypeError as e:
            logger.critical(
                f"Bad arguments for endpoint {endpoint_key} {endpoint_data} {e}"
            )
            return EndpointBadArguments().response
        except EndpointError as e:
            # If endpoint function raises then return it's response
            return e.response
        except Exception as e:
            logger.critical(
                f"Error processing socket endpoint: {endpoint_key} , data:{endpoint_data} {e}"
            )
            return InternalServerError().response

        # If we've come all the way here then no errors occurred and endpoint function executed correctly.
        server_response = EndpointSuccess().response

        # Endpoint return data is optional
        if endpoint_returned_data is None:
            return server_response
        else:
            server_response.update({"data": endpoint_returned_data})
            return endpoint_returned_data