1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
|
"""Nextcloud Talk API for bots."""
import dataclasses
import hashlib
import hmac
import json
import os
import typing
import httpx
from . import options
from ._misc import random_string
from ._session import BasicConfig
from .nextcloud import AsyncNextcloudApp, NextcloudApp
class ObjectContent(typing.TypedDict):
"""Object content of :py:class:`~nc_py_api.talk_bot.TalkBotMessage`."""
message: str
parameters: dict
@dataclasses.dataclass
class TalkBotMessage:
"""Talk message received by bots."""
def __init__(self, raw_data: dict):
self._raw_data = raw_data
@property
def message_type(self) -> str:
"""The type of message like Join, Leave, Create, Activity, etc."""
return self._raw_data["type"]
@property
def actor_id(self) -> str:
"""One of the attendee types followed by the ``/`` character and a unique identifier within the given type.
For the users it is the Nextcloud user ID, for guests a **sha1** value.
"""
return self._raw_data["actor"]["id"]
@property
def actor_display_name(self) -> str:
"""The display name of the attendee sending the message."""
return self._raw_data["actor"]["name"]
@property
def object_id(self) -> int:
"""The message ID of the given message on the origin server.
It can be used to react or reply to the given message.
"""
return self._raw_data["object"]["id"]
@property
def object_name(self) -> str:
"""For normal written messages ``message``, otherwise one of the known ``system message identifiers``."""
return self._raw_data["object"]["name"]
@property
def object_content(self) -> ObjectContent:
"""Dictionary with a ``message`` and ``parameters`` keys."""
return json.loads(self._raw_data["object"]["content"])
@property
def object_media_type(self) -> str:
"""``text/markdown`` when the message should be interpreted as **Markdown**, otherwise ``text/plain``."""
return self._raw_data["object"]["mediaType"]
@property
def conversation_token(self) -> str:
"""The token of the conversation in which the message was posted.
It can be used to react or reply to the given message.
"""
return self._raw_data["target"]["id"]
@property
def conversation_name(self) -> str:
"""The name of the conversation in which the message was posted."""
return self._raw_data["target"]["name"]
def __repr__(self):
return f"<{self.__class__.__name__} conversation={self.conversation_name}, actor={self.actor_display_name}>"
class TalkBot:
"""A class that implements the TalkBot functionality."""
_ep_base: str = "/ocs/v2.php/apps/spreed/api/v1/bot"
def __init__(self, callback_url: str, display_name: str, description: str = ""):
"""Class implementing Nextcloud Talk Bot functionality.
:param callback_url: FastAPI endpoint which will be assigned to bot.
:param display_name: The display name of the bot that is shown as author when it posts a message or reaction.
:param description: Description of the bot helping moderators to decide if they want to enable this bot.
"""
self.callback_url = callback_url.lstrip("/")
self.display_name = display_name
self.description = description
def enabled_handler(self, enabled: bool, nc: NextcloudApp) -> None:
"""Handles the app ``on``/``off`` event in the context of the bot.
:param enabled: Value that was passed to ``/enabled`` handler.
:param nc: **NextcloudApp** class that was passed ``/enabled`` handler.
"""
if enabled:
bot_id, bot_secret = nc.register_talk_bot(self.callback_url, self.display_name, self.description)
os.environ[bot_id] = bot_secret
else:
nc.unregister_talk_bot(self.callback_url)
def send_message(
self, message: str, reply_to_message: int | TalkBotMessage, silent: bool = False, token: str = ""
) -> tuple[httpx.Response, str]:
"""Send a message and returns a "reference string" to identify the message again in a "get messages" request.
:param message: The message to say.
:param reply_to_message: The message ID this message is a reply to.
.. note:: Only allowed when the message type is not ``system`` or ``command``.
:param silent: Flag controlling if the message should create a chat notifications for the users.
:param token: Token of the conversation.
Can be empty if ``reply_to_message`` is :py:class:`~nc_py_api.talk_bot.TalkBotMessage`.
:returns: Tuple, where fist element is :py:class:`httpx.Response` and second is a "reference string".
:raises ValueError: in case of an invalid usage.
:raises RuntimeError: in case of a broken installation.
"""
if not token and not isinstance(reply_to_message, TalkBotMessage):
raise ValueError("Either specify 'token' value or provide 'TalkBotMessage'.")
token = reply_to_message.conversation_token if isinstance(reply_to_message, TalkBotMessage) else token
reference_id = hashlib.sha256(random_string(32).encode("UTF-8")).hexdigest()
params = {
"message": message,
"replyTo": reply_to_message.object_id if isinstance(reply_to_message, TalkBotMessage) else reply_to_message,
"referenceId": reference_id,
"silent": silent,
}
return self._sign_send_request("POST", f"/{token}/message", params, message), reference_id
def react_to_message(self, message: int | TalkBotMessage, reaction: str, token: str = "") -> httpx.Response:
"""React to a message.
:param message: Message ID or :py:class:`~nc_py_api.talk_bot.TalkBotMessage` to react to.
:param reaction: A single emoji.
:param token: Token of the conversation.
Can be empty if ``message`` is :py:class:`~nc_py_api.talk_bot.TalkBotMessage`.
:raises ValueError: in case of an invalid usage.
:raises RuntimeError: in case of a broken installation.
"""
if not token and not isinstance(message, TalkBotMessage):
raise ValueError("Either specify 'token' value or provide 'TalkBotMessage'.")
message_id = message.object_id if isinstance(message, TalkBotMessage) else message
token = message.conversation_token if isinstance(message, TalkBotMessage) else token
params = {
"reaction": reaction,
}
return self._sign_send_request("POST", f"/{token}/reaction/{message_id}", params, reaction)
def delete_reaction(self, message: int | TalkBotMessage, reaction: str, token: str = "") -> httpx.Response:
"""Removes reaction from a message.
:param message: Message ID or :py:class:`~nc_py_api.talk_bot.TalkBotMessage` to remove reaction from.
:param reaction: A single emoji.
:param token: Token of the conversation.
Can be empty if ``message`` is :py:class:`~nc_py_api.talk_bot.TalkBotMessage`.
:raises ValueError: in case of an invalid usage.
:raises RuntimeError: in case of a broken installation.
"""
if not token and not isinstance(message, TalkBotMessage):
raise ValueError("Either specify 'token' value or provide 'TalkBotMessage'.")
message_id = message.object_id if isinstance(message, TalkBotMessage) else message
token = message.conversation_token if isinstance(message, TalkBotMessage) else token
params = {
"reaction": reaction,
}
return self._sign_send_request("DELETE", f"/{token}/reaction/{message_id}", params, reaction)
def _sign_send_request(self, method: str, url_suffix: str, data: dict, data_to_sign: str) -> httpx.Response:
secret = get_bot_secret(self.callback_url)
if secret is None:
raise RuntimeError("Can't find the 'secret' of the bot. Has the bot been installed?")
talk_bot_random = random_string(32)
hmac_sign = hmac.new(secret, talk_bot_random.encode("UTF-8"), digestmod=hashlib.sha256)
hmac_sign.update(data_to_sign.encode("UTF-8"))
nc_app_cfg = BasicConfig()
with httpx.Client(verify=nc_app_cfg.options.nc_cert) as client:
return client.request(
method,
url=nc_app_cfg.endpoint + "/ocs/v2.php/apps/spreed/api/v1/bot" + url_suffix,
json=data,
headers={
"X-Nextcloud-Talk-Bot-Random": talk_bot_random,
"X-Nextcloud-Talk-Bot-Signature": hmac_sign.hexdigest(),
"OCS-APIRequest": "true",
},
cookies={"XDEBUG_SESSION": options.XDEBUG_SESSION} if options.XDEBUG_SESSION else {},
timeout=nc_app_cfg.options.timeout,
)
class AsyncTalkBot:
"""A class that implements the async TalkBot functionality."""
_ep_base: str = "/ocs/v2.php/apps/spreed/api/v1/bot"
def __init__(self, callback_url: str, display_name: str, description: str = ""):
"""Class implementing Nextcloud Talk Bot functionality.
:param callback_url: FastAPI endpoint which will be assigned to bot.
:param display_name: The display name of the bot that is shown as author when it posts a message or reaction.
:param description: Description of the bot helping moderators to decide if they want to enable this bot.
"""
self.callback_url = callback_url.lstrip("/")
self.display_name = display_name
self.description = description
async def enabled_handler(self, enabled: bool, nc: AsyncNextcloudApp) -> None:
"""Handles the app ``on``/``off`` event in the context of the bot.
:param enabled: Value that was passed to ``/enabled`` handler.
:param nc: **NextcloudApp** class that was passed ``/enabled`` handler.
"""
if enabled:
bot_id, bot_secret = await nc.register_talk_bot(self.callback_url, self.display_name, self.description)
os.environ[bot_id] = bot_secret
else:
await nc.unregister_talk_bot(self.callback_url)
async def send_message(
self, message: str, reply_to_message: int | TalkBotMessage, silent: bool = False, token: str = ""
) -> tuple[httpx.Response, str]:
"""Send a message and returns a "reference string" to identify the message again in a "get messages" request.
:param message: The message to say.
:param reply_to_message: The message ID this message is a reply to.
.. note:: Only allowed when the message type is not ``system`` or ``command``.
:param silent: Flag controlling if the message should create a chat notifications for the users.
:param token: Token of the conversation.
Can be empty if ``reply_to_message`` is :py:class:`~nc_py_api.talk_bot.TalkBotMessage`.
:returns: Tuple, where fist element is :py:class:`httpx.Response` and second is a "reference string".
:raises ValueError: in case of an invalid usage.
:raises RuntimeError: in case of a broken installation.
"""
if not token and not isinstance(reply_to_message, TalkBotMessage):
raise ValueError("Either specify 'token' value or provide 'TalkBotMessage'.")
token = reply_to_message.conversation_token if isinstance(reply_to_message, TalkBotMessage) else token
reference_id = hashlib.sha256(random_string(32).encode("UTF-8")).hexdigest()
params = {
"message": message,
"replyTo": reply_to_message.object_id if isinstance(reply_to_message, TalkBotMessage) else reply_to_message,
"referenceId": reference_id,
"silent": silent,
}
return await self._sign_send_request("POST", f"/{token}/message", params, message), reference_id
async def react_to_message(self, message: int | TalkBotMessage, reaction: str, token: str = "") -> httpx.Response:
"""React to a message.
:param message: Message ID or :py:class:`~nc_py_api.talk_bot.TalkBotMessage` to react to.
:param reaction: A single emoji.
:param token: Token of the conversation.
Can be empty if ``message`` is :py:class:`~nc_py_api.talk_bot.TalkBotMessage`.
:raises ValueError: in case of an invalid usage.
:raises RuntimeError: in case of a broken installation.
"""
if not token and not isinstance(message, TalkBotMessage):
raise ValueError("Either specify 'token' value or provide 'TalkBotMessage'.")
message_id = message.object_id if isinstance(message, TalkBotMessage) else message
token = message.conversation_token if isinstance(message, TalkBotMessage) else token
params = {
"reaction": reaction,
}
return await self._sign_send_request("POST", f"/{token}/reaction/{message_id}", params, reaction)
async def delete_reaction(self, message: int | TalkBotMessage, reaction: str, token: str = "") -> httpx.Response:
"""Removes reaction from a message.
:param message: Message ID or :py:class:`~nc_py_api.talk_bot.TalkBotMessage` to remove reaction from.
:param reaction: A single emoji.
:param token: Token of the conversation.
Can be empty if ``message`` is :py:class:`~nc_py_api.talk_bot.TalkBotMessage`.
:raises ValueError: in case of an invalid usage.
:raises RuntimeError: in case of a broken installation.
"""
if not token and not isinstance(message, TalkBotMessage):
raise ValueError("Either specify 'token' value or provide 'TalkBotMessage'.")
message_id = message.object_id if isinstance(message, TalkBotMessage) else message
token = message.conversation_token if isinstance(message, TalkBotMessage) else token
params = {
"reaction": reaction,
}
return await self._sign_send_request("DELETE", f"/{token}/reaction/{message_id}", params, reaction)
async def _sign_send_request(self, method: str, url_suffix: str, data: dict, data_to_sign: str) -> httpx.Response:
secret = await aget_bot_secret(self.callback_url)
if secret is None:
raise RuntimeError("Can't find the 'secret' of the bot. Has the bot been installed?")
talk_bot_random = random_string(32)
hmac_sign = hmac.new(secret, talk_bot_random.encode("UTF-8"), digestmod=hashlib.sha256)
hmac_sign.update(data_to_sign.encode("UTF-8"))
nc_app_cfg = BasicConfig()
async with httpx.AsyncClient(verify=nc_app_cfg.options.nc_cert) as aclient:
return await aclient.request(
method,
url=nc_app_cfg.endpoint + "/ocs/v2.php/apps/spreed/api/v1/bot" + url_suffix,
json=data,
headers={
"X-Nextcloud-Talk-Bot-Random": talk_bot_random,
"X-Nextcloud-Talk-Bot-Signature": hmac_sign.hexdigest(),
"OCS-APIRequest": "true",
},
cookies={"XDEBUG_SESSION": options.XDEBUG_SESSION} if options.XDEBUG_SESSION else {},
timeout=nc_app_cfg.options.timeout,
)
def __get_bot_secret(callback_url: str) -> str:
sha_1 = hashlib.sha1(usedforsecurity=False)
string_to_hash = os.environ["APP_ID"] + "_" + callback_url.lstrip("/")
sha_1.update(string_to_hash.encode("UTF-8"))
return sha_1.hexdigest()
def get_bot_secret(callback_url: str) -> bytes | None:
"""Returns the bot's secret from an environment variable or from the application's configuration on the server."""
secret_key = __get_bot_secret(callback_url)
if secret_key in os.environ:
return os.environ[secret_key].encode("UTF-8")
secret_value = NextcloudApp().appconfig_ex.get_value(secret_key)
if secret_value is not None:
os.environ[secret_key] = secret_value
return secret_value.encode("UTF-8")
return None
async def aget_bot_secret(callback_url: str) -> bytes | None:
"""Returns the bot's secret from an environment variable or from the application's configuration on the server."""
secret_key = __get_bot_secret(callback_url)
if secret_key in os.environ:
return os.environ[secret_key].encode("UTF-8")
secret_value = await AsyncNextcloudApp().appconfig_ex.get_value(secret_key)
if secret_value is not None:
os.environ[secret_key] = secret_value
return secret_value.encode("UTF-8")
return None
|