async def _parse_message(self, opsdroid, response): """Handle logic to parse a received message. Since everyone can send a private message to any user/bot in Telegram, this method allows to set a list of whitelisted users that can interact with the bot. If any other user tries to interact with the bot the command is not parsed and instead the bot will inform that user that he is not allowed to talk with the bot. We also set self.latest_update to +1 in order to get the next available message (or an empty {} if no message has been received yet) with the method self._get_messages(). Args: opsdroid (OpsDroid): An instance of opsdroid core. response (dict): Response returned by aiohttp.ClientSession. """ for result in response["result"]: _LOGGER.debug(result) if result["message"]["text"]: user = result["message"]["from"]["username"] message = Message(result["message"]["text"], user, result["message"]["chat"], self) if not self.whitelisted_users or \ user in self.whitelisted_users: await opsdroid.parse(message) else: message.text = "Sorry, you're not allowed " \ "to speak with this bot." await self.respond(message) self.latest_update = result["update_id"] + 1
async def listen(self, opsdroid): """Listen for new message.""" while True: async with aiohttp.ClientSession() as session: data = {} if self.latest_update is not None: data["offset"] = self.latest_update async with session.post(self.build_url("getUpdates"), data=data) as resp: if resp.status != 200: _LOGGER.error("Telegram error %s, %s", resp.status, resp.text()) else: json = await resp.json() _LOGGER.debug(json) if len(json["result"]) > 0: _LOGGER.debug("Received %i messages from telegram", len(json["result"])) for response in json["result"]: _LOGGER.debug(response) if self.latest_update is None or \ self.latest_update <= response["update_id"]: self.latest_update = response["update_id"] + 1 if "message" in response: if "text" in response["message"]: if response["message"]["from"][ "id"] == self.config.get( "default_user", None): self.default_room = response[ "message"]["chat"]["id"] message = Message( response["message"]["text"], response["message"]["from"]["id"], response["message"]["chat"], self) if self.whitelisted_users is None or \ response["message"]["from"]["id"] in self.whitelisted_users: await opsdroid.parse(message) else: message.text = "Sorry you're not allowed to speak with this bot" await self.respond(message) await asyncio.sleep(self.update_interval)