Example #1
0
 def loop(self, handler):
     handler(None,
             TextMessage(Address("XYZ"), self.address, "/whoami"))
     handler(None, TextMessage(Address("XYZ"), self.address,
                               "Hello"))
     handler(
         None,
         MediaMessage(Address("XYZ"), self.address, MediaType.AUDIO,
                      b""))
Example #2
0
    def _on_login(
            self,
            sender: Address,
            args: Dict[str, Any],
            db_session: Session
    ):
        """
        Handles a login command
        :param sender: The sender of the message
        :param args: The command arguments
        :param db_session: The database session
        :return: None
        """

        data = {"username": args["username"], "password": args["password"]}
        response = api_request("api_key", "post", data)

        if response["status"] == "ok":
            key = ApiKey(
                kudubot_user=sender,
                tippspiel_user=args["username"],
                key=response["data"]["api_key"]
            )
            db_session.add(key)
            db_session.commit()
            reply = "Logged in successfully"
        else:
            reply = "Login unsuccessful"

        reply = TextMessage(self.connection.address, sender, reply, "Login")
        self.connection.send(reply)
Example #3
0
    def handler(_, msg):
        if msg.is_text():
            msg: TextMessage = msg

            if msg.body == "/whoami":
                sender = telegram.address
                receiver = msg.sender
                telegram.send(TextMessage(sender, receiver, receiver.address))
    def _parse_message(self, message_data: Dict[str, Any]) -> \
            Optional[Message]:
        """
        Parses the message data of a Telegram message and generates a
        corresponding Message object.
        :param message_data: The telegram message data
        :return: The generated Message object.
        :raises: InvalidMessageData if the parsing failed
        """
        address = Address(str(message_data["chat"]["id"]))

        if "text" in message_data:
            body = message_data["text"]
            self.logger.debug("Message Body: {}".format(body))
            return TextMessage(address, self.address, body)

        else:

            for media_key, media_type in {
                "photo": MediaType.IMAGE,
                "audio": MediaType.AUDIO,
                "video": MediaType.VIDEO,
                "voice": MediaType.AUDIO
            }.items():

                if media_key in message_data:

                    self.logger.debug("Media Type: {}".format(media_key))
                    media_info = message_data[media_key]

                    if len(media_info) == 0:
                        continue

                    if isinstance(media_info, list):
                        largest = media_info[len(media_info) - 1]
                        file_id = largest["file_id"]
                    elif isinstance(media_info, dict):
                        file_id = media_info["file_id"]
                    else:
                        continue

                    file_info = self.bot.get_file(file_id)
                    resp = requests.get(file_info["file_path"])
                    data = resp.content

                    return MediaMessage(
                        address,
                        self.address,
                        media_type,
                        data,
                        message_data.get("caption", "")
                    )

        raise InvalidMessageData(message_data)
Example #5
0
 def send_message(self, message_text: str):
     """
     Sends a message to the telegram chat
     :param message_text: The message text to send
     :return: None
     """
     try:
         address = Address(self.chat_id)
         message = TextMessage(Config.TELEGRAM_BOT_CONNECTION.address,
                               address, message_text)
         Config.TELEGRAM_BOT_CONNECTION.send(message)
     except AttributeError:
         app.logger.error("Failed to send telegram message: no connection")
Example #6
0
 def send_message(self, message_text: str):
     """
     Sends a message to the telegram chat
     :param message_text: The message text to send
     :return: None
     """
     address = Address(self.chat_id)
     message = TextMessage(
         Config.TELEGRAM_BOT_CONNECTION.address,
         address,
         message_text
     )
     Config.TELEGRAM_BOT_CONNECTION.send(message)
Example #7
0
 def _on_is_authorized(
         self,
         sender: Address,
         _: Dict[str, Any],
         db_session: Session
 ):
     """
     Handles an is_authorized command
     :param sender: The sender of the message
     :param _: The command arguments
     :param db_session: The database session to use
     :return: None
     """
     api_key = self._get_api_key(sender, db_session)
     reply = "yes" if api_is_authorized(api_key) else "no"
     self.connection.send(TextMessage(
         self.connection.address, sender, reply, "Authorized"
     ))
Example #8
0
    def bg_iteration(self, _: int, db_session: Session):
        """
        Implements behaviours of the Background thread that periodically
        checks if any reminders are due
        :return: None
        """
        self.logger.info("Checking for due reminders")

        for reminder in db_session.query(Reminder).all():
            api_key = self._get_api_key(reminder.kudubot_user, db_session)

            if not api_is_authorized(api_key):
                continue

            resp = api_request("match", "get", {}, api_key)
            matches = resp["data"]["matches"]

            bets = api_request("bet", "get", {}, api_key)["data"]["bets"]
            due = reminder.get_due_matches(matches, bets)

            if len(due) > 0:
                body = "Reminders for hk-tippspiel.com:\n\n"
                for match in due:
                    body += "{} vs. {}\n".format(
                        match["home_team"]["name"],
                        match["away_team"]["name"]
                    )
                msg = TextMessage(
                    self.connection.address,
                    reminder.kudubot_user,
                    body,
                    "Reminders"
                )
                self.connection.send(msg)
                last_match = max(due, key=lambda x: x["kickoff"])
                reminder.last_reminder = last_match["kickoff"]
                db_session.commit()

        self.logger.info("Finished checking for due reminders")
Example #9
0
 def receive(self) -> List[Message]:
     """
     A CLI Connection receives messages by listening to the input
     :return: A list of pending Message objects
     """
     return [TextMessage(self.address, self.address, input())]