repo
stringclasses 856
values | pull_number
int64 3
127k
| instance_id
stringlengths 12
58
| issue_numbers
sequencelengths 1
5
| base_commit
stringlengths 40
40
| patch
stringlengths 67
1.54M
| test_patch
stringlengths 0
107M
| problem_statement
stringlengths 3
307k
| hints_text
stringlengths 0
908k
| created_at
timestamp[s] |
---|---|---|---|---|---|---|---|---|---|
opsdroid/opsdroid | 913 | opsdroid__opsdroid-913 | [
"905"
] | 9ab9d65646540e20ca12dc3c8af1d83d0cb1861f | diff --git a/opsdroid/connector/matrix/connector.py b/opsdroid/connector/matrix/connector.py
--- a/opsdroid/connector/matrix/connector.py
+++ b/opsdroid/connector/matrix/connector.py
@@ -140,7 +140,8 @@ async def listen(self): # pragma: no cover
filter=self.filter_id)
_LOGGER.debug("matrix sync request returned")
message = await self._parse_sync_response(response)
- await self.opsdroid.parse(message)
+ if message:
+ await self.opsdroid.parse(message)
except MatrixRequestError as mre:
# We can safely ignore timeout errors. The non-standard error
@@ -201,7 +202,7 @@ def _get_formatted_message_body(message, body=None, msgtype="m.text"):
"msgtype": msgtype,
"format": "org.matrix.custom.html",
"formatted_body": clean_html
- }
+ }
@register_event(Message)
async def send_message(self, message):
| Matrix connector tries to parse empty messages
Talked about this in opsdroid-general: the matrix connector tries to parse empty messages (like ones sent from the bot itself). We should avoid this by checking that the message is not `None` before parsing. Cadair pointed out that we can do this with `if message:` above L143 in the connector.
https://github.com/opsdroid/opsdroid/blob/11508b513ea563a58fc95581b7032256449c65c1/opsdroid/connector/matrix/connector.py#L143
| 2019-04-26T08:50:53 |
||
opsdroid/opsdroid | 930 | opsdroid__opsdroid-930 | [
"928"
] | 7ed0eeebb29ca89aef315e0277b826ef6299837b | diff --git a/opsdroid/parsers/crontab.py b/opsdroid/parsers/crontab.py
--- a/opsdroid/parsers/crontab.py
+++ b/opsdroid/parsers/crontab.py
@@ -1,5 +1,5 @@
"""A helper function for parsing and executing crontab skills."""
-
+import time
import asyncio
import logging
@@ -14,7 +14,7 @@ async def parse_crontab(opsdroid):
"""Parse all crontab skills against the current time."""
while opsdroid.eventloop.is_running():
await asyncio.sleep(60 - arrow.now().time().second)
- _LOGGER.debug(_("Running crontab skills"))
+ _LOGGER.debug(_("Running crontab skills at %s "), time.asctime())
for skill in opsdroid.skills:
for matcher in skill.matchers:
if "crontab" in matcher:
| Add time to crontab log message
When the cron parser is triggered it emits a debug log saying `Running crontab skills`.
It would be more useful if it included the time that opsdroid thinks it is. This would help when trying to debug issues where skills are triggered at the wrong time due to opsdroid having the wrong timezone.
The line which needs updating is [here](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/parsers/crontab.py#L17).
| 2019-05-11T12:29:48 |
||
opsdroid/opsdroid | 940 | opsdroid__opsdroid-940 | [
"934"
] | 41e95f69cd53dd0624a46bbd1bbdebac3419e1f8 | diff --git a/opsdroid/core.py b/opsdroid/core.py
--- a/opsdroid/core.py
+++ b/opsdroid/core.py
@@ -464,7 +464,7 @@ async def parse(self, event):
self.eventloop.create_task(
self.run_skill(ranked_skills[0]["skill"],
ranked_skills[0]["config"],
- event)))
+ ranked_skills[0]["message"])))
return tasks
diff --git a/opsdroid/parsers/parseformat.py b/opsdroid/parsers/parseformat.py
--- a/opsdroid/parsers/parseformat.py
+++ b/opsdroid/parsers/parseformat.py
@@ -1,7 +1,6 @@
"""A helper function for parsing and executing parse_format skills."""
import logging
-import copy
from parse import parse, search
@@ -31,13 +30,12 @@ async def parse_format(opsdroid, skills, message):
opts = matcher["parse_format"]
result = await match_format(message.text, opts)
if result:
- new_message = copy.copy(message)
- new_message.parse_result = result
+ message.parse_result = result
matched_skills.append({
"score": await calculate_score(
opts["expression"], opts["score_factor"]),
"skill": skill,
"config": skill.config,
- "message": new_message
+ "message": message
})
return matched_skills
diff --git a/opsdroid/parsers/regex.py b/opsdroid/parsers/regex.py
--- a/opsdroid/parsers/regex.py
+++ b/opsdroid/parsers/regex.py
@@ -2,7 +2,6 @@
import logging
import re
-import copy
_LOGGER = logging.getLogger(__name__)
@@ -39,13 +38,12 @@ async def parse_regex(opsdroid, skills, message):
opts = matcher["regex"]
regex = await match_regex(message.text, opts)
if regex:
- new_message = copy.copy(message)
- new_message.regex = regex
+ message.regex = regex
matched_skills.append({
"score": await calculate_score(
opts["expression"], opts["score_factor"]),
"skill": skill,
"config": skill.config,
- "message": new_message
+ "message": message
})
return matched_skills
| diff --git a/tests/test_parser_format.py b/tests/test_parser_format.py
--- a/tests/test_parser_format.py
+++ b/tests/test_parser_format.py
@@ -35,6 +35,9 @@ async def test_parse_format_match_condition(self):
message = Message("Hello", "user", "default", mock_connector)
skills = await parse_format(opsdroid, opsdroid.skills, message)
self.assertEqual(mock_skill, skills[0]["skill"])
+ assert skills[0]["message"] is message
+ # test that the original object has had a new attribute added
+ assert hasattr(message, "parse_result")
async def test_parse_format_search_condition(self):
with OpsDroid() as opsdroid:
diff --git a/tests/test_parser_regex.py b/tests/test_parser_regex.py
--- a/tests/test_parser_regex.py
+++ b/tests/test_parser_regex.py
@@ -37,6 +37,9 @@ async def test_parse_regex(self):
skills = await parse_regex(opsdroid, opsdroid.skills, message)
self.assertEqual(mock_skill, skills[0]["skill"])
+ assert skills[0]["message"] is message
+ # test that the original object has had a new attribute added
+ assert hasattr(message, "regex")
async def test_parse_regex_priority_low(self):
with OpsDroid() as opsdroid:
| Regex.group broke after events got merged into core
<!-- Before you post an issue or if you are unsure about something join our gitter channel https://gitter.im/opsdroid/ and ask away! We are more than happy to help you. -->
# Description
After the events PR was merged to Core an `AttributeError` exception is raised when we try to get a regex group.
The issue stars in `opsdroid.core` on [line 467](https://github.com/opsdroid/opsdroid/blob/d1d25927107892008f62e6bf83d4f82fb994736c/opsdroid/core.py#L467)
And possibly something in `opsdroid.events` is not parsing the regex groups.
## Steps to Reproduce
Have a skill that tries to get a regex group from a sentence.
## Expected Functionality
Opsdroid should be able to use that group in the reply.
## Experienced Functionality
An `AttributeError` exception is raised
_Note: This is a very broad issue. I'll be more than happy to dig deeper into it if needed._
| Does the event have the `regex` property at all?
I am going to assume tht it might be something related to how the message is being parsed. Before the events that line was `ranked_skills[0]["message"]` so I guess the Message class is just calling the parsers but not any of the specific methods of that parser? 🤔
I was just about writing and issue about this!
Version 0.15 brokes regex (and parseformat, but let's focus on regex), and I discovered the reason.
In `parse_regex`, regex makes a copy of the Message object instead of directly mutating it:
```python
new_message = copy.copy(message)
new_message.regex = regex
matched_skills.append({
"score": await calculate_score(
opts["expression"], opts["score_factor"]),
"skill": skill,
"config": skill.config,
"message": new_message
})
```
Other parsers like the NLU ones directly mutates the original message.
The problem is that Opsdroid ignores the `message` key of the `matched_skills`, as you can see in `core.py -> parse`:
```python
tasks.append(
self.eventloop.create_task(
self.run_skill(ranked_skills[0]["skill"],
ranked_skills[0]["config"],
event)))
```
As you can see, it runs the skill with the original event and ignores the `message` key of the ranked_skills where regex put the new message.
An easy and fast fix is to mutate the original message as before, but I think that we need to think how to redesign this part to avoid that kind of mutations :thinking:
My suggestion here would be to mutate the original message.
As raised in #933 I'm keen to move from mutating attributes like `message.regex` to adding to a static dictionary attribute like `message.raw_parses['regex']`. | 2019-05-15T08:44:48 |
opsdroid/opsdroid | 943 | opsdroid__opsdroid-943 | [
"942"
] | d89f42c967b5a3c5ba0869d24601675174f30daf | diff --git a/opsdroid/web.py b/opsdroid/web.py
--- a/opsdroid/web.py
+++ b/opsdroid/web.py
@@ -64,7 +64,7 @@ def get_host(self):
try:
host = self.config["host"]
except KeyError:
- host = '127.0.0.1'
+ host = '0.0.0.0'
return host
@property
| diff --git a/tests/test_web.py b/tests/test_web.py
--- a/tests/test_web.py
+++ b/tests/test_web.py
@@ -38,11 +38,11 @@ async def test_web_get_host(self):
with OpsDroid() as opsdroid:
opsdroid.config["web"] = {}
app = web.Web(opsdroid)
- self.assertEqual(app.get_host, "127.0.0.1")
+ self.assertEqual(app.get_host, "0.0.0.0")
- opsdroid.config["web"] = {"host": "0.0.0.0"}
+ opsdroid.config["web"] = {"host": "127.0.0.1"}
app = web.Web(opsdroid)
- self.assertEqual(app.get_host, "0.0.0.0")
+ self.assertEqual(app.get_host, "127.0.0.1")
async def test_web_get_ssl(self):
"""Check the host getter."""
| Make web server default to all networks
Currently the opsdroid web server is only served on `127.0.0.1` by default. In order to make opsdroid accessible via other networks you much set the `web.host` config option to something else (usually `0.0.0.0`).
This can be misleading for new users and is also causing problems when running on more complex infrastructure like Kubernetes.
I propose that the default is changed to `0.0.0.0` which resolves up front issues but still allows users to lock things down to specific networks if they choose.
| 2019-05-15T13:19:01 |
|
opsdroid/opsdroid | 946 | opsdroid__opsdroid-946 | [
"944",
"944"
] | 2b4b3039cf8d704677ee82c2ec957c7dc2369449 | diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -55,6 +55,7 @@ def run(self):
author_email='[email protected]',
description='An open source ChatOps bot framework.',
long_description=README,
+ long_description_content_type='text/markdown',
packages=PACKAGES,
include_package_data=True,
zip_safe=False,
| PyPI deployments are failing
Looks like PyPI deployments are failing. `v0.15.1` and `v0.15.2` haven't gone out.
```
HTTPError: 400 Client Error: The description failed to render in the default format of reStructuredText. See https://pypi.org/help/#description-content-type for more information. for url: https://upload.pypi.org/legacy/
```
PyPI deployments are failing
Looks like PyPI deployments are failing. `v0.15.1` and `v0.15.2` haven't gone out.
```
HTTPError: 400 Client Error: The description failed to render in the default format of reStructuredText. See https://pypi.org/help/#description-content-type for more information. for url: https://upload.pypi.org/legacy/
```
| Looks [related](https://github.com/pypa/warehouse/issues/4079#issuecomment-420929642) to the py35 setuptools issue. #941
Looks [related](https://github.com/pypa/warehouse/issues/4079#issuecomment-420929642) to the py35 setuptools issue. #941 | 2019-05-15T16:35:45 |
|
opsdroid/opsdroid | 960 | opsdroid__opsdroid-960 | [
"953"
] | 1c0f9048e2ca575088191552a5df803dd9602ad9 | diff --git a/opsdroid/__main__.py b/opsdroid/__main__.py
--- a/opsdroid/__main__.py
+++ b/opsdroid/__main__.py
@@ -115,8 +115,8 @@ def get_logging_level(logging_level):
def check_dependencies():
"""Check for system dependencies required by opsdroid."""
- if sys.version_info.major < 3 or sys.version_info.minor < 5:
- logging.critical(_("Whoops! opsdroid requires python 3.5 or above."))
+ if sys.version_info.major < 3 or sys.version_info.minor < 6:
+ logging.critical(_("Whoops! opsdroid requires python 3.6 or above."))
sys.exit(1)
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -71,7 +71,6 @@ def run(self):
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only',
- 'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Communications :: Chat',
| diff --git a/tests/test_main.py b/tests/test_main.py
--- a/tests/test_main.py
+++ b/tests/test_main.py
@@ -157,6 +157,22 @@ def test_check_version_35(self):
with mock.patch.object(sys, 'version_info') as version_info:
version_info.major = 3
version_info.minor = 5
+ with self.assertRaises(SystemExit):
+ opsdroid.check_dependencies()
+
+ def test_check_version_36(self):
+ with mock.patch.object(sys, 'version_info') as version_info:
+ version_info.major = 3
+ version_info.minor = 6
+ try:
+ opsdroid.check_dependencies()
+ except SystemExit:
+ self.fail("check_dependencies() exited unexpectedly!")
+
+ def test_check_version_37(self):
+ with mock.patch.object(sys, 'version_info') as version_info:
+ version_info.major = 3
+ version_info.minor = 7
try:
opsdroid.check_dependencies()
except SystemExit:
| Should we drop Python 3.5 support
It has been raised a few times in the Matrix chat that we should consider dropping Python 3.5 support.
There are a number of improvements in [Python 3.6](https://docs.python.org/3/whatsnew/3.6.html) which we could benefit from. This would also be a breaking change for users still on 3.5 and will require them to upgrade to continue using opsdroid.
The reason this has cropped up for me again is because there appears to be a bug still in 3.5.7 which causes problems with catching exceptions within coroutines. This problem is not present in 3.6.8. I would rather not have to work around this bug if I can help it.
We decided to support 3.5+ because that is the default version which comes pre-installed on the latest release of Debian and variations like Raspbian. This should ensure good support for many users without them having to tinker with their Python and provide a good beginner experience.
As this is an open source software project with a motivation around self hosting and privacy it isn't possible to collect user metrics on Python versions being used. Otherwise we could use this data to asses the impact of dropping 3.5.
[Home Assistant](https://www.home-assistant.io/) (the project which inspired much of opsdroid's community practices) are moving to only supporting the two most recent minor versions of Python, which means they will also be dropping 3.5 in the near future.
My proposal would be to follow their lead. This does put a responsibility on us to keep an eye on Python releases (3.8 is [pencilled in](https://www.python.org/dev/peps/pep-0569/) for the end of the year) and remove support as versions are released.
I would love thoughts and feedback from the community.
| I am all in favour of this. Supporting older versions of Python (and other libs) can cause a lot of extra work and it's really not that hard to find a way of installing a newer Python interpretor. (Docker, debian backports, conda etc)
I'm happy with this as well. I have got a raspbian and was pretty easy to update the python version so perhaps it could be good to drop 3.5 especially after the issues we were having on appveyor.
I'm also on board with dropping 3.5. All hail f-strings! | 2019-05-27T10:00:28 |
opsdroid/opsdroid | 962 | opsdroid__opsdroid-962 | [
"717"
] | 37018a1ab4cab1b7eafeb99e3a9561ec7e44e2b4 | diff --git a/opsdroid/connector/rocketchat/__init__.py b/opsdroid/connector/rocketchat/__init__.py
--- a/opsdroid/connector/rocketchat/__init__.py
+++ b/opsdroid/connector/rocketchat/__init__.py
@@ -35,6 +35,9 @@ def __init__(self, config, opsdroid=None):
self.bot_name = config.get("bot-name", "opsdroid")
self.listening = True
self.latest_update = datetime.datetime.utcnow().isoformat()
+ self._closing = asyncio.Event()
+ self.loop = asyncio.get_event_loop()
+ self.session = None
try:
self.user_id = config["user-id"]
@@ -73,15 +76,14 @@ async def connect(self):
"""
_LOGGER.info("Connecting to Rocket.Chat")
-
- async with aiohttp.ClientSession() as session:
- resp = await session.get(self.build_url("me"), headers=self.headers)
- if resp.status != 200:
- _LOGGER.error("Unable to connect.")
- _LOGGER.error("Rocket.Chat error %s, %s", resp.status, resp.text)
- else:
- json = await resp.json()
- _LOGGER.debug("Connected to Rocket.Chat as %s", json["username"])
+ self.session = aiohttp.ClientSession()
+ resp = await self.session.get(self.build_url("me"), headers=self.headers)
+ if resp.status != 200:
+ _LOGGER.error("Unable to connect.")
+ _LOGGER.error("Rocket.Chat error %s, %s", resp.status, resp.text)
+ else:
+ json = await resp.json()
+ _LOGGER.debug("Connected to Rocket.Chat as %s", json["username"])
async def _parse_message(self, response):
"""Parse the message received.
@@ -124,8 +126,8 @@ async def _get_message(self):
if self.latest_update:
url += "&oldest={}".format(self.latest_update)
- async with aiohttp.ClientSession() as session:
- resp = await session.get(url, headers=self.headers)
+ await asyncio.sleep(self.update_interval)
+ resp = await self.session.get(url, headers=self.headers)
if resp.status != 200:
_LOGGER.error("Rocket.Chat error %s, %s", resp.status, resp.text)
@@ -134,7 +136,7 @@ async def _get_message(self):
json = await resp.json()
await self._parse_message(json)
- async def listen(self):
+ async def get_messages_loop(self):
"""Listen for and parse new messages.
The method will sleep asynchronously at the end of
@@ -148,7 +150,19 @@ async def listen(self):
"""
while self.listening:
await self._get_message()
- await asyncio.sleep(self.update_interval)
+
+ async def listen(self):
+ """Listen for and parse new messages.
+
+ Every connector has to implement the listen method. When an
+ infinite loop is running, it becomes hard to cancel this task.
+ So we are creating a task and set it on a variable so we can
+ cancel the task.
+
+ """
+ message_getter = self.loop.create_task(self.get_messages_loop())
+ await self._closing.wait()
+ message_getter.cancel()
@register_event(Message)
async def send_message(self, message):
@@ -163,17 +177,28 @@ async def send_message(self, message):
"""
_LOGGER.debug("Responding with: %s", message.text)
- async with aiohttp.ClientSession() as session:
- data = {}
- data["channel"] = message.target
- data["alias"] = self.bot_name
- data["text"] = message.text
- data["avatar"] = ""
- resp = await session.post(
- self.build_url("chat.postMessage"), headers=self.headers, data=data
- )
- if resp.status == 200:
- _LOGGER.debug("Successfully responded")
- else:
- _LOGGER.debug("Error - %s: Unable to respond", resp.status)
+ data = {}
+ data["channel"] = message.target
+ data["alias"] = self.bot_name
+ data["text"] = message.text
+ data["avatar"] = ""
+ resp = await self.session.post(
+ self.build_url("chat.postMessage"), headers=self.headers, data=data
+ )
+
+ if resp.status == 200:
+ _LOGGER.debug("Successfully responded")
+ else:
+ _LOGGER.debug("Error - %s: Unable to respond", resp.status)
+
+ async def disconnect(self):
+ """Disconnect from Rocket.Chat.
+
+ Stops the infinite loop found in self._listen() and closes
+ aiohttp session.
+
+ """
+ self.listening = False
+ self._closing.set()
+ await self.session.close()
| diff --git a/tests/test_connector_rocketchat.py b/tests/test_connector_rocketchat.py
--- a/tests/test_connector_rocketchat.py
+++ b/tests/test_connector_rocketchat.py
@@ -1,11 +1,10 @@
"""Tests for the RocketChat class."""
import asyncio
import unittest
-import unittest.mock as mock
+import contextlib
import asynctest
import asynctest.mock as amock
-from opsdroid.__main__ import configure_lang
from opsdroid.core import OpsDroid
from opsdroid.connector.rocketchat import RocketChat
from opsdroid.events import Message
@@ -22,7 +21,12 @@ def setUp(self):
def test_init(self):
"""Test that the connector is initialised properly."""
connector = RocketChat(
- {"name": "rocket.chat", "access-token": "test", "user-id": "userID"},
+ {
+ "name": "rocket.chat",
+ "access-token": "test",
+ "user-id": "userID",
+ "update-interval": 0.1,
+ },
opsdroid=OpsDroid(),
)
self.assertEqual("general", connector.default_target)
@@ -52,6 +56,9 @@ def setUp(self):
self.connector.latest_update = "2018-10-08T12:57:37.126Z"
+ with amock.patch("aiohttp.ClientSession") as mocked_session:
+ self.connector.session = mocked_session
+
async def test_connect(self):
connect_response = amock.Mock()
connect_response.status = 200
@@ -99,15 +106,7 @@ async def test_connect_failure(self):
self.assertLogs("_LOGGER", "error")
async def test_get_message(self):
- connector_group = RocketChat(
- {
- "name": "rocket.chat",
- "token": "test",
- "user-id": "userID",
- "group": "test",
- },
- opsdroid=OpsDroid(),
- )
+ self.connector.group = "test"
response = amock.Mock()
response.status = 200
response.json = amock.CoroutineMock()
@@ -137,19 +136,23 @@ async def test_get_message(self):
]
}
- with OpsDroid() as opsdroid, amock.patch(
- "aiohttp.ClientSession.get"
+ with OpsDroid() as opsdroid, amock.patch.object(
+ self.connector.session, "get"
) as patched_request, amock.patch.object(
- connector_group, "_parse_message"
- ) as mocked_parse_message:
+ self.connector, "_parse_message"
+ ) as mocked_parse_message, amock.patch(
+ "asyncio.sleep"
+ ) as mocked_sleep:
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(response)
- await connector_group._get_message()
+ await self.connector._get_message()
self.assertTrue(patched_request.called)
self.assertTrue(mocked_parse_message.called)
+ self.assertTrue(mocked_sleep.called)
+ self.assertLogs("_LOGGER", "debug")
async def test_parse_message(self):
response = {
@@ -187,15 +190,25 @@ async def test_parse_message(self):
self.assertEqual("2018-05-11T16:05:41.047Z", self.connector.latest_update)
async def test_listen(self):
- self.connector.side_effect = Exception()
- await self.connector.listen()
+ with amock.patch.object(
+ self.connector.loop, "create_task"
+ ) as mocked_task, amock.patch.object(
+ self.connector._closing, "wait"
+ ) as mocked_event:
+ mocked_event.return_value = asyncio.Future()
+ mocked_event.return_value.set_result(True)
+ mocked_task.return_value = asyncio.Future()
+ await self.connector.listen()
+
+ self.assertTrue(mocked_event.called)
+ self.assertTrue(mocked_task.called)
async def test_get_message_failure(self):
listen_response = amock.Mock()
listen_response.status = 401
- with OpsDroid() as opsdroid, amock.patch(
- "aiohttp.ClientSession.get"
+ with OpsDroid() as opsdroid, amock.patch.object(
+ self.connector.session, "get"
) as patched_request:
patched_request.return_value = asyncio.Future()
@@ -204,12 +217,18 @@ async def test_get_message_failure(self):
self.assertLogs("_LOGGER", "error")
self.assertEqual(False, self.connector.listening)
+ async def test_get_messages_loop(self):
+ self.connector._get_messages = amock.CoroutineMock()
+ self.connector._get_messages.side_effect = Exception()
+ with contextlib.suppress(Exception):
+ await self.connector.get_messages_loop()
+
async def test_respond(self):
post_response = amock.Mock()
post_response.status = 200
- with OpsDroid() as opsdroid, amock.patch(
- "aiohttp.ClientSession.post"
+ with OpsDroid() as opsdroid, amock.patch.object(
+ self.connector.session, "post"
) as patched_request:
self.assertTrue(opsdroid.__class__.instances)
@@ -230,8 +249,8 @@ async def test_respond_failure(self):
post_response = amock.Mock()
post_response.status = 401
- with OpsDroid() as opsdroid, amock.patch(
- "aiohttp.ClientSession.post"
+ with OpsDroid() as opsdroid, amock.patch.object(
+ self.connector.session, "post"
) as patched_request:
self.assertTrue(opsdroid.__class__.instances)
@@ -246,3 +265,13 @@ async def test_respond_failure(self):
patched_request.return_value.set_result(post_response)
await test_message.respond("Response")
self.assertLogs("_LOGGER", "debug")
+
+ async def test_disconnect(self):
+ with amock.patch.object(self.connector.session, "close") as mocked_close:
+ mocked_close.return_value = asyncio.Future()
+ mocked_close.return_value.set_result(True)
+
+ await self.connector.disconnect()
+ self.assertFalse(self.connector.listening)
+ self.assertTrue(self.connector.session.closed())
+ self.assertEqual(self.connector._closing.set(), None)
| Implement disconnect method to connectors
<!-- Before you post an issue or if you are unsure about something join our gitter channel https://gitter.im/opsdroid/ and ask away! We are more than happy to help you. -->
# Description
Opsdroid can now exit in a clean way after #711 was merged. But most of the connectors (with the exception of websockets) don't implement the `disconnect` method and when opsdroid tries to exit, an exception occurs, because the connector task was destroyed while pending.
Implementing the disconnect method on every connector will avoid this exception to occur.
---
_As a work around until every connector is addressed should we just get all tasks and cancel every single one within the `core.unload` method?_
## Steps to Reproduce
Start opsdroid, wait for load and then kill it with `ctrl+c` the shell connector will throw the exception.
## Expected Functionality
Opsdroid should be able to exit without any exception being thrown.
## Experienced Functionality
Every single thing is cancelled but the connectors that don't implement the disconnect method.
```python
Caught exception
ERROR opsdroid.core: {'message': 'Task was destroyed but it is pending!', 'task': <Task pending coro=<ConnectorShell.listen() done, defined at /Users/fabiorosado/Library/Application Support/opsdroid/opsdroid-modules/connector/shell/__init__.py:64> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x10dbfd9a8>()]> cb=[gather.<locals>._done_callback(0)() at /usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/tasks.py:609]>}
```
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| Related to #723
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
This still needs fixing.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
Only the Rocket Chat connector needs this implementing now. @FabioRosado is this something you could pick up? | 2019-05-27T15:35:23 |
opsdroid/opsdroid | 966 | opsdroid__opsdroid-966 | [
"954"
] | 0636d6983276e252c2583050ef3c8d5b304d513f | diff --git a/opsdroid/__main__.py b/opsdroid/__main__.py
--- a/opsdroid/__main__.py
+++ b/opsdroid/__main__.py
@@ -6,13 +6,13 @@
import logging
import gettext
import time
-import contextlib
import click
from opsdroid import __version__
from opsdroid.core import OpsDroid
from opsdroid.loader import Loader
+from opsdroid.logging import configure_logging
from opsdroid.const import (
DEFAULT_LOG_FILENAME,
LOCALE_DIR,
@@ -41,81 +41,6 @@ def configure_lang(config):
lang.install()
-def configure_logging(config):
- """Configure the root logger based on user config."""
- rootlogger = logging.getLogger()
- while rootlogger.handlers:
- rootlogger.handlers.pop()
-
- try:
- if config["logging"]["path"]:
- logfile_path = os.path.expanduser(config["logging"]["path"])
- else:
- logfile_path = config["logging"]["path"]
- except KeyError:
- logfile_path = DEFAULT_LOG_FILENAME
-
- try:
- log_level = get_logging_level(config["logging"]["level"])
- except KeyError:
- log_level = logging.INFO
-
- rootlogger.setLevel(log_level)
- formatter = logging.Formatter("%(levelname)s %(name)s: %(message)s")
-
- console_handler = logging.StreamHandler()
- console_handler.setLevel(log_level)
- console_handler.setFormatter(formatter)
- rootlogger.addHandler(console_handler)
-
- with contextlib.suppress(KeyError):
- if not config["logging"]["console"]:
- console_handler.setLevel(logging.CRITICAL)
-
- if logfile_path:
- logdir = os.path.dirname(os.path.realpath(logfile_path))
- if not os.path.isdir(logdir):
- os.makedirs(logdir)
- file_handler = logging.FileHandler(logfile_path)
- file_handler.setLevel(log_level)
- file_handler.setFormatter(formatter)
- rootlogger.addHandler(file_handler)
- _LOGGER.info("=" * 40)
- _LOGGER.info(_("Started opsdroid %s"), __version__)
-
-
-def get_logging_level(logging_level):
- """Get the logger level based on the user configuration.
-
- Args:
- logging_level: logging level from config file
-
- Returns:
- logging LEVEL ->
- CRITICAL = 50
- FATAL = CRITICAL
- ERROR = 40
- WARNING = 30
- WARN = WARNING
- INFO = 20
- DEBUG = 10
- NOTSET = 0
-
- """
- if logging_level == "critical":
- return logging.CRITICAL
-
- if logging_level == "error":
- return logging.ERROR
- if logging_level == "warning":
- return logging.WARNING
-
- if logging_level == "debug":
- return logging.DEBUG
-
- return logging.INFO
-
-
def check_dependencies():
"""Check for system dependencies required by opsdroid."""
if sys.version_info.major < 3 or sys.version_info.minor < 6:
diff --git a/opsdroid/logging.py b/opsdroid/logging.py
new file mode 100644
--- /dev/null
+++ b/opsdroid/logging.py
@@ -0,0 +1,149 @@
+"""Class for Filter logs and logging logic."""
+
+import os
+import logging
+import contextlib
+
+from opsdroid.const import DEFAULT_LOG_FILENAME, __version__
+
+_LOGGER = logging.getLogger(__name__)
+
+
+class ParsingFilter(logging.Filter):
+ """Class that filters logs."""
+
+ def __init__(self, config, *parse_list):
+ """Create object to implement filtering."""
+ super(ParsingFilter, self).__init__()
+ self.config = config["logging"]
+ try:
+ if (
+ self.config["filter"]["whitelist"]
+ and self.config["filter"]["blacklist"]
+ ):
+ _LOGGER.warning(
+ "Both whitelist and blacklist "
+ "filters found in configuration. "
+ "Only one can be used at a time - "
+ "only the whitelist filter will be used."
+ )
+ self.parse_list = [
+ logging.Filter(name) for name in parse_list[0]["whitelist"]
+ ]
+ except KeyError:
+ self.parse_list = parse_list[0].get("whitelist") or parse_list[0].get(
+ "blacklist"
+ )
+
+ self.parse_list = [logging.Filter(name) for name in self.parse_list]
+
+ def filter(self, record):
+ """Apply filter to the log message.
+
+ This is a subset of Logger.filter, this method applies the logger
+ filters and returns a bool. If the value is true the record will
+ be passed to the handlers and the log shown. If the value is
+ false it will be ignored.
+
+ Args:
+ record: a log record containing the log message and the
+ name of the log - example: opsdroid.core.
+
+ Returns:
+ Boolean: If True - pass the log to handler.
+
+ """
+
+ if self.config["filter"].get("whitelist"):
+ return any(name.filter(record) for name in self.parse_list)
+ return not any(name.filter(record) for name in self.parse_list)
+
+
+def configure_logging(config):
+ """Configure the root logger based on user config."""
+ rootlogger = logging.getLogger()
+ while rootlogger.handlers:
+ rootlogger.handlers.pop()
+
+ try:
+ if config["logging"]["path"]:
+ logfile_path = os.path.expanduser(config["logging"]["path"])
+ else:
+ logfile_path = config["logging"]["path"]
+ except KeyError:
+ logfile_path = DEFAULT_LOG_FILENAME
+
+ try:
+ log_level = get_logging_level(config["logging"]["level"])
+ except KeyError:
+ log_level = logging.INFO
+
+ rootlogger.setLevel(log_level)
+
+ try:
+ if config["logging"]["extended"]:
+ formatter = logging.Formatter(
+ "%(levelname)s %(name)s.%(funcName)s(): %(message)s"
+ )
+ except KeyError:
+ formatter = logging.Formatter("%(levelname)s %(name)s: %(message)s")
+
+ console_handler = logging.StreamHandler()
+ console_handler.setLevel(log_level)
+ console_handler.setFormatter(formatter)
+
+ with contextlib.suppress(KeyError):
+ console_handler.addFilter(ParsingFilter(config, config["logging"]["filter"]))
+
+ rootlogger.addHandler(console_handler)
+
+ with contextlib.suppress(KeyError):
+ if not config["logging"]["console"]:
+ console_handler.setLevel(logging.CRITICAL)
+
+ if logfile_path:
+ logdir = os.path.dirname(os.path.realpath(logfile_path))
+ if not os.path.isdir(logdir):
+ os.makedirs(logdir)
+ file_handler = logging.FileHandler(logfile_path)
+ file_handler.setLevel(log_level)
+ file_handler.setFormatter(formatter)
+
+ with contextlib.suppress(KeyError):
+ file_handler.addFilter(ParsingFilter(config, config["logging"]["filter"]))
+
+ rootlogger.addHandler(file_handler)
+ _LOGGER.info("=" * 40)
+ _LOGGER.info(_("Started opsdroid %s"), __version__)
+
+
+def get_logging_level(logging_level):
+ """Get the logger level based on the user configuration.
+
+ Args:
+ logging_level: logging level from config file
+
+ Returns:
+ logging LEVEL ->
+ CRITICAL = 50
+ FATAL = CRITICAL
+ ERROR = 40
+ WARNING = 30
+ WARN = WARNING
+ INFO = 20
+ DEBUG = 10
+ NOTSET = 0
+
+ """
+ if logging_level == "critical":
+ return logging.CRITICAL
+
+ if logging_level == "error":
+ return logging.ERROR
+ if logging_level == "warning":
+ return logging.WARNING
+
+ if logging_level == "debug":
+ return logging.DEBUG
+
+ return logging.INFO
| diff --git a/tests/test_logging.py b/tests/test_logging.py
new file mode 100644
--- /dev/null
+++ b/tests/test_logging.py
@@ -0,0 +1,167 @@
+import unittest
+import unittest.mock as mock
+import logging
+import os
+import tempfile
+import contextlib
+
+import opsdroid.logging as opsdroid
+from opsdroid.__main__ import configure_lang
+
+
+class TestLogging(unittest.TestCase):
+ """Test the logging module."""
+
+ def setUp(self):
+ self._tmp_dir = os.path.join(tempfile.gettempdir(), "opsdroid_tests")
+ with contextlib.suppress(FileExistsError):
+ os.makedirs(self._tmp_dir, mode=0o777)
+ configure_lang({})
+
+ def test_set_logging_level(self):
+ self.assertEqual(logging.DEBUG, opsdroid.get_logging_level("debug"))
+ self.assertEqual(logging.INFO, opsdroid.get_logging_level("info"))
+ self.assertEqual(logging.WARNING, opsdroid.get_logging_level("warning"))
+ self.assertEqual(logging.ERROR, opsdroid.get_logging_level("error"))
+ self.assertEqual(logging.CRITICAL, opsdroid.get_logging_level("critical"))
+ self.assertEqual(logging.INFO, opsdroid.get_logging_level(""))
+
+ def test_configure_no_logging(self):
+ config = {"logging": {"path": False, "console": False}}
+ opsdroid.configure_logging(config)
+ rootlogger = logging.getLogger()
+ self.assertEqual(len(rootlogger.handlers), 1)
+ self.assertEqual(logging.StreamHandler, type(rootlogger.handlers[0]))
+ self.assertEqual(rootlogger.handlers[0].level, logging.CRITICAL)
+
+ def test_configure_file_logging(self):
+ config = {
+ "logging": {
+ "path": os.path.join(self._tmp_dir, "output.log"),
+ "console": False,
+ }
+ }
+ opsdroid.configure_logging(config)
+ rootlogger = logging.getLogger()
+ self.assertEqual(len(rootlogger.handlers), 2)
+ self.assertEqual(logging.StreamHandler, type(rootlogger.handlers[0]))
+ self.assertEqual(rootlogger.handlers[0].level, logging.CRITICAL)
+ self.assertEqual(logging.FileHandler, type(rootlogger.handlers[1]))
+ self.assertEqual(rootlogger.handlers[1].level, logging.INFO)
+
+ def test_configure_file_blacklist(self):
+ config = {
+ "logging": {
+ "path": os.path.join(self._tmp_dir, "output.log"),
+ "console": False,
+ "filter": {"blacklist": "opsdroid.logging"},
+ }
+ }
+ opsdroid.configure_logging(config)
+ rootlogger = logging.getLogger()
+ self.assertEqual(len(rootlogger.handlers), 2)
+ self.assertEqual(logging.StreamHandler, type(rootlogger.handlers[0]))
+ self.assertEqual(rootlogger.handlers[0].level, logging.CRITICAL)
+ self.assertEqual(logging.FileHandler, type(rootlogger.handlers[1]))
+ self.assertEqual(rootlogger.handlers[1].level, logging.INFO)
+ self.assertLogs("_LOGGER", None)
+
+ def test_configure_file_logging_directory_not_exists(self):
+ with mock.patch("logging.getLogger") as logmock:
+ mocklogger = mock.MagicMock()
+ mocklogger.handlers = [True]
+ logmock.return_value = mocklogger
+ config = {
+ "logging": {
+ "path": os.path.join(
+ self._tmp_dir, "mynonexistingdirectory", "output.log"
+ ),
+ "console": False,
+ }
+ }
+ opsdroid.configure_logging(config)
+
+ def test_configure_console_logging(self):
+ config = {"logging": {"path": False, "level": "error", "console": True}}
+ opsdroid.configure_logging(config)
+ rootlogger = logging.getLogger()
+ self.assertEqual(len(rootlogger.handlers), 1)
+ self.assertEqual(logging.StreamHandler, type(rootlogger.handlers[0]))
+ self.assertEqual(rootlogger.handlers[0].level, logging.ERROR)
+
+ def test_configure_console_blacklist(self):
+ config = {
+ "logging": {
+ "path": False,
+ "level": "error",
+ "console": True,
+ "filter": {"blacklist": "opsdroid"},
+ }
+ }
+ opsdroid.configure_logging(config)
+ rootlogger = logging.getLogger()
+ self.assertEqual(len(rootlogger.handlers), 1)
+ self.assertEqual(logging.StreamHandler, type(rootlogger.handlers[0]))
+ self.assertLogs("_LOGGER", None)
+
+ def test_configure_console_whitelist(self):
+ config = {
+ "logging": {
+ "path": False,
+ "level": "info",
+ "console": True,
+ "filter": {"whitelist": "opsdroid.logging"},
+ }
+ }
+ opsdroid.configure_logging(config)
+ rootlogger = logging.getLogger()
+ self.assertEqual(len(rootlogger.handlers), 1)
+ self.assertEqual(logging.StreamHandler, type(rootlogger.handlers[0]))
+ self.assertLogs("_LOGGER", "info")
+
+ def test_configure_extended_logging(self):
+ config = {
+ "logging": {
+ "path": False,
+ "level": "error",
+ "console": True,
+ "extended": True,
+ }
+ }
+ opsdroid.configure_logging(config)
+ rootlogger = logging.getLogger()
+ self.assertEqual(len(rootlogger.handlers), 1)
+ self.assertEqual(logging.StreamHandler, type(rootlogger.handlers[0]))
+
+ def test_configure_default_logging(self):
+ config = {}
+ opsdroid.configure_logging(config)
+ rootlogger = logging.getLogger()
+ print(rootlogger)
+ print(config)
+ self.assertEqual(len(rootlogger.handlers), 2)
+ self.assertEqual(logging.StreamHandler, type(rootlogger.handlers[0]))
+ self.assertEqual(rootlogger.handlers[0].level, logging.INFO)
+ self.assertEqual(logging.FileHandler, type(rootlogger.handlers[1]))
+ self.assertEqual(rootlogger.handlers[1].level, logging.INFO)
+ self.assertLogs("_LOGGER", "info")
+
+
+class TestWhiteAndBlackFilter(unittest.TestCase):
+ def setUp(self):
+ self.config = {
+ "logging": {
+ "path": False,
+ "level": "info",
+ "console": True,
+ "filter": {"whitelist": ["opsdroid"], "blacklist": ["opsdroid.core"]},
+ }
+ }
+
+ def tearDown(self):
+ self.config = {}
+ opsdroid.configure_logging(self.config)
+
+ def test_configure_whitelist_and_blacklist(self):
+ opsdroid.configure_logging(self.config)
+ self.assertLogs("_LOGGER", "warning")
diff --git a/tests/test_main.py b/tests/test_main.py
--- a/tests/test_main.py
+++ b/tests/test_main.py
@@ -1,6 +1,5 @@
import unittest
import unittest.mock as mock
-import logging
import os
import sys
import shutil
@@ -54,71 +53,6 @@ def test_configure_lang(self):
opsdroid.configure_lang({"lang": "es"})
self.assertTrue(translation.return_value.install.called)
- def test_set_logging_level(self):
- self.assertEqual(logging.DEBUG, opsdroid.get_logging_level("debug"))
- self.assertEqual(logging.INFO, opsdroid.get_logging_level("info"))
- self.assertEqual(logging.WARNING, opsdroid.get_logging_level("warning"))
- self.assertEqual(logging.ERROR, opsdroid.get_logging_level("error"))
- self.assertEqual(logging.CRITICAL, opsdroid.get_logging_level("critical"))
- self.assertEqual(logging.INFO, opsdroid.get_logging_level(""))
-
- def test_configure_no_logging(self):
- config = {"logging": {"path": False, "console": False}}
- opsdroid.configure_logging(config)
- rootlogger = logging.getLogger()
- self.assertEqual(len(rootlogger.handlers), 1)
- self.assertEqual(logging.StreamHandler, type(rootlogger.handlers[0]))
- self.assertEqual(rootlogger.handlers[0].level, logging.CRITICAL)
-
- def test_configure_file_logging(self):
- config = {
- "logging": {
- "path": os.path.join(self._tmp_dir, "output.log"),
- "console": False,
- }
- }
- opsdroid.configure_logging(config)
- rootlogger = logging.getLogger()
- self.assertEqual(len(rootlogger.handlers), 2)
- self.assertEqual(logging.StreamHandler, type(rootlogger.handlers[0]))
- self.assertEqual(rootlogger.handlers[0].level, logging.CRITICAL)
- self.assertEqual(logging.FileHandler, type(rootlogger.handlers[1]))
- self.assertEqual(rootlogger.handlers[1].level, logging.INFO)
-
- def test_configure_file_logging_directory_not_exists(self):
- with mock.patch("logging.getLogger") as logmock:
- mocklogger = mock.MagicMock()
- mocklogger.handlers = [True]
- logmock.return_value = mocklogger
- config = {
- "logging": {
- "path": os.path.join(
- self._tmp_dir, "mynonexistingdirectory", "output.log"
- ),
- "console": False,
- }
- }
- opsdroid.configure_logging(config)
- # self.assertEqual(os.path.isfile(config['logging']['path']), True)
-
- def test_configure_console_logging(self):
- config = {"logging": {"path": False, "level": "error", "console": True}}
- opsdroid.configure_logging(config)
- rootlogger = logging.getLogger()
- self.assertEqual(len(rootlogger.handlers), 1)
- self.assertEqual(logging.StreamHandler, type(rootlogger.handlers[0]))
- self.assertEqual(rootlogger.handlers[0].level, logging.ERROR)
-
- def test_configure_default_logging(self):
- config = {}
- opsdroid.configure_logging(config)
- rootlogger = logging.getLogger()
- self.assertEqual(len(rootlogger.handlers), 2)
- self.assertEqual(logging.StreamHandler, type(rootlogger.handlers[0]))
- self.assertEqual(rootlogger.handlers[0].level, logging.INFO)
- self.assertEqual(logging.FileHandler, type(rootlogger.handlers[1]))
- self.assertEqual(rootlogger.handlers[1].level, logging.INFO)
-
def test_welcome_message(self):
config = {"welcome-message": True}
opsdroid.welcome_message(config)
| Add filters to logging
Currently, opsdroid has a lot of things logging into debug mode, which makes it hard to try and find things while doing the actual debugging.
It would be good to implement filters that could be added to the logging through the `config.yaml` file.
After sharing this in the channel Jacob suggested to implement filters by creating a class that goes through all those logs and then use the config to add a list of things to filter and that class would check every log against that list and either show that log or drop it.
| Sounds good!
We should add some kind of config option like:
```yaml
logging:
level: debug
console: true
filters:
- aiosqlite
- websockets.protocol
```
We would need to implement a log filter class which would compare the log domain with the filter list and return `False` for anything which starts with one of the filters.
Thank you that helps as it gives a bit more guidance on how to tackle this issue 😄 👍 | 2019-05-27T20:56:44 |
opsdroid/opsdroid | 968 | opsdroid__opsdroid-968 | [
"878"
] | 5aa672cd733273acddd8c9e4f1e9f8e175c20de7 | diff --git a/opsdroid/connector/slack/__init__.py b/opsdroid/connector/slack/__init__.py
--- a/opsdroid/connector/slack/__init__.py
+++ b/opsdroid/connector/slack/__init__.py
@@ -12,6 +12,7 @@
from opsdroid.connector import Connector, register_event
from opsdroid.events import Message, Reaction
+from opsdroid.connector.slack.events import Blocks
_LOGGER = logging.getLogger(__name__)
@@ -141,6 +142,20 @@ async def send_message(self, message):
icon_emoji=self.icon_emoji,
)
+ @register_event(Blocks)
+ async def send_blocks(self, blocks):
+ """Respond with structured blocks."""
+ _LOGGER.debug("Responding with interactive blocks in room %s", blocks.target)
+ await self.slacker.chat.post(
+ "chat.postMessage",
+ data={
+ "channel": blocks.target,
+ "username": self.bot_name,
+ "blocks": blocks.blocks,
+ "icon_emoji": self.icon_emoji,
+ },
+ )
+
@register_event(Reaction)
async def send_reaction(self, reaction):
"""React to a message."""
diff --git a/opsdroid/connector/slack/events.py b/opsdroid/connector/slack/events.py
new file mode 100644
--- /dev/null
+++ b/opsdroid/connector/slack/events.py
@@ -0,0 +1,44 @@
+"""Classes to describe different kinds of Slack specific event."""
+
+import json
+
+from opsdroid.events import Message
+
+
+class Blocks(Message):
+ """A blocks object.
+
+ Slack uses blocks to add advenced interactivity and formatting to messages.
+ https://api.slack.com/messaging/interactivity
+ Blocks are provided in JSON format to Slack which renders them.
+
+ Args:
+ blocks (string or dict): String or dict of json for blocks
+ room (string, optional): String name of the room or chat channel in
+ which message was sent
+ connector (Connector, optional): Connector object used to interact with
+ given chat service
+ raw_event (dict, optional): Raw message as provided by chat service.
+ None by default
+
+ Attributes:
+ created: Local date and time that message object was created
+ user: String name of user sending message
+ room: String name of the room or chat channel in which message was sent
+ connector: Connector object used to interact with given chat service
+ blocks: Blocks JSON as string
+ raw_event: Raw message provided by chat service
+ raw_match: A match object for a search against which the message was
+ matched. E.g. a regular expression or natural language intent
+ responded_to: Boolean initialized as False. True if event has been
+ responded to
+
+ """
+
+ def __init__(self, blocks, *args, **kwargs):
+ """Create object with minimum properties."""
+ super().__init__("", *args, **kwargs)
+
+ self.blocks = blocks
+ if isinstance(self.blocks, list):
+ self.blocks = json.dumps(self.blocks)
| diff --git a/tests/test_connector_slack.py b/tests/test_connector_slack.py
--- a/tests/test_connector_slack.py
+++ b/tests/test_connector_slack.py
@@ -9,6 +9,7 @@
from opsdroid.core import OpsDroid
from opsdroid.connector.slack import ConnectorSlack
+from opsdroid.connector.slack.events import Blocks
from opsdroid.events import Message, Reaction
from opsdroid.__main__ import configure_lang
@@ -232,6 +233,19 @@ async def test_respond(self):
await connector.send(Message("test", "user", "room", connector))
self.assertTrue(connector.slacker.chat.post_message.called)
+ async def test_send_blocks(self):
+ connector = ConnectorSlack({"api-token": "abc123"}, opsdroid=OpsDroid())
+ connector.slacker.chat.post = amock.CoroutineMock()
+ await connector.send(
+ Blocks(
+ [{"type": "section", "text": {"type": "mrkdwn", "text": "*Test*"}}],
+ "user",
+ "room",
+ connector,
+ )
+ )
+ self.assertTrue(connector.slacker.chat.post.called)
+
async def test_react(self):
connector = ConnectorSlack({"api-token": "abc123"})
connector.slacker.reactions.post = amock.CoroutineMock()
| Slack attachment support
Is there any support for sending [slack attachment(s)](https://api.slack.com/docs/message-attachments) in opsdroid? I found [this open issue](https://github.com/opsdroid/connector-slack/issues/13) on the [connector-slack](https://github.com/opsdroid/connector-slack) project but can't seem to find any new information on additional support for attachments since the `connector-slack` project was deprecated.
| We have just merged event types to opsdroid, perhaps slack attachments could be supported easier with them, but so far the slack connector doesn't support them. Would be good to update the slack connector to support this feature, would you like to work on it?
I could probably take a look at it. Maybe something like `message.respond_with_json(dict)` might be the easiest route? That way users could take advantage of any json api's provided by a backend (i.e. not just the `slack-connector`).
The way we handle events has changed dramatically. It might be useful for @Cadair to give some thoughts on how you imagine this specific example working?
That's an interesting question that I haven't really considered. The events structure is well suited to having an event type for each of the attachments individually. I wonder if it would be worth having a collection event which could pass a group of events to the connector together and then the slack connector could represent them as attachments?
Has there been any update on this? If I could somehow format my slack messages it would greatly improve my end users interactions.
The events have been merged and Jacob has a ongoing PR that will implement sending images and files so this will be done in the future.
Slack is a bit funny with permissions so things need to be tested and such
> If I could somehow format my slack messages it would greatly improve my end users interactions.
What do you mean by this?
Most of our skills, are just interacting with rest API's, returning JSON back to opsdroid. Something like 'list inventories in Ansible AWX Dev', and returning data like
`{3: 'xxx-automation-aws-inventory', 2: 'xxx-automation-ent-dev-Inventory'}`
Its ugly, and hard to read, especially as the results get longer and longer. If we supported attachments, i could use each key/value pair as a field in the attachment.
As a work around you could read the Json and Post the changed message
@FabioRosado
I dont follow.
I'm interested in why you are sending the JSON object back to the chat client. I would've thought you would decode the response and extract the bits you want to show to the user. Alternatively you could pretty format the JSON and return it within code fences.
I see how the attachment [fields](https://api.slack.com/docs/message-attachments#fields) could help but if you have a long JSON you may still end up with it hard to read.
Also looks like Slack are [transitioning from attachments to blocks](https://api.slack.com/messaging/attachments-to-blocks).
Like Jacob said I meant that you could perhaps decode the Json object and transform it into a more readable format.
The blocks seem interesting but like it says in the docs we might need to rethink how to implement things with slack.
I started having a quick hack to look at implementing this and it looks like we will need to fix `aioslacker` first as it seems to be out of date with the Slack API.
```
TypeError: post_message() got an unexpected keyword argument 'blocks'
```
https://api.slack.com/methods/chat.postMessage
Did we created our own fork is aioslacker or was it of something else?
Im an idiot. I was attempting to send things, like I would direct to the slack client. I never even thought to just build up a string, with the proper concatenations to format the message.
```
return_text = f"*{environment} - Accounts*\n"
for account in accounts:
return_text = f"{return_text}```ID: {account['id']} Name: {account['name']} Status: {account['status']}```\n"
await message.respond(f"{return_text}")
```
Works fine.
> Im an idiot.
Don't put yourself down! Could we improve the docs or add examples to help other people avoid these assumptions? | 2019-05-30T19:32:21 |
opsdroid/opsdroid | 973 | opsdroid__opsdroid-973 | [
"792"
] | de5575e56fa28cce6048fa34925401cf90f03948 | diff --git a/opsdroid/database/redis/__init__.py b/opsdroid/database/redis/__init__.py
--- a/opsdroid/database/redis/__init__.py
+++ b/opsdroid/database/redis/__init__.py
@@ -1,11 +1,14 @@
"""Module for storing data within Redis."""
-from datetime import date, datetime
import json
-import time
+import logging
-import asyncio_redis
+import aioredis
+from aioredis import parser
from opsdroid.database import Database
+from opsdroid.helper import JSONEncoder, JSONDecoder
+
+_LOGGER = logging.getLogger(__name__)
class RedisDatabase(Database):
@@ -30,7 +33,7 @@ def __init__(self, config, opsdroid=None):
self.port = self.config.get("port", 6379)
self.database = self.config.get("database", 0)
self.password = self.config.get("password", None)
- self.reconnect = self.config.get("reconnect", False)
+ _LOGGER.debug(_("Loaded redis database connector."))
async def connect(self):
"""Connect to the database.
@@ -39,13 +42,26 @@ async def connect(self):
connect to Redis on localhost on port 6379
"""
- self.client = await asyncio_redis.Connection.create(
- host=self.host,
- port=self.port,
- db=self.database,
- auto_reconnect=self.reconnect,
- password=self.password,
- )
+ try:
+ self.client = await aioredis.create_pool(
+ address=(self.host, int(self.port)),
+ db=self.database,
+ password=self.password,
+ parser=parser.PyReader,
+ )
+
+ _LOGGER.info(
+ _("Connected to redis database %s from %s on port %s"),
+ self.database,
+ self.host,
+ self.port,
+ )
+ except OSError:
+ _LOGGER.warning(
+ _("Unable to connect to redis database on address: %s port: %s"),
+ self.host,
+ self.port,
+ )
async def put(self, key, data):
"""Store the data object in Redis against the key.
@@ -55,8 +71,9 @@ async def put(self, key, data):
data (object): The data object to store.
"""
- data = self.convert_object_to_timestamp(data)
- await self.client.set(key, json.dumps(data))
+ if self.client:
+ _LOGGER.debug(_("Putting %s into redis"), key)
+ await self.client.execute("SET", key, json.dumps(data, cls=JSONEncoder))
async def get(self, key):
"""Get data from Redis for a given key.
@@ -69,56 +86,16 @@ async def get(self, key):
object found for that key.
"""
- data = await self.client.get(key)
+ if self.client:
+ _LOGGER.debug(_("Getting %s from redis"), key)
+ data = await self.client.execute("GET", key)
- if data:
- return self.convert_timestamp_to_object(json.loads(data))
+ if data:
+ return json.loads(data, encoding=JSONDecoder)
- return None
+ return None
async def disconnect(self):
"""Disconnect from the database."""
- self.client.close()
-
- @staticmethod
- def convert_object_to_timestamp(data):
- """
- Serialize dict before storing into Redis.
-
- Args:
- dict: Dict to serialize
-
- Returns:
- dict: Dict from redis to unserialize
-
- """
- for k, value in data.items():
- if isinstance(value, (datetime, date)):
- value = "::".join(
- [type(value).__name__, "%d" % time.mktime(value.timetuple())]
- )
- data[k] = value
- return data
-
- @staticmethod
- def convert_timestamp_to_object(data):
- """
- Unserialize data from Redis.
-
- Args:
- dict: Dict from redis to unserialize
-
- Returns:
- dict: Dict to serialize
-
- """
- for k, value in data.items():
- value_type = value.split("::", 1)[0]
- if value_type == "datetime":
- timestamp = int(value.split("::", 1)[1])
- value = datetime.fromtimestamp(timestamp)
- elif value_type == "date":
- timestamp = int(value.split("::", 1)[1])
- value = date.fromtimestamp(timestamp)
- data[k] = value
- return data
+ if self.client:
+ self.client.close()
diff --git a/opsdroid/database/sqlite/__init__.py b/opsdroid/database/sqlite/__init__.py
--- a/opsdroid/database/sqlite/__init__.py
+++ b/opsdroid/database/sqlite/__init__.py
@@ -2,11 +2,11 @@
import os
import logging
import json
-import datetime
import aiosqlite
from opsdroid.const import DEFAULT_ROOT_PATH
from opsdroid.database import Database
+from opsdroid.helper import JSONEncoder, JSONDecoder
_LOGGER = logging.getLogger(__name__)
@@ -116,124 +116,3 @@ async def get(self, key):
self.client = _db
return data
-
-
-class JSONEncoder(json.JSONEncoder):
- """A extended JSONEncoder class.
-
- This class is customised JSONEncoder class which helps to convert
- dict to JSON. The datetime objects are converted to dict with fields
- as keys.
-
- """
-
- # pylint: disable=method-hidden
- # See https://github.com/PyCQA/pylint/issues/414 for reference
-
- serializers = {}
-
- def default(self, o):
- """Convert the given datetime object to dict.
-
- Args:
- o (object): The datetime object to be marshalled.
-
- Returns:
- dict (object): A dict with datatime object data.
-
- Example:
- A dict which is returned after marshalling::
-
- {
- "__class__": "datetime",
- "year": 2018,
- "month": 10,
- "day": 2,
- "hour": 0,
- "minute": 41,
- "second": 17,
- "microsecond": 74644
- }
-
- """
- marshaller = self.serializers.get(type(o), super(JSONEncoder, self).default)
- return marshaller(o)
-
-
-class JSONDecoder:
- """A JSONDecoder class.
-
- This class will convert dict containing datetime values
- to datetime objects.
-
- """
-
- decoders = {}
-
- def __call__(self, dct):
- """Convert given dict to datetime objects.
-
- Args:
- dct (object): A dict containing datetime values and class type.
-
- Returns:
- object or dct: The datetime object for given dct, or dct if
- respective class decoder is not found.
-
- Example:
- A datetime object returned after decoding::
-
- datetime.datetime(2018, 10, 2, 0, 41, 17, 74644)
-
- """
- if dct.get("__class__") in self.decoders:
- return self.decoders[dct["__class__"]](dct)
- return dct
-
-
-def register_json_type(type_cls, fields, decode_fn):
- """Register JSON types.
-
- This method will register the serializers and decoders for the
- JSONEncoder and JSONDecoder classes respectively.
-
- Args:
- type_cls (object): A datetime object.
- fields (list): List of fields used to store data in dict.
- decode_fn (object): A lambda function object for decoding.
-
- """
- type_name = type_cls.__name__
- JSONEncoder.serializers[type_cls] = lambda obj: dict(
- __class__=type_name, **{field: getattr(obj, field) for field in fields}
- )
- JSONDecoder.decoders[type_name] = decode_fn
-
-
-register_json_type(
- datetime.datetime,
- ["year", "month", "day", "hour", "minute", "second", "microsecond"],
- lambda dct: datetime.datetime(
- dct["year"],
- dct["month"],
- dct["day"],
- dct["hour"],
- dct["minute"],
- dct["second"],
- dct["microsecond"],
- ),
-)
-
-register_json_type(
- datetime.date,
- ["year", "month", "day"],
- lambda dct: datetime.date(dct["year"], dct["month"], dct["day"]),
-)
-
-register_json_type(
- datetime.time,
- ["hour", "minute", "second", "microsecond"],
- lambda dct: datetime.time(
- dct["hour"], dct["minute"], dct["second"], dct["microsecond"]
- ),
-)
diff --git a/opsdroid/helper.py b/opsdroid/helper.py
--- a/opsdroid/helper.py
+++ b/opsdroid/helper.py
@@ -1,10 +1,12 @@
"""Helper functions to use within OpsDroid."""
+import datetime
import os
import stat
import shutil
import logging
import filecmp
+import json
import nbformat
from nbconvert import PythonExporter
@@ -154,3 +156,124 @@ def add_skill_attributes(func):
if not hasattr(func, "constraints"):
func.constraints = []
return func
+
+
+class JSONEncoder(json.JSONEncoder):
+ """A extended JSONEncoder class.
+
+ This class is customised JSONEncoder class which helps to convert
+ dict to JSON. The datetime objects are converted to dict with fields
+ as keys.
+
+ """
+
+ # pylint: disable=method-hidden
+ # See https://github.com/PyCQA/pylint/issues/414 for reference
+
+ serializers = {}
+
+ def default(self, o):
+ """Convert the given datetime object to dict.
+
+ Args:
+ o (object): The datetime object to be marshalled.
+
+ Returns:
+ dict (object): A dict with datatime object data.
+
+ Example:
+ A dict which is returned after marshalling::
+
+ {
+ "__class__": "datetime",
+ "year": 2018,
+ "month": 10,
+ "day": 2,
+ "hour": 0,
+ "minute": 41,
+ "second": 17,
+ "microsecond": 74644
+ }
+
+ """
+ marshaller = self.serializers.get(type(o), super(JSONEncoder, self).default)
+ return marshaller(o)
+
+
+class JSONDecoder:
+ """A JSONDecoder class.
+
+ This class will convert dict containing datetime values
+ to datetime objects.
+
+ """
+
+ decoders = {}
+
+ def __call__(self, dct):
+ """Convert given dict to datetime objects.
+
+ Args:
+ dct (object): A dict containing datetime values and class type.
+
+ Returns:
+ object or dct: The datetime object for given dct, or dct if
+ respective class decoder is not found.
+
+ Example:
+ A datetime object returned after decoding::
+
+ datetime.datetime(2018, 10, 2, 0, 41, 17, 74644)
+
+ """
+ if dct.get("__class__") in self.decoders:
+ return self.decoders[dct["__class__"]](dct)
+ return dct
+
+
+def register_json_type(type_cls, fields, decode_fn):
+ """Register JSON types.
+
+ This method will register the serializers and decoders for the
+ JSONEncoder and JSONDecoder classes respectively.
+
+ Args:
+ type_cls (object): A datetime object.
+ fields (list): List of fields used to store data in dict.
+ decode_fn (object): A lambda function object for decoding.
+
+ """
+ type_name = type_cls.__name__
+ JSONEncoder.serializers[type_cls] = lambda obj: dict(
+ __class__=type_name, **{field: getattr(obj, field) for field in fields}
+ )
+ JSONDecoder.decoders[type_name] = decode_fn
+
+
+register_json_type(
+ datetime.datetime,
+ ["year", "month", "day", "hour", "minute", "second", "microsecond"],
+ lambda dct: datetime.datetime(
+ dct["year"],
+ dct["month"],
+ dct["day"],
+ dct["hour"],
+ dct["minute"],
+ dct["second"],
+ dct["microsecond"],
+ ),
+)
+
+register_json_type(
+ datetime.date,
+ ["year", "month", "day"],
+ lambda dct: datetime.date(dct["year"], dct["month"], dct["day"]),
+)
+
+register_json_type(
+ datetime.time,
+ ["hour", "minute", "second", "microsecond"],
+ lambda dct: datetime.time(
+ dct["hour"], dct["minute"], dct["second"], dct["microsecond"]
+ ),
+)
| diff --git a/tests/test_database_redis.py b/tests/test_database_redis.py
--- a/tests/test_database_redis.py
+++ b/tests/test_database_redis.py
@@ -1,5 +1,5 @@
import asyncio
-import datetime
+import aioredis
import unittest
import asynctest
@@ -35,36 +35,7 @@ def test_init(self):
self.assertEqual("localhost", database.host)
self.assertEqual(6379, database.port)
self.assertEqual(None, database.password)
-
- def test_other(self):
- unserialized_data = {
- "example_string": "test",
- "example_datetime": datetime.datetime.utcfromtimestamp(1538389815),
- "example_date": datetime.date.fromtimestamp(1538366400),
- }
-
- serialized_data = RedisDatabase.convert_object_to_timestamp(unserialized_data)
-
- self.assertEqual(serialized_data["example_string"], "test")
- # Typically I would do assertDictEqual on the result, but as datetime are parsed based on the
- # timezone of the computer it makes the unittest fragile depending on the timezone of the user.
- self.assertEqual(serialized_data["example_datetime"][0:10], "datetime::")
- self.assertEqual(serialized_data["example_date"][0:6], "date::")
-
- def test_convert_timestamp_to_object(self):
- serialized_data = {
- "example_date": "date::1538366400",
- "example_datetime": "datetime::1538389815",
- "example_string": "test",
- }
-
- unserialized_data = RedisDatabase.convert_timestamp_to_object(serialized_data)
-
- self.assertEqual(unserialized_data["example_string"], "test")
- # Typically I would do assertDictEqual on the result, but as datetime are parsed based on the
- # timezone of the computer it makes the unittest fragile depending on the timezone of the user.
- self.assertIsInstance(unserialized_data["example_datetime"], datetime.datetime)
- self.assertIsInstance(unserialized_data["example_date"], datetime.date)
+ self.assertLogs("_LOGGER", "debug")
class TestRedisDatabaseAsync(asynctest.TestCase):
@@ -73,21 +44,41 @@ class TestRedisDatabaseAsync(asynctest.TestCase):
async def test_connect(self):
opsdroid = amock.CoroutineMock()
database = RedisDatabase({}, opsdroid=opsdroid)
- import asyncio_redis
- with amock.patch.object(
- asyncio_redis.Connection, "create"
- ) as mocked_connection:
+ with amock.patch.object(aioredis, "create_pool") as mocked_connection:
mocked_connection.side_effect = NotImplementedError
with suppress(NotImplementedError):
await database.connect()
self.assertTrue(mocked_connection.called)
+ self.assertLogs("_LOGGER", "info")
+
+ async def test_connect_failure(self):
+ opsdroid = amock.CoroutineMock()
+ database = RedisDatabase({}, opsdroid=opsdroid)
+
+ with amock.patch.object(aioredis, "create_pool") as mocked_connection:
+ mocked_connection.side_effect = OSError()
+
+ with suppress(OSError):
+ await database.connect()
+ self.assertLogs("_LOGGER", "warning")
+
+ async def test_connect_logging(self):
+ opsdroid = amock.CoroutineMock()
+ database = RedisDatabase({}, opsdroid=opsdroid)
+
+ with amock.patch.object(aioredis, "create_pool") as mocked_connection:
+ mocked_connection.set_result = amock.CoroutineMock()
+
+ await database.connect()
+ self.assertTrue(mocked_connection.called)
+ self.assertLogs("_LOGGER", "info")
async def test_get(self):
db = RedisDatabase({})
db.client = MockRedisClient()
- db.client.get = amock.CoroutineMock(return_value='{"key":"value"}')
+ db.client.execute = amock.CoroutineMock(return_value='{"key":"value"}')
result = await db.get("string")
@@ -96,7 +87,7 @@ async def test_get(self):
async def test_get_return_None(self):
db = RedisDatabase({})
db.client = MockRedisClient()
- db.client.get = amock.CoroutineMock(return_value=None)
+ db.client.execute = amock.CoroutineMock(return_value=None)
result = await db.get("string")
@@ -105,7 +96,7 @@ async def test_get_return_None(self):
async def test_put(self):
db = RedisDatabase({})
db.client = MockRedisClient()
- db.client.set = amock.CoroutineMock(return_value='{"key":"value"}')
+ db.client.execute = amock.CoroutineMock(return_value='{"key":"value"}')
result = await db.put("string", dict(key="value"))
diff --git a/tests/test_database_sqlite.py b/tests/test_database_sqlite.py
--- a/tests/test_database_sqlite.py
+++ b/tests/test_database_sqlite.py
@@ -1,15 +1,11 @@
"""Tests for the DatabaseSqlite class."""
import asyncio
-import json
-import datetime
import unittest
-import unittest.mock as mock
import asynctest
import asynctest.mock as amock
-from opsdroid.database.sqlite import DatabaseSqlite, JSONEncoder, JSONDecoder
-from opsdroid.database.sqlite import register_json_type
+from opsdroid.database.sqlite import DatabaseSqlite
from opsdroid.__main__ import configure_lang
@@ -88,71 +84,3 @@ async def test_get_and_put(self):
self.assertEqual("opsdroid", database.table)
self.assertEqual({}, data)
self.assertEqual("Connection", type(database.client).__name__)
-
-
-class TestJSONEncoder(unittest.TestCase):
- """A JSON Encoder test class.
-
- Test the custom json encoder class.
-
- """
-
- def setUp(self):
- self.loop = asyncio.new_event_loop()
-
- def test_datetime_to_dict(self):
- """Test default of json encoder class.
-
- This method will test the conversion of the datetime
- object to dict.
-
- """
- type_cls = datetime.datetime
- test_obj = datetime.datetime(2018, 10, 2, 0, 41, 17, 74644)
- encoder = JSONEncoder()
- obj = encoder.default(o=test_obj)
- self.assertEqual(
- {
- "__class__": type_cls.__name__,
- "year": 2018,
- "month": 10,
- "day": 2,
- "hour": 0,
- "minute": 41,
- "second": 17,
- "microsecond": 74644,
- },
- obj,
- )
-
-
-class TestJSONDecoder(unittest.TestCase):
- """A JSON Decoder test class.
-
- Test the custom json decoder class.
-
- """
-
- def setUp(self):
- self.loop = asyncio.new_event_loop()
-
- def test_dict_to_datetime(self):
- """Test call of json decoder class.
-
- This method will test the conversion of the dict to
- datetime object.
-
- """
- test_obj = {
- "__class__": datetime.datetime.__name__,
- "year": 2018,
- "month": 10,
- "day": 2,
- "hour": 0,
- "minute": 41,
- "second": 17,
- "microsecond": 74644,
- }
- decoder = JSONDecoder()
- obj = decoder(test_obj)
- self.assertEqual(datetime.datetime(2018, 10, 2, 0, 41, 17, 74644), obj)
diff --git a/tests/test_helper.py b/tests/test_helper.py
--- a/tests/test_helper.py
+++ b/tests/test_helper.py
@@ -1,4 +1,6 @@
import os
+import asyncio
+import datetime
import tempfile
import unittest
import unittest.mock as mock
@@ -10,6 +12,8 @@
convert_ipynb_to_script,
extract_gist_id,
get_opsdroid,
+ JSONEncoder,
+ JSONDecoder,
)
@@ -67,3 +71,71 @@ def test_extract_gist_id(self):
def test_opsdroid(self):
# Test that get_opsdroid returns None if no instances exist
assert get_opsdroid() is None
+
+
+class TestJSONEncoder(unittest.TestCase):
+ """A JSON Encoder test class.
+
+ Test the custom json encoder class.
+
+ """
+
+ def setUp(self):
+ self.loop = asyncio.new_event_loop()
+
+ def test_datetime_to_dict(self):
+ """Test default of json encoder class.
+
+ This method will test the conversion of the datetime
+ object to dict.
+
+ """
+ type_cls = datetime.datetime
+ test_obj = datetime.datetime(2018, 10, 2, 0, 41, 17, 74644)
+ encoder = JSONEncoder()
+ obj = encoder.default(o=test_obj)
+ self.assertEqual(
+ {
+ "__class__": type_cls.__name__,
+ "year": 2018,
+ "month": 10,
+ "day": 2,
+ "hour": 0,
+ "minute": 41,
+ "second": 17,
+ "microsecond": 74644,
+ },
+ obj,
+ )
+
+
+class TestJSONDecoder(unittest.TestCase):
+ """A JSON Decoder test class.
+
+ Test the custom json decoder class.
+
+ """
+
+ def setUp(self):
+ self.loop = asyncio.new_event_loop()
+
+ def test_dict_to_datetime(self):
+ """Test call of json decoder class.
+
+ This method will test the conversion of the dict to
+ datetime object.
+
+ """
+ test_obj = {
+ "__class__": datetime.datetime.__name__,
+ "year": 2018,
+ "month": 10,
+ "day": 2,
+ "hour": 0,
+ "minute": 41,
+ "second": 17,
+ "microsecond": 74644,
+ }
+ decoder = JSONDecoder()
+ obj = decoder(test_obj)
+ self.assertEqual(datetime.datetime(2018, 10, 2, 0, 41, 17, 74644), obj)
| Redis database keeps auto-reconnecting
<!-- Before you post an issue or if you are unsure about something join our gitter channel https://gitter.im/opsdroid/ and ask away! We are more than happy to help you. -->
# Description
I have found an issue with the Redis database, if you set Redis on your `config.yaml` but the server is not running, the client will try to reconnect to the server ad infinitum.
This is possibly an issue with `asyncio_redis` and I have raised an issue within the project ([#126](https://github.com/jonathanslenders/asyncio-redis/issues/126)).
I have tried to set `auto_reconnect` to False directly on the `connect` method, but had no change.
The`asyncio_redis` source code uses an infinite loop when trying to reconnect and this is triggered whenever the client fails to connect to the server, it should be turned off if `auto_reconnect` is set to `False` but it doesn't seem to be happening.
Finally, when we try to terminal opsdroid with SIGINT the client is unable to the terminal due to the following exception:
```python
INFO opsdroid.core: Stopping database ...
ERROR opsdroid.core: Caught exception
ERROR opsdroid.core: {'message': 'Task exception was never retrieved',
'exception': AttributeError("'NoneType' object has no attribute 'close'",),
'future': <Task finished coro=<OpsDroid.handle_signal() done, defined at /Users/fabiorosado/Documents/GitHub/opsdroid/opsdroid/core.py:120> exception=AttributeError("'NoneType' object has no attribute 'close'",)>}
```
And the asyncio_redis will keep that infinite loop until you close the terminal window 😬
Since this is an issue with `asyncio_redis` there isn't much we can do at the moment, the only thing we could try to do would be fix the `AttributeError` on `opsdroid.core.unload` - perhaps pass if this exception is raised?
## Steps to Reproduce
* Add Redis database to your `config.yaml`
* run opsdroid without starting the Redis database
## Expected Functionality
asyncio_redis shouldn't keep trying to reconnect to the client unless `reconnect` was set to true. This flag doesn't seem to be working as expected.
## Experienced Functionality
Explain what happened instead(Please include the debug log).
## Versions
- **Opsdroid version:** dev
- **Python version:** 3.7
- **OS/Docker version:** macOS 10.14.2
## Configuration File
Please include your version of the configuration file bellow.
```yaml
databases:
- name: redis
```
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
| 2019-06-02T19:21:56 |
opsdroid/opsdroid | 981 | opsdroid__opsdroid-981 | [
"980"
] | 2c9b88332a383696088771b46666e800e39afb3f | diff --git a/opsdroid/__main__.py b/opsdroid/__main__.py
--- a/opsdroid/__main__.py
+++ b/opsdroid/__main__.py
@@ -178,7 +178,6 @@ def main():
welcome_message(config)
with OpsDroid(config=config) as opsdroid:
- opsdroid.load()
opsdroid.run()
diff --git a/opsdroid/core.py b/opsdroid/core.py
--- a/opsdroid/core.py
+++ b/opsdroid/core.py
@@ -135,6 +135,7 @@ async def handle_signal(self):
def run(self):
"""Start the event loop."""
+ self.sync_load()
_LOGGER.info(_("Opsdroid is now running, press ctrl+c to exit."))
if not self.is_running():
self._running = True
@@ -151,7 +152,11 @@ def run(self):
else:
_LOGGER.error(_("Oops! Opsdroid is already running."))
- def load(self):
+ def sync_load(self):
+ """Run the load modules method synchronously."""
+ self.eventloop.run_until_complete(self.load())
+
+ async def load(self):
"""Load modules."""
self.modules = self.loader.load_modules_from_config(self.config)
_LOGGER.debug(_("Loaded %i skills"), len(self.modules["skills"]))
@@ -161,7 +166,7 @@ def load(self):
self.train_parsers(self.modules["skills"])
if self.modules["databases"] is not None:
self.start_databases(self.modules["databases"])
- self.start_connectors(self.modules["connectors"])
+ await self.start_connectors(self.modules["connectors"])
self.cron_task = self.eventloop.create_task(parse_crontab(self))
self.eventloop.create_task(self.web_server.start())
@@ -288,7 +293,7 @@ def train_parsers(self, skills):
asyncio.gather(*tasks, loop=self.eventloop)
)
- def start_connectors(self, connectors):
+ async def start_connectors(self, connectors):
"""Start the connectors."""
for connector_module in connectors:
for _, cls in connector_module["module"].__dict__.items():
@@ -302,10 +307,7 @@ def start_connectors(self, connectors):
if connectors:
for connector in self.connectors:
- if self.eventloop.is_running():
- self.eventloop.create_task(connector.connect())
- else:
- self.eventloop.run_until_complete(connector.connect())
+ await connector.connect()
for connector in self.connectors:
task = self.eventloop.create_task(connector.listen())
self.connector_tasks.append(task)
diff --git a/opsdroid/loader.py b/opsdroid/loader.py
--- a/opsdroid/loader.py
+++ b/opsdroid/loader.py
@@ -177,20 +177,28 @@ def build_module_install_path(self, config):
return os.path.join(self.modules_directory, config["type"], config["name"])
@staticmethod
- def git_clone(git_url, install_path, branch):
+ def git_clone(git_url, install_path, branch, key_path=None):
"""Clone a git repo to a location and wait for finish.
Args:
git_url: The url to the git repository
install_path: Location where the git repository will be cloned
branch: The branch to be cloned
+ key_path: SSH Key for git repository
"""
+ git_env = os.environ.copy()
+ if key_path:
+ git_env[
+ "GIT_SSH_COMMAND"
+ ] = f"ssh -i {key_path} -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no"
+
process = subprocess.Popen(
["git", "clone", "-b", branch, git_url, install_path],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
+ env=git_env,
)
Loader._communicate_process(process)
@@ -607,11 +615,12 @@ def _install_git_module(self, config):
else:
git_url = DEFAULT_GIT_URL + config["type"] + "-" + config["name"] + ".git"
- if any(prefix in git_url for prefix in ["http", "https", "ssh"]):
+ if any(prefix in git_url for prefix in ["http", "https", "ssh", "git@"]):
# TODO Test if url or ssh path exists
# TODO Handle github authentication
_LOGGER.info(_("Cloning %s from remote repository"), config["name"])
- self.git_clone(git_url, config["install_path"], config["branch"])
+ key_path = config.get("key_path", None)
+ self.git_clone(git_url, config["install_path"], config["branch"], key_path)
else:
if os.path.isdir(git_url):
_LOGGER.debug(_("Cloning %s from local repository"), config["name"])
| diff --git a/tests/test_core.py b/tests/test_core.py
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -62,7 +62,7 @@ def test_load_modules(self):
"connectors": [],
}
with self.assertRaises(SystemExit):
- opsdroid.load()
+ opsdroid.eventloop.run_until_complete(opsdroid.load())
self.assertTrue(opsdroid.loader.load_modules_from_config.called)
def test_run(self):
@@ -84,6 +84,7 @@ def test_run_cancelled(self):
opsdroid.eventloop.run_until_complete = mock.Mock(
side_effect=asyncio.CancelledError
)
+ opsdroid.sync_load = mock.MagicMock()
with mock.patch("sys.exit") as mock_sysexit:
opsdroid.run()
@@ -98,6 +99,7 @@ def test_run_already_running(self):
opsdroid.eventloop.run_until_complete = mock.Mock(
side_effect=asyncio.CancelledError
)
+ opsdroid.sync_load = mock.MagicMock()
with mock.patch("sys.exit") as mock_sysexit:
opsdroid.run()
@@ -120,9 +122,9 @@ def test_load(self, mocked_parse_crontab):
)
opsdroid.start_databases = mock.Mock()
opsdroid.setup_skills = mock.Mock()
- opsdroid.start_connectors = mock.Mock()
+ opsdroid.start_connectors = amock.CoroutineMock()
- opsdroid.load()
+ opsdroid.eventloop.run_until_complete(opsdroid.load())
self.assertTrue(opsdroid.start_databases.called)
self.assertTrue(opsdroid.start_connectors.called)
@@ -139,44 +141,6 @@ def test_start_databases(self):
opsdroid.start_databases([module])
self.assertEqual(1, len(opsdroid.memory.databases))
- def test_start_connectors(self):
- with OpsDroid() as opsdroid:
- opsdroid.start_connectors([])
-
- module = {}
- module["config"] = {}
- module["module"] = importlib.import_module(
- "tests.mockmodules.connectors.connector_mocked"
- )
-
- try:
- opsdroid.start_connectors([module])
- except NotImplementedError:
- self.fail("Connector raised NotImplementedError.")
- self.assertEqual(len(opsdroid.connectors), 1)
-
- with mock.patch.object(opsdroid.eventloop, "is_running", return_value=True):
- opsdroid.start_connectors([module])
- self.assertEqual(len(opsdroid.connectors), 2)
-
- def test_start_connectors_not_implemented(self):
- with OpsDroid() as opsdroid:
- opsdroid.start_connectors([])
-
- module = {}
- module["config"] = {}
- module["module"] = importlib.import_module(
- "tests.mockmodules.connectors.connector_bare"
- )
-
- with self.assertRaises(NotImplementedError):
- opsdroid.start_connectors([module])
- self.assertEqual(1, len(opsdroid.connectors))
-
- with self.assertRaises(NotImplementedError):
- opsdroid.start_connectors([module, module])
- self.assertEqual(3, len(opsdroid.connectors))
-
def test_multiple_opsdroids(self):
with OpsDroid() as opsdroid:
opsdroid.__class__.critical = mock.MagicMock()
@@ -488,3 +452,41 @@ async def test_send_name(self):
message = patched_send.call_args[0][0]
assert message is input_message
+
+ async def test_start_connectors(self):
+ with OpsDroid() as opsdroid:
+ opsdroid.start_connectors([])
+
+ module = {}
+ module["config"] = {}
+ module["module"] = importlib.import_module(
+ "tests.mockmodules.connectors.connector_mocked"
+ )
+
+ try:
+ await opsdroid.start_connectors([module])
+ except NotImplementedError:
+ self.fail("Connector raised NotImplementedError.")
+ self.assertEqual(len(opsdroid.connectors), 1)
+
+ with mock.patch.object(opsdroid.eventloop, "is_running", return_value=True):
+ await opsdroid.start_connectors([module])
+ self.assertEqual(len(opsdroid.connectors), 2)
+
+ async def test_start_connectors_not_implemented(self):
+ with OpsDroid() as opsdroid:
+ opsdroid.start_connectors([])
+
+ module = {}
+ module["config"] = {}
+ module["module"] = importlib.import_module(
+ "tests.mockmodules.connectors.connector_bare"
+ )
+
+ with self.assertRaises(NotImplementedError):
+ await opsdroid.start_connectors([module])
+ self.assertEqual(1, len(opsdroid.connectors))
+
+ with self.assertRaises(NotImplementedError):
+ await opsdroid.start_connectors([module, module])
+ self.assertEqual(3, len(opsdroid.connectors))
diff --git a/tests/test_loader.py b/tests/test_loader.py
--- a/tests/test_loader.py
+++ b/tests/test_loader.py
@@ -1,4 +1,3 @@
-import sys
import os
import shutil
import subprocess
@@ -65,7 +64,7 @@ def test_load_config_valid_without_db_and_parsers(self):
def test_load_config_broken_without_connectors(self):
opsdroid, loader = self.setup()
with self.assertRaises(SystemExit) as cm:
- config = loader.load_config_file(
+ _ = loader.load_config_file(
[os.path.abspath("tests/configs/broken_without_connectors.yaml")]
)
self.assertEqual(cm.exception.code, 1)
@@ -81,7 +80,7 @@ def test_load_config_broken(self):
opsdroid, loader = self.setup()
with self.assertRaises(SystemExit) as cm:
- config = loader.load_config_file(
+ _ = loader.load_config_file(
[os.path.abspath("tests/configs/full_broken.yaml")]
)
self.assertEqual(cm.exception.code, 1)
@@ -105,7 +104,7 @@ def test_load_exploit(self):
"""
opsdroid, loader = self.setup()
with self.assertRaises(SystemExit):
- config = loader.load_config_file(
+ _ = loader.load_config_file(
[os.path.abspath("tests/configs/include_exploit.yaml")]
)
self.assertLogs("_LOGGER", "critical")
@@ -182,12 +181,16 @@ def test_load_broken_config_file(self):
def test_git_clone(self):
with mock.patch.object(subprocess, "Popen") as mock_subproc_popen:
opsdroid, loader = self.setup()
+ myrsa = "/path/to/my/id_rsa"
loader.git_clone(
"https://github.com/rmccue/test-repository.git",
os.path.join(self._tmp_dir, "/test"),
"master",
+ myrsa,
)
self.assertTrue(mock_subproc_popen.called)
+ _, mock_subproc_popen_kwargs = mock_subproc_popen.call_args
+ assert myrsa in mock_subproc_popen_kwargs["env"]["GIT_SSH_COMMAND"]
def test_git_pull(self):
with mock.patch.object(subprocess, "Popen") as mock_subproc_popen:
@@ -511,7 +514,29 @@ def test_install_specific_remote_module(self):
) as mockclone:
loader._install_module(config)
mockclone.assert_called_with(
- config["repo"], config["install_path"], config["branch"]
+ config["repo"], config["install_path"], config["branch"], None
+ )
+
+ def test_install_specific_remote_module_ssl(self):
+ opsdroid, loader = self.setup()
+ config = {
+ "name": "testmodule",
+ "install_path": os.path.join(self._tmp_dir, "test_specific_remote_module"),
+ "repo": "https://github.com/rmccue/test-repository.git",
+ "branch": "master",
+ "key_path": os.path.join(
+ self._tmp_dir, os.path.normpath("install/from/here.key")
+ ),
+ }
+ with mock.patch("opsdroid.loader._LOGGER.debug"), mock.patch.object(
+ loader, "git_clone"
+ ) as mockclone:
+ loader._install_module(config)
+ mockclone.assert_called_with(
+ config["repo"],
+ config["install_path"],
+ config["branch"],
+ config["key_path"],
)
def test_install_specific_local_git_module(self):
@@ -600,6 +625,7 @@ def test_install_default_remote_module(self):
+ ".git",
config["install_path"],
config["branch"],
+ None,
)
shutil.rmtree(config["install_path"], onerror=del_rw)
diff --git a/tests/test_main.py b/tests/test_main.py
--- a/tests/test_main.py
+++ b/tests/test_main.py
@@ -151,8 +151,6 @@ def test_main(self):
) as mock_cl, mock.patch.object(
opsdroid, "welcome_message"
) as mock_wm, mock.patch.object(
- OpsDroid, "load"
- ) as mock_load, mock.patch.object(
web, "Web"
), mock.patch.object(
OpsDroid, "run"
@@ -162,5 +160,4 @@ def test_main(self):
self.assertTrue(mock_cd.called)
self.assertTrue(mock_cl.called)
self.assertTrue(mock_wm.called)
- self.assertTrue(mock_load.called)
self.assertTrue(mock_loop.called)
| Possible to Specify ssh key for private github skill
<!-- Before you post an issue or if you are unsure about something join our gitter channel https://gitter.im/opsdroid/ and ask away! We are more than happy to help you. -->
# Description
We almost exclusively use private github repo's, in our github enterprise. It would be ideal if I could load a key into the docker container as a secret or config, and reference it in the configuration to be used when pulling the skill.
## Steps to Reproduce
Currently, unable to pull in a private ssh repo, without rebuilding the docker image
## Expected Functionality
```
skills:
## AWX (https://github.com/jseiser/skill-awx)
- name: awx
repo: https://github.com/jseiser/skill-nothing.git
no-cache: true
key: /root/.config/opsroid/whatever.pem
```
## Experienced Functionality
Explain what happened instead(Please include the debug log).
## Versions
- **Opsdroid version:**
- **Python version:**
- **OS/Docker version:**
## Configuration File
Please include your version of the configuration file bellow.
```yaml
# Your code goes here.
```
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| 2019-06-05T18:41:37 |
|
opsdroid/opsdroid | 988 | opsdroid__opsdroid-988 | [
"881",
"886"
] | 2d992b3c1b1c794aad6a4244a5338a69d9aade5a | diff --git a/opsdroid/parsers/rasanlu.py b/opsdroid/parsers/rasanlu.py
--- a/opsdroid/parsers/rasanlu.py
+++ b/opsdroid/parsers/rasanlu.py
@@ -114,17 +114,41 @@ async def train_rasanlu(config, skills):
return False
if resp.status == 200:
- result = await resp.json()
- if "info" in result and "new model trained" in result["info"]:
+ if resp.content_type == "application/json":
+ result = await resp.json()
+ if "info" in result and "new model trained" in result["info"]:
+ time_taken = (arrow.now() - training_start).total_seconds()
+ _LOGGER.info(
+ _("Rasa NLU training completed in %s seconds."), int(time_taken)
+ )
+ await _init_model(config)
+ return True
+
+ _LOGGER.debug(result)
+ if (
+ resp.content_type == "application/zip"
+ and resp.content_disposition.type == "attachment"
+ ):
time_taken = (arrow.now() - training_start).total_seconds()
_LOGGER.info(
_("Rasa NLU training completed in %s seconds."), int(time_taken)
)
await _init_model(config)
+ """
+ As inditated in the issue #886, returned zip file is ignored, this can be changed
+ This can be changed in future release if needed
+ Saving model.zip file example :
+ try:
+ output_file = open("/target/directory/model.zip","wb")
+ data = await resp.read()
+ output_file.write(data)
+ output_file.close()
+ _LOGGER.debug("Rasa taining model file saved to /target/directory/model.zip")
+ except:
+ _LOGGER.error("Cannot save rasa taining model file to /target/directory/model.zip")
+ """
return True
- _LOGGER.debug(result)
-
_LOGGER.error(_("Bad Rasa NLU response - %s"), await resp.text())
_LOGGER.error(_("Rasa NLU training failed."))
return False
| diff --git a/tests/test_parser_rasanlu.py b/tests/test_parser_rasanlu.py
--- a/tests/test_parser_rasanlu.py
+++ b/tests/test_parser_rasanlu.py
@@ -419,7 +419,7 @@ async def test__get_existing_models_fails(self):
models = await rasanlu._get_existing_models({})
self.assertEqual(models, [])
- async def test_train_rasanlu(self):
+ async def test_train_rasanlu_fails(self):
result = amock.Mock()
result.status = 404
result.text = amock.CoroutineMock()
@@ -462,12 +462,55 @@ async def test_train_rasanlu(self):
patched_request.return_value.set_result(result)
self.assertEqual(await rasanlu.train_rasanlu({}, {}), False)
- result.status = 200
+ result.json.return_value = {"info": "error"}
+ patched_request.return_value = asyncio.Future()
+ patched_request.side_effect = None
+ patched_request.return_value.set_result(result)
+ self.assertEqual(await rasanlu.train_rasanlu({}, {}), False)
+
+ async def test_train_rasanlu_succeeded(self):
+ result = amock.Mock()
+ result.text = amock.CoroutineMock()
+ result.json = amock.CoroutineMock()
+ result.status = 200
+ result.json.return_value = {"info": "new model trained: abc1234"}
+
+ with amock.patch(
+ "aiohttp.ClientSession.post"
+ ) as patched_request, amock.patch.object(
+ rasanlu, "_get_all_intents"
+ ) as mock_gai, amock.patch.object(
+ rasanlu, "_init_model"
+ ) as mock_im, amock.patch.object(
+ rasanlu, "_build_training_url"
+ ) as mock_btu, amock.patch.object(
+ rasanlu, "_get_existing_models"
+ ) as mock_gem, amock.patch.object(
+ rasanlu, "_get_intents_fingerprint"
+ ) as mock_gif:
+
+ mock_gem.return_value = ["abc123"]
+ mock_btu.return_value = "http://example.com"
+ mock_gai.return_value = "Hello World"
+ mock_gif.return_value = "abc1234"
+ result.content_type = "application/json"
+
+ patched_request.side_effect = None
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(result)
self.assertEqual(await rasanlu.train_rasanlu({}, {}), True)
- result.json.return_value = {"info": "error"}
+ result.json.return_value = {}
+ patched_request.side_effect = None
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(result)
self.assertEqual(await rasanlu.train_rasanlu({}, {}), False)
+
+ result.content_type = "application/zip"
+ result.content_disposition.type = "attachment"
+ result.json.return_value = {"info": "new model trained: abc1234"}
+
+ patched_request.side_effect = None
+ patched_request.return_value = asyncio.Future()
+ patched_request.return_value.set_result(result)
+ self.assertEqual(await rasanlu.train_rasanlu({}, {}), True)
| Fixing rasanlu parser : dict object has no attribute matchers issue #860
# Description
When using rasanlu parser with no intents file (no need to train the module, already done) an attribute issue error happened in function _get_all_intents(skills)
...
matchers = [matcher for skill in skills for matcher in skill.matchers]
File "/Users/IOBreaker/Developments/Bots/opsdroid/opsdroid/parsers/rasanlu.py", line 19, in <listcomp>
matchers = [matcher for skill in skills for matcher in skill.matchers]
AttributeError: 'dict' object has no attribute 'matchers'
Fixes #860
After discussion with @jacobtomlinson the decision was to go using intents provided directly by the skill dict.
Beside, an other correction was added to this fixes according to [rasa_nlu](https://github.com/RasaHQ/rasa_nlu/blob/master/docs/http.rst#post-train) documentation
```
The request should always be sent as application/x-yml regardless of wether you use json or md for the data format. Do not send json as application/json for example.
```
## Status
**READY** | **~UNDER DEVELOPMENT~** | **~ON HOLD~**
## Type of change
- Bug fix (non-breaking change which fixes an issue)
# How Has This Been Tested?
I tested the fix on my environment, no issue detected
# Checklist:
- [x] I have performed a self-review of my own code
- [ ] I have made corresponding changes to the documentation (if applicable)
- [x] I have added tests that prove my fix is effective or that my feature works (test file modification)
- [x] New and existing unit tests pass locally with my changes
- [x] Tox ok
rasanlu parser does not manage the new returned response after training request
# Description
This issue was initially detected by @jhofeditz when testing the fix #881.
The new rasanlu trainer instead of returning a json response after a model training, it return a zip file with all files generated by the trainer.
## Steps to Reproduce
1- Download docker image rasa/rasa_nlu:latest-spacy
2- Start docker image
3- Use a skill that interact with rasanlu and that need rasa to be trained using an intents.yml file
4- activate the skill in your opsdroid config file
5- Start opsdroid
## Expected Functionality
Opsdroid should be capable to manage json response and zip response
## Experienced Functionality
Crash of opsdroid due to parsing error
## Versions
- **Opsdroid version: v0.14.1+37.ge71ea43**
- **Rasanlu version: 0.15.0a1**
- **Python version: 3.7.2**
- **OS/Docker version: Docker version 18.09.2, build 6247962 **
## Additional Details
**From Rasa side :**
```
2019-03-30 11:37:34 INFO rasa_nlu.data_router - Logging of requests is disabled. (No 'request_log' directory configured)
2019-03-30 11:37:34 INFO __main__ - Started http server on port 5000
2019-03-30 11:37:34+0000 [-] Log opened.
2019-03-30 11:37:34+0000 [-] Site starting on 5000
2019-03-30 11:37:34+0000 [-] Starting factory <twisted.web.server.Site object at 0x7f65ffbff470>
2019-03-30 11:50:43+0000 [-] 2019-03-30 11:50:43 DEBUG rasa_nlu.data_router - New training queued
Fitting 2 folds for each of 6 candidates, totalling 12 fits
[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
[Parallel(n_jobs=1)]: Done 12 out of 12 | elapsed: 0.0s finished
2019-03-30 11:50:59+0000 [-] "172.17.0.1" - - [30/Mar/2019:11:50:58 +0000] "POST /train?project=ergo&fixed_model_name=1c0badaf3eb8c2bf6546465eadfd8492e7d79c1f0f3520d103d4bc39b4bfc&token=sfgz654zfg546qs4fg646rg64efg HTTP/1.1" 200 11767 "-" "Python/3.7 aiohttp/3.5.4"
2019-03-30 11:53:24+0000 [-] "172.17.0.1" - - [30/Mar/2019:11:53:23 +0000] "GET / HTTP/1.1" 200 29 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0"
2019-03-30 11:53:24+0000 [-] "172.17.0.1" - - [30/Mar/2019:11:53:23 +0000] "GET /favicon.ico HTTP/1.1" 404 233 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0"
2019-03-30 11:54:24+0000 [-] Timing out client: IPv4Address(type='TCP', host='172.17.0.1', port=59948)
```
**From Opsdroid side :**
```
INFO opsdroid.parsers.rasanlu: Starting Rasa NLU training.
INFO opsdroid.parsers.rasanlu: Now training the model. This may take a while...
DEBUG asyncio: Using selector: KqueueSelector
Traceback (most recent call last):
...
File "/Users/hicham/Developments/Bots/opsdroid-iobreaker/opsdroid/opsdroid/parsers/rasanlu.py", line 117, in train_rasanlu
result = await resp.json()
File "/Users/hicham/.virtualenvs/opsdroid/lib/python3.7/site-packages/aiohttp/client_reqrep.py", line 1027, in json
headers=self.headers)
aiohttp.client_exceptions.ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: application/zip'
```
| # [Codecov](https://codecov.io/gh/opsdroid/opsdroid/pull/881?src=pr&el=h1) Report
> Merging [#881](https://codecov.io/gh/opsdroid/opsdroid/pull/881?src=pr&el=desc) into [master](https://codecov.io/gh/opsdroid/opsdroid/commit/de8d5ec638f8f32b5b130f2862f01894a17e9ee1?src=pr&el=desc) will **not change** coverage.
> The diff coverage is `100%`.
[](https://codecov.io/gh/opsdroid/opsdroid/pull/881?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #881 +/- ##
=====================================
Coverage 100% 100%
=====================================
Files 34 34
Lines 2200 2200
=====================================
Hits 2200 2200
```
| [Impacted Files](https://codecov.io/gh/opsdroid/opsdroid/pull/881?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [opsdroid/parsers/rasanlu.py](https://codecov.io/gh/opsdroid/opsdroid/pull/881/diff?src=pr&el=tree#diff-b3BzZHJvaWQvcGFyc2Vycy9yYXNhbmx1LnB5) | `100% <100%> (ø)` | :arrow_up: |
| [opsdroid/loader.py](https://codecov.io/gh/opsdroid/opsdroid/pull/881/diff?src=pr&el=tree#diff-b3BzZHJvaWQvbG9hZGVyLnB5) | `100% <100%> (ø)` | :arrow_up: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/opsdroid/opsdroid/pull/881?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/opsdroid/opsdroid/pull/881?src=pr&el=footer). Last update [de8d5ec...a0694e1](https://codecov.io/gh/opsdroid/opsdroid/pull/881?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
I did some other tests about Content Type and bellow what i've got as results :
### Test 1
- Content-Type : Application/x-yml
- file type : intents.md
- File Content :
```yaml
## intent:user_say_iam_back
i am back
i am back again
back again
```
- Result
```json
{
"error": "Content-Type must be 'application/x-yml' or 'application/json'"
}
```
### Test 2
- Content-Type : Application/json
- file type : intents.json
- File Content :
```json
{
"rasa_nlu_data": {
"regex_features": [
],
"entity_synonyms": [
],
"common_examples": [
{
"text": "i am back",
"intent": "user_is_back",
"entities": [
]
},
{
"text": "i am back again",
"intent": "user_is_back",
"entities": [
]
},
{
"text": "back again",
"intent": "user_is_back",
"entities": [
]
}
]
}
}
```
- Result
```json
{
"info": "new model trained",
"model": "ergo"
}
```
### Test 3
The same config as Test 2, the only difference here is using
- Content-Type : Application/x-yml
- Result
```json
{
"error": "argument of type 'NoneType' is not iterable"
}
```
I'd like to have your feedback about that please
Regards
I founded why we have this behaviours. As you can check [here](https://github.com/RasaHQ/rasa_nlu/blob/master/sample_configs/config_train_server_md.yml) in RasaHQ github docs, the file format has changed.
So i changed the intents.md file format and the training was successful
- Content-Type : Application/x-yml
- File type : intents.md
- File Content :
```yaml
language: "en"
pipeline: "spacy_sklearn"
# data contains the same md, as described in the training data section
data: |
## intent:user_say_iam_back
- i am back
- i am back again
- back again
```
- Opsdroid side
```
INFO opsdroid.parsers.rasanlu: Starting Rasa NLU training.
INFO opsdroid.parsers.rasanlu: Now training the model. This may take a while...
INFO opsdroid.parsers.rasanlu: Rasa NLU training completed in 0 seconds.
INFO opsdroid.parsers.rasanlu: Initialising Rasa NLU model.
DEBUG opsdroid.parsers.rasanlu: Rasa NLU response - {"intent": {"name": null, "confidence": 0.0}, "entities": [], "text": "", "project": "ergo", "model": "model_20190320-144251"}
INFO opsdroid.parsers.rasanlu: Initialisation complete in 1 seconds.
DEBUG opsdroid.connector.websocket: Starting Websocket connector
DEBUG opsdroid.connector.telegram: Loaded telegram connector
```
- Rasanlu server side result
```
2019-03-20 14:42:50+0100 [-] "127.0.0.1" - - [20/Mar/2019:13:42:50 +0000] "GET /status HTTP/1.1" 200 459 "-" "Python/3.7 aiohttp/3.5.4"
2019-03-20 14:42:50+0100 [-] 2019-03-20 14:42:50 DEBUG rasa_nlu.data_router - New training queued
2019-03-20 14:42:51+0100 [-] "127.0.0.1" - - [20/Mar/2019:13:42:51 +0000] "POST /train?project=ergo&fixed_model_name=326346356235623562356fdgsdfbgdf324562362356&token=ed6ahthogeexoonahL7gof1maGh1EiSDF5Hi8sd HTTP/1.1" 200 69 "-" "Python/3.7 aiohttp/3.5.4"
2019-03-20 14:42:52+0100 [-] 2019-03-20 14:42:52 INFO rasa_nlu.components - Added 'nlp_spacy' to component cache. Key 'nlp_spacy-en'.
2019-03-20 14:42:52+0100 [-] "127.0.0.1" - - [20/Mar/2019:13:42:52 +0000] "POST /parse HTTP/1.1" 200 150 "-" "Python/3.7 aiohttp/3.5.4"
```
- Response :
```
{
"info": "new model trained",
"model": "ergo"
}
```
Please can you check from your side and confirm
Next step if it's confirmed is to update the rasanlu.md documentation (about intents.md provided example).
```yaml
## intent:greetings
- Hey
- Hello
- Hi
- Hiya
- hey
- whats up
- wazzup
- heya
```
A nice to have future will be json support ;-)
Regards
This looks great. It's a shame that rasa have broken the format upstream, but I feel like their move to yaml/json is probably a good one.
We should probably modify the code to stop looking for `intents.md` and instead look for `intents.yaml`, `intents.yml` or `intents.json`. This would mean we can support all the formats above.
Would you be happy to make this change here?
It would be great to support json and yaml intent files.
I am going to change the **def _load_intents(config)** in **loader.py** function to load **intents.yml** instead of **intents.md** and modify the corresponding docs to indicate the new why to implement the intent file. This will allow us to close the ongoing issue.
When it's done, why not working on json, yml, yaml support :-)
I changed as discussed the code to manage intents.yml file in loader and tests files.
I updated the doc to reflct the new intents.yml file format.
can you please check
```
SKIPPED: py35: InterpreterNotFound: python3.5
py36: commands succeeded
py37: commands succeeded
lint: commands succeeded
docker: commands succeeded
congratulations :)
```
@iobreaker I am also testing rasa with opsdroid and cloned your repo to test. I just installed the latest Rasa NLU and the API /train endpoint is returning zip content
https://github.com/RasaHQ/rasa_nlu/blob/master/rasa/nlu/server.py#L277
This makes training fail:
> aiohttp.client_exceptions.ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: application/zip'
I only picked up opsdroid today and rasa yesterday, so I might be missing something...
Hi @jhofeditz,
can you please explain exactly how are you using opsdroid with rasanlu
- The content of your intents.yml
- The cli you are using to start rasa server
- The debug log from opsdroid
From my side i can train my model with no problem, bellow an example :
**From rasanlu side**
```
2019-03-27 23:36:43+0100 [-] Starting factory <twisted.web.server.Site object at 0x1310bfa90>
2019-03-27 23:39:14+0100 [-] "127.0.0.1" - - [27/Mar/2019:22:39:13 +0000] "GET /status HTTP/1.1" 200 296 "-" "Python/3.7 aiohttp/3.5.4"
2019-03-27 23:39:14+0100 [-] 2019-03-27 23:39:14 DEBUG rasa_nlu.data_router - New training queued
2019-03-27 23:39:18+0100 [-] "127.0.0.1" - - [27/Mar/2019:22:39:18 +0000] "POST /train?project=ergo&fixed_model_name=5feade1d4feffab3add74c192b2576aea2c76ae4643f6b58467cb69997177616&token=zgazrg345efgez45rtherthtrh454 HTTP/1.1" 200 69 "-" "Python/3.7 aiohttp/3.5.4"
2019-03-27 23:39:18+0100 [-] 2019-03-27 23:39:18 WARNING rasa_nlu.project - Invalid model requested. Using default
2019-03-27 23:39:19+0100 [-] 2019-03-27 23:39:19 INFO rasa_nlu.components - Added 'nlp_spacy' to component cache. Key 'nlp_spacy-en'.
2019-03-27 23:39:20+0100 [-] "127.0.0.1" - - [27/Mar/2019:22:39:19 +0000] "POST /parse HTTP/1.1" 200 150 "-" "Python/3.7 aiohttp/3.5.4"
```
**From opsdroid side**
```
DEBUG opsdroid.core: Loaded 2 skills
INFO opsdroid.parsers.rasanlu: Starting Rasa NLU training.
INFO opsdroid.parsers.rasanlu: Now training the model. This may take a while...
INFO opsdroid.parsers.rasanlu: Rasa NLU training completed in 4 seconds.
INFO opsdroid.parsers.rasanlu: Initialising Rasa NLU model.
DEBUG opsdroid.parsers.rasanlu: Rasa NLU response - {"intent": {"name": null, "confidence": 0.0}, "entities": [], "text": "", "project": "ergo", "model": "model_20190327-233918"}
INFO opsdroid.parsers.rasanlu: Initialisation complete in 1 seconds.
DEBUG opsdroid.connector.websocket: Starting Websocket connector
DEBUG opsdroid.connector.telegram: Loaded telegram connector
DEBUG opsdroid.connector.telegram: Connecting to telegram
INFO opsdroid.core: Opsdroid is now running, press ctrl+c to exit.
INFO opsdroid.web: Started web server on http://127.0.0.1:8080
```
**Test sending yes from telegram to opsdroid after training**
```
DEBUG opsdroid.core: Parsing input: yes
DEBUG opsdroid.core: Processing parsers...
DEBUG opsdroid.core: Checking Rasa NLU...
DEBUG opsdroid.parsers.rasanlu: Rasa NLU response - {"intent": {"name": "affirm", "confidence": 0.8618867670286532}, "entities": [], "intent_ranking": [{"name": "affirm", "confidence": 0.8618867670286532}, ], "text": "yes", "project": "ergo", "model": "model_20190327-233918"}
```
Thx
ah, I was using the `rasa/rasa_nlu:latest-spacy` docker image. When I switch to `0.14.4-spacy` (or `pip install rasa-nlu`) I get the expected yml output.
So, it's either a breaking change in 0.15 or a bug.
Thank you for working on this issue @iobreaker, I am a bit worried about the breaking change of the future versions of rasa nlu, but this is something we will have to tackle when they release the next version.
Jacob seems to be happy with the PR as well so I am going to merge it now to master 😄 👍
@jhofeditz can you please log an issue and describe exactly how to reproduce it (env, cli, config ...)
@FabioRosado because opsdroid is an opensource project with no commitments about releases (best efforts) i think a best practices will be :
- Indicate in the documentation which versions opsdroid support for each external module or parser ...
- For each code that need to address an external resources, a check of supported version should be done by the developer to avoid crashes or a bad behaviors.
I started working on a fix that detect if the returned data is a json one or a zip one.
Now opsdroid know how to deal with it
### Example :
**From Opsdroid Side:**
```
INFO opsdroid.parsers.rasanlu: Starting Rasa NLU training.
INFO opsdroid.parsers.rasanlu: Now training the model. This may take a while...
INFO opsdroid.parsers.rasanlu: Rasa NLU training completed in 16 seconds.
INFO opsdroid.parsers.rasanlu: Initialising Rasa NLU model.
DEBUG opsdroid.parsers.rasanlu: Rasa NLU response - {"intent": {"name": null, "confidence": 0.0}, "entities": [], "text": "", "project": "ergo", "model": "model_20190330-121825"}
INFO opsdroid.parsers.rasanlu: Initialisation complete in 15 seconds.
DEBUG opsdroid.parsers.rasanlu: =====> Model file saved to : /Users/hicham/Desktop/model.zip
```
**From Rasanlu side :**
```
2019-03-30 12:18:09+0000 [-] 2019-03-30 12:18:09 DEBUG rasa_nlu.data_router - New training queued
Fitting 2 folds for each of 6 candidates, totalling 12 fits
[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
[Parallel(n_jobs=1)]: Done 12 out of 12 | elapsed: 0.0s finished
2019-03-30 12:18:26+0000 [-] "172.17.0.1" - - [30/Mar/2019:12:18:26 +0000] "POST /train?project=ergo&fixed_model_name=1c0badaf3eb8c2bfc535cf8553eadfd8492e7d79c1f0f3520d103d4bc39b4bfc&token=fg31d3f5g4e3b13fds21bh3eth13eg1he5zt HTTP/1.1" 200 11766 "-" "Python/3.7 aiohttp/3.5.4"
```
**Testing the new model (intent:affirm) :**
```
DEBUG opsdroid.connector.telegram: {'update_id': 246644773, 'message': {'message_id': 656, 'from': {'id': 65465465, 'is_bot': False, 'first_name': 'IOBreaker', 'language_code': 'en'}, 'chat': {'id': 452282388, 'first_name': 'IOBreaker', 'type': 'private'}, 'date': 1553948755, 'text': 'yes'}}
DEBUG opsdroid.core: Parsing input: yes
DEBUG opsdroid.core: Processing parsers...
DEBUG opsdroid.core: Checking Rasa NLU...
DEBUG opsdroid.parsers.rasanlu: Rasa NLU response - {"intent": {"name": "affirm", "confidence": 0.8215188398116678}, "entities": [], "intent_ranking": [{"name": "affirm", "confidence": 0.8215188398116678}, {"name": "user_say_iam_back", "confidence": 0.09246078336795119}, {"name": "goodbye", "confidence": 0.08602037682038108}], "text": "yes", "project": "ergo", "model": "model_20190330-121825"}
```
Now still 2 things to address :
- Finding why rasa keep training models even if it is the same as before (already trained)
- What to do with the returned zip
+ Just ignore it
+ Add entry in opsdroid config file to allow user to save it in a location or ignore it
+ Extract files and do things
Do not hesitate if you have any ideas :-)
really, do not hesitate to comment :-)
ok no answer :-(
So I am going to ignore the returned zip for the moment and deal with that in new version if needed
Sorry! That sounds good.
Ok Thanks :-)
Will apply the changes and submit a PR | 2019-06-10T15:43:00 |
opsdroid/opsdroid | 1,003 | opsdroid__opsdroid-1003 | [
"770"
] | a6c3b0db765fede8cc706fc512344464ea847758 | diff --git a/opsdroid/loader.py b/opsdroid/loader.py
--- a/opsdroid/loader.py
+++ b/opsdroid/loader.py
@@ -2,6 +2,7 @@
# pylint: disable=too-many-branches
+import yamale
import importlib
import importlib.util
import json
@@ -351,10 +352,20 @@ def include_constructor(loader, node):
try:
with open(config_path, "r") as stream:
_LOGGER.info(_("Loaded config from %s."), config_path)
+ schema_path = os.path.abspath("opsdroid/configuration/schema.yaml")
+ schema = yamale.make_schema(schema_path)
+ data = yamale.make_data(config_path)
+ yamale.validate(schema, data)
return yaml.safe_load(stream)
+
+ except ValueError as error:
+ _LOGGER.critical(error)
+ sys.exit(1)
+
except yaml.YAMLError as error:
_LOGGER.critical(error)
sys.exit(1)
+
except FileNotFoundError as error:
_LOGGER.critical(error)
sys.exit(1)
| diff --git a/tests/configs/broken_without_connectors.yaml b/tests/configs/broken_without_connectors.yaml
new file mode 100644
--- /dev/null
+++ b/tests/configs/broken_without_connectors.yaml
@@ -0,0 +1,3 @@
+skills:
+ - name: hello
+ - name: seen
diff --git a/tests/configs/full_broken.yaml b/tests/configs/full_broken.yaml
new file mode 100644
--- /dev/null
+++ b/tests/configs/full_broken.yaml
@@ -0,0 +1,35 @@
+connectors:
+
+ - name: # WRONG CONFIG: the name field is missing
+ bot-name: "mybot"
+ max-connections: 10
+ connection-timeout: 10
+
+ - name: facebook
+ verify-token: aabbccddee
+ page-access-token: aabbccddee112233445566
+ bot-name: "mybot"
+
+ - name: github
+ github-token: aaabbbcccdddeee111222333444
+
+databases:
+ - name: mongo
+ host: "my host"
+ port: "12345"
+ database: "mydatabase"
+
+ - name: redis
+ host: "my host"
+ port: "12345"
+ database: "7"
+
+ - name: sqlite
+ file: "my_file.db"
+ table: "my_table"
+
+skills:
+ - name: dance
+ - name: hello
+ - name: loudnoises
+ - name: seen
diff --git a/tests/configs/full_valid.yaml b/tests/configs/full_valid.yaml
new file mode 100644
--- /dev/null
+++ b/tests/configs/full_valid.yaml
@@ -0,0 +1,31 @@
+welcome-message: true
+
+connectors:
+
+ - name: websocket
+ bot-name: "mybot"
+ max-connections: 10
+ connection-timeout: 10
+
+databases:
+
+ - name: mongo
+ host: "my host"
+ port: "12345"
+ database: "mydatabase"
+
+parsers:
+
+ - name: dialogflow
+ access-token: "exampleaccesstoken123"
+ min-score: 0.6
+
+skills:
+
+ - name: dance
+
+ - name: hello
+
+ - name: loudnoises
+
+ - name: seen
diff --git a/tests/configs/minimal.yaml b/tests/configs/minimal.yaml
--- a/tests/configs/minimal.yaml
+++ b/tests/configs/minimal.yaml
@@ -1,6 +1,6 @@
connectors:
- shell:
+ - name: shell
skills:
- hello:
- seen:
+ - name: hello
+ - name: seen
diff --git a/tests/configs/minimal_2.yaml b/tests/configs/minimal_2.yaml
--- a/tests/configs/minimal_2.yaml
+++ b/tests/configs/minimal_2.yaml
@@ -1,9 +1,9 @@
connectors:
- shell:
+ - name: shell
skills:
- hello:
- seen:
+ - name: hello
+ - name: seen
databases:
diff --git a/tests/configs/minimal_with_envs.yaml b/tests/configs/minimal_with_envs.yaml
--- a/tests/configs/minimal_with_envs.yaml
+++ b/tests/configs/minimal_with_envs.yaml
@@ -1 +1,6 @@
-test: $ENVVAR
+
+connectors:
+ - name: $ENVVAR
+
+skills:
+ - name: hello
diff --git a/tests/configs/minimal_with_include.yaml b/tests/configs/minimal_with_include.yaml
--- a/tests/configs/minimal_with_include.yaml
+++ b/tests/configs/minimal_with_include.yaml
@@ -1 +1,2 @@
!include minimal.yaml
+
diff --git a/tests/configs/valid_case_sensitivity.yaml b/tests/configs/valid_case_sensitivity.yaml
new file mode 100644
--- /dev/null
+++ b/tests/configs/valid_case_sensitivity.yaml
@@ -0,0 +1,31 @@
+welcome-message: true
+
+connectors:
+
+ - name: Websocket
+ bot-name: "mybot"
+ max-connections: 10
+ connection-timeout: 10
+
+databases:
+
+ - name: Mongo
+ host: "my host"
+ port: "12345"
+ database: "mydatabase"
+
+parsers:
+
+ - name: Dialogflow
+ access-token: "exampleaccesstoken123"
+ min-score: 0.6
+
+skills:
+
+ - name: dance
+
+ - name: hello
+
+ - name: loudnoises
+
+ - name: seen
diff --git a/tests/configs/valid_without_db_and_parsers.yaml b/tests/configs/valid_without_db_and_parsers.yaml
new file mode 100644
--- /dev/null
+++ b/tests/configs/valid_without_db_and_parsers.yaml
@@ -0,0 +1,20 @@
+# CORRECT CONFIG: the databases and parsers are optional
+
+welcome-message: true
+
+connectors:
+
+ - name: websocket
+ bot-name: "mybot"
+ max-connections: 10
+ connection-timeout: 10
+
+skills:
+
+ - name: dance
+
+ - name: hello
+
+ - name: loudnoises
+
+ - name: seen
diff --git a/tests/configs/valid_without_wellcome_message.yaml b/tests/configs/valid_without_wellcome_message.yaml
new file mode 100644
--- /dev/null
+++ b/tests/configs/valid_without_wellcome_message.yaml
@@ -0,0 +1,32 @@
+# CORRECT CONFIG: the file is being checked despite the absence of a welcome message
+
+connectors:
+
+ - name: websocket
+ bot-name: "mybot"
+ max-connections: 10
+ connection-timeout: 10
+
+databases:
+
+ - name: mongo
+ host: "my host"
+ port: "12345"
+ database: "mydatabase"
+
+parsers:
+
+ - name: dialogflow
+ access-token: "exampleaccesstoken123"
+ min-score: 0.6
+
+
+skills:
+
+ - name: dance
+
+ - name: hello
+
+ - name: loudnoises
+
+ - name: seen
diff --git a/tests/test_loader.py b/tests/test_loader.py
--- a/tests/test_loader.py
+++ b/tests/test_loader.py
@@ -41,6 +41,51 @@ def test_load_config_file(self):
)
self.assertIsNotNone(config)
+ def test_load_config_valid(self):
+ opsdroid, loader = self.setup()
+ config = loader.load_config_file(
+ [os.path.abspath("tests/configs/full_valid.yaml")]
+ )
+ self.assertIsNotNone(config)
+
+ def test_load_config_valid_without_wellcome_message(self):
+ opsdroid, loader = self.setup()
+ config = loader.load_config_file(
+ [os.path.abspath("tests/configs/valid_without_wellcome_message.yaml")]
+ )
+ self.assertIsNotNone(config)
+
+ def test_load_config_valid_without_db_and_parsers(self):
+ opsdroid, loader = self.setup()
+ config = loader.load_config_file(
+ [os.path.abspath("tests/configs/valid_without_db_and_parsers.yaml")]
+ )
+ self.assertIsNotNone(config)
+
+ def test_load_config_broken_without_connectors(self):
+ opsdroid, loader = self.setup()
+ with self.assertRaises(SystemExit) as cm:
+ config = loader.load_config_file(
+ [os.path.abspath("tests/configs/broken_without_connectors.yaml")]
+ )
+ self.assertEqual(cm.exception.code, 1)
+
+ def test_load_config_valid_case_sensitivity(self):
+ opsdroid, loader = self.setup()
+ config = loader.load_config_file(
+ [os.path.abspath("tests/configs/valid_case_sensitivity.yaml")]
+ )
+ self.assertIsNotNone(config)
+
+ def test_load_config_broken(self):
+ opsdroid, loader = self.setup()
+
+ with self.assertRaises(SystemExit) as cm:
+ config = loader.load_config_file(
+ [os.path.abspath("tests/configs/full_broken.yaml")]
+ )
+ self.assertEqual(cm.exception.code, 1)
+
def test_load_config_file_2(self):
opsdroid, loader = self.setup()
config = loader.load_config_file(
@@ -67,6 +112,7 @@ def test_load_exploit(self):
self.assertRaises(YAMLError)
unittest.main(exit=False)
+ @unittest.skip("old config type fails validation #770")
def test_load_config_file_with_include(self):
opsdroid, loader = self.setup()
config = loader.load_config_file(
@@ -87,13 +133,14 @@ def test_yaml_load_exploit(self):
# If the command in exploit.yaml is echoed it will return 0
self.assertNotEqual(config, 0)
+ @unittest.skip("old config type fails validation #770")
def test_load_config_file_with_env_vars(self):
opsdroid, loader = self.setup()
- os.environ["ENVVAR"] = "test"
+ os.environ["ENVVAR"] = "shell"
config = loader.load_config_file(
[os.path.abspath("tests/configs/minimal_with_envs.yaml")]
)
- self.assertEqual(config["test"], os.environ["ENVVAR"])
+ self.assertEqual(config["connectors"][0]["name"], os.environ["ENVVAR"])
def test_create_default_config(self):
test_config_path = os.path.join(
| Add config validation
Currently we are not doing a very good job of validating config before loading opsdroid.
An example of this is that we have [very old and now invalid configs](https://github.com/opsdroid/opsdroid/blob/bc95a2bd4d7cf921974f4ee01ec1b51003249bc3/tests/configs/minimal.yaml) in our tests and they are still passing. In that config `skills` is a dictionary, which was changed to a list a long time ago.
We should check our configs are valid before starting to load.
| Hello, I'd love to help out on this project. Do you think this is a good place to start and if so can you say more about what need to be done for the config tests?
Hello @bicep welcome to the project. Can't say exactly if this is the right issue for you - I guess it depends on how well you know yaml and pyyaml 😄
Basically we are loading the `config.yaml` but there is little validation done on this file (for examples, adding three spaces instead of two will make the config break).
As for the tests, what needs to change is from a dictionary into a list and update them - also checking if things will break or not.
I hope this will helps a bit. If you think this is a bit out of scope of what you can do you can check the issues with [good first issue](https://github.com/opsdroid/opsdroid/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) or the [intermediate level](https://github.com/opsdroid/opsdroid/issues?q=is%3Aissue+is%3Aopen+label%3Aintermediate).
Let me know if you need any help with anything 😄 👍
Hi! I'd like to try fix this issue. Could you tell me a little bit more about this? When we need to check config.yaml ? Any code snippet or hint?
I've found some class named Loader, I think it should be there.
We could take a leaf out of Home Assistants book here and have connectors and skills define a schema for their config.
See https://developers.home-assistant.io/docs/en/development_validation.html and https://pypi.org/project/voluptuous/ is the lib they use.
Hello, I would like to handle this issue. Is it still actual?
Heya and welcome!
Yeah this issue is still actual and would be great if you could tackle it. We have just updated pyyaml to the latest version 5.1.1(2?) but home assistant is still using 3-4.
Please let me know if you need any help with this issue.
Thank you 😄👍 | 2019-07-07T10:53:06 |
opsdroid/opsdroid | 1,011 | opsdroid__opsdroid-1011 | [
"1010"
] | 0ed98b0aeea2e03366184f73f4583f2e000c9f66 | diff --git a/opsdroid/connector/telegram/__init__.py b/opsdroid/connector/telegram/__init__.py
--- a/opsdroid/connector/telegram/__init__.py
+++ b/opsdroid/connector/telegram/__init__.py
@@ -173,6 +173,15 @@ async def _parse_message(self, response):
)
await self.send(message)
self.latest_update = result["update_id"] + 1
+ elif (
+ "message" in result
+ and "sticker" in result["message"]
+ and "emoji" in result["message"]["sticker"]
+ ):
+ self.latest_update = result["update_id"] + 1
+ _LOGGER.debug(
+ "Emoji message parsing not supported " "- Ignoring message"
+ )
else:
_LOGGER.error("Unable to parse the message.")
| diff --git a/tests/test_connector_telegram.py b/tests/test_connector_telegram.py
--- a/tests/test_connector_telegram.py
+++ b/tests/test_connector_telegram.py
@@ -286,6 +286,52 @@ async def test_parse_message_unauthorized(self):
self.assertTrue(mocked_respond.called)
self.assertTrue(mocked_respond.called_with(message_text))
+ async def test_parse_message_emoji(self):
+ response = {
+ "result": [
+ {
+ "update_id": 427647860,
+ "message": {
+ "message_id": 12,
+ "from": {
+ "id": 649671308,
+ "is_bot": False,
+ "first_name": "A",
+ "last_name": "User",
+ "username": "user",
+ "language_code": "en-GB",
+ },
+ "chat": {
+ "id": 649671308,
+ "first_name": "A",
+ "last_name": "User",
+ "username": "user",
+ "type": "private",
+ },
+ "date": 1538756863,
+ "sticker": {
+ "width": 512,
+ "height": 512,
+ "emoji": "😔",
+ "set_name": "YourALF",
+ "thumb": {
+ "file_id": "AAQCABODB_MOAARYC8yRaPPoIIZBAAIC",
+ "file_size": 8582,
+ "width": 128,
+ "height": 128,
+ },
+ "file_id": "CAADAgAD3QMAAsSraAu37DAtdiNpAgI",
+ "file_size": 64720,
+ },
+ },
+ }
+ ]
+ }
+
+ with amock.patch("opsdroid.core.OpsDroid.parse"):
+ await self.connector._parse_message(response)
+ self.assertLogs("_LOGGER", "debug")
+
async def test_get_messages(self):
listen_response = amock.Mock()
listen_response.status = 200
| telegram connector does not handle emoji message
Hi,
When opsdroid receive an emoji message from telegram "_perhaps this issue impact other platforms_" it does not succeed to parse the incoming message (no text field found) and enter a loop process indicating **ERROR opsdroid.connector.telegram: Unable to parse the message**
```
DEBUG opsdroid.connector.telegram: {'update_id': 628993004, 'message': {'message_id': 3495, 'from': {'id': 452282388, 'is_bot': False, 'first_name': 'Chami', 'language_code': 'en'}, 'chat': {'id': 452282388, 'first_name': 'Chami', 'type': 'private'}, 'date': 1557067146, 'sticker': {'width': 512, 'height': 512, 'emoji': '🎩', 'set_name': 'MrZoid', 'thumb': {'file_id': 'AAQCABOs8zIOAARKlxOC0H7RiTc2AAIC', 'file_size': 6640, 'width': 128, 'height': 128}, 'file_id': 'CAADAgADBgEAAiUDUg-fFZcSxHZ6mAI', 'file_size': 45888}}}
ERROR opsdroid.connector.telegram: Unable to parse the message.
```
## Steps to Reproduce
1- configure configuration.yaml to use telegram connector
2- start opsdroid last version
3- send an emoji
4- check opsdroid logs/debug messages
## Expected Functionality
Opsdroid should handle emoji messages
## Experienced Functionality
Logs :
```
INFO opsdroid.logging: ========================================
INFO opsdroid.logging: Started opsdroid v0.15.4+33.g0c7e0c0
DEBUG asyncio: Using selector: KqueueSelector
DEBUG opsdroid.loader: Loaded loader
DEBUG opsdroid.loader: Loading modules from config...
DEBUG opsdroid.loader: Loaded skill: opsdroid-modules.skill.hello
DEBUG opsdroid.loader: Loading connector modules...
DEBUG opsdroid.loader: Loaded connector: opsdroid.connector.websocket
DEBUG opsdroid.loader: Loaded connector: opsdroid.connector.telegram
DEBUG opsdroid.connector.telegram: {'update_id': 993865146, 'message': {'message_id': 686, 'from': {'id': 452282388, 'is_bot': False, 'first_name': 'Chami', 'language_code': 'en'}, 'chat': {'id': 452282388, 'first_name': 'Chami', 'type': 'private'}, 'date': 1563032184, 'sticker': {'width': 512, 'height': 512, 'emoji': '😎', 'set_name': 'GreatMindsColor', 'thumb': {'file_id': 'AAQCABMv9jcPAARtFJS24s8gbBsoAAIC', 'file_size': 6098, 'width': 128, 'height': 128}, 'file_id': 'CAADAgAD4AgAAgi3GQKT5DnrvOwaLAI', 'file_size': 40318}}}
ERROR opsdroid.connector.telegram: Unable to parse the message.
DEBUG opsdroid.connector.telegram: {'update_id': 993865146, 'message': {'message_id': 686, 'from': {'id': 452282388, 'is_bot': False, 'first_name': 'Chami', 'language_code': 'en'}, 'chat': {'id': 452282388, 'first_name': 'Chami', 'type': 'private'}, 'date': 1563032184, 'sticker': {'width': 512, 'height': 512, 'emoji': '😎', 'set_name': 'GreatMindsColor', 'thumb': {'file_id': 'AAQCABMv9jcPAARtFJS24s8gbBsoAAIC', 'file_size': 6098, 'width': 128, 'height': 128}, 'file_id': 'CAADAgAD4AgAAgi3GQKT5DnrvOwaLAI', 'file_size': 40318}}}
ERROR opsdroid.connector.telegram: Unable to parse the message.
DEBUG opsdroid.connector.telegram: {'update_id': 993865146, 'message': {'message_id': 686, 'from': {'id': 452282388, 'is_bot': False, 'first_name': 'Chami', 'language_code': 'en'}, 'chat': {'id': 452282388, 'first_name': 'Chami', 'type': 'private'}, 'date': 1563032184, 'sticker': {'width': 512, 'height': 512, 'emoji': '😎', 'set_name': 'GreatMindsColor', 'thumb': {'file_id': 'AAQCABMv9jcPAARtFJS24s8gbBsoAAIC', 'file_size': 6098, 'width': 128, 'height': 128}, 'file_id': 'CAADAgAD4AgAAgi3GQKT5DnrvOwaLAI', 'file_size': 40318}}}
ERROR opsdroid.connector.telegram: Unable to parse the message.
DEBUG opsdroid.connector.telegram: {'update_id': 993865146, 'message': {'message_id': 686, 'from': {'id': 452282388, 'is_bot': False, 'first_name': 'Chami', 'language_code': 'en'}, 'chat': {'id': 452282388, 'first_name': 'Chami', 'type': 'private'}, 'date': 1563032184, 'sticker': {'width': 512, 'height': 512, 'emoji': '😎', 'set_name': 'GreatMindsColor', 'thumb': {'file_id': 'AAQCABMv9jcPAARtFJS24s8gbBsoAAIC', 'file_size': 6098, 'width': 128, 'height': 128}, 'file_id': 'CAADAgAD4AgAAgi3GQKT5DnrvOwaLAI', 'file_size': 40318}}}
ERROR opsdroid.connector.telegram: Unable to parse the message.
DEBUG opsdroid.connector.telegram: {'update_id': 993865146, 'message': {'message_id': 686, 'from': {'id': 452282388, 'is_bot': False, 'first_name': 'Chami', 'language_code': 'en'}, 'chat': {'id': 452282388, 'first_name': 'Chami', 'type': 'private'}, 'date': 1563032184, 'sticker': {'width': 512, 'height': 512, 'emoji': '😎', 'set_name': 'GreatMindsColor', 'thumb': {'file_id': 'AAQCABMv9jcPAARtFJS24s8gbBsoAAIC', 'file_size': 6098, 'width': 128, 'height': 128}, 'file_id': 'CAADAgAD4AgAAgi3GQKT5DnrvOwaLAI', 'file_size': 40318}}}
ERROR opsdroid.connector.telegram: Unable to parse the message.
DEBUG opsdroid.connector.telegram: {'update_id': 993865146, 'message': {'message_id': 686, 'from': {'id': 452282388, 'is_bot': False, 'first_name': 'Chami', 'language_code': 'en'}, 'chat': {'id': 452282388, 'first_name': 'Chami', 'type': 'private'}, 'date': 1563032184, 'sticker': {'width': 512, 'height': 512, 'emoji': '😎', 'set_name': 'GreatMindsColor', 'thumb': {'file_id': 'AAQCABMv9jcPAARtFJS24s8gbBsoAAIC', 'file_size': 6098, 'width': 128, 'height': 128}, 'file_id': 'CAADAgAD4AgAAgi3GQKT5DnrvOwaLAI', 'file_size': 40318}}}
ERROR opsdroid.connector.telegram: Unable to parse the message.
DEBUG opsdroid.connector.telegram: {'update_id': 993865146, 'message': {'message_id': 686, 'from': {'id': 452282388, 'is_bot': False, 'first_name': 'Chami', 'language_code': 'en'}, 'chat': {'id': 452282388, 'first_name': 'Chami', 'type': 'private'}, 'date': 1563032184, 'sticker': {'width': 512, 'height': 512, 'emoji': '😎', 'set_name': 'GreatMindsColor', 'thumb': {'file_id': 'AAQCABMv9jcPAARtFJS24s8gbBsoAAIC', 'file_size': 6098, 'width': 128, 'height': 128}, 'file_id': 'CAADAgAD4AgAAgi3GQKT5DnrvOwaLAI', 'file_size': 40318}}}
ERROR opsdroid.connector.telegram: Unable to parse the message.
DEBUG opsdroid.connector.telegram: {'update_id': 993865146, 'message': {'message_id': 686, 'from': {'id': 452282388, 'is_bot': False, 'first_name': 'Chami', 'language_code': 'en'}, 'chat': {'id': 452282388, 'first_name': 'Chami', 'type': 'private'}, 'date': 1563032184, 'sticker': {'width': 512, 'height': 512, 'emoji': '😎', 'set_name': 'GreatMindsColor', 'thumb': {'file_id': 'AAQCABMv9jcPAARtFJS24s8gbBsoAAIC', 'file_size': 6098, 'width': 128, 'height': 128}, 'file_id': 'CAADAgAD4AgAAgi3GQKT5DnrvOwaLAI', 'file_size': 40318}}}
ERROR opsdroid.connector.telegram: Unable to parse the message.
DEBUG opsdroid.connector.telegram: {'update_id': 993865146, 'message': {'message_id': 686, 'from': {'id': 452282388, 'is_bot': False, 'first_name': 'Chami', 'language_code': 'en'}, 'chat': {'id': 452282388, 'first_name': 'Chami', 'type': 'private'}, 'date': 1563032184, 'sticker': {'width': 512, 'height': 512, 'emoji': '😎', 'set_name': 'GreatMindsColor', 'thumb': {'file_id': 'AAQCABMv9jcPAARtFJS24s8gbBsoAAIC', 'file_size': 6098, 'width': 128, 'height': 128}, 'file_id': 'CAADAgAD4AgAAgi3GQKT5DnrvOwaLAI', 'file_size': 40318}}}
ERROR opsdroid.connector.telegram: Unable to parse the message.
DEBUG opsdroid.connector.telegram: {'update_id': 993865146, 'message': {'message_id': 686, 'from': {'id': 452282388, 'is_bot': False, 'first_name': 'Chami', 'language_code': 'en'}, 'chat': {'id': 452282388, 'first_name': 'Chami', 'type': 'private'}, 'date': 1563032184, 'sticker': {'width': 512, 'height': 512, 'emoji': '😎', 'set_name': 'GreatMindsColor', 'thumb': {'file_id': 'AAQCABMv9jcPAARtFJS24s8gbBsoAAIC', 'file_size': 6098, 'width': 128, 'height': 128}, 'file_id': 'CAADAgAD4AgAAgi3GQKT5DnrvOwaLAI', 'file_size': 40318}}}
ERROR opsdroid.connector.telegram: Unable to parse the message.
DEBUG opsdroid.connector.telegram: {'update_id': 993865146, 'message': {'message_id': 686, 'from': {'id': 452282388, 'is_bot': False, 'first_name': 'Chami', 'language_code': 'en'}, 'chat': {'id': 452282388, 'first_name': 'Chami', 'type': 'private'}, 'date': 1563032184, 'sticker': {'width': 512, 'height': 512, 'emoji': '😎', 'set_name': 'GreatMindsColor', 'thumb': {'file_id': 'AAQCABMv9jcPAARtFJS24s8gbBsoAAIC', 'file_size': 6098, 'width': 128, 'height': 128}, 'file_id': 'CAADAgAD4AgAAgi3GQKT5DnrvOwaLAI', 'file_size': 40318}}}
ERROR opsdroid.connector.telegram: Unable to parse the message.
DEBUG opsdroid.connector.telegram: {'update_id': 993865146, 'message': {'message_id': 686, 'from': {'id': 452282388, 'is_bot': False, 'first_name': 'Chami', 'language_code': 'en'}, 'chat': {'id': 452282388, 'first_name': 'Chami', 'type': 'private'}, 'date': 1563032184, 'sticker': {'width': 512, 'height': 512, 'emoji': '😎', 'set_name': 'GreatMindsColor', 'thumb': {'file_id': 'AAQCABMv9jcPAARtFJS24s8gbBsoAAIC', 'file_size': 6098, 'width': 128, 'height': 128}, 'file_id': 'CAADAgAD4AgAAgi3GQKT5DnrvOwaLAI', 'file_size': 40318}}}
ERROR opsdroid.connector.telegram: Unable to parse the message.
DEBUG opsdroid.connector.telegram: {'update_id': 993865146, 'message': {'message_id': 686, 'from': {'id': 452282388, 'is_bot': False, 'first_name': 'Chami', 'language_code': 'en'}, 'chat': {'id': 452282388, 'first_name': 'Chami', 'type': 'private'}, 'date': 1563032184, 'sticker': {'width': 512, 'height': 512, 'emoji': '😎', 'set_name': 'GreatMindsColor', 'thumb': {'file_id': 'AAQCABMv9jcPAARtFJS24s8gbBsoAAIC', 'file_size': 6098, 'width': 128, 'height': 128}, 'file_id': 'CAADAgAD4AgAAgi3GQKT5DnrvOwaLAI', 'file_size': 40318}}}
ERROR opsdroid.connector.telegram: Unable to parse the message.
DEBUG opsdroid.connector.telegram: {'update_id': 993865146, 'message': {'message_id': 686, 'from': {'id': 452282388, 'is_bot': False, 'first_name': 'Chami', 'language_code': 'en'}, 'chat': {'id': 452282388, 'first_name': 'Chami', 'type': 'private'}, 'date': 1563032184, 'sticker': {'width': 512, 'height': 512, 'emoji': '😎', 'set_name': 'GreatMindsColor', 'thumb': {'file_id': 'AAQCABMv9jcPAARtFJS24s8gbBsoAAIC', 'file_size': 6098, 'width': 128, 'height': 128}, 'file_id': 'CAADAgAD4AgAAgi3GQKT5DnrvOwaLAI', 'file_size': 40318}}}
ERROR opsdroid.connector.telegram: Unable to parse the message.
...
...
...
```
## Versions
- **Opsdroid version: opsdroid v0.15.4+33.g0c7e0c0**
- **Python version: 3.7.2**
## Configuration File
Any configuration file with telegram connector activated
| Thanks for raising this. That’s an expected reaction to an emoji since the connector uses the text found in ‘message’ or ‘chat’ response of the api call to parse the text.
Telegram sets an emoji with the param ‘emoji’ and we haven’t handled this cases so it won’t be able to parse that message since no ‘message’ or ‘chat’ was found in the response.
Do you think we should handle emojis? Not sure if it could be too beneficial imo
Hi @FabioRosado, By handling the emoji i mean avoiding the error loop caused by the emoji message (and by the not updated **last_update** variable)
I did a quick fix that update the next message and display a log when an emoji is detected
```
DEBUG opsdroid.connector.telegram: {'update_id': 993865152, 'message': {'message_id': 695, 'from': {'id': 452282388, 'is_bot': False, 'first_name': 'Chami', 'language_code': 'en'}, 'chat': {'id': 452282388, 'first_name': 'Chami', 'type': 'private'}, 'date': 1563034116, 'sticker': {'width': 512, 'height': 512, 'emoji': '😚', 'set_name': 'ThisCat', 'thumb': {'file_id': 'AAQCABN6xoUqAATJoPUbqEseUvAmAAIC', 'file_size': 8888, 'width': 128, 'height': 128}, 'file_id': 'CAADAgADowADztjoC0gThbizU6HxAg', 'file_size': 60402}}}
DEBUG opsdroid.connector.telegram: Ignoring emoji message
```
As you can see, the log message is now a DEBUG message instead of an ERROR one.
The log indicate clearly that opsdroid is just ignoring the emoji message (for a happy debugging :-) )
What do you think ? | 2019-07-13T17:00:11 |
opsdroid/opsdroid | 1,041 | opsdroid__opsdroid-1041 | [
"666"
] | 4e3b72ebeaf92ea668ab54540786b17af01877e7 | diff --git a/opsdroid/connector/webexteams/__init__.py b/opsdroid/connector/webexteams/__init__.py
new file mode 100644
--- /dev/null
+++ b/opsdroid/connector/webexteams/__init__.py
@@ -0,0 +1,108 @@
+"""A connector for Webex Teams."""
+import json
+import logging
+import uuid
+
+import aiohttp
+
+from webexteamssdk import WebexTeamsAPI
+
+from opsdroid.connector import Connector, register_event
+from opsdroid.events import Message
+
+
+_LOGGER = logging.getLogger(__name__)
+
+
+class ConnectorWebexTeams(Connector):
+ """A connector for Webex Teams."""
+
+ def __init__(self, config, opsdroid=None):
+ """Create a connector."""
+ _LOGGER.debug("Loaded webex teams connector")
+ super().__init__(config, opsdroid=opsdroid)
+ self.name = "webexteams"
+ self.config = config
+ self.opsdroid = opsdroid
+ self.default_room = None
+ self.bot_name = config.get("bot-name", "opsdroid")
+ self.bot_webex_id = None
+ self.secret = uuid.uuid4().hex
+ self.people = {}
+
+ async def connect(self):
+ """Connect to the chat service."""
+ try:
+ self.api = WebexTeamsAPI(access_token=self.config["access-token"])
+ except KeyError:
+ _LOGGER.error("Must set accesst-token for webex teams connector!")
+ return
+
+ await self.clean_up_webhooks()
+ await self.subscribe_to_rooms()
+ await self.set_own_id()
+
+ async def webexteams_message_handler(self, request):
+ """Handle webhooks from the Webex Teams api."""
+ _LOGGER.debug("Handling message from Webex Teams")
+ req_data = await request.json()
+
+ _LOGGER.debug(req_data)
+
+ msg = self.api.messages.get(req_data["data"]["id"])
+
+ if req_data["data"]["personId"] != self.bot_webex_id:
+ person = await self.get_person(req_data["data"]["personId"])
+
+ try:
+ message = Message(
+ msg.text,
+ person.displayName,
+ {"id": msg.roomId, "type": msg.roomType},
+ self,
+ )
+ await self.opsdroid.parse(message)
+ except KeyError as error:
+ _LOGGER.error(error)
+
+ return aiohttp.web.Response(text=json.dumps("Received"), status=201)
+
+ async def clean_up_webhooks(self):
+ """Remove all existing webhooks."""
+ for webhook in self.api.webhooks.list():
+ self.api.webhooks.delete(webhook.id)
+
+ async def subscribe_to_rooms(self):
+ """Create webhooks for all rooms."""
+ _LOGGER.debug("Creating Webex Teams webhook")
+ webhook_endpoint = "/connector/webexteams"
+ self.opsdroid.web_server.web_app.router.add_post(
+ webhook_endpoint, self.webexteams_message_handler
+ )
+
+ self.api.webhooks.create(
+ name="opsdroid",
+ targetUrl="{}{}".format(self.config.get("webhook-url"), webhook_endpoint),
+ resource="messages",
+ event="created",
+ secret=self.secret,
+ )
+
+ async def get_person(self, personId):
+ """Get a person's info from the api or cache."""
+ if personId not in self.people:
+ self.people[personId] = self.api.people.get(personId)
+ return self.people[personId]
+
+ async def set_own_id(self):
+ """Get the bot id and set it in the class."""
+ self.bot_webex_id = self.api.people.me().id
+
+ async def listen(self):
+ """Listen for and parse new messages."""
+ pass # Listening is handled by the aiohttp web server
+
+ @register_event(Message)
+ async def send_message(self, message):
+ """Respond with a message."""
+ self.api.messages.create(message.target["id"], text=message.text)
| diff --git a/tests/test_connector_webexteams.py b/tests/test_connector_webexteams.py
new file mode 100755
--- /dev/null
+++ b/tests/test_connector_webexteams.py
@@ -0,0 +1,163 @@
+"""Tests for the Connector Webex Teams class."""
+import asyncio
+
+import unittest
+import unittest.mock as mock
+import asynctest
+import asynctest.mock as amock
+
+from opsdroid.core import OpsDroid
+from opsdroid.connector.webexteams import ConnectorWebexTeams
+from opsdroid.events import Message, Reaction
+from opsdroid.__main__ import configure_lang
+
+
+class TestConnectorCiscoWebexTeams(unittest.TestCase):
+ """Test the opsdroid Webex Teams connector class."""
+
+ def setUp(self):
+ self.loop = asyncio.new_event_loop()
+ configure_lang({})
+
+ def test_init(self):
+ """Test that the connector is initialised properly."""
+ connector = ConnectorWebexTeams({})
+ self.assertEqual("webexteams", connector.name)
+ self.assertEqual("opsdroid", connector.bot_name)
+
+ def test_missing_api_key(self):
+ """Test that creating without an API without config raises an error."""
+ with self.assertRaises(TypeError):
+ ConnectorWebexTeams()
+
+
+class TestConnectorCiscoSparkAsync(asynctest.TestCase):
+ """Test the async methods of the opsdroid webex teams connector class."""
+
+ async def setUp(self):
+ configure_lang({})
+
+ async def test_connect(self):
+ connector = ConnectorWebexTeams({"access-token": "abc123"}, opsdroid=OpsDroid())
+
+ opsdroid = amock.CoroutineMock()
+ opsdroid.eventloop = self.loop
+ connector.clean_up_webhooks = amock.CoroutineMock()
+ connector.subscribe_to_rooms = amock.CoroutineMock()
+ connector.set_own_id = amock.CoroutineMock()
+
+ with amock.patch(
+ "websockets.connect", new=amock.CoroutineMock()
+ ) as mocked_websocket_connect:
+ await connector.connect()
+
+ self.assertTrue(connector.clean_up_webhooks.called)
+ self.assertTrue(connector.subscribe_to_rooms.called)
+ self.assertTrue(connector.set_own_id.called)
+
+ async def test_message_handler(self):
+ connector = ConnectorWebexTeams({"access-token": "abc123"})
+ connector.opsdroid = OpsDroid()
+ connector.bot_spark_id = "spark123"
+ connector.api = amock.CoroutineMock()
+ request = amock.Mock()
+ request.json = amock.CoroutineMock()
+ request.json.return_value = {
+ "data": {"id": "3vABZrQgDzfcz7LZi", "personId": "21ABZrQgDzfcz7Lsi"}
+ }
+ message = amock.Mock()
+ connector.api.messages.get = amock.Mock()
+ message.text = "Hello"
+ message.roomId = "90ABCrWgrzfcz7LZi"
+ message.roomType = "general"
+ connector.api.messages.get.return_value = message
+ connector.get_person = amock.CoroutineMock()
+ person = amock.CoroutineMock()
+ person.displayName = "Himanshu"
+ connector.get_person.return_value = person
+
+ response = await connector.webexteams_message_handler(request)
+ self.assertLogs("_LOGGER", "debug")
+ self.assertEqual(201, response.status)
+ self.assertEqual('"Received"', response.text)
+ self.assertTrue(connector.api.messages.get.called)
+ self.assertTrue(connector.get_person.called)
+
+ connector.opsdroid = amock.CoroutineMock()
+ connector.opsdroid.parse = amock.CoroutineMock()
+ connector.opsdroid.parse.side_effect = KeyError
+ await connector.webexteams_message_handler(request)
+ self.assertLogs("_LOGGER", "error")
+
+ async def test_connect_fail_keyerror(self):
+ connector = ConnectorWebexTeams({}, opsdroid=OpsDroid())
+ connector.clean_up_webhooks = amock.CoroutineMock()
+ connector.subscribe_to_rooms = amock.CoroutineMock()
+ connector.set_own_id = amock.CoroutineMock()
+ await connector.connect()
+ self.assertLogs("_LOGGER", "error")
+
+ async def test_listen(self):
+ """Test the listen method.
+
+ The Webex Teams connector listens using an API endoint and so the listen
+ method should just pass and do nothing. We just need to test that it
+ does not block.
+
+ """
+ connector = ConnectorWebexTeams({}, opsdroid=OpsDroid())
+ self.assertEqual(await connector.listen(), None)
+
+ async def test_respond(self):
+ connector = ConnectorWebexTeams({"access-token": "abc123"})
+ connector.api = amock.CoroutineMock()
+ connector.api.messages.create = amock.CoroutineMock()
+ message = Message(
+ text="Hello",
+ user="opsdroid",
+ target={"id": "3vABZrQgDzfcz7LZi"},
+ connector=None,
+ )
+ await connector.respond(message)
+ self.assertTrue(connector.api.messages.create.called)
+
+ async def test_get_person(self):
+ connector = ConnectorWebexTeams({"access-token": "abc123"})
+ connector.api = amock.CoroutineMock()
+ connector.api.messages.create = amock.CoroutineMock()
+ connector.api.people.get = amock.CoroutineMock()
+ connector.api.people.get.return_value = "Himanshu"
+ self.assertEqual(len(connector.people), 0)
+ await connector.get_person("3vABZrQgDzfcz7LZi")
+ self.assertEqual(len(connector.people), 1)
+
+ async def test_subscribe_to_rooms(self):
+ connector = ConnectorWebexTeams(
+ {"access-token": "abc123", "webhook-url": "http://127.0.0.1"}
+ )
+ connector.api = amock.CoroutineMock()
+ connector.opsdroid = amock.CoroutineMock()
+ connector.opsdroid.web_server.web_app.router.add_post = amock.CoroutineMock()
+ connector.api.webhooks.create = amock.CoroutineMock()
+ await connector.subscribe_to_rooms()
+ self.assertTrue(connector.api.webhooks.create.called)
+ self.assertTrue(connector.opsdroid.web_server.web_app.router.add_post.called)
+
+ async def test_clean_up_webhooks(self):
+ connector = ConnectorWebexTeams({"access-token": "abc123"})
+ connector.api = amock.CoroutineMock()
+ x = amock.CoroutineMock()
+ x.id = amock.CoroutineMock()
+ connector.api.webhooks.list = amock.Mock()
+ connector.api.webhooks.list.return_value = [x, x]
+ connector.api.webhooks.delete = amock.Mock()
+ await connector.clean_up_webhooks()
+ self.assertTrue(connector.api.webhooks.list.called)
+ self.assertTrue(connector.api.webhooks.delete.called)
+
+ async def test_set_own_id(self):
+ connector = ConnectorWebexTeams({"access-token": "abc123"})
+ connector.api = amock.CoroutineMock()
+ connector.api.people.me().id = "3vABZrQgDzfcz7LZi"
+ await connector.set_own_id()
+ self.assertTrue(connector.bot_webex_id, "3vABZrQgDzfcz7LZi")
| Move Cisco Spark connector into core
This issue covers adding the [Cisco Spark connector](https://github.com/opsdroid/connector-ciscospark) to core.
## Background
A while ago we began moving connectors from external plugins into the core of the project (see #185 for more context). We started with [slack](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/connector/slack/__init__.py) and [websockets](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/connector/websocket/__init__.py) but need to go through all the other existing plugins and move them into the core.
## Steps
- Make a new submodule directory in [`opsdroid.connector`](https://github.com/opsdroid/opsdroid/tree/master/opsdroid/connector) and copy the connector code over.
- Update the [`requirements.txt`](https://github.com/opsdroid/opsdroid/blob/master/requirements.txt) with any dependencies from the connector if necessary.
- Write tests for the connector. (See the [Slack connector tests](https://github.com/jacobtomlinson/opsdroid/blob/master/tests/test_connector_slack.py) for inspiration).
- Copy the relevant information from the connector `README.md` into a [new documentation page](https://github.com/opsdroid/opsdroid/tree/master/docs/connectors).
- Add the new page to the [mkdocs.yml](https://github.com/opsdroid/opsdroid/blob/master/mkdocs.yml).
- Add to the [list of connectors](https://github.com/opsdroid/opsdroid/blob/master/docs/configuration-reference.md#connector-modules).
- Add a deprecation notice to the old connector. (See [the slack connector](https://github.com/opsdroid/connector-slack))
| @jacobtomlinson I would like to solve this
Hello there it would be great if you could take on this task. Please let me know if you need any help | 2019-08-13T20:49:12 |
opsdroid/opsdroid | 1,056 | opsdroid__opsdroid-1056 | [
"566"
] | bea675c5a359a043f02d9dfce56060a1904a1988 | diff --git a/opsdroid/core.py b/opsdroid/core.py
--- a/opsdroid/core.py
+++ b/opsdroid/core.py
@@ -367,22 +367,7 @@ async def get_ranked_skills(self, skills, message):
_LOGGER.debug(_("Processing parsers..."))
parsers = self.config["parsers"] or []
- dialogflow = [
- p for p in parsers if p["name"] == "dialogflow" or p["name"] == "apiai"
- ]
-
- # Show deprecation message but parse message
- # Once it stops working remove this bit
- apiai = [p for p in parsers if p["name"] == "apiai"]
- if apiai:
- _LOGGER.warning(
- _(
- "Api.ai is now called Dialogflow. This "
- "parser will stop working in the future "
- "please swap: 'name: apiai' for "
- "'name: dialogflow' in configuration.yaml"
- )
- )
+ dialogflow = [p for p in parsers if p["name"] == "dialogflow"]
if len(dialogflow) == 1 and (
"enabled" not in dialogflow[0] or dialogflow[0]["enabled"] is not False
diff --git a/opsdroid/matchers.py b/opsdroid/matchers.py
--- a/opsdroid/matchers.py
+++ b/opsdroid/matchers.py
@@ -66,44 +66,6 @@ def matcher(func):
return matcher
-def match_apiai_action(action):
- """Return Dialogflow action match decorator."""
-
- def matcher(func):
- """Add decorated function to skills list for Dialogflow matching."""
- func = add_skill_attributes(func)
- func.matchers.append({"dialogflow_action": action})
- return func
-
- _LOGGER.warning(
- _(
- "Api.ai is now called Dialogflow, this matcher "
- "will stop working in the future. "
- "Use match_dialogflow_action instead."
- )
- )
- return matcher
-
-
-def match_apiai_intent(intent):
- """Return Dialogflow intent match decorator."""
-
- def matcher(func):
- """Add decorated function to skills list for Dialogflow matching."""
- func = add_skill_attributes(func)
- func.matchers.append({"dialogflow_intent": intent})
- return func
-
- _LOGGER.warning(
- _(
- "Api.ai is now called Dialogflow, this matcher "
- "will stop working in the future. "
- "Use match_dialogflow_intent instead."
- )
- )
- return matcher
-
-
def match_dialogflow_action(action):
"""Return Dialogflowi action match decorator."""
diff --git a/opsdroid/parsers/dialogflow.py b/opsdroid/parsers/dialogflow.py
--- a/opsdroid/parsers/dialogflow.py
+++ b/opsdroid/parsers/dialogflow.py
@@ -1,96 +1,131 @@
"""A helper function for parsing and executing Dialogflow skills."""
-
+import os
import logging
-import json
-
-import aiohttp
-from opsdroid.const import (
- DEFAULT_LANGUAGE,
- DIALOGFLOW_API_VERSION,
- DIALOGFLOW_API_ENDPOINT,
-)
+from opsdroid.const import DEFAULT_LANGUAGE
_LOGGER = logging.getLogger(__name__)
-async def call_dialogflow(message, config, lang=DEFAULT_LANGUAGE):
- """Call the Dialogflow api and return the response."""
- async with aiohttp.ClientSession() as session:
- payload = {
- "v": DIALOGFLOW_API_VERSION,
- "lang": lang,
- "sessionId": message.connector.name,
- "query": message.text,
- }
- headers = {
- "Authorization": "Bearer " + config["access-token"],
- "Content-Type": "application/json",
- }
- resp = await session.post(
- DIALOGFLOW_API_ENDPOINT, data=json.dumps(payload), headers=headers
- )
- result = await resp.json()
- _LOGGER.info(_("Dialogflow response - %s"), json.dumps(result))
+async def call_dialogflow(text, opsdroid, config):
+ """Call Dialogflow to get intent from text.
- return result
+ Dialogflow will return an object with a few restrictions, you can't
+ iterate it and the only way to access each element is by using dot
+ notation.
+ Args:
+ text (string): message.text this is the text obtained from the user.
+ opsdroid (OpsDroid): An instance of opsdroid.core.
+ config (dict): configuration settings from the file config.yaml.
-async def parse_dialogflow(opsdroid, skills, message, config):
- """Parse a message against all Dialogflow skills."""
- matched_skills = []
- if "access-token" in config:
- try:
- result = await call_dialogflow(
- message, config, opsdroid.config.get("lang", DEFAULT_LANGUAGE)
+ Return:
+ A 'google.cloud.dialogflow_v2.types.DetectIntentResponse' object.
+
+ Raises:
+ Warning: if Google credentials are not found in environmental
+ variables or 'project-id' is not in config.
+
+ """
+ try:
+ import dialogflow
+
+ if os.environ.get("GOOGLE_APPLICATION_CREDENTIALS") and config.get(
+ "project-id"
+ ):
+ session_client = dialogflow.SessionsClient()
+ project_id = config.get("project-id")
+ language = config.get("lang") or opsdroid.config.get(
+ "lang", DEFAULT_LANGUAGE
)
- except aiohttp.ClientOSError:
- _LOGGER.error(_("No response from Dialogflow, " "check your network."))
- return matched_skills
- if result["status"]["code"] >= 300:
- _LOGGER.error(
- _("Dialogflow error - %s - %s"),
- str(result["status"]["code"]),
- result["status"]["errorType"],
+ session = session_client.session_path(project_id, "opsdroid")
+ text_input = dialogflow.types.TextInput(text=text, language_code=language)
+ query_input = dialogflow.types.QueryInput(text=text_input)
+
+ response = session_client.detect_intent(
+ session=session, query_input=query_input
)
- return matched_skills
- if "min-score" in config and result["result"]["score"] < config["min-score"]:
- _LOGGER.debug(_("Dialogflow score lower than min-score"))
+ return response
+ else:
+ raise Warning(
+ _(
+ "Authentication file not found or 'project-id' not in configuration, dialogflow parser will not be available"
+ )
+ )
+ except ImportError:
+ _LOGGER.error(
+ _(
+ "Unable to find dialogflow dependency. Please install dialogflow with the command pip install dialogflow if you want to use this parser."
+ )
+ )
+ opsdroid.config["parsers"][0]["enabled"] = False
+
+
+async def parse_dialogflow(opsdroid, skills, message, config):
+ """Parse a message against all Dialogflow skills.
+
+ This function does a few things, first it will check if the
+ intent confidence is higher than the minimum score set on config,
+ then it will try to match an action or an intent to a matcher and
+ add the proper skills to the skills list.
+
+ At the moment a broad exception is being used due to the fact that
+ dialogflow library doesn't have the best documentation yet and it's
+ not possible to know what sort of exceptions the library will return.
+
+ Args:
+ opsdroid (OpsDroid): An instance of opsdroid.core.
+ skills (list): A list containing all skills available.
+ message(object): An instance of events.message.
+ config (dict): configuration settings from the
+ file config.yaml.
+
+ Return:
+ Either empty list or a list containing all matched skills.
+
+ """
+ try:
+ result = await call_dialogflow(message.text, opsdroid, config)
+ matched_skills = []
+ if (
+ "min-score" in config
+ and result.query_result.intent_detection_confidence < config["min-score"]
+ ):
+ _LOGGER.debug(_("Dialogflow confidence lower than min-score"))
return matched_skills
if result:
-
for skill in skills:
for matcher in skill.matchers:
-
if "dialogflow_action" in matcher or "dialogflow_intent" in matcher:
if (
- "action" in result["result"]
- and matcher["dialogflow_action"]
- in result["result"]["action"]
+ matcher.get("dialogflow_action")
+ == result.query_result.action
) or (
- "intentName" in result["result"]
- and matcher["dialogflow_intent"]
- in result["result"]["intentName"]
+ matcher.get("dialogflow_intent")
+ == result.query_result.intent.display_name
):
- message.dialogflow = result
- message.apiai = message.dialogflow
- for key, entity in (
- result["result"].get("parameters", {}).items()
- ):
- await message.update_entity(key, entity, None)
+
+ message.dialogflow = result.query_result
+
_LOGGER.debug(
_("Matched against skill %s"), skill.config["name"]
)
matched_skills.append(
{
- "score": result["result"]["score"],
+ "score": result.query_result.intent_detection_confidence,
"skill": skill,
"config": skill.config,
"message": message,
}
)
- return matched_skills
+ return matched_skills
+
+ except Exception as error:
+ # TODO: Refactor broad exception
+ _LOGGER.error(
+ _("There was an error while parsing to dialogflow - {}".format(error))
+ )
| diff --git a/requirements_test.txt b/requirements_test.txt
--- a/requirements_test.txt
+++ b/requirements_test.txt
@@ -1,6 +1,7 @@
black==19.3b0
flake8==3.7.8
coveralls==1.8.2
+dialogflow==0.6.0
astroid==2.3.1
pytest==5.2.0
pytest-cov==2.7.1
diff --git a/tests/test_core.py b/tests/test_core.py
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -1,3 +1,4 @@
+import os
import asyncio
import unittest
import unittest.mock as mock
@@ -306,19 +307,20 @@ async def test_parse_regex_insensitive(self):
self.assertTrue(mock_connector.send.called)
async def test_parse_dialogflow(self):
+ os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path/test.json"
with OpsDroid() as opsdroid:
- opsdroid.config["parsers"] = [{"name": "dialogflow"}]
- dialogflow_action = ""
+ opsdroid.config["parsers"] = [{"name": "dialogflow", "project-id": "test"}]
+ dialogflow_action = "smalltalk.greetings.whatsup"
skill = amock.CoroutineMock()
mock_connector = Connector({}, opsdroid=opsdroid)
match_dialogflow_action(dialogflow_action)(skill)
message = Message("Hello world", "user", "default", mock_connector)
- with amock.patch("opsdroid.parsers.dialogflow.parse_dialogflow"):
+ with amock.patch(
+ "opsdroid.parsers.dialogflow.parse_dialogflow"
+ ), amock.patch("opsdroid.parsers.dialogflow.call_dialogflow"):
tasks = await opsdroid.parse(message)
self.assertEqual(len(tasks), 1)
- # Once apiai parser stops working, remove this test!
- opsdroid.config["parsers"] = [{"name": "apiai"}]
tasks = await opsdroid.parse(message)
self.assertLogs("_LOGGER", "warning")
diff --git a/tests/test_matchers.py b/tests/test_matchers.py
--- a/tests/test_matchers.py
+++ b/tests/test_matchers.py
@@ -39,28 +39,6 @@ async def test_match_regex(self):
)
self.assertTrue(asyncio.iscoroutinefunction(opsdroid.skills[0]))
- async def test_match_apiai(self):
- with OpsDroid() as opsdroid:
- action = "myaction"
- decorator = matchers.match_apiai_action(action)
- opsdroid.skills.append(decorator(await self.getMockSkill()))
- self.assertEqual(len(opsdroid.skills), 1)
- self.assertEqual(
- opsdroid.skills[0].matchers[0]["dialogflow_action"], action
- )
- self.assertTrue(asyncio.iscoroutinefunction(opsdroid.skills[0]))
- intent = "myIntent"
- decorator = matchers.match_apiai_intent(intent)
- opsdroid.skills.append(decorator(await self.getMockSkill()))
- self.assertEqual(len(opsdroid.skills), 2)
- self.assertEqual(
- opsdroid.skills[1].matchers[0]["dialogflow_intent"], intent
- )
- self.assertTrue(asyncio.iscoroutinefunction(opsdroid.skills[1]))
- decorator = matchers.match_apiai_intent(intent)
- opsdroid.skills.append(decorator(await self.getMockSkill()))
- self.assertLogs("_LOGGER", "warning")
-
async def test_match_dialogflow(self):
with OpsDroid() as opsdroid:
action = "myaction"
diff --git a/tests/test_parser_dialogflow.py b/tests/test_parser_dialogflow.py
--- a/tests/test_parser_dialogflow.py
+++ b/tests/test_parser_dialogflow.py
@@ -1,8 +1,9 @@
+import os
import asyncio
import asynctest
import asynctest.mock as amock
-from aiohttp import ClientOSError
+from types import SimpleNamespace
from opsdroid.cli.start import configure_lang
from opsdroid.core import OpsDroid
@@ -12,6 +13,16 @@
from opsdroid.connector import Connector
+class NestedNamespace(SimpleNamespace):
+ def __init__(self, dictionary, **kwargs):
+ super().__init__(**kwargs)
+ for key, value in dictionary.items():
+ if isinstance(value, dict):
+ self.__setattr__(key, NestedNamespace(value))
+ else:
+ self.__setattr__(key, value)
+
+
class TestParserDialogflow(asynctest.TestCase):
"""Test the opsdroid Dialogflow parser."""
@@ -33,137 +44,123 @@ async def mockedskill(opsdroid, config, message):
return mockedskill
async def test_call_dialogflow(self):
+ os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path/test.json"
+ config = {"name": "dialogflow", "project-id": "test"}
opsdroid = amock.CoroutineMock()
mock_connector = Connector({}, opsdroid=opsdroid)
message = Message("Hello world", "user", "default", mock_connector)
- config = {"name": "dialogflow", "access-token": "test"}
+
result = amock.Mock()
result.json = amock.CoroutineMock()
result.json.return_value = {
- "result": {"action": "myaction", "score": 0.7},
- "status": {"code": 200, "errorType": "success"},
+ "query_result": {
+ "query_text": "what is up",
+ "action": "smalltalk.greetings.whatsup",
+ "parameters": {},
+ "all_required_params_present": True,
+ "fulfillment_text": "Not much. What's new with you?",
+ "fulfillment_messages": {
+ "text": {"text": "Not much. What's new with you?"}
+ },
+ "intent": {},
+ "intent_detection_confidence": 1.0,
+ "language_code": "en",
+ }
}
- with amock.patch("aiohttp.ClientSession.post") as patched_request:
- patched_request.return_value = asyncio.Future()
+ with amock.patch("dialogflow.SessionsClient") as patched_request, amock.patch(
+ "dialogflow.types.TextInput"
+ ) as mocked_input, amock.patch(
+ "dialogflow.types.QueryInput"
+ ) as mocked_response:
+ patched_request.session_path.return_value = (
+ "projects/test/agent/sessions/opsdroid"
+ )
+ mocked_input.return_value = 'text: "hi"'
+
+ mocked_response.return_value = asyncio.Future()
patched_request.return_value.set_result(result)
- await dialogflow.call_dialogflow(message, config)
+ await dialogflow.call_dialogflow(message, opsdroid, config)
self.assertTrue(patched_request.called)
- async def test_parse_dialogflow(self):
- with OpsDroid() as opsdroid:
- opsdroid.config["parsers"] = [
- {"name": "dialogflow", "access-token": "test"}
- ]
- mock_skill = await self.getMockSkill()
- mock_skill.config = {"name": "greetings"}
- opsdroid.skills.append(match_dialogflow_action("myaction")(mock_skill))
+ async def test_call_dialogflow_failure(self):
+ config = {"name": "dialogflow"}
+ opsdroid = amock.CoroutineMock()
+ mock_connector = Connector({}, opsdroid=opsdroid)
+ message = Message("Hello world", "user", "default", mock_connector)
- mock_connector = amock.CoroutineMock()
+ with self.assertRaises(Warning):
+ await dialogflow.call_dialogflow(message, opsdroid, config)
+ self.assertLogs("_LOGGER", "error")
+
+ async def test_call_dialogflow_import_failure(self):
+ with OpsDroid() as opsdroid, amock.patch(
+ "dialogflow.SessionsClient"
+ ) as patched_request, amock.patch.object(dialogflow, "parse_dialogflow"):
+ config = {"name": "dialogflow", "project-id": "test"}
+ mock_connector = Connector({}, opsdroid=opsdroid)
message = Message("Hello world", "user", "default", mock_connector)
+ patched_request.side_effect = ImportError()
+ opsdroid.config["parsers"] = [config]
- with amock.patch.object(
- dialogflow, "call_dialogflow"
- ) as mocked_call_dialogflow:
- mocked_call_dialogflow.return_value = {
- "result": {"action": "myaction", "score": 0.7},
- "status": {"code": 200, "errorType": "success"},
+ await dialogflow.call_dialogflow(message, opsdroid, config)
+
+ self.assertLogs("_LOGGER", "error")
+ self.assertIn("enabled", opsdroid.config["parsers"][0])
+ self.assertEqual(opsdroid.config["parsers"][0]["enabled"], False)
+
+ async def test_parse_dialogflow(self):
+ os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path/test.json"
+ dialogflow_response = NestedNamespace(
+ {
+ "query_result": {
+ "query_text": "what is up",
+ "action": "smalltalk.greetings.whatsup",
+ "parameters": {},
+ "all_required_params_present": True,
+ "fulfillment_text": "Not much. What's new with you?",
+ "fulfillment_messages": {
+ "text": {"text": "Not much. What's new with you?"}
+ },
+ "intent": {},
+ "intent_detection_confidence": 1.0,
+ "language_code": "en",
}
- skills = await dialogflow.parse_dialogflow(
- opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
- )
- self.assertEqual(mock_skill, skills[0]["skill"])
+ }
+ )
- async def test_parse_dialogflow_entities(self):
with OpsDroid() as opsdroid:
- opsdroid.config["parsers"] = [
- {"name": "dialogflow", "access-token": "test"}
- ]
+ opsdroid.config["parsers"] = [{"name": "dialogflow", "project-id": "test"}]
mock_skill = await self.getMockSkill()
mock_skill.config = {"name": "greetings"}
opsdroid.skills.append(
- match_dialogflow_action("restaurant.search")(mock_skill)
+ match_dialogflow_action("smalltalk.greetings.whatsup")(mock_skill)
)
mock_connector = amock.CoroutineMock()
- message = Message(
- "I want some good French food", "user", "default", mock_connector
- )
-
- with amock.patch.object(
- dialogflow, "call_dialogflow"
- ) as mocked_call_dialogflow:
- mocked_call_dialogflow.return_value = {
- "id": "aab19d9e-3a85-4d44-95ac-2eda162c9663",
- "timestamp": "2019-05-24T16:44:06.972Z",
- "lang": "en",
- "result": {
- "source": "agent",
- "resolvedQuery": "I want some good French food",
- "action": "restaurant.search",
- "actionIncomplete": False,
- "parameters": {"Cuisine": "French"},
- "contexts": [],
- "metadata": {
- "intentId": "4e6ce594-6be3-461d-8d5b-418343cfbda6",
- "webhookUsed": "false",
- "webhookForSlotFillingUsed": "false",
- "isFallbackIntent": "false",
- "intentName": "restaurant.search",
- },
- "fulfillment": {
- "speech": "",
- "messages": [{"type": 0, "speech": ""}],
- },
- "score": 0.8299999833106995,
- },
- "status": {"code": 200, "errorType": "success"},
- "sessionId": "30ad1a2f-e760-d62f-5a21-e8aafc1eaa35",
- }
- [skill] = await dialogflow.parse_dialogflow(
- opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
- )
- self.assertEqual(len(skill["message"].entities.keys()), 1)
- self.assertTrue("Cuisine" in skill["message"].entities.keys())
- self.assertEqual(
- skill["message"].entities["Cuisine"]["value"], "French"
- )
-
- async def test_parse_dialogflow_raises(self):
- with OpsDroid() as opsdroid:
- opsdroid.config["parsers"] = [
- {"name": "dialogflow", "access-token": "test"}
- ]
- mock_skill = await self.getRaisingMockSkill()
- mock_skill.config = {"name": "greetings"}
- opsdroid.skills.append(match_dialogflow_action("myaction")(mock_skill))
-
- mock_connector = amock.MagicMock()
- mock_connector.send = amock.CoroutineMock()
message = Message("Hello world", "user", "default", mock_connector)
with amock.patch.object(
dialogflow, "call_dialogflow"
) as mocked_call_dialogflow:
- mocked_call_dialogflow.return_value = {
- "result": {"action": "myaction", "score": 0.7},
- "status": {"code": 200, "errorType": "success"},
- }
+ mocked_call_dialogflow.return_value = dialogflow_response
+
skills = await dialogflow.parse_dialogflow(
opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
)
self.assertEqual(mock_skill, skills[0]["skill"])
-
- await opsdroid.run_skill(skills[0]["skill"], skills[0]["config"], message)
- self.assertLogs("_LOGGER", "exception")
+ self.assertLogs("_LOGGERS", "debug")
async def test_parse_dialogflow_failure(self):
+ os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path/test.json"
+
with OpsDroid() as opsdroid:
- opsdroid.config["parsers"] = [
- {"name": "dialogflow", "access-token": "test"}
- ]
- mock_skill = amock.CoroutineMock()
- match_dialogflow_action("myaction")(mock_skill)
+ opsdroid.config["parsers"] = [{"name": "dialogflow", "project-id": "test"}]
+ mock_skill = await self.getMockSkill()
+ mock_skill.config = {"name": "greetings"}
+ opsdroid.skills.append(
+ match_dialogflow_action("smalltalk.greetings.whatsup")(mock_skill)
+ )
mock_connector = amock.CoroutineMock()
message = Message("Hello world", "user", "default", mock_connector)
@@ -171,19 +168,36 @@ async def test_parse_dialogflow_failure(self):
with amock.patch.object(
dialogflow, "call_dialogflow"
) as mocked_call_dialogflow:
- mocked_call_dialogflow.return_value = {
- "result": {"action": "myaction", "score": 0.7},
- "status": {"code": 404, "errorType": "not found"},
- }
+ mocked_call_dialogflow.side_effect = Exception()
+
skills = await dialogflow.parse_dialogflow(
opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
)
- self.assertFalse(skills)
+ self.assertEqual(skills, None)
+ self.assertLogs("_LOGGERS", "debug")
async def test_parse_dialogflow_low_score(self):
+ os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path/test.json"
+ dialogflow_response = NestedNamespace(
+ {
+ "query_result": {
+ "query_text": "what is up",
+ "action": "smalltalk.greetings.whatsup",
+ "parameters": {},
+ "all_required_params_present": True,
+ "fulfillment_text": "Not much. What's new with you?",
+ "fulfillment_messages": {
+ "text": {"text": "Not much. What's new with you?"}
+ },
+ "intent": {},
+ "intent_detection_confidence": 0.3,
+ "language_code": "en",
+ }
+ }
+ )
with OpsDroid() as opsdroid:
opsdroid.config["parsers"] = [
- {"name": "dialogflow", "access-token": "test", "min-score": 0.8}
+ {"name": "dialogflow", "project-id": "test", "min-score": 0.8}
]
mock_skill = amock.CoroutineMock()
match_dialogflow_action("myaction")(mock_skill)
@@ -194,32 +208,10 @@ async def test_parse_dialogflow_low_score(self):
with amock.patch.object(
dialogflow, "call_dialogflow"
) as mocked_call_dialogflow:
- mocked_call_dialogflow.return_value = {
- "result": {"action": "myaction", "score": 0.7},
- "status": {"code": 200, "errorType": "success"},
- }
- await dialogflow.parse_dialogflow(
- opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
- )
-
- self.assertFalse(mock_skill.called)
-
- async def test_parse_dialogflow_raise_ClientOSError(self):
- with OpsDroid() as opsdroid:
- opsdroid.config["parsers"] = [
- {"name": "dialogflow", "access-token": "test", "min-score": 0.8}
- ]
- mock_skill = amock.CoroutineMock()
- match_dialogflow_action("myaction")(mock_skill)
-
- mock_connector = amock.CoroutineMock()
- message = Message("Hello world", "user", "default", mock_connector)
-
- with amock.patch.object(dialogflow, "call_dialogflow") as mocked_call:
- mocked_call.side_effect = ClientOSError()
+ mocked_call_dialogflow.return_value = dialogflow_response
await dialogflow.parse_dialogflow(
opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
)
self.assertFalse(mock_skill.called)
- self.assertTrue(mocked_call.called)
+ self.assertLogs("_LOGGERS", "debug")
| Upgrade Dialogflow to V2 API
There is now a V2 API for Dialogflow.
We should look at the parser and skill and upgrade the API if applicable.
https://dialogflow.com/docs/reference/v2-agent-setup
| I had a look at what changed on the V2 of the API and it seems a lot did change. The major things that will need to be addressed are:
- Use OAuth instead of token to make api calls
- endpoint `/query` stops works and should know be `detectIntent` [documentation reference](https://cloud.google.com/dialogflow-enterprise/docs/reference/rest/v2beta1/projects.agent.sessions/detectIntent)
- webhooks are available now
The [migration reference](https://dialogflow.com/docs/reference/v1-v2-migration-guide-api) might be useful. We can use V1 of the API until 23rd of October 2019, so we should work on this in order to keep dialogflow working with opsdroid.
Just had a reminder email that this needs to be done by October 23rd.
I'll try to address this issue on my days off 👍 | 2019-09-01T16:31:52 |
opsdroid/opsdroid | 1,081 | opsdroid__opsdroid-1081 | [
"1000"
] | 96477f218d4b900746bc868956caa53d1b862c76 | diff --git a/opsdroid/connector/slack/__init__.py b/opsdroid/connector/slack/__init__.py
--- a/opsdroid/connector/slack/__init__.py
+++ b/opsdroid/connector/slack/__init__.py
@@ -1,13 +1,8 @@
"""A connector for Slack."""
import logging
-import asyncio
-import json
import re
-import aiohttp
-import websockets
-import slacker
-from aioslacker import Slacker
+import slack
from emoji import demojize
from opsdroid.connector import Connector, register_event
@@ -30,37 +25,48 @@ def __init__(self, config, opsdroid=None):
self.icon_emoji = config.get("icon-emoji", ":robot_face:")
self.token = config["api-token"]
self.timeout = config.get("connect-timeout", 10)
- self.slacker = Slacker(token=self.token, timeout=self.timeout)
+ self.slack = slack.WebClient(token=self.token, run_async=True)
+ self.slack_rtm = slack.RTMClient(token=self.token, run_async=True)
self.websocket = None
self.bot_name = config.get("bot-name", "opsdroid")
+ self.auth_info = None
+ self.user_info = None
+ self.bot_id = None
self.known_users = {}
self.keepalive = None
self.reconnecting = False
self.listening = True
self._message_id = 0
+ # Register callbacks
+ slack.RTMClient.on(event="message", callback=self.process_message)
+
async def connect(self):
"""Connect to the chat service."""
_LOGGER.info("Connecting to Slack")
try:
- connection = await self.slacker.rtm.start()
- self.websocket = await websockets.connect(connection.body["url"])
+ # The slack library recommends you call `self.slack_rtm.start()`` here but it
+ # seems to mess with the event loop's signal handlers which breaks opsdroid.
+ # Therefore we need to directly call the private `_connect_and_read` method
+ # instead. This method also blocks so we need to dispatch it to the loop as a task.
+ self.opsdroid.eventloop.create_task(self.slack_rtm._connect_and_read())
+
+ self.auth_info = (await self.slack.api_call("auth.test")).data
+ self.user_info = (
+ await self.slack.api_call(
+ "users.info",
+ http_verb="GET",
+ params={"user": self.auth_info["user_id"]},
+ )
+ ).data
+ self.bot_id = self.user_info["user"]["profile"]["bot_id"]
_LOGGER.debug("Connected as %s", self.bot_name)
_LOGGER.debug("Using icon %s", self.icon_emoji)
_LOGGER.debug("Default room is %s", self.default_target)
_LOGGER.info("Connected successfully")
-
- if self.keepalive is None or self.keepalive.done():
- self.keepalive = self.opsdroid.eventloop.create_task(
- self.keepalive_websocket()
- )
- except aiohttp.ClientOSError as error:
- _LOGGER.error(error)
- _LOGGER.error("Failed to connect to Slack, retrying in 10")
- await self.reconnect(10)
- except slacker.Error as error:
+ except slack.errors.SlackApiError as error:
_LOGGER.error(
"Unable to connect to Slack due to %s - "
"The Slack Connector will not be available.",
@@ -70,83 +76,67 @@ async def connect(self):
await self.disconnect()
raise
- async def reconnect(self, delay=None):
- """Reconnect to the websocket."""
- try:
- self.reconnecting = True
- if delay is not None:
- await asyncio.sleep(delay)
- await self.connect()
- finally:
- self.reconnecting = False
-
async def disconnect(self):
"""Disconnect from Slack."""
- await self.slacker.close()
+ await self.slack_rtm.stop()
+ self.listening = False
async def listen(self):
"""Listen for and parse new messages."""
- while self.listening:
- try:
- await self.receive_from_websocket()
- except AttributeError:
- break
-
- async def receive_from_websocket(self):
- """Get the next message from the websocket."""
- try:
- content = await self.websocket.recv()
- await self.process_message(json.loads(content))
- except websockets.exceptions.ConnectionClosed:
- _LOGGER.info("Slack websocket closed, reconnecting...")
- await self.reconnect(5)
- async def process_message(self, message):
+ async def process_message(self, **payload):
"""Process a raw message and pass it to the parser."""
- if "type" in message and message["type"] == "message" and "user" in message:
-
- # Ignore bot messages
- if "subtype" in message and message["subtype"] == "bot_message":
- return
-
- # Lookup username
- _LOGGER.debug("Looking up sender username")
- try:
- user_info = await self.lookup_username(message["user"])
- except ValueError:
- return
-
- # Replace usernames in the message
- _LOGGER.debug("Replacing userids in message with usernames")
- message["text"] = await self.replace_usernames(message["text"])
-
- await self.opsdroid.parse(
- Message(
- message["text"],
- user_info["name"],
- message["channel"],
- self,
- raw_event=message,
- )
+ message = payload["data"]
+
+ # Ignore own messages
+ if (
+ "subtype" in message
+ and message["subtype"] == "bot_message"
+ and message["bot_id"] == self.bot_id
+ ):
+ return
+
+ # Lookup username
+ _LOGGER.debug("Looking up sender username")
+ try:
+ user_info = await self.lookup_username(message["user"])
+ except ValueError:
+ return
+
+ # Replace usernames in the message
+ _LOGGER.debug("Replacing userids in message with usernames")
+ message["text"] = await self.replace_usernames(message["text"])
+
+ await self.opsdroid.parse(
+ Message(
+ message["text"],
+ user_info["name"],
+ message["channel"],
+ self,
+ raw_event=message,
)
+ )
@register_event(Message)
async def send_message(self, message):
"""Respond with a message."""
_LOGGER.debug("Responding with: '%s' in room %s", message.text, message.target)
- await self.slacker.chat.post_message(
- message.target,
- message.text,
- as_user=False,
- username=self.bot_name,
- icon_emoji=self.icon_emoji,
+ await self.slack.api_call(
+ "chat.postMessage",
+ data={
+ "channel": message.target,
+ "text": message.text,
+ "as_user": False,
+ "username": self.bot_name,
+ "icon_emoji": self.icon_emoji,
+ },
)
@register_event(Blocks)
async def send_blocks(self, blocks):
"""Respond with structured blocks."""
_LOGGER.debug("Responding with interactive blocks in room %s", blocks.target)
- await self.slacker.chat.post(
+ await self.slack.api_call(
"chat.postMessage",
data={
"channel": blocks.target,
@@ -162,7 +152,7 @@ async def send_reaction(self, reaction):
emoji = demojize(reaction.emoji).replace(":", "")
_LOGGER.debug("Reacting with: %s", emoji)
try:
- await self.slacker.reactions.post(
+ await self.slack.api_call(
"reactions.add",
data={
"name": emoji,
@@ -170,42 +160,19 @@ async def send_reaction(self, reaction):
"timestamp": reaction.linked_event.raw_event["ts"],
},
)
- except slacker.Error as error:
- if str(error) == "invalid_name":
+ except slack.errors.SlackApiError as error:
+ if "invalid_name" in str(error):
_LOGGER.warning("Slack does not support the emoji %s", emoji)
else:
raise
- async def keepalive_websocket(self):
- """Keep pinging the websocket to keep it alive."""
- while self.listening:
- await self.ping_websocket()
-
- async def ping_websocket(self):
- """Ping the websocket."""
- await asyncio.sleep(60)
- self._message_id += 1
- try:
- await self.websocket.send(
- json.dumps({"id": self._message_id, "type": "ping"})
- )
- except (
- websockets.exceptions.InvalidState,
- websockets.exceptions.ConnectionClosed,
- aiohttp.ClientOSError,
- TimeoutError,
- ):
- _LOGGER.info("Slack websocket closed, reconnecting...")
- if not self.reconnecting:
- await self.reconnect()
-
async def lookup_username(self, userid):
"""Lookup a username and cache it."""
if userid in self.known_users:
user_info = self.known_users[userid]
else:
- response = await self.slacker.users.info(userid)
- user_info = response.body["user"]
+ response = await self.slack.users_info(user=userid)
+ user_info = response.data["user"]
if isinstance(user_info, dict):
self.known_users[userid] = user_info
else:
| diff --git a/tests/test_connector_slack.py b/tests/test_connector_slack.py
--- a/tests/test_connector_slack.py
+++ b/tests/test_connector_slack.py
@@ -5,7 +5,7 @@
import unittest.mock as mock
import asynctest
import asynctest.mock as amock
-import slacker
+import slack
from opsdroid.core import OpsDroid
from opsdroid.connector.slack import ConnectorSlack
@@ -66,84 +66,39 @@ async def test_connect(self):
connector = ConnectorSlack({"api-token": "abc123"}, opsdroid=OpsDroid())
opsdroid = amock.CoroutineMock()
opsdroid.eventloop = self.loop
- connector.slacker.rtm.start = amock.CoroutineMock()
- connector.keepalive_websocket = amock.CoroutineMock()
- with amock.patch(
- "websockets.connect", new=amock.CoroutineMock()
- ) as mocked_websocket_connect:
- await connector.connect()
- self.assertTrue(connector.slacker.rtm.start.called)
- self.assertTrue(mocked_websocket_connect.called)
- self.assertTrue(connector.keepalive_websocket.called)
+ connector.slack_rtm._connect_and_read = amock.CoroutineMock()
+ connector.slack.api_call = amock.CoroutineMock()
+ await connector.connect()
+ self.assertTrue(connector.slack_rtm._connect_and_read.called)
+ self.assertTrue(connector.slack.api_call.called)
async def test_connect_auth_fail(self):
connector = ConnectorSlack({"api-token": "abc123"}, opsdroid=OpsDroid())
opsdroid = amock.CoroutineMock()
opsdroid.eventloop = self.loop
- connector.slacker.rtm.start = amock.CoroutineMock()
- connector.slacker.rtm.start.side_effect = slacker.Error()
+ connector.slack_rtm._connect_and_read = amock.Mock()
+ connector.slack_rtm._connect_and_read.side_effect = slack.errors.SlackApiError(
+ message="", response=""
+ )
await connector.connect()
self.assertLogs("_LOGGER", "error")
- async def test_reconnect_on_error(self):
- import aiohttp
-
- connector = ConnectorSlack({"api-token": "abc123"}, opsdroid=OpsDroid())
- connector.slacker.rtm.start = amock.CoroutineMock()
- connector.slacker.rtm.start.side_effect = aiohttp.ClientOSError()
- connector.reconnect = amock.CoroutineMock()
-
- await connector.connect()
- self.assertTrue(connector.reconnect.called)
-
async def test_abort_on_connection_error(self):
connector = ConnectorSlack({"api-token": "abc123"})
- connector.slacker.rtm.start = amock.CoroutineMock()
- connector.slacker.rtm.start.side_effect = Exception()
- connector.slacker.close = amock.CoroutineMock()
+ connector.slack_rtm._connect_and_read = amock.CoroutineMock()
+ connector.slack_rtm._connect_and_read.side_effect = Exception()
+ connector.slack_rtm.stop = amock.CoroutineMock()
with self.assertRaises(Exception):
await connector.connect()
- self.assertTrue(connector.slacker.close.called)
+ self.assertTrue(connector.slack_rtm.stop.called)
async def test_listen_loop(self):
"""Test that listening consumes from the socket."""
connector = ConnectorSlack({"api-token": "abc123"}, opsdroid=OpsDroid())
- connector.receive_from_websocket = amock.CoroutineMock()
- connector.receive_from_websocket.side_effect = Exception()
- with self.assertRaises(Exception):
- await connector.listen()
- self.assertTrue(connector.receive_from_websocket.called)
-
- async def test_listen_break_loop(self):
- """Test that listening consumes from the socket."""
- connector = ConnectorSlack({"api-token": "abc123"}, opsdroid=OpsDroid())
- connector.receive_from_websocket = amock.CoroutineMock()
- connector.receive_from_websocket.side_effect = AttributeError
+ connector.listening = False
await connector.listen()
- self.assertTrue(connector.receive_from_websocket.called)
-
- async def test_receive_from_websocket(self):
- """Test receive_from_websocket receives and reconnects."""
- import websockets
-
- connector = ConnectorSlack({"api-token": "abc123"}, opsdroid=OpsDroid())
-
- connector.websocket = amock.CoroutineMock()
- connector.websocket.recv = amock.CoroutineMock()
- connector.websocket.recv.return_value = "[]"
- connector.process_message = amock.CoroutineMock()
- await connector.receive_from_websocket()
- self.assertTrue(connector.websocket.recv.called)
- self.assertTrue(connector.process_message.called)
-
- connector.websocket.recv.side_effect = websockets.exceptions.ConnectionClosed(
- 500, "Mock Error"
- )
- connector.reconnect = amock.CoroutineMock()
- await connector.receive_from_websocket()
- self.assertTrue(connector.reconnect.called)
async def test_process_message(self):
"""Test processing a slack message."""
@@ -161,81 +116,57 @@ async def test_process_message(self):
"ts": "1355517523.000005",
"edited": {"user": "U2147483697", "ts": "1355517536.000001"},
}
- await connector.process_message(message)
+ await connector.process_message(data=message)
self.assertTrue(connector.opsdroid.parse.called)
connector.opsdroid.parse.reset_mock()
+ message["bot_id"] = "abc"
message["subtype"] = "bot_message"
- await connector.process_message(message)
+ connector.bot_id = message["bot_id"]
+ await connector.process_message(data=message)
self.assertFalse(connector.opsdroid.parse.called)
+ del message["bot_id"]
del message["subtype"]
+ connector.bot_id = None
connector.opsdroid.parse.reset_mock()
connector.lookup_username.side_effect = ValueError
- await connector.process_message(message)
+ await connector.process_message(data=message)
self.assertFalse(connector.opsdroid.parse.called)
- async def test_keepalive_websocket_loop(self):
- """Test that listening consumes from the socket."""
- connector = ConnectorSlack({"api-token": "abc123"}, opsdroid=OpsDroid())
- connector.ping_websocket = amock.CoroutineMock()
- connector.ping_websocket.side_effect = Exception()
- with self.assertRaises(Exception):
- await connector.keepalive_websocket()
- self.assertTrue(connector.ping_websocket.called)
-
- async def test_ping_websocket(self):
- """Test pinging the websocket."""
- import websockets
-
- connector = ConnectorSlack({"api-token": "abc123"}, opsdroid=OpsDroid())
- with amock.patch("asyncio.sleep", new=amock.CoroutineMock()) as mocked_sleep:
- connector.websocket = amock.CoroutineMock()
- connector.websocket.send = amock.CoroutineMock()
- await connector.ping_websocket()
- self.assertTrue(mocked_sleep.called)
- self.assertTrue(connector.websocket.send.called)
-
- connector.reconnect = amock.CoroutineMock()
- connector.websocket.send.side_effect = websockets.exceptions.ConnectionClosed(
- 500, "Mock Error"
- )
- await connector.ping_websocket()
- self.assertTrue(connector.reconnect.called)
-
async def test_lookup_username(self):
"""Test that looking up a username works and that it caches."""
connector = ConnectorSlack({"api-token": "abc123"}, opsdroid=OpsDroid())
- connector.slacker.users.info = amock.CoroutineMock()
+ connector.slack.users_info = amock.CoroutineMock()
mock_user = mock.Mock()
- mock_user.body = {"user": {"name": "testuser"}}
- connector.slacker.users.info.return_value = mock_user
+ mock_user.data = {"user": {"name": "testuser"}}
+ connector.slack.users_info.return_value = mock_user
self.assertEqual(len(connector.known_users), 0)
await connector.lookup_username("testuser")
self.assertTrue(len(connector.known_users), 1)
- self.assertTrue(connector.slacker.users.info.called)
+ self.assertTrue(connector.slack.users_info.called)
- connector.slacker.users.info.reset_mock()
+ connector.slack.users_info.reset_mock()
await connector.lookup_username("testuser")
self.assertEqual(len(connector.known_users), 1)
- self.assertFalse(connector.slacker.users.info.called)
+ self.assertFalse(connector.slack.users_info.called)
with self.assertRaises(ValueError):
- mock_user.body = {"user": None}
- connector.slacker.users.info.return_value = mock_user
+ mock_user.data = {"user": None}
+ connector.slack.users_info.return_value = mock_user
await connector.lookup_username("invaliduser")
async def test_respond(self):
connector = ConnectorSlack({"api-token": "abc123"}, opsdroid=OpsDroid())
- connector.slacker.chat.post_message = amock.CoroutineMock()
+ connector.slack.api_call = amock.CoroutineMock()
await connector.send(Message("test", "user", "room", connector))
- self.assertTrue(connector.slacker.chat.post_message.called)
+ self.assertTrue(connector.slack.api_call.called)
async def test_send_blocks(self):
connector = ConnectorSlack({"api-token": "abc123"}, opsdroid=OpsDroid())
- connector.slacker.chat.post = amock.CoroutineMock()
+ connector.slack.api_call = amock.CoroutineMock()
await connector.send(
Blocks(
[{"type": "section", "text": {"type": "mrkdwn", "text": "*Test*"}}],
@@ -244,26 +175,25 @@ async def test_send_blocks(self):
connector,
)
)
- self.assertTrue(connector.slacker.chat.post.called)
+ self.assertTrue(connector.slack.api_call.called)
async def test_react(self):
connector = ConnectorSlack({"api-token": "abc123"})
- connector.slacker.reactions.post = amock.CoroutineMock()
+ connector.slack.api_call = amock.CoroutineMock()
prev_message = Message("test", "user", "room", connector, raw_event={"ts": 0})
with OpsDroid() as opsdroid:
await prev_message.respond(Reaction("😀"))
- self.assertTrue(connector.slacker.reactions.post)
+ self.assertTrue(connector.slack.api_call)
self.assertEqual(
- connector.slacker.reactions.post.call_args[1]["data"]["name"],
- "grinning_face",
+ connector.slack.api_call.call_args[1]["data"]["name"], "grinning_face"
)
async def test_react_invalid_name(self):
- import slacker
+ import slack
connector = ConnectorSlack({"api-token": "abc123"})
- connector.slacker.reactions.post = amock.CoroutineMock(
- side_effect=slacker.Error("invalid_name")
+ connector.slack.api_call = amock.CoroutineMock(
+ side_effect=slack.errors.SlackApiError("invalid_name", "invalid_name")
)
prev_message = Message("test", "user", "room", connector, raw_event={"ts": 0})
with OpsDroid() as opsdroid:
@@ -271,26 +201,18 @@ async def test_react_invalid_name(self):
self.assertLogs("_LOGGER", "warning")
async def test_react_unknown_error(self):
- import slacker
+ import slack
connector = ConnectorSlack({"api-token": "abc123"})
- connector.slacker.reactions.post = amock.CoroutineMock(
- side_effect=slacker.Error("unknown")
+ connector.slack.api_call = amock.CoroutineMock(
+ side_effect=slack.errors.SlackApiError("unknown", "unknown")
)
- with self.assertRaises(slacker.Error), OpsDroid() as opsdroid:
+ with self.assertRaises(slack.errors.SlackApiError), OpsDroid() as opsdroid:
prev_message = Message(
"test", "user", "room", connector, raw_event={"ts": 0}
)
await prev_message.respond(Reaction("😀"))
- async def test_reconnect(self):
- connector = ConnectorSlack({"api-token": "abc123"}, opsdroid=OpsDroid())
- connector.connect = amock.CoroutineMock()
- with amock.patch("asyncio.sleep") as mocked_sleep:
- await connector.reconnect(10)
- self.assertTrue(connector.connect.called)
- self.assertTrue(mocked_sleep.called)
-
async def test_replace_usernames(self):
connector = ConnectorSlack({"api-token": "abc123"}, opsdroid=OpsDroid())
connector.lookup_username = amock.CoroutineMock()
| Slack integration uses old API/Token method
# Description
Opsdroid's Slack integration wants to operate off of a Webhook or API Token, which seems to be a deprecating (not yet deprecated) method of integrating with Slack. See attached screenshot of the warning message they display when trying to do a 'Webhook' or generic 'Bot' integration in an Enterprise Slack instance.
## Steps to Reproduce
Try to set up a 'Webhook' or 'API/Bot' integration in the usual manner:
Menu -> Customize Slack -> Configure Apps -> Custom Integrations
Observe Slack's notice that "Custom integrations will be deprecated and possibly removed in the future. Learn more about replacing them with apps that have more features and use the latest APIs"
## Expected Functionality
Ideally, Opsdroid would be able to integrate with Slack using their shiny Apps/not-Webhook API, and I don't have to go through a Security Team review because of the deprecation warning :-)
## Experienced Functionality
Explain what happened instead(Please include the debug log).
## Versions
- **Opsdroid version:** latest
- **Python version:** 3.2
- **OS/Docker version:** latest
## Configuration File
n/a
## Additional Details
[Custom Integration warning](https://i.imgur.com/fWWFXHw.png)
| This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
This may be resolved with #1036 | 2019-09-26T13:59:50 |
opsdroid/opsdroid | 1,099 | opsdroid__opsdroid-1099 | [
"1085"
] | 6e386760476f9f4889ebaff8d883587564e33a61 | diff --git a/opsdroid/constraints.py b/opsdroid/constraints.py
--- a/opsdroid/constraints.py
+++ b/opsdroid/constraints.py
@@ -5,6 +5,7 @@
"""
import logging
+from functools import wraps
from opsdroid.helper import add_skill_attributes
@@ -12,7 +13,17 @@
_LOGGER = logging.getLogger(__name__)
-def constrain_rooms(rooms):
+def invert_wrapper(func):
+ """Inverts the result of a function."""
+
+ @wraps(func)
+ def inverted_func(*args, **kwargs):
+ return not func(*args, **kwargs)
+
+ return inverted_func
+
+
+def constrain_rooms(rooms, invert=False):
"""Return room constraint decorator."""
def constraint_decorator(func):
@@ -23,13 +34,15 @@ def constraint_callback(message, rooms=rooms):
return message.target in rooms
func = add_skill_attributes(func)
+ if invert:
+ constraint_callback = invert_wrapper(constraint_callback)
func.constraints.append(constraint_callback)
return func
return constraint_decorator
-def constrain_users(users):
+def constrain_users(users, invert=False):
"""Return user constraint decorator."""
def constraint_decorator(func):
@@ -40,13 +53,15 @@ def constraint_callback(message, users=users):
return message.user in users
func = add_skill_attributes(func)
+ if invert:
+ constraint_callback = invert_wrapper(constraint_callback)
func.constraints.append(constraint_callback)
return func
return constraint_decorator
-def constrain_connectors(connectors):
+def constrain_connectors(connectors, invert=False):
"""Return connector constraint decorator."""
def constraint_decorator(func):
@@ -57,6 +72,8 @@ def constraint_callback(message, connectors=connectors):
return message.connector and (message.connector.name in connectors)
func = add_skill_attributes(func)
+ if invert:
+ constraint_callback = invert_wrapper(constraint_callback)
func.constraints.append(constraint_callback)
return func
| diff --git a/tests/test_constraints.py b/tests/test_constraints.py
--- a/tests/test_constraints.py
+++ b/tests/test_constraints.py
@@ -43,6 +43,17 @@ async def test_constrain_rooms_skips(self):
tasks = await opsdroid.parse(Message("Hello", "user", "#general", None))
self.assertEqual(len(tasks), 2) # match_always and the skill
+ async def test_constrain_rooms_inverted(self):
+ with OpsDroid() as opsdroid:
+ opsdroid.eventloop = mock.CoroutineMock()
+ skill = await self.getMockSkill()
+ skill = match_regex(r".*")(skill)
+ skill = constraints.constrain_rooms(["#general"], invert=True)(skill)
+ opsdroid.skills.append(skill)
+
+ tasks = await opsdroid.parse(Message("Hello", "user", "#general", None))
+ self.assertEqual(len(tasks), 1) # match_always only
+
async def test_constrain_users_constrains(self):
with OpsDroid() as opsdroid:
opsdroid.eventloop = mock.CoroutineMock()
@@ -67,6 +78,17 @@ async def test_constrain_users_skips(self):
tasks = await opsdroid.parse(Message("Hello", "user", "#general", None))
self.assertEqual(len(tasks), 2) # match_always and the skill
+ async def test_constrain_users_inverted(self):
+ with OpsDroid() as opsdroid:
+ opsdroid.eventloop = mock.CoroutineMock()
+ skill = await self.getMockSkill()
+ skill = match_regex(r".*")(skill)
+ skill = constraints.constrain_users(["user"], invert=True)(skill)
+ opsdroid.skills.append(skill)
+
+ tasks = await opsdroid.parse(Message("Hello", "user", "#general", None))
+ self.assertEqual(len(tasks), 1) # match_always only
+
async def test_constrain_connectors_constrains(self):
with OpsDroid() as opsdroid:
opsdroid.eventloop = mock.CoroutineMock()
@@ -95,6 +117,21 @@ async def test_constrain_connectors_skips(self):
)
self.assertEqual(len(tasks), 2) # match_always and the skill
+ async def test_constrain_connectors_inverted(self):
+ with OpsDroid() as opsdroid:
+ opsdroid.eventloop = mock.CoroutineMock()
+ skill = await self.getMockSkill()
+ skill = match_regex(r".*")(skill)
+ skill = constraints.constrain_connectors(["slack"], invert=True)(skill)
+ opsdroid.skills.append(skill)
+ connector = mock.Mock()
+ connector.configure_mock(name="slack")
+
+ tasks = await opsdroid.parse(
+ Message("Hello", "user", "#general", connector)
+ )
+ self.assertEqual(len(tasks), 1) # match_always only
+
async def test_constraint_can_be_called_after_skip(self):
with OpsDroid() as opsdroid:
opsdroid.eventloop = mock.CoroutineMock()
| Invert constraints
I can imagine situations where it would be useful to be able to invert constraints so that they do the opposite of what they are designed to do.
```python
from opsdroid.skill import Skill
from opsdroid.matchers import match_regex
from opsdroid.constraints import constrain_users
class MySkill(Skill):
@match_regex(r'hi')
@constrain_users(['alice', 'bob'], invert=True)
async def hello(self, message):
"""Says 'Hey' to anyone EXCEPT 'alice' and 'bob'."""
await message.respond('Hey')
```
| Hey @jacobtomlinson
Would love to work on this one during `hacktoberfest` if you don't mind.
Please go ahead! | 2019-09-30T20:07:59 |
opsdroid/opsdroid | 1,108 | opsdroid__opsdroid-1108 | [
"1093"
] | 26699c5e7cc014a0d3ab74baf66fbadce939ab73 | diff --git a/opsdroid/core.py b/opsdroid/core.py
--- a/opsdroid/core.py
+++ b/opsdroid/core.py
@@ -254,27 +254,12 @@ def setup_skills(self, skills):
continue
if hasattr(func, "skill"):
- _LOGGER.warning(
- _(
- "Function based skills are deprecated "
- "and will be removed in a future "
- "release. Please use class-based skills "
- "instead."
- )
- )
func.config = skill["config"]
self.skills.append(func)
with contextlib.suppress(AttributeError):
for skill in skills:
skill["module"].setup(self, self.config)
- _LOGGER.warning(
- _(
- "<skill module>.setup() is deprecated and "
- "will be removed in a future release. "
- "Please use class-based skills instead."
- )
- )
async def train_parsers(self, skills):
"""Train the parsers."""
| Remove function skill deprecation warning
A while back we added class based skills and added a deprecation warning to function based skills.
In hindsight we probably don't want to deprecate function based skills as they can still be useful and easier for a beginner to get on with.
So let's remove [this deprecation warning](https://github.com/opsdroid/opsdroid/blob/96477f218d4b900746bc868956caa53d1b862c76/opsdroid/core.py#L259).
| I can certainly do that to get used to the code, as I'm a beginner to the project (as well as to count towards my PR's for Hacktoberfest).
If possible, will contribute with another PR as well, for some other issue.
Hi Jacob,
I did the changes and trying to push but getting 403 access denied message, do i have to add myself in contributor list or something?
Thanks,
Vijay | 2019-10-01T13:50:13 |
|
opsdroid/opsdroid | 1,114 | opsdroid__opsdroid-1114 | [
"1113"
] | 9355390aab8ac6ace13e82c5b08b4b982a5ff78c | diff --git a/opsdroid/loader.py b/opsdroid/loader.py
--- a/opsdroid/loader.py
+++ b/opsdroid/loader.py
@@ -43,6 +43,11 @@
class Loader:
"""Class to load in config and modules."""
+ try:
+ yaml_loader = yaml.CSafeLoader
+ except AttributeError:
+ yaml_loader = yaml.SafeLoader
+
def __init__(self, opsdroid):
"""Create object with opsdroid instance."""
self.opsdroid = opsdroid
@@ -338,7 +343,7 @@ def load_config_file(cls, config_paths):
config_path = cls.create_default_config(DEFAULT_CONFIG_PATH)
env_var_pattern = re.compile(r"^\$([A-Z_]*)$")
- yaml.SafeLoader.add_implicit_resolver("!envvar", env_var_pattern, first="$")
+ cls.yaml_loader.add_implicit_resolver("!envvar", env_var_pattern, first="$")
def envvar_constructor(loader, node):
"""Yaml parser for env vars."""
@@ -352,11 +357,10 @@ def include_constructor(loader, node):
included_yaml = os.path.join(main_yaml_path, loader.construct_scalar(node))
with open(included_yaml, "r") as included:
- return yaml.safe_load(included)
-
- yaml.SafeLoader.add_constructor("!envvar", envvar_constructor)
- yaml.SafeLoader.add_constructor("!include", include_constructor)
+ return yaml.load(included, Loader=cls.yaml_loader)
+ cls.yaml_loader.add_constructor("!envvar", envvar_constructor)
+ cls.yaml_loader.add_constructor("!include", include_constructor)
try:
with open(config_path, "r") as stream:
_LOGGER.info(_("Loaded config from %s."), config_path)
@@ -364,7 +368,7 @@ def include_constructor(loader, node):
schema = yamale.make_schema(schema_path)
data = yamale.make_data(config_path)
yamale.validate(schema, data)
- return yaml.safe_load(stream)
+ return yaml.load(stream, Loader=cls.yaml_loader)
except ValueError as error:
_LOGGER.critical(error)
| diff --git a/tests/test_loader.py b/tests/test_loader.py
--- a/tests/test_loader.py
+++ b/tests/test_loader.py
@@ -111,7 +111,6 @@ def test_load_exploit(self):
self.assertRaises(YAMLError)
unittest.main(exit=False)
- @unittest.skip("old config type fails validation #770")
def test_load_config_file_with_include(self):
opsdroid, loader = self.setup()
config = loader.load_config_file(
| !include constructor is broken on python 3.6
<!-- Before you post an issue or if you are unsure about something join our gitter channel https://gitter.im/opsdroid/ and ask away! We are more than happy to help you. -->
# Description
After adding pyyaml validation, the `!include` constructor stopped working. I am still unsure if the issue is due to yamale and how it handles nested yaml files.
We need to fix the include constructor so we can keep the functionality of including a yaml file inside another.
## Steps to Reproduce
Add [skill-chat](https://github.com/FabioRosado/skill-chat) to opsdroid
set up skill-chat with a costumised yaml - follow the readme
start opsdroid
## Expected Functionality
Opsdroid should be able to include the custom file inside the configuration
## Experienced Functionality
```
python -m opsdroid start
could not determine a constructor for the tag '!include'
in "/Users/fabiorosado/Library/Application Support/opsdroid/configuration.yaml", line 130, column 16
```
## Versions
- **Opsdroid version:**
- **Python version:**
- **OS/Docker version:**
## Configuration File
Please include your version of the configuration file bellow.
```yaml
Skills:
- name: chat
path: /Users/fabiorosado/Documents/GitHub/skill-chat
customise: !include customise.yaml
```
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| 2019-10-01T19:14:45 |
|
opsdroid/opsdroid | 1,125 | opsdroid__opsdroid-1125 | [
"1019"
] | 2b04dab3e4d1e64d8a033e90c1a538e920583a2d | diff --git a/scripts/update_example_config/update_example_config.py b/scripts/update_example_config/update_example_config.py
--- a/scripts/update_example_config/update_example_config.py
+++ b/scripts/update_example_config/update_example_config.py
@@ -1,4 +1,4 @@
-from github import Github
+from github import Github, Repository
from argparse import ArgumentParser
import jinja2
import base64
@@ -31,6 +31,21 @@ def render(tpl_path, context):
)
+def get_core_modules():
+ """Get core module names of databases and connectors."""
+ core_modules = [
+ "database-" + name
+ for name in os.listdir("./opsdroid/database")
+ if os.path.isdir(os.path.join("./opsdroid/database", name))
+ ]
+ core_modules += [
+ "connector-" + name
+ for name in os.listdir("./opsdroid/connector")
+ if os.path.isdir(os.path.join("./opsdroid/connector", name))
+ ]
+ return core_modules
+
+
def get_repos():
"""Get repository details for: skills, connectors, database."""
return [
@@ -42,14 +57,25 @@ def get_repos():
]
-def get_readme(repo):
+def get_readme(module):
"""Get readme.md details from repository."""
- readme_base64 = repo.get_readme().content
- return base64.b64decode(readme_base64).decode("utf-8")
+ isRepo = isinstance(module, Repository.Repository)
+ if isRepo:
+ readme_base64 = module.get_readme().content
+ return base64.b64decode(readme_base64).decode("utf-8")
+ else:
+ if module[:9] == "connector":
+ mdfile = module[10:] + ".md"
+ subfolder = "connectors/"
+ else:
+ mdfile = module[9:] + ".md"
+ subfolder = "databases/"
+ core_readme = open("./docs/" + subfolder + mdfile, "rb").read().decode("utf-8")
+ return core_readme
def get_config_details(readme):
- """Gets all the configuration details located in the readme.md file,
+ """Gets all the configuration details located in the readme.md/<modulename>.md file of modules,
under the title "Configuration".
Note: Regex divided by multiline in order to pass lint.
@@ -62,20 +88,33 @@ def get_config_details(readme):
return config
-def get_config_params(repo, readme):
+def get_config_params(module, readme):
"""Returns parameters to be used in the update."""
- if repo.name[:5] == "skill":
- raw_name = repo.name[6:]
- repo_type = "skill"
- elif repo.name[:9] == "connector":
- raw_name = repo.name[10:]
- repo_type = "connector"
+ isRepo = isinstance(module, Repository.Repository)
+
+ if isRepo:
+ if module.name[:5] == "skill":
+ raw_name = module.name[6:]
+ repo_type = "skill"
+ elif module.name[:9] == "connector":
+ raw_name = module.name[10:]
+ repo_type = "connector"
+ else:
+ raw_name = module.name[9:]
+ repo_type = "database"
else:
- raw_name = repo.name[9:]
- repo_type = "database"
+ if module[:5] == "skill":
+ raw_name = module[6:]
+ repo_type = "skill"
+ elif module[:9] == "connector":
+ raw_name = module[10:]
+ repo_type = "connector"
+ else:
+ raw_name = module[9:]
+ repo_type = "database"
name = raw_name.replace("-", " ").capitalize()
- url = repo.html_url
+ url = module.html_url if isRepo else "core"
config = get_config_details(readme)
if config:
@@ -123,9 +162,9 @@ def get_parsers_details():
def validate_yaml_format(mapping, error_strict):
"""Scans the configuration format and validates yaml formatting."""
try:
- yaml.load(mapping["config"])
+ yaml.load(mapping["config"], Loader=yaml.FullLoader)
except (KeyError, TypeError):
- yaml.load(mapping)
+ yaml.load(mapping, Loader=yaml.FullLoader)
except yaml.scanner.ScannerError as e:
if error_strict:
raise e
@@ -137,7 +176,9 @@ def validate_yaml_format(mapping, error_strict):
def triage_modules(g, active_modules, error_strict=False):
"""Allocate modules to their type and active/inactive status."""
+ core_modules = get_core_modules()
repos = get_repos()
+ repos += core_modules
skills = {"commented": [], "uncommented": []}
connectors = {"commented": [], "uncommented": []}
@@ -156,19 +197,27 @@ def triage_modules(g, active_modules, error_strict=False):
params = get_config_params(repo, readme)
validate_yaml_format(params, error_strict)
- if params["repo_type"] == "skill":
- if params["raw_name"] in active_modules:
- skills["uncommented"].append(params)
- skills["commented"].append(params)
-
- elif params["repo_type"] == "connector":
- if params["raw_name"] in active_modules:
- connectors["uncommented"].append(params)
- connectors["commented"].append(params)
+ if (isinstance(repo, Repository.Repository)) and (
+ params["repo_type"] + "-" + params["raw_name"] in core_modules
+ ):
+ pass
else:
- if params["raw_name"] == active_modules:
- databases["uncommented"].append(params)
- databases["commented"].append(params)
+ if params["repo_type"] == "skill":
+ if params["raw_name"] in active_modules:
+ skills["uncommented"].append(params)
+ else:
+ skills["commented"].append(params)
+
+ elif params["repo_type"] == "connector":
+ if params["raw_name"] in active_modules:
+ connectors["uncommented"].append(params)
+ else:
+ connectors["commented"].append(params)
+ else:
+ if params["raw_name"] == active_modules:
+ databases["uncommented"].append(params)
+ else:
+ databases["commented"].append(params)
return modules
@@ -218,7 +267,7 @@ def update_config(g, active_modules, config_path, error_strict=False):
if args.active_modules:
active_modules.append((args.active_skills.split(",")))
else:
- active_modules = ["dance", "hello", "seen", "loudnoises", "websocket", "shell"]
+ active_modules = ["dance", "hello", "seen", "loudnoises", "websocket"]
if not args.output:
base_path = "/".join(os.path.realpath(__file__).split("/")[:-3])
config_path = base_path
| Update example config script
Our `configuration.yaml` file has suffered a few alterations and the script that should update the `example_configuration.yaml` file is really out of date.
There are also a few bugs where the skill is added both to commented ones and active ones.
We should update this script in order to get out configuration files up to date. We should also update the `example_configuration.yaml` file.
| Hi
Can I work on this issue?
Hello! That would be awesome!
Please let me know if you need any help whilst working on this issue 😄👍
Hi
I went through the `example_config.yaml` and the corresponding script that updates it, and I don't understand what needs to be updated.
Hello @bistaastha Apologies for not replying to you sooner.
You will need to do a few things to fix this issue:
1. Update the script to remove the connectors/databases that have been included in the core
2. Make sure that the connectors/databases that have been included into core are shown in the example_config.yaml
3. Update the script to not include duplicate things - sometimes it would leave commented out skills and letter would show them commented as well
4. Update the example_config with the latest version.
I hope this made things more clear?
Yes, it does. Thank you :)
Hi.
I'm editing the example_config.yaml right now. There are skills which are both commented out and active. Which part has to be kept?
The default connectors/skills that should remain uncommented are:
connectors: websockets
skills: dance, hello, loudnoises, seen
All the others should remain commented out. Hope this helps
Actually loudnoises and seen were commented as well as uncommented.
Thanks, this helps.
Hi @bistaastha ,
I was going through the conversation.are you still working on the same?
I was thinking about helping out so let me know if you need my help.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
Since we haven't got any PR being raised in regards to this issue I am going to say that this issue is still open and we are accepting PR's to fix this 😄
Hello,
can I take this issue?
Sure @jos3p!
> Hello,
> can I take this issue?
Hello @jos3p if you are not working on this issue I would like to try, can you update me where you left off, or need help?
I'm still on it, will post a pullrequest soon | 2019-10-04T02:30:14 |
|
opsdroid/opsdroid | 1,138 | opsdroid__opsdroid-1138 | [
"532"
] | c04bb1c446068c9f8f4f11f6dd8bc8c7f287c2c8 | diff --git a/opsdroid/loader.py b/opsdroid/loader.py
--- a/opsdroid/loader.py
+++ b/opsdroid/loader.py
@@ -588,6 +588,16 @@ def _is_gist_module(config):
return "gist" in config
def _install_module_dependencies(self, config):
+ """Install the dependencies of the module.
+
+ Args:
+ self: instance method
+ config: dict of the module config fields
+
+ Returns:
+ bool: True if installation succeeds
+
+ """
if config.get("no-dep", False):
_LOGGER.debug(
_(
@@ -664,6 +674,13 @@ def _install_local_module(config):
_LOGGER.error("Failed to install from %s", str(config["path"]))
def _install_gist_module(self, config):
+ """Install a module from gist path.
+
+ Args:
+ self: instance method
+ config: dict of module config fields
+
+ """
gist_id = extract_gist_id(config["gist"])
# Get the content of the gist
| Add Google Style Docstrings
We should implement Google Style Docstrings to every function, method, class in opsdroid. This style will support existing documentation and will help in the future by generating documentation automatically.
This consists in a bit of effort so this issue can be worked by more than one contributor, just make sure that everyone knows what you are working on in order to avoid other contributors spending time on something that you are working on.
If you are unfamiliar with the Google Style Docstrings I'd recommend that you check these resources:
- [Sphix 1.8.0+ - Google Style Docstrings](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html)
Docstrings that need to be updated:
- main.py
- [x] configure_lang
- [ ] configure_log
- [ ] get_logging_level
- [ ] check_dependencies
- [ ] print_version
- [ ] print_example_config
- [ ] edit_files
- [x] welcome_message
- ~~helper.py~~
- [x] get_opsdroid
- [x] del_rw
- [x] move_config_to_appdir
- memory.py
- [x] Memory
- [x] get
- [x] put
- [x] _get_from_database
- [x] _put_to_database
- message.py
- [x] Message
- [x] __init__
- [x] _thinking_delay
- [x] _typing delay
- [x] respond
- [x] react
- web.py
- [ ] Web
- [x] get_port
- [x] get_host
- [x] get_ssl_context
- [ ] start
- [ ] build_response
- [ ] web_index_handler
- [ ] web_stats_handler
- matchers.py
- [ ] match_regex
- [ ] match_apiai_action
- [ ] match_apiai_intent
- [ ] match_dialogflow_action
- [ ] match_dialogflow_intent
- [ ] match_luisai_intent
- [ ] match_rasanlu
- [ ] match_recastai
- [ ] match_witai
- [ ] match_crontab
- [ ] match_webhook
- [ ] match_always
- core.py
- [ ] OpsDroid
- [ ] default_connector
- [ ] exit
- [ ] critical
- [ ] call_stop
- [ ] disconnect
- [ ] stop
- [ ] load
- [ ] start_loop
- [x] setup_skills
- [ ] train_parsers
- [ ] start_connector_tasks
- [ ] start_database
- [ ] run_skill
- [ ] get_ranked_skills
- [ ] parse
- loader.py
- [ ] Loader
- [x] import_module_from_spec
- [x] import_module
- [x] check_cache
- [x] build_module_import_path
- [x] build_module_install_path
- [x] git_clone
- [x] git_pull
- [x] pip_install_deps
- [x] create_default_config
- [x] load_config_file
- [ ] envvar_constructor
- [ ] include_constructor
- [x] setup_modules_directory
- [x] load_modules_from_config
- [x] _load_modules
- [x] _install_module
- [x] _update_module
- [ ] _install_git_module
- [x] _install_local_module
---- ORIGINAL POST ----
I've been wondering about this for a while now and I would like to know if we should replace/update all the docstrings in opsdroid with the Google Style doc strings.
I think this could help new and old contributors to contribute and commit to opsdroid since the Google Style docstrings give more information about every method/function and specifies clearly what sort of input the function/method expects, what will it return and what will be raised (if applicable).
The downsize of this style is that the length of every .py file will increase due to the doc strings, but since most IDE's allow you to hide those fields it shouldn't be too bad.
Here is a good example of Google Style Doc strings: [Sphix 1.8.0+ - Google Style Docstrings](http://www.sphinx-doc.org/en/master/ext/example_google.html)
I would like to know what you all think about this idea and if its worth spending time on it.
| Yes we should definitely do this!
It can also be really useful for automatically generating reference documentation.
Awesome I'll wait a few days to see if anyone is opposed to this idea or if they would like to give some advice/comment on the issue.
If in a few days no one says anything I'll edit this issue just to explain more in depth what we expect of the comments and how to do it - I'd recommend dividing opsdroid per each .py file so different people can contribute to the issue 😄
I like the idea. Is it possible to add a test that inspects the doc strings, and fails if they don't match the format? If so, would Jacob be happy with test coverage "reducing" in the short term as this test was added, but before all the doc strings complied?
On 29 April 2018 2:42:05 am AEST, "Fábio Rosado" <[email protected]> wrote:
>Awesome I'll wait a few days to see if anyone is opposed to this idea
>or if they would like to give some advice/comment on the issue.
>
>If in a few days no one says anything I'll edit this issue just to
>explain more in depth what we expect of the comments and how to do it -
>I'd recommend dividing opsdroid per each .py file so different people
>can contribute to the issue 😄
>
>--
>You are receiving this because you are subscribed to this thread.
>Reply to this email directly or view it on GitHub:
>https://github.com/opsdroid/opsdroid/issues/532#issuecomment-385189370
--
Sent from my Android device with K-9 Mail. Please excuse my brevity.
Yes I'm happy with that approach.
I've been thinking about it and I think there are two reasons why anyone would want to do this. The first is for autogenerating documentation, the second is making it easier for people to contribute.
As you said you are intending this to help people contribute, and I definitely agree. I just want to be clear on why we are doing this beyond it just being a thing that some projects do.
We currently run `pydocstyle` as part of the lint suite. I wonder if there is a way of telling it to enforce this docstring style?
I'm not sure if it's possible to enforce google doc style in the lint, but I know that you can run tests on the docstrings like @go8ose suggested, Sphinx has a command for this (it uses the doctest module), but this tests might provide some issues and headaches.
The doctests will use the string representation present in the docstring to run the tests, if the result is not consistent like... a function that deals with dates for example and uses date.now() this test will always fail.
Another example would be running doctests with dictionaries, these tests will mostly fail due to the unsorted nature of dicts, the only way to make them pass would be to sort the dict all the time.
One way to work around it would be to just test some docstrings and not others. In Sphinx you can just add the command:
```
..doctest::
>>> foo()
bar
```
Finally, I believe that all the tests that we have at the moment do a very good job at testing every single piece of code in opsdroid so perhaps adding the doctests would be extra effort for no real gain - these will test what it's being tested already.
--EDIT--
I've updated my first post with all the functions,classes and methods that need to be updated, let me know if you need some added in or removed 👍
Hi Fabio,
I'm not suggesting we add more tests in the form of doctests. That would indeed be a waste of effort. I'm suggesting we check conformance with the google style doc strings.
Jacob suggested seeing if this can be checked in the linting run. That is a good idea, linting is what I should have suggested initially.
Cheers,
Geoff
On 30 April 2018 5:51:38 pm AEST, "Fábio Rosado" <[email protected]> wrote:
>I'm not sure if it's possible to enforce google doc style in the lint,
>but I know that you can run tests on the docstrings like @go8ose
>suggested, Sphinx has a command for this (it uses the doctest module),
>but this tests might provide some issues and headaches.
>
>The doctests will use the string representation present in the
>docstring to run the tests, if the result is not consistent like... a
>function that deals with dates for example and uses date.now() this
>test will always fail.
>Another example would be running doctests with dictionaries, these
>tests will mostly fail due to the unsorted nature of dicts, the only
>way to make them pass would be to sort the dict all the time.
>
>One way to work around it would be to just test some docstrings and not
>others. In Sphinx you can just add the command:
>
>``` ..doctest::
>>>> foo()
>bar
>```
>
>Finally, I believe that all the tests that we have at the moment do a
>very good job at testing every single piece of code in opsdroid so
>perhaps adding the doctests would be extra effort for no real gain -
>these will test what it's being tested already.
>
>--
>You are receiving this because you were mentioned.
>Reply to this email directly or view it on GitHub:
>https://github.com/opsdroid/opsdroid/issues/532#issuecomment-385332374
--
Sent from my Android device with K-9 Mail. Please excuse my brevity.
This tool looks like it tests the docstrings against the google convention. We should explore it more.
https://github.com/terrencepreilly/darglint
Hi Fabio,
I like your idea, i new here on this project i can try to do something and make a pull request.
For my part i'm going to begin with **helper.py** it's Thk ok for you ?
Thk best regards
Heya @sims34 yeah that would be much appreciated, let me know in gitter if you need any help with this 👍
Hi Fabio,
I am new here on this project. I was hoping I could help out with main.py
Regards
Hey @purvaudai, please go ahead!
Hello @purvaudai did you manage to work on `main.py`? If you are stuck with something let us know, we would be happy to help you getting started 👍
Hi Guys is anyone working on this issue
@mraza007 not currently. Please go ahead.
Sure I will start working on this issue. Is there a way that you can assign this issue to me and on what files do I have to add google style doc string functions
Sorry for the lack of replies from my side. I tried solving this issue but
got confused, so I decided to look through the docs again, and I got
carried away learning. I am sorry for the lack of professionalism from my
side.
On Mon, 25 Jun 2018 at 19:33, Muhammad <[email protected]> wrote:
> Sure I will start working on this issue. Is there a way that you can
> assign this issue to me and on what files do I have to add google style doc
> string functions
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <https://github.com/opsdroid/opsdroid/issues/532#issuecomment-399963131>,
> or mute the thread
> <https://github.com/notifications/unsubscribe-auth/AeXNt1F1hUU9JhsW2bl75KQG7SRQEceRks5uAO2_gaJpZM4TqkMs>
> .
>
--
Purva Udai Singh
@purvaudai Hey are working on this issue do you want to continue
Hi guys I'd love to contribute too.
@mraza007 @purvaudai I know you guys are working on this, but if you need my help with any of the file, I'll be more than happy to contribute.
@mraza007 @purvaudai @NikhilRaverkar Thanks for all wanting to contribute! There is a lot to be done on this issue so I strongly recommend picking a file and starting work on it.
Don't worry too much about duplicates, it's unlikely to happen given the number of methods that need updating. I would also be happy for you to submit lots of small PRs. Just pick a few methods, update the docstrings and raise a PR.
Yup I think that would be a great idea
@purvaudai Don't worry my friend sometimes these things happen, if you want to contribute to opsdroid in the future we will be glad to help you 👍
@mraza007 @NikhilRaverkar If you guys need any help, let us know. You can work on different files if you want and if something is not clear feel free to hit us up either in here or our [gitter channel](https://gitter.im/opsdroid/developers)
Sure I just joined the channel I will start working on this over the weekend
I’ll start working on this over the weekend.
Thanks a lot,
Nikhil
> On Jun 28, 2018, at 10:44 AM, Muhammad <[email protected]> wrote:
>
> Sure I just joined the channel I will start working on this over the week
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub, or mute the thread.
I would like to contribute to this. For starters I was thinking about taking the web.py file. :smile:
Hello, please go ahead and let us know if you need any help
@FabioRosado Can I grab message.py? This would be my first issue!
@archime please go ahead! Let me know if you need any help with this issue. Also, welcome to the project 👍
Hey, I'd like to add couple of docstrings, however I've got a question first.
The Google style guide in the description seems to be deprecated.
Should I reference this one https://github.com/google/styleguide/blob/gh-pages/pyguide.md instead?
Hello @kritokrator Thanks for showing interest in this matter.
The sphinx documentation has an up to date style. We are not using typehints in our codebase yet so we will be specifying the type as:
```
Args:
arg1 (String): This arg does things
arg2 (Boolean, optional): This arg can be true, its optional
```
This is a very brief explanation but should get you started, I also recommend you check the [Facebook Connector](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/connector/facebook/__init__.py) as an example of how we would like the doc strings 👍
Hey @FabioRosado, I would like to add docstrings to web.py. The link above no longer works so is this the format you are looking for?
https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
Looking forward to this as this is my first issue!
Hello @GrugLife you are right that is the style we intent to implement in opsdroid. We would be glad to have you contribute to the project let me know if you need any help 😀👍
Hi @FabioRosado, I would like to help on this and would like to start on main.py - this is my first time using github so I'm not entirely sure how to proceed - but I'm sure I'll figure it out. Looking forward to working with you.
Hello @empathic-geek thank you so much for reaching out and working on this issue 😄 Please do let me know if you encounter any issue setting up your development environment or if you have any questions at all!
You can reach me on the [opsdroid chat](https://gitter.im/opsdroid/developers) or any other social networks 😄 👍
I've create pull request for some docstring update :)
Hi @FabioRosado, I would like to start on loader.py.
Hello @WillHensel that would be awesome, feel free to start a PR and let us know if you need any help 👍
Hi @FabioRosado, I would like to take a crack at matchers.py. This will be my first time contributing to a project so I'll ask for your patience :smiley:
Hello Xavier welcome! It would be great if you could work on that and it will help us a lot moving forward to a more consistent code base!
If you do need any help please let us know 😄
Hey @FabioRosado, taking up core.py. Raising multiple small PRs as suggested by @jacobtomlinson.
> Don't worry too much about duplicates, it's unlikely to happen given the number of methods that need updating. I would also be happy for you to submit lots of small PRs. Just pick a few methods, update the docstrings and raise a PR.
Hello @killerontherun1 that would be awesome, please let me know if you need any help with anything 👍
Hey Fabio, do you have a doctest written? So that one can check whether the
docstrings are fine or not?
On Sun, 30 Jun, 2019, 3:51 PM Fábio Rosado, <[email protected]>
wrote:
> Hello @killerontherun1 <https://github.com/killerontherun1> that would be
> awesome, please let me know if you need any help with anything 👍
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <https://github.com/opsdroid/opsdroid/issues/532?email_source=notifications&email_token=AF2JNPBQZIS5V5VSUCD3VQTP5CCIXA5CNFSM4E5KIMWKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGODY4JK2A#issuecomment-507024744>,
> or mute the thread
> <https://github.com/notifications/unsubscribe-auth/AF2JNPABO7T6TRR6PFHRN7LP5CCIXANCNFSM4E5KIMWA>
> .
>
Yeah you can have a look at this link: [Example of Google style docstrings](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html), you can also have a look at the following methods that have been updated with the docstrings:
- Core:
- setup_skills
- send
- Memory.py
And there are a few other places, these should provide you some help. Let me know if you need further help
Sorry, I'm a bit of a noob. But do you want me to rewrite the docstrings itself? Or just adjust the follow the syntax in the given link?
Hi I'd like to help out with this as well! I can try to check out the `matchers.py `file if no one else is working on that.
Hello @profwacko that would be great let me know if you need any help 👍
Hi!
I am a beginner of this project, but I will participate because I can contribute easily.
It may be a really small PR...
Sounds great @pluse09! We look forward to reviewing it.
The URL to Sphinx example in the first comment is broken, it has an extra "l" in ".html"
I'd commented on other issues that I'd tackle on them but people already started to do some part of it, so I'll let for them. So, I'll try to document some of the missing files in the list above, respecting what @pluse09 already started doing at #1087.
I'd like to try my hand at adding docstrings to the `core.py` file and its pending methods, if it's not assigned to anyone else already!
Please go ahead
Hi, may I look into `loaders.py`, there are couple of methods that need Google style docstrings
Hello @suparnasnair thank you for the message, that would be great. Please let me know if you need any help with anything 😄👍 | 2019-10-06T19:02:42 |
|
opsdroid/opsdroid | 1,147 | opsdroid__opsdroid-1147 | [
"667"
] | 1577bf4a2522092c79d887eb3239564ad955ddf9 | diff --git a/opsdroid/connector/shell/__init__.py b/opsdroid/connector/shell/__init__.py
new file mode 100644
--- /dev/null
+++ b/opsdroid/connector/shell/__init__.py
@@ -0,0 +1,132 @@
+"""A connector to send messages using the command line."""
+import logging
+import os
+import sys
+import platform
+import asyncio
+
+from opsdroid.connector import Connector, register_event
+from opsdroid.events import Message
+
+_LOGGER = logging.getLogger(__name__)
+
+
+class ConnectorShell(Connector):
+ """A connector to send messages using the command line."""
+
+ def __init__(self, config, opsdroid=None):
+ """Create the connector."""
+ _LOGGER.debug(_("Loaded shell connector"))
+ super().__init__(config, opsdroid=opsdroid)
+ self.name = "shell"
+ self.config = config
+ self.bot_name = config.get("bot-name", "opsdroid")
+ self.prompt_length = None
+ self.listening = True
+ self.reader = None
+ self._closing = asyncio.Event()
+ self.loop = asyncio.get_event_loop()
+
+ for name in ("LOGNAME", "USER", "LNAME", "USERNAME"):
+ user = os.environ.get(name)
+ if user:
+ self.user = user
+
+ @property
+ def is_listening(self):
+ """Helper, gets listening."""
+ return self.listening
+
+ @is_listening.setter
+ def is_listening(self, val):
+ """Helper, sets listening."""
+ self.listening = val
+
+ async def read_stdin(self):
+ """Create a stream reader to read stdin asynchronously.
+
+ Returns:
+ class: asyncio.streams.StreamReader
+
+ """
+ self.reader = asyncio.StreamReader(loop=self.loop)
+ reader_protocol = asyncio.StreamReaderProtocol(self.reader)
+
+ await self.loop.connect_read_pipe(lambda: reader_protocol, sys.stdin)
+
+ return self.reader
+
+ async def async_input(self):
+ """Read user input asynchronously from stdin.
+
+ Returns:
+ string: A decoded string from user input.
+
+ """
+ if not self.reader:
+ self.reader = await self.read_stdin()
+ line = await self.reader.readline()
+
+ return line.decode("utf8").replace("\r", "").replace("\n", "")
+
+ def draw_prompt(self):
+ """Draw the user input prompt."""
+ prompt = self.bot_name + "> "
+ self.prompt_length = len(prompt)
+ print(prompt, end="", flush=True)
+
+ def clear_prompt(self):
+ """Clear the prompt."""
+ print("\r" + (" " * self.prompt_length) + "\r", end="", flush=True)
+
+ async def parseloop(self):
+ """Parseloop moved out for testing."""
+ self.draw_prompt()
+ user_input = await self.async_input()
+ message = Message(user_input, self.user, None, self)
+ await self.opsdroid.parse(message)
+
+ async def _parse_message(self):
+ """Parse user input."""
+ while self.is_listening:
+ await self.parseloop()
+
+ async def connect(self):
+ """Connect to the shell.
+
+ There is nothing to do here since stdin is already available.
+
+ Since this is the first method called when opsdroid starts, a logging
+ message is shown if the user is using windows.
+
+ """
+ if platform.system() == "Windows":
+ _LOGGER.warning(
+ "The shell connector does not work on windows."
+ " Please install the Opsdroid Desktop App."
+ )
+ pass
+
+ async def listen(self):
+ """Listen for and parse new user input."""
+ _LOGGER.debug(_("Connecting to shell"))
+ message_processor = self.loop.create_task(self._parse_message())
+ await self._closing.wait()
+ message_processor.cancel()
+
+ @register_event(Message)
+ async def respond(self, message):
+ """Respond with a message.
+
+ Args:
+ message (object): An instance of Message
+
+ """
+ _LOGGER.debug(_("Responding with: %s"), message.text)
+ self.clear_prompt()
+ print(message.text)
+ self.draw_prompt()
+
+ async def disconnect(self):
+ """Disconnects the connector."""
+ self._closing.set()
| diff --git a/tests/test_connector_shell.py b/tests/test_connector_shell.py
new file mode 100644
--- /dev/null
+++ b/tests/test_connector_shell.py
@@ -0,0 +1,169 @@
+"""Tests for the shell connector class."""
+import os
+import io
+import contextlib
+import asyncio
+import unittest
+import unittest.mock as mock
+import asynctest
+import asynctest.mock as amock
+
+from opsdroid.core import OpsDroid
+from opsdroid.connector.shell import ConnectorShell
+from opsdroid.message import Message
+from opsdroid.cli.start import configure_lang
+
+
+class TestConnectorShell(unittest.TestCase):
+ """Test the opsdroid shell connector class."""
+
+ def setUp(self):
+ self.connector = ConnectorShell({"name": "shell", "bot-name": "opsdroid-test"})
+ self.loop = asyncio.new_event_loop()
+ configure_lang({})
+ os.environ["USERNAME"] = "opsdroid"
+
+ def test_init(self):
+ """Test that the connector is initialised properly."""
+ self.assertEqual(self.connector.user, "opsdroid")
+ self.assertEqual(len(self.connector.config), 2)
+ self.assertEqual("shell", self.connector.name)
+ self.assertEqual("opsdroid-test", self.connector.bot_name)
+
+ def test_is_listening(self):
+ self.assertEqual(self.connector.listening, self.connector.is_listening)
+
+ def test_is_listening_setter(self):
+ self.assertEqual(self.connector.listening, self.connector.is_listening)
+ self.connector.is_listening = False
+ self.assertFalse(self.connector.listening)
+
+ def test_draw_prompt(self):
+ self.assertEqual(self.connector.prompt_length, None)
+
+ f = io.StringIO()
+ with contextlib.redirect_stdout(f):
+ self.connector.prompt_length = 1
+ self.connector.draw_prompt()
+ prompt = f.getvalue()
+ self.assertEqual(prompt, "opsdroid-test> ")
+ self.connector.draw_prompt()
+ self.assertEqual(self.connector.prompt_length, 15)
+
+ def test_clear_prompt(self):
+ self.connector.prompt_length = 1
+
+ f = io.StringIO()
+ with contextlib.redirect_stdout(f):
+ self.connector.clear_prompt()
+ prompt = f.getvalue()
+ self.assertEqual(prompt, "\r \r")
+
+
+class TestConnectorShellAsync(asynctest.TestCase):
+ """Test the async methods of the opsdroid shell connector class."""
+
+ def setUp(self):
+ os.environ["LOGNAME"] = "opsdroid"
+ self.connector = ConnectorShell({"name": "shell", "bot-name": "opsdroid"})
+
+ async def test_read_stdin(self):
+ with amock.patch(
+ "opsdroid.connector.shell.ConnectorShell.read_stdin"
+ ) as mocked_read_stdin:
+ await self.connector.read_stdin()
+ self.assertTrue(mocked_read_stdin.called)
+
+ if os.name == "nt":
+ with amock.patch(
+ "asyncio.events.AbstractEventLoop.connect_read_pipe"
+ ) as mock:
+ with contextlib.suppress(NotImplementedError):
+ await self.connector.read_stdin()
+ else:
+ self.connector.loop.connect_read_pipe = amock.CoroutineMock()
+ self.connector.reader = None
+ self.assertIsNone(self.connector.reader)
+ result = await self.connector.read_stdin()
+ self.assertEqual(result, self.connector.reader)
+
+ async def test_connect(self):
+ connector = ConnectorShell({}, opsdroid=OpsDroid())
+ await connector.connect()
+ self.assertTrue(connector.connect)
+
+ with amock.patch("platform.system", amock.MagicMock(return_value="Windows")):
+ await connector.connect()
+ self.assertTrue(connector.connect)
+
+ @amock.patch("opsdroid.connector.shell.ConnectorShell.read_stdin")
+ async def test_async_input(self, mocked_read):
+ mocked_read.readline.return_value.side_effect = "hi"
+ with contextlib.suppress(AttributeError, TypeError):
+ await self.connector.async_input()
+ self.assertEqual(mocked_read, "hi")
+
+ connector = ConnectorShell({}, opsdroid=OpsDroid())
+ f = asyncio.Future()
+ f.set_result(b"hi\n")
+
+ with asynctest.patch("asyncio.streams.StreamReader.readline") as mocked_line:
+ mocked_line.return_value = f
+ connector.reader = asyncio.streams.StreamReader
+ returned = await connector.async_input()
+ self.assertEqual(returned, "hi")
+
+ async def test_parse_message(self):
+ connector = ConnectorShell({}, opsdroid=OpsDroid())
+
+ with amock.patch(
+ "opsdroid.connector.shell.ConnectorShell.parseloop"
+ ) as mockedloop:
+ self.assertTrue(connector.listening)
+ connector.listening = True
+ with amock.patch(
+ "opsdroid.connector.shell.ConnectorShell.is_listening",
+ new_callable=amock.PropertyMock,
+ side_effect=[True, False],
+ ) as mocklistening:
+ await connector._parse_message()
+ mockedloop.assert_called()
+
+ async def test_parseloop(self):
+ connector = ConnectorShell({}, opsdroid=OpsDroid())
+
+ connector.draw_prompt = amock.CoroutineMock()
+ connector.draw_prompt.return_value = "opsdroid> "
+ connector.async_input = amock.CoroutineMock()
+ connector.async_input.return_value = "hello"
+
+ connector.opsdroid = amock.CoroutineMock()
+ connector.opsdroid.parse = amock.CoroutineMock()
+
+ await connector.parseloop()
+ self.assertTrue(connector.opsdroid.parse.called)
+
+ async def test_listen(self):
+ connector = ConnectorShell({}, opsdroid=OpsDroid())
+ connector.listening = False
+ with amock.patch(
+ "asyncio.events.AbstractEventLoop.create_task"
+ ) as mock, amock.patch("asyncio.locks.Event.wait") as mockwait:
+ await connector.listen()
+
+ async def test_respond(self):
+ message = Message(
+ text="Hi", user="opsdroid", room="test", connector=self.connector
+ )
+ self.connector.prompt_length = 1
+
+ f = io.StringIO()
+ with contextlib.redirect_stdout(f):
+ await self.connector.respond(message)
+ prompt = f.getvalue()
+ self.assertEqual(prompt.strip(), "Hi\nopsdroid>")
+
+ async def test_disconnect(self):
+ connector = ConnectorShell({}, opsdroid=OpsDroid())
+ await self.connector.disconnect()
+ self.assertEqual(self.connector._closing.set(), None)
| Move shell connector into core
This issue covers adding the [Shell connector](https://github.com/opsdroid/connector-shell) to core.
## Background
A while ago we began moving connectors from external plugins into the core of the project (see #185 for more context). We started with [slack](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/connector/slack/__init__.py) and [websockets](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/connector/websocket/__init__.py) but need to go through all the other existing plugins and move them into the core.
## Steps
- Make a new submodule directory in [`opsdroid.connector`](https://github.com/opsdroid/opsdroid/tree/master/opsdroid/connector) and copy the connector code over.
- Update the [`requirements.txt`](https://github.com/opsdroid/opsdroid/blob/master/requirements.txt) with any dependencies from the connector if necessary.
- Write tests for the connector. (See the [Slack connector tests](https://github.com/jacobtomlinson/opsdroid/blob/master/tests/test_connector_slack.py) for inspiration).
- Copy the relevant information from the connector `README.md` into a [new documentation page](https://github.com/opsdroid/opsdroid/tree/master/docs/connectors).
- Add the new page to the [mkdocs.yml](https://github.com/opsdroid/opsdroid/blob/master/mkdocs.yml).
- Add to the [list of connectors](https://github.com/opsdroid/opsdroid/blob/master/docs/configuration-reference.md#connector-modules).
- Add a deprecation notice to the old connector. (See [the slack connector](https://github.com/opsdroid/connector-slack))
| @jacobtomlinson I'd like to take this issue.
Hello @Replayattack please go ahead and work on this issue, if you need any help let us know 👍
Hey @Replayattack I'm guessing you've not had time to work on this. If anyone else wants to take this up then please go ahead. | 2019-10-09T01:38:54 |
opsdroid/opsdroid | 1,166 | opsdroid__opsdroid-1166 | [
"1159"
] | a7715c3b8617842ed10e5e12acc67da4df36f25b | diff --git a/opsdroid/connector/matrix/connector.py b/opsdroid/connector/matrix/connector.py
--- a/opsdroid/connector/matrix/connector.py
+++ b/opsdroid/connector/matrix/connector.py
@@ -30,9 +30,7 @@ def __init__(self, config, opsdroid=None): # noqa: D107
super().__init__(config, opsdroid=opsdroid)
self.name = "ConnectorMatrix" # The name of your connector
- self.rooms = config.get("rooms", None)
- if not self.rooms:
- self.rooms = {"main": config["room"]}
+ self.rooms = config["rooms"]
self.room_ids = {}
self.default_target = self.rooms["main"]
self.mxid = config["mxid"]
| diff --git a/tests/test_connector_matrix.py b/tests/test_connector_matrix.py
--- a/tests/test_connector_matrix.py
+++ b/tests/test_connector_matrix.py
@@ -21,7 +21,7 @@ def setup_connector():
"""Initiate a basic connector setup for testing on"""
connector = ConnectorMatrix(
{
- "room": "#test:localhost",
+ "rooms": {"main": "#test:localhost"},
"mxid": "@opsdroid:localhost",
"password": "hello",
"homeserver": "http://localhost:8008",
| Error when starting with matrix-connector
When I try to start opsdroid I keep getting the following error. I double checked indentation and when I delete the matrix-connector part opsdroid starts fine.
```
opsdroid_1 | Error validating data /root/.config/opsdroid/configuration.yaml with schema /usr/src/app/opsdroid/configuration/schema.yaml
opsdroid_1 | connectors.1.name: 'matrix' is not a regex match.
opsdroid_1 | connectors.1.name: 'matrix' is not a regex match.
opsdroid_1 | connectors.1.name: 'matrix' is not a regex match.
opsdroid_1 | connectors.1.webhook-url: Required field missing
opsdroid_1 | connectors.1.access-token: Required field missing
opsdroid_1 | connectors.1.name: 'matrix' is not a regex match.
opsdroid_1 | connectors.1.verify-token: Required field missing
opsdroid_1 | connectors.1.page-access-token: Required field missing
opsdroid_1 | connectors.1.name: 'matrix' is not a regex match.
opsdroid_1 | connectors.1.mxid: 'xxx' is not a regex match.
opsdroid_1 | connectors.1.room: Required field missing
opsdroid_1 | connectors.1.rooms.main: 'xxx' is not a regex match.
opsdroid_1 | connectors.1.rooms.other: 'xxx' is not a regex match.
opsdroid_1 | connectors.1.homeserver: 'xxx' is not a regex match.
opsdroid_1 | connectors.1.name: 'matrix' is not a regex match.
opsdroid_1 | connectors.1.api-token: Required field missing
opsdroid_1 | connectors.1.name: 'matrix' is not a regex match.
opsdroid_1 | connectors.1.token: Required field missing
opsdroid_1 | connectors.1.name: 'matrix' is not a regex match.
opsdroid_1 | connectors.1.consumer_key: Required field missing
opsdroid_1 | connectors.1.consumer_secret: Required field missing
opsdroid_1 | connectors.1.oauth_token: Required field missing
opsdroid_1 | connectors.1.oauth_token_secret: Required field missing
opsdroid_1 | connectors.1.name: 'matrix' is not a regex match.
opsdroid_1 | connectors.1.room-id: Required field missing
opsdroid_1 | connectors.1.access-token: Required field missing
```
## Configuration File
```yaml
## _ _ _
## ___ _ __ ___ __| |_ __ ___ (_) __| |
## / _ \| '_ \/ __|/ _` | '__/ _ \| |/ _` |
## | (_) | |_) \__ \ (_| | | | (_) | | (_| |
## \___/| .__/|___/\__,_|_| \___/|_|\__,_|
## |_|
## __ _
## ___ ___ _ __ / _(_) __ _
## / __/ _ \| '_ \| |_| |/ _` |
## | (_| (_) | | | | _| | (_| |
## \___\___/|_| |_|_| |_|\__, |
## |___/
##
## A default config file to use with opsdroid
## see https://github.com/opsdroid/opsdroid/blob/master/opsdroid/configuration/example_configuration.yaml for more config options
## Set the logging level
logging:
level: info
path: opsdroid.log
console: true
## Show welcome message
welcome-message: true
## Connector modules
connectors:
- name: websocket
# optional
bot-name: "mybot" # default "opsdroid"
max-connections: 10 # default is 10 users can be connected at once
connection-timeout: 10 # default 10 seconds before requested socket times out
## Matrix (core)
- name: matrix
# Required
mxid: "xxx"
password: "xxx"
# a dictionary of multiple rooms
# One of these should be named 'main'
rooms:
'main': 'xxx'
'other': 'xxx'
# Optional
homeserver: "xxx"
nick: "xxx" # The nick will be set on startup
room_specific_nicks: False # Look up room specific nicknames of senders (expensive in large rooms)
## Skill modules
skills:
## Dance (https://github.com/opsdroid/skill-dance)
- name: dance
## Hello (https://github.com/opsdroid/skill-hello)
- name: hello
## Loudnoises (https://github.com/opsdroid/skill-loudnoises)
- name: loudnoises
## Seen (https://github.com/opsdroid/skill-seen)
- name: seen
```
| cc @Cadair @SolarDrew
The config looks fine to me, I am little confused as to how this:
```
opsdroid_1 | connectors.1.name: 'matrix' is not a regex match.
```
is being triggered off [this](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/configuration/schema.yaml#L70) regex?
I forgot to mention that I'm using the docker image `opsdroid/opsdroid:latest` pulled yesterday. So should be v0.16.0
@Cadair yeah it's that regex. I've seen something similar when indentation has been off. There aren't any other options missing in the config are there?
Could this be some issue with the yamale check? I remember the issue I had with Telegram(#1055) the messages seems somewhat similar to what I was getting 🤔
--EDIT--
With the yamale checks in place, I'm going to assume that they are being thrown because of the `xxx` that is being passed. Perhaps one of the options is marked as required and doesn't accept anything that is not in the regex check?
--EDIT 2--
I check the schema.yaml and it seems that my suspicion was correct, the issue was some of the options that was passed to the configuration file. You can see on [line 71](https://github.com/opsdroid/opsdroid/blob/b8c2dfa48e0af19bd9cbe89d2d090ef04b283831/opsdroid/configuration/schema.yaml#L71) and [line 75](https://github.com/opsdroid/opsdroid/blob/b8c2dfa48e0af19bd9cbe89d2d090ef04b283831/opsdroid/configuration/schema.yaml#L75) that the regex expects the string to end with `:matrix.org` or the homeserver to be `https://matrix.org`.
I believe the regex for rooms-main should be changed as well otherwise it will always fail if someone self-hosts matrix.
@awesome-michael were you running matrix on your own server? If that's the case then I am going to say that I'm 100% sure the issue is here 🤔
Yes I'm trying to connect to my own homeserver. In fact I'm trying to connect to pantalaimon that should connect to my own homeserver as suggested in #992 ;)
I'll check if editing the regex will help with this issue.
Please let us know but I think it will be one of these fields (if not all of then) that are causing the issues. For what I've gathered they assume you are using matrix.org only.
Please feel free to raise a PR fixing the issue if you wish otherwise i'll try to tackle it when I got the time once it has been confirmed 😄 👍
> the regex expects the string to end with :matrix.org or the homeserver to be https://matrix.org.
:see_no_evil: Why?! :scream:
Looks like this has been busted since the introduction of these schemas: https://github.com/opsdroid/opsdroid/pull/1003
I think we probably shouldn't be validating any of those fields anywhere near as strongly as that, I am nervous about validating them at all beyond type really.
Ok let's roll the validation back a bit.
I'm also not very impressed with the error handling in yamale. It seems to just blast a ton of errors at you
> > the regex expects the string to end with :matrix.org or the homeserver to be https://matrix.org.
>
> 🙈 Why?! 😱
Perhaps the contributor didn't knew the matrix connector could connect to own servers 🤔
Instead of reverting the validation PR how about we fix the schema? I'm with Cadair about validating the yaml beyond type - it makes sense on the required things but doesn't on other situations like this one.
Yamale allows you to just specify type like this:
```
friend:
name: str()
```
We could check if some things are strings, lists, dicts, etc. You can also write custom validators but I'm not sure if it will be used much atm.
I also agree that the error handling in yamale is pretty bad since it just regurgitates the errors at you and you need to cross check with the schema what is expected. (unless this is an issue with the regex validator)
> Instead of reverting the validation PR how about we fix the schema?
Yeah I didn't mean revert the PR. I meant relax the rules.
Oh sorry misunderstood the comment!
I did a quick look at yaml validators and Cerberus seems like a good way to get error handling 🤔
What do you think? [Cerberus Usage](http://docs.python-cerberus.org/en/stable/usage.html)
Would that be a replacement for yamale?
If we want better error handling we might have to replace it yeah, not sure how it compares with yamale yet though
okay I verified that the regex checks are responsible for the error. I changed the scheme.yaml to
```
...
---
matrix:
name: regex('^(?i)matrix$')
mxid: str(required=True)
password: str(required=True)
room: str()
rooms: (include('room1'))
homeserver: str(required=True)
nick: str(required=False)
room_specific_nicks: bool(required=False)
send_m_notice: bool(required=False)
---
room1:
'main': str()
'other': str()
---
...
```
(the rooms were checked to end with `matrix.org` too)
and altered my config to
```
## Matrix (core)
- name: matrix
# Required
mxid: "xxx"
password: "xxx"
# a dictionary of multiple rooms
# One of these should be named 'main'
rooms:
'main': 'xxx'
'other': 'xxx'
# Optional
homeserver: "xxx"
nick: "xxx" # The nick will be set on startup
room_specific_nicks: False # Look up room specific nicknames of senders (expensive in large rooms)
webhook-url: ''
access-token: ''
verify-token: ''
page-access-token: ''
room: ''
api-token: ''
token: ''
consumer_key: ''
consumer_secret: ''
oauth_token: ''
oauth_token_secret: ''
room-id: ''
access-token: ''
```
I had to provide all the `Required field missing` from the error above too.
So it seems the schema check for Matrix is really broken :(
As I read through the discussion I think I won't be able to provide a PR for this.
If you are participating on the hacktoberfest you can just change the schema for what you have show shown on your comment that seems a good temporary fix until we decide what to do next.
If not or you don’t have time I will open a PR to fix the issue tomorrow 😄👍 anyway thank you for raising the issue and helping us with this!
Since hacktoberfest seems to be perfect occasion for this (would be my first PR) I begun to write a fix. Now I think I have an explanation for all the `Required field missing` errors:
all these fields are checked with `str()` in the other sections. Looks like `str()` is equivalent to `str(required=True)` and the parser is ignoring that these fields come from other sections.
How to deal with that problem?
That’s a good question, I don’t understand why yamale decided to just go add the required if you specify a type, this is pretty weird...
It’s a pain in the back but perhaps turn all of those that are not required to False?
Was my first thought too.. but I think these values are checked with `str()` because they are all required for their sections...
I read a bit through the documentation of yamale..
It says
> Schema files may contain more than one YAML document (nodes separated by ---)
and
> Every root node not in the first YAML document will be treated like an include
so the schema.yaml you built can not check for the individual connectors but checks always everything. Thats the reason it complains about the required fields so much. | 2019-10-15T16:46:36 |
opsdroid/opsdroid | 1,183 | opsdroid__opsdroid-1183 | [
"532"
] | bca5db9de029d15175d19df39a559f3b90ee3b7c | diff --git a/opsdroid/cli/config.py b/opsdroid/cli/config.py
--- a/opsdroid/cli/config.py
+++ b/opsdroid/cli/config.py
@@ -7,7 +7,19 @@
def print_example_config(ctx, param, value):
- """[Deprecated] Print out the example config."""
+ """[Deprecated] Print out the example config.
+
+ Args:
+ ctx (:obj:`click.Context`): The current click cli context.
+ param (dict): a dictionary of all parameters pass to the click
+ context when invoking this function as a callback.
+ value (bool): the value of this parameter after invocation.
+ Defaults to False, set to True when this flag is called.
+
+ Returns:
+ int: the exit code. Always returns 0 in this case.
+
+ """
if not value or ctx.resilient_parsing:
return
if ctx.command.name == "cli":
diff --git a/opsdroid/cli/utils.py b/opsdroid/cli/utils.py
--- a/opsdroid/cli/utils.py
+++ b/opsdroid/cli/utils.py
@@ -20,7 +20,21 @@
def edit_files(ctx, param, value):
- """Open config/log file with favourite editor."""
+ """Open config/log file with favourite editor.
+
+ Args:
+ ctx (:obj:`click.Context`): The current click cli context.
+ param (dict): a dictionary of all parameters pass to the click
+ context when invoking this function as a callback.
+ value (string): the value of this parameter after invocation.
+ It is either "config" or "log" depending on the program
+ calling this function.
+
+ Returns:
+ int: the exit code. Always returns 0 in this case.
+
+ """
+
if value == "config":
file = DEFAULT_CONFIG_PATH
if ctx.command.name == "cli":
@@ -72,7 +86,13 @@ def configure_lang(config):
def check_dependencies():
- """Check for system dependencies required by opsdroid."""
+ """Check for system dependencies required by opsdroid.
+
+ Returns:
+ int: the exit code. Returns 1 if the Python version installed is
+ below 3.6.
+
+ """
if sys.version_info.major < 3 or sys.version_info.minor < 6:
logging.critical(_("Whoops! opsdroid requires python 3.6 or above."))
sys.exit(1)
| Add Google Style Docstrings
We should implement Google Style Docstrings to every function, method, class in opsdroid. This style will support existing documentation and will help in the future by generating documentation automatically.
This consists in a bit of effort so this issue can be worked by more than one contributor, just make sure that everyone knows what you are working on in order to avoid other contributors spending time on something that you are working on.
If you are unfamiliar with the Google Style Docstrings I'd recommend that you check these resources:
- [Sphix 1.8.0+ - Google Style Docstrings](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html)
Docstrings that need to be updated:
- main.py
- [x] configure_lang
- [ ] configure_log
- [ ] get_logging_level
- [ ] check_dependencies
- [ ] print_version
- [ ] print_example_config
- [ ] edit_files
- [x] welcome_message
- ~~helper.py~~
- [x] get_opsdroid
- [x] del_rw
- [x] move_config_to_appdir
- memory.py
- [x] Memory
- [x] get
- [x] put
- [x] _get_from_database
- [x] _put_to_database
- message.py
- [x] Message
- [x] __init__
- [x] _thinking_delay
- [x] _typing delay
- [x] respond
- [x] react
- web.py
- [ ] Web
- [x] get_port
- [x] get_host
- [x] get_ssl_context
- [ ] start
- [ ] build_response
- [ ] web_index_handler
- [ ] web_stats_handler
- matchers.py
- [ ] match_regex
- [ ] match_apiai_action
- [ ] match_apiai_intent
- [ ] match_dialogflow_action
- [ ] match_dialogflow_intent
- [ ] match_luisai_intent
- [ ] match_rasanlu
- [ ] match_recastai
- [ ] match_witai
- [ ] match_crontab
- [ ] match_webhook
- [ ] match_always
- core.py
- [ ] OpsDroid
- [ ] default_connector
- [ ] exit
- [ ] critical
- [ ] call_stop
- [ ] disconnect
- [ ] stop
- [ ] load
- [ ] start_loop
- [x] setup_skills
- [ ] train_parsers
- [ ] start_connector_tasks
- [ ] start_database
- [ ] run_skill
- [ ] get_ranked_skills
- [ ] parse
- loader.py
- [ ] Loader
- [x] import_module_from_spec
- [x] import_module
- [x] check_cache
- [x] build_module_import_path
- [x] build_module_install_path
- [x] git_clone
- [x] git_pull
- [x] pip_install_deps
- [x] create_default_config
- [x] load_config_file
- [ ] envvar_constructor
- [ ] include_constructor
- [x] setup_modules_directory
- [x] load_modules_from_config
- [x] _load_modules
- [x] _install_module
- [x] _update_module
- [ ] _install_git_module
- [x] _install_local_module
---- ORIGINAL POST ----
I've been wondering about this for a while now and I would like to know if we should replace/update all the docstrings in opsdroid with the Google Style doc strings.
I think this could help new and old contributors to contribute and commit to opsdroid since the Google Style docstrings give more information about every method/function and specifies clearly what sort of input the function/method expects, what will it return and what will be raised (if applicable).
The downsize of this style is that the length of every .py file will increase due to the doc strings, but since most IDE's allow you to hide those fields it shouldn't be too bad.
Here is a good example of Google Style Doc strings: [Sphix 1.8.0+ - Google Style Docstrings](http://www.sphinx-doc.org/en/master/ext/example_google.html)
I would like to know what you all think about this idea and if its worth spending time on it.
| Yes we should definitely do this!
It can also be really useful for automatically generating reference documentation.
Awesome I'll wait a few days to see if anyone is opposed to this idea or if they would like to give some advice/comment on the issue.
If in a few days no one says anything I'll edit this issue just to explain more in depth what we expect of the comments and how to do it - I'd recommend dividing opsdroid per each .py file so different people can contribute to the issue 😄
I like the idea. Is it possible to add a test that inspects the doc strings, and fails if they don't match the format? If so, would Jacob be happy with test coverage "reducing" in the short term as this test was added, but before all the doc strings complied?
On 29 April 2018 2:42:05 am AEST, "Fábio Rosado" <[email protected]> wrote:
>Awesome I'll wait a few days to see if anyone is opposed to this idea
>or if they would like to give some advice/comment on the issue.
>
>If in a few days no one says anything I'll edit this issue just to
>explain more in depth what we expect of the comments and how to do it -
>I'd recommend dividing opsdroid per each .py file so different people
>can contribute to the issue 😄
>
>--
>You are receiving this because you are subscribed to this thread.
>Reply to this email directly or view it on GitHub:
>https://github.com/opsdroid/opsdroid/issues/532#issuecomment-385189370
--
Sent from my Android device with K-9 Mail. Please excuse my brevity.
Yes I'm happy with that approach.
I've been thinking about it and I think there are two reasons why anyone would want to do this. The first is for autogenerating documentation, the second is making it easier for people to contribute.
As you said you are intending this to help people contribute, and I definitely agree. I just want to be clear on why we are doing this beyond it just being a thing that some projects do.
We currently run `pydocstyle` as part of the lint suite. I wonder if there is a way of telling it to enforce this docstring style?
I'm not sure if it's possible to enforce google doc style in the lint, but I know that you can run tests on the docstrings like @go8ose suggested, Sphinx has a command for this (it uses the doctest module), but this tests might provide some issues and headaches.
The doctests will use the string representation present in the docstring to run the tests, if the result is not consistent like... a function that deals with dates for example and uses date.now() this test will always fail.
Another example would be running doctests with dictionaries, these tests will mostly fail due to the unsorted nature of dicts, the only way to make them pass would be to sort the dict all the time.
One way to work around it would be to just test some docstrings and not others. In Sphinx you can just add the command:
```
..doctest::
>>> foo()
bar
```
Finally, I believe that all the tests that we have at the moment do a very good job at testing every single piece of code in opsdroid so perhaps adding the doctests would be extra effort for no real gain - these will test what it's being tested already.
--EDIT--
I've updated my first post with all the functions,classes and methods that need to be updated, let me know if you need some added in or removed 👍
Hi Fabio,
I'm not suggesting we add more tests in the form of doctests. That would indeed be a waste of effort. I'm suggesting we check conformance with the google style doc strings.
Jacob suggested seeing if this can be checked in the linting run. That is a good idea, linting is what I should have suggested initially.
Cheers,
Geoff
On 30 April 2018 5:51:38 pm AEST, "Fábio Rosado" <[email protected]> wrote:
>I'm not sure if it's possible to enforce google doc style in the lint,
>but I know that you can run tests on the docstrings like @go8ose
>suggested, Sphinx has a command for this (it uses the doctest module),
>but this tests might provide some issues and headaches.
>
>The doctests will use the string representation present in the
>docstring to run the tests, if the result is not consistent like... a
>function that deals with dates for example and uses date.now() this
>test will always fail.
>Another example would be running doctests with dictionaries, these
>tests will mostly fail due to the unsorted nature of dicts, the only
>way to make them pass would be to sort the dict all the time.
>
>One way to work around it would be to just test some docstrings and not
>others. In Sphinx you can just add the command:
>
>``` ..doctest::
>>>> foo()
>bar
>```
>
>Finally, I believe that all the tests that we have at the moment do a
>very good job at testing every single piece of code in opsdroid so
>perhaps adding the doctests would be extra effort for no real gain -
>these will test what it's being tested already.
>
>--
>You are receiving this because you were mentioned.
>Reply to this email directly or view it on GitHub:
>https://github.com/opsdroid/opsdroid/issues/532#issuecomment-385332374
--
Sent from my Android device with K-9 Mail. Please excuse my brevity.
This tool looks like it tests the docstrings against the google convention. We should explore it more.
https://github.com/terrencepreilly/darglint
Hi Fabio,
I like your idea, i new here on this project i can try to do something and make a pull request.
For my part i'm going to begin with **helper.py** it's Thk ok for you ?
Thk best regards
Heya @sims34 yeah that would be much appreciated, let me know in gitter if you need any help with this 👍
Hi Fabio,
I am new here on this project. I was hoping I could help out with main.py
Regards
Hey @purvaudai, please go ahead!
Hello @purvaudai did you manage to work on `main.py`? If you are stuck with something let us know, we would be happy to help you getting started 👍
Hi Guys is anyone working on this issue
@mraza007 not currently. Please go ahead.
Sure I will start working on this issue. Is there a way that you can assign this issue to me and on what files do I have to add google style doc string functions
Sorry for the lack of replies from my side. I tried solving this issue but
got confused, so I decided to look through the docs again, and I got
carried away learning. I am sorry for the lack of professionalism from my
side.
On Mon, 25 Jun 2018 at 19:33, Muhammad <[email protected]> wrote:
> Sure I will start working on this issue. Is there a way that you can
> assign this issue to me and on what files do I have to add google style doc
> string functions
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <https://github.com/opsdroid/opsdroid/issues/532#issuecomment-399963131>,
> or mute the thread
> <https://github.com/notifications/unsubscribe-auth/AeXNt1F1hUU9JhsW2bl75KQG7SRQEceRks5uAO2_gaJpZM4TqkMs>
> .
>
--
Purva Udai Singh
@purvaudai Hey are working on this issue do you want to continue
Hi guys I'd love to contribute too.
@mraza007 @purvaudai I know you guys are working on this, but if you need my help with any of the file, I'll be more than happy to contribute.
@mraza007 @purvaudai @NikhilRaverkar Thanks for all wanting to contribute! There is a lot to be done on this issue so I strongly recommend picking a file and starting work on it.
Don't worry too much about duplicates, it's unlikely to happen given the number of methods that need updating. I would also be happy for you to submit lots of small PRs. Just pick a few methods, update the docstrings and raise a PR.
Yup I think that would be a great idea
@purvaudai Don't worry my friend sometimes these things happen, if you want to contribute to opsdroid in the future we will be glad to help you 👍
@mraza007 @NikhilRaverkar If you guys need any help, let us know. You can work on different files if you want and if something is not clear feel free to hit us up either in here or our [gitter channel](https://gitter.im/opsdroid/developers)
Sure I just joined the channel I will start working on this over the weekend
I’ll start working on this over the weekend.
Thanks a lot,
Nikhil
> On Jun 28, 2018, at 10:44 AM, Muhammad <[email protected]> wrote:
>
> Sure I just joined the channel I will start working on this over the week
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub, or mute the thread.
I would like to contribute to this. For starters I was thinking about taking the web.py file. :smile:
Hello, please go ahead and let us know if you need any help
@FabioRosado Can I grab message.py? This would be my first issue!
@archime please go ahead! Let me know if you need any help with this issue. Also, welcome to the project 👍
Hey, I'd like to add couple of docstrings, however I've got a question first.
The Google style guide in the description seems to be deprecated.
Should I reference this one https://github.com/google/styleguide/blob/gh-pages/pyguide.md instead?
Hello @kritokrator Thanks for showing interest in this matter.
The sphinx documentation has an up to date style. We are not using typehints in our codebase yet so we will be specifying the type as:
```
Args:
arg1 (String): This arg does things
arg2 (Boolean, optional): This arg can be true, its optional
```
This is a very brief explanation but should get you started, I also recommend you check the [Facebook Connector](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/connector/facebook/__init__.py) as an example of how we would like the doc strings 👍
Hey @FabioRosado, I would like to add docstrings to web.py. The link above no longer works so is this the format you are looking for?
https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
Looking forward to this as this is my first issue!
Hello @GrugLife you are right that is the style we intent to implement in opsdroid. We would be glad to have you contribute to the project let me know if you need any help 😀👍
Hi @FabioRosado, I would like to help on this and would like to start on main.py - this is my first time using github so I'm not entirely sure how to proceed - but I'm sure I'll figure it out. Looking forward to working with you.
Hello @empathic-geek thank you so much for reaching out and working on this issue 😄 Please do let me know if you encounter any issue setting up your development environment or if you have any questions at all!
You can reach me on the [opsdroid chat](https://gitter.im/opsdroid/developers) or any other social networks 😄 👍
I've create pull request for some docstring update :)
Hi @FabioRosado, I would like to start on loader.py.
Hello @WillHensel that would be awesome, feel free to start a PR and let us know if you need any help 👍
Hi @FabioRosado, I would like to take a crack at matchers.py. This will be my first time contributing to a project so I'll ask for your patience :smiley:
Hello Xavier welcome! It would be great if you could work on that and it will help us a lot moving forward to a more consistent code base!
If you do need any help please let us know 😄
Hey @FabioRosado, taking up core.py. Raising multiple small PRs as suggested by @jacobtomlinson.
> Don't worry too much about duplicates, it's unlikely to happen given the number of methods that need updating. I would also be happy for you to submit lots of small PRs. Just pick a few methods, update the docstrings and raise a PR.
Hello @killerontherun1 that would be awesome, please let me know if you need any help with anything 👍
Hey Fabio, do you have a doctest written? So that one can check whether the
docstrings are fine or not?
On Sun, 30 Jun, 2019, 3:51 PM Fábio Rosado, <[email protected]>
wrote:
> Hello @killerontherun1 <https://github.com/killerontherun1> that would be
> awesome, please let me know if you need any help with anything 👍
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <https://github.com/opsdroid/opsdroid/issues/532?email_source=notifications&email_token=AF2JNPBQZIS5V5VSUCD3VQTP5CCIXA5CNFSM4E5KIMWKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGODY4JK2A#issuecomment-507024744>,
> or mute the thread
> <https://github.com/notifications/unsubscribe-auth/AF2JNPABO7T6TRR6PFHRN7LP5CCIXANCNFSM4E5KIMWA>
> .
>
Yeah you can have a look at this link: [Example of Google style docstrings](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html), you can also have a look at the following methods that have been updated with the docstrings:
- Core:
- setup_skills
- send
- Memory.py
And there are a few other places, these should provide you some help. Let me know if you need further help
Sorry, I'm a bit of a noob. But do you want me to rewrite the docstrings itself? Or just adjust the follow the syntax in the given link?
Hi I'd like to help out with this as well! I can try to check out the `matchers.py `file if no one else is working on that.
Hello @profwacko that would be great let me know if you need any help 👍
Hi!
I am a beginner of this project, but I will participate because I can contribute easily.
It may be a really small PR...
Sounds great @pluse09! We look forward to reviewing it.
The URL to Sphinx example in the first comment is broken, it has an extra "l" in ".html"
I'd commented on other issues that I'd tackle on them but people already started to do some part of it, so I'll let for them. So, I'll try to document some of the missing files in the list above, respecting what @pluse09 already started doing at #1087.
I'd like to try my hand at adding docstrings to the `core.py` file and its pending methods, if it's not assigned to anyone else already!
Please go ahead
Hi, may I look into `loaders.py`, there are couple of methods that need Google style docstrings
Hello @suparnasnair thank you for the message, that would be great. Please let me know if you need any help with anything 😄👍
I have updated for 2 methods for a start. Sorry I'm a newbie. Please let me know if this is fine, I can go ahead with the remaining ones and clean them up. Thanks !
@FabioRosado there are couple of methods left in loader.py(envvar_constructor, include_constructor), can I take them up if no one else is working on them?
@suparnasnair your PR was great. Welcome to open source! Please feel free to do more.
@p0larstern please go ahead.
@FabioRosado did you mean to close this?
Ooops I didn't notice that the PR that I've merged would close the issue. I've reopened it haha
Hi, I'm new to open source. Can I help out with adding docstrings in `main.py` if noone else is working on it?
@lkcbharath please go ahead
Hi @FabioRosado would there be a quick way for me to understand the functionality of each of the functions I'm writing docstrings for (in `matchers.py`)? Or maybe sort of bump me into the best direction for that.
I'd say reading the matchers documentation might give you a better understanding of what each of them do. But basically matchers are decorators that you use to match a skill(python function) to an intent obtained from a parser.
For example on the dialogflow - the parser will call the API and send over the message from the user, then the API does its thing and returns a response which might contain an intent and other entities.
In dialogflow there is an intent called - `smalltalk.greetings` so you use the `@match_dialogflow_intent('smalltalk.greetings')` to trigger a skill. The matchers basically make that bridge between parsing a message and getting a result and then match a skill with said intent.
You can check the example on the [dialogflow documentation](https://docs.opsdroid.dev/en/stable/matchers/dialogflow/) for more information.
I hope this made sense?
Hi @FabioRosado!
I'm looking to help out on this as well. Looks like the checklist may be out of date now? - I see there was a merge for the CORE section but still some outstanding checkboxes. Can you confirm if the checklist is up to date? I'd love to try and tackle any stragglers.
Hello paqman unfortunately the checklist has been out of date for a while and I haven't have the time to fix it yet. It would be great if you could tackle some of them, Im off in 5 days so I'll try to update the list, you can wait until then or check each file and see if any is left without the google style docstrings - I know there is still a lot of them that don't have it | 2019-10-22T16:44:28 |
|
opsdroid/opsdroid | 1,184 | opsdroid__opsdroid-1184 | [
"532"
] | 8d36a33874af683d8362b50d0c95285783224cc3 | diff --git a/opsdroid/events.py b/opsdroid/events.py
--- a/opsdroid/events.py
+++ b/opsdroid/events.py
@@ -219,6 +219,7 @@ async def _thinking_delay(self):
"""Make opsdroid wait x-seconds before responding.
Number of seconds defined in YAML config. file, accessed via connector.
+
"""
seconds = self.connector.configuration.get("thinking-delay", 0)
@@ -232,6 +233,10 @@ async def _typing_delay(self, text):
Seconds to delay equals number of characters in response multiplied by
number of seconds defined in YAML config. file, accessed via connector.
+
+ Args:
+ text (str): The text input to perform typing simulation on.
+
"""
seconds = self.connector.configuration.get("typing-delay", 0)
char_count = len(text)
| Add Google Style Docstrings
We should implement Google Style Docstrings to every function, method, class in opsdroid. This style will support existing documentation and will help in the future by generating documentation automatically.
This consists in a bit of effort so this issue can be worked by more than one contributor, just make sure that everyone knows what you are working on in order to avoid other contributors spending time on something that you are working on.
If you are unfamiliar with the Google Style Docstrings I'd recommend that you check these resources:
- [Sphix 1.8.0+ - Google Style Docstrings](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html)
Docstrings that need to be updated:
- main.py
- [x] configure_lang
- [ ] configure_log
- [ ] get_logging_level
- [ ] check_dependencies
- [ ] print_version
- [ ] print_example_config
- [ ] edit_files
- [x] welcome_message
- ~~helper.py~~
- [x] get_opsdroid
- [x] del_rw
- [x] move_config_to_appdir
- memory.py
- [x] Memory
- [x] get
- [x] put
- [x] _get_from_database
- [x] _put_to_database
- message.py
- [x] Message
- [x] __init__
- [x] _thinking_delay
- [x] _typing delay
- [x] respond
- [x] react
- web.py
- [ ] Web
- [x] get_port
- [x] get_host
- [x] get_ssl_context
- [ ] start
- [ ] build_response
- [ ] web_index_handler
- [ ] web_stats_handler
- matchers.py
- [ ] match_regex
- [ ] match_apiai_action
- [ ] match_apiai_intent
- [ ] match_dialogflow_action
- [ ] match_dialogflow_intent
- [ ] match_luisai_intent
- [ ] match_rasanlu
- [ ] match_recastai
- [ ] match_witai
- [ ] match_crontab
- [ ] match_webhook
- [ ] match_always
- core.py
- [ ] OpsDroid
- [ ] default_connector
- [ ] exit
- [ ] critical
- [ ] call_stop
- [ ] disconnect
- [ ] stop
- [ ] load
- [ ] start_loop
- [x] setup_skills
- [ ] train_parsers
- [ ] start_connector_tasks
- [ ] start_database
- [ ] run_skill
- [ ] get_ranked_skills
- [ ] parse
- loader.py
- [ ] Loader
- [x] import_module_from_spec
- [x] import_module
- [x] check_cache
- [x] build_module_import_path
- [x] build_module_install_path
- [x] git_clone
- [x] git_pull
- [x] pip_install_deps
- [x] create_default_config
- [x] load_config_file
- [ ] envvar_constructor
- [ ] include_constructor
- [x] setup_modules_directory
- [x] load_modules_from_config
- [x] _load_modules
- [x] _install_module
- [x] _update_module
- [ ] _install_git_module
- [x] _install_local_module
---- ORIGINAL POST ----
I've been wondering about this for a while now and I would like to know if we should replace/update all the docstrings in opsdroid with the Google Style doc strings.
I think this could help new and old contributors to contribute and commit to opsdroid since the Google Style docstrings give more information about every method/function and specifies clearly what sort of input the function/method expects, what will it return and what will be raised (if applicable).
The downsize of this style is that the length of every .py file will increase due to the doc strings, but since most IDE's allow you to hide those fields it shouldn't be too bad.
Here is a good example of Google Style Doc strings: [Sphix 1.8.0+ - Google Style Docstrings](http://www.sphinx-doc.org/en/master/ext/example_google.html)
I would like to know what you all think about this idea and if its worth spending time on it.
| Yes we should definitely do this!
It can also be really useful for automatically generating reference documentation.
Awesome I'll wait a few days to see if anyone is opposed to this idea or if they would like to give some advice/comment on the issue.
If in a few days no one says anything I'll edit this issue just to explain more in depth what we expect of the comments and how to do it - I'd recommend dividing opsdroid per each .py file so different people can contribute to the issue 😄
I like the idea. Is it possible to add a test that inspects the doc strings, and fails if they don't match the format? If so, would Jacob be happy with test coverage "reducing" in the short term as this test was added, but before all the doc strings complied?
On 29 April 2018 2:42:05 am AEST, "Fábio Rosado" <[email protected]> wrote:
>Awesome I'll wait a few days to see if anyone is opposed to this idea
>or if they would like to give some advice/comment on the issue.
>
>If in a few days no one says anything I'll edit this issue just to
>explain more in depth what we expect of the comments and how to do it -
>I'd recommend dividing opsdroid per each .py file so different people
>can contribute to the issue 😄
>
>--
>You are receiving this because you are subscribed to this thread.
>Reply to this email directly or view it on GitHub:
>https://github.com/opsdroid/opsdroid/issues/532#issuecomment-385189370
--
Sent from my Android device with K-9 Mail. Please excuse my brevity.
Yes I'm happy with that approach.
I've been thinking about it and I think there are two reasons why anyone would want to do this. The first is for autogenerating documentation, the second is making it easier for people to contribute.
As you said you are intending this to help people contribute, and I definitely agree. I just want to be clear on why we are doing this beyond it just being a thing that some projects do.
We currently run `pydocstyle` as part of the lint suite. I wonder if there is a way of telling it to enforce this docstring style?
I'm not sure if it's possible to enforce google doc style in the lint, but I know that you can run tests on the docstrings like @go8ose suggested, Sphinx has a command for this (it uses the doctest module), but this tests might provide some issues and headaches.
The doctests will use the string representation present in the docstring to run the tests, if the result is not consistent like... a function that deals with dates for example and uses date.now() this test will always fail.
Another example would be running doctests with dictionaries, these tests will mostly fail due to the unsorted nature of dicts, the only way to make them pass would be to sort the dict all the time.
One way to work around it would be to just test some docstrings and not others. In Sphinx you can just add the command:
```
..doctest::
>>> foo()
bar
```
Finally, I believe that all the tests that we have at the moment do a very good job at testing every single piece of code in opsdroid so perhaps adding the doctests would be extra effort for no real gain - these will test what it's being tested already.
--EDIT--
I've updated my first post with all the functions,classes and methods that need to be updated, let me know if you need some added in or removed 👍
Hi Fabio,
I'm not suggesting we add more tests in the form of doctests. That would indeed be a waste of effort. I'm suggesting we check conformance with the google style doc strings.
Jacob suggested seeing if this can be checked in the linting run. That is a good idea, linting is what I should have suggested initially.
Cheers,
Geoff
On 30 April 2018 5:51:38 pm AEST, "Fábio Rosado" <[email protected]> wrote:
>I'm not sure if it's possible to enforce google doc style in the lint,
>but I know that you can run tests on the docstrings like @go8ose
>suggested, Sphinx has a command for this (it uses the doctest module),
>but this tests might provide some issues and headaches.
>
>The doctests will use the string representation present in the
>docstring to run the tests, if the result is not consistent like... a
>function that deals with dates for example and uses date.now() this
>test will always fail.
>Another example would be running doctests with dictionaries, these
>tests will mostly fail due to the unsorted nature of dicts, the only
>way to make them pass would be to sort the dict all the time.
>
>One way to work around it would be to just test some docstrings and not
>others. In Sphinx you can just add the command:
>
>``` ..doctest::
>>>> foo()
>bar
>```
>
>Finally, I believe that all the tests that we have at the moment do a
>very good job at testing every single piece of code in opsdroid so
>perhaps adding the doctests would be extra effort for no real gain -
>these will test what it's being tested already.
>
>--
>You are receiving this because you were mentioned.
>Reply to this email directly or view it on GitHub:
>https://github.com/opsdroid/opsdroid/issues/532#issuecomment-385332374
--
Sent from my Android device with K-9 Mail. Please excuse my brevity.
This tool looks like it tests the docstrings against the google convention. We should explore it more.
https://github.com/terrencepreilly/darglint
Hi Fabio,
I like your idea, i new here on this project i can try to do something and make a pull request.
For my part i'm going to begin with **helper.py** it's Thk ok for you ?
Thk best regards
Heya @sims34 yeah that would be much appreciated, let me know in gitter if you need any help with this 👍
Hi Fabio,
I am new here on this project. I was hoping I could help out with main.py
Regards
Hey @purvaudai, please go ahead!
Hello @purvaudai did you manage to work on `main.py`? If you are stuck with something let us know, we would be happy to help you getting started 👍
Hi Guys is anyone working on this issue
@mraza007 not currently. Please go ahead.
Sure I will start working on this issue. Is there a way that you can assign this issue to me and on what files do I have to add google style doc string functions
Sorry for the lack of replies from my side. I tried solving this issue but
got confused, so I decided to look through the docs again, and I got
carried away learning. I am sorry for the lack of professionalism from my
side.
On Mon, 25 Jun 2018 at 19:33, Muhammad <[email protected]> wrote:
> Sure I will start working on this issue. Is there a way that you can
> assign this issue to me and on what files do I have to add google style doc
> string functions
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <https://github.com/opsdroid/opsdroid/issues/532#issuecomment-399963131>,
> or mute the thread
> <https://github.com/notifications/unsubscribe-auth/AeXNt1F1hUU9JhsW2bl75KQG7SRQEceRks5uAO2_gaJpZM4TqkMs>
> .
>
--
Purva Udai Singh
@purvaudai Hey are working on this issue do you want to continue
Hi guys I'd love to contribute too.
@mraza007 @purvaudai I know you guys are working on this, but if you need my help with any of the file, I'll be more than happy to contribute.
@mraza007 @purvaudai @NikhilRaverkar Thanks for all wanting to contribute! There is a lot to be done on this issue so I strongly recommend picking a file and starting work on it.
Don't worry too much about duplicates, it's unlikely to happen given the number of methods that need updating. I would also be happy for you to submit lots of small PRs. Just pick a few methods, update the docstrings and raise a PR.
Yup I think that would be a great idea
@purvaudai Don't worry my friend sometimes these things happen, if you want to contribute to opsdroid in the future we will be glad to help you 👍
@mraza007 @NikhilRaverkar If you guys need any help, let us know. You can work on different files if you want and if something is not clear feel free to hit us up either in here or our [gitter channel](https://gitter.im/opsdroid/developers)
Sure I just joined the channel I will start working on this over the weekend
I’ll start working on this over the weekend.
Thanks a lot,
Nikhil
> On Jun 28, 2018, at 10:44 AM, Muhammad <[email protected]> wrote:
>
> Sure I just joined the channel I will start working on this over the week
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub, or mute the thread.
I would like to contribute to this. For starters I was thinking about taking the web.py file. :smile:
Hello, please go ahead and let us know if you need any help
@FabioRosado Can I grab message.py? This would be my first issue!
@archime please go ahead! Let me know if you need any help with this issue. Also, welcome to the project 👍
Hey, I'd like to add couple of docstrings, however I've got a question first.
The Google style guide in the description seems to be deprecated.
Should I reference this one https://github.com/google/styleguide/blob/gh-pages/pyguide.md instead?
Hello @kritokrator Thanks for showing interest in this matter.
The sphinx documentation has an up to date style. We are not using typehints in our codebase yet so we will be specifying the type as:
```
Args:
arg1 (String): This arg does things
arg2 (Boolean, optional): This arg can be true, its optional
```
This is a very brief explanation but should get you started, I also recommend you check the [Facebook Connector](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/connector/facebook/__init__.py) as an example of how we would like the doc strings 👍
Hey @FabioRosado, I would like to add docstrings to web.py. The link above no longer works so is this the format you are looking for?
https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
Looking forward to this as this is my first issue!
Hello @GrugLife you are right that is the style we intent to implement in opsdroid. We would be glad to have you contribute to the project let me know if you need any help 😀👍
Hi @FabioRosado, I would like to help on this and would like to start on main.py - this is my first time using github so I'm not entirely sure how to proceed - but I'm sure I'll figure it out. Looking forward to working with you.
Hello @empathic-geek thank you so much for reaching out and working on this issue 😄 Please do let me know if you encounter any issue setting up your development environment or if you have any questions at all!
You can reach me on the [opsdroid chat](https://gitter.im/opsdroid/developers) or any other social networks 😄 👍
I've create pull request for some docstring update :)
Hi @FabioRosado, I would like to start on loader.py.
Hello @WillHensel that would be awesome, feel free to start a PR and let us know if you need any help 👍
Hi @FabioRosado, I would like to take a crack at matchers.py. This will be my first time contributing to a project so I'll ask for your patience :smiley:
Hello Xavier welcome! It would be great if you could work on that and it will help us a lot moving forward to a more consistent code base!
If you do need any help please let us know 😄
Hey @FabioRosado, taking up core.py. Raising multiple small PRs as suggested by @jacobtomlinson.
> Don't worry too much about duplicates, it's unlikely to happen given the number of methods that need updating. I would also be happy for you to submit lots of small PRs. Just pick a few methods, update the docstrings and raise a PR.
Hello @killerontherun1 that would be awesome, please let me know if you need any help with anything 👍
Hey Fabio, do you have a doctest written? So that one can check whether the
docstrings are fine or not?
On Sun, 30 Jun, 2019, 3:51 PM Fábio Rosado, <[email protected]>
wrote:
> Hello @killerontherun1 <https://github.com/killerontherun1> that would be
> awesome, please let me know if you need any help with anything 👍
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <https://github.com/opsdroid/opsdroid/issues/532?email_source=notifications&email_token=AF2JNPBQZIS5V5VSUCD3VQTP5CCIXA5CNFSM4E5KIMWKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGODY4JK2A#issuecomment-507024744>,
> or mute the thread
> <https://github.com/notifications/unsubscribe-auth/AF2JNPABO7T6TRR6PFHRN7LP5CCIXANCNFSM4E5KIMWA>
> .
>
Yeah you can have a look at this link: [Example of Google style docstrings](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html), you can also have a look at the following methods that have been updated with the docstrings:
- Core:
- setup_skills
- send
- Memory.py
And there are a few other places, these should provide you some help. Let me know if you need further help
Sorry, I'm a bit of a noob. But do you want me to rewrite the docstrings itself? Or just adjust the follow the syntax in the given link?
Hi I'd like to help out with this as well! I can try to check out the `matchers.py `file if no one else is working on that.
Hello @profwacko that would be great let me know if you need any help 👍
Hi!
I am a beginner of this project, but I will participate because I can contribute easily.
It may be a really small PR...
Sounds great @pluse09! We look forward to reviewing it.
The URL to Sphinx example in the first comment is broken, it has an extra "l" in ".html"
I'd commented on other issues that I'd tackle on them but people already started to do some part of it, so I'll let for them. So, I'll try to document some of the missing files in the list above, respecting what @pluse09 already started doing at #1087.
I'd like to try my hand at adding docstrings to the `core.py` file and its pending methods, if it's not assigned to anyone else already!
Please go ahead
Hi, may I look into `loaders.py`, there are couple of methods that need Google style docstrings
Hello @suparnasnair thank you for the message, that would be great. Please let me know if you need any help with anything 😄👍
I have updated for 2 methods for a start. Sorry I'm a newbie. Please let me know if this is fine, I can go ahead with the remaining ones and clean them up. Thanks !
@FabioRosado there are couple of methods left in loader.py(envvar_constructor, include_constructor), can I take them up if no one else is working on them?
@suparnasnair your PR was great. Welcome to open source! Please feel free to do more.
@p0larstern please go ahead.
@FabioRosado did you mean to close this?
Ooops I didn't notice that the PR that I've merged would close the issue. I've reopened it haha
Hi, I'm new to open source. Can I help out with adding docstrings in `main.py` if noone else is working on it?
@lkcbharath please go ahead
Hi @FabioRosado would there be a quick way for me to understand the functionality of each of the functions I'm writing docstrings for (in `matchers.py`)? Or maybe sort of bump me into the best direction for that.
I'd say reading the matchers documentation might give you a better understanding of what each of them do. But basically matchers are decorators that you use to match a skill(python function) to an intent obtained from a parser.
For example on the dialogflow - the parser will call the API and send over the message from the user, then the API does its thing and returns a response which might contain an intent and other entities.
In dialogflow there is an intent called - `smalltalk.greetings` so you use the `@match_dialogflow_intent('smalltalk.greetings')` to trigger a skill. The matchers basically make that bridge between parsing a message and getting a result and then match a skill with said intent.
You can check the example on the [dialogflow documentation](https://docs.opsdroid.dev/en/stable/matchers/dialogflow/) for more information.
I hope this made sense?
Hi @FabioRosado!
I'm looking to help out on this as well. Looks like the checklist may be out of date now? - I see there was a merge for the CORE section but still some outstanding checkboxes. Can you confirm if the checklist is up to date? I'd love to try and tackle any stragglers.
Hello paqman unfortunately the checklist has been out of date for a while and I haven't have the time to fix it yet. It would be great if you could tackle some of them, Im off in 5 days so I'll try to update the list, you can wait until then or check each file and see if any is left without the google style docstrings - I know there is still a lot of them that don't have it | 2019-10-22T19:39:58 |
|
opsdroid/opsdroid | 1,220 | opsdroid__opsdroid-1220 | [
"1217"
] | 120ecc05e0eb5414510f9f8270ea9c3b0c6e6f11 | diff --git a/opsdroid/connector/slack/__init__.py b/opsdroid/connector/slack/__init__.py
--- a/opsdroid/connector/slack/__init__.py
+++ b/opsdroid/connector/slack/__init__.py
@@ -90,6 +90,10 @@ async def process_message(self, **payload):
"""Process a raw message and pass it to the parser."""
message = payload["data"]
+ # Ignore message edits
+ if "subtype" in message and message["subtype"] == "message_changed":
+ return
+
# Ignore own messages
if (
"subtype" in message
| diff --git a/tests/test_connector_slack.py b/tests/test_connector_slack.py
--- a/tests/test_connector_slack.py
+++ b/tests/test_connector_slack.py
@@ -129,6 +129,12 @@ async def test_process_message(self):
del message["subtype"]
connector.bot_id = None
+ connector.opsdroid.parse.reset_mock()
+ message["subtype"] = "message_changed"
+ await connector.process_message(data=message)
+ self.assertFalse(connector.opsdroid.parse.called)
+ del message["subtype"]
+
connector.opsdroid.parse.reset_mock()
connector.lookup_username.side_effect = ValueError
await connector.process_message(data=message)
@@ -181,7 +187,7 @@ async def test_react(self):
connector = ConnectorSlack({"api-token": "abc123"})
connector.slack.api_call = amock.CoroutineMock()
prev_message = Message("test", "user", "room", connector, raw_event={"ts": 0})
- with OpsDroid() as opsdroid:
+ with OpsDroid():
await prev_message.respond(Reaction("😀"))
self.assertTrue(connector.slack.api_call)
self.assertEqual(
@@ -196,7 +202,7 @@ async def test_react_invalid_name(self):
side_effect=slack.errors.SlackApiError("invalid_name", "invalid_name")
)
prev_message = Message("test", "user", "room", connector, raw_event={"ts": 0})
- with OpsDroid() as opsdroid:
+ with OpsDroid():
await prev_message.respond(Reaction("😀"))
self.assertLogs("_LOGGER", "warning")
@@ -207,7 +213,7 @@ async def test_react_unknown_error(self):
connector.slack.api_call = amock.CoroutineMock(
side_effect=slack.errors.SlackApiError("unknown", "unknown")
)
- with self.assertRaises(slack.errors.SlackApiError), OpsDroid() as opsdroid:
+ with self.assertRaises(slack.errors.SlackApiError), OpsDroid():
prev_message = Message(
"test", "user", "room", connector, raw_event={"ts": 0}
)
| Slack connector crashes after running dance several times
# Description
Slack connector crashes after running dance several times in a row
## Steps to Reproduce
Launch opsdroid with slack connector configured with bot token
go the channel connected in and run dance 3+ times in a row
## Expected Functionality
Opsdroid keeps running fine
## Experienced Functionality
Opsdroid crashes with the following error:
```
ERROR slack.rtm.client: When calling '#process_message()' in the 'opsdroid.connector.slack' module the following error was raised: 'user'
Traceback (most recent call last):
File "C:\Users\koe4945\desktop\git\personal\ops\venv\Scripts\opsdroid-script.py", line 11, in <module>
load_entry_point('opsdroid', 'console_scripts', 'opsdroid')()
File "c:\users\koe4945\desktop\git\personal\ops\venv\lib\site-packages\click\core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "c:\users\koe4945\desktop\git\personal\ops\venv\lib\site-packages\click\core.py", line 717, in main
rv = self.invoke(ctx)
File "c:\users\koe4945\desktop\git\personal\ops\venv\lib\site-packages\click\core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\koe4945\desktop\git\personal\ops\venv\lib\site-packages\click\core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\koe4945\desktop\git\personal\ops\venv\lib\site-packages\click\core.py", line 555, in invoke
return callback(*args, **kwargs)
File "c:\users\koe4945\desktop\git\personal\ops\opsdroid\opsdroid\cli\start.py", line 31, in start
opsdroid.run()
File "c:\users\koe4945\desktop\git\personal\ops\opsdroid\opsdroid\core.py", line 161, in run
self.eventloop.run_until_complete(asyncio.gather(*pending))
File "C:\Users\koe4945\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 584, in run_until_complete
return future.result()
File "c:\users\koe4945\desktop\git\personal\ops\python-slackclient\slack\rtm\client.py", line 339, in _connect_and_read
await self._read_messages()
File "c:\users\koe4945\desktop\git\personal\ops\python-slackclient\slack\rtm\client.py", line 390, in _read_messages
await self._dispatch_event(event, data=payload)
File "c:\users\koe4945\desktop\git\personal\ops\python-slackclient\slack\rtm\client.py", line 437, in _dispatch_event
rtm_client=self, web_client=self._web_client, data=data
File "c:\users\koe4945\desktop\git\personal\ops\opsdroid\opsdroid\connector\slack\__init__.py", line 104, in process_message
user_info = await self.lookup_username(message["user"])
KeyError: 'user'
ERROR: Unhandled exception in opsdroid, exiting...
```
## Versions
- **Opsdroid version:** v0.16.0+62.g620590f
- **Python version:** 3.7.3
- **OS/Docker version:** Windows 10
## Configuration File
Please include your version of the configuration file below.
```yaml
connectors:
- name: slack
# required
api-token: "[...bot token...]"
```
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
| 2019-10-30T09:21:42 |
|
opsdroid/opsdroid | 1,228 | opsdroid__opsdroid-1228 | [
"532"
] | ebbe5488f09e833f37c97f94357582b2ddb2d26e | diff --git a/opsdroid/matchers.py b/opsdroid/matchers.py
--- a/opsdroid/matchers.py
+++ b/opsdroid/matchers.py
@@ -151,7 +151,17 @@ def matcher(func):
def match_luisai_intent(intent):
- """Return luisai intent match decorator."""
+ """Return luis.ai intent match decorator.
+
+ Decorator that calls a function on specific luis.ai intents.
+
+ Args:
+ intent (str): luis.ai intent name
+
+ Returns:
+ Decorated Function
+
+ """
def matcher(func):
"""Add decorated function to skills list for luisai matching."""
@@ -163,7 +173,17 @@ def matcher(func):
def match_rasanlu(intent):
- """Return Rasa NLU intent match decorator."""
+ """Return Rasa NLU intent match decorator.
+
+ Decorator that calls a function on specific Rasa NLU intents.
+
+ Args:
+ intent (str): Rasa NLU intent name
+
+ Returns:
+ Decorated Function
+
+ """
def matcher(func):
"""Add decorated function to skills list for Rasa NLU matching."""
@@ -175,7 +195,17 @@ def matcher(func):
def match_recastai(intent):
- """Return recastai intent match decorator."""
+ """Return Recast.ai intent match decorator.
+
+ Decorator that calls a function on specific Recast.ai intents.
+
+ Args:
+ intent (str): Recast.ai intent name
+
+ Returns:
+ Decorated Function
+
+ """
def matcher(func):
"""Add decorated function to skills list for recastai matching."""
@@ -194,7 +224,17 @@ def matcher(func):
def match_sapcai(intent):
- """Return SAP Conversational AI intent match decorator."""
+ """Return SAP Conversational AI intent match decorator.
+
+ Decorator that calls a function on specific SAP Conversational AI intents.
+
+ Args:
+ intent (str): SAP Conversational AI intent name
+
+ Returns:
+ Decorated Function
+
+ """
def matcher(func):
"""Add decorated function to skills list for SAPCAI matching."""
@@ -206,7 +246,17 @@ def matcher(func):
def match_watson(intent):
- """Return watson intent match decorator."""
+ """Return IBM Watson intent match decorator.
+
+ Decorator that calls a function on specific IBM Watson intents.
+
+ Args:
+ intent (str): IBM Watson intent name
+
+ Returns:
+ Decorated Function
+
+ """
def matcher(func):
"""Add decorated function to skills list for watson matching."""
@@ -218,7 +268,17 @@ def matcher(func):
def match_witai(intent):
- """Return witai intent match decorator."""
+ """Return wit.ai intent match decorator.
+
+ Decorator that calls a function on specific wit.ai intents.
+
+ Args:
+ intent (str): wit.ai intent name
+
+ Returns:
+ Decorated Function
+
+ """
def matcher(func):
"""Add decorated function to skills list for witai matching."""
| Add Google Style Docstrings
We should implement Google Style Docstrings to every function, method, class in opsdroid. This style will support existing documentation and will help in the future by generating documentation automatically.
This consists in a bit of effort so this issue can be worked by more than one contributor, just make sure that everyone knows what you are working on in order to avoid other contributors spending time on something that you are working on.
If you are unfamiliar with the Google Style Docstrings I'd recommend that you check these resources:
- [Sphix 1.8.0+ - Google Style Docstrings](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html)
Docstrings that need to be updated:
- main.py
- [x] configure_lang
- [ ] configure_log
- [ ] get_logging_level
- [ ] check_dependencies
- [ ] print_version
- [ ] print_example_config
- [ ] edit_files
- [x] welcome_message
- ~~helper.py~~
- [x] get_opsdroid
- [x] del_rw
- [x] move_config_to_appdir
- memory.py
- [x] Memory
- [x] get
- [x] put
- [x] _get_from_database
- [x] _put_to_database
- message.py
- [x] Message
- [x] __init__
- [x] _thinking_delay
- [x] _typing delay
- [x] respond
- [x] react
- web.py
- [ ] Web
- [x] get_port
- [x] get_host
- [x] get_ssl_context
- [ ] start
- [ ] build_response
- [ ] web_index_handler
- [ ] web_stats_handler
- matchers.py
- [ ] match_regex
- [ ] match_apiai_action
- [ ] match_apiai_intent
- [ ] match_dialogflow_action
- [ ] match_dialogflow_intent
- [ ] match_luisai_intent
- [ ] match_rasanlu
- [ ] match_recastai
- [ ] match_witai
- [ ] match_crontab
- [ ] match_webhook
- [ ] match_always
- core.py
- [ ] OpsDroid
- [ ] default_connector
- [ ] exit
- [ ] critical
- [ ] call_stop
- [ ] disconnect
- [ ] stop
- [ ] load
- [ ] start_loop
- [x] setup_skills
- [ ] train_parsers
- [ ] start_connector_tasks
- [ ] start_database
- [ ] run_skill
- [ ] get_ranked_skills
- [ ] parse
- loader.py
- [ ] Loader
- [x] import_module_from_spec
- [x] import_module
- [x] check_cache
- [x] build_module_import_path
- [x] build_module_install_path
- [x] git_clone
- [x] git_pull
- [x] pip_install_deps
- [x] create_default_config
- [x] load_config_file
- [ ] envvar_constructor
- [ ] include_constructor
- [x] setup_modules_directory
- [x] load_modules_from_config
- [x] _load_modules
- [x] _install_module
- [x] _update_module
- [ ] _install_git_module
- [x] _install_local_module
---- ORIGINAL POST ----
I've been wondering about this for a while now and I would like to know if we should replace/update all the docstrings in opsdroid with the Google Style doc strings.
I think this could help new and old contributors to contribute and commit to opsdroid since the Google Style docstrings give more information about every method/function and specifies clearly what sort of input the function/method expects, what will it return and what will be raised (if applicable).
The downsize of this style is that the length of every .py file will increase due to the doc strings, but since most IDE's allow you to hide those fields it shouldn't be too bad.
Here is a good example of Google Style Doc strings: [Sphix 1.8.0+ - Google Style Docstrings](http://www.sphinx-doc.org/en/master/ext/example_google.html)
I would like to know what you all think about this idea and if its worth spending time on it.
| Yes we should definitely do this!
It can also be really useful for automatically generating reference documentation.
Awesome I'll wait a few days to see if anyone is opposed to this idea or if they would like to give some advice/comment on the issue.
If in a few days no one says anything I'll edit this issue just to explain more in depth what we expect of the comments and how to do it - I'd recommend dividing opsdroid per each .py file so different people can contribute to the issue 😄
I like the idea. Is it possible to add a test that inspects the doc strings, and fails if they don't match the format? If so, would Jacob be happy with test coverage "reducing" in the short term as this test was added, but before all the doc strings complied?
On 29 April 2018 2:42:05 am AEST, "Fábio Rosado" <[email protected]> wrote:
>Awesome I'll wait a few days to see if anyone is opposed to this idea
>or if they would like to give some advice/comment on the issue.
>
>If in a few days no one says anything I'll edit this issue just to
>explain more in depth what we expect of the comments and how to do it -
>I'd recommend dividing opsdroid per each .py file so different people
>can contribute to the issue 😄
>
>--
>You are receiving this because you are subscribed to this thread.
>Reply to this email directly or view it on GitHub:
>https://github.com/opsdroid/opsdroid/issues/532#issuecomment-385189370
--
Sent from my Android device with K-9 Mail. Please excuse my brevity.
Yes I'm happy with that approach.
I've been thinking about it and I think there are two reasons why anyone would want to do this. The first is for autogenerating documentation, the second is making it easier for people to contribute.
As you said you are intending this to help people contribute, and I definitely agree. I just want to be clear on why we are doing this beyond it just being a thing that some projects do.
We currently run `pydocstyle` as part of the lint suite. I wonder if there is a way of telling it to enforce this docstring style?
I'm not sure if it's possible to enforce google doc style in the lint, but I know that you can run tests on the docstrings like @go8ose suggested, Sphinx has a command for this (it uses the doctest module), but this tests might provide some issues and headaches.
The doctests will use the string representation present in the docstring to run the tests, if the result is not consistent like... a function that deals with dates for example and uses date.now() this test will always fail.
Another example would be running doctests with dictionaries, these tests will mostly fail due to the unsorted nature of dicts, the only way to make them pass would be to sort the dict all the time.
One way to work around it would be to just test some docstrings and not others. In Sphinx you can just add the command:
```
..doctest::
>>> foo()
bar
```
Finally, I believe that all the tests that we have at the moment do a very good job at testing every single piece of code in opsdroid so perhaps adding the doctests would be extra effort for no real gain - these will test what it's being tested already.
--EDIT--
I've updated my first post with all the functions,classes and methods that need to be updated, let me know if you need some added in or removed 👍
Hi Fabio,
I'm not suggesting we add more tests in the form of doctests. That would indeed be a waste of effort. I'm suggesting we check conformance with the google style doc strings.
Jacob suggested seeing if this can be checked in the linting run. That is a good idea, linting is what I should have suggested initially.
Cheers,
Geoff
On 30 April 2018 5:51:38 pm AEST, "Fábio Rosado" <[email protected]> wrote:
>I'm not sure if it's possible to enforce google doc style in the lint,
>but I know that you can run tests on the docstrings like @go8ose
>suggested, Sphinx has a command for this (it uses the doctest module),
>but this tests might provide some issues and headaches.
>
>The doctests will use the string representation present in the
>docstring to run the tests, if the result is not consistent like... a
>function that deals with dates for example and uses date.now() this
>test will always fail.
>Another example would be running doctests with dictionaries, these
>tests will mostly fail due to the unsorted nature of dicts, the only
>way to make them pass would be to sort the dict all the time.
>
>One way to work around it would be to just test some docstrings and not
>others. In Sphinx you can just add the command:
>
>``` ..doctest::
>>>> foo()
>bar
>```
>
>Finally, I believe that all the tests that we have at the moment do a
>very good job at testing every single piece of code in opsdroid so
>perhaps adding the doctests would be extra effort for no real gain -
>these will test what it's being tested already.
>
>--
>You are receiving this because you were mentioned.
>Reply to this email directly or view it on GitHub:
>https://github.com/opsdroid/opsdroid/issues/532#issuecomment-385332374
--
Sent from my Android device with K-9 Mail. Please excuse my brevity.
This tool looks like it tests the docstrings against the google convention. We should explore it more.
https://github.com/terrencepreilly/darglint
Hi Fabio,
I like your idea, i new here on this project i can try to do something and make a pull request.
For my part i'm going to begin with **helper.py** it's Thk ok for you ?
Thk best regards
Heya @sims34 yeah that would be much appreciated, let me know in gitter if you need any help with this 👍
Hi Fabio,
I am new here on this project. I was hoping I could help out with main.py
Regards
Hey @purvaudai, please go ahead!
Hello @purvaudai did you manage to work on `main.py`? If you are stuck with something let us know, we would be happy to help you getting started 👍
Hi Guys is anyone working on this issue
@mraza007 not currently. Please go ahead.
Sure I will start working on this issue. Is there a way that you can assign this issue to me and on what files do I have to add google style doc string functions
Sorry for the lack of replies from my side. I tried solving this issue but
got confused, so I decided to look through the docs again, and I got
carried away learning. I am sorry for the lack of professionalism from my
side.
On Mon, 25 Jun 2018 at 19:33, Muhammad <[email protected]> wrote:
> Sure I will start working on this issue. Is there a way that you can
> assign this issue to me and on what files do I have to add google style doc
> string functions
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <https://github.com/opsdroid/opsdroid/issues/532#issuecomment-399963131>,
> or mute the thread
> <https://github.com/notifications/unsubscribe-auth/AeXNt1F1hUU9JhsW2bl75KQG7SRQEceRks5uAO2_gaJpZM4TqkMs>
> .
>
--
Purva Udai Singh
@purvaudai Hey are working on this issue do you want to continue
Hi guys I'd love to contribute too.
@mraza007 @purvaudai I know you guys are working on this, but if you need my help with any of the file, I'll be more than happy to contribute.
@mraza007 @purvaudai @NikhilRaverkar Thanks for all wanting to contribute! There is a lot to be done on this issue so I strongly recommend picking a file and starting work on it.
Don't worry too much about duplicates, it's unlikely to happen given the number of methods that need updating. I would also be happy for you to submit lots of small PRs. Just pick a few methods, update the docstrings and raise a PR.
Yup I think that would be a great idea
@purvaudai Don't worry my friend sometimes these things happen, if you want to contribute to opsdroid in the future we will be glad to help you 👍
@mraza007 @NikhilRaverkar If you guys need any help, let us know. You can work on different files if you want and if something is not clear feel free to hit us up either in here or our [gitter channel](https://gitter.im/opsdroid/developers)
Sure I just joined the channel I will start working on this over the weekend
I’ll start working on this over the weekend.
Thanks a lot,
Nikhil
> On Jun 28, 2018, at 10:44 AM, Muhammad <[email protected]> wrote:
>
> Sure I just joined the channel I will start working on this over the week
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub, or mute the thread.
I would like to contribute to this. For starters I was thinking about taking the web.py file. :smile:
Hello, please go ahead and let us know if you need any help
@FabioRosado Can I grab message.py? This would be my first issue!
@archime please go ahead! Let me know if you need any help with this issue. Also, welcome to the project 👍
Hey, I'd like to add couple of docstrings, however I've got a question first.
The Google style guide in the description seems to be deprecated.
Should I reference this one https://github.com/google/styleguide/blob/gh-pages/pyguide.md instead?
Hello @kritokrator Thanks for showing interest in this matter.
The sphinx documentation has an up to date style. We are not using typehints in our codebase yet so we will be specifying the type as:
```
Args:
arg1 (String): This arg does things
arg2 (Boolean, optional): This arg can be true, its optional
```
This is a very brief explanation but should get you started, I also recommend you check the [Facebook Connector](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/connector/facebook/__init__.py) as an example of how we would like the doc strings 👍
Hey @FabioRosado, I would like to add docstrings to web.py. The link above no longer works so is this the format you are looking for?
https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
Looking forward to this as this is my first issue!
Hello @GrugLife you are right that is the style we intent to implement in opsdroid. We would be glad to have you contribute to the project let me know if you need any help 😀👍
Hi @FabioRosado, I would like to help on this and would like to start on main.py - this is my first time using github so I'm not entirely sure how to proceed - but I'm sure I'll figure it out. Looking forward to working with you.
Hello @empathic-geek thank you so much for reaching out and working on this issue 😄 Please do let me know if you encounter any issue setting up your development environment or if you have any questions at all!
You can reach me on the [opsdroid chat](https://gitter.im/opsdroid/developers) or any other social networks 😄 👍
I've create pull request for some docstring update :)
Hi @FabioRosado, I would like to start on loader.py.
Hello @WillHensel that would be awesome, feel free to start a PR and let us know if you need any help 👍
Hi @FabioRosado, I would like to take a crack at matchers.py. This will be my first time contributing to a project so I'll ask for your patience :smiley:
Hello Xavier welcome! It would be great if you could work on that and it will help us a lot moving forward to a more consistent code base!
If you do need any help please let us know 😄
Hey @FabioRosado, taking up core.py. Raising multiple small PRs as suggested by @jacobtomlinson.
> Don't worry too much about duplicates, it's unlikely to happen given the number of methods that need updating. I would also be happy for you to submit lots of small PRs. Just pick a few methods, update the docstrings and raise a PR.
Hello @killerontherun1 that would be awesome, please let me know if you need any help with anything 👍
Hey Fabio, do you have a doctest written? So that one can check whether the
docstrings are fine or not?
On Sun, 30 Jun, 2019, 3:51 PM Fábio Rosado, <[email protected]>
wrote:
> Hello @killerontherun1 <https://github.com/killerontherun1> that would be
> awesome, please let me know if you need any help with anything 👍
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <https://github.com/opsdroid/opsdroid/issues/532?email_source=notifications&email_token=AF2JNPBQZIS5V5VSUCD3VQTP5CCIXA5CNFSM4E5KIMWKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGODY4JK2A#issuecomment-507024744>,
> or mute the thread
> <https://github.com/notifications/unsubscribe-auth/AF2JNPABO7T6TRR6PFHRN7LP5CCIXANCNFSM4E5KIMWA>
> .
>
Yeah you can have a look at this link: [Example of Google style docstrings](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html), you can also have a look at the following methods that have been updated with the docstrings:
- Core:
- setup_skills
- send
- Memory.py
And there are a few other places, these should provide you some help. Let me know if you need further help
Sorry, I'm a bit of a noob. But do you want me to rewrite the docstrings itself? Or just adjust the follow the syntax in the given link?
Hi I'd like to help out with this as well! I can try to check out the `matchers.py `file if no one else is working on that.
Hello @profwacko that would be great let me know if you need any help 👍
Hi!
I am a beginner of this project, but I will participate because I can contribute easily.
It may be a really small PR...
Sounds great @pluse09! We look forward to reviewing it.
The URL to Sphinx example in the first comment is broken, it has an extra "l" in ".html"
I'd commented on other issues that I'd tackle on them but people already started to do some part of it, so I'll let for them. So, I'll try to document some of the missing files in the list above, respecting what @pluse09 already started doing at #1087.
I'd like to try my hand at adding docstrings to the `core.py` file and its pending methods, if it's not assigned to anyone else already!
Please go ahead
Hi, may I look into `loaders.py`, there are couple of methods that need Google style docstrings
Hello @suparnasnair thank you for the message, that would be great. Please let me know if you need any help with anything 😄👍
I have updated for 2 methods for a start. Sorry I'm a newbie. Please let me know if this is fine, I can go ahead with the remaining ones and clean them up. Thanks !
@FabioRosado there are couple of methods left in loader.py(envvar_constructor, include_constructor), can I take them up if no one else is working on them?
@suparnasnair your PR was great. Welcome to open source! Please feel free to do more.
@p0larstern please go ahead.
@FabioRosado did you mean to close this?
Ooops I didn't notice that the PR that I've merged would close the issue. I've reopened it haha
Hi, I'm new to open source. Can I help out with adding docstrings in `main.py` if noone else is working on it?
@lkcbharath please go ahead
Hi @FabioRosado would there be a quick way for me to understand the functionality of each of the functions I'm writing docstrings for (in `matchers.py`)? Or maybe sort of bump me into the best direction for that.
I'd say reading the matchers documentation might give you a better understanding of what each of them do. But basically matchers are decorators that you use to match a skill(python function) to an intent obtained from a parser.
For example on the dialogflow - the parser will call the API and send over the message from the user, then the API does its thing and returns a response which might contain an intent and other entities.
In dialogflow there is an intent called - `smalltalk.greetings` so you use the `@match_dialogflow_intent('smalltalk.greetings')` to trigger a skill. The matchers basically make that bridge between parsing a message and getting a result and then match a skill with said intent.
You can check the example on the [dialogflow documentation](https://docs.opsdroid.dev/en/stable/matchers/dialogflow/) for more information.
I hope this made sense?
Hi @FabioRosado!
I'm looking to help out on this as well. Looks like the checklist may be out of date now? - I see there was a merge for the CORE section but still some outstanding checkboxes. Can you confirm if the checklist is up to date? I'd love to try and tackle any stragglers.
Hello paqman unfortunately the checklist has been out of date for a while and I haven't have the time to fix it yet. It would be great if you could tackle some of them, Im off in 5 days so I'll try to update the list, you can wait until then or check each file and see if any is left without the google style docstrings - I know there is still a lot of them that don't have it
Hi @FabioRosado, thanks for the tips. It's definitely more clear now. The checklist for `matchers.py` seems to be lacking a few more functions, namely:
- [ ] match_event
- [ ] match_parse
- [ ] match_sapcai
- [ ] match_watson
Also the following functions don't seem to be there anymore, i'm guessing they are now the dialogflow api ones?
- [ ] ~match_apiai_action~
- [ ] ~match_apiai_intent~
I'll fix up the docstrings for these as a starting point:
- [ ] match_event
- [ ] match_regex
- [ ] match_parse
Yeah you were right the api ai matcher has now become dialogflow - i think I added the google style on them when i updated the version not sure though.
Those new ones aren't there because they were added after I created this issue, which reminds me that I forgot to update the list 👍
@FabioRosado I hope my pull request is okay for the first few changes I did, please let me know if there's anything I can do to make the pull request better! I am also doing this for hacktoberfest 😄
I'll claim a few more docstrings for matchers.py, i'll be doing the `diaglogflow`, `crontab`, `webhook` and `always` docstrings.
Here's the updated checklist for that:
- [x] match_regex
- [ ] ~match_apiai_action~
- [ ] ~match_apiai_intent~
- [ ] match_dialogflow_action
- [ ] match_dialogflow_intent
- [ ] match_luisai_intent
- [ ] match_rasanlu
- [ ] match_recastai
- [ ] match_witai
- [ ] match_crontab
- [ ] match_webhook
- [ ] match_always
- [x] match_event
- [x] match_parse
- [ ] match_sapcai
- [ ] match_watson | 2019-10-31T14:45:02 |
|
opsdroid/opsdroid | 1,233 | opsdroid__opsdroid-1233 | [
"1232"
] | 5cc5465bafa30b03663b4dd16c6d31f1e78007ac | diff --git a/opsdroid/connector/slack/__init__.py b/opsdroid/connector/slack/__init__.py
--- a/opsdroid/connector/slack/__init__.py
+++ b/opsdroid/connector/slack/__init__.py
@@ -1,6 +1,8 @@
"""A connector for Slack."""
import logging
import re
+import ssl
+import certifi
import slack
from emoji import demojize
@@ -25,8 +27,13 @@ def __init__(self, config, opsdroid=None):
self.icon_emoji = config.get("icon-emoji", ":robot_face:")
self.token = config["api-token"]
self.timeout = config.get("connect-timeout", 10)
- self.slack = slack.WebClient(token=self.token, run_async=True)
- self.slack_rtm = slack.RTMClient(token=self.token, run_async=True)
+ self.ssl_context = ssl.create_default_context(cafile=certifi.where())
+ self.slack = slack.WebClient(
+ token=self.token, run_async=True, ssl=self.ssl_context
+ )
+ self.slack_rtm = slack.RTMClient(
+ token=self.token, run_async=True, ssl=self.ssl_context
+ )
self.websocket = None
self.bot_name = config.get("bot-name", "opsdroid")
self.auth_info = None
| ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed in Slack Connector
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://riot.im/app/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
I am trying to build a Slack bot using Opsdroid (master branch). When running `opsdroid start`, I get an error where the Opsdroid bot fails to connect with the Slack Workspace.
## Steps to Reproduce
1. Install opsdroid
```
pip install git+https://github.com/opsdroid/opsdroid.git
```
2. Create `configuration.yaml` with following content
```
welcome-message: true
connectors:
- name: slack
api-token: "<Bot OAuth Token>"
skills:
- name: hello
```
3. Start opsdroid
```
opsdroid start
```
## Expected Functionality
The expected functionality is for the Opsdroid Bot to get connected with Slack Workspace and interact with the Slack user as per the configured skill.
## Experienced Functionality
The Opsdroid Bot failed to connect with the Slack Workspace with the following error:
```
INFO opsdroid.connector.slack: Connecting to Slack
Traceback (most recent call last):
File "/home/daniccan/c8/OpsDroid/c8-alertbot/env/lib/python3.6/site-packages/aiohttp/connector.py", line 936, in _wrap_create_connection
return await self._loop.create_connection(*args, **kwargs) # type: ignore # noqa
File "/usr/lib/python3.6/asyncio/base_events.py", line 820, in create_connection
sock, protocol_factory, ssl, server_hostname)
File "/usr/lib/python3.6/asyncio/base_events.py", line 846, in _create_connection_transport
yield from waiter
File "/usr/lib/python3.6/asyncio/sslproto.py", line 505, in data_received
ssldata, appdata = self._sslpipe.feed_ssldata(data)
File "/usr/lib/python3.6/asyncio/sslproto.py", line 201, in feed_ssldata
self._sslobj.do_handshake()
File "/usr/lib/python3.6/ssl.py", line 689, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/daniccan/c8/OpsDroid/c8-alertbot/env/lib/python3.6/site-packages/opsdroid/connector/slack/__init__.py", line 55, in connect
self.auth_info = (await self.slack.api_call("auth.test")).data
File "/home/daniccan/c8/OpsDroid/c8-alertbot/env/lib/python3.6/site-packages/slack/web/base_client.py", line 229, in _send
http_verb=http_verb, api_url=api_url, req_args=req_args
File "/home/daniccan/c8/OpsDroid/c8-alertbot/env/lib/python3.6/site-packages/slack/web/base_client.py", line 259, in _request
async with session.request(http_verb, api_url, **req_args) as res:
File "/home/daniccan/c8/OpsDroid/c8-alertbot/env/lib/python3.6/site-packages/aiohttp/client.py", line 1012, in __aenter__
self._resp = await self._coro
File "/home/daniccan/c8/OpsDroid/c8-alertbot/env/lib/python3.6/site-packages/aiohttp/client.py", line 483, in _request
timeout=real_timeout
File "/home/daniccan/c8/OpsDroid/c8-alertbot/env/lib/python3.6/site-packages/aiohttp/connector.py", line 523, in connect
proto = await self._create_connection(req, traces, timeout)
File "/home/daniccan/c8/OpsDroid/c8-alertbot/env/lib/python3.6/site-packages/aiohttp/connector.py", line 859, in _create_connection
req, traces, timeout)
File "/home/daniccan/c8/OpsDroid/c8-alertbot/env/lib/python3.6/site-packages/aiohttp/connector.py", line 1004, in _create_direct_connection
raise last_exc
File "/home/daniccan/c8/OpsDroid/c8-alertbot/env/lib/python3.6/site-packages/aiohttp/connector.py", line 986, in _create_direct_connection
req=req, client_error=client_error)
File "/home/daniccan/c8/OpsDroid/c8-alertbot/env/lib/python3.6/site-packages/aiohttp/connector.py", line 941, in _wrap_create_connection
raise ClientConnectorSSLError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorSSLError: Cannot connect to host www.slack.com:443 ssl:default [[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)]
```
## Versions
- **Opsdroid version:** master branch in git
- **Python version:** 3.6.8
- **OS/Docker version:** Ubuntu 18.04 LTS
## Configuration File
Please include your version of the configuration file below.
```yaml
welcome-message: true
connectors:
- name: slack
api-token: "<Bot OAuth Token>"
skills:
- name: hello
```
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| It looks like the SSL certificate for Slack is being rejected. Do you have the certificate bundle installed ([instructions](https://www.techrepublic.com/article/how-to-install-ca-certificates-in-ubuntu-server/))?
How do I get the certificate bundle of Slack?
This looks like an issue with the `websocket-client` library version 0.48.0 and above. FYI, https://github.com/websocket-client/websocket-client/issues/451#issuecomment-417918570. I am unable to lock on to version 0.47.0 of the library due to another dependency.
```
pkg_resources.DistributionNotFound: The 'websocket-client==0.48.0' distribution was not found and is required by ibm-watson
``` | 2019-11-01T11:32:02 |
|
opsdroid/opsdroid | 1,241 | opsdroid__opsdroid-1241 | [
"1239"
] | 674013037eab826640174407a73f8fed1a29b290 | diff --git a/opsdroid/connector/slack/__init__.py b/opsdroid/connector/slack/__init__.py
--- a/opsdroid/connector/slack/__init__.py
+++ b/opsdroid/connector/slack/__init__.py
@@ -87,7 +87,7 @@ async def connect(self):
async def disconnect(self):
"""Disconnect from Slack."""
- await self.slack_rtm.stop()
+ self.slack_rtm.stop()
self.listening = False
async def listen(self):
| Exiting opsdroid with ctrl+c fails with exception
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://riot.im/app/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
I am trying to build a Slack bot using Opsdroid (master branch). When pressing `ctrl+c` to exit opsdroid, the process does not stop and throws an error.
## Steps to Reproduce
1. Start opsdroid and wait for it to run
```
opsdroid start
```
2. Press `ctrl+c` to exit the process
## Expected Functionality
The opsdroid process should exit on pressing `ctrl+c`.
## Experienced Functionality
The opsdroid process fails to exit with an exception. The debug log is as follows:
```
INFO opsdroid.logging: ========================================
INFO opsdroid.logging: Started opsdroid v0.16.0+82.g4c55e97
INFO opsdroid: ========================================
INFO opsdroid: You can customise your opsdroid by modifying your configuration.yaml
INFO opsdroid: Read more at: http://opsdroid.readthedocs.io/#configuration
INFO opsdroid: Watch the Get Started Videos at: http://bit.ly/2fnC0Fh
INFO opsdroid: Install Opsdroid Desktop at:
https://github.com/opsdroid/opsdroid-desktop/releases
INFO opsdroid: ========================================
WARNING opsdroid.loader: No databases in configuration.This will cause skills which store things in memory to lose data when opsdroid is restarted.
INFO opsdroid.connector.slack: Connecting to Slack
INFO opsdroid.connector.slack: Connected successfully
INFO opsdroid.web: Started web server on http://0.0.0.0:8080
INFO opsdroid.core: Opsdroid is now running, press ctrl+c to exit.
^CINFO opsdroid.core: Received stop signal, exiting.
INFO opsdroid.core: Removing skills...
INFO opsdroid.core: Removed hello
INFO opsdroid.core: Removed seen
INFO opsdroid.core: Removed help
INFO opsdroid.core: Stopping connector slack...
ERROR: Unhandled exception in opsdroid, exiting...
Caught exception
{'message': 'Task exception was never retrieved', 'exception': TypeError("object NoneType can't be used in 'await' expression",), 'future': <Task finished coro=<OpsDroid.handle_signal() done, defined at /home/daniccan/c8/OpsDroid/c8-alertbot/env/lib/python3.6/site-packages/opsdroid/core.py:147> exception=TypeError("object NoneType can't be used in 'await' expression",)>}
WARNING slack.rtm.client: Websocket was closed.
```
## Versions
- **Opsdroid version:** master branch in git
- **Python version:** 3.6.8
- **OS/Docker version:** Ubuntu 18.04 LTS
## Configuration File
Please include your version of the configuration file below.
```yaml
# Your code goes here.
welcome-message: true
connectors:
- name: slack
api-token: "<Bot OAuth Token>"
skills:
- name: hello
- name: seen
- name: help
```
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| Ok just reproduced locally. This seems to happen when `slack` is the first connector in the list.
#### Fails to exit
```yaml
connectors:
- name: slack
api-token: "<Bot OAuth Token>"
skills:
- name: hello
```
and
```yaml
connectors:
- name: slack
api-token: "<Bot OAuth Token>"
- name: websocket
skills:
- name: hello
```
#### Successfully exits
```yaml
connectors:
- name: websocket
- name: slack
api-token: "<Bot OAuth Token>"
skills:
- name: hello
```
But with the following errors in the log.
```
...
ERROR: Unhandled exception in opsdroid, exiting...
ERROR: Unhandled exception in opsdroid, exiting...
ERROR: Unhandled exception in opsdroid, exiting...
``` | 2019-11-04T12:20:26 |
|
opsdroid/opsdroid | 1,244 | opsdroid__opsdroid-1244 | [
"654"
] | 644978a15d67ceb0786ec7fe82bfd94db7022326 | diff --git a/opsdroid/loader.py b/opsdroid/loader.py
--- a/opsdroid/loader.py
+++ b/opsdroid/loader.py
@@ -114,8 +114,8 @@ def import_module(config):
_LOGGER.error(_("Failed to load %s: %s"), config["type"], config["module_path"])
return None
- @staticmethod
- def check_cache(config):
+ @classmethod
+ def check_cache(cls, config):
"""Remove module if 'no-cache' set in config.
Args:
@@ -124,10 +124,29 @@ def check_cache(config):
"""
if "no-cache" in config and config["no-cache"]:
_LOGGER.debug(_("'no-cache' set, removing %s"), config["install_path"])
- if os.path.isdir(config["install_path"]):
- shutil.rmtree(config["install_path"])
- if os.path.isfile(config["install_path"] + ".py"):
- os.remove(config["install_path"] + ".py")
+ cls.remove_cache(config)
+
+ if "no-cache" not in config and cls._is_local_module(config):
+ _LOGGER.debug(
+ _(
+ "Removing cache for local module %s, set 'no-cache: false' to disable this."
+ ),
+ config["install_path"],
+ )
+ cls.remove_cache(config)
+
+ @staticmethod
+ def remove_cache(config):
+ """Remove module cache.
+
+ Args:
+ config: dict of config information related to the module
+
+ """
+ if os.path.isdir(config["install_path"]):
+ shutil.rmtree(config["install_path"])
+ if os.path.isfile(config["install_path"] + ".py"):
+ os.remove(config["install_path"] + ".py")
@staticmethod
def is_builtin_module(config):
| diff --git a/tests/test_loader.py b/tests/test_loader.py
--- a/tests/test_loader.py
+++ b/tests/test_loader.py
@@ -298,6 +298,28 @@ def test_loading_intents(self):
self.assertEqual(intent_contents, loaded_intents)
shutil.rmtree(config["install_path"], onerror=del_rw)
+ def test_check_cache_clears_local_by_default(self):
+ config = {}
+ config["path"] = "abc"
+ config["install_path"] = os.path.join(
+ self._tmp_dir, os.path.normpath("test/module")
+ )
+ os.makedirs(config["install_path"], mode=0o777)
+ ld.Loader.check_cache(config)
+ self.assertFalse(os.path.isdir(config["install_path"]))
+
+ def test_check_cache_clear_local_by_default_disabled(self):
+ config = {}
+ config["no-cache"] = False
+ config["path"] = "abc"
+ config["install_path"] = os.path.join(
+ self._tmp_dir, os.path.normpath("test/module")
+ )
+ os.makedirs(config["install_path"], mode=0o777)
+ ld.Loader.check_cache(config)
+ self.assertTrue(os.path.isdir(config["install_path"]))
+ shutil.rmtree(config["install_path"], onerror=del_rw)
+
def test_loading_intents_failed(self):
config = {}
config["no-cache"] = True
| Treat skills with explicit path as local
When defining custom skills in the configuration file, we have the ability to define a path for the skill. When this path is defined, we should be able to safely assume that the skill is local and accessible by the bot and therefore should not need to be cached.
My suggestion is to treat skills which have been explicitly defined with a local path as local skills and automatically apply the `nocache=true` unless caching is otherwise defined in the config.
| I like that idea and it does make sense to have the nocache set to true if the path is available in the config when you are developing the skill.
We need to check with the community if this is something we should implement as well, the reason for that being that some devs are probably using their own skills with opsdroid and perhaps having the nocache set could cause a burden to them when opsdroid is run.
To add some context this issue has come from a chat on Gitter/Matrix. We were saying that for anything specific with `path` should default to `no-cache: true` and anything with `repo` should default to `no-cache: false`. The user is still free to configure in whichever way they like.
My only concern is that this inconsistency may cause confusion. However as the current caching is already causing confusion I think this is probably a better approach.
Ah okay I checked Gitter but is nothing there about this. Are we using matrix more?
The two are bridged so you can use either. We were discussing it in general yesterday, but it might've gotten lost in the noise :).
This just came up again. We really should do this. | 2019-11-06T15:21:02 |
opsdroid/opsdroid | 1,247 | opsdroid__opsdroid-1247 | [
"1246"
] | 3005a0582bc10ba870c2eeb436d810883fdf479b | diff --git a/opsdroid/connector/slack/__init__.py b/opsdroid/connector/slack/__init__.py
--- a/opsdroid/connector/slack/__init__.py
+++ b/opsdroid/connector/slack/__init__.py
@@ -27,6 +27,7 @@ def __init__(self, config, opsdroid=None):
self.icon_emoji = config.get("icon-emoji", ":robot_face:")
self.token = config["api-token"]
self.timeout = config.get("connect-timeout", 10)
+ self.chat_as_user = config.get("chat-as-user", False)
self.ssl_context = ssl.create_default_context(cafile=certifi.where())
self.slack = slack.WebClient(
token=self.token, run_async=True, ssl=self.ssl_context
@@ -141,7 +142,7 @@ async def send_message(self, message):
data={
"channel": message.target,
"text": message.text,
- "as_user": False,
+ "as_user": self.chat_as_user,
"username": self.bot_name,
"icon_emoji": self.icon_emoji,
},
@@ -157,6 +158,7 @@ async def send_blocks(self, blocks):
"chat.postMessage",
data={
"channel": blocks.target,
+ "as_user": self.chat_as_user,
"username": self.bot_name,
"blocks": blocks.blocks,
"icon_emoji": self.icon_emoji,
| Direct messages to Slack Users is sent via Slack Bot instead of the configured Bot User
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://riot.im/app/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
Sending messages directly to Slack Users is sent by the default Slack Bot instead of the configured Bot User.
## Steps to Reproduce
1. Configure Slack Connector in Opsdroid.
2. Send a message to a user instead of a channel by setting the `message.target` value (e.g. @someuser)
## Expected Functionality
The message should be sent to the user via the bot user whose API token we have configured.
## Experienced Functionality
The message is sent to the user via the default Slack Bot.
## Versions
- **Opsdroid version:** master branch in git
- **Python version:** 3.6.8
- **OS/Docker version:** Ubuntu 18.04 LTS
## Configuration File
Please include your version of the configuration file below.
```yaml
# Your code goes here.
welcome-message: true
connectors:
- name: slack
api-token: "<Bot OAuth Token>"
skills:
- name: myskill
path: /path/to/myskill
```
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| 2019-11-07T08:02:20 |
||
opsdroid/opsdroid | 1,251 | opsdroid__opsdroid-1251 | [
"673"
] | 4f961ee251fa52345d3a72d181b6db0a1e895441 | diff --git a/opsdroid/connector/mattermost/__init__.py b/opsdroid/connector/mattermost/__init__.py
new file mode 100644
--- /dev/null
+++ b/opsdroid/connector/mattermost/__init__.py
@@ -0,0 +1,107 @@
+"""A connector for Mattermost."""
+import logging
+import json
+
+from mattermostdriver import Driver, Websocket
+
+from opsdroid.connector import Connector, register_event
+from opsdroid.events import Message
+
+_LOGGER = logging.getLogger(__name__)
+
+
+class ConnectorMattermost(Connector):
+ """A connector for Mattermost."""
+
+ def __init__(self, config, opsdroid=None):
+ """Create the connector."""
+ super().__init__(config, opsdroid=opsdroid)
+ _LOGGER.debug(_("Starting Mattermost connector"))
+ self.name = "mattermost"
+ self.token = config["api-token"]
+ self.url = config["url"]
+ self.team_name = config["team-name"]
+ self.scheme = config.get("scheme", "https")
+ self.port = config.get("port", 8065)
+ self.verify = config.get("ssl-verify", True)
+ self.timeout = config.get("connect-timeout", 30)
+ self.request_timeout = None
+ self.mfa_token = None
+ self.debug = False
+ self.listening = True
+
+ self.mm_driver = Driver(
+ {
+ "url": self.url,
+ "token": self.token,
+ "scheme": self.scheme,
+ "port": self.port,
+ "verify": self.verify,
+ "timeout": self.timeout,
+ "request_timeout": self.request_timeout,
+ "mfa_token": self.mfa_token,
+ "debug": self.debug,
+ }
+ )
+
+ async def connect(self):
+ """Connect to the chat service."""
+ _LOGGER.info(_("Connecting to Mattermost"))
+
+ login_response = self.mm_driver.login()
+
+ _LOGGER.info(login_response)
+
+ if "id" in login_response:
+ self.bot_id = login_response["id"]
+ if "username" in login_response:
+ self.bot_name = login_response["username"]
+
+ _LOGGER.info(_("Connected as %s"), self.bot_name)
+
+ self.mm_driver.websocket = Websocket(
+ self.mm_driver.options, self.mm_driver.client.token
+ )
+
+ _LOGGER.info(_("Connected successfully"))
+
+ async def disconnect(self):
+ """Disconnect from Mattermost."""
+ self.listening = False
+ self.mm_driver.logout()
+
+ async def listen(self):
+ """Listen for and parse new messages."""
+ await self.mm_driver.websocket.connect(self.process_message)
+
+ async def process_message(self, raw_message):
+ """Process a raw message and pass it to the parser."""
+ _LOGGER.info(raw_message)
+
+ message = json.loads(raw_message)
+
+ if "event" in message and message["event"] == "posted":
+ data = message["data"]
+ post = json.loads(data["post"])
+ await self.opsdroid.parse(
+ Message(
+ post["message"],
+ data["sender_name"],
+ data["channel_name"],
+ self,
+ raw_event=message,
+ )
+ )
+
+ @register_event(Message)
+ async def send_message(self, message):
+ """Respond with a message."""
+ _LOGGER.debug(
+ _("Responding with: '%s' in room %s"), message.text, message.target
+ )
+ channel_id = self.mm_driver.channels.get_channel_by_name_and_team_name(
+ self.team_name, message.target
+ )["id"]
+ self.mm_driver.posts.create_post(
+ options={"channel_id": channel_id, "message": message.text}
+ )
| diff --git a/tests/test_connector_mattermost.py b/tests/test_connector_mattermost.py
new file mode 100644
--- /dev/null
+++ b/tests/test_connector_mattermost.py
@@ -0,0 +1,175 @@
+"""Tests for the ConnectorMattermost class."""
+import asyncio
+import json
+
+import unittest
+import unittest.mock as mock
+import asynctest
+import asynctest.mock as amock
+
+from opsdroid.core import OpsDroid
+from opsdroid.connector.mattermost import ConnectorMattermost
+from opsdroid.cli.start import configure_lang
+from opsdroid.events import Message
+
+
+class TestConnectorMattermost(unittest.TestCase):
+ """Test the opsdroid Mattermost connector class."""
+
+ def setUp(self):
+ self.loop = asyncio.new_event_loop()
+ configure_lang({})
+
+ def test_init(self):
+ """Test that the connector is initialised properly."""
+ connector = ConnectorMattermost(
+ {"api-token": "abc123", "url": "localhost", "team-name": "opsdroid"},
+ opsdroid=OpsDroid(),
+ )
+ self.assertEqual("mattermost", connector.name)
+ self.assertEqual(30, connector.timeout)
+
+ def test_missing_api_key(self):
+ """Test that creating without an API key raises an error."""
+ with self.assertRaises(KeyError):
+ ConnectorMattermost({}, opsdroid=OpsDroid())
+
+
+class TestConnectorMattermostAsync(asynctest.TestCase):
+ """Test the async methods of the opsdroid Mattermost connector class."""
+
+ async def setUp(self):
+ configure_lang({})
+
+ async def test_connect(self):
+ connector = ConnectorMattermost(
+ {
+ "api-token": "abc123",
+ "url": "localhost",
+ "team-name": "opsdroid",
+ "scheme": "http",
+ },
+ opsdroid=OpsDroid(),
+ )
+ opsdroid = amock.CoroutineMock()
+ opsdroid.eventloop = self.loop
+ connector.mm_driver.login = mock.MagicMock()
+ connector.mm_driver.login.return_value = {"id": "1", "username": "opsdroid_bot"}
+ await connector.connect()
+ self.assertEqual("1", connector.bot_id)
+ self.assertEqual("opsdroid_bot", connector.bot_name)
+
+ async def test_disconnect(self):
+ connector = ConnectorMattermost(
+ {
+ "api-token": "abc123",
+ "url": "localhost",
+ "team-name": "opsdroid",
+ "scheme": "http",
+ },
+ opsdroid=OpsDroid(),
+ )
+ opsdroid = amock.CoroutineMock()
+ opsdroid.eventloop = self.loop
+ connector.mm_driver.login = mock.MagicMock()
+ connector.mm_driver.login.return_value = {"id": "1", "username": "opsdroid_bot"}
+ connector.mm_driver.logout = mock.MagicMock()
+ await connector.connect()
+ await connector.disconnect()
+ self.assertTrue(connector.mm_driver.logout.called)
+
+ async def test_listen(self):
+ """Test that listening consumes from the socket."""
+ connector = ConnectorMattermost(
+ {
+ "api-token": "abc123",
+ "url": "localhost",
+ "team-name": "opsdroid",
+ "scheme": "http",
+ },
+ opsdroid=OpsDroid(),
+ )
+ connector.mm_driver.websocket = mock.Mock()
+ connector.mm_driver.websocket.connect = amock.CoroutineMock()
+ await connector.listen()
+
+ async def test_process_message(self):
+ """Test processing a mattermost message."""
+ connector = ConnectorMattermost(
+ {
+ "api-token": "abc123",
+ "url": "localhost",
+ "team-name": "opsdroid",
+ "scheme": "http",
+ },
+ opsdroid=OpsDroid(),
+ )
+ connector.opsdroid = amock.CoroutineMock()
+ connector.opsdroid.parse = amock.CoroutineMock()
+
+ post = json.dumps(
+ {
+ "id": "wr9wetwc87bgdcx6opkjaxwb6a",
+ "create_at": 1574001673419,
+ "update_at": 1574001673419,
+ "edit_at": 0,
+ "delete_at": 0,
+ "is_pinned": False,
+ "user_id": "mrtopue9oigr8poa3bgfq4if4a",
+ "channel_id": "hdnm8gbxfp8bmcns7oswmwur4r",
+ "root_id": "",
+ "parent_id": "",
+ "original_id": "",
+ "message": "hello",
+ "type": "",
+ "props": {},
+ "hashtags": "",
+ "pending_post_id": "mrtopue9oigr8poa3bgfq4if4a:1574001673362",
+ "metadata": {},
+ }
+ )
+
+ message = json.dumps(
+ {
+ "event": "posted",
+ "data": {
+ "channel_display_name": "@daniccan",
+ "channel_name": "546qd6zsyffcfcafd77a3kdadr__mrtopue9oigr8poa3bgfq4if4a",
+ "channel_type": "D",
+ "mentions": '["546qd6zsyffcfcafd77a3kdadr"]',
+ "post": post,
+ "sender_name": "@daniccan",
+ "team_id": "",
+ },
+ "broadcast": {
+ "omit_users": "",
+ "user_id": "",
+ "channel_id": "hdnm8gbxfp8bmcns7oswmwur4r",
+ "team_id": "",
+ },
+ "seq": 3,
+ }
+ )
+ await connector.process_message(message)
+ self.assertTrue(connector.opsdroid.parse.called)
+
+ async def test_send_message(self):
+ connector = ConnectorMattermost(
+ {
+ "api-token": "abc123",
+ "url": "localhost",
+ "team-name": "opsdroid",
+ "scheme": "http",
+ },
+ opsdroid=OpsDroid(),
+ )
+ connector.mm_driver = mock.Mock()
+ connector.mm_driver.channels = mock.Mock()
+ connector.mm_driver.channels.get_channel_by_name_and_team_name = (
+ mock.MagicMock()
+ )
+ connector.mm_driver.posts = mock.Mock()
+ connector.mm_driver.posts.create_post = mock.MagicMock()
+ await connector.send(Message("test", "user", "room", connector))
+ self.assertTrue(connector.mm_driver.channels.get_channel_by_name_and_team_name)
+ self.assertTrue(connector.mm_driver.posts.create_post.called)
| Create a Mattermost connector module
Let's add a [Mattermost connector](https://mattermost.com/).
## Steps
- Make a new submodule directory in [`opsdroid.connector`](https://github.com/opsdroid/opsdroid/tree/master/opsdroid/connector) called `mattermost` and create an `__init__.py` file inside.
- Implement the connector according to the [documentation on writing connectors](https://opsdroid.readthedocs.io/en/stable/extending/connectors/).
- Update the [`requirements.txt`](https://github.com/opsdroid/opsdroid/blob/master/requirements.txt) with any new dependencies from the connector if necessary.
- Write tests for the connector. (See the [Slack connector tests](https://github.com/jacobtomlinson/opsdroid/blob/master/tests/test_connector_slack.py) for inspiration).
- Create a [new documentation page](https://github.com/opsdroid/opsdroid/tree/master/docs/connectors).
- Add the new page to the [mkdocs.yml](https://github.com/opsdroid/opsdroid/blob/master/mkdocs.yml).
- Add to the [list of connectors](https://github.com/opsdroid/opsdroid/blob/master/docs/configuration-reference.md#connector-modules).
### Resources to get you started
- [Mattermost API](https://api.mattermost.com/)
- [Asyncio Mattermost Python module](https://pypi.org/project/mattermostdriver-asyncio/)
### Asyncio
Opsdroid uses [asyncio and an event loop](https://docs.python.org/3/library/asyncio.html), so here are some things to bear in mind:
- Functions should be coroutines which are defined with `async def myfunc(): ...`
- Coroutines are called with `await`. For example `await myfunc()`. This is how asyncio allows many functions to take it in turns as they swap over when the current thread calls `await`.
- **Don't block the thread!** If you need to make a call to a blocking function such as `time.sleep()` or any kind of IO request such as `requests.get()` then you should `await` an async variant. For example you can call `await asyncio.sleep(10)` to sleep without blocking the whole application and you can use `aiohttp` as an async url library.
| Hi, @jacobtomlinson can I take this issue?
Hello @leeyjjoel please go ahead and work on the issue and let us know if you need any help while working on it 👍 | 2019-11-11T11:24:46 |
opsdroid/opsdroid | 1,260 | opsdroid__opsdroid-1260 | [
"1259"
] | 1effb60bb3779cd0d33d396e6c0f1b3cc3611b2e | diff --git a/opsdroid/web.py b/opsdroid/web.py
--- a/opsdroid/web.py
+++ b/opsdroid/web.py
@@ -128,6 +128,22 @@ def register_skill(self, opsdroid, skill, webhook):
async def wrapper(req, opsdroid=opsdroid, config=skill.config):
"""Wrap up the aiohttp handler."""
+ webhook_token = self.config.get("webhook-token", None)
+ authorization_header = []
+ if req is not None:
+ authorization_header = req.headers.get("Authorization", "").split()
+
+ if webhook_token is not None:
+ if not (
+ len(authorization_header) == 2
+ and authorization_header[0] == "Bearer"
+ and authorization_header[1] == webhook_token
+ ):
+ _LOGGER.error(
+ _("Unauthorized to run skill %s via webhook"), webhook
+ )
+ return Web.build_response(403, {"called_skill": webhook})
+
_LOGGER.info(_("Running skill %s via webhook"), webhook)
opsdroid.stats["webhooks_called"] = opsdroid.stats["webhooks_called"] + 1
resp = await opsdroid.run_skill(skill, config, req)
| diff --git a/tests/test_matchers.py b/tests/test_matchers.py
--- a/tests/test_matchers.py
+++ b/tests/test_matchers.py
@@ -4,6 +4,8 @@
import asyncio
import aiohttp.web
+from aiohttp.test_utils import make_mocked_request
+
from opsdroid.cli.start import configure_lang
from opsdroid.core import OpsDroid
from opsdroid.web import Web
@@ -143,6 +145,26 @@ async def test_match_webhook_response(self):
webhookresponse = await wrapperfunc(None)
self.assertEqual(type(webhookresponse), aiohttp.web.Response)
+ async def test_match_webhook_response_with_authorization_failure(self):
+ with OpsDroid() as opsdroid:
+ opsdroid.loader.current_import_config = {"name": "testhook"}
+ opsdroid.config["web"] = {"webhook-token": "aabbccddeeff"}
+ opsdroid.web_server = Web(opsdroid)
+ opsdroid.web_server.web_app = mock.Mock()
+ webhook = "test"
+ decorator = matchers.match_webhook(webhook)
+ opsdroid.skills.append(decorator(await self.getMockSkill()))
+ opsdroid.skills[0].config = {"name": "mockedskill"}
+ opsdroid.web_server.setup_webhooks(opsdroid.skills)
+ postcalls, _ = opsdroid.web_server.web_app.router.add_post.call_args_list[0]
+ wrapperfunc = postcalls[1]
+ webhookresponse = await wrapperfunc(
+ make_mocked_request(
+ "POST", postcalls[0], headers={"Authorization": "Bearer wwxxyyzz"}
+ )
+ )
+ self.assertEqual(type(webhookresponse), aiohttp.web.Response)
+
async def test_match_webhook_custom_response(self):
with OpsDroid() as opsdroid:
opsdroid.loader.current_import_config = {"name": "testhook"}
| Token based authentication for Webhook Matcher
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://riot.im/app/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
The webhook matcher allows you to trigger the skill by calling a specific URL endpoint.
Currently, a skill with a webhook matcher would be called if you send a `POST` to `http://localhost:8080/skill/exampleskill/examplewebhook`.
This URL is public and does not have any form of authentication/authorization checks, which means it can be triggered by anyone. Adding an `Authorization` header with a token-based authentication would secure the webhook.
## Steps to Reproduce
1. Create a skill `exampleskill` with a webhook matcher `examplewebhook`.
2. Send a `POST` request to `http://localhost:8080/skill/exampleskill/examplewebhook` to trigger the bot.
## Expected Functionality
1. The webhook should check for the `Authorization` header and perform a token-based authentication.
2. The bot should be triggered based on the success/failure of the authentication.
## Experienced Functionality
The Bot gets triggered without any authentication/authorization.
## Versions
- **Opsdroid version:** master branch in git
- **Python version:** 3.6.8
- **OS/Docker version:** Ubuntu 18.04
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| Yep this would be awesome! What are your thoughts on now we would configure this? Would there be one token for all endpoints, would we configure it in the skill?
My choice would be one token for all endpoints. Configuring in each skill would not be maintainable as the number of skills grows.
Sounds good to me! Maybe it should be in the `web` section of the config. | 2019-11-19T11:29:54 |
opsdroid/opsdroid | 1,270 | opsdroid__opsdroid-1270 | [
"1240"
] | 70ebfaf50ab5754e64fa8569d4a127522931fa31 | diff --git a/opsdroid/configuration/__init__.py b/opsdroid/configuration/__init__.py
--- a/opsdroid/configuration/__init__.py
+++ b/opsdroid/configuration/__init__.py
@@ -7,7 +7,7 @@
import logging
import yaml
-from opsdroid.const import DEFAULT_CONFIG_PATH, EXAMPLE_CONFIG_FILE
+from opsdroid.const import DEFAULT_CONFIG_PATH, ENV_VAR_REGEX, EXAMPLE_CONFIG_FILE
from opsdroid.configuration.validation import validate_configuration, BASE_SCHEMA
from opsdroid.helper import update_pre_0_17_config_format
@@ -71,7 +71,7 @@ def get_config_path(config_paths):
return config_path
-env_var_pattern = re.compile(r"^\$([A-Z_]*)$")
+env_var_pattern = re.compile(ENV_VAR_REGEX)
def envvar_constructor(loader, node):
diff --git a/opsdroid/const.py b/opsdroid/const.py
--- a/opsdroid/const.py
+++ b/opsdroid/const.py
@@ -41,3 +41,4 @@
WATSON_API_ENDPOINT = "https://{gateway}.watsonplatform.net/assistant/api"
WATSON_API_VERSION = "2019-02-28"
+ENV_VAR_REGEX = r"^\"?\${?(?=\_?[A-Z])([A-Z-_]+)}?\"?$"
| diff --git a/tests/test_loader.py b/tests/test_loader.py
--- a/tests/test_loader.py
+++ b/tests/test_loader.py
@@ -10,6 +10,7 @@
import pkg_resources
from opsdroid.cli.start import configure_lang
from opsdroid.configuration import load_config_file
+from opsdroid.const import ENV_VAR_REGEX
from opsdroid import loader as ld
from opsdroid.helper import del_rw
@@ -685,3 +686,34 @@ def test_setup_module_bad_config(self):
loader.load_modules_from_config(config)
self.assertTrue(mock_sysexit.called)
self.assertLogs("_LOGGER", "critical")
+
+ def test_env_var_regex(self):
+ test_data = [
+ {"env_var": "$OPS_DROID", "match": True},
+ {"env_var": "$OPS-DROID", "match": True},
+ {"env_var": "${OPS_DROID}", "match": True},
+ {"env_var": '"$OPSDROID_SLACK_TOKEN"', "match": True},
+ {"env_var": "$_OPS_DROID", "match": True},
+ {"env_var": "${_OPS_DROID}", "match": True},
+ {"env_var": "$INVALID!_CHARACTERS@", "match": False},
+ {"env_var": "OPS_DROID", "match": False},
+ {"env_var": "$OPS_DROID23", "match": False},
+ {"env_var": "$UPPER-AND-lower", "match": False},
+ {"env_var": '"MISSING_PREFIX"', "match": False},
+ {"env_var": "$all_lowercase", "match": False},
+ {"env_var": "a simple sentence.", "match": False},
+ {"env_var": "$", "match": False},
+ {"env_var": "${}", "match": False},
+ {"env_var": "", "match": False},
+ {"env_var": "556373", "match": False},
+ {"env_var": "${@!!}", "match": False},
+ {"env_var": "${_-_-}", "match": False},
+ {"env_var": "$ALONGSTRINGTHAT$CONTAINS$", "match": False},
+ {"env_var": "NOPREFIXALONGSTRINGTHAT$CONTAINS$", "match": False},
+ ]
+ for d in test_data:
+ # Tests opsdroid constant ENV_VAR_REGEX for both valid and invalid environment variables.
+ if d["match"]:
+ self.assertRegex(d["env_var"], ENV_VAR_REGEX)
+ else:
+ self.assertNotRegex(d["env_var"], ENV_VAR_REGEX)
| Update regex pattern for the envvar construtor
You can use envvars on your configuration, but they need to follow this pattern `$ENVVARNAME` the regex pattern should be updated to allow users to use either `$ENVVARNAME` or `${ENVVARNAME}`.
While we are at it we should allow users to use other characters as well like `_` or `-`.
This change needs to be done on [opsdroid.loader.load_config_file](https://github.com/opsdroid/opsdroid/blob/674013037eab826640174407a73f8fed1a29b290/opsdroid/loader.py#L347)
| I'm also having issues when using quotes.
#### Works
```yaml
connectors:
- name: slack
api-token: $OPSDROID_SLACK_TOKEN
```
#### Doesn't work
```yaml
connectors:
- name: slack
api-token: "$OPSDROID_SLACK_TOKEN"
```
Hey @FabioRosado,
I am new to opsdroid and just starting to dip my toes into open source. Something like this might satisfy your requirements:
`re.compile(r"^\"?\${?([A-Z-_]*)}?\"?$")`
Here are some examples:

Is this issue available to work on? I would also be happy to add tests for the regex pattern if necessary.
Thanks for commenting @benjpalmer, that looks great ~(I think `$something` is a valid env var, just not a best practice style)~. Please feel free to pick this up.
Shout if you need any help, we are usually around in Matrix chat [over here](https://riot.im/app/#/room/#opsdroid-developers:matrix.org).
**Edit: actually thinking about it let's go with convention and not allow lowercase** | 2019-11-25T18:48:36 |
opsdroid/opsdroid | 1,289 | opsdroid__opsdroid-1289 | [
"244"
] | 9f60059486a60036e4624815a0f3265b57e1054f | diff --git a/opsdroid/cli/config.py b/opsdroid/cli/config.py
--- a/opsdroid/cli/config.py
+++ b/opsdroid/cli/config.py
@@ -3,11 +3,12 @@
import click
from opsdroid.cli.utils import (
+ build_config,
edit_files,
- warn_deprecated_cli_option,
- validate_config,
list_all_modules,
path_option,
+ validate_config,
+ warn_deprecated_cli_option,
)
from opsdroid.const import EXAMPLE_CONFIG_FILE
@@ -125,3 +126,31 @@ def list_modules(ctx):
"""
list_all_modules(ctx, ctx.obj, "config")
+
+
[email protected]()
[email protected]_context
[email protected](
+ "--verbose",
+ "verbose",
+ is_flag=True,
+ help="Turns logging level to debug to see all logging messages.",
+)
+def build(ctx, verbose):
+ """Load configuration, load modules and install dependencies.
+
+ This function loads the configuration and install all necessary
+ dependencies defined on a `requirements.txt` file inside the module.
+ If the flag `--verbose` is passed the logging level will be set as debug and
+ all logs will be shown to the user.
+
+
+ Args:
+ ctx (:obj:`click.Context`): The current click cli context.
+ verbose (bool): set the logging level to debug.
+
+ Returns:
+ int: the exit code. Always returns 0 in this case.
+
+ """
+ build_config(ctx, {"path": ctx.obj, "verbose": verbose}, "config")
diff --git a/opsdroid/cli/utils.py b/opsdroid/cli/utils.py
--- a/opsdroid/cli/utils.py
+++ b/opsdroid/cli/utils.py
@@ -1,6 +1,7 @@
"""Utilities for the opsdroid CLI commands."""
import click
+import contextlib
import gettext
import os
import logging
@@ -20,6 +21,8 @@
)
from opsdroid.helper import get_config_option
from opsdroid.loader import Loader
+from opsdroid.logging import configure_logging
+
_LOGGER = logging.getLogger("opsdroid")
@@ -226,3 +229,44 @@ def list_all_modules(ctx, path, value):
)
ctx.exit(0)
+
+
+def build_config(ctx, params, value):
+ """Load configuration, load modules and install dependencies.
+
+ This function loads the configuration and install all necessary
+ dependencies defined on a `requirements.txt` file inside the module.
+ If the flag `--verbose` is passed the logging level will be set as debug and
+ all logs will be shown to the user.
+
+
+ Args:
+ ctx (:obj:`click.Context`): The current click cli context.
+ params (dict): a dictionary of all parameters pass to the click
+ context when invoking this function as a callback.
+ value (string): the value of this parameter after invocation.
+ It is either "config" or "log" depending on the program
+ calling this function.
+
+ Returns:
+ int: the exit code. Always returns 0 in this case.
+
+ """
+ click.echo("Opsdroid will build modules from config.")
+ path = params.get("path")
+
+ with contextlib.suppress(Exception):
+ check_dependencies()
+
+ config = load_config_file([path] if path else DEFAULT_CONFIG_LOCATIONS)
+
+ if params["verbose"]:
+ config["logging"] = {"level": "debug"}
+ configure_logging(config)
+
+ with OpsDroid(config=config) as opsdroid:
+
+ opsdroid.loader.load_modules_from_config(config)
+
+ click.echo(click.style("SUCCESS:", bg="green", bold=True), nl=False)
+ click.echo(" Opsdroid modules successfully built from config.")
| diff --git a/tests/test_cli.py b/tests/test_cli.py
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -266,3 +266,48 @@ def test_config_validate_from_path(self):
self.assertTrue(click_echo.called)
self.assertFalse(opsdroid_load.called)
self.assertEqual(result.exit_code, 0)
+
+ def test_config_build_from_path(self):
+ with mock.patch.object(click, "echo") as click_echo, mock.patch(
+ "opsdroid.configuration.load_config_file"
+ ) as opsdroid_load:
+ runner = CliRunner()
+ from opsdroid.cli import config
+
+ result = runner.invoke(
+ config,
+ [
+ "-f",
+ os.path.abspath("tests/configs/full_valid.yaml"),
+ "build",
+ "--verbose",
+ ],
+ )
+ self.assertTrue(click_echo.called)
+ self.assertFalse(opsdroid_load.called)
+ self.assertEqual(result.exit_code, 0)
+
+ def test_config_build(self):
+ with mock.patch.object(click, "echo") as click_echo, mock.patch(
+ "opsdroid.configuration.load_config_file"
+ ) as opsdroid_load:
+ runner = CliRunner()
+ from opsdroid.cli.config import build
+
+ result = runner.invoke(build, [])
+ self.assertTrue(click_echo.called)
+ self.assertFalse(opsdroid_load.called)
+ self.assertEqual(result.exit_code, 0)
+
+ def test_config_build_exception(self):
+ with mock.patch.object(click, "echo") as click_echo, mock.patch(
+ "opsdroid.configuration.load_config_file"
+ ), mock.patch("opsdroid.loader") as mock_load:
+
+ mock_load.load_modules_from_config.side_effect = Exception()
+ runner = CliRunner()
+ from opsdroid.cli.config import build
+
+ result = runner.invoke(build, [])
+ self.assertTrue(click_echo.called)
+ self.assertEqual(result.exit_code, 0)
| Add --load-config flag
Need a flag for installing local skill dependencies when running a dockerized app. Should call the install new requirements.txt from skills loaded by `path` without running the bot
| This flag basically needs to tell opsdroid to exit after running the [load method](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/__main__.py#L121).
This would allow you to install all modules and their dependancies without running opsdroid itself.
Can I take this one?
Hello @betojulio that would be great, please go ahead and submit a PR with this issue, if you need any help with anything you can ask us in [gitter](https://gitter.im/opsdroid/developers)
Cool, thanks...
On Thu, Mar 14, 2019 at 7:51 AM Fábio Rosado <[email protected]>
wrote:
> Hello @betojulio <https://github.com/betojulio> that would be great,
> please go ahead and submit a PR with this issue, if you need any help with
> anything you can ask us in gitter <https://gitter.im/opsdroid/developers>
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <https://github.com/opsdroid/opsdroid/issues/244#issuecomment-472863429>,
> or mute the thread
> <https://github.com/notifications/unsubscribe-auth/AGlG8VDHZb1qccl32Ip5xwQDR78_mcBgks5vWlP2gaJpZM4Ppox9>
> .
>
| 2019-12-03T19:33:31 |
opsdroid/opsdroid | 1,306 | opsdroid__opsdroid-1306 | [
"1302"
] | 3a265fd76aa0d7055d60329bc244ca075fc1761e | diff --git a/opsdroid/connector/slack/__init__.py b/opsdroid/connector/slack/__init__.py
--- a/opsdroid/connector/slack/__init__.py
+++ b/opsdroid/connector/slack/__init__.py
@@ -265,7 +265,19 @@ async def slack_interactions_handler(self, request):
target=payload["channel"]["id"],
connector=self,
)
- await block_action.update_entity("value", action["value"])
+
+ action_value = None
+ if action["type"] == "button":
+ action_value = action["value"]
+ elif action["type"] in ["overflow", "static_select"]:
+ action_value = action["selected_option"]["value"]
+ elif action["type"] == "datepicker":
+ action_value = action["selected_date"]
+ elif action["type"] == "multi_static_select":
+ action_value = [v["value"] for v in action["selected_options"]]
+
+ if action_value:
+ await block_action.update_entity("value", action_value)
await self.opsdroid.parse(block_action)
elif payload["type"] == "message_action":
await self.opsdroid.parse(
diff --git a/opsdroid/parsers/event_type.py b/opsdroid/parsers/event_type.py
--- a/opsdroid/parsers/event_type.py
+++ b/opsdroid/parsers/event_type.py
@@ -33,6 +33,13 @@ async def match_event(event, event_opts):
event_value = event_opts.get(key, None)
entity_value = event.entities.get(key, {}).get("value", None)
+ if (
+ isinstance(event_value, list)
+ and isinstance(entity_value, list)
+ and sorted(event_value) != sorted(entity_value)
+ ):
+ return False
+
if event_value != entity_value:
return False
| diff --git a/tests/test_connector_slack.py b/tests/test_connector_slack.py
--- a/tests/test_connector_slack.py
+++ b/tests/test_connector_slack.py
@@ -276,7 +276,77 @@ async def test_block_actions_interactivity(self):
"value": "click_me_123",
"type": "button",
"action_ts": "1548426417.840180",
- }
+ },
+ {
+ "type": "overflow",
+ "block_id": "B5XNP",
+ "action_id": "BnhtF",
+ "selected_option": {
+ "text": {
+ "type": "plain_text",
+ "text": "Option 1",
+ "emoji": True,
+ },
+ "value": "value-0",
+ },
+ "action_ts": "1576336883.317406",
+ },
+ {
+ "type": "datepicker",
+ "block_id": "CAwR",
+ "action_id": "VS+",
+ "selected_date": "2019-12-31",
+ "initial_date": "1990-04-28",
+ "action_ts": "1576337318.133466",
+ },
+ {
+ "type": "multi_static_select",
+ "block_id": "rOL",
+ "action_id": "Cd9",
+ "selected_options": [
+ {
+ "text": {
+ "type": "plain_text",
+ "text": "Choice 1",
+ "emoji": True,
+ },
+ "value": "value-0",
+ },
+ {
+ "text": {
+ "type": "plain_text",
+ "text": "Choice 2",
+ "emoji": True,
+ },
+ "value": "value-1",
+ },
+ ],
+ "placeholder": {
+ "type": "plain_text",
+ "text": "Select items",
+ "emoji": True,
+ },
+ "action_ts": "1576337351.609054",
+ },
+ {
+ "type": "static_select",
+ "block_id": "OGN1",
+ "action_id": "4jd",
+ "selected_option": {
+ "text": {
+ "type": "plain_text",
+ "text": "Choice 2",
+ "emoji": True,
+ },
+ "value": "value-1",
+ },
+ "placeholder": {
+ "type": "plain_text",
+ "text": "Select an item",
+ "emoji": True,
+ },
+ "action_ts": "1576337378.859991",
+ },
],
}
@@ -286,6 +356,7 @@ async def test_block_actions_interactivity(self):
response = await connector.slack_interactions_handler(mock_request)
self.assertTrue(connector.opsdroid.parse.called)
+ self.assertEqual(connector.opsdroid.parse.call_count, len(req_ob["actions"]))
self.assertEqual(type(response), aiohttp.web.Response)
self.assertEqual(response.status, 200)
| The Slack Connector interaction handler fails on Overflow block elements
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://riot.im/app/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
When an [Overflow block element](https://api.slack.com/reference/block-kit/block-elements#overflow) is clicked in Slack, a `KeyError` is raised from the Slack Connector.
## Steps to Reproduce
1. Setup the Slack Connector.
2. Create a Skill that responds to a message with Blocks that contains an Overflow element:
```python
@match_regex(r'overflow block')
async def overflow_block(self, message):
sample_response = [{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "This block has an overflow menu."
},
"accessory": {
"type": "overflow",
"options": [
{
"text": {
"type": "plain_text",
"text": "Option 1",
"emoji": True
},
"value": "value-0"
},
{
"text": {
"type": "plain_text",
"text": "Option 2",
"emoji": True
},
"value": "value-1"
}
]
}
}]
await message.respond(Blocks(sample_response))
```
3. And a Slack Interactions handler:
```python
@match_event(BlockActions)
async def slack_interactions(self, event: BlockActions):
await event.respond(f'Received payload: {event.payload}')
```
4. In Slack, send "overflow block" to the bot and interact with the Overflow menu button it responds with.
## Expected Functionality
The Slack Interactions handler from step 3 above should be called and a response with the message payload should be sent back to the chat.
## Experienced Functionality
In Slack, a small exclamation mark appears near the Overflow action button, indicating something went wrong with the interaction.
In Opsdroid, the following message appears in the log:
```
ERROR aiohttp.server: Error handling request
Traceback (most recent call last):
File "/path/to/venv/lib/python3.7/site-packages/aiohttp/web_protocol.py", line 418, in start
resp = await task
File "/path/to/venv/lib/python3.7/site-packages/aiohttp/web_app.py", line 458, in _handle
resp = await handler(request)
File "/path/to/venv/lib/python3.7/site-packages/opsdroid/connector/slack/__init__.py", line 268, in slack_interactions_handler
await block_action.update_entity("value", action["value"])
KeyError: 'value'
INFO aiohttp.access: 127.0.0.1 [14/Dec/2019:15:01:36 +0000] "POST /connector/slack/interactions HTTP/1.1" 500 244 "-" "Slackbot 1.0 (+https://api.slack.com/robots)"
```
## Versions
- **Opsdroid version:** 0.17.0
- **Python version:** 3.7
- **OS/Docker version:** macOS 10.14.6
## Configuration File
Please include your version of the configuration file below.
```yaml
logging:
level: debug
console: true
web:
host: '127.0.0.1'
port: 8090
parsers:
connectors:
- name: slack
api-token: "*******************"
default: true
skills:
- name: skill
path: /path/to/skill
no-cache: true
```
## Additional Details
This is happening because the Overflow element payload is a bit different from the payload sent by the Button element which is handled correctly.
This is a Button element action fragment:
```json
{
"type": "button",
"block_id": "I1V6",
"action_id": "nmMCa",
"text": {
"type": "plain_text",
"text": "Button",
"emoji": true
},
"value": "click_me_123",
"action_ts": "1576336692.912336"
}
```
You can see there is a `value` key there, but in an Overflow action fragment the `value` key is nested under the `selected_option` object.:
```json
{
"type": "overflow",
"block_id": "B5XNP",
"action_id": "BnhtF",
"selected_option": {
"text": {
"type": "plain_text",
"text": "Option 1",
"emoji": true
},
"value": "value-0"
},
"action_ts": "1576336883.317406"
}
```
There are other block elements that will result in the same behaviour:
- Datepicker - here the `value` is `selected_date`:
```json
{
"type": "datepicker",
"block_id": "CAwR",
"action_id": "VS+",
"selected_date": "2019-12-31",
"initial_date": "1990-04-28",
"action_ts": "1576337318.133466"
}
```
- Multi-Select - here there can be multiple selected options:
```json
{
"type": "multi_static_select",
"block_id": "rOL",
"action_id": "Cd9",
"selected_options": [
{
"text": {
"type": "plain_text",
"text": "Choice 2",
"emoji": true
},
"value": "value-1"
},
{
"text": {
"type": "plain_text",
"text": "Choice 1",
"emoji": true
},
"value": "value-0"
}
],
"placeholder": {
"type": "plain_text",
"text": "Select items",
"emoji": true
},
"action_ts": "1576337351.609054"
}
```
- Select - this one is similar to the Overflow with `value` in the `selected_option`:
```json
{
"type": "static_select",
"block_id": "OGN1",
"action_id": "4jd",
"selected_option": {
"text": {
"type": "plain_text",
"text": "Choice 2",
"emoji": true
},
"value": "value-1"
},
"placeholder": {
"type": "plain_text",
"text": "Select an item",
"emoji": true
},
"action_ts": "1576337378.859991"
}
```
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| I would actually like to pick this up and fix it but i'm not sure how to handle the Multi-Select element - is saving all the selected item's values as a list under the "value" entity acceptable?
Thanks so much for taking the time to raise such a thorough issue!
If you're happy to work on it that would be appreciated too. I think a list of items sounds great! | 2019-12-17T21:33:57 |
opsdroid/opsdroid | 1,328 | opsdroid__opsdroid-1328 | [
"1310"
] | 1216df8413717b14e68cf6bca509859ff033756b | diff --git a/opsdroid/connector/websocket/__init__.py b/opsdroid/connector/websocket/__init__.py
--- a/opsdroid/connector/websocket/__init__.py
+++ b/opsdroid/connector/websocket/__init__.py
@@ -97,7 +97,7 @@ async def websocket_handler(self, request):
self.active_connections[socket] = websocket
async for msg in websocket:
if msg.type == aiohttp.WSMsgType.TEXT:
- message = Message(msg.data, None, None, self)
+ message = Message(text=msg.data, user=None, target=None, connector=self)
await self.opsdroid.parse(message)
elif msg.type == aiohttp.WSMsgType.ERROR:
_LOGGER.error(
| Hello skill not working
Hi,
I have setup opsdroid in windows 10
Versions:
Opsdroid 0.17.0
Python 3.8.1
Configuration.yaml:
[configuration.txt](https://github.com/opsdroid/opsdroid/files/3991251/configuration.txt)
Right after launching opsdroid with start command: when i type "hi" in the windows client seeing below error:
```
C:\Users\integrat>opsdroid start
INFO opsdroid.logging: ========================================
INFO opsdroid.logging: Started opsdroid v0.17.0.
INFO opsdroid: ========================================
INFO opsdroid: You can customise your opsdroid by modifying your configuration.yaml.
INFO opsdroid: Read more at: http://opsdroid.readthedocs.io/#configuration
INFO opsdroid: Watch the Get Started Videos at: http://bit.ly/2fnC0Fh
INFO opsdroid: Install Opsdroid Desktop at:
https://github.com/opsdroid/opsdroid-desktop/releases
INFO opsdroid: ========================================
WARNING opsdroid.loader: No databases in configuration. This will cause skills which store things in memory to lose data when opsdroid is restarted.
INFO opsdroid.web: Started web server on http://0.0.0.0:8080
INFO opsdroid.core: Opsdroid is now running, press ctrl+c to exit.
INFO aiohttp.access: 10.52.81.154 [21/Dec/2019:09:39:20 +0000] "POST /connector/websocket HTTP/1.1" 200 252 "-" "-"
ERROR opsdroid.core: Exception when running skill 'hello'.
Traceback (most recent call last):
File "c:\users\integrat\appdata\local\programs\python\python38-32\lib\site-packages\opsdroid\core.py", line 396, in run_skill
return await skill(event)
File "C:\Users\integrat\AppData\Local\opsdroid-modules\opsdroid\opsdroid-modules\skill\hello\__init__.py", line 13, in hello
await message.respond(text)
File "c:\users\integrat\appdata\local\programs\python\python38-32\lib\site-packages\opsdroid\events.py", line 263, in respond
"thinking-delay" in self.connector.configuration
AttributeError: 'NoneType' object has no attribute 'configuration'
ERROR aiohttp.server: Error handling request
Traceback (most recent call last):
File "c:\users\integrat\appdata\local\programs\python\python38-32\lib\site-packages\opsdroid\core.py", line 396, in run_skill
return await skill(event)
File "C:\Users\integrat\AppData\Local\opsdroid-modules\opsdroid\opsdroid-modules\skill\hello\__init__.py", line 13, in hello
await message.respond(text)
File "c:\users\integrat\appdata\local\programs\python\python38-32\lib\site-packages\opsdroid\events.py", line 263, in respond
"thinking-delay" in self.connector.configuration
AttributeError: 'NoneType' object has no attribute 'configuration'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\users\integrat\appdata\local\programs\python\python38-32\lib\site-packages\aiohttp\web_protocol.py", line 418, in start
resp = await task
File "c:\users\integrat\appdata\local\programs\python\python38-32\lib\site-packages\aiohttp\web_app.py", line 458, in _handle
resp = await handler(request)
File "c:\users\integrat\appdata\local\programs\python\python38-32\lib\site-packages\opsdroid\connector\websocket\__init__.py", line 101, in websocket_handler
await self.opsdroid.parse(message)
File "c:\users\integrat\appdata\local\programs\python\python38-32\lib\site-packages\opsdroid\core.py", line 509, in parse
await asyncio.gather(*tasks)
File "c:\users\integrat\appdata\local\programs\python\python38-32\lib\site-packages\opsdroid\core.py", line 402, in run_skill
await event.respond(
File "c:\users\integrat\appdata\local\programs\python\python38-32\lib\site-packages\opsdroid\events.py", line 263, in respond
"thinking-delay" in self.connector.configuration
AttributeError: 'NoneType' object has no attribute 'configuration'
INFO aiohttp.access: 10.52.81.154 [21/Dec/2019:09:39:24 +0000] "POST /connector/websocket HTTP/1.1" 200 252 "-" "-"
`
```
| 2020-01-03T14:08:22 |
||
opsdroid/opsdroid | 1,355 | opsdroid__opsdroid-1355 | [
"1354"
] | 942ff1c843ceb8071007fe33d4d2fb371af8feb1 | diff --git a/opsdroid/connector/telegram/__init__.py b/opsdroid/connector/telegram/__init__.py
--- a/opsdroid/connector/telegram/__init__.py
+++ b/opsdroid/connector/telegram/__init__.py
@@ -34,9 +34,9 @@ def __init__(self, config, opsdroid=None):
self.name = "telegram"
self.opsdroid = opsdroid
self.latest_update = None
- self.default_target = None
self.listening = True
self.default_user = config.get("default-user", None)
+ self.default_target = self.default_user
self.whitelisted_users = config.get("whitelisted-users", None)
self.update_interval = config.get("update-interval", 1)
self.session = None
@@ -167,9 +167,13 @@ async def _parse_message(self, response):
"""
for result in response["result"]:
_LOGGER.debug(result)
+
if result.get("edited_message", None):
result["message"] = result.pop("edited_message")
- if "channel" in result["message"]["chat"]["type"]:
+ if result.get("channel_post", None) or result.get(
+ "edited_channel_post", None
+ ):
+ self.latest_update = result["update_id"] + 1
_LOGGER.debug(
_("Channel message parsing not supported " "- Ignoring message.")
)
@@ -179,7 +183,7 @@ async def _parse_message(self, response):
text=result["message"]["text"],
user=user,
user_id=user_id,
- target=result["message"]["chat"],
+ target=result["message"]["chat"]["id"],
connector=self,
)
@@ -277,10 +281,12 @@ async def send_message(self, message):
message (object): An instance of Message.
"""
- _LOGGER.debug(_("Responding with: %s."), message.text)
+ _LOGGER.debug(
+ _("Responding with: '%s' at target: '%s'"), message.text, message.target
+ )
data = dict()
- data["chat_id"] = message.target["id"]
+ data["chat_id"] = message.target
data["text"] = message.text
resp = await self.session.post(self.build_url("sendMessage"), data=data)
if resp.status == 200:
| Telegram connector needs update for event message
# Description
The telegram connector uses message.target['id'] instead of message.target. This leads to problems when trying to use default_target per normal configuration and usage of the event flow logic.
## Steps to Reproduce
Setup telegram as the default connector... call the telegram connector.send with a target...
```
await self.opsdroid.send(Message(text='hello', target='<useridhere>')
```
The default_target is also always None.
```
await self.opsdroid.send(Message(text='hello')
```
You can hack around it with..
```
sillytarget = { 'id': <useridhere> }
await self.opsdroid.send(Message(text='hello', target=sillytarget)
```
## Expected Functionality
message.target should work like the other core connectors
## Experienced Functionality
Errors out.
```
opsdroid | ERROR opsdroid.connector.telegram.send_message(): Unable to respond.
```
## Versions
- opsdroid: latest/stable
- python 3.7.6
- docker image: opsdroid/opsdroid:latest
## Configuration File
```yaml
connectors:
## Telegram (core)
telegram:
token: "......"
# optional
update-interval: 0.5 # Interval between checking for messages
whitelisted-users: # List of users who can speak to the bot, if not set anyone can speak
- ......
```
## Additional Details
None
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| 2020-02-04T21:15:29 |
||
opsdroid/opsdroid | 1,363 | opsdroid__opsdroid-1363 | [
"1361",
"1361"
] | 9102978e8ce405213e590a999df6d20c81b948dc | diff --git a/opsdroid/connector/slack/__init__.py b/opsdroid/connector/slack/__init__.py
--- a/opsdroid/connector/slack/__init__.py
+++ b/opsdroid/connector/slack/__init__.py
@@ -144,7 +144,8 @@ async def process_message(self, **payload):
_LOGGER.debug(_("Looking up sender username."))
try:
user_info = await self.lookup_username(message["user"])
- except ValueError:
+ except (ValueError, KeyError) as error:
+ _LOGGER.error(_("Username lookup failed for %s."), error)
return
# Replace usernames in the message
| diff --git a/tests/test_connector_slack.py b/tests/test_connector_slack.py
--- a/tests/test_connector_slack.py
+++ b/tests/test_connector_slack.py
@@ -148,6 +148,11 @@ async def test_process_message(self):
await connector.process_message(data=message)
self.assertFalse(connector.opsdroid.parse.called)
+ connector.opsdroid.parse.reset_mock()
+ connector.lookup_username.side_effect = KeyError
+ await connector.process_message(data=message)
+ self.assertFalse(connector.opsdroid.parse.called)
+
async def test_lookup_username(self):
"""Test that looking up a username works and that it caches."""
connector = ConnectorSlack({"token": "abc123"}, opsdroid=OpsDroid())
| opsdroid slack connector intermittently ends up in an exception
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://riot.im/app/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description - opsdroid slack connector intermittently ends up in an exception
this doesnt happen for all users - but i see that line 146 in File "/usr/local/lib/python3.7/site-packages/opsdroid/connector/slack/__init__.py" is the culprit.
```
INFO opsdroid.connector.slack: Connected successfully.
INFO opsdroid.web: Started web server on http://0.0.0.0:8080
INFO opsdroid.core: Opsdroid is now running, press ctrl+c to exit.
DEBUG slack.rtm.client: The Websocket connection has been opened.
DEBUG opsdroid.parsers.crontab: Running crontab skills at Mon Feb 10 10:21:00 2020.
DEBUG slack.rtm.client: Running 1 callbacks for event: 'message'
DEBUG opsdroid.connector.slack: Looking up sender username.
ERROR slack.rtm.client: When calling '#process_message()' in the 'opsdroid.connector.slack' module the following error was raised: 'user'
DEBUG asyncio: Using selector: EpollSelector
Traceback (most recent call last):
File "/usr/local/bin/opsdroid", line 8, in <module>
sys.exit(cli())
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/opsdroid/cli/start.py", line 42, in start
opsdroid.run()
File "/usr/local/lib/python3.7/site-packages/opsdroid/core.py", line 165, in run
self.eventloop.run_until_complete(asyncio.gather(*pending))
File "/usr/local/lib/python3.7/asyncio/base_events.py", line 583, in run_until_complete
return future.result()
File "/usr/local/lib/python3.7/site-packages/slack/rtm/client.py", line 339, in _connect_and_read
await self._read_messages()
File "/usr/local/lib/python3.7/site-packages/slack/rtm/client.py", line 390, in _read_messages
await self._dispatch_event(event, data=payload)
File "/usr/local/lib/python3.7/site-packages/slack/rtm/client.py", line 437, in _dispatch_event
rtm_client=self, web_client=self._web_client, data=data
File "/usr/local/lib/python3.7/site-packages/opsdroid/connector/slack/__init__.py", line 146, in process_message
user_info = await self.lookup_username(message["user"])
KeyError: 'user'
ERROR: Unhandled exception in opsdroid, exiting...
```
## Steps to Reproduce
Please also include relevant information and steps to reproduce the bug/issue.
i am not sure if this can be reproduced elsewhere - otherwise would have been reported by other users.
the slack channel has about 82 users.
the bot is part of 2 channels.
also users interact with the bot directly /
## Expected Functionality
no exception - Looking up sender username should succeed.
## Experienced Functionality
Explain what happened instead(Please include the debug log).
```INFO opsdroid.connector.slack: Connected successfully.
INFO opsdroid.web: Started web server on http://0.0.0.0:8080
INFO opsdroid.core: Opsdroid is now running, press ctrl+c to exit.
DEBUG slack.rtm.client: The Websocket connection has been opened.
DEBUG opsdroid.parsers.crontab: Running crontab skills at Mon Feb 10 10:21:00 2020.
DEBUG slack.rtm.client: Running 1 callbacks for event: 'message'
DEBUG opsdroid.connector.slack: Looking up sender username.
ERROR slack.rtm.client: When calling '#process_message()' in the 'opsdroid.connector.slack' module the following error was raised: 'user'
DEBUG asyncio: Using selector: EpollSelector
Traceback (most recent call last):
File "/usr/local/bin/opsdroid", line 8, in <module>
sys.exit(cli())
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/opsdroid/cli/start.py", line 42, in start
opsdroid.run()
File "/usr/local/lib/python3.7/site-packages/opsdroid/core.py", line 165, in run
self.eventloop.run_until_complete(asyncio.gather(*pending))
File "/usr/local/lib/python3.7/asyncio/base_events.py", line 583, in run_until_complete
return future.result()
File "/usr/local/lib/python3.7/site-packages/slack/rtm/client.py", line 339, in _connect_and_read
await self._read_messages()
File "/usr/local/lib/python3.7/site-packages/slack/rtm/client.py", line 390, in _read_messages
await self._dispatch_event(event, data=payload)
File "/usr/local/lib/python3.7/site-packages/slack/rtm/client.py", line 437, in _dispatch_event
rtm_client=self, web_client=self._web_client, data=data
File "/usr/local/lib/python3.7/site-packages/opsdroid/connector/slack/__init__.py", line 146, in process_message
user_info = await self.lookup_username(message["user"])
KeyError: 'user'
ERROR: Unhandled exception in opsdroid, exiting...
```
## Versions
- **Opsdroid version:** latest master code.
- **Python version:** python3.7
- **OS/Docker version:** 18.06.3-ce
## Configuration File
Please include your version of the configuration file below.
configuration file passed in values.yaml helm chart
```yaml
configuration: |
welcome-message: true
connectors:
slack:
token: "xxx"
bot-name: "xxx" # default "opsdroid"
default-room: "#xxx" # default "#general"
#icon-emoji: ":smile:" # default ":robot_face:"
connect-timeout: 10 # default 10 seconds
chat-as-user: false # default false
skills:
- name: skill-yyy-statistics
path: /home/skill/skill-yyy-statistics
db_server: "1.1.1.1"
db_name: "xx"
user: "xxx"
password: "xxx"
- name: skill-yyy-help
path: /home/skill/skill-yyy-help
- name: skill-yyy-cache
path: /home/skill/skill-yyy-cache
db_server: "1.1.1.1"
db_name: "zz"
user: "xxx"
password: "xxxx"
- name: skill-yyy-eee
path: /home/skill/skill-yyy-eee
- name: skill-yyy-ttt
path: /home/skill/skill-yyy-ttt
```
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
opsdroid slack connector intermittently ends up in an exception
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://riot.im/app/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description - opsdroid slack connector intermittently ends up in an exception
this doesnt happen for all users - but i see that line 146 in File "/usr/local/lib/python3.7/site-packages/opsdroid/connector/slack/__init__.py" is the culprit.
```
INFO opsdroid.connector.slack: Connected successfully.
INFO opsdroid.web: Started web server on http://0.0.0.0:8080
INFO opsdroid.core: Opsdroid is now running, press ctrl+c to exit.
DEBUG slack.rtm.client: The Websocket connection has been opened.
DEBUG opsdroid.parsers.crontab: Running crontab skills at Mon Feb 10 10:21:00 2020.
DEBUG slack.rtm.client: Running 1 callbacks for event: 'message'
DEBUG opsdroid.connector.slack: Looking up sender username.
ERROR slack.rtm.client: When calling '#process_message()' in the 'opsdroid.connector.slack' module the following error was raised: 'user'
DEBUG asyncio: Using selector: EpollSelector
Traceback (most recent call last):
File "/usr/local/bin/opsdroid", line 8, in <module>
sys.exit(cli())
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/opsdroid/cli/start.py", line 42, in start
opsdroid.run()
File "/usr/local/lib/python3.7/site-packages/opsdroid/core.py", line 165, in run
self.eventloop.run_until_complete(asyncio.gather(*pending))
File "/usr/local/lib/python3.7/asyncio/base_events.py", line 583, in run_until_complete
return future.result()
File "/usr/local/lib/python3.7/site-packages/slack/rtm/client.py", line 339, in _connect_and_read
await self._read_messages()
File "/usr/local/lib/python3.7/site-packages/slack/rtm/client.py", line 390, in _read_messages
await self._dispatch_event(event, data=payload)
File "/usr/local/lib/python3.7/site-packages/slack/rtm/client.py", line 437, in _dispatch_event
rtm_client=self, web_client=self._web_client, data=data
File "/usr/local/lib/python3.7/site-packages/opsdroid/connector/slack/__init__.py", line 146, in process_message
user_info = await self.lookup_username(message["user"])
KeyError: 'user'
ERROR: Unhandled exception in opsdroid, exiting...
```
## Steps to Reproduce
Please also include relevant information and steps to reproduce the bug/issue.
i am not sure if this can be reproduced elsewhere - otherwise would have been reported by other users.
the slack channel has about 82 users.
the bot is part of 2 channels.
also users interact with the bot directly /
## Expected Functionality
no exception - Looking up sender username should succeed.
## Experienced Functionality
Explain what happened instead(Please include the debug log).
```INFO opsdroid.connector.slack: Connected successfully.
INFO opsdroid.web: Started web server on http://0.0.0.0:8080
INFO opsdroid.core: Opsdroid is now running, press ctrl+c to exit.
DEBUG slack.rtm.client: The Websocket connection has been opened.
DEBUG opsdroid.parsers.crontab: Running crontab skills at Mon Feb 10 10:21:00 2020.
DEBUG slack.rtm.client: Running 1 callbacks for event: 'message'
DEBUG opsdroid.connector.slack: Looking up sender username.
ERROR slack.rtm.client: When calling '#process_message()' in the 'opsdroid.connector.slack' module the following error was raised: 'user'
DEBUG asyncio: Using selector: EpollSelector
Traceback (most recent call last):
File "/usr/local/bin/opsdroid", line 8, in <module>
sys.exit(cli())
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/opsdroid/cli/start.py", line 42, in start
opsdroid.run()
File "/usr/local/lib/python3.7/site-packages/opsdroid/core.py", line 165, in run
self.eventloop.run_until_complete(asyncio.gather(*pending))
File "/usr/local/lib/python3.7/asyncio/base_events.py", line 583, in run_until_complete
return future.result()
File "/usr/local/lib/python3.7/site-packages/slack/rtm/client.py", line 339, in _connect_and_read
await self._read_messages()
File "/usr/local/lib/python3.7/site-packages/slack/rtm/client.py", line 390, in _read_messages
await self._dispatch_event(event, data=payload)
File "/usr/local/lib/python3.7/site-packages/slack/rtm/client.py", line 437, in _dispatch_event
rtm_client=self, web_client=self._web_client, data=data
File "/usr/local/lib/python3.7/site-packages/opsdroid/connector/slack/__init__.py", line 146, in process_message
user_info = await self.lookup_username(message["user"])
KeyError: 'user'
ERROR: Unhandled exception in opsdroid, exiting...
```
## Versions
- **Opsdroid version:** latest master code.
- **Python version:** python3.7
- **OS/Docker version:** 18.06.3-ce
## Configuration File
Please include your version of the configuration file below.
configuration file passed in values.yaml helm chart
```yaml
configuration: |
welcome-message: true
connectors:
slack:
token: "xxx"
bot-name: "xxx" # default "opsdroid"
default-room: "#xxx" # default "#general"
#icon-emoji: ":smile:" # default ":robot_face:"
connect-timeout: 10 # default 10 seconds
chat-as-user: false # default false
skills:
- name: skill-yyy-statistics
path: /home/skill/skill-yyy-statistics
db_server: "1.1.1.1"
db_name: "xx"
user: "xxx"
password: "xxx"
- name: skill-yyy-help
path: /home/skill/skill-yyy-help
- name: skill-yyy-cache
path: /home/skill/skill-yyy-cache
db_server: "1.1.1.1"
db_name: "zz"
user: "xxx"
password: "xxxx"
- name: skill-yyy-eee
path: /home/skill/skill-yyy-eee
- name: skill-yyy-ttt
path: /home/skill/skill-yyy-ttt
```
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| Thanks for raising this!
It looks like opsdroid is getting a message which does not have a user field. This is a little strange as I woudl expect all messages to have a user, perhaps some system messages do not or something.
We should catch this `KeyError`, skip parsing and log it.
If we also catch `KeyError` [here](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/connector/slack/__init__.py#L147) and then add a log line with `_LOGGER.error` before the return [here](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/connector/slack/__init__.py#L148) I think that would do it.
Thanks for raising this!
It looks like opsdroid is getting a message which does not have a user field. This is a little strange as I woudl expect all messages to have a user, perhaps some system messages do not or something.
We should catch this `KeyError`, skip parsing and log it.
If we also catch `KeyError` [here](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/connector/slack/__init__.py#L147) and then add a log line with `_LOGGER.error` before the return [here](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/connector/slack/__init__.py#L148) I think that would do it. | 2020-02-11T20:41:27 |
opsdroid/opsdroid | 1,399 | opsdroid__opsdroid-1399 | [
"1381"
] | 76ccc9f7ce3c40a08e198247421a4a97a3f61332 | diff --git a/opsdroid/connector/matrix/connector.py b/opsdroid/connector/matrix/connector.py
--- a/opsdroid/connector/matrix/connector.py
+++ b/opsdroid/connector/matrix/connector.py
@@ -210,6 +210,11 @@ async def listen(self): # pragma: no cover
except Exception: # pylint: disable=W0703
_LOGGER.exception(_("Matrix sync error."))
+ def lookup_target(self, room):
+ """Convert name or alias of a room to the corresponding room ID."""
+ room = self.get_roomname(room)
+ return self.room_ids.get(room, room)
+
async def get_nick(self, roomid, mxid):
"""
Get nickname from user ID.
diff --git a/opsdroid/constraints.py b/opsdroid/constraints.py
--- a/opsdroid/constraints.py
+++ b/opsdroid/constraints.py
@@ -31,6 +31,9 @@ def constraint_decorator(func):
def constraint_callback(message, rooms=rooms):
"""Check if the room is correct."""
+ if hasattr(message.connector, "lookup_target"):
+ rooms = list(map(message.connector.lookup_target, rooms))
+
return message.target in rooms
func = add_skill_attributes(func)
diff --git a/opsdroid/parsers/event_type.py b/opsdroid/parsers/event_type.py
--- a/opsdroid/parsers/event_type.py
+++ b/opsdroid/parsers/event_type.py
@@ -51,6 +51,9 @@ async def match_event(event, event_opts):
async def parse_event_type(opsdroid, event):
"""Parse an event if it's of a certain type."""
for skill in opsdroid.skills:
+ for constraint in skill.constraints:
+ if not constraint(event):
+ return
for matcher in skill.matchers:
event_opts = matcher.get("event_type", {})
result = await match_event(event, event_opts)
| diff --git a/tests/test_connector_matrix.py b/tests/test_connector_matrix.py
--- a/tests/test_connector_matrix.py
+++ b/tests/test_connector_matrix.py
@@ -414,6 +414,15 @@ def test_get_roomname(self):
assert self.connector.get_roomname("!aroomid:localhost") == "main"
assert self.connector.get_roomname("someroom") == "someroom"
+ def test_lookup_target(self):
+ self.connector.room_ids = {"main": "!aroomid:localhost"}
+
+ assert self.connector.lookup_target("main") == "!aroomid:localhost"
+ assert self.connector.lookup_target("#test:localhost") == "!aroomid:localhost"
+ assert (
+ self.connector.lookup_target("!aroomid:localhost") == "!aroomid:localhost"
+ )
+
async def test_respond_image(self):
gif_bytes = (
b"GIF89a\x01\x00\x01\x00\x00\xff\x00,"
diff --git a/tests/test_parser_event_type.py b/tests/test_parser_event_type.py
--- a/tests/test_parser_event_type.py
+++ b/tests/test_parser_event_type.py
@@ -6,6 +6,7 @@
from opsdroid.matchers import match_event
from opsdroid import events
from opsdroid.parsers.event_type import parse_event_type
+from opsdroid.constraints import constrain_rooms
class TestParserEvent(asynctest.TestCase):
@@ -56,6 +57,23 @@ async def test_parse_event_with_args(self):
await opsdroid.parse(message2)
self.assertFalse(opsdroid.run_skill.called)
+ async def test_parse_event_with_constraint(self):
+ with OpsDroid() as opsdroid:
+ opsdroid.run_skill = amock.CoroutineMock()
+ mock_skill = await self.getMockSkill()
+ mock_skill = match_event(events.JoinRoom)(mock_skill)
+ mock_skill = constrain_rooms(["#general"])(mock_skill)
+ opsdroid.skills.append(mock_skill)
+
+ mock_connector = amock.CoroutineMock()
+ mock_connector.lookup_target = amock.Mock(return_value="some_room_id")
+ message = events.JoinRoom(
+ user="user", target="some_room_id", connector=mock_connector
+ )
+
+ await opsdroid.parse(message)
+ self.assertTrue(opsdroid.run_skill.called)
+
async def test_parse_str_event(self):
with OpsDroid() as opsdroid:
opsdroid.run_skill = amock.CoroutineMock()
| Constraints don't apply to non-Message events
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://riot.im/app/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
It seems that constrains don't apply to non-Message events.
## Steps to Reproduce
```python
class ExampleSkill(Skill):
@match_event(JoinRoom)
@constrain_rooms(['room1'])
async def user_join(self, event):
print('User joined {}'.format(event.target))
```
## Expected Functionality
The `user_join()` skill method would only run if a user joined `room1`
## Experienced Functionality
The `user_join()` skill method is run when a user joins any room the connector is configured to join.
## Versions
- **Opsdroid version:** 7282a5da06
- **Python version:** 3.7.6
- **OS/Docker version:** Linux/Debian (testing)
## Configuration File
```yaml
connector:
- name: matrix
mxid: '@user:matrix.org'
password: xxx
nick: 'User'
rooms:
'room1': <room id>
'room2': <room id>
```
| Yep: https://github.com/opsdroid/opsdroid/blob/master/opsdroid/core.py#L494L497 should be an easy fix, and there is no good reason for it either. | 2020-03-14T16:20:23 |
opsdroid/opsdroid | 1,408 | opsdroid__opsdroid-1408 | [
"1407"
] | 41b852c13559825542c70fb75f2c3f90c2fefaa9 | diff --git a/opsdroid/connector/shell/__init__.py b/opsdroid/connector/shell/__init__.py
--- a/opsdroid/connector/shell/__init__.py
+++ b/opsdroid/connector/shell/__init__.py
@@ -125,7 +125,6 @@ async def respond(self, message):
_LOGGER.debug(_("Responding with: %s."), message.text)
self.clear_prompt()
print(message.text)
- self.draw_prompt()
async def disconnect(self):
"""Disconnects the connector."""
| diff --git a/tests/test_connector_shell.py b/tests/test_connector_shell.py
--- a/tests/test_connector_shell.py
+++ b/tests/test_connector_shell.py
@@ -161,7 +161,7 @@ async def test_respond(self):
with contextlib.redirect_stdout(f):
await self.connector.respond(message)
prompt = f.getvalue()
- self.assertEqual(prompt.strip(), "Hi\nopsdroid>")
+ self.assertEqual(prompt.strip(), "Hi")
async def test_disconnect(self):
connector = ConnectorShell({}, opsdroid=OpsDroid())
| Duplicated shell prompt
# Description
When I run the hello skill from the shell, I found duplicated shell prompt output. I think there's some issue with the shell connector.
## Steps to Reproduce
```
qidong@ubuntu:~/Documents/opsdroid$ opsdroid start
mybot> hello
Hello qidong
mybot> mybot>
```
## Expected Functionality
There should be only one prompt printed after the skill response.
## Experienced Functionality
One extra prompt is printed.
## Configuration File
```yaml
logging:
console: false
connectors:
websocket:
bot-name: "mybot"
max-connections: 10
connection-timeout: 10
shell:
bot-name: "mybot"
skills:
## Hello (https://github.com/opsdroid/skill-hello)
hello: {}
```
| 2020-03-23T02:19:04 |
|
opsdroid/opsdroid | 1,432 | opsdroid__opsdroid-1432 | [
"1429"
] | 1af196fb064b7f3aa627014cdec2ff531baf674e | diff --git a/opsdroid/logging.py b/opsdroid/logging.py
--- a/opsdroid/logging.py
+++ b/opsdroid/logging.py
@@ -83,13 +83,13 @@ def configure_logging(config):
rootlogger.setLevel(log_level)
- try:
+ formatter = logging.Formatter("%(levelname)s %(name)s: %(message)s")
+
+ with contextlib.suppress(KeyError):
if config["logging"]["extended"]:
formatter = logging.Formatter(
"%(levelname)s %(name)s.%(funcName)s(): %(message)s"
)
- except KeyError:
- formatter = logging.Formatter("%(levelname)s %(name)s: %(message)s")
console_handler = logging.StreamHandler()
console_handler.setLevel(log_level)
| Opsdroid logger returning errors
# Description
Hi, I have been using `opsdroid` for a few days now, and while it is a good framework, I have been having a lot of trouble. Most recently I have been getting a error `formatter refrenced before use`. I have linted my configuration.yaml and none of my python files have errors. The error message below only shows errors in opsdroid library files. Even so, I am probably doing something wrong. Any help is greatly appreciated!
## Steps to Reproduce
I just linted and built my config. Neither of those actions returned errors.
## Expected Functionality
My bot should have run on Telegram and in bash.
## Experienced Functionality
```bash
Traceback (most recent call last):
File "/home/gideongrinberg/.local/bin/opsdroid", line 8, in <module>
sys.exit(cli())
File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/home/gideongrinberg/.local/lib/python3.6/site-packages/opsdroid/cli/start.py", line 38, in start
configure_logging(config)
File "/home/gideongrinberg/.local/lib/python3.6/site-packages/opsdroid/logging.py", line 93, in configure_logging
console_handler.setFormatter(formatter)
UnboundLocalError: local variable 'formatter' referenced before assignment
```
## Versions
- **Opsdroid version:** 0.17.1
- **Python version:** Python 3.6.9
- **OS/Docker version:** Ubuntu 18.04 on Window Subsystem Linux (Windows 10)
## Configuration File
My config.yaml is to large to include, but this is the only line I've change from the example (other than adding tokens)
```yaml
recycle-nlp:
path: '~/opdroid_recycle/skill-recycle-nlp'
```
Again, that file returns no errors when I run `opsdroid config -f [PATH] lint` or `opsdroid config -f [PATH] build`.
Additionally, the python file:
```python
from opsdroid.skill import Skill
from opsdroid.matchers import match_luisai_intent
class recycle-nlp(Skill):
@match_luisai_intent('recycle')
async def recycle-nlp(self, message):
if message.luisai["topScoringIntent"]["intent"]=="recycle":
await message.respond(str(message.luisai))
```
My directory structure (/home for WSL, not windows):
```
| /home
|____ opsdroid_recycle
|
|_____ config.yaml
|_____skill-recycle-nlp
|
|____ __init__.py
|______ README.md
|______ LICENSE
|
|___.local/lib/python3.6/site-packages
```
## Additional Details
Interestingly, my bot worked fine with the example config
Any help is much appreciated!
| I've hit the same error, when enabling logging as defined in the default configuration sourced from https://raw.githubusercontent.com/opsdroid/opsdroid/master/opsdroid/configuration/example_configuration.yaml.
The block that triggers the error is:
```yaml
logging:
level: info
path: opsdroid.log
console: true
extended: false
filter:
whitelist:
- opsdroid.core
blacklist:
- opsdroid.loader
```
The error message is as follows
```python
opsdroid start -f /opt/opsdroid/configuration.yaml
Traceback (most recent call last):
File "/opt/opsdroid/bin/opsdroid", line 8, in <module>
sys.exit(cli())
File "/opt/opsdroid/lib/python3.7/site-packages/click/core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "/opt/opsdroid/lib/python3.7/site-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/opt/opsdroid/lib/python3.7/site-packages/click/core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/opt/opsdroid/lib/python3.7/site-packages/click/core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/opt/opsdroid/lib/python3.7/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/opt/opsdroid/lib/python3.7/site-packages/opsdroid/cli/start.py", line 38, in start
configure_logging(config)
File "/opt/opsdroid/lib/python3.7/site-packages/opsdroid/logging.py", line 93, in configure_logging
console_handler.setFormatter(formatter)
UnboundLocalError: local variable 'formatter' referenced before assignment
```
Version
```
pip freeze | grep opsdroid
opsdroid==0.17.1
```
@nzlosh where you able to fix this? Did you try `opsdroid config -f [PATH] lint`?
@nzlosh this issue appears to be logging related. The `formatter` is defined in [logging.py](https://github.com/opsdroid/opsdroid/blob/7f817f61a6d4042b4bd930e4aca15b3387786cd0/opsdroid/logging.py). @FabioRosado appears to have worked on that file most recently, so maybe he can shed some light on how to fix this.
Hello @Gideon357 and @nzlosh Thank you for raising this issue and I'd like to apologise for the troubles you are having with opsdroid.
Just out of curiosity are you setting your logging with the `extended` set to false and do you have any `whitelist` or `blacklist` filter set to it?
I might have botched up something while creating the extended filter. I'm going to work on this issue tomorrow and hopefully fix it.
@FabioRosado thanks for responding. I was using the default configuration that I generated using `opsdroid config gen > config.yaml`. If you need help fixing it, let me know. I do know @nzlosh had his logging setup like this:
```yaml
logging:
level: info
path: opsdroid.log
console: true
extended: false
filter:
whitelist:
- opsdroid.core
blacklist:
- opsdroid.loader
```
| 2020-04-16T15:42:51 |
|
opsdroid/opsdroid | 1,435 | opsdroid__opsdroid-1435 | [
"1434"
] | 3d2bf69c946a8d9a7ebe91adb85d2ffd44cc5b54 | diff --git a/opsdroid/connector/telegram/__init__.py b/opsdroid/connector/telegram/__init__.py
--- a/opsdroid/connector/telegram/__init__.py
+++ b/opsdroid/connector/telegram/__init__.py
@@ -5,7 +5,7 @@
from voluptuous import Required
from opsdroid.connector import Connector, register_event
-from opsdroid.events import Message, Image
+from opsdroid.events import Message, Image, File
_LOGGER = logging.getLogger(__name__)
@@ -318,6 +318,30 @@ async def send_image(self, file_event):
else:
_LOGGER.debug(_("Unable to send image - Status Code %s."), resp.status)
+ @register_event(File)
+ async def send_file(self, file_event):
+ """Send File to Telegram.
+
+ Gets the chat id from the channel and then
+ sends the bytes of the file as multipart/form-data.
+
+ """
+ data = aiohttp.FormData()
+ data.add_field(
+ "chat_id", str(file_event.target["id"]), content_type="multipart/form-data"
+ )
+ data.add_field(
+ "document",
+ await file_event.get_file_bytes(),
+ content_type="multipart/form-data",
+ )
+
+ resp = await self.session.post(self.build_url("sendDocument"), data=data)
+ if resp.status == 200:
+ _LOGGER.debug(_("Sent %s file successfully."), file_event.name)
+ else:
+ _LOGGER.debug(_("Unable to send file - Status Code %s."), resp.status)
+
async def disconnect(self):
"""Disconnect from Telegram.
| diff --git a/tests/test_connector_telegram.py b/tests/test_connector_telegram.py
--- a/tests/test_connector_telegram.py
+++ b/tests/test_connector_telegram.py
@@ -7,7 +7,7 @@
from opsdroid.core import OpsDroid
from opsdroid.connector.telegram import ConnectorTelegram
-from opsdroid.events import Message, Image
+from opsdroid.events import Message, Image, File
from opsdroid.cli.start import configure_lang
@@ -510,6 +510,38 @@ async def test_respond_image_failure(self):
await self.connector.send_image(image)
self.assertLogs("_LOOGER", "debug")
+ async def test_respond_file(self):
+ post_response = amock.Mock()
+ post_response.status = 200
+
+ file_bytes = b"plain text file example"
+
+ file = File(file_bytes=file_bytes, target={"id": "123"})
+
+ with amock.patch.object(self.connector.session, "post") as patched_request:
+
+ patched_request.return_value = asyncio.Future()
+ patched_request.return_value.set_result(post_response)
+
+ await self.connector.send_file(file)
+ self.assertTrue(patched_request.called)
+
+ async def test_respond_file_failure(self):
+ post_response = amock.Mock()
+ post_response.status = 400
+
+ file_bytes = b"plain text file example"
+
+ file = File(file_bytes=file_bytes, target={"id": "123"})
+
+ with amock.patch.object(self.connector.session, "post") as patched_request:
+
+ patched_request.return_value = asyncio.Future()
+ patched_request.return_value.set_result(post_response)
+
+ await self.connector.send_file(file)
+ self.assertLogs("_LOOGER", "debug")
+
async def test_listen(self):
with amock.patch.object(
self.connector.loop, "create_task"
| Telegram connector can not handle the File event type
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://riot.im/app/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
Telegram connector does not handle File events.
## Steps to Reproduce
```
@match_regex(r'Please, send me a pdf file')
async def sendDocument(self, message):
path= '/file.pdf'
with open(path, 'rb') as file:
fileEvent = File(file_bytes= file, mimetype= 'application/pdf', target= {'id': message.target})
await message.respond( fileEvent )
```
## Expected Functionality
The connector should handle the File event type.
## Experienced Functionality
You get the following error
> `TypeError: Connector <class 'opsdroid.connector.telegram.ConnectorTelegram'> can not handle the 'File' event type.`
## Versions
- **Opsdroid version:** v0.17.1
- **Python version:** 3.7
- **OS/Docker version:** Fedora 31
## Configuration File
Not relevant, I think
## Additional Details
The solution should be quite similar to [Adds Image support for Telegram #929](https://github.com/opsdroid/opsdroid/pull/929)
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| 2020-04-18T17:17:56 |
|
opsdroid/opsdroid | 1,454 | opsdroid__opsdroid-1454 | [
"1453"
] | a33700a18b1ee874955ffc23570c8f4eae5b04e8 | diff --git a/opsdroid/parsers/regex.py b/opsdroid/parsers/regex.py
--- a/opsdroid/parsers/regex.py
+++ b/opsdroid/parsers/regex.py
@@ -1,16 +1,16 @@
"""A helper function for parsing and executing regex skills."""
import logging
-import re
+import regex
_LOGGER = logging.getLogger(__name__)
-async def calculate_score(regex, score_factor):
+async def calculate_score(expression, score_factor):
"""Calculate the score of a regex."""
# The score asymptotically approaches the max score
# based on the length of the expression.
- return (1 - (1 / ((len(regex) + 1) ** 2))) * score_factor
+ return (1 - (1 / ((len(expression) + 1) ** 2))) * score_factor
async def match_regex(text, opts):
@@ -19,15 +19,15 @@ async def match_regex(text, opts):
def is_case_sensitive():
if opts["case_sensitive"]:
return False
- return re.IGNORECASE
+ return regex.IGNORECASE
if opts["matching_condition"].lower() == "search":
- regex = re.search(opts["expression"], text, is_case_sensitive())
+ matched_regex = regex.search(opts["expression"], text, is_case_sensitive())
elif opts["matching_condition"].lower() == "fullmatch":
- regex = re.fullmatch(opts["expression"], text, is_case_sensitive())
+ matched_regex = regex.fullmatch(opts["expression"], text, is_case_sensitive())
else:
- regex = re.match(opts["expression"], text, is_case_sensitive())
- return regex
+ matched_regex = regex.match(opts["expression"], text, is_case_sensitive())
+ return matched_regex
async def parse_regex(opsdroid, skills, message):
@@ -37,10 +37,10 @@ async def parse_regex(opsdroid, skills, message):
for matcher in skill.matchers:
if "regex" in matcher:
opts = matcher["regex"]
- regex = await match_regex(message.text, opts)
- if regex:
- message.regex = regex
- for regroup, value in regex.groupdict().items():
+ matched_regex = await match_regex(message.text, opts)
+ if matched_regex:
+ message.regex = matched_regex
+ for regroup, value in matched_regex.groupdict().items():
message.update_entity(regroup, value, None)
matched_skills.append(
{
| diff --git a/tests/test_parser_regex.py b/tests/test_parser_regex.py
--- a/tests/test_parser_regex.py
+++ b/tests/test_parser_regex.py
@@ -148,3 +148,19 @@ async def test_parse_regex_named_groups_entities(self):
self.assertEqual(len(parsed_message.entities.keys()), 1)
self.assertTrue("name" in parsed_message.entities.keys())
self.assertEqual(parsed_message.entities["name"]["value"], "opsdroid")
+
+ async def test_parse_regex_identically_named_groups_entities(self):
+ with OpsDroid() as opsdroid:
+ regex = r"Hello (?P<name>.*)|Hi (?P<name>.*)"
+
+ mock_skill_named_groups = await self.getMockSkill()
+ opsdroid.skills.append(match_regex(regex)(mock_skill_named_groups))
+
+ mock_connector = amock.CoroutineMock()
+ message = Message("Hello opsdroid", "user", "default", mock_connector)
+
+ [skill] = await opsdroid.get_ranked_skills(opsdroid.skills, message)
+ parsed_message = skill["message"]
+ self.assertEqual(len(parsed_message.entities.keys()), 1)
+ self.assertTrue("name" in parsed_message.entities.keys())
+ self.assertEqual(parsed_message.entities["name"]["value"], "opsdroid")
| Parser regex.py does not support identically named group in regex_matcher
# Description
When using the same group name in **match_regex** decorator **regex.py** issue an error because the python re module used to parse messages does not support identical named group
## Steps to Reproduce
- Create a skill like (the goal is to have a multiple patterns using the same group name)
```python
from opsdroid.matchers import match_regex
from opsdroid.skill import Skill
PATTERNS = '|'.join([
"say (?P<word>\w+)",
"repeat (?P<word>\w+)",
"say",
"repeat"
])
class SaySkill(Skill):
@match_regex(PATTERNS, case_sensitive=False, matching_condition='match')
async def say(self, message):
word = message.entities['word']['value'] or None
if word is None:
word = 'No word to say'
await message.respond(word)
```
- Add it to configuration file
- using opsdroid shell or opsdroid desktop test it
- Issue occurs
```
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=say hello)>.
ERROR aiohttp.server: Error handling request
Traceback (most recent call last):
File "/usr/lib64/python3.6/site-packages/aiohttp/web_protocol.py", line 418, in start
resp = await task
File "/usr/lib64/python3.6/site-packages/aiohttp/web_app.py", line 458, in _handle
resp = await handler(request)
File "/home/ibot/ibot-opsdroid/opsdroid/opsdroid/connector/websocket/__init__.py", line 101, in websocket_handler
await self.opsdroid.parse(message)
File "/home/ibot/ibot-opsdroid/opsdroid/opsdroid/core.py", line 498, in parse
ranked_skills = await self.get_ranked_skills(unconstrained_skills, event)
File "/home/ibot/ibot-opsdroid/opsdroid/opsdroid/core.py", line 421, in get_ranked_skills
ranked_skills += await parse_regex(self, skills, message)
File "/home/ibot/ibot-opsdroid/opsdroid/opsdroid/parsers/regex.py", line 40, in parse_regex
regex = await match_regex(message.text, opts)
File "/home/ibot/ibot-opsdroid/opsdroid/opsdroid/parsers/regex.py", line 29, in match_regex
regex = re.match(opts["expression"], text, is_case_sensitive())
File "/usr/lib64/python3.6/re.py", line 172, in match
return _compile(pattern, flags).match(string)
File "/usr/lib64/python3.6/re.py", line 301, in _compile
p = sre_compile.compile(pattern, flags)
File "/usr/lib64/python3.6/sre_compile.py", line 562, in compile
p = sre_parse.parse(p, flags)
File "/usr/lib64/python3.6/sre_parse.py", line 855, in parse
p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
File "/usr/lib64/python3.6/sre_parse.py", line 416, in _parse_sub
not nested and not items))
File "/usr/lib64/python3.6/sre_parse.py", line 759, in _parse
raise source.error(err.msg, len(name) + 1) from None
sre_constants.error: redefinition of group name 'city' as group 2; was group 1 at position 42 <-------
```
## Expected Functionality
Handling multiple patterns with the same name group
```
DEBUG opsdroid.parsers.crontab: Running crontab skills at Fri May 1 19:03:00 2020.
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=say hello)>.
DEBUG opsdroid.core: Processing parsers...
DEBUG opsdroid.connector.websocket: Responding with: 'hello' in target 8d9c8b96-8bcd-11ea-b043-0050568f7a82 <----------
```
## Experienced Functionality
debug logs :
```
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=say hello)>.
ERROR aiohttp.server: Error handling request
Traceback (most recent call last):
File "/usr/lib64/python3.6/site-packages/aiohttp/web_protocol.py", line 418, in start
resp = await task
File "/usr/lib64/python3.6/site-packages/aiohttp/web_app.py", line 458, in _handle
resp = await handler(request)
File "/home/ibot/ibot-opsdroid/opsdroid/opsdroid/connector/websocket/__init__.py", line 101, in websocket_handler
await self.opsdroid.parse(message)
File "/home/ibot/ibot-opsdroid/opsdroid/opsdroid/core.py", line 498, in parse
ranked_skills = await self.get_ranked_skills(unconstrained_skills, event)
File "/home/ibot/ibot-opsdroid/opsdroid/opsdroid/core.py", line 421, in get_ranked_skills
ranked_skills += await parse_regex(self, skills, message)
File "/home/ibot/ibot-opsdroid/opsdroid/opsdroid/parsers/regex.py", line 40, in parse_regex
regex = await match_regex(message.text, opts)
File "/home/ibot/ibot-opsdroid/opsdroid/opsdroid/parsers/regex.py", line 29, in match_regex
regex = re.match(opts["expression"], text, is_case_sensitive())
File "/usr/lib64/python3.6/re.py", line 172, in match
return _compile(pattern, flags).match(string)
File "/usr/lib64/python3.6/re.py", line 301, in _compile
p = sre_compile.compile(pattern, flags)
File "/usr/lib64/python3.6/sre_compile.py", line 562, in compile
p = sre_parse.parse(p, flags)
File "/usr/lib64/python3.6/sre_parse.py", line 855, in parse
p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
File "/usr/lib64/python3.6/sre_parse.py", line 416, in _parse_sub
not nested and not items))
File "/usr/lib64/python3.6/sre_parse.py", line 759, in _parse
raise source.error(err.msg, len(name) + 1) from None
sre_constants.error: redefinition of group name 'city' as group 2; was group 1 at position 42 <-------
```
## Versions
- **Opsdroid version:*v0.18.0*
- **Python version:*3.6.7*
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| 2020-05-01T17:25:26 |
|
opsdroid/opsdroid | 1,485 | opsdroid__opsdroid-1485 | [
"1345"
] | 5682527d6e3737026b828f4aba215a23ae8a39f3 | diff --git a/opsdroid/core.py b/opsdroid/core.py
--- a/opsdroid/core.py
+++ b/opsdroid/core.py
@@ -486,6 +486,46 @@ async def get_ranked_skills(self, skills, message):
return sorted(ranked_skills, key=lambda k: k["score"], reverse=True)
+ def get_connector(self, name):
+ """Get a connector object.
+
+ Get a specific connector by name from the list of active connectors.
+
+ Args:
+ name (string): Name of the connector we want to access.
+
+ Returns:
+ connector (opsdroid.connector.Connector): An opsdroid connector.
+
+ """
+ try:
+ [connector] = [
+ connector for connector in self.connectors if connector.name == name
+ ]
+ return connector
+ except ValueError:
+ return None
+
+ def get_database(self, name):
+ """Get a database object.
+
+ Get a specific database by name from the list of active databases.
+
+ Args:
+ name (string): Name of the database we want to access.
+
+ Returns:
+ database (opsdroid.database.Database): An opsdroid database.
+
+ """
+ try:
+ [database] = [
+ database for database in self.memory.databases if database.name == name
+ ]
+ return database
+ except ValueError:
+ return None
+
async def _constrain_skills(self, skills, message):
"""Remove skills with contraints which prohibit them from running.
diff --git a/opsdroid/database/__init__.py b/opsdroid/database/__init__.py
--- a/opsdroid/database/__init__.py
+++ b/opsdroid/database/__init__.py
@@ -97,6 +97,7 @@ class InMemoryDatabase(Database):
def __init__(self, config={}, opsdroid=None): # noqa: D107
super().__init__(config, opsdroid)
self.memory = {}
+ self.name = "inmem"
async def connect(self): # noqa: D102
pass # pragma: nocover
| diff --git a/tests/test_core.py b/tests/test_core.py
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -582,3 +582,21 @@ async def modify_dir(opsdroid, directory):
)
assert opsdroid.reload.called
+
+ async def test_get_connector_database(self):
+ skill_path = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)),
+ "mockmodules/skills/skill/skilltest",
+ )
+ example_config = {
+ "connectors": {"websocket": {}},
+ "skills": {"test": {"path": skill_path}},
+ }
+ with OpsDroid(config=example_config) as opsdroid:
+ await opsdroid.load()
+
+ assert opsdroid.get_connector("websocket") is not None
+ assert opsdroid.get_connector("slack") is None
+
+ assert opsdroid.get_database("inmem") is not None
+ assert opsdroid.get_database("redis") is None
| Add get module convenience methods
Sometimes it is helpful to be able to grab a connector, database, etc from within your skill.
You may wish to call `connector.send` on a specific connector, or use the `database.client` to directly interact with the database (just don't mess with the `opsdroid` table).
Currently you can access the lists of modules from the attributes `opsdroid.connectors`, `opsdroid.databases`, etc. However to grab a specific connector or database you end up doing a list compehension.
```python
[slack] = [connector for connector in self.opsdroid.connectors if connector.name == "slack"]
await slack.send(Message("Hello world"))
```
It would be nice to have some convenience methods such as `get_connector` and `get_database` in the `opsdroid` object to make accessing these easier. For example
```python
slack = self.opsdroid.get_connector("slack")
await slack.send(Message("Hello world"))
sqlite = self.opsdroid.get_database("sqlite")
cur = await sqlite.client.cursor()
await cur.execute("INSERT INTO students (name) VALUES ('" + name + "');") # Beware of Bobby Tables
await self.client.commit()
```
| If it doesn't already work, we should allow the `connector=` kwarg to `Event` to be a string, which gets converted into the connector based on the name. This would let you do send easily by doing something like
```python
opsdroid.send(Message("hello", connector="slack"))
```
Ooh yes definitely!
This would be a really useful feature. However is there a potential problem with just using the connector name as the key? What if there are multiple connectors of the same type?
Maybe there needs to be some sort of `id` associated with the connector configuration? ie:
```
connectors:
- name: matrix
id: connector1
mxid: '@user1:matrix.org'
password: xxx
rooms:
'room1': '#room1:matrix.org'
- name: matrix
id: connector2
mxid: '@user1:matrix.org'
password: xxx
rooms:
'room1': '#room1:matrix.org'
```
It would then be used something like:
```
opsdroid.send(Message("hello", connector="connector1"))
```
However, if we were willing to make a backward incompatible change, then changing the existing `name` to `type` might be preferable. ie:
```
connectors:
- name: connector1
type: matrix
...
- name: connector1
type: matrix
...
```
There may be a way to fudge this a bit to provide some backwards compatibility (ie `type` defaults to the value of `name` if not provided), but for the moment I'm just putting some general thoughts out there.
You cannot set a duplicate name. Opsdroid tries to autodetect which module you want based on the name. Setting the name to `matrix` will set the module property to `opsdroid.connector.matrix`. So for multiple matrix connectors you should set something like this.
```
connectors:
- name: matrix
- name: othermatrix
module: opsdroid.connector.matrix
```
@jacobtomlinson yeah, it think you can probably ignore my contribution. I think i wrote that before I realised the config syntax had changed. | 2020-05-19T13:47:23 |
opsdroid/opsdroid | 1,504 | opsdroid__opsdroid-1504 | [
"1501"
] | 7c38ffca869b35c31dff9273735e20c9c498cfb1 | diff --git a/opsdroid/connector/webexteams/__init__.py b/opsdroid/connector/webexteams/__init__.py
--- a/opsdroid/connector/webexteams/__init__.py
+++ b/opsdroid/connector/webexteams/__init__.py
@@ -14,7 +14,7 @@
_LOGGER = logging.getLogger(__name__)
-CONFIG_SCHEMA = {Required("webhook-url"): Url, Required("token"): str}
+CONFIG_SCHEMA = {Required("webhook-url"): Url(), Required("token"): str}
class ConnectorWebexTeams(Connector):
| diff --git a/tests/test_connector_webexteams.py b/tests/test_connector_webexteams.py
--- a/tests/test_connector_webexteams.py
+++ b/tests/test_connector_webexteams.py
@@ -24,6 +24,10 @@ def test_init(self):
self.assertEqual("webexteams", connector.name)
self.assertEqual("opsdroid", connector.bot_name)
+ def test_webhook_url_is_valid(self):
+ connector = ConnectorWebexTeams({"webhook-url": "https://example.com"})
+ assert connector.config.get("webhook-url").startswith("https")
+
def test_missing_api_key(self):
"""Test that creating without an API without config raises an error."""
with self.assertRaises(TypeError):
| Cisco WebEx Teams connector doesn't start
# Error
```
INFO opsdroid.logging: ========================================
INFO opsdroid.logging: Started opsdroid 0+unknown.
WARNING opsdroid: 'welcome-message: true/false' is missing in configuration.yaml
WARNING opsdroid.loader: No databases in configuration. This will cause skills which store things in memory to lose data when opsdroid is restarted.
INFO opsdroid.loader: Cloning hello from remote repository.
Traceback (most recent call last):
File "/usr/local/bin/opsdroid", line 8, in <module>
sys.exit(cli())
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/opsdroid/cli/start.py", line 42, in start
opsdroid.run()
File "/usr/local/lib/python3.7/site-packages/opsdroid/core.py", line 158, in run
self.sync_load()
File "/usr/local/lib/python3.7/site-packages/opsdroid/core.py", line 177, in sync_load
self.eventloop.run_until_complete(self.load())
File "/usr/local/lib/python3.7/asyncio/base_events.py", line 587, in run_until_complete
return future.result()
File "/usr/local/lib/python3.7/site-packages/opsdroid/core.py", line 185, in load
await self.start_connectors(self.modules["connectors"])
File "/usr/local/lib/python3.7/site-packages/opsdroid/core.py", line 319, in start_connectors
await self.eventloop.create_task(connector.connect())
File "/usr/local/lib/python3.7/site-packages/opsdroid/connector/webexteams/__init__.py", line 53, in connect
await self.subscribe_to_rooms()
File "/usr/local/lib/python3.7/site-packages/opsdroid/connector/webexteams/__init__.py", line 99, in subscribe_to_rooms
secret=self.secret,
File "/usr/local/lib/python3.7/site-packages/webexteamssdk/api/webhooks.py", line 159, in create
json_data = self._session.post(API_ENDPOINT, json=post_data)
File "/usr/local/lib/python3.7/site-packages/webexteamssdk/restsession.py", line 401, in post
**kwargs)
File "/usr/local/lib/python3.7/site-packages/webexteamssdk/restsession.py", line 258, in request
check_response_code(response, erc)
File "/usr/local/lib/python3.7/site-packages/webexteamssdk/utils.py", line 220, in check_response_code
raise ApiError(response)
webexteamssdk.exceptions.ApiError: [400] Bad Request - POST failed: HTTP/1.1 400 Bad Request (url = https://webhook-engine-a.wbx2.com/webhook-engine/api/v1/webhooks, request/response TrackingId = ROUTER_5ECD21B0-63B3-01BB-00D6-B2CAA80F00D6, error = 'Invalid targetUrl: Illegal character in path at index 0: <function Url at 0x7fd36ce31f80>/connector/webexteams')
```
# How to reproduce
* Create `configuration.yaml` with the following content:
```
connectors:
webexteams:
token: MYBOTACCESSTOKEN
webhook-url: https://my-webhook-url.com
# Seem that webhook-url is not relevant for the error message
skills:
hello:
```
* Create `debug.sh` with the following content:
```
docker run --rm -ti -p 8080:8080 \
-v `pwd`/configuration.yaml:/root/.config/opsdroid/configuration.yaml:ro \
opsdroid/opsdroid:v0.18.0 sh
```
* `chmod +x debug.sh`
* `./debug.sh`
* (in the container) `opsdroid start`
| 2020-05-26T21:11:01 |
|
opsdroid/opsdroid | 1,540 | opsdroid__opsdroid-1540 | [
"1534"
] | 9b81f0aec0056f59d2181b6792a53bfc24b344e4 | diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -74,6 +74,7 @@ def run(self):
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
+ "Programming Language :: Python :: 3.8",
"Topic :: Communications :: Chat",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
"Topic :: Software Development :: Libraries :: Python Modules",
| Add 3.8 support to setup.py
We've been running CI against 3.8 for a while now, we should update the metadata in `setup.py` to explicitly state we support 3.8.
We should also update the [support table](https://github.com/opsdroid/opsdroid/blob/master/docs/maintaining/supported-python-versions.md) to say we support 3.8.
| and also pull 3.6 now 0.19 is out as well.
Can I work on this issue?
Hello @elijose55 please go ahead and submit a PR, let us know if you need any help | 2020-06-17T15:51:56 |
|
opsdroid/opsdroid | 1,548 | opsdroid__opsdroid-1548 | [
"992"
] | f3c18960ba381a3eb21d6b820eb8b265bcd380c5 | diff --git a/opsdroid/connector/matrix/connector.py b/opsdroid/connector/matrix/connector.py
--- a/opsdroid/connector/matrix/connector.py
+++ b/opsdroid/connector/matrix/connector.py
@@ -1,5 +1,4 @@
"""Connector for Matrix (https://matrix.org)."""
-
import re
import logging
import functools
@@ -10,7 +9,7 @@
from voluptuous import Required
from opsdroid.connector import Connector, register_event
-from opsdroid import events
+from opsdroid import events, const
from .html_cleaner import clean
from .create_events import MatrixEventCreator
@@ -18,6 +17,7 @@
import nio
import json
+from pathlib import Path
_LOGGER = logging.getLogger(__name__)
CONFIG_SCHEMA = {
@@ -27,6 +27,9 @@
"homeserver": str,
"nick": str,
"room_specific_nicks": bool,
+ "device_name": str,
+ "device_id": str,
+ "store_path": str,
}
__all__ = ["ConnectorMatrix"]
@@ -74,7 +77,7 @@ def __init__(self, config, opsdroid=None): # noqa: D107
self.room_ids = {}
self.default_target = self.rooms["main"]["alias"]
self.mxid = config["mxid"]
- self.nick = config.get("nick", None)
+ self.nick = config.get("nick")
self.homeserver = config.get("homeserver", "https://matrix.org")
self.password = config["password"]
self.room_specific_nicks = config.get("room_specific_nicks", False)
@@ -83,6 +86,12 @@ def __init__(self, config, opsdroid=None): # noqa: D107
self.filter_id = None
self.connection = None
self.device_name = config.get("device_name", "opsdroid")
+ self.device_id = config.get("device_id", "opsdroid")
+ self.store_path = config.get(
+ "store_path", str(Path(const.DEFAULT_ROOT_PATH, "matrix"))
+ )
+ self._ignore_unverified = True
+ self._allow_encryption = nio.crypto.ENCRYPTION_ENABLED
self._event_creator = MatrixEventCreator(self)
@@ -131,10 +140,45 @@ async def make_filter(self, api, fjson):
resp_json = await resp.json()
return int(resp_json["filter_id"])
+ async def exchange_keys(self, initial_sync=False):
+ """Send to-device messages and perform key exchange operations."""
+ await self.connection.send_to_device_messages()
+ if self.connection.should_upload_keys:
+ await self.connection.keys_upload()
+ if self.connection.should_query_keys:
+ await self.connection.keys_query()
+
+ if initial_sync:
+ for room_id in self.room_ids.values():
+ try:
+ await self.connection.keys_claim(
+ self.connection.get_missing_sessions(room_id)
+ )
+ except nio.LocalProtocolError:
+ continue
+ elif self.connection.should_claim_keys:
+ await self.connection.keys_claim(
+ self.connection.get_users_for_key_claiming()
+ )
+
async def connect(self):
"""Create connection object with chat library."""
- config = nio.AsyncClientConfig(encryption_enabled=False, pickle_key="")
- mapi = nio.AsyncClient(self.homeserver, self.mxid, config=config)
+
+ if self._allow_encryption:
+ Path(self.store_path).mkdir(exist_ok=True)
+
+ config = nio.AsyncClientConfig(
+ encryption_enabled=self._allow_encryption,
+ pickle_key="",
+ store_name="opsdroid.db" if self._allow_encryption else "",
+ )
+ mapi = nio.AsyncClient(
+ self.homeserver,
+ self.mxid,
+ config=config,
+ store_path=self.store_path if self._allow_encryption else "",
+ device_id=self.device_id,
+ )
login_response = await mapi.login(
password=self.password, device_name=self.device_name
@@ -167,7 +211,9 @@ async def connect(self):
)
# Do initial sync so we don't get old messages later.
- response = await self.connection.sync(timeout=3000, sync_filter=first_filter_id)
+ response = await self.connection.sync(
+ timeout=3000, sync_filter=first_filter_id, full_state=True
+ )
if isinstance(response, nio.SyncError):
_LOGGER.error(
@@ -177,6 +223,8 @@ async def connect(self):
self.connection.sync_token = response.next_batch
+ await self.exchange_keys(initial_sync=True)
+
if self.nick:
display_name = await self.connection.get_displayname(self.mxid)
if display_name != self.nick:
@@ -214,13 +262,8 @@ async def _parse_sync_response(self, response):
if roomInfo.timeline:
for event in roomInfo.timeline.events:
if event.sender != self.mxid:
- # if isinstance(event, nio.MegolmEvent):
- # event is encrypted
- # event = await self.connection.decrypt_event(event)
-
if event.source["type"] == "m.room.member":
event.source["content"] = event.content
-
return await self._event_creator.create_event(
event.source, roomid
)
@@ -241,6 +284,8 @@ async def listen(self): # pragma: no cover
_LOGGER.debug(_("Matrix sync request returned."))
+ await self.exchange_keys()
+
message = await self._parse_sync_response(response)
if message:
@@ -323,6 +368,7 @@ async def _send_message(self, message):
self._get_formatted_message_body(
message.text, msgtype=self.message_type(message.target)
),
+ ignore_unverified_devices=self._ignore_unverified,
)
@register_event(events.EditedMessage)
@@ -349,8 +395,11 @@ async def _send_edit(self, message):
"m.relates_to": {"rel_type": "m.replace", "event_id": edited_event_id},
}
- return (
- await self.connection.room_send(message.target, "m.room.message", content),
+ return await self.connection.room_send(
+ message.target,
+ "m.room.message",
+ content,
+ ignore_unverified_devices=self._ignore_unverified,
)
@register_event(events.Reply)
@@ -368,8 +417,11 @@ async def _send_reply(self, reply):
content["m.relates_to"] = {"m.in_reply_to": {"event_id": reply_event_id}}
- return (
- await self.connection.room_send(reply.target, "m.room.message", content),
+ return await self.connection.room_send(
+ reply.target,
+ "m.room.message",
+ content,
+ ignore_unverified_devices=self._ignore_unverified,
)
@register_event(events.Reaction)
@@ -382,63 +434,94 @@ async def _send_reaction(self, reaction):
"key": reaction.emoji,
}
}
- return await self.connection.room_send(reaction.target, "m.reaction", content)
+ return await self.connection.room_send(
+ reaction.target,
+ "m.reaction",
+ content,
+ ignore_unverified_devices=self._ignore_unverified,
+ )
- async def _get_image_info(self, image):
- width, height = await image.get_dimensions()
- return {
- "w": width,
- "h": height,
- "mimetype": await image.get_mimetype(),
- "size": len(await image.get_file_bytes()),
- }
+ async def _get_file_info(self, file_event):
+ info_dict = {}
+ if isinstance(file_event, events.Image):
+ info_dict["w"], info_dict["h"] = await file_event.get_dimensions()
+
+ info_dict["mimetype"] = await file_event.get_mimetype()
+ info_dict["size"] = len(await file_event.get_file_bytes())
+
+ return info_dict
async def _file_to_mxc_url(self, file_event):
"""Given a file event return the mxc url."""
uploaded = False
mxc_url = None
+ file_dict = None
if file_event.url:
url = urlparse(file_event.url)
if url.scheme == "mxc":
mxc_url = file_event.url
if not mxc_url:
+ encrypt_file = (
+ self._allow_encryption
+ and file_event.target in self.connection.store.load_encrypted_rooms()
+ )
upload_file = await file_event.get_file_bytes()
- mxc_url = await self.connection.upload(
- lambda x, y: upload_file, await file_event.get_mimetype()
+ mimetype = await file_event.get_mimetype()
+
+ response = await self.connection.upload(
+ lambda x, y: upload_file, content_type=mimetype, encrypt=encrypt_file
)
- mxc_url = mxc_url[0].content_uri
+ response, file_dict = response
+
+ if isinstance(response, nio.UploadError):
+ _LOGGER.error(
+ f"Error while sending the file. Reason: {response.message} (status code {response.status_code})"
+ )
+ return response, None, None
+
+ mxc_url = response.content_uri
uploaded = True
- return mxc_url, uploaded
+ if file_dict:
+ file_dict["url"] = mxc_url
+ file_dict["mimetype"] = mimetype
+
+ return mxc_url, uploaded, file_dict
@register_event(events.File)
@register_event(events.Image)
@ensure_room_id_and_send
async def _send_file(self, file_event):
- mxc_url, uploaded = await self._file_to_mxc_url(file_event)
+ mxc_url, uploaded, file_dict = await self._file_to_mxc_url(file_event)
- if isinstance(file_event, events.Image):
- if uploaded:
- extra_info = await self._get_image_info(file_event)
- else:
- extra_info = {}
- msg_type = "m.image"
+ if isinstance(mxc_url, nio.UploadError):
+ return
+
+ name = file_event.name or "opsdroid_upload"
+ if uploaded:
+ extra_info = await self._get_file_info(file_event)
else:
extra_info = {}
- msg_type = "m.file"
+ msg_type = f"m.{file_event.__class__.__name__}".lower()
+
+ content = {
+ "body": name,
+ "info": extra_info,
+ "msgtype": msg_type,
+ "url": mxc_url,
+ }
+
+ if file_dict:
+ content["file"] = file_dict
+ del content["url"]
- name = file_event.name or "opsdroid_upload"
await self.connection.room_send(
room_id=file_event.target,
message_type="m.room.message",
- content={
- "body": name,
- "info": extra_info,
- "msgtype": msg_type,
- "url": mxc_url,
- },
+ content=content,
+ ignore_unverified_devices=self._ignore_unverified,
)
@register_event(events.NewRoom)
@@ -518,7 +601,7 @@ async def _send_room_desciption(self, desc_event):
@register_event(events.RoomImage)
@ensure_room_id_and_send
async def _send_room_image(self, image_event):
- mxc_url, _ = await self._file_to_mxc_url(image_event.room_image)
+ mxc_url, _, _ = await self._file_to_mxc_url(image_event.room_image)
return await image_event.respond(matrixevents.MatrixRoomAvatar(mxc_url))
@register_event(events.UserRole)
diff --git a/opsdroid/connector/matrix/create_events.py b/opsdroid/connector/matrix/create_events.py
--- a/opsdroid/connector/matrix/create_events.py
+++ b/opsdroid/connector/matrix/create_events.py
@@ -119,7 +119,13 @@ async def create_message(self, event, roomid):
return events.Message(**kwargs)
async def _file_kwargs(self, event, roomid):
- url = await self.connector.mxc_to_http(event["content"]["url"])
+
+ if "url" in event["content"]:
+ url = event["content"]["url"]
+ else:
+ url = event["content"]["file"]["url"]
+
+ url = await self.connector.connection.mxc_to_http(url)
user = await self.connector.get_nick(roomid, event["sender"])
return dict(
| diff --git a/requirements_test.txt b/requirements_test.txt
--- a/requirements_test.txt
+++ b/requirements_test.txt
@@ -7,6 +7,7 @@ pytest==5.4.2
pytest-asyncio==0.12.0
pytest-cov==2.7.1
pytest-timeout==1.4.0
+pytest-mock==3.2.0
pydocstyle==5.0.2
asynctest==0.13.0
mypy-lang==0.5.0
diff --git a/tests/test_connector_matrix.py b/tests/test_connector_matrix.py
--- a/tests/test_connector_matrix.py
+++ b/tests/test_connector_matrix.py
@@ -3,7 +3,7 @@
from copy import deepcopy
import aiohttp
-import asynctest
+
import asynctest.mock as amock
import nio
@@ -19,7 +19,8 @@
api_string = "nio.AsyncClient.{}"
-def setup_connector():
[email protected]
+def connector():
"""Initiate a basic connector setup for testing on"""
connector = ConnectorMatrix(
{
@@ -29,16 +30,16 @@ def setup_connector():
"homeserver": "http://localhost:8008",
}
)
+ api = nio.AsyncClient("https://notaurl.com", None)
+ connector.connection = api
+
return connector
-class TestConnectorMatrixAsync(asynctest.TestCase):
[email protected]
+class TestConnectorMatrixAsync:
"""Test the async methods of the opsdroid Matrix connector class."""
- @pytest.fixture(autouse=True)
- def inject_fixtures(self, caplog):
- self._caplog = caplog
-
@property
def sync_return(self):
"""Define some mock json to return from the sync method"""
@@ -213,13 +214,7 @@ def filter_json(self):
},
}
- def setUp(self):
- """Basic setting up for tests"""
- self.connector = setup_connector()
- self.api = nio.AsyncClient("https://notaurl.com", None)
- self.connector.connection = self.api
-
- async def test_make_filter(self):
+ async def test_make_filter(self, connector):
with amock.patch(api_string.format("send")) as patched_filter:
connect_response = amock.Mock()
@@ -227,17 +222,68 @@ async def test_make_filter(self):
connect_response.json = amock.CoroutineMock()
connect_response.json.return_value = {"filter_id": 10}
- self.api.token = "abc"
+ connector.connection.token = "abc"
patched_filter.return_value = asyncio.Future()
patched_filter.return_value.set_result(connect_response)
- filter_id = await self.connector.make_filter(self.api, self.filter_json)
+ filter_id = await connector.make_filter(
+ connector.connection, self.filter_json
+ )
assert filter_id == 10
assert patched_filter.called
- async def test_connect(self):
+ async def test_exchange_keys(self, mocker, connector):
+
+ connector.room_ids = {"main": "!aroomid:localhost"}
+
+ patched_send_to_device = mocker.patch(
+ api_string.format("send_to_device_messages"), return_value=asyncio.Future()
+ )
+ patched_send_to_device.return_value.set_result(None)
+
+ mocker.patch(api_string.format("should_upload_keys"), return_value=True)
+ patched_keys_upload = mocker.patch(
+ api_string.format("keys_upload"), return_value=asyncio.Future()
+ )
+ patched_keys_upload.return_value.set_result(None)
+
+ mocker.patch(api_string.format("should_query_keys"), return_value=True)
+ patched_keys_query = mocker.patch(
+ api_string.format("keys_query"), return_value=asyncio.Future()
+ )
+ patched_keys_query.return_value.set_result(None)
+
+ mocker.patch(api_string.format("should_claim_keys"), return_value=True)
+ patched_keys_claim = mocker.patch(
+ api_string.format("keys_claim"), return_value=asyncio.Future()
+ )
+ patched_keys_claim.return_value.set_result(None)
+
+ patched_missing_sessions = mocker.patch(
+ api_string.format("get_missing_sessions"), return_value=None
+ )
+
+ await connector.exchange_keys(initial_sync=True)
+
+ assert patched_send_to_device.called
+ assert patched_keys_upload.called
+ assert patched_keys_query.called
+ patched_keys_claim.assert_called_once_with(patched_missing_sessions())
+
+ patched_get_users = mocker.patch(
+ api_string.format("get_users_for_key_claiming"), return_value=None
+ )
+
+ await connector.exchange_keys(initial_sync=False)
+
+ assert patched_send_to_device.called
+ assert patched_keys_upload.called
+ assert patched_keys_query.called
+ patched_keys_claim.assert_called_with(patched_get_users())
+
+ async def test_connect(self, mocker, caplog, connector):
with amock.patch(api_string.format("login")) as patched_login, amock.patch(
api_string.format("join")
) as patched_join, amock.patch(
@@ -249,6 +295,20 @@ async def test_connect(self):
) as patched_get_nick, amock.patch(
api_string.format("set_displayname")
) as patch_set_nick, amock.patch(
+ api_string.format("send_to_device_messages")
+ ) as patched_send_to_device, amock.patch(
+ api_string.format("should_upload_keys")
+ ) as patched_should_upload, amock.patch(
+ api_string.format("should_query_keys")
+ ) as patched_should_query, amock.patch(
+ api_string.format("keys_upload")
+ ) as patched_keys_upload, amock.patch(
+ api_string.format("keys_query")
+ ) as patched_keys_query, amock.patch(
+ "pathlib.Path.mkdir"
+ ) as patched_mkdir, amock.patch(
+ "pathlib.Path.is_dir"
+ ) as patched_is_dir, amock.patch(
"aiohttp.ClientSession"
) as patch_cs, OpsDroid() as _:
@@ -292,20 +352,41 @@ async def test_connect(self):
patch_set_nick.return_value = asyncio.Future()
patch_set_nick.return_value.set_result(nio.ProfileSetDisplayNameResponse())
- await self.connector.connect()
+ patched_is_dir.return_value = False
+ patched_mkdir.return_value = None
- assert "!aroomid:localhost" in self.connector.room_ids.values()
+ patched_send_to_device.return_value = asyncio.Future()
+ patched_send_to_device.return_value.set_result(None)
- assert self.connector.connection.token == "arbitrary string1"
+ patched_should_upload.return_value = True
+ patched_keys_upload.return_value = asyncio.Future()
+ patched_keys_upload.return_value.set_result(None)
- assert self.connector.connection.sync_token == "arbitrary string2"
+ patched_should_query.return_value = True
+ patched_keys_query.return_value = asyncio.Future()
+ patched_keys_query.return_value.set_result(None)
- self.connector.nick = "Rabbit Hole"
+ await connector.connect()
+
+ if nio.crypto.ENCRYPTION_ENABLED:
+ assert patched_mkdir.called
+
+ assert patched_send_to_device.called
+ assert patched_keys_upload.called
+ assert patched_keys_query.called
+
+ assert "!aroomid:localhost" in connector.room_ids.values()
+
+ assert connector.connection.token == "arbitrary string1"
+
+ assert connector.connection.sync_token == "arbitrary string2"
+
+ connector.nick = "Rabbit Hole"
patched_get_nick.return_value = asyncio.Future()
patched_get_nick.return_value.set_result("Rabbit Hole")
- await self.connector.connect()
+ await connector.connect()
assert patched_get_nick.called
assert not patch_set_nick.called
@@ -313,9 +394,9 @@ async def test_connect(self):
patched_get_nick.return_value = asyncio.Future()
patched_get_nick.return_value.set_result("Neo")
- self.connector.mxid = "@morpheus:matrix.org"
+ connector.mxid = "@morpheus:matrix.org"
- await self.connector.connect()
+ await connector.connect()
assert patched_get_nick.called
patch_set_nick.assert_called_once_with("Rabbit Hole")
@@ -328,11 +409,11 @@ async def test_connect(self):
patched_sync.return_value.set_result(
nio.SyncError(message=error_message, status_code=error_code)
)
- self._caplog.clear()
- await self.connector.connect()
+ caplog.clear()
+ await connector.connect()
assert [
f"Error during initial sync: {error_message} (status code {error_code})"
- ] == [rec.message for rec in self._caplog.records]
+ ] == [rec.message for rec in caplog.records]
# test join error
patched_sync.return_value = asyncio.Future()
@@ -350,26 +431,26 @@ async def test_connect(self):
patched_join.return_value.set_result(
nio.JoinError(message=error_message, status_code=error_code)
)
- self._caplog.clear()
- await self.connector.connect()
+ caplog.clear()
+ await connector.connect()
assert [
- f"Error while joining room: {self.connector.rooms['main']['alias']}, Message: {error_message} (status code {error_code})"
- ] == [rec.message for rec in self._caplog.records]
+ f"Error while joining room: {connector.rooms['main']['alias']}, Message: {error_message} (status code {error_code})"
+ ] == [rec.message for rec in caplog.records]
# test login error
patched_login.return_value = asyncio.Future()
patched_login.return_value.set_result(
nio.LoginError(message=error_message, status_code=error_code)
)
- self._caplog.clear()
- await self.connector.connect()
+ caplog.clear()
+ await connector.connect()
assert [
f"Error while connecting: {error_message} (status code {error_code})"
- ] == [rec.message for rec in self._caplog.records]
+ ] == [rec.message for rec in caplog.records]
- async def test_parse_sync_response(self):
- self.connector.room_ids = {"main": "!aroomid:localhost"}
- self.connector.filter_id = "arbitrary string"
+ async def test_parse_sync_response(self, connector):
+ connector.room_ids = {"main": "!aroomid:localhost"}
+ connector.filter_id = "arbitrary string"
with amock.patch(api_string.format("get_displayname")) as patched_name:
@@ -378,15 +459,13 @@ async def test_parse_sync_response(self):
nio.ProfileGetDisplayNameResponse("SomeUsersName")
)
- returned_message = await self.connector._parse_sync_response(
- self.sync_return
- )
+ returned_message = await connector._parse_sync_response(self.sync_return)
assert isinstance(returned_message, events.Message)
assert returned_message.text == "LOUD NOISES"
assert returned_message.user == "SomeUsersName"
assert returned_message.target == "!aroomid:localhost"
- assert returned_message.connector == self.connector
+ assert returned_message.connector == connector
raw_message = (
self.sync_return.rooms.join["!aroomid:localhost"]
.timeline.events[0]
@@ -394,14 +473,14 @@ async def test_parse_sync_response(self):
)
assert returned_message.raw_event == raw_message
- returned_message = await self.connector._parse_sync_response(
+ returned_message = await connector._parse_sync_response(
self.sync_return_join
)
assert isinstance(returned_message, events.JoinRoom)
assert returned_message.user == "SomeUsersName"
assert returned_message.target == "!aroomid:localhost"
- assert returned_message.connector == self.connector
+ assert returned_message.connector == connector
raw_message = (
self.sync_return_join.rooms.join["!aroomid:localhost"]
.timeline.events[0]
@@ -410,27 +489,27 @@ async def test_parse_sync_response(self):
raw_message["content"] = {"membership": "join"}
assert returned_message.raw_event == raw_message
- async def test_sync_parse_invites(self):
+ async def test_sync_parse_invites(self, connector):
with amock.patch(api_string.format("get_displayname")) as patched_name:
- self.connector.opsdroid = amock.MagicMock()
- self.connector.opsdroid.parse.return_value = asyncio.Future()
- self.connector.opsdroid.parse.return_value.set_result("")
+ connector.opsdroid = amock.MagicMock()
+ connector.opsdroid.parse.return_value = asyncio.Future()
+ connector.opsdroid.parse.return_value.set_result("")
patched_name.return_value = asyncio.Future()
patched_name.return_value.set_result(
nio.ProfileGetDisplayNameResponse("SomeUsersName")
)
- await self.connector._parse_sync_response(self.sync_invite)
+ await connector._parse_sync_response(self.sync_invite)
- (invite,), _ = self.connector.opsdroid.parse.call_args
+ (invite,), _ = connector.opsdroid.parse.call_args
assert invite.target == "!AWtmOvkBPTCSPbdaHn:localhost"
assert invite.user == "SomeUsersName"
assert invite.user_id == "@neo:matrix.org"
- assert invite.connector is self.connector
+ assert invite.connector is connector
- async def test_get_nick(self):
- self.connector.room_specific_nicks = False
+ async def test_get_nick(self, connector):
+ connector.room_specific_nicks = False
with amock.patch(api_string.format("get_displayname")) as patched_globname:
@@ -440,13 +519,10 @@ async def test_get_nick(self):
patched_globname.return_value.set_result(
nio.ProfileGetDisplayNameResponse(displayname="notaperson")
)
- assert (
- await self.connector.get_nick("#notaroom:localhost", mxid)
- == "notaperson"
- )
+ assert await connector.get_nick("#notaroom:localhost", mxid) == "notaperson"
- async def test_get_room_specific_nick(self):
- self.connector.room_specific_nicks = True
+ async def test_get_room_specific_nick(self, caplog, connector):
+ connector.room_specific_nicks = True
with amock.patch(
api_string.format("get_displayname")
@@ -475,32 +551,26 @@ async def test_get_room_specific_nick(self):
)
)
- assert (
- await self.connector.get_nick("#notaroom:localhost", mxid)
- == "notaperson"
- )
+ assert await connector.get_nick("#notaroom:localhost", mxid) == "notaperson"
- assert await self.connector.get_nick(None, mxid) == "notaperson"
+ assert await connector.get_nick(None, mxid) == "notaperson"
# test member not in list
patched_joined.return_value = asyncio.Future()
patched_joined.return_value.set_result(
nio.JoinedMembersResponse(members=[], room_id="notanid")
)
- assert await self.connector.get_nick("#notaroom:localhost", mxid) == mxid
+ assert await connector.get_nick("#notaroom:localhost", mxid) == mxid
# test JoinedMembersError
patched_joined.return_value = asyncio.Future()
patched_joined.return_value.set_result(
nio.JoinedMembersError(message="Some error", status_code=400)
)
- self._caplog.clear()
- assert (
- await self.connector.get_nick("#notaroom:localhost", mxid)
- == "notaperson"
- )
+ caplog.clear()
+ assert await connector.get_nick("#notaroom:localhost", mxid) == "notaperson"
assert ["Failed to lookup room members for #notaroom:localhost."] == [
- rec.message for rec in self._caplog.records
+ rec.message for rec in caplog.records
]
# test displayname is not set
@@ -508,10 +578,10 @@ async def test_get_room_specific_nick(self):
patched_globname.return_value.set_result(
nio.ProfileGetDisplayNameResponse(displayname=None)
)
- self._caplog.clear()
- assert await self.connector.get_nick("#notaroom:localhost", mxid) == mxid
+ caplog.clear()
+ assert await connector.get_nick("#notaroom:localhost", mxid) == mxid
assert ["Failed to lookup room members for #notaroom:localhost."] == [
- rec.message for rec in self._caplog.records
+ rec.message for rec in caplog.records
]
# test ProfileGetDisplayNameError
@@ -519,14 +589,12 @@ async def test_get_room_specific_nick(self):
patched_globname.return_value.set_result(
nio.ProfileGetDisplayNameError(message="Some error", status_code=400)
)
- self._caplog.clear()
- assert await self.connector.get_nick("#notaroom:localhost", mxid) == mxid
- assert (
- f"Failed to lookup nick for {mxid}." == self._caplog.records[1].message
- )
+ caplog.clear()
+ assert await connector.get_nick("#notaroom:localhost", mxid) == mxid
+ assert f"Failed to lookup nick for {mxid}." == caplog.records[1].message
- async def test_get_nick_not_set(self):
- self.connector.room_specific_nicks = False
+ async def test_get_nick_not_set(self, connector):
+ connector.room_specific_nicks = False
with amock.patch(api_string.format("get_displayname")) as patched_globname:
@@ -537,10 +605,10 @@ async def test_get_nick_not_set(self):
patched_globname.return_value.set_result(
nio.ProfileGetDisplayNameResponse(displayname=None)
)
- assert await self.connector.get_nick("#notaroom:localhost", mxid) == mxid
+ assert await connector.get_nick("#notaroom:localhost", mxid) == mxid
- async def test_get_nick_error(self):
- self.connector.room_specific_nicks = False
+ async def test_get_nick_error(self, connector):
+ connector.room_specific_nicks = False
with amock.patch(api_string.format("get_displayname")) as patched_globname:
@@ -551,38 +619,36 @@ async def test_get_nick_error(self):
patched_globname.return_value.set_result(
nio.ProfileGetDisplayNameError(message="Error")
)
- assert await self.connector.get_nick("#notaroom:localhost", mxid) == mxid
+ assert await connector.get_nick("#notaroom:localhost", mxid) == mxid
- async def test_get_formatted_message_body(self):
+ async def test_get_formatted_message_body(self, connector):
original_html = "<p><h3><no>Hello World</no></h3></p>"
original_body = "### Hello World"
- message = self.connector._get_formatted_message_body(original_html)
+ message = connector._get_formatted_message_body(original_html)
assert message["formatted_body"] == "<h3>Hello World</h3>"
assert message["body"] == "Hello World"
- message = self.connector._get_formatted_message_body(
- original_html, original_body
- )
+ message = connector._get_formatted_message_body(original_html, original_body)
assert message["formatted_body"] == "<h3>Hello World</h3>"
assert message["body"] == "### Hello World"
- async def _get_message(self):
- self.connector.room_ids = {"main": "!aroomid:localhost"}
- self.connector.filter_id = "arbitrary string"
+ async def _get_message(self, connector):
+ connector.room_ids = {"main": "!aroomid:localhost"}
+ connector.filter_id = "arbitrary string"
m = "opsdroid.connector.matrix.ConnectorMatrix.get_nick"
with amock.patch(m) as patched_nick:
patched_nick.return_value = asyncio.Future()
patched_nick.return_value.set_result("Neo")
- return await self.connector._parse_sync_response(self.sync_return)
+ return await connector._parse_sync_response(self.sync_return)
- async def test_send_edited_message(self):
+ async def test_send_edited_message(self, connector):
message = events.EditedMessage(
text="New message",
target="!test:localhost",
linked_event=events.Message("hello", event_id="$hello"),
- connector=self.connector,
+ connector=connector,
)
with amock.patch(
api_string.format("room_send")
@@ -590,7 +656,7 @@ async def test_send_edited_message(self):
patched_send.return_value = asyncio.Future()
patched_send.return_value.set_result({})
- new_content = self.connector._get_formatted_message_body(message.text)
+ new_content = connector._get_formatted_message_body(message.text)
content = {
"msgtype": "m.text",
"m.new_content": new_content,
@@ -601,34 +667,50 @@ async def test_send_edited_message(self):
},
}
- await self.connector.send(message)
+ await connector.send(message)
patched_send.assert_called_once_with(
- message.target, "m.room.message", content
+ message.target,
+ "m.room.message",
+ content,
+ ignore_unverified_devices=True,
)
# Test linked event as event id
message.linked_event = "$hello"
- await self.connector.send(message)
+ await connector.send(message)
- patched_send.assert_called_with(message.target, "m.room.message", content)
+ patched_send.assert_called_with(
+ message.target,
+ "m.room.message",
+ content,
+ ignore_unverified_devices=True,
+ )
# Test responding to an edit
await message.respond(events.EditedMessage("hello"))
- patched_send.assert_called_with(message.target, "m.room.message", content)
+ patched_send.assert_called_with(
+ message.target,
+ "m.room.message",
+ content,
+ ignore_unverified_devices=True,
+ )
- async def test_respond_retry(self):
- message = await self._get_message()
+ async def test_respond_retry(self, connector):
+ message = await self._get_message(connector)
with amock.patch(api_string.format("room_send")) as patched_send:
patched_send.return_value = asyncio.Future()
patched_send.return_value.set_result(None)
- await self.connector.send(message)
+ await connector.send(message)
- message_obj = self.connector._get_formatted_message_body(message.text)
+ message_obj = connector._get_formatted_message_body(message.text)
patched_send.assert_called_once_with(
- message.target, "m.room.message", message_obj
+ message.target,
+ "m.room.message",
+ message_obj,
+ ignore_unverified_devices=True,
)
patched_send.side_effect = [
@@ -636,89 +718,156 @@ async def test_respond_retry(self):
patched_send.return_value,
]
- await self.connector.send(message)
+ await connector.send(message)
- message_obj = self.connector._get_formatted_message_body(message.text)
+ message_obj = connector._get_formatted_message_body(message.text)
patched_send.assert_called_with(
- message.target, "m.room.message", message_obj
+ message.target,
+ "m.room.message",
+ message_obj,
+ ignore_unverified_devices=True,
)
- async def test_respond_room(self):
- message = await self._get_message()
+ async def test_respond_room(self, connector):
+ message = await self._get_message(connector)
with amock.patch(api_string.format("room_send")) as patched_send:
patched_send.return_value = asyncio.Future()
patched_send.return_value.set_result(None)
message.target = "main"
- await self.connector.send(message)
+ await connector.send(message)
- message_obj = self.connector._get_formatted_message_body(message.text)
+ message_obj = connector._get_formatted_message_body(message.text)
patched_send.assert_called_once_with(
- "!aroomid:localhost", "m.room.message", message_obj
+ "!aroomid:localhost",
+ "m.room.message",
+ message_obj,
+ ignore_unverified_devices=True,
)
- async def test_disconnect(self):
- self.connector.connection = amock.MagicMock()
- self.connector.connection.close = amock.CoroutineMock()
- await self.connector.disconnect()
- assert self.connector.connection.close.called
+ async def test_disconnect(self, mocker, connector):
+ patched_close = mocker.patch(
+ api_string.format("close"), return_value=asyncio.Future()
+ )
+ patched_close.return_value.set_result(None)
+
+ await connector.disconnect()
+ assert patched_close.called
- def test_get_roomname(self):
- self.connector.rooms = {
+ def test_get_roomname(self, connector):
+ connector.rooms = {
"main": {"alias": "#notthisroom:localhost"},
"test": {"alias": "#thisroom:localhost"},
}
- self.connector.room_ids = dict(
+ connector.room_ids = dict(
zip(
- self.connector.rooms.keys(),
+ connector.rooms.keys(),
["!aroomid:localhost", "!anotherroomid:localhost"],
)
)
- assert self.connector.get_roomname("#thisroom:localhost") == "test"
- assert self.connector.get_roomname("!aroomid:localhost") == "main"
- assert self.connector.get_roomname("someroom") == "someroom"
+ assert connector.get_roomname("#thisroom:localhost") == "test"
+ assert connector.get_roomname("!aroomid:localhost") == "main"
+ assert connector.get_roomname("someroom") == "someroom"
- def test_lookup_target(self):
- self.connector.room_ids = {"main": "!aroomid:localhost"}
+ def test_lookup_target(self, connector):
+ connector.room_ids = {
+ "main": "!aroomid:localhost",
+ "test": "#test:localhost",
+ }
- assert self.connector.lookup_target("main") == "!aroomid:localhost"
- assert self.connector.lookup_target("#test:localhost") == "!aroomid:localhost"
- assert (
- self.connector.lookup_target("!aroomid:localhost") == "!aroomid:localhost"
- )
+ assert connector.lookup_target("main") == "!aroomid:localhost"
+ assert connector.lookup_target("#test:localhost") == "!aroomid:localhost"
+ assert connector.lookup_target("!aroomid:localhost") == "!aroomid:localhost"
- async def test_respond_image(self):
+ async def test_respond_image(self, mocker, caplog, connector):
gif_bytes = (
b"GIF89a\x01\x00\x01\x00\x00\xff\x00,"
b"\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x00;"
)
image = events.Image(file_bytes=gif_bytes, target="!test:localhost")
- with amock.patch(api_string.format("room_send")) as patched_send, amock.patch(
- api_string.format("upload")
- ) as patched_upload:
- patched_upload.return_value = asyncio.Future()
- patched_upload.return_value.set_result([nio.UploadResponse("mxc://aurl")])
+ patched_send = mocker.patch(
+ api_string.format("room_send"), return_value=asyncio.Future()
+ )
+ patched_send.return_value.set_result(None)
- patched_send.return_value = asyncio.Future()
- patched_send.return_value.set_result(None)
- await self.connector.send(image)
+ connector.connection.store = mocker.MagicMock()
+ connector.connection.store.load_encrypted_rooms.return_value = []
- patched_send.assert_called_once_with(
- room_id="!test:localhost",
- message_type="m.room.message",
- content={
- "body": "opsdroid_upload",
- "info": {"w": 1, "h": 1, "mimetype": "image/gif", "size": 26},
- "msgtype": "m.image",
- "url": "mxc://aurl",
- },
- )
+ patched_upload = mocker.patch(
+ api_string.format("upload"), return_value=asyncio.Future()
+ )
+ patched_upload.return_value.set_result([nio.UploadResponse("mxc://aurl"), None])
+
+ await connector.send(image)
+
+ patched_send.assert_called_once_with(
+ room_id="!test:localhost",
+ message_type="m.room.message",
+ content={
+ "body": "opsdroid_upload",
+ "info": {"w": 1, "h": 1, "mimetype": "image/gif", "size": 26},
+ "msgtype": "m.image",
+ "url": "mxc://aurl",
+ },
+ ignore_unverified_devices=True,
+ )
+
+ file_dict = {
+ "v": "v2",
+ "key": {
+ "kty": "oct",
+ "alg": "A256CTR",
+ "ext": True,
+ "key_ops": ["encrypt", "decrypt"],
+ "k": "randomkey",
+ },
+ "iv": "randomiv",
+ "hashes": {"sha256": "shakey"},
+ "url": "mxc://aurl",
+ "mimetype": "image/gif",
+ }
+
+ connector.connection.store.load_encrypted_rooms.return_value = [
+ "!test:localhost"
+ ]
+ patched_upload.return_value = asyncio.Future()
+ patched_upload.return_value.set_result(
+ [nio.UploadResponse("mxc://aurl"), file_dict]
+ )
- async def test_respond_mxc(self):
+ await connector.send(image)
+
+ patched_send.assert_called_with(
+ room_id="!test:localhost",
+ message_type="m.room.message",
+ content={
+ "body": "opsdroid_upload",
+ "info": {"w": 1, "h": 1, "mimetype": "image/gif", "size": 26},
+ "msgtype": "m.image",
+ "file": file_dict,
+ },
+ ignore_unverified_devices=True,
+ )
+
+ error_message = "Some error message"
+ error_code = 400
+ connector.connection.store.load_encrypted_rooms.return_value = []
+ patched_upload.return_value = asyncio.Future()
+ patched_upload.return_value.set_result(
+ [nio.UploadError(message=error_message, status_code=error_code), None]
+ )
+
+ caplog.clear()
+ await connector.send(image)
+ assert [
+ f"Error while sending the file. Reason: {error_message} (status code {error_code})"
+ ] == [rec.message for rec in caplog.records]
+
+ async def test_respond_mxc(self, connector):
gif_bytes = (
b"GIF89a\x01\x00\x01\x00\x00\xff\x00,"
b"\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x00;"
@@ -734,7 +883,7 @@ async def test_respond_mxc(self):
patched_send.return_value = asyncio.Future()
patched_send.return_value.set_result(None)
- await self.connector.send(image)
+ await connector.send(image)
patched_send.assert_called_once_with(
content={
@@ -745,35 +894,81 @@ async def test_respond_mxc(self):
},
message_type="m.room.message",
room_id="!test:localhost",
+ ignore_unverified_devices=True,
)
- async def test_respond_file(self):
+ async def test_respond_file(self, mocker, connector):
file_event = events.File(
- file_bytes=b"aslkdjlaksdjlkajdlk", target="!test:localhost"
+ file_bytes=b"aslkdjlaksdjlkajdlk",
+ target="!test:localhost",
+ mimetype="text/plain",
)
- with amock.patch(api_string.format("room_send")) as patched_send, amock.patch(
- api_string.format("upload")
- ) as patched_upload:
- patched_upload.return_value = asyncio.Future()
- patched_upload.return_value.set_result([nio.UploadResponse("mxc://aurl")])
+ patched_send = mocker.patch(
+ api_string.format("room_send"), return_value=asyncio.Future()
+ )
+ patched_send.return_value.set_result(None)
- patched_send.return_value = asyncio.Future()
- patched_send.return_value.set_result(None)
- await self.connector.send(file_event)
+ connector.connection.store = mocker.MagicMock()
+ connector.connection.store.load_encrypted_rooms.return_value = []
- patched_send.assert_called_once_with(
- room_id="!test:localhost",
- message_type="m.room.message",
- content={
- "body": "opsdroid_upload",
- "info": {},
- "msgtype": "m.file",
- "url": "mxc://aurl",
- },
- )
+ patched_upload = mocker.patch(
+ api_string.format("upload"), return_value=asyncio.Future()
+ )
+ patched_upload.return_value.set_result([nio.UploadResponse("mxc://aurl"), None])
+
+ await connector.send(file_event)
+
+ patched_send.assert_called_once_with(
+ room_id="!test:localhost",
+ message_type="m.room.message",
+ content={
+ "body": "opsdroid_upload",
+ "info": {"mimetype": "text/plain", "size": 19},
+ "msgtype": "m.file",
+ "url": "mxc://aurl",
+ },
+ ignore_unverified_devices=True,
+ )
+
+ file_dict = {
+ "v": "v2",
+ "key": {
+ "kty": "oct",
+ "alg": "A256CTR",
+ "ext": True,
+ "key_ops": ["encrypt", "decrypt"],
+ "k": "randomkey",
+ },
+ "iv": "randomiv",
+ "hashes": {"sha256": "shakey"},
+ "url": "mxc://aurl",
+ "mimetype": "text/plain",
+ }
+
+ connector.connection.store.load_encrypted_rooms.return_value = [
+ "!test:localhost"
+ ]
+ patched_upload.return_value = asyncio.Future()
+ patched_upload.return_value.set_result(
+ [nio.UploadResponse("mxc://aurl"), file_dict]
+ )
- async def test_respond_new_room(self):
+ await connector.send(file_event)
+
+ patched_send.assert_called_with(
+ room_id="!test:localhost",
+ message_type="m.room.message",
+ content={
+ "body": "opsdroid_upload",
+ "info": {"mimetype": "text/plain", "size": 19},
+ "msgtype": "m.file",
+ "file": file_dict,
+ },
+ ignore_unverified_devices=True,
+ )
+
+ async def test_respond_new_room(self, caplog, connector):
event = events.NewRoom(name="test", target="!test:localhost")
with amock.patch(api_string.format("room_create")) as patched_send, amock.patch(
api_string.format("room_put_state")
@@ -792,7 +987,7 @@ async def test_respond_new_room(self):
nio.RoomCreateResponse(room_id="!test:localhost")
)
- resp = await self.connector.send(event)
+ resp = await connector.send(event)
assert resp == "!test:localhost"
assert patched_send.called_once_with(name="test")
@@ -804,24 +999,24 @@ async def test_respond_new_room(self):
patched_send.return_value.set_result(
nio.RoomCreateError(message=error_message, status_code=error_code)
)
- self._caplog.clear()
- resp = await self.connector.send(event)
+ caplog.clear()
+ resp = await connector.send(event)
assert [
f"Error while creating the room. Reason: {error_message} (status code {error_code})"
- ] == [rec.message for rec in self._caplog.records]
+ ] == [rec.message for rec in caplog.records]
- async def test_respond_room_address(self):
+ async def test_respond_room_address(self, connector):
event = events.RoomAddress("#test:localhost", target="!test:localhost")
with amock.patch(api_string.format("room_put_state")) as patched_send:
patched_send.return_value = asyncio.Future()
patched_send.return_value.set_result({})
- await self.connector.send(event)
+ await connector.send(event)
assert patched_send.called_once_with("!test:localhost", "#test:localhost")
- async def test_respond_join_room(self):
+ async def test_respond_join_room(self, connector):
event = events.JoinRoom(target="#test:localhost")
with amock.patch(
api_string.format("room_resolve_alias")
@@ -838,10 +1033,10 @@ async def test_respond_join_room(self):
patched_send.return_value = asyncio.Future()
patched_send.return_value.set_result({})
- await self.connector.send(event)
+ await connector.send(event)
assert patched_send.called_once_with("#test:localhost")
- async def test_respond_join_room_error(self):
+ async def test_respond_join_room_error(self, caplog, connector):
event = events.JoinRoom(target="#test:localhost")
with amock.patch(
api_string.format("room_resolve_alias")
@@ -859,32 +1054,32 @@ async def test_respond_join_room_error(self):
patched_get_room_id.return_value.set_result(
nio.RoomResolveAliasError(message=error_message, status_code=error_code)
)
- self._caplog.clear()
- await self.connector.send(event)
+ caplog.clear()
+ await connector.send(event)
assert patched_send.called_once_with("#test:localhost")
assert patched_get_room_id.called_once_with("#test:localhost")
assert [
f"Error resolving room id for #test:localhost: {error_message} (status code {error_code})"
- ] == [rec.message for rec in self._caplog.records]
+ ] == [rec.message for rec in caplog.records]
- async def test_respond_user_invite(self):
+ async def test_respond_user_invite(self, connector):
event = events.UserInvite("@test:localhost", target="!test:localhost")
with amock.patch(api_string.format("room_invite")) as patched_send:
patched_send.return_value = asyncio.Future()
patched_send.return_value.set_result({})
- await self.connector.send(event)
+ await connector.send(event)
assert patched_send.called_once_with("#test:localhost", "@test:localhost")
- async def test_respond_room_description(self):
+ async def test_respond_room_description(self, connector):
event = events.RoomDescription("A test room", target="!test:localhost")
with amock.patch(api_string.format("room_put_state")) as patched_send:
patched_send.return_value = asyncio.Future()
patched_send.return_value.set_result({})
- await self.connector.send(event)
+ await connector.send(event)
assert patched_send.called_once_with("#test:localhost", "A test room")
- async def test_respond_room_image(self):
+ async def test_respond_room_image(self, connector):
image = events.Image(url="mxc://aurl")
event = events.RoomImage(image, target="!test:localhost")
@@ -893,16 +1088,17 @@ async def test_respond_room_image(self):
) as patched_send:
patched_send.return_value = asyncio.Future()
patched_send.return_value.set_result({})
- opsdroid.connectors = [self.connector]
- await self.connector.send(event)
+ opsdroid.connectors = [connector]
+ await connector.send(event)
assert patched_send.called_once_with(
"#test:localhost",
"m.room.avatar",
{"url": "mxc://aurl"},
state_key=None,
+ ignore_unverified_devices=True,
)
- async def test_respond_user_role(self):
+ async def test_respond_user_role(self, connector):
existing_power_levels = {
"ban": 50,
"events": {"m.room.name": 100, "m.room.power_levels": 100},
@@ -943,7 +1139,7 @@ async def test_respond_user_role(self):
with amock.patch(
api_string.format("room_get_state_event")
) as patched_power_levels:
- opsdroid.connectors = [self.connector]
+ opsdroid.connectors = [connector]
patched_power_levels.return_value = asyncio.Future()
patched_power_levels.return_value.set_result(
@@ -957,7 +1153,7 @@ async def test_respond_user_role(self):
patched_send.return_value = asyncio.Future()
patched_send.return_value.set_result({})
- await self.connector.send(event)
+ await connector.send(event)
modified_power_levels = deepcopy(existing_power_levels)
modified_power_levels["users"]["@test:localhost"] = pl
@@ -969,12 +1165,9 @@ async def test_respond_user_role(self):
state_key=None,
)
- async def test_send_reaction(self):
+ async def test_send_reaction(self, connector):
message = events.Message(
- "hello",
- event_id="$11111",
- connector=self.connector,
- target="!test:localhost",
+ "hello", event_id="$11111", connector=connector, target="!test:localhost",
)
reaction = events.Reaction("⭕")
with OpsDroid() as _:
@@ -996,12 +1189,9 @@ async def test_send_reaction(self):
"!test:localhost", "m.reaction", content
)
- async def test_send_reply(self):
+ async def test_send_reply(self, connector):
message = events.Message(
- "hello",
- event_id="$11111",
- connector=self.connector,
- target="!test:localhost",
+ "hello", event_id="$11111", connector=connector, target="!test:localhost",
)
reply = events.Reply("reply")
with OpsDroid() as _:
@@ -1011,7 +1201,7 @@ async def test_send_reply(self):
await message.respond(reply)
- content = self.connector._get_formatted_message_body(
+ content = connector._get_formatted_message_body(
reply.text, msgtype="m.text"
)
@@ -1023,16 +1213,16 @@ async def test_send_reply(self):
"!test:localhost", "m.room.message", content
)
- async def test_send_reply_id(self):
+ async def test_send_reply_id(self, connector):
reply = events.Reply("reply", linked_event="$hello", target="!hello:localhost")
with OpsDroid() as _:
with amock.patch(api_string.format("room_send")) as patched_send:
patched_send.return_value = asyncio.Future()
patched_send.return_value.set_result(None)
- await self.connector.send(reply)
+ await connector.send(reply)
- content = self.connector._get_formatted_message_body(
+ content = connector._get_formatted_message_body(
reply.text, msgtype="m.text"
)
@@ -1042,7 +1232,7 @@ async def test_send_reply_id(self):
"!test:localhost", "m.room.message", content
)
- async def test_alias_already_exists(self):
+ async def test_alias_already_exists(self, caplog, connector):
with amock.patch(api_string.format("room_put_state")) as patched_alias:
patched_alias.return_value = asyncio.Future()
@@ -1050,7 +1240,7 @@ async def test_alias_already_exists(self):
nio.RoomPutStateResponse(event_id="some_id", room_id="!test:localhost")
)
- resp = await self.connector._send_room_address(
+ resp = await connector._send_room_address(
events.RoomAddress(target="!test:localhost", address="hello")
)
assert resp.event_id == "some_id"
@@ -1063,28 +1253,28 @@ async def test_alias_already_exists(self):
patched_alias.return_value.set_result(
nio.RoomPutStateError(message=error_message, status_code=error_code)
)
- self._caplog.clear()
- resp = await self.connector._send_room_address(
+ caplog.clear()
+ resp = await connector._send_room_address(
events.RoomAddress(target="!test:localhost", address="hello")
)
assert [
f"Error while setting room alias: {error_message} (status code {error_code})"
- ] == [rec.message for rec in self._caplog.records]
+ ] == [rec.message for rec in caplog.records]
error_code = 409
patched_alias.return_value = asyncio.Future()
patched_alias.return_value.set_result(
nio.RoomPutStateError(message=error_message, status_code=error_code)
)
- self._caplog.clear()
- resp = await self.connector._send_room_address(
+ caplog.clear()
+ resp = await connector._send_room_address(
events.RoomAddress(target="!test:localhost", address="hello")
)
assert ["A room with the alias hello already exists."] == [
- rec.message for rec in self._caplog.records
+ rec.message for rec in caplog.records
]
- async def test_already_in_room(self):
+ async def test_already_in_room(self, caplog, connector):
with amock.patch(api_string.format("room_invite")) as patched_invite:
patched_invite.return_value = asyncio.Future()
@@ -1094,14 +1284,14 @@ async def test_already_in_room(self):
)
)
- self._caplog.clear()
- resp = await self.connector._send_user_invitation(
+ caplog.clear()
+ resp = await connector._send_user_invitation(
events.UserInvite(target="!test:localhost", user_id="@neo:matrix.org")
)
assert resp.message == "@neo.matrix.org is already in the room"
assert [
"Error while inviting user @neo:matrix.org to room !test:localhost: @neo.matrix.org is already in the room (status code 400)"
- ] == [rec.message for rec in self._caplog.records]
+ ] == [rec.message for rec in caplog.records]
patched_invite.return_value = asyncio.Future()
patched_invite.return_value.set_result(
@@ -1109,48 +1299,48 @@ async def test_already_in_room(self):
message="@neo.matrix.org is already in the room", status_code=403
)
)
- resp = await self.connector._send_user_invitation(
+ resp = await connector._send_user_invitation(
events.UserInvite(target="!test:localhost", user_id="@neo:matrix.org")
)
assert resp.message == "@neo.matrix.org is already in the room"
- async def test_invalid_role(self):
- with self.assertRaises(ValueError):
- await self.connector._set_user_role(
+ async def test_invalid_role(self, connector):
+ with pytest.raises(ValueError):
+ await connector._set_user_role(
events.UserRole(
"wibble", target="!test:localhost", user_id="@test:localhost"
)
)
- async def test_no_user_id(self):
- with self.assertRaises(ValueError):
- await self.connector._set_user_role(
+ async def test_no_user_id(self, connector):
+ with pytest.raises(ValueError):
+ await connector._set_user_role(
events.UserRole("wibble", target="!test:localhost")
)
- def test_m_notice(self):
- self.connector.rooms["test"] = {
+ def test_m_notice(self, connector):
+ connector.rooms["test"] = {
"alias": "#test:localhost",
"send_m_notice": True,
}
- assert self.connector.message_type("main") == "m.text"
- assert self.connector.message_type("test") == "m.notice"
- self.connector.send_m_notice = True
- assert self.connector.message_type("main") == "m.notice"
+ assert connector.message_type("main") == "m.text"
+ assert connector.message_type("test") == "m.notice"
+ connector.send_m_notice = True
+ assert connector.message_type("main") == "m.notice"
# Reset the state
- self.connector.send_m_notice = False
- del self.connector.rooms["test"]
+ connector.send_m_notice = False
+ del connector.rooms["test"]
- def test_construct(self):
+ def test_construct(self, connector):
jr = matrix_events.MatrixJoinRules("hello")
assert jr.content["join_rule"] == "hello"
hv = matrix_events.MatrixHistoryVisibility("hello")
assert hv.content["history_visibility"] == "hello"
- async def test_send_generic_event(self):
+ async def test_send_generic_event(self, connector):
event = matrix_events.GenericMatrixRoomEvent(
"opsdroid.dev", {"hello": "world"}, target="!test:localhost"
)
@@ -1159,18 +1349,15 @@ async def test_send_generic_event(self):
patched_send.return_value = asyncio.Future()
patched_send.return_value.set_result(None)
- await self.connector.send(event)
+ await connector.send(event)
assert patched_send.called_once_with(
"!test:localhost", "opsdroid.dev", {"hello": "world"}
)
-class TestEventCreatorMatrixAsync(asynctest.TestCase):
- def setUp(self):
- """Basic setting up for tests"""
- self.connector = setup_connector()
- self.api = nio.AsyncClient("https://notaurl.com", None)
- self.connector.connection = self.api
[email protected]
+class TestEventCreatorMatrixAsync:
+ """Basic setting up for tests"""
@property
def message_json(self):
@@ -1203,6 +1390,37 @@ def file_json(self):
"age": 23394532373,
}
+ @property
+ def encrypted_file_json(self):
+ return {
+ "origin_server_ts": 1534013434328,
+ "sender": "@neo:matrix.org",
+ "event_id": "$1534013434516721kIgMV:matrix.org",
+ "content": {
+ "body": "stereo_reproject.py",
+ "info": {"mimetype": "text/x-python", "size": 1239},
+ "msgtype": "m.file",
+ "file": {
+ "v": "v2",
+ "key": {
+ "kty": "oct",
+ "alg": "A256CTR",
+ "ext": True,
+ "key_ops": ["encrypt", "decrypt"],
+ "k": "randomkey",
+ },
+ "iv": "randomiv",
+ "hashes": {"sha256": "shakey"},
+ "url": "mxc://matrix.org/vtgAIrGtuYJQCXNKRGhVfSMX",
+ "mimetype": "text/x-python",
+ },
+ },
+ "room_id": "!MeRdFpEonLoCwhoHeT:matrix.org",
+ "type": "m.room.message",
+ "unsigned": {"age": 23394532373},
+ "age": 23394532373,
+ }
+
@property
def image_json(self):
return {
@@ -1233,6 +1451,62 @@ def image_json(self):
"age": 2542608318,
}
+ @property
+ def encrypted_image_json(self):
+ return {
+ "content": {
+ "body": "index.png",
+ "info": {
+ "h": 1149,
+ "mimetype": "image/png",
+ "size": 1949708,
+ "thumbnail_info": {
+ "h": 600,
+ "mimetype": "image/png",
+ "size": 568798,
+ "w": 612,
+ },
+ "thumbnail_file": {
+ "v": "v2",
+ "key": {
+ "kty": "oct",
+ "alg": "A256CTR",
+ "ext": True,
+ "key_ops": ["encrypt", "decrypt"],
+ "k": "randomkey",
+ },
+ "iv": "randomiv",
+ "hashes": {"sha256": "shakey"},
+ "url": "mxc://matrix.org/HjHqeJDDxcnOEGydCQlJZQwC",
+ "mimetype": "image/png",
+ },
+ "w": 1172,
+ },
+ "msgtype": "m.image",
+ "file": {
+ "v": "v2",
+ "key": {
+ "kty": "oct",
+ "alg": "A256CTR",
+ "ext": True,
+ "key_ops": ["encrypt", "decrypt"],
+ "k": "randomkey",
+ },
+ "iv": "randomiv",
+ "hashes": {"sha256": "shakey"},
+ "url": "mxc://matrix.org/iDHKYJSQZZrrhOxAkMBMOaeo",
+ "mimetype": "image/png",
+ },
+ },
+ "event_id": "$15548652221495790FYlHC:matrix.org",
+ "origin_server_ts": 1554865222742,
+ "room_id": "!MeRdFpEonLoCwhoHeT:matrix.org",
+ "sender": "@neo:matrix.org",
+ "type": "m.room.message",
+ "unsigned": {"age": 2542608318},
+ "age": 2542608318,
+ }
+
@property
def room_name_json(self):
return {
@@ -1334,22 +1608,17 @@ def join_room_json(self):
"unsigned": {"age": 1234},
}
- @property
- def event_creator(self):
+ @pytest.fixture
+ def event_creator(self, connector):
patched_get_nick = amock.MagicMock()
patched_get_nick.return_value = asyncio.Future()
patched_get_nick.return_value.set_result("Rabbit Hole")
- self.connector.get_nick = patched_get_nick
-
- patched_mxc = amock.MagicMock()
- patched_mxc.return_value = asyncio.Future()
- patched_mxc.return_value.set_result("http://somefileurl")
- self.connector.mxc_to_http = patched_mxc
+ connector.get_nick = patched_get_nick
- return MatrixEventCreator(self.connector)
+ return MatrixEventCreator(connector)
- async def test_create_message(self):
- event = await self.event_creator.create_event(self.message_json, "hello")
+ async def test_create_message(self, connector, event_creator):
+ event = await event_creator.create_event(self.message_json, "hello")
assert isinstance(event, events.Message)
assert event.text == "I just did it manually."
assert event.user == "Rabbit Hole"
@@ -1358,62 +1627,86 @@ async def test_create_message(self):
assert event.event_id == "$15573463541827394vczPd:matrix.org"
assert event.raw_event == self.message_json
- async def test_create_file(self):
- event = await self.event_creator.create_event(self.file_json, "hello")
+ async def test_create_file(self, connector, event_creator):
+ event = await event_creator.create_event(self.file_json, "hello")
+ encrypted_event = await event_creator.create_event(
+ self.encrypted_file_json, "hello"
+ )
+
assert isinstance(event, events.File)
- assert event.url == "http://somefileurl"
- assert event.user == "Rabbit Hole"
- assert event.user_id == "@neo:matrix.org"
- assert event.target == "hello"
- assert event.event_id == "$1534013434516721kIgMV:matrix.org"
+ assert isinstance(encrypted_event, events.File)
+ assert (
+ event.url
+ == encrypted_event.url
+ == "https://notaurl.com/_matrix/media/r0/download/matrix.org/vtgAIrGtuYJQCXNKRGhVfSMX"
+ )
+ assert event.user == encrypted_event.user == "Rabbit Hole"
+ assert event.user_id == encrypted_event.user_id == "@neo:matrix.org"
+ assert event.target == encrypted_event.target == "hello"
+ assert (
+ event.event_id
+ == encrypted_event.event_id
+ == "$1534013434516721kIgMV:matrix.org"
+ )
assert event.raw_event == self.file_json
+ assert encrypted_event.raw_event == self.encrypted_file_json
- async def test_create_image(self):
- event = await self.event_creator.create_event(self.image_json, "hello")
+ async def test_create_image(self, connector, event_creator):
+ event = await event_creator.create_event(self.image_json, "hello")
+ encrypted_event = await event_creator.create_event(
+ self.encrypted_image_json, "hello"
+ )
assert isinstance(event, events.Image)
- assert event.url == "http://somefileurl"
- assert event.user == "Rabbit Hole"
- assert event.user_id == "@neo:matrix.org"
- assert event.target == "hello"
- assert event.event_id == "$15548652221495790FYlHC:matrix.org"
+ assert (
+ event.url
+ == encrypted_event.url
+ == "https://notaurl.com/_matrix/media/r0/download/matrix.org/iDHKYJSQZZrrhOxAkMBMOaeo"
+ )
+ assert event.user == encrypted_event.user == "Rabbit Hole"
+ assert event.user_id == encrypted_event.user_id == "@neo:matrix.org"
+ assert event.target == encrypted_event.target == "hello"
+ assert (
+ event.event_id
+ == encrypted_event.event_id
+ == "$15548652221495790FYlHC:matrix.org"
+ )
assert event.raw_event == self.image_json
+ assert encrypted_event.raw_event == self.encrypted_image_json
- async def test_unsupported_type(self):
+ async def test_unsupported_type(self, connector, event_creator):
json = self.message_json
json["type"] = "wibble"
- event = await self.event_creator.create_event(json, "hello")
+ event = await event_creator.create_event(json, "hello")
assert isinstance(event, matrix_events.GenericMatrixRoomEvent)
assert event.event_type == "wibble"
assert "wibble" in repr(event)
assert event.target in repr(event)
assert str(event.content) in repr(event)
- async def test_unsupported_message_type(self):
+ async def test_unsupported_message_type(self, connector, event_creator):
json = self.message_json
json["content"]["msgtype"] = "wibble"
- event = await self.event_creator.create_event(json, "hello")
+ event = await event_creator.create_event(json, "hello")
assert isinstance(event, matrix_events.GenericMatrixRoomEvent)
assert event.content["msgtype"] == "wibble"
- async def test_room_name(self):
- event = await self.event_creator.create_event(self.room_name_json, "hello")
+ async def test_room_name(self, connector, event_creator):
+ event = await event_creator.create_event(self.room_name_json, "hello")
assert isinstance(event, events.RoomName)
assert event.user == "Rabbit Hole"
assert event.user_id == "@neo:matrix.org"
assert event.event_id == "$3r_PWCT9Vurlv-OFleAsf5gEnoZd-LEGHY6AGqZ5tJg"
assert event.raw_event == self.room_name_json
- async def test_room_description(self):
- event = await self.event_creator.create_event(
- self.room_description_json, "hello"
- )
+ async def test_room_description(self, connector, event_creator):
+ event = await event_creator.create_event(self.room_description_json, "hello")
assert isinstance(event, events.RoomDescription)
assert event.user == "Rabbit Hole"
assert event.user_id == "@neo:matrix.org"
assert event.event_id == "$bEg2XISusHMKLBw9b4lMNpB2r9qYoesp512rKvbo5LA"
assert event.raw_event == self.room_description_json
- async def test_edited_message(self):
+ async def test_edited_message(self, connector, event_creator):
with amock.patch(api_string.format("room_context")) as patched_send:
patched_send.return_value = asyncio.Future()
patched_send.return_value.set_result(
@@ -1427,9 +1720,7 @@ async def test_edited_message(self):
state=[],
)
)
- event = await self.event_creator.create_event(
- self.message_edit_json, "hello"
- )
+ event = await event_creator.create_event(self.message_edit_json, "hello")
assert isinstance(event, events.EditedMessage)
assert event.text == "hello"
@@ -1441,7 +1732,7 @@ async def test_edited_message(self):
assert isinstance(event.linked_event, events.Message)
- async def test_reaction(self):
+ async def test_reaction(self, connector, event_creator):
with amock.patch(api_string.format("room_context")) as patched_send:
patched_send.return_value = asyncio.Future()
patched_send.return_value.set_result(
@@ -1455,7 +1746,7 @@ async def test_reaction(self):
state=[],
)
)
- event = await self.event_creator.create_event(self.reaction_json, "hello")
+ event = await event_creator.create_event(self.reaction_json, "hello")
assert isinstance(event, events.Reaction)
assert event.emoji == "👍"
@@ -1467,7 +1758,7 @@ async def test_reaction(self):
assert isinstance(event.linked_event, events.Message)
- async def test_reply(self):
+ async def test_reply(self, connector, event_creator):
with amock.patch(api_string.format("room_context")) as patched_send:
patched_send.return_value = asyncio.Future()
patched_send.return_value.set_result(
@@ -1481,7 +1772,7 @@ async def test_reply(self):
state=[],
)
)
- event = await self.event_creator.create_event(self.reply_json, "hello")
+ event = await event_creator.create_event(self.reply_json, "hello")
assert isinstance(event, events.Reply)
assert event.text == "hello"
@@ -1493,7 +1784,7 @@ async def test_reply(self):
assert isinstance(event.linked_event, events.Message)
- async def test_create_joinroom(self):
+ async def test_create_joinroom(self, connector, event_creator):
with amock.patch(api_string.format("room_context")) as patched_send:
patched_send.return_value = asyncio.Future()
patched_send.return_value.set_result(
@@ -1508,7 +1799,7 @@ async def test_create_joinroom(self):
)
)
- event = await self.event_creator.create_event(self.join_room_json, "hello")
+ event = await event_creator.create_event(self.join_room_json, "hello")
assert isinstance(event, events.JoinRoom)
assert event.user == "Rabbit Hole"
assert event.user_id == "@example:example.org"
@@ -1529,8 +1820,8 @@ def custom_json(self):
"age": 48926251,
}
- async def test_create_generic(self):
- event = await self.event_creator.create_event(self.custom_json, "hello")
+ async def test_create_generic(self, connector, event_creator):
+ event = await event_creator.create_event(self.custom_json, "hello")
assert isinstance(event, matrix_events.GenericMatrixRoomEvent)
assert event.user == "Rabbit Hole"
assert event.user_id == "@neo:matrix.org"
@@ -1552,8 +1843,8 @@ def custom_state_json(self):
"event_id": "$bEg2XISusHMKLBw9b4lMNpB2r9qYoesp512rKvbo5LA",
}
- async def test_create_generic_state(self):
- event = await self.event_creator.create_event(self.custom_state_json, "hello")
+ async def test_create_generic_state(self, connector, event_creator):
+ event = await event_creator.create_event(self.custom_state_json, "hello")
assert isinstance(event, matrix_events.MatrixStateEvent)
assert event.user == "Rabbit Hole"
assert event.user_id == "@neo:matrix.org"
| Add support for end to end encryption in Matrix Connector
I tried opsdroid in a docker container to connect to a matrix server. So far everything works fine. But I realized that opsdroid does react in unencrypted rooms only. I assume that there is no end-to-end-encryption support built in the matrix connector. Is there a possibility to enable encryption in opsdroid?
| cc @Cadair @SolarDrew
It's something I want to add, but I am unlikely to have time in the near future. To do it we need to change the underlying matrix library.
In the short term if you want to use opsdroid in encrypted rooms the best thing would be to use https://github.com/matrix-org/pantalaimon which is an e2ee proxy.
Is there anything we can do in opsdroid in the short term to warn users about this? Perhaps detect the room is encrypted and log a warning message.
We could emit a warning if we receive encrypted events, would be easier to detect than rooms.
The way I propose we would fix this, is change the underlying layer of the matrix connector to use [matrix-nio](https://github.com/poljar/matrix-nio) which is a more actively maintained Python library, and has built in support for asyncio.
For more details on using `matrix-nio` there is this: https://matrix.org/docs/guides/usage-of-matrix-nio guide. | 2020-06-23T17:29:42 |
opsdroid/opsdroid | 1,555 | opsdroid__opsdroid-1555 | [
"1554"
] | f69714045da88362587ffef10f3dabe928689bf3 | diff --git a/opsdroid/const.py b/opsdroid/const.py
--- a/opsdroid/const.py
+++ b/opsdroid/const.py
@@ -36,9 +36,6 @@
LUISAI_DEFAULT_URL = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/"
-DIALOGFLOW_API_ENDPOINT = "https://api.dialogflow.com/v1/query"
-DIALOGFLOW_API_VERSION = "20150910"
-
WITAI_DEFAULT_VERSION = "20170307"
WITAI_API_ENDPOINT = "https://api.wit.ai/message?"
diff --git a/opsdroid/core.py b/opsdroid/core.py
--- a/opsdroid/core.py
+++ b/opsdroid/core.py
@@ -31,6 +31,7 @@
from opsdroid.parsers.watson import parse_watson
from opsdroid.parsers.rasanlu import parse_rasanlu, train_rasanlu
from opsdroid.parsers.crontab import parse_crontab
+from opsdroid.helper import get_parser_config
_LOGGER = logging.getLogger(__name__)
@@ -315,9 +316,9 @@ async def train_parsers(self, skills):
skills (list): A list of all the loaded skills.
"""
- if "parsers" in self.config:
- parsers = self.config["parsers"] or {}
- rasanlu = parsers.get("rasanlu")
+ if "parsers" in self.modules:
+ parsers = self.modules.get("parsers", {})
+ rasanlu = get_parser_config("rasanlu", parsers)
if rasanlu and rasanlu["enabled"]:
await train_rasanlu(rasanlu, skills)
@@ -448,38 +449,38 @@ async def get_ranked_skills(self, skills, message):
ranked_skills += await parse_regex(self, skills, message)
ranked_skills += await parse_format(self, skills, message)
- if "parsers" in self.config:
+ if "parsers" in self.modules:
_LOGGER.debug(_("Processing parsers..."))
- parsers = self.config["parsers"] or {}
+ parsers = self.modules.get("parsers", {})
- dialogflow = parsers.get("dialogflow")
+ dialogflow = get_parser_config("dialogflow", parsers)
if dialogflow and dialogflow["enabled"]:
_LOGGER.debug(_("Checking dialogflow..."))
ranked_skills += await parse_dialogflow(
self, skills, message, dialogflow
)
- luisai = parsers.get("luisai")
+ luisai = get_parser_config("luisai", parsers)
if luisai and luisai["enabled"]:
_LOGGER.debug(_("Checking luisai..."))
ranked_skills += await parse_luisai(self, skills, message, luisai)
- sapcai = parsers.get("sapcai")
+ sapcai = get_parser_config("sapcai", parsers)
if sapcai and sapcai["enabled"]:
_LOGGER.debug(_("Checking SAPCAI..."))
ranked_skills += await parse_sapcai(self, skills, message, sapcai)
- witai = parsers.get("witai")
+ witai = get_parser_config("witai", parsers)
if witai and witai["enabled"]:
_LOGGER.debug(_("Checking wit.ai..."))
ranked_skills += await parse_witai(self, skills, message, witai)
- watson = parsers.get("watson")
+ watson = get_parser_config("watson", parsers)
if watson and watson["enabled"]:
_LOGGER.debug(_("Checking IBM Watson..."))
ranked_skills += await parse_watson(self, skills, message, watson)
- rasanlu = parsers.get("rasanlu")
+ rasanlu = get_parser_config("rasanlu", parsers)
if rasanlu and rasanlu["enabled"]:
_LOGGER.debug(_("Checking Rasa NLU..."))
ranked_skills += await parse_rasanlu(self, skills, message, rasanlu)
diff --git a/opsdroid/helper.py b/opsdroid/helper.py
--- a/opsdroid/helper.py
+++ b/opsdroid/helper.py
@@ -182,6 +182,28 @@ def add_skill_attributes(func):
return func
+def get_parser_config(name, modules):
+ """Get parser from modules list.
+
+ After the change to the configuration we are adding the "enabled" flag to each
+ active module, this allows us to disable to module if there is any problem with
+ it. This helper method helps getting the config from the list of active parsers.
+
+ Args:
+ name (string): Name of the parser to be fetched.
+ modules (list): List of all active modules.
+
+ Returns:
+ dict or None: The module config or None if not found.
+
+ """
+ if modules:
+ for parser in modules:
+ if parser["config"]["name"] == name:
+ return parser["config"]
+ return None
+
+
def get_config_option(options, config, found, not_found):
"""Get config details and return useful information to list active modules.
| diff --git a/tests/test_core.py b/tests/test_core.py
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -325,9 +325,18 @@ async def test_parse_regex_insensitive(self):
async def test_parse_dialogflow(self):
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path/test.json"
with OpsDroid() as opsdroid:
- opsdroid.config["parsers"] = {
- "dialogflow": {"project-id": "test", "enabled": True}
+ opsdroid.modules = {
+ "parsers": [
+ {
+ "config": {
+ "name": "dialogflow",
+ "project-id": "test",
+ "enabled": True,
+ }
+ }
+ ]
}
+
dialogflow_action = "smalltalk.greetings.whatsup"
skill = amock.CoroutineMock()
mock_connector = Connector({}, opsdroid=opsdroid)
@@ -349,7 +358,9 @@ async def test_parse_dialogflow(self):
async def test_parse_luisai(self):
with OpsDroid() as opsdroid:
- opsdroid.config["parsers"] = {"luisai": {"enabled": True}}
+ opsdroid.modules = {
+ "parsers": [{"config": {"name": "luisai", "enabled": True}}]
+ }
luisai_intent = ""
skill = amock.CoroutineMock()
mock_connector = Connector({}, opsdroid=opsdroid)
@@ -366,7 +377,11 @@ async def test_parse_luisai(self):
async def test_parse_rasanlu(self):
with OpsDroid() as opsdroid:
- opsdroid.config["parsers"] = {"rasanlu": {"enabled": True}}
+ opsdroid.modules = {
+ "parsers": [
+ {"config": {"name": "rasanlu", "module": "", "enabled": True}}
+ ]
+ }
rasanlu_intent = ""
skill = amock.CoroutineMock()
mock_connector = Connector({}, opsdroid=opsdroid)
@@ -380,7 +395,9 @@ async def test_parse_rasanlu(self):
async def test_parse_sapcai(self):
with OpsDroid() as opsdroid:
- opsdroid.config["parsers"] = {"sapcai": {"enabled": True}}
+ opsdroid.modules = {
+ "parsers": [{"config": {"name": "sapcai", "enabled": True}}]
+ }
sapcai_intent = ""
skill = amock.CoroutineMock()
mock_connector = Connector({}, opsdroid=opsdroid)
@@ -394,7 +411,9 @@ async def test_parse_sapcai(self):
async def test_parse_watson(self):
with OpsDroid() as opsdroid:
- opsdroid.config["parsers"] = {"watson": {"enabled": True}}
+ opsdroid.modules = {
+ "parsers": [{"config": {"name": "watson", "enabled": True}}]
+ }
watson_intent = ""
skill = amock.CoroutineMock()
mock_connector = Connector({}, opsdroid=opsdroid)
@@ -406,7 +425,9 @@ async def test_parse_watson(self):
async def test_parse_witai(self):
with OpsDroid() as opsdroid:
- opsdroid.config["parsers"] = {"witai": {"enabled": True}}
+ opsdroid.modules = {
+ "parsers": [{"config": {"name": "witai", "enabled": True}}]
+ }
witai_intent = ""
skill = amock.CoroutineMock()
mock_connector = Connector({}, opsdroid=opsdroid)
@@ -526,7 +547,9 @@ async def test_start_databases(self):
async def test_train_rasanlu(self):
with OpsDroid() as opsdroid:
- opsdroid.config["parsers"] = {"rasanlu": {"enabled": True}}
+ opsdroid.modules = {
+ "parsers": [{"config": {"name": "rasanlu", "enabled": True}}]
+ }
with amock.patch("opsdroid.parsers.rasanlu.train_rasanlu"):
await opsdroid.train_parsers({})
diff --git a/tests/test_helper.py b/tests/test_helper.py
--- a/tests/test_helper.py
+++ b/tests/test_helper.py
@@ -4,6 +4,7 @@
import tempfile
import unittest
import unittest.mock as mock
+import pytest
from opsdroid.helper import (
del_rw,
@@ -15,6 +16,7 @@
JSONDecoder,
convert_dictionary,
get_config_option,
+ get_parser_config,
)
@@ -167,3 +169,54 @@ def test_dict_to_datetime(self):
decoder = JSONDecoder()
obj = decoder(test_obj)
self.assertEqual(datetime.datetime(2018, 10, 2, 0, 41, 17, 74644), obj)
+
+
+def test_get_parser_config():
+ parsers = [
+ {
+ "name": "dialogflow",
+ "module": "",
+ "config": {
+ "name": "dialogflow",
+ "module": "",
+ "project-id": "test-ddd33",
+ "type": "parsers",
+ "enabled": True,
+ "entrypoint": None,
+ "is_builtin": "",
+ "module_path": "opsdroid.parsers.dialogflow",
+ "install_path": "",
+ "branch": "master",
+ },
+ "intents": None,
+ },
+ {
+ "name": "regex",
+ "module": "",
+ "config": {
+ "name": "regex",
+ "module": "",
+ "type": "parsers",
+ "enabled": True,
+ "entrypoint": None,
+ "is_builtin": "",
+ "module_path": "opsdroid.parsers.regex",
+ "install_path": "",
+ "branch": "master",
+ },
+ "intents": None,
+ },
+ ]
+
+ dialogflow_config = get_parser_config("dialogflow", parsers)
+
+ assert dialogflow_config
+ assert dialogflow_config["name"] == "dialogflow"
+
+
+def test_get_parser_config_none():
+ parsers = {}
+
+ config = get_parser_config("dialogflow", parsers)
+
+ assert not config
| Parsers raising KeyError if enabled flag is not set in config
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://riot.im/app/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
While testing the new version of dialogflow, the parser breaks opsdroid if we don't have the `enabled` flag set on the config. Oddly enough when opsdroid loads dialogflow we can see that enabled is being set by `opsdroid.loader.setup_module_config`
```python
INFO opsdroid.loader: {'name': 'dialogflow', 'module': '', 'project-id': 'test-ddd33', 'type': 'parsers', 'enabled': True, 'entrypoint': None, 'is_builtin': ModuleSpec(name='opsdroid.parsers.dialogflow', loader=<_frozen_importlib_external.SourceFileLoader object at 0x108bf8e10>, origin='/Users/fabiorosado/Documents/GitHub.tmp/opsdroid/opsdroid/parsers/dialogflow.py'), 'module_path': 'opsdroid.parsers.dialogflow', 'install_path': '/Users/fabiorosado/Library/Application Support/opsdroid/opsdroid-modules/parsers/dialogflow', 'branch': 'master'}
```
## Steps to Reproduce
- Setup dialogflow flow
- run opsdroid
- exception occurs
## Expected Functionality
- opsdroid should parse message
## Experienced Functionality
KeyError exception raised on `opsdroid.core.get_ranked_skills`.
<details>
<summary>Debug Log</summary>
```python
INFO opsdroid.logging: ========================================
INFO opsdroid.logging: Started opsdroid v0.8.1+833.g5c8dbb7.dirty.
INFO opsdroid: ========================================
INFO opsdroid: You can customise your opsdroid by modifying your configuration.yaml.
INFO opsdroid: Read more at: http://opsdroid.readthedocs.io/#configuration
INFO opsdroid: Watch the Get Started Videos at: http://bit.ly/2fnC0Fh
INFO opsdroid: Install Opsdroid Desktop at:
https://github.com/opsdroid/opsdroid-desktop/releases
INFO opsdroid: ========================================
DEBUG asyncio: Using selector: KqueueSelector
DEBUG opsdroid.loader: Loaded loader.
DEBUG opsdroid.loader: Loading modules from config...
WARNING opsdroid.loader: No databases in configuration. This will cause skills which store things in memory to lose data when opsdroid is restarted.
DEBUG opsdroid.loader: Loading parsers modules...
DEBUG opsdroid.loader: Loaded parsers: opsdroid.parsers.dialogflow.
DEBUG opsdroid.loader: Loading skill modules...
DEBUG opsdroid.loader: Updating dance...
DEBUG opsdroid.loader: b'Already up to date.'
DEBUG opsdroid.loader: b'Current branch master is up to date.'
DEBUG opsdroid.loader: Couldn't find the file requirements.txt, skipping.
DEBUG opsdroid.loader: Loaded skill: opsdroid-modules.skill.dance.
DEBUG opsdroid.loader: Updating hello...
DEBUG opsdroid.loader: b'Already up to date.'
DEBUG opsdroid.loader: b'Current branch master is up to date.'
DEBUG opsdroid.loader: Couldn't find the file requirements.txt, skipping.
DEBUG opsdroid.loader: Loaded skill: opsdroid-modules.skill.hello.
DEBUG opsdroid.loader: Updating loudnoises...
DEBUG opsdroid.loader: b'Already up to date.'
DEBUG opsdroid.loader: b'Current branch master is up to date.'
DEBUG opsdroid.loader: Couldn't find the file requirements.txt, skipping.
DEBUG opsdroid.loader: Loaded skill: opsdroid-modules.skill.loudnoises.
DEBUG opsdroid.loader: Updating seen...
DEBUG opsdroid.loader: b'Already up to date.'
DEBUG opsdroid.loader: b'Current branch master is up to date.'
DEBUG opsdroid.loader: b'Processing /Users/fabiorosado/Library/Caches/pip/wheels/c8/61/2f/47076152dc9487142c2ae48754c87539ff0993decf0fc2f198/ago-0.0.93-py3-none-any.whl'
DEBUG opsdroid.loader: b'Installing collected packages: ago'
DEBUG opsdroid.loader: b'Successfully installed ago-0.0.93'
DEBUG opsdroid.loader: b'WARNING: Target directory /Users/fabiorosado/Library/Application Support/opsdroid/site-packages/ago.py already exists. Specify --upgrade to force replacement.'
DEBUG opsdroid.loader: b'WARNING: Target directory /Users/fabiorosado/Library/Application Support/opsdroid/site-packages/__pycache__ already exists. Specify --upgrade to force replacement.'
DEBUG opsdroid.loader: b'WARNING: Target directory /Users/fabiorosado/Library/Application Support/opsdroid/site-packages/ago-0.0.93.dist-info already exists. Specify --upgrade to force replacement.'
DEBUG opsdroid.loader: Loaded skill: opsdroid-modules.skill.seen.
DEBUG opsdroid.loader: Loading connector modules...
DEBUG opsdroid.loader: Loaded connector: opsdroid.connector.websocket.
DEBUG opsdroid.loader: Loaded connector: opsdroid.connector.shell.
DEBUG opsdroid.core: Loaded 4 skills.
DEBUG opsdroid.connector.websocket: Starting Websocket connector.
DEBUG opsdroid.connector.shell: Loaded shell Connector.
DEBUG opsdroid.connector.shell: Connecting to shell.
INFO opsdroid.web: Started web server on http://0.0.0.0:8080
INFO opsdroid.core: Opsdroid is now running, press ctrl+c to exit.
opsdroid> DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
hi
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=hi)>.
DEBUG opsdroid.core: Processing parsers...
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
DEBUG asyncio: Using selector: KqueueSelector
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/Users/fabiorosado/Documents/GitHub.tmp/opsdroid/opsdroid/__main__.py", line 12, in <module>
init()
File "/Users/fabiorosado/Documents/GitHub.tmp/opsdroid/opsdroid/__main__.py", line 9, in init
opsdroid.cli.cli()
File "/Users/fabiorosado/.local/share/virtualenvs/opsdroid-AmeH9qot/lib/python3.7/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/Users/fabiorosado/.local/share/virtualenvs/opsdroid-AmeH9qot/lib/python3.7/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/Users/fabiorosado/.local/share/virtualenvs/opsdroid-AmeH9qot/lib/python3.7/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/fabiorosado/.local/share/virtualenvs/opsdroid-AmeH9qot/lib/python3.7/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/fabiorosado/.local/share/virtualenvs/opsdroid-AmeH9qot/lib/python3.7/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/Users/fabiorosado/Documents/GitHub.tmp/opsdroid/opsdroid/cli/start.py", line 42, in start
opsdroid.run()
File "/Users/fabiorosado/Documents/GitHub.tmp/opsdroid/opsdroid/core.py", line 165, in run
self.eventloop.run_until_complete(asyncio.gather(*pending))
File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 583, in run_until_complete
return future.result()
File "/Users/fabiorosado/Documents/GitHub.tmp/opsdroid/opsdroid/connector/shell/__init__.py", line 93, in _parse_message
await self.parseloop()
File "/Users/fabiorosado/Documents/GitHub.tmp/opsdroid/opsdroid/connector/shell/__init__.py", line 88, in parseloop
await self.opsdroid.parse(message)
File "/Users/fabiorosado/Documents/GitHub.tmp/opsdroid/opsdroid/core.py", line 498, in parse
ranked_skills = await self.get_ranked_skills(unconstrained_skills, event)
File "/Users/fabiorosado/Documents/GitHub.tmp/opsdroid/opsdroid/core.py", line 429, in get_ranked_skills
if dialogflow and dialogflow["enabled"]:
KeyError: 'enabled'
ERROR: Unhandled exception in opsdroid, exiting...
ERROR: Unhandled exception in opsdroid, exiting...
```
</details>
## Versions
- **Opsdroid version:** opsdroid v0.8.1+833.g5c8dbb7.dirty.
- **Python version:** Python 3.8.1
- **OS/Docker version:** MacOs Catalina
## Configuration File
Please include your version of the configuration file below.
```yaml
parsers:
dialogflow:
project-id: test-ddd33
```
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| We should also check if the envvar `GOOGLE_APPLICATION_CREDENTIALS` exists and if not we should log it. Currently we are [raising a warning](https://github.com/opsdroid/opsdroid/blob/f69714045da88362587ffef10f3dabe928689bf3/opsdroid/parsers/dialogflow.py#L55) and opsdroid handles this error and doesn't send the warning message.
If that envvar doesn't exist the user should be warned about that but opsdroid should still run fine.
After digging further the issue seems to happen on every connector. I'm working on a fix right now | 2020-07-01T11:16:54 |
opsdroid/opsdroid | 1,594 | opsdroid__opsdroid-1594 | [
"1229",
"1129"
] | 12e5025b8bed3f6b21cc8ff92dbe5398fb014a26 | diff --git a/opsdroid/connector/slack/__init__.py b/opsdroid/connector/slack/__init__.py
--- a/opsdroid/connector/slack/__init__.py
+++ b/opsdroid/connector/slack/__init__.py
@@ -32,6 +32,7 @@
"icon-emoji": str,
"connect-timeout": int,
"chat-as-user": bool,
+ "start_thread": bool,
}
@@ -48,6 +49,7 @@ def __init__(self, config, opsdroid=None):
self.token = config["token"]
self.timeout = config.get("connect-timeout", 10)
self.chat_as_user = config.get("chat-as-user", False)
+ self.start_thread = config.get("start_thread", False)
self.ssl_context = ssl.create_default_context(cafile=certifi.where())
self.slack = slack.WebClient(
token=self.token,
@@ -130,15 +132,27 @@ async def _send_message(self, message):
_LOGGER.debug(
_("Responding with: '%s' in room %s."), message.text, message.target
)
+ data = {
+ "channel": message.target,
+ "text": message.text,
+ "as_user": self.chat_as_user,
+ "username": self.bot_name,
+ "icon_emoji": self.icon_emoji,
+ }
+
+ if message.linked_event:
+ if "thread_ts" in message.linked_event.raw_event:
+ if (
+ message.linked_event.event_id
+ != message.linked_event.raw_event["thread_ts"]
+ ):
+ # Linked Event is inside a thread
+ data["thread_ts"] = message.linked_event.raw_event["thread_ts"]
+ elif self.start_thread:
+ data["thread_ts"] = message.linked_event.event_id
+
await self.slack.api_call(
- "chat.postMessage",
- data={
- "channel": message.target,
- "text": message.text,
- "as_user": self.chat_as_user,
- "username": self.bot_name,
- "icon_emoji": self.icon_emoji,
- },
+ "chat.postMessage", data=data,
)
@register_event(Blocks)
| diff --git a/tests/test_connector_slack.py b/tests/test_connector_slack.py
--- a/tests/test_connector_slack.py
+++ b/tests/test_connector_slack.py
@@ -163,10 +163,68 @@ async def test_respond(self):
connector = ConnectorSlack({"token": "abc123"}, opsdroid=self.od)
connector.slack.api_call = amock.CoroutineMock()
await connector.send(
- events.Message(text="test", user="user", target="room", connector=connector)
+ events.Message(
+ text="test", user="user", target="room", connector=connector,
+ )
)
self.assertTrue(connector.slack.api_call.called)
+ async def test_send_message_inside_thread(self):
+ connector = ConnectorSlack({"token": "abc123"}, opsdroid=self.od)
+ connector.slack.api_call = amock.CoroutineMock()
+ linked_event = events.Message(
+ text="linked text", raw_event={"thread_ts": "1582838099.000600"}
+ )
+ message = events.Message(
+ text="test",
+ user="user",
+ target="room",
+ connector=connector,
+ linked_event=linked_event,
+ event_id="1582838099.000601",
+ )
+
+ await connector.send(message)
+ connector.slack.api_call.assert_called_once_with(
+ "chat.postMessage",
+ data={
+ "channel": "room",
+ "text": "test",
+ "as_user": False,
+ "username": "opsdroid",
+ "icon_emoji": ":robot_face:",
+ "thread_ts": "1582838099.000600",
+ },
+ )
+
+ async def test_send_message_start_thread_is_true(self):
+ connector = ConnectorSlack({"token": "abc123"}, opsdroid=self.od)
+ connector.slack.api_call = amock.CoroutineMock()
+ connector.start_thread = True
+ event_id = "1582838099.000601"
+ linked_event = events.Message(
+ text="linked text", event_id=event_id, raw_event={}
+ )
+ message = events.Message(
+ text="test",
+ user="user",
+ target="room",
+ connector=connector,
+ linked_event=linked_event,
+ )
+ await connector.send(message)
+ connector.slack.api_call.assert_called_once_with(
+ "chat.postMessage",
+ data={
+ "channel": "room",
+ "text": "test",
+ "as_user": False,
+ "username": "opsdroid",
+ "icon_emoji": ":robot_face:",
+ "thread_ts": "1582838099.000601",
+ },
+ )
+
async def test_send_blocks(self):
connector = ConnectorSlack({"token": "abc123"}, opsdroid=self.od)
connector.slack.api_call = amock.CoroutineMock()
| Ability to send messages to threads
# Description
In Slack there is the ability to do threaded messaging. It would be nice to be able to send a message into a thread from the original message.
## Steps to Reproduce
Feature Enhancement
## Expected Functionality
Send a message and be able to say "attach it to this thread".
Possible approach:
```
async def send_message(self, message, thread=None):
```
## Experienced Functionality
Message is attached to the thread
## Versions
- **Opsdroid version:** v0.16.0+77.g17247f9
- **Python version:** 3.7.3
- **OS/Docker version:** Windows 10
## Configuration File
Please include your version of the configuration file below.
```yaml
# Your code goes here.
```
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
Make remaining logging messages translatable
## Description
I searched for `_LOGGER` in VS Code and it yielded 322 results, out of which about 100 were relevant and not yet translatable. I wrapped all of them in `_(<string>)` and tested after that. Some of the logging calls with more than two arguments caused some tests to fail after that, so I reverted the changes, ultimately changing about ~50 calls. I also ran `black` manually as per @jos3p's [suggestion](https://github.com/opsdroid/opsdroid/issues/1128#issuecomment-538653664) since I had some issues with `pre-commit`.
Fixes #1128
## Status
**READY**
## Type of change
- New feature (non-breaking change which adds functionality)
# How Has This Been Tested?
I followed the [contributing guide]https://opsdroid.readthedocs.io/en/latest/contributing/l), i.e.:
`pip install -U pre-commit`
`pre-commit install`
`pip install -U tox`
`tox`
As explained in the description, some of the tests failed after changing ALL the logging messages to be wrapped inside `_()`, so I reverted the changes on those to achieve the same testing results as before the changes.
# Checklist:
- [X] I have performed a self-review of my own code
- [X] I have made corresponding changes to the documentation (if applicable)
- [X] I have added tests that prove my fix is effective or that my feature works
- [X] New and existing unit tests pass locally with my changes
| The API I would envisage for this is:
```python
connector.send(Message("my message", target="thread_ts"))
```
The question is how we easily expose the original thread_ts to users. It would currently require a connector specific trip into the `raw_event` attribute.
Maybe we should make connectors which support replies / threads to set the target of the event, so you could do:
```python
connector.send(Message("my message", target=message.target))
```
if fact, if we set `message.target` in the slack connector if the message is in a thread this:
```python
message.respond("Message")
```
would reply in the thread, because of [this](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/events.py#L137) line.
So, in summary:
We should add a check for the existence of the `thread_ts` key in the slack event, and if it exists then set the `.target` attribute of the event the connector emits. This would therefore *by default* respond in the thread.
I generally like this approach.
> This would therefore by default respond in the thread.
I'm not sure I like this. I use multiple Slacks on a day to day basis (hooray 😒) and each has its own etiquette. Some like threads, some hate threads. Therefore I think this should be configurable somehow.
Currently the target gets set to the room. Your proposal is to set the target to the `thread_ts` instead. Maybe we could have a configuration option like `respond-in-thread: false` to toggle this functionality?
Another option (which you might actually be suggesting) would be for the bot to respond to the room by default unless the user message is in an existing thread, in which case you respond in the thread.
The configuration option in that case could be whether you want the bot to start a thread by default or not.
# [Codecov](https://codecov.io/gh/opsdroid/opsdroid/pull/1129?src=pr&el=h1) Report
> Merging [#1129](https://codecov.io/gh/opsdroid/opsdroid/pull/1129?src=pr&el=desc) into [master](https://codecov.io/gh/opsdroid/opsdroid/commit/1a4930c48fa7d39819068647c387d6b8dd4f575d?src=pr&el=desc) will **not change** coverage.
> The diff coverage is `100%`.
[](https://codecov.io/gh/opsdroid/opsdroid/pull/1129?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #1129 +/- ##
=======================================
Coverage 99.91% 99.91%
=======================================
Files 46 46
Lines 2489 2489
=======================================
Hits 2487 2487
Misses 2 2
```
| [Impacted Files](https://codecov.io/gh/opsdroid/opsdroid/pull/1129?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [opsdroid/logging.py](https://codecov.io/gh/opsdroid/opsdroid/pull/1129/diff?src=pr&el=tree#diff-b3BzZHJvaWQvbG9nZ2luZy5weQ==) | `100% <ø> (ø)` | :arrow_up: |
| [opsdroid/connector/github/\_\_init\_\_.py](https://codecov.io/gh/opsdroid/opsdroid/pull/1129/diff?src=pr&el=tree#diff-b3BzZHJvaWQvY29ubmVjdG9yL2dpdGh1Yi9fX2luaXRfXy5weQ==) | `100% <100%> (ø)` | :arrow_up: |
| [opsdroid/connector/facebook/\_\_init\_\_.py](https://codecov.io/gh/opsdroid/opsdroid/pull/1129/diff?src=pr&el=tree#diff-b3BzZHJvaWQvY29ubmVjdG9yL2ZhY2Vib29rL19faW5pdF9fLnB5) | `100% <100%> (ø)` | :arrow_up: |
| [opsdroid/loader.py](https://codecov.io/gh/opsdroid/opsdroid/pull/1129/diff?src=pr&el=tree#diff-b3BzZHJvaWQvbG9hZGVyLnB5) | `99.31% <100%> (ø)` | :arrow_up: |
| [opsdroid/connector/slack/\_\_init\_\_.py](https://codecov.io/gh/opsdroid/opsdroid/pull/1129/diff?src=pr&el=tree#diff-b3BzZHJvaWQvY29ubmVjdG9yL3NsYWNrL19faW5pdF9fLnB5) | `100% <100%> (ø)` | :arrow_up: |
| [opsdroid/connector/rocketchat/\_\_init\_\_.py](https://codecov.io/gh/opsdroid/opsdroid/pull/1129/diff?src=pr&el=tree#diff-b3BzZHJvaWQvY29ubmVjdG9yL3JvY2tldGNoYXQvX19pbml0X18ucHk=) | `100% <100%> (ø)` | :arrow_up: |
| [opsdroid/connector/websocket/\_\_init\_\_.py](https://codecov.io/gh/opsdroid/opsdroid/pull/1129/diff?src=pr&el=tree#diff-b3BzZHJvaWQvY29ubmVjdG9yL3dlYnNvY2tldC9fX2luaXRfXy5weQ==) | `100% <100%> (ø)` | :arrow_up: |
| [opsdroid/connector/gitter/\_\_init\_\_.py](https://codecov.io/gh/opsdroid/opsdroid/pull/1129/diff?src=pr&el=tree#diff-b3BzZHJvaWQvY29ubmVjdG9yL2dpdHRlci9fX2luaXRfXy5weQ==) | `100% <100%> (ø)` | :arrow_up: |
| [opsdroid/connector/webexteams/\_\_init\_\_.py](https://codecov.io/gh/opsdroid/opsdroid/pull/1129/diff?src=pr&el=tree#diff-b3BzZHJvaWQvY29ubmVjdG9yL3dlYmV4dGVhbXMvX19pbml0X18ucHk=) | `100% <100%> (ø)` | :arrow_up: |
| [opsdroid/connector/matrix/connector.py](https://codecov.io/gh/opsdroid/opsdroid/pull/1129/diff?src=pr&el=tree#diff-b3BzZHJvaWQvY29ubmVjdG9yL21hdHJpeC9jb25uZWN0b3IucHk=) | `100% <100%> (ø)` | :arrow_up: |
| ... and [2 more](https://codecov.io/gh/opsdroid/opsdroid/pull/1129/diff?src=pr&el=tree-more) | |
------
[Continue to review full report at Codecov](https://codecov.io/gh/opsdroid/opsdroid/pull/1129?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/opsdroid/opsdroid/pull/1129?src=pr&el=footer). Last update [1a4930c...4343a3f](https://codecov.io/gh/opsdroid/opsdroid/pull/1129?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
Of course, I'll get to it right away!
It should be all done right now. Apologies if I skipped any, although I'm certain that at least 99% of them are translatable now. I also intentionally skipped calls like `_LOGGER.debug(fbmsg)` since I assume that wouldn't change anything.
All done! When you do merge this PR, please let me know if there are any other issues that would be fitting for a beginner/intermediate to work on!
@FabioRosado I know this PR is closed, but I have one last question. As the commits got squished, how should I keep my fork up-to-date? I needed to re-fork, because it said that my fork is 5 commits ahead of the remote.
The way I do it is to open a new branch when I want to work on an issue and then delete the branch when its done. This will still make your fork outdated, you will need to add the opsdroid repository to your remote with the command:
`git remote add upstream https://github.com/opsdroid/opsdroid.git`
then you can do `git pull upstream master` and finally `git push` this will keep your opsdroid fork up to date.
Note that you can call the main opsdroid remote whatever you like, I just tend to call origin(my repo) and upstream (the main repo).
I hope this makes sense, please let me know if you need any help with anything else 😄
Also I was thinking that since you are from Poland you could work on translating opsdroid into Polish maybe? we don't have the issue open but it will count for your hacktoberfest anyway 😄 👍
@FabioRosado Thanks, that makes sense!
And yes, I could certainly work on translating opsdroid into Polish. I can work both on this and on the docstrings to mix things up a little bit if that's okay. :P
Haha of course that would be great 😄
Again let me know if you need any help 👍 | 2020-07-28T09:32:23 |
opsdroid/opsdroid | 1,595 | opsdroid__opsdroid-1595 | [
"1541"
] | 1aa51009a7513f3f28b311807ca9f8782908ca58 | diff --git a/opsdroid/cli/utils.py b/opsdroid/cli/utils.py
--- a/opsdroid/cli/utils.py
+++ b/opsdroid/cli/utils.py
@@ -112,11 +112,11 @@ def check_dependencies():
Returns:
int: the exit code. Returns 1 if the Python version installed is
- below 3.6.
+ below 3.7.
"""
- if sys.version_info.major < 3 or sys.version_info.minor < 6:
- logging.critical(_("Whoops! opsdroid requires python 3.6 or above."))
+ if sys.version_info.major < 3 or sys.version_info.minor < 7:
+ logging.critical(_("Whoops! opsdroid requires python 3.7 or above."))
sys.exit(1)
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -72,7 +72,6 @@ def run(self):
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
- "Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Topic :: Communications :: Chat",
| diff --git a/tests/test_cli.py b/tests/test_cli.py
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -103,12 +103,10 @@ def test_check_version_36(self):
with mock.patch.object(sys, "version_info") as version_info:
version_info.major = 3
version_info.minor = 6
- try:
+ with self.assertRaises(SystemExit):
from opsdroid.cli.utils import check_dependencies
check_dependencies()
- except SystemExit:
- self.fail("check_dependencies() exited unexpectedly!")
def test_check_version_37(self):
with mock.patch.object(sys, "version_info") as version_info:
| Drop Python 3.6
We should now drop Python 3.6 as 0.19 is out.
_Originally posted by @Cadair in https://github.com/opsdroid/opsdroid/issues/1534#issuecomment-644825884_
| This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
| 2020-07-28T10:02:33 |
opsdroid/opsdroid | 1,598 | opsdroid__opsdroid-1598 | [
"1597"
] | 6495f75a09b5aee45af7b6a475b8c9051d9f406f | diff --git a/opsdroid/helper.py b/opsdroid/helper.py
--- a/opsdroid/helper.py
+++ b/opsdroid/helper.py
@@ -63,7 +63,7 @@ def convert_dictionary(modules):
if isinstance(modules, list):
_LOGGER.warning(
- "Opsdroid has a new configuration format since version 0.17.0, we will change your configuration now. Please read on how to migrate in the documentation."
+ "Opsdroid has a new configuration format since version 0.17.0. Please read on how to migrate in the documentation at https://docs.opsdroid.dev/en/stable/configuration.html#migrate-to-new-configuration-layout."
)
for module in modules:
module_copy = module.copy()
| Configuration validator warning could be more useful + accurate
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://riot.im/app/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
The Opsdroid warning "Opsdroid has a new configuration format since version 0.17.0, we will change your configuration now. Please read on how to migrate in the documentation." indicates that the daemon itself will re-write your configuration file, but this is not the case.
It could also include a link to how one might be able to migrate their config-file, saving frantic seconds of Googling :-)
## Steps to Reproduce
Just use an otherwise-working config-file that doesn't conform to the new standard
## Expected Functionality
Warning message should reflect reality (shouldn't say "We will change your config now") and hint to the user where they can directly read up on the new format (such as via including a link)
## Experienced Functionality
Explain what happened instead(Please include the debug log).
## Versions
- **Opsdroid version:** 0.19.0
- **Python version:** 3.8.4
- **OS/Docker version:**
## Configuration File
Please include your version of the configuration file below.
```yaml
# Your code goes here.
```
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| 2020-07-28T19:17:17 |
||
opsdroid/opsdroid | 1,642 | opsdroid__opsdroid-1642 | [
"1631",
"1631"
] | 8926b73db114c674b5b1f5ca77ac58633e72e2ef | diff --git a/opsdroid/core.py b/opsdroid/core.py
--- a/opsdroid/core.py
+++ b/opsdroid/core.py
@@ -58,6 +58,9 @@ def __init__(self, config=None, config_path=None):
self.eventloop.add_signal_handler(
sig, lambda: asyncio.ensure_future(self.handle_signal())
)
+ self.eventloop.add_signal_handler(
+ signal.SIGHUP, lambda: asyncio.ensure_future(self.reload())
+ )
self.eventloop.set_exception_handler(self.handle_async_exception)
self.skills = []
self.memory = Memory()
| diff --git a/tests/test_core.py b/tests/test_core.py
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -7,6 +7,8 @@
import asynctest
import asynctest.mock as amock
import importlib
+import signal
+import threading
import time
from opsdroid.cli.start import configure_lang
@@ -82,6 +84,28 @@ def test_run(self):
self.assertTrue(opsdroid.eventloop.run_until_complete.called)
self.assertTrue(mock_sysexit.called)
+ def test_signals(self):
+ if os.name == "nt":
+ pytest.skip("SIGHUP unsupported on windows")
+ loop = asyncio.get_event_loop()
+
+ def real_test_signals(opsdroid):
+ asyncio.set_event_loop(loop)
+ opsdroid.load = amock.CoroutineMock()
+ opsdroid.unload = amock.CoroutineMock()
+ opsdroid.reload = amock.CoroutineMock()
+ threading.Timer(2, lambda: os.kill(os.getpid(), signal.SIGHUP)).start()
+ threading.Timer(3, lambda: os.kill(os.getpid(), signal.SIGINT)).start()
+ with mock.patch("sys.exit") as mock_sysexit:
+ opsdroid.run()
+ self.assertTrue(opsdroid.reload.called)
+ self.assertTrue(mock_sysexit.called)
+
+ with OpsDroid() as opsdroid:
+ thread = threading.Thread(target=real_test_signals, args=(opsdroid,))
+ thread.start()
+ thread.join()
+
def test_run_cancelled(self):
with OpsDroid() as opsdroid:
opsdroid.is_running = amock.Mock(side_effect=[False, True, False])
| Add a SIGHUP handler to reload opsdroid
Many linux daemons respond to the [`SIGHUP`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGHUP) signal by reloading their configurations. Combined with opsdroid's `no_cache: true` this could be used to reload a skill (or other plugin) while developing it.
This should be added in the same manner as the [existing handlers](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/core.py#L56-L60).
Add a SIGHUP handler to reload opsdroid
Many linux daemons respond to the [`SIGHUP`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGHUP) signal by reloading their configurations. Combined with opsdroid's `no_cache: true` this could be used to reload a skill (or other plugin) while developing it.
This should be added in the same manner as the [existing handlers](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/core.py#L56-L60).
| Hey @Cadair, I would like to work on this issue and fix it. Any starting steps you'd like to suggest? Thanks.
Hey @Cadair, I would like to work on this issue and fix it. Any starting steps you'd like to suggest? Thanks. | 2020-10-01T15:25:28 |
opsdroid/opsdroid | 1,648 | opsdroid__opsdroid-1648 | [
"1502"
] | af00ac9f4eb725b27a08359d90bf80e1cd70588c | diff --git a/opsdroid/conftest.py b/opsdroid/conftest.py
--- a/opsdroid/conftest.py
+++ b/opsdroid/conftest.py
@@ -1,8 +1,29 @@
"""Pytest config for all opsdroid tests."""
+import pytest
+
+import asyncio
+
from opsdroid.testing import opsdroid
+from opsdroid.connector import Connector
from opsdroid.cli.start import configure_lang
__all__ = ["opsdroid"]
configure_lang({})
+
+
[email protected](scope="session")
+def get_connector():
+ def _get_connector(config={}):
+ return Connector(config, opsdroid=opsdroid)
+
+ return _get_connector
+
+
[email protected]_fixture
+def event_loop():
+ """Create an instance of the default event loop for each test case."""
+ loop = asyncio.get_event_loop_policy().new_event_loop()
+ yield loop
+ loop.close()
| diff --git a/opsdroid/tests/test_connector.py b/opsdroid/tests/test_connector.py
new file mode 100644
--- /dev/null
+++ b/opsdroid/tests/test_connector.py
@@ -0,0 +1,114 @@
+import pytest
+
+import asynctest.mock as amock
+
+from opsdroid.connector import Connector, register_event
+from opsdroid.events import Message, Reaction
+
+
+class TestConnectorBaseClass:
+ """Test the opsdroid connector base class."""
+
+ def test_init(self, opsdroid, get_connector):
+ connector = get_connector(config={"example_item": "test"})
+ assert connector.default_target is None
+ assert connector.name == ""
+ assert connector.config["example_item"] == "test"
+
+ def test_property(self, get_connector):
+ connector = get_connector(config={"name": "shell"})
+ assert connector.configuration.get("name") == "shell"
+
+ def test_connect(self, event_loop, get_connector):
+ with pytest.raises(NotImplementedError):
+ event_loop.run_until_complete(get_connector().connect())
+
+ def test_listen(self, event_loop, get_connector):
+ with pytest.raises(NotImplementedError):
+ event_loop.run_until_complete(get_connector().listen())
+
+ def test_respond(self, event_loop, get_connector):
+ with pytest.raises(TypeError):
+ event_loop.run_until_complete(get_connector().send(Message("")))
+
+ def test_unsupported_event(self, event_loop, get_connector):
+ with pytest.raises(TypeError):
+ event_loop.run_until_complete(get_connector().send(Reaction("emoji")))
+
+ def test_incorrect_event(self):
+ class NotAnEvent:
+ pass
+
+ class MyConnector(Connector):
+ @register_event(NotAnEvent)
+ def send_my_event(self, event):
+ pass
+
+ with pytest.raises(TypeError):
+ MyConnector()
+
+ def test_event_subclasses(self):
+ class MyEvent(Message):
+ pass
+
+ class MyConnector(Connector):
+ @register_event(Message, include_subclasses=True)
+ def send_my_event(self, event):
+ pass
+
+ connector = MyConnector({})
+ assert MyEvent in connector.events
+
+
+class TestConnectorAsync:
+ """Test the async methods of the opsdroid connector base class."""
+
+ @pytest.mark.asyncio
+ async def test_disconnect(self, get_connector):
+ res = await get_connector().disconnect()
+ assert res is None
+
+ @pytest.mark.asyncio
+ async def test_send_incorrect_event(self):
+ connector = Connector({"name": "shell"})
+ with pytest.raises(TypeError):
+ await connector.send(object())
+
+ @pytest.mark.asyncio
+ async def test_dep_respond(self, recwarn):
+ connector = Connector({"name": "shell"})
+ with amock.patch("opsdroid.connector.Connector.send") as patched_send:
+ await connector.respond("hello", room="bob")
+
+ assert len(recwarn) >= 1
+ assert recwarn.pop(DeprecationWarning)
+
+ assert patched_send.call_count == 1
+
+ @pytest.mark.asyncio
+ async def test_dep_react(self, get_connector, recwarn):
+ connector = get_connector({"name": "shell"})
+
+ with amock.patch("opsdroid.events.Message.respond") as patched_respond:
+ await connector.react(Message("ori"), "hello")
+
+ assert len(recwarn) >= 1
+ assert recwarn.pop(DeprecationWarning)
+
+ assert patched_respond.call_count == 1
+
+ @pytest.mark.asyncio
+ async def test_deprecated_properties(self, get_connector, recwarn):
+ connector = get_connector({"name": "shell"})
+
+ connector.default_target = "spam"
+ assert connector.default_room == "spam"
+
+ assert len(recwarn) >= 1
+ assert recwarn.pop(DeprecationWarning)
+
+ connector.default_room = "eggs"
+ assert connector.default_target == "eggs"
+
+ assert len(recwarn) >= 1
+ assert recwarn.pop(DeprecationWarning)
diff --git a/tests/test_helper.py b/opsdroid/tests/test_helper.py
similarity index 51%
rename from tests/test_helper.py
rename to opsdroid/tests/test_helper.py
--- a/tests/test_helper.py
+++ b/opsdroid/tests/test_helper.py
@@ -1,10 +1,6 @@
import os
-import asyncio
import datetime
import tempfile
-import unittest
-import unittest.mock as mock
-import pytest
from opsdroid.helper import (
del_rw,
@@ -20,40 +16,39 @@
)
-class TestHelper(unittest.TestCase):
+class TestHelper:
"""Test the opsdroid helper classes."""
- def test_del_rw(self):
- with mock.patch("os.chmod") as mock_chmod, mock.patch(
- "os.remove"
- ) as mock_remove:
- del_rw(None, None, None)
- self.assertTrue(mock_chmod.called)
- self.assertTrue(mock_remove.called)
+ def test_del_rw(self, mocker):
+ mock_chmod = mocker.patch("os.chmod")
+ mock_remove = mocker.patch("os.remove")
+ del_rw(None, None, None)
+ assert mock_chmod.called is True
+ assert mock_remove.called is True
def test_file_is_ipython_notebook(self):
- self.assertTrue(file_is_ipython_notebook("test.ipynb"))
- self.assertFalse(file_is_ipython_notebook("test.py"))
+ assert file_is_ipython_notebook("test.ipynb") is True
+ assert file_is_ipython_notebook("test.py") is False
def test_convert_ipynb_to_script(self):
notebook_path = os.path.abspath("tests/mockmodules/skills/test_notebook.ipynb")
with tempfile.NamedTemporaryFile(mode="w", delete=False) as output_file:
convert_ipynb_to_script(notebook_path, output_file.name)
- self.assertTrue(os.path.getsize(output_file.name) > 0)
+ assert os.path.getsize(output_file.name) > 0
def test_extract_gist_id(self):
- self.assertEqual(
+ assert (
extract_gist_id(
"https://gist.github.com/jacobtomlinson/"
"c9852fa17d3463acc14dca1217d911f6"
- ),
- "c9852fa17d3463acc14dca1217d911f6",
+ )
+ == "c9852fa17d3463acc14dca1217d911f6"
)
- self.assertEqual(
- extract_gist_id("c9852fa17d3463acc14dca1217d911f6"),
- "c9852fa17d3463acc14dca1217d911f6",
+ assert (
+ extract_gist_id("c9852fa17d3463acc14dca1217d911f6")
+ == "c9852fa17d3463acc14dca1217d911f6"
)
def test_opsdroid(self):
@@ -66,8 +61,8 @@ def test_convert_dictionary(self):
{"name": "mattermost", "api-token": "test"},
]
updated_modules = convert_dictionary(modules)
- self.assertEqual(updated_modules["telegram"].get("token"), "test")
- self.assertIn("token", updated_modules["mattermost"])
+ assert updated_modules["telegram"].get("token") == "test"
+ assert "token" in updated_modules["mattermost"]
def test_get_config_option(self):
module_config = {"repo": "test"}
@@ -76,10 +71,10 @@ def test_get_config_option(self):
["repo", "path", "gist"],
module_config,
True,
- f"opsdroid.connectors.websocket",
+ "opsdroid.connectors.websocket",
)
- self.assertEqual(result, (True, "repo", "test"))
+ assert result == (True, "repo", "test")
def test_get_config_no_option(self):
module_config = {
@@ -92,7 +87,7 @@ def test_get_config_no_option(self):
["repo", "path", "gist"], module_config, True, "module"
)
- self.assertEqual(result, ("module", "module", "module"))
+ assert result == ("module", "module", "module")
def test_get_config_option_exception(self):
module_config = None
@@ -100,19 +95,16 @@ def test_get_config_option_exception(self):
result = get_config_option(
["repo", "path", "gist"], module_config, True, "module"
)
- self.assertEqual(result, ("module", "module", "module"))
+ assert result == ("module", "module", "module")
-class TestJSONEncoder(unittest.TestCase):
+class TestJSONEncoder:
"""A JSON Encoder test class.
Test the custom json encoder class.
"""
- def setUp(self):
- self.loop = asyncio.new_event_loop()
-
def test_datetime_to_dict(self):
"""Test default of json encoder class.
@@ -124,31 +116,25 @@ def test_datetime_to_dict(self):
test_obj = datetime.datetime(2018, 10, 2, 0, 41, 17, 74644)
encoder = JSONEncoder()
obj = encoder.default(o=test_obj)
- self.assertEqual(
- {
- "__class__": type_cls.__name__,
- "year": 2018,
- "month": 10,
- "day": 2,
- "hour": 0,
- "minute": 41,
- "second": 17,
- "microsecond": 74644,
- },
- obj,
- )
+ assert {
+ "__class__": type_cls.__name__,
+ "year": 2018,
+ "month": 10,
+ "day": 2,
+ "hour": 0,
+ "minute": 41,
+ "second": 17,
+ "microsecond": 74644,
+ } == obj
-class TestJSONDecoder(unittest.TestCase):
+class TestJSONDecoder:
"""A JSON Decoder test class.
Test the custom json decoder class.
"""
- def setUp(self):
- self.loop = asyncio.new_event_loop()
-
def test_dict_to_datetime(self):
"""Test call of json decoder class.
@@ -168,55 +154,53 @@ def test_dict_to_datetime(self):
}
decoder = JSONDecoder()
obj = decoder(test_obj)
- self.assertEqual(datetime.datetime(2018, 10, 2, 0, 41, 17, 74644), obj)
-
+ assert datetime.datetime(2018, 10, 2, 0, 41, 17, 74644) == obj
-def test_get_parser_config():
- parsers = [
- {
- "name": "dialogflow",
- "module": "",
- "config": {
+ def test_get_parser_config(self):
+ parsers = [
+ {
"name": "dialogflow",
"module": "",
- "project-id": "test-ddd33",
- "type": "parsers",
- "enabled": True,
- "entrypoint": None,
- "is_builtin": "",
- "module_path": "opsdroid.parsers.dialogflow",
- "install_path": "",
- "branch": "master",
+ "config": {
+ "name": "dialogflow",
+ "module": "",
+ "project-id": "test-ddd33",
+ "type": "parsers",
+ "enabled": True,
+ "entrypoint": None,
+ "is_builtin": "",
+ "module_path": "opsdroid.parsers.dialogflow",
+ "install_path": "",
+ "branch": "master",
+ },
+ "intents": None,
},
- "intents": None,
- },
- {
- "name": "regex",
- "module": "",
- "config": {
+ {
"name": "regex",
"module": "",
- "type": "parsers",
- "enabled": True,
- "entrypoint": None,
- "is_builtin": "",
- "module_path": "opsdroid.parsers.regex",
- "install_path": "",
- "branch": "master",
+ "config": {
+ "name": "regex",
+ "module": "",
+ "type": "parsers",
+ "enabled": True,
+ "entrypoint": None,
+ "is_builtin": "",
+ "module_path": "opsdroid.parsers.regex",
+ "install_path": "",
+ "branch": "master",
+ },
+ "intents": None,
},
- "intents": None,
- },
- ]
-
- dialogflow_config = get_parser_config("dialogflow", parsers)
+ ]
- assert dialogflow_config
- assert dialogflow_config["name"] == "dialogflow"
+ dialogflow_config = get_parser_config("dialogflow", parsers)
+ assert dialogflow_config
+ assert dialogflow_config["name"] == "dialogflow"
-def test_get_parser_config_none():
- parsers = {}
+ def test_get_parser_config_none(self):
+ parsers = {}
- config = get_parser_config("dialogflow", parsers)
+ config = get_parser_config("dialogflow", parsers)
- assert not config
+ assert not config
diff --git a/tests/test_connector.py b/tests/test_connector.py
deleted file mode 100644
--- a/tests/test_connector.py
+++ /dev/null
@@ -1,119 +0,0 @@
-import unittest
-import asyncio
-
-import asynctest
-import asynctest.mock as amock
-
-from opsdroid.core import OpsDroid
-from opsdroid.connector import Connector, register_event
-from opsdroid.events import Message, Reaction
-from opsdroid.cli.start import configure_lang
-
-
-class TestConnectorBaseClass(unittest.TestCase):
- """Test the opsdroid connector base class."""
-
- def setUp(self):
- self.loop = asyncio.new_event_loop()
- configure_lang({})
-
- def test_init(self):
- config = {"example_item": "test"}
- connector = Connector(config, opsdroid=OpsDroid())
- self.assertEqual(None, connector.default_target)
- self.assertEqual("", connector.name)
- self.assertEqual("test", connector.config["example_item"])
-
- def test_property(self):
- opsdroid = amock.CoroutineMock()
- connector = Connector({"name": "shell"}, opsdroid=opsdroid)
- self.assertEqual("shell", connector.configuration.get("name"))
-
- def test_connect(self):
- connector = Connector({}, opsdroid=OpsDroid())
- with self.assertRaises(NotImplementedError):
- self.loop.run_until_complete(connector.connect())
-
- def test_listen(self):
- connector = Connector({}, opsdroid=OpsDroid())
- with self.assertRaises(NotImplementedError):
- self.loop.run_until_complete(connector.listen())
-
- def test_respond(self):
- connector = Connector({}, opsdroid=OpsDroid())
- with self.assertRaises(TypeError):
- self.loop.run_until_complete(connector.send(Message("")))
-
- def test_unsupported_event(self):
- connector = Connector({}, opsdroid=OpsDroid())
- with self.assertRaises(TypeError):
- self.loop.run_until_complete(connector.send(Reaction("emoji")))
-
- def test_incorrect_event(self):
- class NotanEvent:
- pass
-
- class MyConnector(Connector):
- @register_event(NotanEvent)
- def send_my_event(self, event):
- pass
-
- with self.assertRaises(TypeError):
- MyConnector()
-
- def test_event_subclasses(self):
- class MyEvent(Message):
- pass
-
- class MyConnector(Connector):
- @register_event(Message, include_subclasses=True)
- def send_my_event(self, event):
- pass
-
- c = MyConnector({})
- assert MyEvent in c.events
-
-
-class TestConnectorAsync(asynctest.TestCase):
- """Test the async methods of the opsdroid connector base class."""
-
- async def setup(self):
- configure_lang({})
-
- async def test_disconnect(self):
- connector = Connector({}, opsdroid=OpsDroid())
- res = await connector.disconnect()
- assert res is None
-
- async def test_send_incorrect_event(self):
- connector = Connector({"name": "shell"})
- with self.assertRaises(TypeError):
- await connector.send(object())
-
- async def test_dep_respond(self):
- connector = Connector({"name": "shell"})
- with amock.patch("opsdroid.connector.Connector.send") as patched_send:
- with self.assertWarns(DeprecationWarning):
- await connector.respond("hello", room="bob")
-
- patched_send.call_count == 1
-
- async def test_dep_react(self):
- connector = Connector({"name": "shell"})
- with amock.patch("opsdroid.events.Message.respond") as patched_respond:
- with self.assertWarns(DeprecationWarning):
- await connector.react(Message("ori"), "hello")
-
- patched_respond.call_count == 1
-
- async def test_depreacted_properties(self):
- connector = Connector({"name": "shell"})
-
- connector.default_target = "spam"
- with self.assertWarns(DeprecationWarning):
- assert connector.default_room == "spam"
-
- with self.assertWarns(DeprecationWarning):
- connector.default_room = "eggs"
-
- assert connector.default_target == "eggs"
| Migrate tests from unittest to pytest
Our existing test suite has been written with the Python [`unittest`](https://docs.python.org/3/library/unittest.html) framework. However, as the test suite has grown and opsdroid has become more complex we are running into issues with the tests. Mainly around setting up and tearing down tests.
The @opsdroid/maintainers team have decided that we want to migrate all tests to be written with the [`pytest`](https://docs.pytest.org/en/latest/contents.html) framework instead so that we can make better use of fixtures. Fixtures are more reusable and portable and should help reduce complexity all over.
There's a lot to be done but it can be done piece by piece as `pytest` can run tests in either format. So if you wish to help in the effort you can start by searching the codebase for unittest suites. These are classes which are subclassed from `unittest.TestCase` or `asynctest.TestCase`, so searching all files for `unittest.TestCase` and `asynctest.TestCase` should be a good place to start.
For detailed information on running the test suite and contributing to opsdroid [see the docs](https://docs.opsdroid.dev/en/latest/contributing/index.html). But the quickest way to get started us with [`tox`](https://tox.readthedocs.io/en/latest/).
```bash
pip install -U tox # You only need to install tox once
tox -e py36,lint # Run the Python 3.6 tests (the lowest version we support) and the linter
```
Once you have found a test suite you wish to convert there are a few steps you need to follow to convert from unittest to pytest:
- Move tests from top level `tests` directory to a nested `tests` directory in opsdroid. Create one in an appropriate place if there isn't already one.
- Remove test from class, pytest tests are just regular functions.
- Change assertions to use regular `assert` or [pytest assertions](https://docs.pytest.org/en/latest/assert.html).
- Mark async tests. In unittest we write async tests by using the `asynctest.TestCase`, but in pytest we decorate our tests with `@pytest.mark.asyncio` instead.
- Move setup operations to fixtures. If a test class contains a `setUp` method anything created here should become a fixture. Check the existing fixtures in `conftest.py` before creating new ones.
- Add docstrings to tests and fixtures to explain what they do. We have been pretty rubbish with this up until now and there are many tests which are not obvious in what they are testing.
Here's an example:
```python
# Before (unittest)
import asynctest
import asynctest.mock as mock
from opsdroid.cli.start import configure_lang
from opsdroid.core import OpsDroid
from opsdroid.events import Message
from opsdroid.matchers import match_regex
from opsdroid import constraints
class TestConstraints(asynctest.TestCase):
"""Test the opsdroid constraint decorators."""
async def setUp(self):
configure_lang({})
async def getMockSkill(self):
async def mockedskill(opsdroid, config, message):
pass
mockedskill.config = {}
return mockedskill
async def test_constrain_rooms_constrains(self):
with OpsDroid() as opsdroid:
skill = await self.getMockSkill()
skill = match_regex(r".*")(skill)
skill = constraints.constrain_rooms(["#general"])(skill)
opsdroid.skills.append(skill)
tasks = await opsdroid.parse(
Message(text="Hello", user="user", target="#random", connector=None)
)
self.assertEqual(len(tasks), 2) # Just match_always and match_event
```
```python
# After (pytest)
import pytest
from opsdroid.cli.start import configure_lang
from opsdroid.core import OpsDroid
from opsdroid.events import Message
from opsdroid.matchers import match_regex
from opsdroid import constraints
configure_lang({}) # Required for our internationalization of error messages
@pytest.fixture
def opsdroid():
"""An instance of the OpsDroid class."""
with OpsDroid() as opsdroid:
yield opsdroid
@pytest.fixture
def mock_skill():
"""A skill which does nothing but follows the skill API."""
async def mockedskill(opsdroid, config, message):
pass
mockedskill.config = {}
return mockedskill
@pytest.mark.asyncio
async def test_constrain_rooms_constrains(opsdroid, mock_skill):
"""Test that with the room constraint a skill is not called."""
skill = match_regex(r".*")(mock_skill)
skill = constraints.constrain_rooms(["#general"])(skill)
opsdroid.skills.append(skill)
tasks = await opsdroid.parse(
Message(text="Hello", user="user", target="#random", connector=None)
)
assert len(tasks) == 2 # Just match_always and match_event
```
Fixtures such as the `opsdroid` fixture will be extremely useful in many tests, so we will be creating some standard ones like this which will be available in all tests. If you write a fixture that you think could be useful in other places please don't hesitate to contribute it to the `conftest.py` file.
If you have any questions you can chat to us on [Matrix](https://riot.im/app/#/room/#opsdroid-general:matrix.org). We encourage you to get started and if you have issues or get stuck then open a [draft PR](https://github.blog/2019-02-14-introducing-draft-pull-requests/) with your changes and we can take a look.
---
When this issue is complete the documentation about the migration should be removed from the testing docs.
| @jacobtomlinson Can I claim it?
@tarangchikhalia you are welcome to start converting some tests and raise a PR. As I explained in the issue there are many tests to convert. So it will take a while and I expect many people will work on it, nobody can specifically claim this issue.
Hi @tarangchikhalia ,
How is this going? Have you written started making some progress on this one?
I found this to be a good first issue for me to start contributing, and I do not want us to do the same thing twice. Please let me know of the modules that you have already worked on so that I can start with something else.
(If there is a different communication channel for questions like this, please direct me to the correct place).
Thanks.
@abhishekmadhu as the issue states please just search the codebase for old tests and convert them over. There are many to do and ideally I would like to see lots of small PRs rather than large ones converting many tests. That way folks don't have to worry about treading on each others toes.
> So if you wish to help in the effort you can start by searching the codebase for unittest suites. These are classes which are subclassed from `unittest.TestCase` or `asynctest.TestCase`, so searching all files for `unittest.TestCase` and `asynctest.TestCase` should be a good place to start.
Hi @jacobtomlinson, I am hoping to contribute on this project starting from migratings tests from unittest to pytest. I have tried my hands on simple database_test module and opened a pull request, however there is a codecoverage fail for that. Does it needs to be attending or I can move to other test modules?
I'm happy to resolve the issue. Please move on to more tests.
Hi, this is my first time contributing and I am eager to help, I tried to convert test_database_sqlite.py to a pytest in a draft request so any feedback on this will be greatly appreciated. Also I just wanted to mention that the "see the docs" link in the first comment leads to a page that does not exist.
Hello @rr3khan thank you for pointing that to us. The [contributing documentation](https://docs.opsdroid.dev/en/stable/contributing.html) is here.
I am off to work but I'll try to have a look at the PR when I come back 😄👍
Fixed the link above, thanks! | 2020-10-02T11:46:22 |
opsdroid/opsdroid | 1,650 | opsdroid__opsdroid-1650 | [
"1610"
] | 60fd745a865cc806766842e983e097a3beb14d2c | diff --git a/opsdroid/core.py b/opsdroid/core.py
--- a/opsdroid/core.py
+++ b/opsdroid/core.py
@@ -21,6 +21,7 @@
from opsdroid.loader import Loader
from opsdroid.web import Web
from opsdroid.parsers.always import parse_always
+from opsdroid.parsers.catchall import parse_catchall
from opsdroid.parsers.event_type import parse_event_type
from opsdroid.parsers.regex import parse_regex
from opsdroid.parsers.parseformat import parse_format
@@ -577,7 +578,8 @@ async def parse(self, event):
)
)
)
-
+ if len(tasks) == 2: # no other skills ran other than 2 default ones
+ tasks.append(self.eventloop.create_task(parse_catchall(self, event)))
await asyncio.gather(*tasks)
return tasks
diff --git a/opsdroid/matchers.py b/opsdroid/matchers.py
--- a/opsdroid/matchers.py
+++ b/opsdroid/matchers.py
@@ -358,3 +358,28 @@ def matcher(func):
if callable(func):
return matcher(func)
return matcher
+
+
+def match_catchall(func=None, messages_only=False):
+ """Return catch-all match decorator.
+
+ Decorator that runs the function only if no other skills were matched for a message
+
+ Args:
+ messages_only(bool): Whether to match only on messages, or on all events. Defaults to False.
+
+ Returns:
+ Decorated Function
+
+ """
+
+ def matcher(func):
+ """Add decorated function to skills list for catch-all matching."""
+ func = add_skill_attributes(func)
+ func.matchers.append({"catchall": True, "messages_only": messages_only})
+ return func
+
+ # Allow for decorator with or without parenthesis as there are no args.
+ if callable(func):
+ return matcher(func)
+ return matcher
diff --git a/opsdroid/parsers/catchall.py b/opsdroid/parsers/catchall.py
new file mode 100644
--- /dev/null
+++ b/opsdroid/parsers/catchall.py
@@ -0,0 +1,20 @@
+"""A helper function for parsing and executing catch-all skills."""
+
+import logging
+
+from opsdroid import events
+
+_LOGGER = logging.getLogger(__name__)
+
+
+async def parse_catchall(opsdroid, event):
+ """Parse an event against catch-all skills, if found."""
+ for skill in opsdroid.skills:
+ for matcher in skill.matchers:
+ if "catchall" in matcher:
+ if (
+ matcher["messages_only"]
+ and isinstance(event, events.Message)
+ or not matcher["messages_only"]
+ ):
+ await opsdroid.run_skill(skill, skill.config, event)
| diff --git a/opsdroid/parsers/tests/test_parser_catchall.py b/opsdroid/parsers/tests/test_parser_catchall.py
new file mode 100644
--- /dev/null
+++ b/opsdroid/parsers/tests/test_parser_catchall.py
@@ -0,0 +1,144 @@
+"""Test the opsdroid catch-all parser."""
+
+import logging
+
+import asynctest.mock as amock
+import pytest
+from opsdroid.cli.start import configure_lang
+from opsdroid.core import OpsDroid
+from opsdroid.events import Message, OpsdroidStarted
+from opsdroid.matchers import match_always, match_catchall
+from opsdroid.parsers.catchall import parse_catchall
+
+pytestmark = pytest.mark.asyncio
+
+configure_lang({})
+
+
+async def getMockSkill():
+ async def mockedskill(config, message):
+ pass
+
+ mockedskill.config = {}
+ return mockedskill
+
+
+async def getRaisingMockSkill():
+ async def mockedskill(config, message):
+ raise Exception()
+
+ mockedskill.config = {}
+ return mockedskill
+
+
+async def test_parse_catchall_decorator_parens():
+ with OpsDroid() as opsdroid:
+ mock_skill = await getMockSkill()
+ opsdroid.skills.append(match_catchall()(mock_skill))
+ opsdroid.run_skill = amock.CoroutineMock()
+
+ mock_connector = amock.CoroutineMock()
+ message = Message(
+ text="Hello world",
+ user="user",
+ target="default",
+ connector=mock_connector,
+ )
+
+ await parse_catchall(opsdroid, message)
+
+ assert opsdroid.run_skill.called
+
+
+async def test_parse_catchall_decorate_no_parens():
+ with OpsDroid() as opsdroid:
+ mock_skill = await getMockSkill()
+ opsdroid.skills.append(match_catchall(mock_skill))
+ opsdroid.run_skill = amock.CoroutineMock()
+
+ mock_connector = amock.CoroutineMock()
+ message = Message(
+ text="Hello world",
+ user="user",
+ target="default",
+ connector=mock_connector,
+ )
+
+ await parse_catchall(opsdroid, message)
+
+ assert opsdroid.run_skill.called
+
+
+async def test_parse_catchall_raises(caplog):
+ caplog.set_level(logging.ERROR)
+ with OpsDroid() as opsdroid:
+ mock_skill = await getRaisingMockSkill()
+ mock_skill.config = {"name": "greetings"}
+ opsdroid.skills.append(match_catchall()(mock_skill))
+ assert len(opsdroid.skills) == 1
+
+ mock_connector = amock.MagicMock()
+ mock_connector.send = amock.CoroutineMock()
+ message = Message(
+ text="Hello world",
+ user="user",
+ target="default",
+ connector=mock_connector,
+ )
+
+ await parse_catchall(opsdroid, message)
+ assert "ERROR" in caplog.text
+
+
+async def test_parse_catchall_not_called():
+ with OpsDroid() as opsdroid:
+ mock_skill = await getMockSkill()
+ catchall_skill = amock.CoroutineMock()
+ opsdroid.skills.append(match_always()(mock_skill))
+ opsdroid.skills.append(match_catchall()(catchall_skill))
+ opsdroid.run_skill = amock.CoroutineMock()
+
+ mock_connector = amock.CoroutineMock()
+ message = Message(
+ text="Hello world",
+ user="user",
+ target="default",
+ connector=mock_connector,
+ )
+
+ await parse_catchall(opsdroid, message)
+
+ assert not catchall_skill.called
+
+
+async def test_parse_catchall_messages_only_default():
+ with OpsDroid() as opsdroid:
+ catchall_skill = await getMockSkill()
+ event = OpsdroidStarted()
+ opsdroid.skills.append(match_catchall()(catchall_skill))
+ opsdroid.run_skill = amock.CoroutineMock()
+
+ await parse_catchall(opsdroid, event)
+
+ assert opsdroid.run_skill.called
+
+
+async def test_parse_catchall_messages_only_enabled():
+ with OpsDroid() as opsdroid:
+ catchall_skill = await getMockSkill()
+ event = OpsdroidStarted()
+ opsdroid.skills.append(match_catchall(messages_only=True)(catchall_skill))
+ opsdroid.run_skill = amock.CoroutineMock()
+
+ mock_connector = amock.CoroutineMock()
+ message = Message(
+ text="Hello world",
+ user="user",
+ target="default",
+ connector=mock_connector,
+ )
+
+ await parse_catchall(opsdroid, event)
+ assert not opsdroid.run_skill.called
+ await parse_catchall(opsdroid, message)
+ assert opsdroid.run_skill.called
diff --git a/tests/test_constraints.py b/tests/test_constraints.py
--- a/tests/test_constraints.py
+++ b/tests/test_constraints.py
@@ -31,7 +31,7 @@ async def test_constrain_rooms_constrains(self):
tasks = await opsdroid.parse(
Message(text="Hello", user="user", target="#random", connector=None)
)
- self.assertEqual(len(tasks), 2) # Just match_always and match_event
+ self.assertEqual(len(tasks), 3) # Just match_always and match_event
async def test_constrain_rooms_skips(self):
with OpsDroid() as opsdroid, mock.patch("opsdroid.parsers.always.parse_always"):
@@ -55,7 +55,7 @@ async def test_constrain_rooms_inverted(self):
tasks = await opsdroid.parse(
Message(text="Hello", user="user", target="#general", connector=None)
)
- self.assertEqual(len(tasks), 2) # Just match_always and match_event
+ self.assertEqual(len(tasks), 3) # Just match_always and match_event
async def test_constrain_users_constrains(self):
with OpsDroid() as opsdroid:
@@ -69,7 +69,7 @@ async def test_constrain_users_constrains(self):
text="Hello", user="otheruser", target="#general", connector=None
)
)
- self.assertEqual(len(tasks), 2) # Just match_always and match_event
+ self.assertEqual(len(tasks), 3) # Just match_always and match_event
async def test_constrain_users_skips(self):
with OpsDroid() as opsdroid:
@@ -93,7 +93,7 @@ async def test_constrain_users_inverted(self):
tasks = await opsdroid.parse(
Message(text="Hello", user="user", target="#general", connector=None)
)
- self.assertEqual(len(tasks), 2) # Just match_always and match_event
+ self.assertEqual(len(tasks), 3) # Just match_always and match_event
async def test_constrain_connectors_constrains(self):
with OpsDroid() as opsdroid:
@@ -109,7 +109,7 @@ async def test_constrain_connectors_constrains(self):
text="Hello", user="user", target="#random", connector=connector
)
)
- self.assertEqual(len(tasks), 2) # Just match_always and match_event
+ self.assertEqual(len(tasks), 3) # Just match_always and match_event
async def test_constrain_connectors_skips(self):
with OpsDroid() as opsdroid:
@@ -141,7 +141,7 @@ async def test_constrain_connectors_inverted(self):
text="Hello", user="user", target="#general", connector=connector
)
)
- self.assertEqual(len(tasks), 2) # Just match_always and match_event
+ self.assertEqual(len(tasks), 3) # Just match_always and match_event
async def test_constraint_can_be_called_after_skip(self):
with OpsDroid() as opsdroid:
@@ -160,7 +160,7 @@ async def test_constraint_can_be_called_after_skip(self):
text="Hello", user="otheruser", target="#general", connector=None
)
)
- self.assertEqual(len(tasks), 2) # Just match_always and match_event
+ self.assertEqual(len(tasks), 3) # Just match_always and match_event
tasks = await opsdroid.parse(
Message(text="Hello", user="user", target="#general", connector=None)
diff --git a/tests/test_core.py b/tests/test_core.py
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -377,7 +377,7 @@ async def test_parse_dialogflow(self):
"opsdroid.parsers.dialogflow.parse_dialogflow"
), amock.patch("opsdroid.parsers.dialogflow.call_dialogflow"):
tasks = await opsdroid.parse(message)
- self.assertEqual(len(tasks), 2)
+ self.assertEqual(len(tasks), 3)
tasks = await opsdroid.parse(message)
self.assertLogs("_LOGGER", "warning")
@@ -399,7 +399,7 @@ async def test_parse_luisai(self):
)
with amock.patch("opsdroid.parsers.luisai.parse_luisai"):
tasks = await opsdroid.parse(message)
- self.assertEqual(len(tasks), 2)
+ self.assertEqual(len(tasks), 3)
async def test_parse_rasanlu(self):
with OpsDroid() as opsdroid:
@@ -417,7 +417,7 @@ async def test_parse_rasanlu(self):
)
with amock.patch("opsdroid.parsers.rasanlu.parse_rasanlu"):
tasks = await opsdroid.parse(message)
- self.assertEqual(len(tasks), 2)
+ self.assertEqual(len(tasks), 3)
async def test_parse_sapcai(self):
with OpsDroid() as opsdroid:
@@ -433,7 +433,7 @@ async def test_parse_sapcai(self):
)
with amock.patch("opsdroid.parsers.sapcai.parse_sapcai"):
tasks = await opsdroid.parse(message)
- self.assertEqual(len(tasks), 2)
+ self.assertEqual(len(tasks), 3)
async def test_parse_watson(self):
with OpsDroid() as opsdroid:
@@ -447,7 +447,7 @@ async def test_parse_watson(self):
message = Message("Hello world", "user", "default", mock_connector)
with amock.patch("opsdroid.parsers.watson.parse_watson"):
tasks = await opsdroid.parse(message)
- self.assertEqual(len(tasks), 2)
+ self.assertEqual(len(tasks), 3)
async def test_parse_witai(self):
with OpsDroid() as opsdroid:
@@ -466,7 +466,7 @@ async def test_parse_witai(self):
)
with amock.patch("opsdroid.parsers.witai.parse_witai"):
tasks = await opsdroid.parse(message)
- self.assertEqual(len(tasks), 2)
+ self.assertEqual(len(tasks), 3)
async def test_send_default_one(self):
with OpsDroid() as opsdroid, amock.patch(
| Feature request: Please consider implementing a 'catch-all' responder
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://riot.im/app/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
I have a skill with many regex matchers, all starting with some flavor of "botname". ex:
```
botname get environment
botname get hostinfo
botname get verbose hostinfo
botname get hosthealth
botname get verbose hosthealth
```
etc, with various complexities of regex applied to capture hostnames, etc. It would be nice to be able to define a 'catchall' matcher that would fire only if it was the only string matched. For example, if a user typed the invalid string:
```
botname gte infohost
```
that would match nothing in the above list. If there was a 'catchall' that was set to match strings for "^botname", it could fire a "print help text" message so long as the string didn't match any of the other responders.
## Versions
- **Opsdroid version:** 0.19.0
- **Python version:** 3.8.4
- **OS/Docker version:**
## Configuration File
n/a
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| This is an example of opsdroid being treated like a command line in your chat client.
Many design decisions in opsdroid were based on moving away from this use case to something more natural where the bot would be in a room with many other people and it would robustly respond to queries like "what is the environment?", "can you tell me the environment?", "please get environment", etc. These kind of requests would be mixed with other chat between colleagues which is not aimed at the bot and the bot would just stay quiet.
One thing that use case didn't consider is someone directly addressing the bot but asking something the bot doesn't understand. For example "botname please get the flargle bargle". In that case the bot is being addressed directly and so it should respond, but the question doesn't match anything.
In #273 we discuss the bot being able to know when it is being spoken to. This would open us up to being able to catch that situation.
Given that many folks seem to use opsdroid as a CLI in chat, rather than a natural language bot, I think it would be reasonable to add a catchall matcher. But we should be thoughtful about users who do have bots in rooms with other conversations going on.
My initial design would be something like this.
```python
class MySkill(Skill):
@match_catchall
async def catchall(self, event):
await event.respond("Sorry I have no idea what you are talking about")
```
The catchall logic would probably go somewhere like `get_ranked_skills`. If the `ranked_skills` list was still empty at the end of the function we would check for the catchall matcher and return that. This does assume only one use of `match_catchall`.
https://github.com/opsdroid/opsdroid/blob/c2792eab5196e2cbbd4f62d1c8e9e70db36d3e36/opsdroid/core.py#L436
This would then support the design from #273 (which would probably be implemented as a constraint in modern opsdroid) where we could do something like this.
```python
class MySkill(Skill):
@match_catchall
@constrain_spoken_to
async def catchall(self, event):
await event.respond("I think you were talking to me, but I have no idea what you're asking")
```
That way the catchall matcher would only trigger if the bot is addressed directly. | 2020-10-02T20:36:16 |
opsdroid/opsdroid | 1,654 | opsdroid__opsdroid-1654 | [
"1446"
] | 9acb47c8a985ab397af098ce27ac168c7c36ddd5 | diff --git a/opsdroid/events.py b/opsdroid/events.py
--- a/opsdroid/events.py
+++ b/opsdroid/events.py
@@ -2,16 +2,19 @@
import asyncio
import io
import logging
+import tempfile
from abc import ABCMeta
from collections import defaultdict
from datetime import datetime
from random import randrange
+from bitstring import BitArray
import aiohttp
-
import puremagic
+import os
from get_image_size import get_image_size_from_bytesio
from opsdroid.helper import get_opsdroid
+from videoprops import get_video_properties
_LOGGER = logging.getLogger(__name__)
@@ -404,6 +407,55 @@ async def get_dimensions(self):
return get_image_size_from_bytesio(io.BytesIO(fbytes), len(fbytes))
+class Video(File):
+ """Event class specifically for video files."""
+
+ async def get_bin(self):
+ """Return the binary representation of video."""
+
+ """
+ The two below lines gets a bitarray of the video bytes.This method enable video bytes to be converted to hex/bin.
+ Doc: https://github.com/scott-griffiths/bitstring/blob/master/doc/bitarray.rst
+ """
+ fbytes = await self.get_file_bytes()
+ my_bit_array = BitArray(fbytes)
+
+ # Return that bitarray
+ return my_bit_array.bin
+
+ async def get_properties(self):
+ """Get the video properties like codec, resolution.Returns Video properties saved in a Dictionary."""
+
+ """
+ NamedTemporaryFile is too hard to use portably when you need to open the file by name after writing it.
+ On posix you can open the file for reading by name without closing it first.
+ But on Windows, To do that you need to close the file first, which means you have to pass delete=False,
+ which in turn means that you get no help in cleaning up the actual file resource.
+ """
+
+ fbytes = await self.get_file_bytes() # get bytes of file
+
+ temp_vid = tempfile.NamedTemporaryFile(
+ prefix="opsdroid_vid_", delete=False
+ ) # create a file to store the bytes
+ temp_vid.write(fbytes)
+ temp_vid.close()
+
+ try:
+ vid_details = get_video_properties(temp_vid.name)
+ os.remove(temp_vid.name) # delete the temp file
+ return vid_details
+ except RuntimeError as error:
+ if "ffmpeg" in str(error).lower():
+ _LOGGER.warning(
+ _(
+ "Video events are not supported unless ffmpeg is installed. Install FFMPEG on your system. Here is the error: "
+ )
+ )
+ _LOGGER.warning(_(error))
+ os.remove(temp_vid.name) # delete the temp file
+
+
class NewRoom(Event):
"""Event class to represent the creation of a new room."""
| diff --git a/tests/test_events.py b/tests/test_events.py
--- a/tests/test_events.py
+++ b/tests/test_events.py
@@ -4,9 +4,9 @@
import asynctest.mock as amock
from opsdroid import events
-from opsdroid.core import OpsDroid
-from opsdroid.connector import Connector
from opsdroid.cli.start import configure_lang
+from opsdroid.connector import Connector
+from opsdroid.core import OpsDroid
class TestEventCreator(asynctest.TestCase):
@@ -353,3 +353,108 @@ async def test_no_mime_type(self):
)
self.assertEqual(await event.get_mimetype(), "")
+
+
+class TestVideo(asynctest.TestCase):
+ """Test the opsdroid Video class"""
+
+ mkv_bytes = b'\x1aE\xdf\xa3\xa3B\x86\x81\x01B\xf7\x81\x01B\xf2\x81\x04B\xf3\x81\x08B\x82\x88matroskaB\x87\x81\x04B\x85\x81\x02\x18S\x80g\x01\x00\x00\x00\x00\x00\x08S\x11M\x9bt\xc1\xbf\x84f\xe0E\xc7M\xbb\x8bS\xab\x84\x15I\xa9fS\xac\x81\xe5M\xbb\x8cS\xab\x84\x16T\xaekS\xac\x82\x01UM\xbb\x8cS\xab\x84\x12T\xc3gS\xac\x82\x01\xe2M\xbb\x8cS\xab\x84\x1cS\xbbkS\xac\x82\x087\xec\x01\x00\x00\x00\x00\x00\x00\x96\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x15I\xa9f\xeb\xbf\x84\x10N\x0e,*\xd7\xb1\x83\x0fB@{\xa9\x85videoM\x80\x8dLavf58.29.100WA\x9aHandBrake 1.3.3 2020061500s\xa4\x90\x9b\xf1\x82\xac\x9a\xfa\n\xbch\xc2\rSf\t8"Da\x88\x08\xb7\x80\x95\xd1\xcf\x9c\x00D\x89\x88@\x8f@\x00\x00\x00\x00\x00\x16T\xaek@\x87\xbf\x84\xb3\xf6V5\xae\x01\x00\x00\x00\x00\x00\x00x\xd7\x81\x01s\xc5\x81\x01\x9c\x81\x00"\xb5\x9c\x83und\x86\x8fV_MPEG4/ISO/AVC\x83\x81\x01#\xe3\x83\x84\x0b\xeb\xc2\x00\xe0\x01\x00\x00\x00\x00\x00\x00\x12\xb0\x81 \xba\x81 T\xb0\x81\x10T\xba\x81\tT\xb2\x81\x03c\xa2\xad\x01M@\x1f\xff\xe1\x00\x1egM@\x1f\xec\xa4\xb7\xfe\x00 \x00\x12\xd4\x18\x18\x19\x00\x00\x03\x00\x01\x00\x00\x03\x00\n\x8f\x181\x96\x01\x00\x04h\xce\x04\xf2\x12T\xc3g@\x82\xbf\x84V\x8d\xc4\xbess\x01\x00\x00\x00\x00\x00\x00.c\xc0\x01\x00\x00\x00\x00\x00\x00\x00g\xc8\x01\x00\x00\x00\x00\x00\x00\x1aE\xa3\x87ENCODERD\x87\x8dLavf58.29.100ss\x01\x00\x00\x00\x00\x00\x00:c\xc0\x01\x00\x00\x00\x00\x00\x00\x04c\xc5\x81\x01g\xc8\x01\x00\x00\x00\x00\x00\x00"E\xa3\x88DURATIOND\x87\x9400:00:01.000000000\x00\x00\x1fC\xb6uE\xc7\xbf\x84J\xfd>P\xe7\x81\x00\xa3Do\x81\x00\x00\x80\x00\x00\x02\xf1\x06\x05\xff\xff\xed\xdcE\xe9\xbd\xe6\xd9H\xb7\x96,\xd8 \xd9#\xee\xefx264 - core 155 r2917 0a84d98 - H.264/MPEG-4 AVC codec - Copyleft 2003-2018 - http://www.videolan.org/x264.html - options: cabac=0 ref=1 deblock=0:0:0 analyse=0x1:0x111 me=hex subme=2 psy=1 psy_rd=1.00:0.00 mixed_ref=0 me_range=16 chroma_me=1 trellis=0 8x8dct=0 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=0 threads=1 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=0 open_gop=0 weightp=0 keyint=50 keyint_min=5 scenecut=40 intra_refresh=0 rc_lookahead=10 rc=crf mbtree=1 crf=22.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 vbv_maxrate=14000 vbv_bufsize=14000 crf_max=0.0 nal_hrd=none filler=0 ip_ratio=1.40 aq=1:1.00\x00\x80\x00\x00\x01re\x88\x84\x02\xb1\x08\x8d\t\xd8p~\x16\x00\x01\x03%\x1e\x1f\xd4\x98T\x98\x05\x7f\x00y\x88\x02`\x00\x10\x01\xb0\x16"\x1dY\x80\x1a\x99\x18\x18%<K@5\xac}F\xaa\xea\x1b[}\xfd\xb0\xc2\xa0\xb0\xc0\x05\x01\xa9\x83\xfe\x14|b\xfd\x9b\x06\n\xe0;\xde\x12\xf5\x06\x8e\x0f\xc2_\xe4\xc2\xa0-\xd0\n\xd2\x02\xc7\xb7\xc8i@\x92@0\r\x0et\x00\xd2\x0e\xcc=\xc1\x99\x1dg8\xd2\x04\xb7\x91\x83K\x8f\xfc\xe7:\xc8\xd2\x08\xa5\x0cw\xd5\x9d\xb1\xaa\xc7\xd7t\xc9\xeb5w\x19\x8e\xdae\x8cH\x82\x11\x05\x99\x10{x_\x0f\xac%\x03k\x94D\xaa\xe2\xf0\xa1\xbb\xb0\\\x93\x81M\xecww\xa7\x84\xf0\xc6Ik\xfe3U\xcc\x02\xff\xff\x06<\x8c\x82\xe9\xa1\xb4o\xc4\xf8\x15\xce\xda\xef\x06\xf0\n\xc4\xb0\xfcb?\xaf\xf3\xf2\xa0}.\xfc}\x16g\x92[6\xaf\xe0\x13\xfc#m\xac\xaa+\x87\xffT;\xbf\xf1lrLO_C\xf7\xe5\x1e\xcdM\x98\x04\xbf\xb7\xf2.\xb2\x87\x8e\xbb$j\x1fyp\xf9\x80\x94\x82\x08%)K\x1bj\x02&|\x9d|\xb9v\xd1a\xad\xfe\x00+\xcdag\xb1\xe2r\x86<u\xa8I\xb6\xab6\xc0\xa4\x91YA\xec\x9f\x8a\x80|\xcb\xdb|\x01\xb1\xe8]\x88\x88\xb9\x8d\xc0\xfc^m}\xf7f\x9a\xb8K\xda\xd0a\xbc\xa2\xb8\x90^P\xdb\xaa\xca]\x0f\xe0\x05\xf6\xc6\x11I<\x8b\xcf`\rZzy\xf8$y\xae\xc8\xfb\\\xfe0\x8f7\xfc\xa3@\x9d\x81\x02X\x00\x00\x00\x00\x95A\x9a#\x03,\x91|\x0c3\x18\xcd\xcbf\x17\x96z\x8bw\x08\\\x1c\xea!\x03\x92\x88\xc5\xe4\x80m|E\xadMw0\xb2\xfa#\x88\x12&4\xb0\x14\xd9\x8e\x8e\x1e\x8e\x91\x87\xf3\x1aS\xe2\x7f\xba\xd3,\r7j\xdd\xf8\x95q\x9a\x0cUm\x987\x01\x82+l\xbd\xa3\x03>\xef\x18i\xd1\x99\x81d\x84\xd4=r\xb0\xf6\x81\x99\x85;\x87xcN\xaa\x92\xa9\xa3x%oO\x02\xa9-\x8b\xc9~V\x1b\x84\xe2\x02\x84\xcc h\xea*xD\x1c\xbf\x17\xc7\xa9\xf5f1\x10\xe7\xf6\x97\x86\x19+k\x99\xac\xf2`\xa3\xd4\x81\x00\xc8\x00\x00\x00\x00LA\x9eA@\xcb7p\x8e\xceIn\x11\x99FF"\x1c\x035\xbf\xc3z\xfb\x91\x8a*\x10p\x9d\x95\xb4\x14\x8a\xca\xc3\xa9\xca\xce\xa4\xb5\xe4\xb1\x92\xdf!\x0cXy\xcd\x1b\x8a\xdfv\x10\x9da- M\xf9\x1f\xc3\xb4D\x9d=c\xcdh\xb2\xae\xc4\x14\xff\xc6\xb1\xa3\xac\x81\x01\x90\x00\x00\x00\x00$\x01\x9eb@\xa4\xa5\xbd\xcf\xf0X]\xcacf\x08\xbb(\xb2\x01\xd8\xe9\x13\xef\x85\x16Z\x12H\x95IL\xd6\x0cq\x13\xf8\xa3\xa6\x81\x03 \x00\x00\x00\x00\x1eA\x9ad4@\xa4\x9f\x1c\'\xc7\xd37\xafO\xca\\\xa7\x0c1\xaa\xa0\x81)\x91\x98\xcc\xbf\xf1\xac@\x1cS\xbbk\x97\xbf\x84D\xc6\xab+\xbb\x8f\xb3\x81\x00\xb7\x8a\xf7\x81\x01\xf1\x82\x02j\xf0\x81\t'
+ vid_bin = "0001101001000101110111111010001110100011010000101000011010000001000000010100001011110111100000010000000101000010111100101000000100000100010000101111001110000001000010000100001010000010100010000110110101100001011101000111001001101111011100110110101101100001010000101000011110000001000001000100001010000101100000010000001000011000010100111000000001100111000000010000000000000000000000000000000000000000000010000101001100010001010011011001101101110100110000011011111110000100011001101110000001000101110001110100110110111011100010110101001110101011100001000001010101001001101010010110011001010011101011001000000111100101010011011011101110001100010100111010101110000100000101100101010010101110011010110101001110101100100000100000000101010101010011011011101110001100010100111010101110000100000100100101010011000011011001110101001110101100100000100000000111100010010011011011101110001100010100111010101110000100000111000101001110111011011010110101001110101100100000100000100000110111111011000000000100000000000000000000000000000000000000000000000010010110000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000101010100100110101001011001101110101110111111100001000001000001001110000011100010110000101010110101111011000110000011000011110100001001000000011110111010100110000101011101100110100101100100011001010110111101001101100000001000110101001100011000010111011001100110001101010011100000101110001100100011100100101110001100010011000000110000010101110100000110011010010010000110000101101110011001000100001001110010011000010110101101100101001000000011000100101110001100110010111000110011001000000011001000110000001100100011000000110000001101100011000100110101001100000011000001110011101001001001000010011011111100011000001010101100100110101111101000001010101111000110100011000010000011010101001101100110000010010011100000100010010001000110000110001000000010001011011110000000100101011101000111001111100111000000000001000100100010011000100001000000100011110100000000000000000000000000000000000000000000000001011001010100101011100110101101000000100001111011111110000100101100111111011001010110001101011010111000000001000000000000000000000000000000000000000000000000011110001101011110000001000000010111001111000101100000010000000110011100100000010000000000100010101101011001110010000011011101010110111001100100100001101000111101010110010111110100110101010000010001010100011100110100001011110100100101010011010011110010111101000001010101100100001110000011100000010000000100100011111000111000001110000100000010111110101111000010000000001110000000000001000000000000000000000000000000000000000000000000000100101011000010000001001000001011101010000001001000000101010010110000100000010001000001010100101110101000000100001001010101001011001010000001000000110110001110100010101011010000000101001101010000000001111111111111111000010000000000011110011001110100110101000000000111111110110010100100101101111111111000000000001000000000000000010010110101000001100000011000000110010000000000000000000000110000000000000001000000000000000000000011000000000000101010001111000110000011000110010110000000010000000000000100011010001100111000000100111100100001001001010100110000110110011101000000100000101011111110000100010101101000110111000100101111100111001101110011000000010000000000000000000000000000000000000000000000000010111001100011110000000000000100000000000000000000000000000000000000000000000000000000011001111100100000000001000000000000000000000000000000000000000000000000000110100100010110100011100001110100010101001110010000110100111101000100010001010101001001000100100001111000110101001100011000010111011001100110001101010011100000101110001100100011100100101110001100010011000000110000011100110111001100000001000000000000000000000000000000000000000000000000001110100110001111000000000000010000000000000000000000000000000000000000000000000000010001100011110001011000000100000001011001111100100000000001000000000000000000000000000000000000000000000000001000100100010110100011100010000100010001010101010100100100000101010100010010010100111101001110010001001000011110010100001100000011000000111010001100000011000000111010001100000011000100101110001100000011000000110000001100000011000000110000001100000011000000110000000000000000000000011111010000111011011001110101010001011100011110111111100001000100101011111101001111100101000011100111100000010000000010100011010001000110111110000001000000000000000010000000000000000000000000000010111100010000011000000101111111111111111111101101110111000100010111101001101111011110011011011001010010001011011110010110001011001101100000100000110110010010001111101110111011110111100000110010001101100011010000100000001011010010000001100011011011110111001001100101001000000011000100110101001101010010000001110010001100100011100100110001001101110010000000110000011000010011100000110100011001000011100100111000001000000010110100100000010010000010111000110010001101100011010000101111010011010101000001000101010001110010110100110100001000000100000101010110010000110010000001100011011011110110010001100101011000110010000000101101001000000100001101101111011100000111100101101100011001010110011001110100001000000011001000110000001100000011001100101101001100100011000000110001001110000010000000101101001000000110100001110100011101000111000000111010001011110010111101110111011101110111011100101110011101100110100101100100011001010110111101101100011000010110111000101110011011110111001001100111001011110111100000110010001101100011010000101110011010000111010001101101011011000010000000101101001000000110111101110000011101000110100101101111011011100111001100111010001000000110001101100001011000100110000101100011001111010011000000100000011100100110010101100110001111010011000100100000011001000110010101100010011011000110111101100011011010110011110100110000001110100011000000111010001100000010000001100001011011100110000101101100011110010111001101100101001111010011000001111000001100010011101000110000011110000011000100110001001100010010000001101101011001010011110101101000011001010111100000100000011100110111010101100010011011010110010100111101001100100010000001110000011100110111100100111101001100010010000001110000011100110111100101011111011100100110010000111101001100010010111000110000001100000011101000110000001011100011000000110000001000000110110101101001011110000110010101100100010111110111001001100101011001100011110100110000001000000110110101100101010111110111001001100001011011100110011101100101001111010011000100110110001000000110001101101000011100100110111101101101011000010101111101101101011001010011110100110001001000000111010001110010011001010110110001101100011010010111001100111101001100000010000000111000011110000011100001100100011000110111010000111101001100000010000001100011011100010110110100111101001100000010000001100100011001010110000101100100011110100110111101101110011001010011110100110010001100010010110000110001001100010010000001100110011000010111001101110100010111110111000001110011011010110110100101110000001111010011000100100000011000110110100001110010011011110110110101100001010111110111000101110000010111110110111101100110011001100111001101100101011101000011110100110000001000000111010001101000011100100110010101100001011001000111001100111101001100010010000001101100011011110110111101101011011000010110100001100101011000010110010001011111011101000110100001110010011001010110000101100100011100110011110100110001001000000111001101101100011010010110001101100101011001000101111101110100011010000111001001100101011000010110010001110011001111010011000000100000011011100111001000111101001100000010000001100100011001010110001101101001011011010110000101110100011001010011110100110001001000000110100101101110011101000110010101110010011011000110000101100011011001010110010000111101001100000010000001100010011011000111010101110010011000010111100101011111011000110110111101101101011100000110000101110100001111010011000000100000011000110110111101101110011100110111010001110010011000010110100101101110011001010110010001011111011010010110111001110100011100100110000100111101001100000010000001100010011001100111001001100001011011010110010101110011001111010011001100100000011000100101111101110000011110010111001001100001011011010110100101100100001111010011001000100000011000100101111101100001011001000110000101110000011101000011110100110001001000000110001001011111011000100110100101100001011100110011110100110000001000000110010001101001011100100110010101100011011101000011110100110001001000000111011101100101011010010110011101101000011101000110001000111101001100000010000001101111011100000110010101101110010111110110011101101111011100000011110100110000001000000111011101100101011010010110011101101000011101000111000000111101001100000010000001101011011001010111100101101001011011100111010000111101001101010011000000100000011010110110010101111001011010010110111001110100010111110110110101101001011011100011110100110101001000000111001101100011011001010110111001100101011000110111010101110100001111010011010000110000001000000110100101101110011101000111001001100001010111110111001001100101011001100111001001100101011100110110100000111101001100000010000001110010011000110101111101101100011011110110111101101011011000010110100001100101011000010110010000111101001100010011000000100000011100100110001100111101011000110111001001100110001000000110110101100010011101000111001001100101011001010011110100110001001000000110001101110010011001100011110100110010001100100010111000110000001000000111000101100011011011110110110101110000001111010011000000101110001101100011000000100000011100010111000001101101011010010110111000111101001100000010000001110001011100000110110101100001011110000011110100110110001110010010000001110001011100000111001101110100011001010111000000111101001101000010000001110110011000100111011001011111011011010110000101111000011100100110000101110100011001010011110100110001001101000011000000110000001100000010000001110110011000100111011001011111011000100111010101100110011100110110100101111010011001010011110100110001001101000011000000110000001100000010000001100011011100100110011001011111011011010110000101111000001111010011000000101110001100000010000001101110011000010110110001011111011010000111001001100100001111010110111001101111011011100110010100100000011001100110100101101100011011000110010101110010001111010011000000100000011010010111000001011111011100100110000101110100011010010110111100111101001100010010111000110100001100000010000001100001011100010011110100110001001110100011000100101110001100000011000000000000100000000000000000000000000000010111001001100101100010001000010000000010101100010000100010001101000010011101100001110000011111100001011000000000000000010000001100100101000111100001111111010100100110000101010010011000000001010111111100000000011110011000100000000010011000000000000000010000000000011011000000010110001000100001110101011001100000000001101010011001000110000001100000100101001111000100101101000000001101011010110001111101010001101010101011101010000110110101101101111101111111011011000011000010101000001011000011000000000001010000000110101001100000111111111000010100011111000110001011111101100110110000011000001010111000000011101111011110000100101111010100000110100011100000111111000010010111111110010011000010101000000010110111010000000010101101001000000010110001111011011111001000011010010100000010010010010000000011000000001101000011100111010000000000110100100000111011001100001111011100000110011001000111010110011100111000110100100000010010110111100100011000001101001011100011111111110011100111001110101100100011010010000010001010010100001100011101111101010110011101101100011010101011000111110101110111010011001001111010110011010101110111000110011000111011011010011001011000110001001000100000100001000100000101100110010001000001111011011110000101111100001111101011000010010100000011011010111001010001000100101010101110001011110000101000011011101110110000010111001001001110000001010011011110110001110111011101111010011110000100111100001100011001001001011010111111111000110011010101011100110000000010111111111111111100000110001111001000110010000010111010011010000110110100011011111100010011111000000101011100111011011010111011110000011011110000000010101100010010110000111111000110001000111111101011111111001111110010101000000111110100101110111111000111110100010110011001111001001001011011001101101010111111100000000100111111110000100011011011011010110010101010001010111000011111111111010101000011101110111111111100010110110001110010010011000100111101011111010000111111011111100101000111101100110101001101100110000000010010111111101101111111001000101110101100101000011110001110101110110010010001101010000111110111100101110000111110011000000010010100100000100000100000100101001010010100101100011011011010100000001000100110011111001001110101111100101110010111011011010001011000011010110111111110000000000010101111001101011000010110011110110001111000100111001010000110001111000111010110101000010010011011011010101011001101101100000010100100100100010101100101000001111011001001111110001010100000000111110011001011110110110111110000000001101100011110100001011101100010001000100010111001100011011100000011111100010111100110110101111101111101110110011010011010101110000100101111011010110100000110000110111100101000101011100010010000010111100101000011011011101010101100101001011101000011111110000000000101111101101100011000010001010010010011110010001011110011110110000000001101010110100111101001111001111110000010010001111001101011101100100011111011010111001111111000110000100011110011011111111100101000110100000010011101100000010000001001011000000000000000000000000000000000001001010101000001100110100010001100000011001011001001000101111100000011000011001100011000110011011100101101100110000101111001011001111010100010110111011100001000010111000001110011101010001000010000001110010010100010001100010111100100100000000110110101111100010001011010110101001101011101110011000010110010111110100010001110001000000100100010011000110100101100000001010011011001100011101000111000011110100011101001000110000111111100110001101001010011111000100111111110111010110100110010110000001101001101110110101011011101111110001001010101110001100110100000110001010101011011011001100000110111000000011000001000101011011011001011110110100011000000110011111011101111000110000110100111010001100110011000000101100100100001001101010000111101011100101011000011110110100000011001100110000101001110111000011101111000011000110100111010101010100100101010100110100011011110000010010101101111010011110000001010101001001011011000101111001001011111100101011000011011100001001110001000000010100001001100110000100000011010001110101000101010011110000100010000011100101111110001011111000111101010011111010101100110001100010001000011100111111101101001011110000110000110010010101101101011100110011010110011110010011000001010001111010100100000010000000011001000000000000000000000000000000000000100110001000001100111100100000101000000110010110011011101110000100011101100111001001001011011100001000110011001010001100100011000100010000111000000001100110101101111111100001101111010111110111001000110001010001010100001000001110000100111011001010110110100000101001000101011001010110000111010100111001010110011101010010010110101111001001011000110010010110111110010000100001100010110000111100111001101000110111000101011011111011101100001000010011101011000010010110100100000010011011111100100011111110000111011010001000100100111010011110101100011110011010110100010110010101011101100010000010100111111111100011010110001101000111010110010000001000000011001000000000000000000000000000000000000001001000000000110011110011000100100000010100100101001011011110111001111111100000101100001011101110010100110001101100110000010001011101100101000101100100000000111011000111010010001001111101111100001010001011001011010000100100100100010010101010010010100110011010110000011000111000100010011111110001010001110100110100000010000001100100000000000000000000000000000000000000001111001000001100110100110010000110100010000001010010010011111000111000010011111000111110100110011011110101111010011111100101001011100101001110000110000110001101010101010000010000001001010011001000110011000110011001011111111110001101011000100000000011100010100111011101101101011100101111011111110000100010001001100011010101011001010111011101110001111101100111000000100000000101101111000101011110111100000010000000111110001100000100000001001101010111100001000000100001001"
+ props = {
+ "index": 0,
+ "codec_name": "h264",
+ "codec_long_name": "H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10",
+ "profile": "Main",
+ "codec_type": "video",
+ "codec_time_base": "1/10",
+ "codec_tag_string": "[0][0][0][0]",
+ "codec_tag": "0x0000",
+ "width": 32,
+ "height": 32,
+ "coded_width": 32,
+ "coded_height": 32,
+ "has_b_frames": 2,
+ "sample_aspect_ratio": "16:9",
+ "display_aspect_ratio": "16:9",
+ "pix_fmt": "yuv420p",
+ "level": 31,
+ "color_range": "tv",
+ "color_space": "smpte170m",
+ "color_transfer": "smpte170m",
+ "color_primaries": "smpte170m",
+ "chroma_location": "left",
+ "field_order": "progressive",
+ "refs": 1,
+ "is_avc": "true",
+ "nal_length_size": "4",
+ "r_frame_rate": "5/1",
+ "avg_frame_rate": "5/1",
+ "time_base": "1/1000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "bits_per_raw_sample": "8",
+ "disposition": {
+ "default": 1,
+ "dub": 0,
+ "original": 0,
+ "comment": 0,
+ "lyrics": 0,
+ "karaoke": 0,
+ "forced": 0,
+ "hearing_impaired": 0,
+ "visual_impaired": 0,
+ "clean_effects": 0,
+ "attached_pic": 0,
+ "timed_thumbnails": 0,
+ },
+ "tags": {"DURATION": "00:00:01.000000000"},
+ }
+
+ async def setup(self):
+ configure_lang({})
+
+ async def test_video(self):
+ opsdroid = amock.CoroutineMock()
+ mock_connector = Connector({}, opsdroid=opsdroid)
+ event = events.Video(
+ self.mkv_bytes,
+ user_id="user_id",
+ user="user",
+ target="default",
+ connector=mock_connector,
+ )
+
+ self.assertEqual(event.user_id, "user_id")
+ self.assertEqual(event.user, "user")
+ self.assertEqual(event.target, "default")
+ self.assertEqual(await event.get_file_bytes(), self.mkv_bytes)
+ self.assertEqual(await event.get_mimetype(), "video/x-matroska")
+ self.assertEqual(await event.get_bin(), self.vid_bin)
+ self.assertEqual(await event.get_properties(), self.props)
+
+ async def test_explicit_mime_type(self):
+ opsdroid = amock.CoroutineMock()
+ mock_connector = Connector({}, opsdroid=opsdroid)
+ event = events.Image(
+ self.mkv_bytes,
+ user_id="user_id",
+ user="user",
+ target="default",
+ mimetype="video/x-matroska",
+ connector=mock_connector,
+ )
+
+ self.assertEqual(await event.get_mimetype(), "video/x-matroska")
+
+ async def test_no_mime_type(self):
+ opsdroid = amock.CoroutineMock()
+ mock_connector = Connector({}, opsdroid=opsdroid)
+ event = events.Image(
+ b"aslkdjsalkdjlaj",
+ user_id="user_id",
+ user="user",
+ target="default",
+ connector=mock_connector,
+ )
+
+ self.assertEqual(await event.get_mimetype(), "")
| Add support for video events
We currently only have event types for file and image, but we should also have a video type to handle things like mp4.
| I'm a beginner, but I'd like to help. Could you assign this issue to me?
Let us know how you get on or if you need any help. The best thing to do is open a PR early and ask for comments on it :smile:
just to confirm, the place to modify event types is at this file: opsdroid/opsdroid/connector/matrix/create_events.py
If I was wrong, could you let me know which file I should dig into as a starting point? tyty
What feature should the Video event type support? I suppose it's not the same feature as image dimension.
Since @arctdav hasn't been working on the issue, could I continue on this? I read the progress so far on the PR and could help with the testing!
@SaquibShahzad go ahead
Awesome @SaquibShahzad let us know if you need any help 👍
Hey is anyone working on this issue? My team would like to work on this issue as a project.
Hello @haardikdharma10 no one is currently working on this issue. Would be great if your team could pick it up 👍
> Hello @haardikdharma10 no one is currently working on this issue. Would be great if your team could pick it up 👍
are you referring to my team?
> > Hello @haardikdharma10 no one is currently working on this issue. Would be great if your team could pick it up 👍
>
> are you referring to my team?
That's what I guess. @FabioRosado :P
I'm from @HritwikSinghal 's team. Will you provide the acceptance tests on this?
@HritwikSinghal yes I think @FabioRosado meant you 😆.
@subodhawasthi we expect all contributors to write tests and documentation for their changes. We will not provide tests.
@jacobtomlinson So what would be the criteria for acceptance? There have to be some standard tests that you perform for every PR to accept it
You can check the other PRs but to sum up:
- Coverage must remain the same (100% or close)
- your tests must all pass
- other tests need to pass
- you need to run black to lint your code
- you must write documentation for the thing you are adding
If you need help with running tests or black the contributing section in our docs explains it but we can give you a hand if you have any issues 👍
ok thanks, we will start working on it ASAP
Can I get more detail about that
@devraj4522 my team is actually working on this issue and we need to close this pull request for submission of our project. So can you please leave this issue to us since our grade depends on it ?
FabioRosado, i assure you i am working on this issue with my team and we will close this issue in near future, its just that our mid-sem exams are going on currently.
Ok I didn't knew . | 2020-10-07T19:07:12 |
opsdroid/opsdroid | 1,659 | opsdroid__opsdroid-1659 | [
"1658"
] | 29452ee7ec3d435616a883b59940a2d4d2dc7269 | diff --git a/opsdroid/connector/twitch/__init__.py b/opsdroid/connector/twitch/__init__.py
--- a/opsdroid/connector/twitch/__init__.py
+++ b/opsdroid/connector/twitch/__init__.py
@@ -61,10 +61,13 @@ def __init__(self, config, opsdroid=None):
# TODO: Allow usage of SSL connection
self.server = "ws://irc-ws.chat.twitch.tv"
self.port = "80"
- self.base_url = config.get("base-url")
self.loop = asyncio.get_event_loop()
self.reconnections = 0
self.auth_file = TWITCH_JSON
+ try:
+ self.base_url = opsdroid.config["web"]["base-url"]
+ except KeyError:
+ self.base_url = config.get("forward-url")
async def validate_request(self, request, secret):
"""Compute sha256 hash of request and secret.
| diff --git a/opsdroid/connector/twitch/tests/test_connector_twitch.py b/opsdroid/connector/twitch/tests/test_connector_twitch.py
--- a/opsdroid/connector/twitch/tests/test_connector_twitch.py
+++ b/opsdroid/connector/twitch/tests/test_connector_twitch.py
@@ -33,6 +33,35 @@ def test_init(opsdroid):
assert connector.reconnections == 0
+def test_base_url_twitch_config(opsdroid):
+ config = {
+ "code": "yourcode",
+ "channel": "test",
+ "client-id": "client-id",
+ "client-secret": "client-secret",
+ "forward-url": "http://my-awesome-url",
+ }
+
+ connector = ConnectorTwitch(config, opsdroid=opsdroid)
+
+ assert connector.base_url == "http://my-awesome-url"
+
+
+def test_base_url_web_config(opsdroid):
+ config = {
+ "code": "yourcode",
+ "channel": "test",
+ "client-id": "client-id",
+ "client-secret": "client-secret",
+ }
+
+ opsdroid.config["web"] = {"base-url": "http://my-awesome-url"}
+
+ connector = ConnectorTwitch(config, opsdroid=opsdroid)
+
+ assert connector.base_url == "http://my-awesome-url"
+
+
@pytest.mark.asyncio
async def test_validate_request(opsdroid):
connector = ConnectorTwitch(connector_config, opsdroid=opsdroid)
| Twitch connector can't connect to webhook
When I was working on the Twitter connector, I realised that I had changed the configuration for the webhook URL to use the `base-url` although I forgot to make the changes to the `connect_webhook` method.
This means that the Twitch connector isn't able to connect to webhooks because we are passing a None url.
I am going to raise a PR to fix this issue in a moment.
| 2020-10-23T13:47:25 |
|
opsdroid/opsdroid | 1,660 | opsdroid__opsdroid-1660 | [
"1656"
] | e334a75243d27a5d2cb30db846a2c6ca427045d3 | diff --git a/opsdroid/web.py b/opsdroid/web.py
--- a/opsdroid/web.py
+++ b/opsdroid/web.py
@@ -34,8 +34,10 @@ def __init__(self, opsdroid):
self.web_app = web.Application()
self.runner = web.AppRunner(self.web_app)
self.site = None
- self.web_app.router.add_get("/", self.web_index_handler)
- self.web_app.router.add_get("", self.web_index_handler)
+ if not self.config.get("disable_web_index_handler_in_root", False):
+ self.web_app.router.add_get("/", self.web_index_handler)
+ self.web_app.router.add_get("", self.web_index_handler)
+
self.web_app.router.add_get("/stats", self.web_stats_handler)
self.web_app.router.add_get("/stats/", self.web_stats_handler)
| diff --git a/opsdroid/tests/test_web.py b/opsdroid/tests/test_web.py
--- a/opsdroid/tests/test_web.py
+++ b/opsdroid/tests/test_web.py
@@ -38,6 +38,24 @@ async def test_web_get_host(opsdroid):
assert app.get_host == "127.0.0.1"
+async def test_web_disable_web_index_handler_in_root(opsdroid):
+ """Check disabling of web index handler in root."""
+ opsdroid.config["web"] = {"disable_web_index_handler_in_root": True}
+ app = web.Web(opsdroid)
+ canonicals = [resource.canonical for resource in app.web_app._router.resources()]
+ assert "/" not in canonicals
+
+ opsdroid.config["web"] = {"disable_web_index_handler_in_root": False}
+ app = web.Web(opsdroid)
+ canonicals = [resource.canonical for resource in app.web_app._router.resources()]
+ assert "/" in canonicals
+
+ opsdroid.config["web"] = {}
+ app = web.Web(opsdroid)
+ canonicals = [resource.canonical for resource in app.web_app._router.resources()]
+ assert "/" in canonicals
+
+
async def test_web_get_ssl(opsdroid):
"""Check the host getter."""
opsdroid.config["web"] = {}
| Add a config option to disable registering a route for /
In the web server by default a route is registered for the base / path. This should be configurable in case a user wants to register their own.
| Hey there,I would like to work on this issue since this is beginner one.Can you guide me as to what has to be done inorder to resolve this issue?
[this](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/web.py#L28) line needs to be configurable. If the added config option is false then it shouldn't be run.
@Cadair is this what you are asking for?
`
if (self.web_index_handler){
self.web_app.router.add_get("/", self.web_index_handler)
}
` | 2020-10-25T15:56:05 |
opsdroid/opsdroid | 1,683 | opsdroid__opsdroid-1683 | [
"1673"
] | 354d210b90c5e2f6d2a833a51f1fe3ec9f98f161 | diff --git a/opsdroid/database/redis/__init__.py b/opsdroid/database/redis/__init__.py
--- a/opsdroid/database/redis/__init__.py
+++ b/opsdroid/database/redis/__init__.py
@@ -94,7 +94,7 @@ async def get(self, key):
data = await self.client.execute("GET", key)
if data:
- return json.loads(data, encoding=JSONDecoder)
+ return json.loads(data, object_hook=JSONDecoder())
return None
| skill-seen broken with redis database?
I've been testing opsdroid with a redis database and the seen skill appears to be having problems serializing python datetime objects.
user: when did you last see user?
opsdroid: Whoops there has been an error.
opsdroid: Check the log for details.
this is the opsdroid log with DEBUG logging enabled:
```
notrexroof_1 | DEBUG opsdroid.memory: Putting seen to memory.
notrexroof_1 | DEBUG opsdroid.database.redis: Putting seen into Redis.
notrexroof_1 | ERROR opsdroid.core: Exception when running skill 'seen'.
notrexroof_1 | Traceback (most recent call last):
notrexroof_1 | File "/usr/local/lib/python3.8/site-packages/opsdroid/core.py", line 427, in run_skill
notrexroof_1 | return await skill(self, config, event)
notrexroof_1 | File "/root/.local/share/opsdroid/opsdroid-modules/skill/seen/__init__.py", line 16, in last_seen
notrexroof_1 | await message.respond("I last saw {} {}".format(name, human(seen[name], precision=1)))
notrexroof_1 | File "/root/.local/share/opsdroid/site-packages/ago.py", line 55, in human
notrexroof_1 | delta = get_delta_from_subject(subject)
notrexroof_1 | File "/root/.local/share/opsdroid/site-packages/ago.py", line 16, in get_delta_from_subject
notrexroof_1 | subject = float(subject)
notrexroof_1 | TypeError: float() argument must be a string or a number, not 'dict'
```
I know this hasn't been touched in a few years, but I'm wondering if there is a general issue with serializing objects into a redis database within opsdroid.
| Thanks for raising this.
As you say these examples are a little old now so have perhaps gotten out of date.
From reading that error message I'm not sure this is a problem with redis but more an issue with what is being stored in redis. The `seen[name]` value seems to be coming back as a dictionary.
thanks for following up!
I will note that this skill works as expected if you use sqlite instead of redis.
this is what the key looks like in redis:
```
127.0.0.1:6379> get seen
"{\"null\": {\"__class__\": \"datetime\", \"year\": 2020, \"month\": 11, \"day\": 19, \"hour\": 16, \"minute\": 17, \"second\": 41, \"microsecond\": 118770}, \"notrexroof\": {\"__class__\": \"datetime\", \"year\": 2020, \"month\": 11, \"day\": 19, \"hour\": 16, \"minute\": 17, \"second\": 41, \"microsecond\": 466016}, \"rexroof\": {\"__class__\": \"datetime\", \"year\": 2020, \"month\": 11, \"day\": 19, \"hour\": 16, \"minute\": 18, \"second\": 31, \"microsecond\": 277084}, \"commanderroot\": {\"__class__\": \"datetime\", \"year\": 2020, \"month\": 11, \"day\": 19, \"hour\": 13, \"minute\": 16, \"second\": 28, \"microsecond\": 59796}, \"rubberslayer\": {\"__class__\": \"datetime\", \"year\": 2020, \"month\": 11, \"day\": 19, \"hour\": 13, \"minute\": 11, \"second\": 35, \"microsecond\": 518734}, \"crazyic\": {\"__class__\": \"datetime\", \"year\": 2020, \"month\": 11, \"day\": 19, \"hour\": 16, \"minute\": 18, \"second\": 34, \"microsecond\": 9786}, \"saddestkitty\": {\"__class__\": \"datetime\", \"year\": 2020, \"month\": 11, \"day\": 19, \"hour\": 13, \"minute\": 27, \"second\": 56, \"microsecond\": 623723}, \"pmash2\": {\"__class__\": \"datetime\", \"year\": 2020, \"month\": 11, \"day\": 19, \"hour\": 13, \"minute\": 48, \"second\": 5, \"microsecond\": 643626}, \"thiccur\": {\"__class__\": \"datetime\", \"year\": 2020, \"month\": 11, \"day\": 19, \"hour\": 13, \"minute\": 35, \"second\": 2, \"microsecond\": 931169}, \"lurxx\": {\"__class__\": \"datetime\", \"year\": 2020, \"month\": 11, \"day\": 19, \"hour\": 13, \"minute\": 38, \"second\": 32, \"microsecond\": 572882}, \"ildelara\": {\"__class__\": \"datetime\", \"year\": 2020, \"month\": 11, \"day\": 19, \"hour\": 13, \"minute\": 41, \"second\": 47, \"microsecond\": 789482}}"
127.0.0.1:6379>
```
> I will note that this skill works as expected if you use sqlite instead of redis.
Oh interesting! Both database modules serialise to JSON and back again.
I don't have time to look at this right now. But I'll move this over to the main opsdroid repo and hopefully someone can take a look. | 2020-11-28T03:37:00 |
|
opsdroid/opsdroid | 1,686 | opsdroid__opsdroid-1686 | [
"1685"
] | 40548bdf8ae5935c495134fec6d3cf2804958876 | diff --git a/opsdroid/database/matrix/__init__.py b/opsdroid/database/matrix/__init__.py
--- a/opsdroid/database/matrix/__init__.py
+++ b/opsdroid/database/matrix/__init__.py
@@ -89,8 +89,7 @@ async def migrate_database(self):
)
)
await self.connector.connection.room_redact(
- room_id=self.room_id,
- event_id=event["event_id"],
+ room_id=self.room_id, event_id=event["event_id"]
)
self.should_migrate = False
@@ -165,19 +164,21 @@ async def get(self, key, get_full=False):
)
ori_data = await self.connector.connection.room_get_state_event(
- room_id=self.room_id,
- event_type=self._event_type,
- state_key=state_key,
+ room_id=self.room_id, event_type=self._event_type, state_key=state_key
)
+
if isinstance(ori_data, RoomGetStateEventError):
+ if (
+ ori_data.transport_response is not None
+ and ori_data.transport_response.status == 404
+ ):
+ _LOGGER.error(
+ f"Error getting {key} from matrix room {self.room_id}: Event not found"
+ )
+ return
raise RuntimeError(
f"Error getting {key} from matrix room {self.room_id}: {ori_data.message}({ori_data.status_code})"
)
- elif ori_data.transport_response.status == 404:
- _LOGGER.error(
- f"Error getting {key} from matrix room {self.room_id}: Event not found"
- )
- return
data = ori_data.content
@@ -197,8 +198,7 @@ async def get(self, key, get_full=False):
for k, v in data.items():
if isinstance(v, dict) and len(v) == 1 and "encrypted_val" in v:
resp = await self.connector.connection.room_get_event(
- room_id=self.room_id,
- event_id=v["encrypted_val"],
+ room_id=self.room_id, event_id=v["encrypted_val"]
)
if isinstance(resp, RoomGetEventError):
_LOGGER.error(
@@ -230,9 +230,7 @@ async def delete(self, key):
)
data = await self.connector.connection.room_get_state_event(
- room_id=self.room_id,
- event_type=self._event_type,
- state_key=state_key,
+ room_id=self.room_id, event_type=self._event_type, state_key=state_key
)
if isinstance(data, RoomGetStateEventError):
_LOGGER.error(
@@ -240,7 +238,10 @@ async def delete(self, key):
)
return
- if data.transport_response.status == 404:
+ if (
+ data.transport_response is not None
+ and data.transport_response.status == 404
+ ):
_LOGGER.error(
f"State event {self._event_type} with state key '{state_key}' doesn't exist."
)
diff --git a/opsdroid/events.py b/opsdroid/events.py
--- a/opsdroid/events.py
+++ b/opsdroid/events.py
@@ -55,7 +55,7 @@ def __new__(mcls, name, bases, members): # noqa: D102
if "_no_register" in members:
return cls
- if name in mcls.event_registry:
+ if name in mcls.event_registry and mcls.event_registry[name] is not cls:
raise NameError(
"An event subclass named {name} has already been "
"defined. Event subclass names must be globally "
@@ -77,14 +77,14 @@ class Event(metaclass=EventMetaClass):
Args:
user_id (string, optional): String id of user sending message
user (string, optional): String name of user sending message
- room (string, optional): String name of the room or chat channel in
- which message was sent
+ target (string, optional): String name of the room or chat channel in
+ which message was sent
connector (Connector, optional): Connector object used to interact with
given chat service
raw_event (dict, optional): Raw message as provided by chat service.
None by default
raw_parses (dict, optional): Raw response as provided by parse service.
- None by default
+ None by default
event_id (object, optional): The unique id for this event as provided
by the connector.
linked_event (Event, optional): An event to link to this one, i.e. the
@@ -195,19 +195,19 @@ class Message(Event):
Args:
text (string): String text of message
- room (string, optional): String name of the room or chat channel in
- which message was sent
+ target (string, optional): String name of the room or chat channel in
+ which message was sent
connector (Connector, optional): Connector object used to interact with
given chat service
raw_event (dict, optional): Raw message as provided by chat service.
None by default
raw_parses (dict, optional): Raw response as provided by parse service.
- None by default
+ None by default
Attributes:
created: Local date and time that message object was created
user: String name of user sending message
- room: String name of the room or chat channel in which message was sent
+ target: String name of the room or chat channel in which message was sent
connector: Connector object used to interact with given chat service
text: Text of message as string
raw_event: Raw message provided by chat service
| diff --git a/tests/test_database_matrix.py b/tests/test_database_matrix.py
--- a/tests/test_database_matrix.py
+++ b/tests/test_database_matrix.py
@@ -8,6 +8,7 @@
from opsdroid.core import OpsDroid
from opsdroid.database.matrix import DatabaseMatrix, memory_in_event_room
from opsdroid.events import Message
+from opsdroid.cli.start import configure_lang # noqa
@pytest.fixture
@@ -97,7 +98,7 @@ async def test_default_config(patched_send, opsdroid_matrix):
"/_matrix/client/r0/rooms/%21notaroomid/state/dev.opsdroid.database/",
{"twim": {"hello": "world"}},
),
- ],
+ ]
)
@@ -166,7 +167,7 @@ async def test_put_custom_state_key(patched_send, opsdroid_matrix):
"/_matrix/client/r0/rooms/%21notaroomid/state/dev.opsdroid.database/wibble",
{"twim": {"hello": "world"}},
),
- ],
+ ]
)
@@ -234,7 +235,7 @@ async def test_single_state_key_false(patched_send, opsdroid_matrix):
"/_matrix/client/r0/rooms/%21notaroomid/state/dev.opsdroid.database/hello",
{"hello": "world"},
),
- ],
+ ]
)
@@ -302,7 +303,7 @@ async def test_single_state_key_false_dict(patched_send, opsdroid_matrix):
"/_matrix/client/r0/rooms/%21notaroomid/state/dev.opsdroid.database/twim",
{"twim": {"hello": "world", "twim": "hello"}},
),
- ],
+ ]
)
@@ -373,7 +374,7 @@ async def test_single_state_not_a_dict(patched_send, opsdroid_matrix):
"/_matrix/client/r0/rooms/%21notaroomid/state/dev.opsdroid.database/",
{"twim": value},
),
- ],
+ ]
)
@@ -382,8 +383,6 @@ async def test_default_update_same_key(patched_send, opsdroid_matrix):
patched_send.return_value = nio.RoomGetStateEventResponse(
{"twim": {"hello": "world"}}, "", "", ""
)
- patched_send.return_value.transport_response = AsyncMock()
- patched_send.return_value.transport_response.status = 200
db = DatabaseMatrix(
{"should_encrypt": False, "single_state_key": False}, opsdroid=opsdroid_matrix
@@ -403,7 +402,7 @@ async def test_default_update_same_key(patched_send, opsdroid_matrix):
"/_matrix/client/r0/rooms/%21notaroomid/state/dev.opsdroid.database/twim",
{"twim": {"hello": "bob"}},
),
- ],
+ ]
)
@@ -417,8 +416,6 @@ def side_effect(resp, *args, **kwargs):
resp = nio.RoomGetStateEventResponse(
{"twim": {"encrypted_val": "enceventid"}}, "", "", ""
)
- resp.transport_response = AsyncMock()
- resp.transport_response.status = 200
return resp
elif resp is nio.RoomGetEventResponse:
event = nio.Event(
@@ -469,8 +466,6 @@ async def test_update_same_key_single_state_key(patched_send, opsdroid_matrix):
patched_send.return_value = nio.RoomGetStateEventResponse(
{"twim": {"hello": "world"}}, "", "", ""
)
- patched_send.return_value.transport_response = AsyncMock()
- patched_send.return_value.transport_response.status = 200
db = DatabaseMatrix(
{"should_encrypt": False, "single_state_key": True}, opsdroid=opsdroid_matrix
@@ -490,7 +485,7 @@ async def test_update_same_key_single_state_key(patched_send, opsdroid_matrix):
"/_matrix/client/r0/rooms/%21notaroomid/state/dev.opsdroid.database/",
{"twim": {"hello": "bob"}},
),
- ],
+ ]
)
@@ -506,8 +501,6 @@ def side_effect(resp, *args, **kwargs):
resp = nio.RoomGetStateEventResponse(
{"twim": {"encrypted_val": "enceventid"}}, "", "", ""
)
- resp.transport_response = AsyncMock()
- resp.transport_response.status = 200
return resp
elif resp is nio.RoomGetEventResponse:
event = nio.Event(
@@ -558,8 +551,6 @@ async def test_default_update_same_key_value(patched_send, opsdroid_matrix, capl
patched_send.return_value = nio.RoomGetStateEventResponse(
{"twim": {"hello": "world"}}, "", "", ""
)
- patched_send.return_value.transport_response = AsyncMock()
- patched_send.return_value.transport_response.status = 200
db = DatabaseMatrix(
{"should_encrypt": False, "single_state_key": False}, opsdroid=opsdroid_matrix
@@ -574,7 +565,7 @@ async def test_default_update_same_key_value(patched_send, opsdroid_matrix, capl
"GET",
"/_matrix/client/r0/rooms/%21notaroomid/state/dev.opsdroid.database/twim",
)
- ],
+ ]
)
assert ["Not updating matrix state, as content hasn't changed."] == [
@@ -592,8 +583,6 @@ def side_effect(resp, *args, **kwargs):
resp = nio.RoomGetStateEventResponse(
{"twim": {"encrypted_val": "enceventid"}}, "", "", ""
)
- resp.transport_response = AsyncMock()
- resp.transport_response.status = 200
return resp
else:
event = nio.Event(
@@ -623,7 +612,7 @@ def side_effect(resp, *args, **kwargs):
"/_matrix/client/r0/rooms/%21notaroomid/state/dev.opsdroid.database/twim",
),
matrix_call("GET", "/_matrix/client/r0/rooms/%21notaroomid/event/"),
- ],
+ ]
)
assert ["Not updating matrix state, as content hasn't changed."] == [
@@ -638,8 +627,6 @@ async def test_default_update_same_key_value_single_state_key(
patched_send.return_value = nio.RoomGetStateEventResponse(
{"twim": {"hello": "world"}}, "", "", ""
)
- patched_send.return_value.transport_response = AsyncMock()
- patched_send.return_value.transport_response.status = 200
db = DatabaseMatrix(
{"should_encrypt": False, "single_state_key": True}, opsdroid=opsdroid_matrix
@@ -654,7 +641,7 @@ async def test_default_update_same_key_value_single_state_key(
"GET",
"/_matrix/client/r0/rooms/%21notaroomid/state/dev.opsdroid.database/",
)
- ],
+ ]
)
assert ["Not updating matrix state, as content hasn't changed."] == [
@@ -672,8 +659,6 @@ def side_effect(resp, *args, **kwargs):
resp = nio.RoomGetStateEventResponse(
{"twim": {"encrypted_val": "enceventid"}}, "", "", ""
)
- resp.transport_response = AsyncMock()
- resp.transport_response.status = 200
return resp
else:
event = nio.Event(
@@ -703,7 +688,7 @@ def side_effect(resp, *args, **kwargs):
"/_matrix/client/r0/rooms/%21notaroomid/state/dev.opsdroid.database/",
),
matrix_call("GET", "/_matrix/client/r0/rooms/%21notaroomid/event/"),
- ],
+ ]
)
assert ["Not updating matrix state, as content hasn't changed."] == [
@@ -716,8 +701,6 @@ async def test_default_update_single_state_key(patched_send, opsdroid_matrix):
patched_send.return_value = nio.RoomGetStateEventResponse(
{"twim": "hello"}, "", "", ""
)
- patched_send.return_value.transport_response = AsyncMock()
- patched_send.return_value.transport_response.status = 200
db = DatabaseMatrix(
{"should_encrypt": False, "single_state_key": True}, opsdroid=opsdroid_matrix
@@ -737,7 +720,7 @@ async def test_default_update_single_state_key(patched_send, opsdroid_matrix):
"/_matrix/client/r0/rooms/%21notaroomid/state/dev.opsdroid.database/",
{"twim": "hello", "pill": "red"},
),
- ],
+ ]
)
@@ -751,8 +734,6 @@ async def test_default_update_single_state_key_enc(
def side_effect(resp, *args, **kwargs):
if resp is nio.RoomGetStateEventResponse:
resp = nio.RoomGetStateEventResponse({"twim": "hello"}, "", "", "")
- resp.transport_response = AsyncMock()
- resp.transport_response.status = 200
return resp
else:
return nio.RoomSendResponse("enceventid", "!notaroomid")
@@ -789,8 +770,6 @@ async def test_get_single_state_key(patched_send, opsdroid_matrix):
patched_send.return_value = nio.RoomGetStateEventResponse(
{"twim": "hello", "wibble": "wobble"}, "", "", ""
)
- patched_send.return_value.transport_response = AsyncMock()
- patched_send.return_value.transport_response.status = 200
db = DatabaseMatrix({}, opsdroid=opsdroid_matrix)
db.should_migrate = False
@@ -817,8 +796,6 @@ def side_effect(resp, *args, **kwargs):
"",
"",
)
- resp.transport_response = AsyncMock()
- resp.transport_response.status = 200
return resp
else:
event = nio.Event(
@@ -847,7 +824,7 @@ def side_effect(resp, *args, **kwargs):
"/_matrix/client/r0/rooms/%21notaroomid/state/dev.opsdroid.database/",
),
matrix_call("GET", "/_matrix/client/r0/rooms/%21notaroomid/event/"),
- ],
+ ]
)
assert data == "hello"
@@ -858,8 +835,6 @@ async def test_get(patched_send, opsdroid_matrix):
patched_send.return_value = nio.RoomGetStateEventResponse(
{"twim": "world"}, "", "", ""
)
- patched_send.return_value.transport_response = AsyncMock()
- patched_send.return_value.transport_response.status = 200
db = DatabaseMatrix(
{"should_encrypt": False, "single_state_key": False}, opsdroid=opsdroid_matrix
@@ -885,8 +860,6 @@ def side_effect(resp, *args, **kwargs):
resp = nio.RoomGetStateEventResponse(
{"twim": {"encrypted_val": "enceventid"}}, "", "", ""
)
- resp.transport_response = AsyncMock()
- resp.transport_response.status = 200
return resp
else:
event = nio.Event(
@@ -915,7 +888,7 @@ def side_effect(resp, *args, **kwargs):
"/_matrix/client/r0/rooms/%21notaroomid/state/dev.opsdroid.database/twim",
),
matrix_call("GET", "/_matrix/client/r0/rooms/%21notaroomid/event/"),
- ],
+ ]
)
assert data == "world"
@@ -926,8 +899,6 @@ async def test_get_no_key_single_state_key(patched_send, opsdroid_matrix):
patched_send.return_value = nio.RoomGetStateEventResponse(
{"wibble": "wobble"}, "", "", ""
)
- patched_send.return_value.transport_response = AsyncMock()
- patched_send.return_value.transport_response.status = 200
db = DatabaseMatrix(
{"should_encrypt": False, "single_state_key": True}, opsdroid=opsdroid_matrix
@@ -941,16 +912,17 @@ async def test_get_no_key_single_state_key(patched_send, opsdroid_matrix):
@pytest.mark.asyncio
async def test_get_no_key_404(patched_send, opsdroid_matrix):
- patched_send.return_value = nio.RoomGetStateEventError({"errcode": 404})
+ patched_send.return_value = nio.RoomGetStateEventError({"errcode": "M_NOTFOUND"})
+ patched_send.return_value.transport_response = AsyncMock()
+ patched_send.return_value.transport_response.status = 404
db = DatabaseMatrix(
{"should_encrypt": False, "single_state_key": False}, opsdroid=opsdroid_matrix
)
db.should_migrate = False
- with pytest.raises(RuntimeError):
- data = await db.get("twim")
- assert data is None
+ data = await db.get("twim")
+ assert data is None
@pytest.mark.asyncio
@@ -963,8 +935,7 @@ async def test_get_no_key_500(patched_send, opsdroid_matrix):
db.should_migrate = False
with pytest.raises(RuntimeError):
- data = await db.get("twim")
- assert data is None
+ await db.get("twim")
@pytest.mark.asyncio
@@ -972,8 +943,6 @@ async def test_delete(patched_send, opsdroid_matrix):
patched_send.return_value = nio.RoomGetStateEventResponse(
{"twim": "hello"}, "", "", ""
)
- patched_send.return_value.transport_response = AsyncMock()
- patched_send.return_value.transport_response.status = 200
db = DatabaseMatrix({}, opsdroid=opsdroid_matrix)
db.should_migrate = False
@@ -990,7 +959,7 @@ async def test_delete(patched_send, opsdroid_matrix):
"/_matrix/client/r0/rooms/%21notaroomid/state/dev.opsdroid.database/",
{},
),
- ],
+ ]
)
assert data == "hello"
@@ -1001,8 +970,6 @@ async def test_delete_single_state_key_false(patched_send, opsdroid_matrix):
patched_send.return_value = nio.RoomGetStateEventResponse(
{"twim": "hello"}, "", "", ""
)
- patched_send.return_value.transport_response = AsyncMock()
- patched_send.return_value.transport_response.status = 200
db = DatabaseMatrix({"single_state_key": False}, opsdroid=opsdroid_matrix)
db.should_migrate = False
@@ -1019,7 +986,7 @@ async def test_delete_single_state_key_false(patched_send, opsdroid_matrix):
"/_matrix/client/r0/rooms/%21notaroomid/state/dev.opsdroid.database/twim",
{},
),
- ],
+ ]
)
assert data == "hello"
@@ -1030,8 +997,6 @@ async def test_delete_multiple_keys(patched_send, opsdroid_matrix):
patched_send.return_value = nio.RoomGetStateEventResponse(
{"hello": "world", "twim": "hello", "pill": "red"}, "", "", ""
)
- patched_send.return_value.transport_response = AsyncMock()
- patched_send.return_value.transport_response.status = 200
db = DatabaseMatrix({}, opsdroid=opsdroid_matrix)
db.should_migrate = False
@@ -1048,7 +1013,7 @@ async def test_delete_multiple_keys(patched_send, opsdroid_matrix):
"/_matrix/client/r0/rooms/%21notaroomid/state/dev.opsdroid.database/",
{"pill": "red"},
),
- ],
+ ]
)
assert data == ["world", "hello"]
@@ -1059,8 +1024,6 @@ async def test_delete_no_key(patched_send, opsdroid_matrix):
patched_send.return_value = nio.RoomGetStateEventResponse(
{"twim": "hello"}, "", "", ""
)
- patched_send.return_value.transport_response = AsyncMock()
- patched_send.return_value.transport_response.status = 200
db = DatabaseMatrix({}, opsdroid=opsdroid_matrix)
db.should_migrate = False
@@ -1101,8 +1064,6 @@ async def test_room_switch(patched_send, opsdroid_matrix):
patched_send.return_value = nio.RoomGetStateEventResponse(
{"hello": "world"}, "", "", ""
)
- patched_send.return_value.transport_response = AsyncMock()
- patched_send.return_value.transport_response.status = 200
db = DatabaseMatrix({"should_encrypt": False}, opsdroid=opsdroid_matrix)
db.should_migrate = False
@@ -1199,7 +1160,7 @@ def side_effect(resp, *args, **kwargs):
"{}",
response_data=("!notaroomid",),
),
- ],
+ ]
)
@@ -1254,7 +1215,7 @@ def side_effect(resp, *args, **kwargs):
"{}",
response_data=("!notaroomid",),
),
- ],
+ ]
)
@@ -1265,8 +1226,6 @@ def side_effect(resp, *args, **kwargs):
resp = nio.RoomGetStateEventResponse(
{"twim": {"encrypted_val": "enceventid"}}, "", "", ""
)
- resp.transport_response = AsyncMock()
- resp.transport_response.status = 200
return resp
else:
return nio.RoomGetEventError(message="testing")
@@ -1292,7 +1251,7 @@ def side_effect(resp, *args, **kwargs):
await db.get("hello")
assert [
- "Error migrating from opsdroid.database to dev.opsdroid.database in room !notaroomid: testing(None)",
+ "Error migrating from opsdroid.database to dev.opsdroid.database in room !notaroomid: testing(None)"
] == [rec.message for rec in caplog.records]
patched_send.side_effect = [
@@ -1313,8 +1272,6 @@ def side_effect(resp, *args, **kwargs):
resp = nio.RoomGetStateEventResponse(
{"hello": {"encrypted_val": "enceventid"}}, "", "", ""
)
- resp.transport_response = AsyncMock()
- resp.transport_response.status = 200
return resp
else:
return nio.RoomGetEventError(message="testing")
| Matrix database raises an error when it should return None on getting a nonexistent key
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://riot.im/app/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
Please include a summary of the issue.
## Steps to Reproduce
Run `opsdroid.database.get("key")` when `"key"` has never been added to the room state.
## Expected Functionality
the `get()` method should return None
## Experienced Functionality
An exception was rasied:
<details>
```
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/opsdroid/core.py", line 427, in run_skill
return await skill(self, config, event)
File "/root/.local/share/opsdroid/opsdroid-modules/skill/motw/__init__.py", line 72, in _wrapper
return await func(opsdroid, config, message)
File "/root/.local/share/opsdroid/opsdroid-modules/skill/motw/__init__.py", line 277, in level_up
all_exp = await opsdroid.memory.get("motw_experience") or {}
File "/usr/local/lib/python3.8/site-packages/opsdroid/memory.py", line 37, in get
result = await self._get_from_database(key)
File "/usr/local/lib/python3.8/site-packages/opsdroid/memory.py", line 86, in _get_from_database
results.append(await database.get(key))
File "/usr/local/lib/python3.8/site-packages/opsdroid/database/matrix/__init__.py", line 173, in get
raise RuntimeError(
RuntimeError: Error getting motw_experience from matrix room !pgoIAkPLtxFWwdEVJf:cadair.com: Event not found.(M_NOT_FOUND)
```
</details>
## Versions
- **Opsdroid version:** master
- **Python version:** 3.8
## Database Config:
```
databases:
matrix:
single_state_key: False
no_cache: true
```
| 2020-12-04T09:19:46 |
|
opsdroid/opsdroid | 1,692 | opsdroid__opsdroid-1692 | [
"1691"
] | 03afd709682bd60deaeeb9c872e45a3aa153f4d8 | diff --git a/opsdroid/connector/gitter/__init__.py b/opsdroid/connector/gitter/__init__.py
--- a/opsdroid/connector/gitter/__init__.py
+++ b/opsdroid/connector/gitter/__init__.py
@@ -12,6 +12,7 @@
_LOGGER = logging.getLogger(__name__)
GITTER_STREAM_API = "https://stream.gitter.im/v1/rooms"
GITTER_MESSAGE_BASE_API = "https://api.gitter.im/v1/rooms"
+CURRENT_USER_API = "https://api.gitter.im/v1/user/me"
CONFIG_SCHEMA = {Required("token"): str, Required("room-id"): str, "bot-name": str}
@@ -23,9 +24,9 @@ def __init__(self, config, opsdroid=None):
super().__init__(config, opsdroid=opsdroid)
_LOGGER.debug(_("Starting Gitter Connector."))
self.name = "gitter"
+ self.bot_name = None # set at connection time
self.session = None
self.response = None
- self.bot_name = self.config.get("bot-name", "opsdroid")
self.room_id = self.config.get("room-id")
self.access_token = self.config.get("token")
self.update_interval = 1
@@ -40,13 +41,31 @@ async def connect(self):
_LOGGER.debug(_("Connecting with Gitter stream."))
self.session = aiohttp.ClientSession()
- gitter_url = self.build_url(
+ # Gitter figures out who we are based on just our access token, but we
+ # need to additionally know our own user ID in order to know which
+ # messages comes from us.
+ current_user_url = self.build_url(
+ CURRENT_USER_API,
+ access_token=self.access_token,
+ )
+ response = await self.session.get(current_user_url, timeout=None)
+ # We cannot continue without a user ID, so raise if this failed.
+ response.raise_for_status()
+ response_json = await response.json()
+ self.bot_gitter_id = response_json["id"]
+ self.bot_name = response_json["username"]
+ _LOGGER.debug(
+ _("Successfully obtained bot's gitter id, %s."), self.bot_gitter_id
+ )
+
+ message_stream_url = self.build_url(
GITTER_STREAM_API,
self.room_id,
"chatMessages",
access_token=self.access_token,
)
- self.response = await self.session.get(gitter_url, timeout=None)
+ self.response = await self.session.get(message_stream_url, timeout=None)
+ self.response.raise_for_status()
def build_url(self, base_url, *res, **params):
"""Build the url. args ex:(base_url,p1,p2=1,p2=2)."""
@@ -72,7 +91,8 @@ async def _get_messages(self):
await asyncio.sleep(self.update_interval)
async for data in self.response.content.iter_chunked(1024):
message = await self.parse_message(data)
- if message is not None:
+ # Do not parse messages that we ourselves sent.
+ if message is not None and message.user_id != self.bot_gitter_id:
await self.opsdroid.parse(message)
async def parse_message(self, message):
@@ -85,12 +105,12 @@ async def parse_message(self, message):
return Message(
text=message["text"],
user=message["fromUser"]["username"],
+ user_id=message["fromUser"]["id"],
target=self.room_id,
connector=self,
)
except KeyError as err:
- _LOGGER.error(_("Unable to parse message %s."), err)
- _LOGGER.error(err)
+ _LOGGER.error(_("Unable to parse message %r."), err)
@register_event(Message)
async def send_message(self, message):
| diff --git a/tests/test_connector_gitter.py b/tests/test_connector_gitter.py
--- a/tests/test_connector_gitter.py
+++ b/tests/test_connector_gitter.py
@@ -1,6 +1,7 @@
"""Tests for the RocketChat class."""
import asyncio
+import json
import unittest
import asynctest
import asynctest.mock as amock
@@ -40,13 +41,21 @@ def setUp(self):
self.connector.session = mocked_session
async def test_connect(self):
+ BOT_GITTER_ID = "12345"
with amock.patch("aiohttp.ClientSession.get") as patched_request:
mockresponse = amock.CoroutineMock()
mockresponse.status = 200
- mockresponse.json = amock.CoroutineMock(return_value={"login": "opsdroid"})
+ mockresponse.json = amock.CoroutineMock(
+ return_value={
+ "login": "opsdroid",
+ "id": BOT_GITTER_ID,
+ "username": "bot",
+ }
+ )
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(mockresponse)
await self.connector.connect()
+ assert self.connector.bot_gitter_id == BOT_GITTER_ID
def test_build_url(self):
self.assertEqual(
@@ -91,10 +100,23 @@ async def test_listen_break_loop(self):
async def test_get_message(self):
"""Test that listening consumes from the socket."""
+ BOT_GITTER_ID = "12345"
+ OTHER_GITTER_ID = "67890"
+
async def iter_chuncked1(n=None):
- response = [{"message": "hi"}, {"message": "hi"}]
+ response = [
+ {
+ "text": "hi",
+ "fromUser": {"username": "not a bot", "id": OTHER_GITTER_ID},
+ },
+ {"text": "hi", "fromUser": {"username": "bot", "id": BOT_GITTER_ID}},
+ {
+ "text": "hi",
+ "fromUser": {"username": "not a bot", "id": OTHER_GITTER_ID},
+ },
+ ]
for doc in response:
- yield doc
+ yield json.dumps(doc).encode()
response1 = amock.CoroutineMock()
response1.content.iter_chunked = iter_chuncked1
@@ -103,12 +125,26 @@ async def iter_chuncked1(n=None):
{"bot-name": "github", "room-id": "test-id", "token": "test-token"},
opsdroid=OpsDroid(),
)
- connector.parse_message = amock.CoroutineMock()
+ # Connect first, in order to set bot_gitter_id.
+ with amock.patch("aiohttp.ClientSession.get") as patched_request:
+ mockresponse = amock.CoroutineMock()
+ mockresponse.status = 200
+ mockresponse.json = amock.CoroutineMock(
+ return_value={
+ "login": "opsdroid",
+ "id": BOT_GITTER_ID,
+ "username": "bot",
+ }
+ )
+ patched_request.return_value = asyncio.Future()
+ patched_request.return_value.set_result(mockresponse)
+ await connector.connect()
+
connector.opsdroid.parse = amock.CoroutineMock()
connector.response = response1
assert await connector._get_messages() is None
- self.assertTrue(connector.parse_message.called)
- self.assertTrue(connector.opsdroid.parse.called)
+ # Should be called *twice* given these three messages (skipping own message)
+ assert connector.opsdroid.parse.call_count == 2
async def test_send_message_success(self):
post_response = amock.Mock()
| Making skill-hello case insensitive exposed a bug: infinite self-responses.
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://riot.im/app/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
Thanks for this great project!
While trying out a case-insensitive variation of skill-hello that I just [submitted as a PR against skill-hello](https://github.com/opsdroid/skill-hello/pull/4) I encountered an infinite loop of the bot responding to itself.
## Expected behavior
I expected to say "Hi" and get one "Hi" / "Hello" / "Hey" back.
## Experienced behavior
Instead, the bot responded to me and then to _itself_. It happens to respond with a capitalized first letter (e.g. "Hi", "Hey", "Hello"). This is why my case-insensitive variation happens to expose this self-response bug: it was previously ignoring "Hi" because of the capital "H". On my branch, it now matches its own responses.
In the detail box below I have pasted the relevant DEBUG logs, where you can see my initial message, its response (good so far...), and then a string of its responses to its own responses. The infinite loop eventually stopped after 20 messages or so; I suspect the bot was throttled by gitter at that point.
(In this example my username is `danielballan` and the bot is `twinkling-tree`. Forgive the silly bot name; my application is a hobby project controlling Christmas tree lights.)
<details>
```
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc10aa6bb528c38a9d47', 'text': 'hi', 'html': 'hi', 'sent': '2021-01-03T15:00:32.273Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '54ac2a22db8155e6700e6990', 'username': 'danielballan', 'displayName': 'Dan Allan', 'url': '/danielballan', 'avatarUrl': 'https://avatars-05.gitter.im/gh/uv/4/danielballan', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/2279598?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/2279598?v=4&s=128', 'v': 35, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=hi)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc1163fe034496359a84', 'text': 'Hi danielballan', 'html': 'Hi danielballan', 'sent': '2021-01-03T15:00:33.815Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hi danielballan)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc1197312f4b6b07832c', 'text': 'Hey twinkling-tree', 'html': 'Hey twinkling-tree', 'sent': '2021-01-03T15:00:33.910Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hey twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc12acd1e516f8ce8723', 'text': 'Hello twinkling-tree', 'html': 'Hello twinkling-tree', 'sent': '2021-01-03T15:00:34.012Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hello twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc12dbb17f28c5b79b25', 'text': 'Hey twinkling-tree', 'html': 'Hey twinkling-tree', 'sent': '2021-01-03T15:00:34.093Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hey twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc12de608143155d1990', 'text': 'Hi twinkling-tree', 'html': 'Hi twinkling-tree', 'sent': '2021-01-03T15:00:34.195Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hi twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc1269ee7f0422dd640f', 'text': 'Hey twinkling-tree', 'html': 'Hey twinkling-tree', 'sent': '2021-01-03T15:00:34.312Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hey twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc12acd1e516f8ce8726', 'text': 'Hey twinkling-tree', 'html': 'Hey twinkling-tree', 'sent': '2021-01-03T15:00:34.406Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hey twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc12c746c6431cf1d1cc', 'text': 'Hello twinkling-tree', 'html': 'Hello twinkling-tree', 'sent': '2021-01-03T15:00:34.509Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hello twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc12dbb17f28c5b79b28', 'text': 'Hi twinkling-tree', 'html': 'Hi twinkling-tree', 'sent': '2021-01-03T15:00:34.599Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hi twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc1222f12e449b2af62b', 'text': 'Hi twinkling-tree', 'html': 'Hi twinkling-tree', 'sent': '2021-01-03T15:00:34.709Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hi twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc12acd1e516f8ce872a', 'text': 'Hello twinkling-tree', 'html': 'Hello twinkling-tree', 'sent': '2021-01-03T15:00:34.797Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hello twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc12c746c6431cf1d1d3', 'text': 'Hi twinkling-tree', 'html': 'Hi twinkling-tree', 'sent': '2021-01-03T15:00:34.915Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hi twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc1397312f4b6b078330', 'text': 'Hi twinkling-tree', 'html': 'Hi twinkling-tree', 'sent': '2021-01-03T15:00:34.999Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hi twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc13e7f693041f4a73e3', 'text': 'Hi twinkling-tree', 'html': 'Hi twinkling-tree', 'sent': '2021-01-03T15:00:35.098Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hi twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc13acd1e516f8ce872e', 'text': 'Hi twinkling-tree', 'html': 'Hi twinkling-tree', 'sent': '2021-01-03T15:00:35.194Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hi twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc13dbb17f28c5b79b2c', 'text': 'Hi twinkling-tree', 'html': 'Hi twinkling-tree', 'sent': '2021-01-03T15:00:35.273Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hi twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc1369ee7f0422dd6413', 'text': 'Hey twinkling-tree', 'html': 'Hey twinkling-tree', 'sent': '2021-01-03T15:00:35.360Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hey twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc13dbb17f28c5b79b30', 'text': 'Hello twinkling-tree', 'html': 'Hello twinkling-tree', 'sent': '2021-01-03T15:00:35.443Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hello twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc1322f12e449b2af62f', 'text': 'Hello twinkling-tree', 'html': 'Hello twinkling-tree', 'sent': '2021-01-03T15:00:35.524Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hello twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc13c746c6431cf1d1d8', 'text': 'Hey twinkling-tree', 'html': 'Hey twinkling-tree', 'sent': '2021-01-03T15:00:35.612Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hey twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc138bb73474696f4e51', 'text': 'Hello twinkling-tree', 'html': 'Hello twinkling-tree', 'sent': '2021-01-03T15:00:35.699Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hello twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc1369ee7f0422dd6417', 'text': 'Hi twinkling-tree', 'html': 'Hi twinkling-tree', 'sent': '2021-01-03T15:00:35.790Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hi twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc13de608143155d1996', 'text': 'Hello twinkling-tree', 'html': 'Hello twinkling-tree', 'sent': '2021-01-03T15:00:35.883Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hello twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc1393af5216fc7c683f', 'text': 'Hey twinkling-tree', 'html': 'Hey twinkling-tree', 'sent': '2021-01-03T15:00:35.971Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hey twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc1497312f4b6b078334', 'text': 'Hey twinkling-tree', 'html': 'Hey twinkling-tree', 'sent': '2021-01-03T15:00:36.054Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hey twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc14ce40bd3cdb1b8692', 'text': 'Hi twinkling-tree', 'html': 'Hi twinkling-tree', 'sent': '2021-01-03T15:00:36.139Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hi twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc14ac9d8e7463ea02b2', 'text': 'Hey twinkling-tree', 'html': 'Hey twinkling-tree', 'sent': '2021-01-03T15:00:36.228Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hey twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc1422f12e449b2af633', 'text': 'Hello twinkling-tree', 'html': 'Hello twinkling-tree', 'sent': '2021-01-03T15:00:36.323Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hello twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc14aa6bb528c38a9d64', 'text': 'Hello twinkling-tree', 'html': 'Hello twinkling-tree', 'sent': '2021-01-03T15:00:36.408Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hello twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc1469ee7f0422dd641c', 'text': 'Hello twinkling-tree', 'html': 'Hello twinkling-tree', 'sent': '2021-01-03T15:00:36.499Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hello twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
DEBUG opsdroid.connector.gitter: {'id': '5ff1dc148bb73474696f4e55', 'text': 'Hi twinkling-tree', 'html': 'Hi twinkling-tree', 'sent': '2021-01-03T15:00:36.584Z', 'readBy': 0, 'urls': [], 'mentions': [], 'issues': [], 'meta': [], 'v': 1, 'fromUser': {'id': '5ff0c884d73408ce4ff7d787', 'username': 'twinkling-tree', 'displayName': 'twinkling-tree', 'url': '/twinkling-tree', 'avatarUrl': 'https://avatars-01.gitter.im/gh/uv/4/twinkling-tree', 'avatarUrlSmall': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=60', 'avatarUrlMedium': 'https://avatars2.githubusercontent.com/u/76883179?v=4&s=128', 'v': 3, 'gv': '4'}}
DEBUG opsdroid.core: Parsing input: <opsdroid.events.Message(text=Hi twinkling-tree)>.
DEBUG opsdroid.memory: Getting seen from memory.
DEBUG opsdroid.memory: Putting seen to memory.
INFO opsdroid.connector.gitter: Successfully responded.
```
</details>
## Steps to Reproduce
Run against the branch linked in the description and say "Hi" or any variation recognized by skill-hello.
## Versions
- **Opsdroid version:** 0.19.0
- **Python version:** 3.7.3
- **OS/Docker version:** Raspbian GNU/Linux 10
## Configuration File
```yaml
connectors:
gitter:
bot-name: "twinkling-tree"
room-id: "<room is>" # danielballan/twinkling-tree
token: "<token>"
skills:
custom_hello:
repo: "https://github.com/danielballan/skill-hello.git"
branch: "case_insensitive"
seen: {}
logging:
level: debug
path: ~/.opsdroid/output.log
console: true
```
The fix seems simple enough: the bot knows its `bot-name` from the configuration and should use that to avoid responding to itself. My question is, **Where is to right place to filter self-responses?** My first thought was to add this to `skill-hello`, but I don't think it has access to the bot name, only the sender. And this seems like something that should happen in a more general place, not a skill-specific one. Does this code belong in the gitter connector? I notice that `bot_name` is set that but not referred to anywhere in the class.
https://github.com/opsdroid/opsdroid/blob/03afd709682bd60deaeeb9c872e45a3aa153f4d8/opsdroid/connector/gitter/__init__.py#L28
It is used by another layer? Is that where this fix belongs? I'm happy to submit a patch if you can give me nudge in the right direction. Thanks!
---
Edit reasons: hide the token and room id.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| Hello and thank you for raising this issue. I'm thinking that the reason why opsdroid doesn't reply to itself in the case sensitive is mostly because it will reply with a lower case string 🤔
Your assumption is right, this seems a bug from the gitter connector itself, I'm thinking that if we change line 75 (that if statement) to handle the case where Message is coming from the bot.
The Message event contains a user parameter, we should check if we are creating the event right first when parsing the message - that should prevent opsdroid from replying to itself 🤔
Here's the [Message event docs](https://docs.opsdroid.dev/en/stable/skills/events.html#message) for reference
It would be awesome if you could tackle this issue, if you don't have the time I'll try to get a fix as soon as possible 😄
Btw make sure to refresh your gitter token 😄
Great, thanks. It makes sense this would have be handled in the connector. I think I can submit a patch in the next day or two for the gitter one.
Ha. Thanks for the heads up about the token—yikes.
No worries, I tend to leak my tokens while live stream all the time haha | 2021-01-04T14:35:55 |
opsdroid/opsdroid | 1,707 | opsdroid__opsdroid-1707 | [
"813"
] | ad8007b78f8da36ebec02a57dfd3e3f6d3d31e89 | diff --git a/opsdroid/connector/matrix/connector.py b/opsdroid/connector/matrix/connector.py
--- a/opsdroid/connector/matrix/connector.py
+++ b/opsdroid/connector/matrix/connector.py
@@ -13,7 +13,7 @@
from opsdroid import const, events
from opsdroid.connector import Connector, register_event
-from voluptuous import Required
+from voluptuous import Required, Inclusive
from . import events as matrixevents
from .create_events import MatrixEventCreator
@@ -21,8 +21,9 @@
_LOGGER = logging.getLogger(__name__)
CONFIG_SCHEMA = {
- Required("mxid"): str,
- Required("password"): str,
+ Inclusive("mxid", "login"): str,
+ Inclusive("password", "login"): str,
+ "access_token": str,
Required("rooms"): dict,
"homeserver": str,
"nick": str,
@@ -90,10 +91,11 @@ def __init__(self, config, opsdroid=None): # noqa: D107
self.rooms = self._process_rooms_dict(config["rooms"])
self.room_ids = {}
self.default_target = self.rooms["main"]["alias"]
- self.mxid = config["mxid"]
+ self.mxid = config.get("mxid")
+ self.password = config.get("password")
+ self.access_token = config.get("access_token")
self.nick = config.get("nick")
self.homeserver = config.get("homeserver", "https://matrix.org")
- self.password = config["password"]
self.room_specific_nicks = config.get("room_specific_nicks", False)
self.send_m_notice = config.get("send_m_notice", False)
self.session = None
@@ -144,18 +146,14 @@ def filter_json(self):
"event_format": "client",
"account_data": {"limit": 0, "types": []},
"presence": {"limit": 0, "types": []},
- "room": {
- "account_data": {"types": []},
- "ephemeral": {"types": []},
- "state": {"types": []},
- },
+ "room": {"account_data": {"types": []}, "ephemeral": {"types": []}},
}
)
async def make_filter(self, api, fjson):
"""Make a filter on the server for future syncs."""
path = f"/_matrix/client/r0/user/{self.mxid}/filter"
- headers = {"Authorization": f"Bearer {api.token}"}
+ headers = {"Authorization": f"Bearer {api.access_token}"}
resp = await api.send(method="post", path=path, data=fjson, headers=headers)
resp_json = await resp.json()
@@ -194,7 +192,7 @@ async def connect(self):
pickle_key="",
store_name="opsdroid.db" if self._allow_encryption else "",
)
- mapi = nio.AsyncClient(
+ self.connection = nio.AsyncClient(
self.homeserver,
self.mxid,
config=config,
@@ -202,20 +200,41 @@ async def connect(self):
device_id=self.device_id,
)
- login_response = await mapi.login(
- password=self.password, device_name=self.device_name
- )
- if isinstance(login_response, nio.LoginError):
- _LOGGER.error(
- f"Error while connecting: {login_response.message} (status code {login_response.status_code})"
+ if self.access_token is not None:
+ self.connection.access_token = self.access_token
+
+ whoami_response = await self.connection.whoami()
+ if isinstance(whoami_response, nio.responses.WhoamiError):
+ _LOGGER.error(
+ f"Error while connecting: {whoami_response.message} (status code {whoami_response.status_code})"
+ )
+ return
+
+ self.mxid = whoami_response.user_id
+ self.connection.user_id = self.mxid
+
+ elif self.mxid is not None and self.password is not None:
+ login_response = await self.connection.login(
+ password=self.password, device_name=self.device_name
)
- return
+ if isinstance(login_response, nio.LoginError):
+ _LOGGER.error(
+ f"Error while connecting: {login_response.message} (status code {login_response.status_code})"
+ )
+ return
- mapi.token = login_response.access_token
- mapi.sync_token = None
+ self.access_token = (
+ self.connection.access_token
+ ) = login_response.access_token
+ else:
+ raise ValueError(
+ "Configuration for the matrix connector should specify mxid and password or access_token."
+ ) # pragma: no cover
+
+ self.connection.sync_token = None
for roomname, room in self.rooms.items():
- response = await mapi.join(room["alias"])
+ response = await self.connection.join(room["alias"])
if isinstance(response, nio.JoinError):
_LOGGER.error(
f"Error while joining room: {room['alias']}, Message: {response.message} (status code {response.status_code})"
@@ -224,12 +243,10 @@ async def connect(self):
else:
self.room_ids[roomname] = response.room_id
- self.connection = mapi
-
# Create a filter now, saves time on each later sync
- self.filter_id = await self.make_filter(mapi, self.filter_json)
+ self.filter_id = await self.make_filter(self.connection, self.filter_json)
first_filter_id = await self.make_filter(
- mapi, '{ "room": { "timeline" : { "limit" : 1 } } }'
+ self.connection, '{ "room": { "timeline" : { "limit" : 1 } } }'
)
# Do initial sync so we don't get old messages later.
@@ -249,8 +266,20 @@ async def connect(self):
if self.nick:
display_name = await self.connection.get_displayname(self.mxid)
+ if isinstance(display_name, nio.ErrorResponse):
+ _LOGGER.warning(
+ f"Error fetching current display_name: {display_name.message} (status code {display_name.status_code})"
+ )
+ display_name = None
+ else:
+ display_name = display_name.displayname
+
if display_name != self.nick:
- await self.connection.set_displayname(self.nick)
+ display_name_resp = await self.connection.set_displayname(self.nick)
+ if isinstance(display_name_resp, nio.ErrorResponse):
+ _LOGGER.warning(
+ f"Error setting display_name: {display_name_resp.message} (status code {display_name_resp.status_code})"
+ )
async def disconnect(self):
"""Close the matrix session."""
diff --git a/opsdroid/core.py b/opsdroid/core.py
--- a/opsdroid/core.py
+++ b/opsdroid/core.py
@@ -149,7 +149,7 @@ def handle_async_exception(loop, context):
# pylint: disable=broad-except
except Exception: # pragma: nocover
print("Caught exception")
- print(context)
+ print(context)
def is_running(self):
"""Check whether opsdroid is running."""
| diff --git a/opsdroid/connector/github/tests/test_connector_github.py b/opsdroid/connector/github/tests/test_connector_github.py
--- a/opsdroid/connector/github/tests/test_connector_github.py
+++ b/opsdroid/connector/github/tests/test_connector_github.py
@@ -57,7 +57,7 @@ async def test_connect(connector, mock_api):
assert mock_api.called("/user")
assert mock_api.call_count("/user") == 1
- request = mock_api.get_request("/user")
+ request = mock_api.get_request("/user", "GET")
assert "Authorization" in request.headers
assert "abc123" in request.headers["Authorization"]
@@ -96,29 +96,20 @@ async def test_listen(connector):
async def test_send(opsdroid, connector, mock_api):
await opsdroid.send(
Message(
- text="test",
- user="jacobtomlinson",
- target=ISSUE_TARGET,
- connector=connector,
+ text="test", user="jacobtomlinson", target=ISSUE_TARGET, connector=connector
)
)
assert mock_api.called(COMMENTS_URI)
@pytest.mark.add_response(
- COMMENTS_URI,
- "POST",
- get_response_path("github_send_failure.json"),
- status=400,
+ COMMENTS_URI, "POST", get_response_path("github_send_failure.json"), status=400
)
@pytest.mark.asyncio
async def test_send_failure(opsdroid, connector, mock_api, caplog):
await opsdroid.send(
Message(
- text="test",
- user="jacobtomlinson",
- target=ISSUE_TARGET,
- connector=connector,
+ text="test", user="jacobtomlinson", target=ISSUE_TARGET, connector=connector
)
)
assert mock_api.called(COMMENTS_URI)
@@ -132,10 +123,7 @@ async def test_do_not_send_to_self(opsdroid, connector, mock_api):
await opsdroid.send(
Message(
- text="test",
- user="opsdroid-bot",
- target=ISSUE_TARGET,
- connector=connector,
+ text="test", user="opsdroid-bot", target=ISSUE_TARGET, connector=connector
)
)
assert not mock_api.called(COMMENTS_URI)
diff --git a/opsdroid/connector/matrix/tests/conftest.py b/opsdroid/connector/matrix/tests/conftest.py
new file mode 100644
--- /dev/null
+++ b/opsdroid/connector/matrix/tests/conftest.py
@@ -0,0 +1,150 @@
+import json
+from pathlib import Path
+
+import pytest
+
+from opsdroid.connector.matrix import ConnectorMatrix
+
+################################################################################
+# Connector and config fixtures.
+################################################################################
+
+
[email protected]
+def default_config(mock_api_obj):
+ return {"homeserver": mock_api_obj.base_url, "rooms": {"main": "#test:localhost"}}
+
+
[email protected]
+def login_config(mock_api_obj):
+ return {
+ "mxid": "@opsdroid:localhost",
+ "password": "supersecret",
+ "homeserver": mock_api_obj.base_url,
+ "rooms": {"main": "#test:localhost"},
+ }
+
+
[email protected]
+def token_config(mock_api_obj):
+ return {
+ "access_token": "token",
+ "homeserver": mock_api_obj.base_url,
+ "rooms": {"main": "#test:localhost"},
+ }
+
+
[email protected]
+async def connector(opsdroid, request, mock_api_obj):
+ if hasattr(request, "param"):
+ fix_name = request.param
+ else:
+ marker = request.node.get_closest_marker("matrix_connector_config")
+ fix_name = marker.args[0]
+
+ if isinstance(fix_name, str):
+ config = request.getfixturevalue(fix_name)
+ elif isinstance(fix_name, dict):
+ config = fix_name
+ else:
+ raise TypeError(
+ "Config should be a string name for a fixture or a dict for the config"
+ )
+
+ if "homeserver" not in config:
+ config["homeserver"] = mock_api_obj.base_url
+
+ conn = ConnectorMatrix(config, opsdroid=opsdroid)
+ yield conn
+ if conn.connection is not None:
+ await conn.disconnect()
+
+
+################################################################################
+# Sync Factory
+################################################################################
+
+
+def get_matrix_response(name):
+ return Path(__file__).parent / "responses" / f"{name}.json"
+
+
+def empty_sync(room_id):
+ with open(get_matrix_response("empty_sync_response")) as fobj:
+ empty_sync = json.load(fobj)
+
+ room_block = empty_sync["rooms"]["join"].pop("ROOMID")
+ empty_sync["rooms"]["join"][room_id] = room_block
+
+ return empty_sync
+
+
+def event_factory(event_type, content, sender):
+ return {
+ "content": content,
+ "event_id": "$1234567890987654321234567890",
+ "origin_server_ts": 9876543210,
+ "sender": sender,
+ "type": event_type,
+ "unsigned": {"age": 100},
+ }
+
+
+def message_factory(body, msgtype, sender, **extra_content):
+ content = {"msgtype": msgtype, "body": body, **extra_content}
+ return event_factory("m.room.message", content, sender)
+
+
+def sync_response(events, room_id="!12345:localhost"):
+ sync = empty_sync(room_id)
+ sync["rooms"]["join"][room_id]["timeline"]["events"] = events
+ return sync
+
+
[email protected]
+def message_sync_response(request):
+ room_id = "!12345:localhost"
+ room_id_markers = [
+ marker for marker in request.node.own_markers if marker.name == "sync_room_id"
+ ]
+ if room_id:
+ room_id = room_id_markers[0].args[0]
+
+ markers = [
+ marker
+ for marker in request.node.own_markers
+ if marker.name == "add_sync_messsage"
+ ]
+
+ events = []
+ for marker in markers:
+ events.append(message_factory(*marker.args, **marker.kwargs))
+
+ return sync_response(events, room_id=room_id)
+
+
+################################################################################
+# Response Fixtures
+################################################################################
+
+
[email protected]
+def double_filter_response(mock_api_obj):
+ mock_api_obj.add_response(
+ "/_matrix/client/r0/user/@opsdroid:localhost/filter",
+ "POST",
+ {"filter_id": "1234567890"},
+ )
+ mock_api_obj.add_response(
+ "/_matrix/client/r0/user/@opsdroid:localhost/filter",
+ "POST",
+ {"filter_id": "0987654321"},
+ )
+
+
[email protected]
+def single_message_sync_response(mock_api_obj):
+ """Return a sync response with a single test message in it."""
+ event = message_factory("Test", "m.text", "@stuart:localhost")
+ sync = sync_response([event])
+ mock_api_obj.add_response("/_matrix/client/r0/sync", "GET", sync)
diff --git a/opsdroid/connector/matrix/tests/responses/empty_sync_response.json b/opsdroid/connector/matrix/tests/responses/empty_sync_response.json
new file mode 100644
--- /dev/null
+++ b/opsdroid/connector/matrix/tests/responses/empty_sync_response.json
@@ -0,0 +1,47 @@
+{
+ "account_data": {
+ "events": []
+ },
+ "device_lists": {
+ "changed": [],
+ "left": []
+ },
+ "device_one_time_keys_count": {
+ "signed_curve25519": 0
+ },
+ "next_batch": "s12_19_4_2_5_1_1_11_1",
+ "presence": {
+ "events": [
+ ]
+ },
+ "rooms": {
+ "invite": {},
+ "join": {
+ "ROOMID": {
+ "account_data": {
+ "events": []
+ },
+ "ephemeral": {
+ "events": []
+ },
+ "state": {
+ "events": []
+ },
+ "summary": {},
+ "timeline": {
+ "events": [],
+ "limited": false,
+ "prev_batch": "s11_19_4_2_5_1_1_11_1"
+ },
+ "unread_notifications": {
+ "highlight_count": 0,
+ "notification_count": 0
+ }
+ }
+ },
+ "leave": {}
+ },
+ "to_device": {
+ "events": []
+ }
+}
diff --git a/opsdroid/connector/matrix/tests/test_connector_connect.py b/opsdroid/connector/matrix/tests/test_connector_connect.py
new file mode 100644
--- /dev/null
+++ b/opsdroid/connector/matrix/tests/test_connector_connect.py
@@ -0,0 +1,214 @@
+import pytest
+import logging
+
+from opsdroid.connector.matrix import ConnectorMatrix
+
+
+def test_constructor(opsdroid, default_config):
+ connector = ConnectorMatrix(default_config, opsdroid)
+ assert isinstance(connector, ConnectorMatrix)
+
+
[email protected]
+def mock_whoami_join(mock_api_obj):
+ mock_api_obj.add_response(
+ "/_matrix/client/r0/account/whoami", "GET", {"user_id": "@opsdroid:localhost"}
+ )
+ mock_api_obj.add_response(
+ "/_matrix/client/r0/join/#test:localhost",
+ "POST",
+ {"room_id": "!12355:localhost"},
+ )
+
+
[email protected]_connector_config("token_config")
[email protected]
+async def test_connect_access_token(
+ opsdroid,
+ connector,
+ double_filter_response,
+ single_message_sync_response,
+ mock_whoami_join,
+ mock_api,
+):
+ assert isinstance(connector, ConnectorMatrix)
+ assert connector.access_token == "token"
+ await connector.connect()
+
+ assert mock_api.called("/_matrix/client/r0/account/whoami")
+ assert (
+ mock_api.call_count("/_matrix/client/r0/user/@opsdroid:localhost/filter") == 2
+ )
+ assert mock_api.called("/_matrix/client/r0/sync")
+ assert mock_api.called("/_matrix/client/r0/join/#test:localhost")
+
+ whoami_call = mock_api.get_request("/_matrix/client/r0/account/whoami", "GET", 0)
+ assert "access_token" in whoami_call.query
+ assert whoami_call.query["access_token"] == "token"
+
+
[email protected]_connector_config("token_config")
[email protected]_response(
+ "/_matrix/client/r0/account/whoami",
+ "GET",
+ {"errcode": "M_UNKNOWN_TOKEN", "error": "Invalid macaroon passed."},
+ status=401,
+)
[email protected]
+async def test_connect_invalid_access_token(caplog, opsdroid, connector, mock_api):
+ assert isinstance(connector, ConnectorMatrix)
+ assert connector.access_token == "token"
+ await connector.connect()
+
+ assert mock_api.called("/_matrix/client/r0/account/whoami")
+
+ assert "Invalid macaroon passed." in caplog.records[0].message
+ assert "M_UNKNOWN_TOKEN" in caplog.records[0].message
+
+
[email protected]_connector_config("login_config")
[email protected]_response(
+ "/_matrix/client/r0/login",
+ "POST",
+ {
+ "user_id": "@opsdroid:localhost",
+ "access_token": "abc123",
+ "device_id": "GHTYAJCE",
+ },
+)
[email protected]
+async def test_connect_login(
+ opsdroid,
+ connector,
+ double_filter_response,
+ single_message_sync_response,
+ mock_whoami_join,
+ mock_api,
+):
+ assert isinstance(connector, ConnectorMatrix)
+ await connector.connect()
+
+ assert mock_api.called("/_matrix/client/r0/login")
+ assert (
+ mock_api.call_count("/_matrix/client/r0/user/@opsdroid:localhost/filter") == 2
+ )
+ assert mock_api.called("/_matrix/client/r0/sync")
+ assert mock_api.called("/_matrix/client/r0/join/#test:localhost")
+
+ assert connector.access_token == connector.connection.access_token == "abc123"
+
+
[email protected]_connector_config("login_config")
[email protected]_response(
+ "/_matrix/client/r0/login",
+ "POST",
+ {"errcode": "M_FORBIDDEN", "error": "Invalid password"},
+ status=403,
+)
[email protected]
+async def test_connect_login_error(caplog, opsdroid, connector, mock_api):
+ assert isinstance(connector, ConnectorMatrix)
+ await connector.connect()
+
+ assert mock_api.called("/_matrix/client/r0/login")
+
+ assert "Invalid password" in caplog.records[0].message
+ assert "M_FORBIDDEN" in caplog.records[0].message
+
+
[email protected]_connector_config("token_config")
[email protected]_response(
+ "/_matrix/client/r0/account/whoami", "GET", {"user_id": "@opsdroid:localhost"}
+)
[email protected]_response(
+ "/_matrix/client/r0/join/#test:localhost",
+ "POST",
+ {"errcode": "M_FORBIDDEN", "error": "You are not invited to this room."},
+ status=403,
+)
[email protected]
+async def test_connect_join_fail(
+ opsdroid,
+ connector,
+ double_filter_response,
+ single_message_sync_response,
+ mock_api,
+ caplog,
+):
+ assert isinstance(connector, ConnectorMatrix)
+ assert connector.access_token == "token"
+ await connector.connect()
+
+ assert caplog.record_tuples == [
+ (
+ "opsdroid.connector.matrix.connector",
+ logging.ERROR,
+ "Error while joining room: #test:localhost, Message: You are not invited to this room. (status code M_FORBIDDEN)",
+ )
+ ]
+
+
[email protected]_connector_config(
+ {"access_token": "token", "rooms": {"main": "#test:localhost"}, "nick": "opsdroid"}
+)
[email protected]_response(
+ "/_matrix/client/r0/profile/@opsdroid:localhost/displayname",
+ "PUT",
+ {"errcode": "M_FORBIDDEN", "error": "Invalid user"},
+ status=403,
+)
[email protected]
+async def test_connect_set_nick_errors(
+ opsdroid,
+ connector,
+ double_filter_response,
+ single_message_sync_response,
+ mock_whoami_join,
+ mock_api,
+ caplog,
+):
+ await connector.connect()
+
+ assert caplog.record_tuples == [
+ (
+ "opsdroid.connector.matrix.connector",
+ logging.WARNING,
+ "Error fetching current display_name: unknown error (status code None)",
+ ),
+ (
+ "opsdroid.connector.matrix.connector",
+ logging.WARNING,
+ "Error setting display_name: Invalid user (status code M_FORBIDDEN)",
+ ),
+ ]
+
+ caplog.clear()
+
+
[email protected]_connector_config(
+ {"access_token": "token", "rooms": {"main": "#test:localhost"}, "nick": "opsdroid"}
+)
[email protected]_response(
+ "/_matrix/client/r0/profile/@opsdroid:localhost/displayname", "PUT", {}
+)
[email protected]_response(
+ "/_matrix/client/r0/profile/@opsdroid:localhost/displayname",
+ "GET",
+ {"displayname": "Wibble"},
+)
[email protected]
+async def test_connect_set_nick(
+ opsdroid,
+ connector,
+ double_filter_response,
+ single_message_sync_response,
+ mock_whoami_join,
+ mock_api,
+):
+ await connector.connect()
+ assert mock_api.called(
+ "/_matrix/client/r0/profile/@opsdroid:localhost/displayname", "GET"
+ )
+ assert mock_api.called(
+ "/_matrix/client/r0/profile/@opsdroid:localhost/displayname", "PUT"
+ )
diff --git a/opsdroid/testing/external_api.py b/opsdroid/testing/external_api.py
--- a/opsdroid/testing/external_api.py
+++ b/opsdroid/testing/external_api.py
@@ -5,6 +5,7 @@
for both opsdroid core and skills.
"""
import asyncio
+from collections import defaultdict
import json
from contextlib import asynccontextmanager
from os import PathLike
@@ -64,9 +65,9 @@ def __init__(self):
self.site = None
self.host = "localhost"
self.port = 8089
- self._calls = {}
- self.responses = {}
- self._payloads = {}
+ self._calls = defaultdict(list)
+ self.responses = defaultdict(list)
+ self._payloads = defaultdict(list)
self.status = "stopped"
self.start_timeout = 10 # seconds
@@ -98,15 +99,12 @@ async def stop(self) -> None:
async def _handler(self, request: web.Request) -> web.Response:
route = request.path
- if route in self._calls:
- self._calls[route].append(request)
- else:
- self._calls[route] = [request]
- if route in self._payloads:
- self._payloads[route].append(await request.post())
- else:
- self._payloads[route] = [await request.post()]
- status, response = self.responses[route].pop(0)
+ method = request.method
+
+ self._calls[(route, method)].append(request)
+ self._payloads[route].append(await request.post())
+
+ status, response = self.responses[(route, method)].pop(0)
return web.json_response(response, status=status)
@property
@@ -128,20 +126,19 @@ def add_response(
else:
response = response
- if route in self.responses:
- self.responses[route].append((status, response))
- else:
-
+ if (route, method) not in self.responses:
if method.upper() == "GET":
routes = [web.get(route, self._handler)]
elif method.upper() == "POST":
routes = [web.post(route, self._handler)]
+ elif method.upper() == "PUT":
+ routes = [web.put(route, self._handler)]
else:
raise TypeError(f"Unsupported method {method}")
-
- self.responses[route] = [(status, response)]
self.app.add_routes(routes)
+ self.responses[(route, method)].append((status, response))
+
@asynccontextmanager
async def running(self) -> "ExternalAPIMockServer":
"""Start the External API server within a context manager."""
@@ -158,7 +155,7 @@ def reset(self) -> None:
else:
raise RuntimeError("Web server must be stopped before it can be reset.")
- def called(self, route: str) -> bool:
+ def called(self, route: str, method: str = None) -> bool:
"""Route has been called.
Args:
@@ -168,9 +165,12 @@ def called(self, route: str) -> bool:
Wether or not it was called.
"""
- return route in self._calls
+ if not method:
+ return route in [k[0] for k in self._calls.keys()]
- def call_count(self, route: str) -> int:
+ return (route, method) in self._calls
+
+ def call_count(self, route: str, method: str = None) -> int:
"""Route has been called n times.
Args:
@@ -180,9 +180,15 @@ def call_count(self, route: str) -> int:
The number of times it was called.
"""
- return len(self._calls[route])
+ if not method:
+ all_calls = [
+ len(call[1]) for call in self._calls.items() if call[0][0] == route
+ ]
+ return sum(all_calls)
+
+ return len(self._calls[(route, method)])
- def get_request(self, route: str, idx: int = 0) -> web.Request:
+ def get_request(self, route: str, method: str, idx: int = 0) -> web.Request:
"""Route has been called n times.
Args:
@@ -193,7 +199,7 @@ def get_request(self, route: str, idx: int = 0) -> web.Request:
The request that was made.
"""
- return self._calls[route][idx]
+ return self._calls[(route, method)][idx]
def get_payload(self, route: str, idx: int = 0) -> Dict:
"""Return data payload that the route was called with.
diff --git a/opsdroid/testing/tests/test_testing.py b/opsdroid/testing/tests/test_testing.py
--- a/opsdroid/testing/tests/test_testing.py
+++ b/opsdroid/testing/tests/test_testing.py
@@ -46,7 +46,7 @@ async def test_external_api_mock_server(session):
assert resp.status == 200
assert mock_api.called("/test")
assert mock_api.call_count("/test") == i + 1
- assert mock_api.get_request("/test").path == "/test"
+ assert mock_api.get_request("/test", "GET").path == "/test"
async with session.post(
f"{mock_api.base_url}/fail", data={"hello": "world"}
diff --git a/tests/test_connector_matrix.py b/tests/test_connector_matrix.py
--- a/tests/test_connector_matrix.py
+++ b/tests/test_connector_matrix.py
@@ -284,171 +284,6 @@ async def test_exchange_keys(self, mocker, connector):
assert patched_keys_query.called
patched_keys_claim.assert_called_with(patched_get_users())
- async def test_connect(self, mocker, caplog, connector):
- with amock.patch(api_string.format("login")) as patched_login, amock.patch(
- api_string.format("join")
- ) as patched_join, amock.patch(
- api_string.format("sync")
- ) as patched_sync, amock.patch(
- api_string.format("send")
- ) as patched_filter, amock.patch(
- api_string.format("get_displayname")
- ) as patched_get_nick, amock.patch(
- api_string.format("set_displayname")
- ) as patch_set_nick, amock.patch(
- api_string.format("send_to_device_messages")
- ) as patched_send_to_device, amock.patch(
- api_string.format("should_upload_keys")
- ) as patched_should_upload, amock.patch(
- api_string.format("should_query_keys")
- ) as patched_should_query, amock.patch(
- api_string.format("keys_upload")
- ) as patched_keys_upload, amock.patch(
- api_string.format("keys_query")
- ) as patched_keys_query, amock.patch(
- "pathlib.Path.mkdir"
- ) as patched_mkdir, amock.patch(
- "pathlib.Path.is_dir"
- ) as patched_is_dir, amock.patch(
- "aiohttp.ClientSession"
- ) as patch_cs, OpsDroid() as _:
-
- # Skip actually creating a client session
- patch_cs.return_value = amock.MagicMock()
-
- patched_login.return_value = asyncio.Future()
- patched_login.return_value.set_result(
- nio.LoginResponse(
- user_id="@opsdroid:localhost",
- device_id="testdevice",
- access_token="arbitrary string1",
- )
- )
-
- patched_join.return_value = asyncio.Future()
- patched_join.return_value.set_result(
- nio.JoinResponse(room_id="!aroomid:localhost")
- )
-
- patched_sync.return_value = asyncio.Future()
- patched_sync.return_value.set_result(
- nio.SyncResponse(
- next_batch="arbitrary string2",
- rooms={},
- device_key_count={"signed_curve25519": 50},
- device_list={"changed": [], "left": []},
- to_device_events={"events": []},
- presence_events={"events": []},
- )
- )
-
- connect_response = amock.Mock()
- connect_response.status = 200
- connect_response.json = amock.CoroutineMock()
- connect_response.return_value = {"filter_id": 1}
-
- patched_filter.return_value = asyncio.Future()
- patched_filter.return_value.set_result(connect_response)
-
- patch_set_nick.return_value = asyncio.Future()
- patch_set_nick.return_value.set_result(nio.ProfileSetDisplayNameResponse())
-
- patched_is_dir.return_value = False
- patched_mkdir.return_value = None
-
- patched_send_to_device.return_value = asyncio.Future()
- patched_send_to_device.return_value.set_result(None)
-
- patched_should_upload.return_value = True
- patched_keys_upload.return_value = asyncio.Future()
- patched_keys_upload.return_value.set_result(None)
-
- patched_should_query.return_value = True
- patched_keys_query.return_value = asyncio.Future()
- patched_keys_query.return_value.set_result(None)
-
- await connector.connect()
-
- if nio.crypto.ENCRYPTION_ENABLED:
- assert patched_mkdir.called
-
- assert patched_send_to_device.called
- assert patched_keys_upload.called
- assert patched_keys_query.called
-
- assert "!aroomid:localhost" in connector.room_ids.values()
-
- assert connector.connection.token == "arbitrary string1"
-
- assert connector.connection.sync_token == "arbitrary string2"
-
- connector.nick = "Rabbit Hole"
-
- patched_get_nick.return_value = asyncio.Future()
- patched_get_nick.return_value.set_result("Rabbit Hole")
-
- await connector.connect()
-
- assert patched_get_nick.called
- assert not patch_set_nick.called
-
- patched_get_nick.return_value = asyncio.Future()
- patched_get_nick.return_value.set_result("Neo")
-
- connector.mxid = "@morpheus:matrix.org"
-
- await connector.connect()
-
- assert patched_get_nick.called
- patch_set_nick.assert_called_once_with("Rabbit Hole")
-
- error_message = "Some error message"
- error_code = 400
-
- # test sync error
- patched_sync.return_value = asyncio.Future()
- patched_sync.return_value.set_result(
- nio.SyncError(message=error_message, status_code=error_code)
- )
- caplog.clear()
- await connector.connect()
- assert [
- f"Error during initial sync: {error_message} (status code {error_code})"
- ] == [rec.message for rec in caplog.records]
-
- # test join error
- patched_sync.return_value = asyncio.Future()
- patched_sync.return_value.set_result(
- nio.SyncResponse(
- next_batch="arbitrary string2",
- rooms={},
- device_key_count={"signed_curve25519": 50},
- device_list={"changed": [], "left": []},
- to_device_events={"events": []},
- presence_events={"events": []},
- )
- )
- patched_join.return_value = asyncio.Future()
- patched_join.return_value.set_result(
- nio.JoinError(message=error_message, status_code=error_code)
- )
- caplog.clear()
- await connector.connect()
- assert [
- f"Error while joining room: {connector.rooms['main']['alias']}, Message: {error_message} (status code {error_code})"
- ] == [rec.message for rec in caplog.records]
-
- # test login error
- patched_login.return_value = asyncio.Future()
- patched_login.return_value.set_result(
- nio.LoginError(message=error_message, status_code=error_code)
- )
- caplog.clear()
- await connector.connect()
- assert [
- f"Error while connecting: {error_message} (status code {error_code})"
- ] == [rec.message for rec in caplog.records]
-
async def test_parse_sync_response(self, connector):
connector.room_ids = {"main": "!aroomid:localhost"}
connector.filter_id = "arbitrary string"
| support providing an access token in the configuration for the matrix connector rather than the password
This would alleviate the need to plain text the password in the config, and the access token can be deactivated. This would be a case of detecting the key in the config and skipping the login call
| Could you create a PR with the changes that have been merged into your fork? Seems like a nice thing to add 😄
There is / was one
Erm... yeah you are right! Ignore me 😬
Would be good to get some progress on that. Looks like the change is done, just needs tests and docs.
I am going to write tests for it and docs. Will create a PR later today hopefully 😄
Just submitted a PR. Tox showed that the coverage was 100% hopefully it will work and we can merge the PR 😄 | 2021-01-16T18:07:49 |
opsdroid/opsdroid | 1,708 | opsdroid__opsdroid-1708 | [
"1704"
] | 88de58e4c2bebe912b11eb340e7091b8d31327f6 | diff --git a/opsdroid/core.py b/opsdroid/core.py
--- a/opsdroid/core.py
+++ b/opsdroid/core.py
@@ -56,7 +56,7 @@ def __init__(self, config=None, config_path=None):
if os.name != "nt":
for sig in (signal.SIGINT, signal.SIGTERM):
self.eventloop.add_signal_handler(
- sig, lambda: asyncio.ensure_future(self.handle_signal())
+ sig, lambda: asyncio.ensure_future(self.handle_stop_signal())
)
self.eventloop.add_signal_handler(
signal.SIGHUP, lambda: asyncio.ensure_future(self.reload())
@@ -155,9 +155,10 @@ def is_running(self):
"""Check whether opsdroid is running."""
return self._running
- async def handle_signal(self):
+ async def handle_stop_signal(self):
"""Handle signals."""
self._running = False
+ await self.stop()
await self.unload()
def run(self):
| diff --git a/tests/test_core.py b/tests/test_core.py
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -217,13 +217,15 @@ async def mockedskill(message):
mockedskill.config = {}
return mockedskill
- async def test_handle_signal(self):
+ async def test_handle_stop_signal(self):
with OpsDroid() as opsdroid:
opsdroid._running = True
self.assertTrue(opsdroid.is_running())
+ opsdroid.stop = amock.CoroutineMock()
opsdroid.unload = amock.CoroutineMock()
- await opsdroid.handle_signal()
+ await opsdroid.handle_stop_signal()
self.assertFalse(opsdroid.is_running())
+ self.assertTrue(opsdroid.stop.called)
self.assertTrue(opsdroid.unload.called)
async def test_unload_and_stop(self):
| Opsdroid does not exit with ctrl-c
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://riot.im/app/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
Opsdroid is not exiting with ctrl-c. When starting Opsdroid locally, I was able to exit the bot with the ctrl-c escape key. Now it only hangs, and I have to kill the process manually to exit,
## Steps to Reproduce
- Clone the repo and install the latest branch of Opsdroid
- execute `opsdroid start`
I have tested this without a configuration file, so it uses the default one, and also is happening when trying to connect with the slack connector.
## Expected Functionality
ctrl-c signal should work when executed.
## Experienced Functionality
- ctl-c signal is not working and opsdroid just hangs there. I has to be manually killed
## Versions
- **Opsdroid version:** v0.19.0+84.ga99dfb6
- **Python version:** Tested in 3.7.7 and 3.8.5 same issue on both
- **OS/Docker version:** Ubuntu 20.04
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
```
--> opsdroid start
INFO opsdroid.logging: ========================================
INFO opsdroid.logging: Started opsdroid v0.19.0+84.ga99dfb6.
INFO opsdroid: ========================================
INFO opsdroid: You can customise your opsdroid by modifying your configuration.yaml.
INFO opsdroid: Read more at: http://opsdroid.readthedocs.io/#configuration
INFO opsdroid: Watch the Get Started Videos at: http://bit.ly/2fnC0Fh
INFO opsdroid: Install Opsdroid Desktop at:
https://github.com/opsdroid/opsdroid-desktop/releases
INFO opsdroid: ========================================
WARNING opsdroid.loader: No databases in configuration. This will cause skills which store things in memory to lose data when opsdroid is restarted.
INFO opsdroid.core: Opsdroid is now running, press ctrl+c to exit.
INFO opsdroid.web: Started web server on http://0.0.0.0:8080
^C^Cc^C^C^C^C^C^C
```
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| cc @cognifloyd. I think this may be due to recent signalling work. | 2021-01-17T00:22:06 |
opsdroid/opsdroid | 1,715 | opsdroid__opsdroid-1715 | [
"1712"
] | 467477e5bb6030286adda3ec657127d0568c2141 | diff --git a/opsdroid/connector/matrix/connector.py b/opsdroid/connector/matrix/connector.py
--- a/opsdroid/connector/matrix/connector.py
+++ b/opsdroid/connector/matrix/connector.py
@@ -182,7 +182,6 @@ async def exchange_keys(self, initial_sync=False):
async def connect(self):
"""Create connection object with chat library."""
-
if self._allow_encryption:
_LOGGER.debug(f"Using {self.store_path} for the matrix client store.")
Path(self.store_path).mkdir(exist_ok=True)
@@ -299,14 +298,12 @@ async def _parse_sync_response(self, response):
][0]
sender = await self.get_nick(None, invite_event.sender)
- await self.opsdroid.parse(
- events.UserInvite(
- target=roomid,
- user_id=invite_event.sender,
- user=sender,
- connector=self,
- raw_event=invite_event,
- )
+ yield events.UserInvite(
+ target=roomid,
+ user_id=invite_event.sender,
+ user=sender,
+ connector=self,
+ raw_event=invite_event,
)
for roomid, roomInfo in response.rooms.join.items():
@@ -320,7 +317,7 @@ async def _parse_sync_response(self, response):
event = self.connection.decrypt_event(event)
except nio.exceptions.EncryptionError: # pragma: no cover
_LOGGER.exception(f"Failed to decrypt event {event}")
- return await self._event_creator.create_event(
+ yield await self._event_creator.create_event(
event.source, roomid
)
@@ -342,10 +339,8 @@ async def listen(self): # pragma: no cover
await self.exchange_keys()
- message = await self._parse_sync_response(response)
-
- if message:
- await self.opsdroid.parse(message)
+ async for event in self._parse_sync_response(response):
+ await self.opsdroid.parse(event)
def lookup_target(self, room):
"""Convert name or alias of a room to the corresponding room ID."""
| diff --git a/opsdroid/connector/matrix/tests/conftest.py b/opsdroid/connector/matrix/tests/conftest.py
--- a/opsdroid/connector/matrix/tests/conftest.py
+++ b/opsdroid/connector/matrix/tests/conftest.py
@@ -2,6 +2,7 @@
from pathlib import Path
import pytest
+import nio
from opsdroid.connector.matrix import ConnectorMatrix
@@ -35,7 +36,7 @@ def token_config(mock_api_obj):
@pytest.fixture
-async def connector(opsdroid, request, mock_api_obj):
+async def connector(opsdroid, request, mock_api_obj, mocker):
if hasattr(request, "param"):
fix_name = request.param
else:
@@ -55,11 +56,31 @@ async def connector(opsdroid, request, mock_api_obj):
config["homeserver"] = mock_api_obj.base_url
conn = ConnectorMatrix(config, opsdroid=opsdroid)
+ conn.connection = mocker.MagicMock()
yield conn
- if conn.connection is not None:
+ if isinstance(conn.connection, nio.AsyncClient):
await conn.disconnect()
[email protected]
+async def connector_connected(
+ opsdroid,
+ double_filter_response,
+ single_message_sync_response,
+ mock_whoami_join,
+ mock_api,
+):
+ config = {
+ "access_token": "token",
+ "homeserver": mock_api.base_url,
+ "rooms": {"main": "#test:localhost"},
+ }
+ conn = ConnectorMatrix(config, opsdroid=opsdroid)
+ await conn.connect()
+ yield conn
+ await conn.disconnect()
+
+
################################################################################
# Sync Factory
################################################################################
@@ -148,3 +169,15 @@ def single_message_sync_response(mock_api_obj):
event = message_factory("Test", "m.text", "@stuart:localhost")
sync = sync_response([event])
mock_api_obj.add_response("/_matrix/client/r0/sync", "GET", sync)
+
+
[email protected]
+def mock_whoami_join(mock_api_obj):
+ mock_api_obj.add_response(
+ "/_matrix/client/r0/account/whoami", "GET", {"user_id": "@opsdroid:localhost"}
+ )
+ mock_api_obj.add_response(
+ "/_matrix/client/r0/join/#test:localhost",
+ "POST",
+ {"room_id": "!12355:localhost"},
+ )
diff --git a/opsdroid/connector/matrix/tests/test_connector_connect.py b/opsdroid/connector/matrix/tests/test_connector_connect.py
--- a/opsdroid/connector/matrix/tests/test_connector_connect.py
+++ b/opsdroid/connector/matrix/tests/test_connector_connect.py
@@ -9,18 +9,6 @@ def test_constructor(opsdroid, default_config):
assert isinstance(connector, ConnectorMatrix)
[email protected]
-def mock_whoami_join(mock_api_obj):
- mock_api_obj.add_response(
- "/_matrix/client/r0/account/whoami", "GET", {"user_id": "@opsdroid:localhost"}
- )
- mock_api_obj.add_response(
- "/_matrix/client/r0/join/#test:localhost",
- "POST",
- {"room_id": "!12355:localhost"},
- )
-
-
@pytest.mark.matrix_connector_config("token_config")
@pytest.mark.asyncio
async def test_connect_access_token(
diff --git a/opsdroid/connector/matrix/tests/test_event_parsing.py b/opsdroid/connector/matrix/tests/test_event_parsing.py
new file mode 100644
--- /dev/null
+++ b/opsdroid/connector/matrix/tests/test_event_parsing.py
@@ -0,0 +1,56 @@
+from opsdroid.connector.matrix.tests.conftest import message_factory, sync_response
+import pytest
+
+from nio.responses import SyncResponse
+
+
+async def events_from_sync(events, connector):
+ response = SyncResponse.from_dict(sync_response(events))
+ return [m async for m in connector._parse_sync_response(response)]
+
+
+def assert_event_properties(event, **kwargs):
+ for attr, value in kwargs.items():
+ assert getattr(event, attr) == value
+
+
[email protected]_response(
+ "/_matrix/client/r0/profile/@test:localhost/displayname",
+ "GET",
+ {"displayname": "test"},
+)
[email protected]_response(
+ "/_matrix/client/r0/profile/@test:localhost/displayname",
+ "GET",
+ {"displayname": "test"},
+)
[email protected]_connector_config(
+ {"access_token": "hello", "rooms": {"main": "#test:localhost"}}
+)
[email protected]
+async def test_receive_message(opsdroid, connector_connected, mock_api, caplog):
+ events = await events_from_sync(
+ [
+ message_factory("Hello", "m.text", "@test:localhost"),
+ message_factory("Hello2", "m.text", "@test:localhost"),
+ ],
+ connector_connected,
+ )
+
+ assert_event_properties(
+ events[0],
+ text="Hello",
+ user_id="@test:localhost",
+ user="test",
+ target="!12345:localhost",
+ )
+
+ assert_event_properties(
+ events[1],
+ text="Hello2",
+ user_id="@test:localhost",
+ user="test",
+ target="!12345:localhost",
+ )
+
+ assert len(caplog.records) == 0, caplog.records
diff --git a/tests/test_connector_matrix.py b/tests/test_connector_matrix.py
--- a/tests/test_connector_matrix.py
+++ b/tests/test_connector_matrix.py
@@ -295,7 +295,12 @@ async def test_parse_sync_response(self, connector):
nio.ProfileGetDisplayNameResponse("SomeUsersName")
)
- returned_message = await connector._parse_sync_response(self.sync_return)
+ returned_message = [
+ m async for m in connector._parse_sync_response(self.sync_return)
+ ]
+ assert len(returned_message) == 1
+
+ returned_message = returned_message[0]
assert isinstance(returned_message, events.Message)
assert returned_message.text == "LOUD NOISES"
@@ -309,9 +314,9 @@ async def test_parse_sync_response(self, connector):
)
assert returned_message.raw_event == raw_message
- returned_message = await connector._parse_sync_response(
- self.sync_return_join
- )
+ returned_message = [
+ m async for m in connector._parse_sync_response(self.sync_return_join)
+ ][0]
assert isinstance(returned_message, events.JoinRoom)
assert returned_message.user == "SomeUsersName"
@@ -327,17 +332,14 @@ async def test_parse_sync_response(self, connector):
async def test_sync_parse_invites(self, connector):
with amock.patch(api_string.format("get_displayname")) as patched_name:
- connector.opsdroid = amock.MagicMock()
- connector.opsdroid.parse.return_value = asyncio.Future()
- connector.opsdroid.parse.return_value.set_result("")
patched_name.return_value = asyncio.Future()
patched_name.return_value.set_result(
nio.ProfileGetDisplayNameResponse("SomeUsersName")
)
- await connector._parse_sync_response(self.sync_invite)
-
- (invite,), _ = connector.opsdroid.parse.call_args
+ (invite,) = [
+ m async for m in connector._parse_sync_response(self.sync_invite)
+ ]
assert invite.target == "!AWtmOvkBPTCSPbdaHn:localhost"
assert invite.user == "SomeUsersName"
@@ -477,7 +479,8 @@ async def _get_message(self, connector):
patched_nick.return_value = asyncio.Future()
patched_nick.return_value.set_result("Neo")
- return await connector._parse_sync_response(self.sync_return)
+ async for x in connector._parse_sync_response(self.sync_return):
+ return x
async def test_send_edited_message(self, connector):
message = events.EditedMessage(
@@ -498,10 +501,7 @@ def expected_content(message):
"msgtype": "m.text",
"m.new_content": new_content,
"body": f"* {new_content['body']}",
- "m.relates_to": {
- "rel_type": "m.replace",
- "event_id": event_id,
- },
+ "m.relates_to": {"rel_type": "m.replace", "event_id": event_id},
}
with amock.patch(
@@ -616,10 +616,7 @@ def test_get_roomname(self, connector):
assert connector.get_roomname("someroom") == "someroom"
def test_lookup_target(self, connector):
- connector.room_ids = {
- "main": "!aroomid:localhost",
- "test": "#test:localhost",
- }
+ connector.room_ids = {"main": "!aroomid:localhost", "test": "#test:localhost"}
assert connector.lookup_target("main") == "!aroomid:localhost"
assert connector.lookup_target("#test:localhost") == "!aroomid:localhost"
@@ -1011,10 +1008,7 @@ async def test_respond_user_role(self, connector):
async def test_send_reaction(self, connector):
message = events.Message(
- "hello",
- event_id="$11111",
- connector=connector,
- target="!test:localhost",
+ "hello", event_id="$11111", connector=connector, target="!test:localhost"
)
reaction = events.Reaction("⭕")
with OpsDroid() as _:
@@ -1038,10 +1032,7 @@ async def test_send_reaction(self, connector):
async def test_send_reply(self, connector):
message = events.Message(
- "hello",
- event_id="$11111",
- connector=connector,
- target="!test:localhost",
+ "hello", event_id="$11111", connector=connector, target="!test:localhost"
)
reply = events.Reply("reply")
with OpsDroid() as _:
@@ -1169,10 +1160,7 @@ async def test_no_user_id(self, connector):
)
def test_m_notice(self, connector):
- connector.rooms["test"] = {
- "alias": "#test:localhost",
- "send_m_notice": True,
- }
+ connector.rooms["test"] = {"alias": "#test:localhost", "send_m_notice": True}
assert connector.message_type("main") == "m.text"
assert connector.message_type("test") == "m.notice"
| Handle multiple events in a single sync response in the matrix connector
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://riot.im/app/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
Currently, when parsing a sync response, the matrix connector returns out of the method when it encounters the first event in the timeline.
https://github.com/opsdroid/opsdroid/blob/3fe47d89df719e22861352fc3806d4093832c024/opsdroid/connector/matrix/connector.py#L284-L286
This is then subsequently passed to `opsdroid.parse` in the `listen` method:
https://github.com/opsdroid/opsdroid/blob/3fe47d89df719e22861352fc3806d4093832c024/opsdroid/connector/matrix/connector.py#L306-L309
The fix for this is to allow returning a list of `Event`s from the `_parse_sync_response` method and then iterating over them in `listen`.
| An alternative (probably preferable) solution is to move the call to `opsdroid.parse` into the `_parse_sync_response` method.
Since I am a beginner, I am not sure if what I understood was what you were referring to. Just wanted to ask is it just moving the call for `opsdorid.parse` in the `_parse_sync_response` method instead of this [return statement](https://github.com/opsdroid/opsdroid/blob/3fe47d89df719e22861352fc3806d4093832c024/opsdroid/connector/matrix/connector.py#L284) where each event will be passed in the `opsdorid.parse` method inside the `for` loop.
This is approximately @Cadair's solution in #1715.
```python
async def _parse_sync_response(self, response):
# ... snip
for roomid, roomInfo in response.rooms.join.items():
if roomInfo.timeline:
for event in roomInfo.timeline.events:
if event.sender != self.mxid:
# ... snip
await self.opsdroid.parse(
self._event_creator.create_event(event.source, roomid)
)
async def listen(self):
# ... snip
while True:
response = await self.connection.sync(
# ... snip
)
# ... snip
await self._parse_sync_response(response)
```
I think this might be a bit cleaner (which I've recommended in #1715):
```python
async def _parse_sync_response(self, response):
# ... snip
for roomid, roomInfo in response.rooms.join.items():
if roomInfo.timeline:
for event in roomInfo.timeline.events:
if event.sender != self.mxid:
# ... snip
yield await self._event_creator.create_event(
event.source, roomid
)
return
async def listen(self):
# ... snip
while True:
response = await self.connection.sync(
# ... snip
)
# ... snip
async for message in self._parse_sync_response(response):
if message:
await self.opsdroid.parse(message)
```
I was thinking more like this, similar to @Cadair :
>
> ```python
> async def _parse_sync_response(self, response):
> # ... snip
> for roomid, roomInfo in response.rooms.join.items():
> if roomInfo.timeline:
> for event in roomInfo.timeline.events:
> if event.sender != self.mxid:
> # ... snip
> await self.opsdroid.parse(
> self._event_creator.create_event(event.source, roomid)
> )
>
> async def listen(self):
> # ... snip
> while True:
> response = await self.connection.sync(
> # ... snip
> )
> # ... snip
> await self._parse_sync_response(response)
> ```
>
@cognifloyd, yours is also a beautiful solution:
>
> ```python
> async def _parse_sync_response(self, response):
> # ... snip
> for roomid, roomInfo in response.rooms.join.items():
> if roomInfo.timeline:
> for event in roomInfo.timeline.events:
> if event.sender != self.mxid:
> # ... snip
> yield await self._event_creator.create_event(
> event.source, roomid
> )
> return
>
> async def listen(self):
> # ... snip
> while True:
> response = await self.connection.sync(
> # ... snip
> )
> # ... snip
> async for message in self._parse_sync_response(response):
> if message:
> await self.opsdroid.parse(message)
> ```
@Cadair, @cognifloyd Do you want me to make the change as the one stated above? | 2021-01-18T16:59:33 |
opsdroid/opsdroid | 1,721 | opsdroid__opsdroid-1721 | [
"1713"
] | 623a70bbc002db570915fb8336ddd5ed4abb8638 | diff --git a/opsdroid/connector/matrix/connector.py b/opsdroid/connector/matrix/connector.py
--- a/opsdroid/connector/matrix/connector.py
+++ b/opsdroid/connector/matrix/connector.py
@@ -9,6 +9,7 @@
import aiohttp
import nio
import nio.responses
+import nio.exceptions
from opsdroid import const, events
from opsdroid.connector import Connector, register_event
@@ -29,6 +30,7 @@
"device_name": str,
"device_id": str,
"store_path": str,
+ "enable_encryption": bool,
}
__all__ = ["ConnectorMatrix"]
@@ -103,7 +105,14 @@ def __init__(self, config, opsdroid=None): # noqa: D107
"store_path", str(Path(const.DEFAULT_ROOT_PATH, "matrix"))
)
self._ignore_unverified = True
- self._allow_encryption = nio.crypto.ENCRYPTION_ENABLED
+ self._allow_encryption = config.get("enable_encryption", False)
+ if (
+ self._allow_encryption and not nio.crypto.ENCRYPTION_ENABLED
+ ): # pragma: no cover
+ _LOGGER.warning(
+ "enable_encryption is True but encryption support is not available."
+ )
+ self._allow_encryption = False
self._event_creator = MatrixEventCreator(self)
@@ -278,9 +287,10 @@ async def _parse_sync_response(self, response):
if event.source["type"] == "m.room.member":
event.source["content"] = event.content
if isinstance(event, nio.MegolmEvent):
- _LOGGER.error(
- f"Failed to decrypt event {event}"
- ) # pragma: nocover
+ try: # pragma: no cover
+ event = self.connection.decrypt_event(event)
+ except nio.exceptions.EncryptionError: # pragma: no cover
+ _LOGGER.exception(f"Failed to decrypt event {event}")
return await self._event_creator.create_event(
event.source, roomid
)
| diff --git a/tests/test_connector_matrix.py b/tests/test_connector_matrix.py
--- a/tests/test_connector_matrix.py
+++ b/tests/test_connector_matrix.py
@@ -28,6 +28,7 @@ def connector():
"mxid": "@opsdroid:localhost",
"password": "hello",
"homeserver": "http://localhost:8008",
+ "enable_encryption": True,
}
)
api = nio.AsyncClient("https://notaurl.com", None)
diff --git a/tests/test_database_matrix.py b/tests/test_database_matrix.py
--- a/tests/test_database_matrix.py
+++ b/tests/test_database_matrix.py
@@ -29,6 +29,7 @@ def opsdroid_matrix(mocker):
"mxid": "@opsdroid:localhost",
"password": "hello",
"homeserver": "http://localhost:8008",
+ "enable_encryption": True,
}
)
connector.room_ids = {"main": "!notaroomid"}
| Log information if the matrix connector is unable to decrypt an event
This requires understanding the [matrix-nio](https://github.com/poljar/matrix-nio) library for how (if at all) this information is exposed.
The relevant section of the code is:
https://github.com/opsdroid/opsdroid/blob/3fe47d89df719e22861352fc3806d4093832c024/opsdroid/connector/matrix/connector.py#L280-L283
| 2021-01-20T21:29:40 |
|
opsdroid/opsdroid | 1,742 | opsdroid__opsdroid-1742 | [
"1720"
] | 210aa307eac3123da14bf6b0275bd20c80b7892c | diff --git a/opsdroid/connector/matrix/connector.py b/opsdroid/connector/matrix/connector.py
--- a/opsdroid/connector/matrix/connector.py
+++ b/opsdroid/connector/matrix/connector.py
@@ -96,7 +96,11 @@ def __init__(self, config, opsdroid=None): # noqa: D107
self.access_token = config.get("access_token")
self.nick = config.get("nick")
self.homeserver = config.get("homeserver", "https://matrix.org")
- self.room_specific_nicks = config.get("room_specific_nicks", False)
+ # deprecated in 0.21
+ if config.get("room_specific_nicks", None):
+ _LOGGER.warning(
+ "The `room_specific_nicks` config option is deprecated as it is now always True."
+ ) # pragma: no cover
self.send_m_notice = config.get("send_m_notice", False)
self.session = None
self.filter_id = None
@@ -296,12 +300,11 @@ async def _parse_sync_response(self, response):
if isinstance(e, nio.InviteMemberEvent)
if e.membership == "invite"
][0]
- sender = await self.get_nick(None, invite_event.sender)
yield events.UserInvite(
target=roomid,
user_id=invite_event.sender,
- user=sender,
+ user=invite_event.sender,
connector=self,
raw_event=invite_event,
)
@@ -354,25 +357,16 @@ async def get_nick(self, roomid, mxid):
Get the nickname of a sender depending on the room specific config
setting.
"""
- if self.room_specific_nicks and roomid is not None:
-
- res = await self.connection.joined_members(roomid)
- if isinstance(res, nio.JoinedMembersError):
- logging.exception("Failed to lookup room members for %s.", roomid)
- # fallback to global profile
- else:
- for member in res.members:
- if member.user_id == mxid:
- return member.display_name
- return mxid
-
- res = await self.connection.get_displayname(mxid)
- if isinstance(res, nio.ProfileGetDisplayNameError):
- _LOGGER.error("Failed to lookup nick for %s.", mxid)
- return mxid
- if res.displayname is None:
+ room_state = await self.connection.room_get_state_event(
+ roomid, "m.room.member", mxid
+ )
+ if isinstance(room_state, nio.RoomGetStateEventError):
+ _LOGGER.error(
+ f"Error during getting display name from room state: {room_state.message} (status code {room_state.status_code})"
+ )
return mxid
- return res.displayname
+
+ return room_state.content.get("displayname", mxid) or mxid
def get_roomname(self, room):
"""Get the name of a room from alias or room ID."""
| diff --git a/opsdroid/connector/matrix/tests/test_event_parsing.py b/opsdroid/connector/matrix/tests/test_event_parsing.py
--- a/opsdroid/connector/matrix/tests/test_event_parsing.py
+++ b/opsdroid/connector/matrix/tests/test_event_parsing.py
@@ -1,8 +1,11 @@
-from opsdroid.connector.matrix.tests.conftest import message_factory, sync_response
+import logging
+
import pytest
from nio.responses import SyncResponse
+from opsdroid.connector.matrix.tests.conftest import message_factory, sync_response
+
async def events_from_sync(events, connector):
response = SyncResponse.from_dict(sync_response(events))
@@ -15,12 +18,12 @@ def assert_event_properties(event, **kwargs):
@pytest.mark.add_response(
- "/_matrix/client/r0/profile/@test:localhost/displayname",
+ "/_matrix/client/r0/rooms/!12345:localhost/state/m.room.member/@test:localhost",
"GET",
{"displayname": "test"},
)
@pytest.mark.add_response(
- "/_matrix/client/r0/profile/@test:localhost/displayname",
+ "/_matrix/client/r0/rooms/!12345:localhost/state/m.room.member/@test:localhost",
"GET",
{"displayname": "test"},
)
@@ -53,4 +56,89 @@ async def test_receive_message(opsdroid, connector_connected, mock_api, caplog):
target="!12345:localhost",
)
- assert len(caplog.records) == 0, caplog.records
+ assert len(caplog.record_tuples) == 0, caplog.records
+
+
[email protected]_connector_config(
+ {"access_token": "hello", "rooms": {"main": "#test:localhost"}}
+)
[email protected]
+async def test_get_nick_error(opsdroid, connector_connected, mock_api, caplog):
+ events = await events_from_sync(
+ [
+ message_factory("Hello", "m.text", "@test:localhost"),
+ ],
+ connector_connected,
+ )
+
+ assert_event_properties(
+ events[0],
+ text="Hello",
+ user_id="@test:localhost",
+ user="@test:localhost",
+ target="!12345:localhost",
+ )
+
+ assert len(caplog.record_tuples) == 1
+
+ assert caplog.record_tuples == [
+ (
+ "opsdroid.connector.matrix.connector",
+ logging.ERROR,
+ "Error during getting display name from room state: unknown error (status code None)",
+ )
+ ]
+
+
[email protected]_response(
+ "/_matrix/client/r0/rooms/!12345:localhost/state/m.room.member/@test:localhost",
+ "GET",
+ {"displayname": "test"},
+)
[email protected]_connector_config(
+ {"access_token": "hello", "rooms": {"main": "#test:localhost"}}
+)
[email protected]
+async def test_invite_with_message(opsdroid, connector_connected, mock_api, caplog):
+ events = [
+ message_factory("Hello", "m.text", "@test:localhost"),
+ ]
+
+ sync_dict = sync_response(events)
+ sync_dict["rooms"]["invite"] = {
+ "!12345:localhost": {
+ "invite_state": {
+ "events": [
+ {
+ "content": {"displayname": "Test", "membership": "invite"},
+ "origin_server_ts": 1612718865588,
+ "sender": "@other:localhost",
+ "state_key": "@test:localhost",
+ "type": "m.room.member",
+ "event_id": "$NGAUv_hybVRv5jop5SdWyMW-fCJ66D5d4FMNtydCzw",
+ }
+ ]
+ }
+ }
+ }
+
+ response = SyncResponse.from_dict(sync_dict)
+
+ events = [m async for m in connector_connected._parse_sync_response(response)]
+
+ assert_event_properties(
+ events[0],
+ user_id="@other:localhost",
+ user="@other:localhost",
+ target="!12345:localhost",
+ )
+
+ assert_event_properties(
+ events[1],
+ text="Hello",
+ user_id="@test:localhost",
+ user="test",
+ target="!12345:localhost",
+ )
+
+ assert len(caplog.record_tuples) == 0, caplog.records
diff --git a/tests/test_connector_matrix.py b/tests/test_connector_matrix.py
--- a/tests/test_connector_matrix.py
+++ b/tests/test_connector_matrix.py
@@ -284,181 +284,6 @@ async def test_exchange_keys(self, mocker, connector):
assert patched_keys_query.called
patched_keys_claim.assert_called_with(patched_get_users())
- async def test_parse_sync_response(self, connector):
- connector.room_ids = {"main": "!aroomid:localhost"}
- connector.filter_id = "arbitrary string"
-
- with amock.patch(api_string.format("get_displayname")) as patched_name:
-
- patched_name.return_value = asyncio.Future()
- patched_name.return_value.set_result(
- nio.ProfileGetDisplayNameResponse("SomeUsersName")
- )
-
- returned_message = [
- m async for m in connector._parse_sync_response(self.sync_return)
- ]
- assert len(returned_message) == 1
-
- returned_message = returned_message[0]
-
- assert isinstance(returned_message, events.Message)
- assert returned_message.text == "LOUD NOISES"
- assert returned_message.user == "SomeUsersName"
- assert returned_message.target == "!aroomid:localhost"
- assert returned_message.connector == connector
- raw_message = (
- self.sync_return.rooms.join["!aroomid:localhost"]
- .timeline.events[0]
- .source
- )
- assert returned_message.raw_event == raw_message
-
- returned_message = [
- m async for m in connector._parse_sync_response(self.sync_return_join)
- ][0]
-
- assert isinstance(returned_message, events.JoinRoom)
- assert returned_message.user == "SomeUsersName"
- assert returned_message.target == "!aroomid:localhost"
- assert returned_message.connector == connector
- raw_message = (
- self.sync_return_join.rooms.join["!aroomid:localhost"]
- .timeline.events[0]
- .source
- )
- raw_message["content"] = {"membership": "join"}
- assert returned_message.raw_event == raw_message
-
- async def test_sync_parse_invites(self, connector):
- with amock.patch(api_string.format("get_displayname")) as patched_name:
- patched_name.return_value = asyncio.Future()
- patched_name.return_value.set_result(
- nio.ProfileGetDisplayNameResponse("SomeUsersName")
- )
-
- (invite,) = [
- m async for m in connector._parse_sync_response(self.sync_invite)
- ]
-
- assert invite.target == "!AWtmOvkBPTCSPbdaHn:localhost"
- assert invite.user == "SomeUsersName"
- assert invite.user_id == "@neo:matrix.org"
- assert invite.connector is connector
-
- async def test_get_nick(self, connector):
- connector.room_specific_nicks = False
-
- with amock.patch(api_string.format("get_displayname")) as patched_globname:
-
- mxid = "@notaperson:matrix.org"
-
- patched_globname.return_value = asyncio.Future()
- patched_globname.return_value.set_result(
- nio.ProfileGetDisplayNameResponse(displayname="notaperson")
- )
- assert await connector.get_nick("#notaroom:localhost", mxid) == "notaperson"
-
- async def test_get_room_specific_nick(self, caplog, connector):
- connector.room_specific_nicks = True
-
- with amock.patch(
- api_string.format("get_displayname")
- ) as patched_globname, amock.patch(
- api_string.format("joined_members")
- ) as patched_joined:
-
- mxid = "@notaperson:matrix.org"
-
- patched_globname.return_value = asyncio.Future()
- patched_globname.return_value.set_result(
- nio.ProfileGetDisplayNameResponse(displayname="notaperson")
- )
-
- patched_joined.return_value = asyncio.Future()
- patched_joined.return_value.set_result(
- nio.JoinedMembersResponse(
- members=[
- nio.RoomMember(
- user_id="@notaperson:matrix.org",
- display_name="notaperson",
- avatar_url="",
- )
- ],
- room_id="notanid",
- )
- )
-
- assert await connector.get_nick("#notaroom:localhost", mxid) == "notaperson"
-
- assert await connector.get_nick(None, mxid) == "notaperson"
-
- # test member not in list
- patched_joined.return_value = asyncio.Future()
- patched_joined.return_value.set_result(
- nio.JoinedMembersResponse(members=[], room_id="notanid")
- )
- assert await connector.get_nick("#notaroom:localhost", mxid) == mxid
-
- # test JoinedMembersError
- patched_joined.return_value = asyncio.Future()
- patched_joined.return_value.set_result(
- nio.JoinedMembersError(message="Some error", status_code=400)
- )
- caplog.clear()
- assert await connector.get_nick("#notaroom:localhost", mxid) == "notaperson"
- assert ["Failed to lookup room members for #notaroom:localhost."] == [
- rec.message for rec in caplog.records
- ]
-
- # test displayname is not set
- patched_globname.return_value = asyncio.Future()
- patched_globname.return_value.set_result(
- nio.ProfileGetDisplayNameResponse(displayname=None)
- )
- caplog.clear()
- assert await connector.get_nick("#notaroom:localhost", mxid) == mxid
- assert ["Failed to lookup room members for #notaroom:localhost."] == [
- rec.message for rec in caplog.records
- ]
-
- # test ProfileGetDisplayNameError
- patched_globname.return_value = asyncio.Future()
- patched_globname.return_value.set_result(
- nio.ProfileGetDisplayNameError(message="Some error", status_code=400)
- )
- caplog.clear()
- assert await connector.get_nick("#notaroom:localhost", mxid) == mxid
- assert f"Failed to lookup nick for {mxid}." == caplog.records[1].message
-
- async def test_get_nick_not_set(self, connector):
- connector.room_specific_nicks = False
-
- with amock.patch(api_string.format("get_displayname")) as patched_globname:
-
- mxid = "@notaperson:matrix.org"
-
- # Test that failed nickname lookup returns the mxid
- patched_globname.return_value = asyncio.Future()
- patched_globname.return_value.set_result(
- nio.ProfileGetDisplayNameResponse(displayname=None)
- )
- assert await connector.get_nick("#notaroom:localhost", mxid) == mxid
-
- async def test_get_nick_error(self, connector):
- connector.room_specific_nicks = False
-
- with amock.patch(api_string.format("get_displayname")) as patched_globname:
-
- mxid = "@notaperson:matrix.org"
-
- # Test if that leads to a global displayname being returned
- patched_globname.return_value = asyncio.Future()
- patched_globname.return_value.set_result(
- nio.ProfileGetDisplayNameError(message="Error")
- )
- assert await connector.get_nick("#notaroom:localhost", mxid) == mxid
-
async def test_get_formatted_message_body(self, connector):
original_html = "<p><h3><no>Hello World</no></h3></p>"
original_body = "### Hello World"
| Improve performance of room_specific_nicks in matrix connector
# Description
At the moment we iterate over all the members in a room to calculate the room specific nick names:
https://github.com/opsdroid/opsdroid/blob/623a70bbc002db570915fb8336ddd5ed4abb8638/opsdroid/connector/matrix/connector.py#L325-L333
This is very inefficient when we can use the state endpoint to query it for the specific user: https://matrix.org/docs/spec/client_server/r0.5.0#get-matrix-client-r0-rooms-roomid-state-eventtype-statekey
Using the https://matrix-nio.readthedocs.io/en/latest/nio.html#nio.AsyncClient.room_get_state_event method from nio
| 2021-02-07T17:08:20 |
|
opsdroid/opsdroid | 1,774 | opsdroid__opsdroid-1774 | [
"1773"
] | bd61d9ac606817b294473910bb06f2a71ffcd4d8 | diff --git a/opsdroid/connector/mattermost/__init__.py b/opsdroid/connector/mattermost/__init__.py
--- a/opsdroid/connector/mattermost/__init__.py
+++ b/opsdroid/connector/mattermost/__init__.py
@@ -95,10 +95,10 @@ async def process_message(self, raw_message):
post = json.loads(data["post"])
await self.opsdroid.parse(
Message(
- post["message"],
- data["sender_name"],
- data["channel_name"],
- self,
+ text=post["message"],
+ user=data["sender_name"],
+ target=data["channel_name"],
+ connector=self,
raw_event=message,
)
)
| diff --git a/tests/test_connector_mattermost.py b/tests/test_connector_mattermost.py
--- a/tests/test_connector_mattermost.py
+++ b/tests/test_connector_mattermost.py
@@ -170,6 +170,8 @@ async def test_send_message(self):
)
connector.mm_driver.posts = mock.Mock()
connector.mm_driver.posts.create_post = mock.MagicMock()
- await connector.send(Message("test", "user", "room", connector))
+ await connector.send(
+ Message(text="test", user="user", target="room", connector=connector)
+ )
self.assertTrue(connector.mm_driver.channels.get_channel_by_name_and_team_name)
self.assertTrue(connector.mm_driver.posts.create_post.called)
| Mattermost connector is broken
# Description
The Mattermost connector is broken. It can connect to a Mattermost instance, but when sending a message to OpsDroid (using the Hello skill) you get:
```
ERROR opsdroid.core: Exception when running skill 'hello'.
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/opsdroid/core.py", line 465, in run_skill
return await skill(event)
File "/root/.local/share/opsdroid/opsdroid-modules/skill/hello/__init__.py", line 13, in hello
await message.respond(text)
File "/usr/local/lib/python3.8/site-packages/opsdroid/events.py", line 278, in respond
"thinking-delay" in self.connector.configuration
AttributeError: 'NoneType' object has no attribute 'configuration'
WARNING mattermostdriver.websocket: Failed to establish websocket connection: 'NoneType' object has no attribute 'configuration'
```
## Steps to Reproduce
Configure the Mattermost connector and the Hello skill, start Opsdroid and send a message to the bot in Mattermost.
## Expected Functionality
A reply form the Hello skill.
## Experienced Functionality
No reply, and the above error in the Opsdroid logs.
## Versions
- **Opsdroid version:** 0.22.0
- **Python version:** 3.8
- **OS/Docker version:** N/A
## Configuration File
Please include your version of the configuration file below.
```yaml
welcome-message: false
connectors:
## Mattermost (core)
mattermost:
# Required
token: "<redacted>"
url: "<redacted>"
team-name: "<redacted>"
# Optional
scheme: "https" # default: https
port: 443 # default: 8065
ssl-verify: true # default: true
connect-timeout: 30 # default: 30
skills:
## Hello (https://github.com/opsdroid/skill-hello)
hello: {}
## Seen (https://github.com/opsdroid/skill-seen)
seen: {}
```
## Additional Details
Looks like this the Mattermost connector was missed in #1116 -- I'll submit a PR shortly to correct this.
| 2021-05-13T08:15:27 |
|
opsdroid/opsdroid | 1,776 | opsdroid__opsdroid-1776 | [
"1775"
] | 638e3a85e6a557a18097d06ef6d5f4d1c50bd0a1 | diff --git a/opsdroid/connector/mattermost/__init__.py b/opsdroid/connector/mattermost/__init__.py
--- a/opsdroid/connector/mattermost/__init__.py
+++ b/opsdroid/connector/mattermost/__init__.py
@@ -39,6 +39,7 @@ def __init__(self, config, opsdroid=None):
self.mfa_token = None
self.debug = False
self.listening = True
+ self.bot_id = None
self.mm_driver = Driver(
{
@@ -66,8 +67,7 @@ async def connect(self):
self.bot_id = login_response["id"]
if "username" in login_response:
self.bot_name = login_response["username"]
-
- _LOGGER.info(_("Connected as %s"), self.bot_name)
+ _LOGGER.info(_("Connected as %s"), self.bot_name)
self.mm_driver.websocket = Websocket(
self.mm_driver.options, self.mm_driver.client.token
@@ -93,15 +93,18 @@ async def process_message(self, raw_message):
if "event" in message and message["event"] == "posted":
data = message["data"]
post = json.loads(data["post"])
- await self.opsdroid.parse(
- Message(
- text=post["message"],
- user=data["sender_name"],
- target=data["channel_name"],
- connector=self,
- raw_event=message,
+ # don't parse our own messages (https://github.com/opsdroid/opsdroid/issues/1775)
+ # (but also parse if somehow our bot_id is unknown, like in the unit tests)
+ if self.bot_id is None or self.bot_id != post["user_id"]:
+ await self.opsdroid.parse(
+ Message(
+ text=post["message"],
+ user=data["sender_name"],
+ target=data["channel_name"],
+ connector=self,
+ raw_event=message,
+ )
)
- )
@register_event(Message)
async def send_message(self, message):
| Infinite self-responses in Mattermost connector
After fixing the Mattermost connector with PR #1774 it turns out it suffers from the same infinite self-response problem (#1691) as was fixed for the Gitter connector in #1692.
| 2021-05-13T09:13:32 |
||
opsdroid/opsdroid | 1,777 | opsdroid__opsdroid-1777 | [
"1770"
] | bd61d9ac606817b294473910bb06f2a71ffcd4d8 | diff --git a/opsdroid/connector/slack/connector.py b/opsdroid/connector/slack/connector.py
--- a/opsdroid/connector/slack/connector.py
+++ b/opsdroid/connector/slack/connector.py
@@ -288,13 +288,12 @@ async def _send_message(self, message):
}
if message.linked_event:
- if "thread_ts" in message.linked_event.raw_event:
- if (
- message.linked_event.event_id
- != message.linked_event.raw_event["thread_ts"]
- ):
+ raw_event = message.linked_event.raw_event
+
+ if isinstance(raw_event, dict) and "thread_ts" in raw_event:
+ if message.linked_event.event_id != raw_event["thread_ts"]:
# Linked Event is inside a thread
- data["thread_ts"] = message.linked_event.raw_event["thread_ts"]
+ data["thread_ts"] = raw_event["thread_ts"]
elif self.start_thread:
data["thread_ts"] = message.linked_event.event_id
| Slack connector should check if message event exists before iterating
When sending a lot of messages to a slack block (for example sending output from the terminal to a block) we will get a rate limit and get reset by peer.
The `_send_message` method will freeze opsdroid and we have to kill it from the terminal
```python
ERROR opsdroid.core: Exception when running skill 'nuke'.
Traceback (most recent call last):
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/aiohttp/connector.py", line 969, in _wrap_create_connection
return await self._loop.create_connection(*args, **kwargs) # type: ignore # noqa
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/asyncio/base_events.py", line 1050, in create_connection
transport, protocol = await self._create_connection_transport(
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/asyncio/base_events.py", line 1080, in _create_connection_transport
await waiter
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/asyncio/selector_events.py", line 846, in _read_ready__data_received
data = self._sock.recv(self.max_size)
ConnectionResetError: [Errno 54] Connection reset by peer
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/core.py", line 465, in run_skill
return await skill(event)
File "/Users/samanthahughes/Library/Application Support/opsdroid/opsdroid-modules/skill/nuke/__init__.py", line 454, in block
await self.handle_nuke_arm(account=account)
File "/Users/samanthahughes/Library/Application Support/opsdroid/opsdroid-modules/skill/nuke/__init__.py", line 361, in handle_nuke_arm
await self.opsdroid.send(
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/core.py", line 662, in send
return await event.connector.send(event)
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/connector/__init__.py", line 220, in send
return await self.events[type(event)](self, event)
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/connector/slack/connector.py", line 300, in _edit_blocks
return await self.slack_web_client.api_call(
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/slack_sdk/web/async_base_client.py", line 137, in api_call
return await self._send(
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/slack_sdk/web/async_base_client.py", line 168, in _send
res = await self._request(
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/slack_sdk/web/async_base_client.py", line 188, in _request
return await _request_with_session(
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/slack_sdk/web/async_internal_utils.py", line 87, in _request_with_session
async with session.request(http_verb, api_url, **req_args) as res:
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/aiohttp/client.py", line 1117, in __aenter__
self._resp = await self._coro
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/aiohttp/client.py", line 520, in _request
conn = await self._connector.connect(
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/aiohttp/connector.py", line 535, in connect
proto = await self._create_connection(req, traces, timeout)
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/aiohttp/connector.py", line 892, in _create_connection
_, proto = await self._create_direct_connection(req, traces, timeout)
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/aiohttp/connector.py", line 1051, in _create_direct_connection
raise last_exc
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/aiohttp/connector.py", line 1020, in _create_direct_connection
transp, proto = await self._wrap_create_connection(
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/aiohttp/connector.py", line 975, in _wrap_create_connection
raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host www.slack.com:443 ssl:<ssl.SSLContext object at 0x7ffa5257ea40> [Connection reset by peer]
ERROR slack_sdk.socket_mode.aiohttp: Failed to run a request listener: argument of type 'NoneType' is not iterable
Traceback (most recent call last):
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/aiohttp/connector.py", line 969, in _wrap_create_connection
return await self._loop.create_connection(*args, **kwargs) # type: ignore # noqa
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/asyncio/base_events.py", line 1050, in create_connection
transport, protocol = await self._create_connection_transport(
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/asyncio/base_events.py", line 1080, in _create_connection_transport
await waiter
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/asyncio/selector_events.py", line 846, in _read_ready__data_received
data = self._sock.recv(self.max_size)
ConnectionResetError: [Errno 54] Connection reset by peer
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/core.py", line 465, in run_skill
return await skill(event)
File "/Users/samanthahughes/Library/Application Support/opsdroid/opsdroid-modules/skill/nuke/__init__.py", line 454, in block
await self.handle_nuke_arm(account=account)
File "/Users/samanthahughes/Library/Application Support/opsdroid/opsdroid-modules/skill/nuke/__init__.py", line 361, in handle_nuke_arm
await self.opsdroid.send(
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/core.py", line 662, in send
return await event.connector.send(event)
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/connector/__init__.py", line 220, in send
return await self.events[type(event)](self, event)
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/connector/slack/connector.py", line 300, in _edit_blocks
return await self.slack_web_client.api_call(
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/slack_sdk/web/async_base_client.py", line 137, in api_call
return await self._send(
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/slack_sdk/web/async_base_client.py", line 168, in _send
res = await self._request(
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/slack_sdk/web/async_base_client.py", line 188, in _request
return await _request_with_session(
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/slack_sdk/web/async_internal_utils.py", line 87, in _request_with_session
async with session.request(http_verb, api_url, **req_args) as res:
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/aiohttp/client.py", line 1117, in __aenter__
self._resp = await self._coro
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/aiohttp/client.py", line 520, in _request
conn = await self._connector.connect(
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/aiohttp/connector.py", line 535, in connect
proto = await self._create_connection(req, traces, timeout)
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/aiohttp/connector.py", line 892, in _create_connection
_, proto = await self._create_direct_connection(req, traces, timeout)
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/aiohttp/connector.py", line 1051, in _create_direct_connection
raise last_exc
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/aiohttp/connector.py", line 1020, in _create_direct_connection
transp, proto = await self._wrap_create_connection(
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/aiohttp/connector.py", line 975, in _wrap_create_connection
raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host www.slack.com:443 ssl:<ssl.SSLContext object at 0x7ffa5257ea40> [Connection reset by peer]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/slack_sdk/socket_mode/async_client.py", line 133, in run_message_listeners
await listener(self, request)
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/connector/slack/connector.py", line 165, in socket_event_handler
await self.event_handler(payload)
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/connector/slack/connector.py", line 149, in event_handler
await self.opsdroid.parse(e)
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/core.py", line 640, in parse
await asyncio.gather(*tasks)
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/parsers/event_type.py", line 61, in parse_event_type
await opsdroid.run_skill(skill, skill.config, event)
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/core.py", line 471, in run_skill
await event.respond(
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/connector/slack/events.py", line 96, in respond
response_txt = await super().respond(response_event)
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/events.py", line 147, in respond
result = await opsdroid.send(event)
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/core.py", line 662, in send
return await event.connector.send(event)
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/connector/__init__.py", line 220, in send
return await self.events[type(event)](self, event)
File "/Users/samanthahughes/miniconda3/envs/opsdroid/lib/python3.8/site-packages/opsdroid/connector/slack/connector.py", line 234, in _send_message
if "thread_ts" in message.linked_event.raw_event:
TypeError: argument of type 'NoneType' is not iterable
^CINFO opsdroid.core: Received stop signal, exiting.
INFO opsdroid.core: Stopping connector slack...
```
| hey @FabioRosado
If you could share, I would be interested to know what does the `message.linked_event` holds, as it seems it does not have the `raw_event` attribute. It should be safe to add an extra check to see if the `raw_event` actually exists or not, but knowing what the link event holds would give more context on how that exception could be handled.
Also, how do you know it's a rate limit error? Usually Slack gives a "rate_limited" API error, which I am not seeing on those logs. It looks to me more like a network connection problem to slack
```
Cannot connect to host www.slack.com:443 ssl:<ssl.SSLContext object at 0x7ffa5257ea40> [Connection reset by peer]
During handling of the above exception, another exception occurred:
```
| 2021-05-19T08:57:54 |
|
opsdroid/opsdroid | 1,781 | opsdroid__opsdroid-1781 | [
"1756"
] | 52ff7e08030fb83f37c88f00cbb0a1fbc2d6790d | diff --git a/opsdroid/const.py b/opsdroid/const.py
--- a/opsdroid/const.py
+++ b/opsdroid/const.py
@@ -32,7 +32,7 @@
REGEX_PARSE_SCORE_FACTOR = 0.6
RASANLU_DEFAULT_URL = "http://localhost:5000"
-RASANLU_DEFAULT_PROJECT = "opsdroid"
+RASANLU_DEFAULT_MODELS_PATH = "models"
LUISAI_DEFAULT_URL = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/"
diff --git a/opsdroid/parsers/rasanlu.py b/opsdroid/parsers/rasanlu.py
--- a/opsdroid/parsers/rasanlu.py
+++ b/opsdroid/parsers/rasanlu.py
@@ -9,10 +9,10 @@
import aiohttp
import arrow
-from opsdroid.const import RASANLU_DEFAULT_URL, RASANLU_DEFAULT_PROJECT
+from opsdroid.const import RASANLU_DEFAULT_URL, RASANLU_DEFAULT_MODELS_PATH
_LOGGER = logging.getLogger(__name__)
-CONFIG_SCHEMA = {"url": str, "project": str, "token": str, "min-score": float}
+CONFIG_SCHEMA = {"url": str, "token": str, "models-path": str, "min-score": float}
async def _get_all_intents(skills):
@@ -31,21 +31,22 @@ async def _get_intents_fingerprint(intents):
async def _build_training_url(config):
"""Build the url for training a Rasa NLU model."""
- url = "{}/train?project={}&fixed_model_name={}".format(
+ url = "{}/model/train".format(
config.get("url", RASANLU_DEFAULT_URL),
- config.get("project", RASANLU_DEFAULT_PROJECT),
- config["model"],
)
if "token" in config:
- url += "&token={}".format(config["token"])
+ url += "?&token={}".format(config["token"])
return url
async def _build_status_url(config):
"""Build the url for getting the status of Rasa NLU."""
- return "{}/status".format(config.get("url", RASANLU_DEFAULT_URL))
+ url = "{}/status".format(config.get("url", RASANLU_DEFAULT_URL))
+ if "token" in config:
+ url += "?&token={}".format(config["token"])
+ return url
async def _init_model(config):
@@ -65,20 +66,88 @@ async def _init_model(config):
return True
-async def _get_existing_models(config):
- """Get a list of models already trained in the Rasa NLU project."""
- project = config.get("project", RASANLU_DEFAULT_PROJECT)
+async def _get_rasa_nlu_version(config):
+ """Get Rasa NLU version data"""
+ async with aiohttp.ClientSession(trust_env=True) as session:
+ url = config.get("url", RASANLU_DEFAULT_URL) + "/version"
+ try:
+ resp = await session.get(url)
+ except aiohttp.client_exceptions.ClientConnectorError:
+ _LOGGER.error(_("Unable to connect to Rasa NLU."))
+ return None
+ if resp.status == 200:
+ result = await resp.json()
+ _LOGGER.debug(_("Rasa NLU response - %s."), json.dumps(result))
+ else:
+ result = await resp.text()
+ _LOGGER.error(_("Bad Rasa NLU response - %s."), result)
+ return result
+
+
+async def _check_rasanlu_compatibility(config):
+ """Check if Rasa NLU is compatible with the API we implement"""
+ _LOGGER.debug(_("Checking Rasa NLU version."))
+ json_object = await _get_rasa_nlu_version(config)
+ version = json_object["version"]
+ minimum_compatible_version = json_object["minimum_compatible_version"]
+ # Make sure we don't run against a 1.x.x Rasa NLU because it has a different API
+ if int(minimum_compatible_version[0:1]) >= 2:
+ _LOGGER.debug(_("Rasa NLU version {}.".format(version)))
+ return True
+
+ _LOGGER.error(
+ _(
+ "Incompatible Rasa NLU version ({}). Use Rasa Version >= 2.X.X.".format(
+ version
+ )
+ )
+ )
+ return False
+
+
+async def _load_model(config):
+ """Load model from the filesystem of the Rasa NLU environment"""
+ async with aiohttp.ClientSession(trust_env=True) as session:
+ headers = {}
+ data = {
+ "model_file": "{}/{}".format(
+ config.get("models-path", RASANLU_DEFAULT_MODELS_PATH),
+ config["model_filename"],
+ ),
+ }
+ url = config.get("url", RASANLU_DEFAULT_URL) + "/model"
+ if "token" in config:
+ url += "?token={}".format(config["token"])
+ try:
+ resp = await session.put(url, data=json.dumps(data), headers=headers)
+ except aiohttp.client_exceptions.ClientConnectorError:
+ _LOGGER.error(_("Unable to connect to Rasa NLU."))
+ return None
+ if resp.status == 204:
+ result = await resp.json()
+ else:
+ result = await resp.text()
+ _LOGGER.error(_("Bad Rasa NLU response - %s."), result)
+
+ return result
+
+
+async def _is_model_loaded(config):
+ """Check whether the model is loaded in Rasa NLU"""
async with aiohttp.ClientSession(trust_env=True) as session:
+ url = config.get("url", RASANLU_DEFAULT_URL) + "/status"
+ if "token" in config:
+ url += "?token={}".format(config["token"])
try:
resp = await session.get(await _build_status_url(config))
- if resp.status == 200:
- result = await resp.json()
- if project in result["available_projects"]:
- project_models = result["available_projects"][project]
- return project_models["available_models"]
- except aiohttp.ClientOSError:
- pass
- return []
+ except aiohttp.client_exceptions.ClientConnectorError:
+ _LOGGER.error(_("Unable to connect to Rasa NLU."))
+ return None
+ if resp.status == 200:
+ result = await resp.json()
+ if result["model_file"].find(config["model_filename"]):
+ return True
+ return False
async def train_rasanlu(config, skills):
@@ -89,23 +158,19 @@ async def train_rasanlu(config, skills):
_LOGGER.warning(_("No intents found, skipping training."))
return False
- config["model"] = await _get_intents_fingerprint(intents)
- if config["model"] in await _get_existing_models(config):
- _LOGGER.info(_("This model already exists, skipping training..."))
- await _init_model(config)
- return True
+ await _check_rasanlu_compatibility(config)
+
+ """
+ TODO: think about how to correlate intent with trained model
+ so we can just load the model without training it again if it wasn't changed
+ """
async with aiohttp.ClientSession(trust_env=True) as session:
_LOGGER.info(_("Now training the model. This may take a while..."))
url = await _build_training_url(config)
- # https://github.com/RasaHQ/rasa_nlu/blob/master/docs/http.rst#post-train
- # Note : The request should always be sent as
- # application/x-yml regardless of wether you use
- # json or md for the data format. Do not send json as
- # application/json for example.+
- headers = {"content-type": "application/x-yml"}
+ headers = {"Content-Type": "application/x-yaml"}
try:
training_start = arrow.now()
@@ -115,39 +180,41 @@ async def train_rasanlu(config, skills):
return False
if resp.status == 200:
- if resp.content_type == "application/json":
- result = await resp.json()
- if "info" in result and "new model trained" in result["info"]:
- time_taken = (arrow.now() - training_start).total_seconds()
- _LOGGER.info(
- _("Rasa NLU training completed in %s seconds."), int(time_taken)
- )
- await _init_model(config)
- return True
-
- _LOGGER.debug(result)
if (
- resp.content_type == "application/zip"
+ resp.content_type == "application/x-tar"
and resp.content_disposition.type == "attachment"
):
time_taken = (arrow.now() - training_start).total_seconds()
_LOGGER.info(
_("Rasa NLU training completed in %s seconds."), int(time_taken)
)
- await _init_model(config)
+ config["model_filename"] = resp.content_disposition.filename
+ # close the connection and don't retrieve the model tar
+ # because using it is currently not implemented
+ resp.close()
+
"""
- As inditated in the issue #886, returned zip file is ignored, this can be changed
- This can be changed in future release if needed
- Saving model.zip file example :
+ model_path = "/tmp/{}".format(resp.content_disposition.filename)
try:
- output_file = open("/target/directory/model.zip","wb")
+ output_file = open(model_path,"wb")
data = await resp.read()
output_file.write(data)
output_file.close()
- _LOGGER.debug("Rasa taining model file saved to /target/directory/model.zip")
+ _LOGGER.debug("Rasa taining model file saved to {}", model_path)
except:
- _LOGGER.error("Cannot save rasa taining model file to /target/directory/model.zip")
+ _LOGGER.error("Cannot save rasa taining model file to {}", model_path)
"""
+
+ await _load_model(config)
+ # Check if the current trained model is loaded
+ if await _is_model_loaded(config):
+ _LOGGER.info(_("Successfully loaded Rasa NLU model."))
+ else:
+ _LOGGER.error(_("Failed getting Rasa NLU server status."))
+ return False
+
+ # Check if we will get a valid response from Rasa
+ await call_rasanlu("", config)
return True
_LOGGER.error(_("Bad Rasa NLU response - %s."), await resp.text())
@@ -159,14 +226,10 @@ async def call_rasanlu(text, config):
"""Call the Rasa NLU api and return the response."""
async with aiohttp.ClientSession(trust_env=True) as session:
headers = {}
- data = {
- "q": text,
- "project": config.get("project", "default"),
- "model": config.get("model", "fallback"),
- }
+ data = {"text": text}
+ url = config.get("url", RASANLU_DEFAULT_URL) + "/model/parse"
if "token" in config:
- data["token"] = config["token"]
- url = config.get("url", RASANLU_DEFAULT_URL) + "/parse"
+ url += "?&token={}".format(config["token"])
try:
resp = await session.post(url, data=json.dumps(data), headers=headers)
except aiohttp.client_exceptions.ClientConnectorError:
| diff --git a/tests/test_parser_rasanlu.py b/tests/test_parser_rasanlu.py
--- a/tests/test_parser_rasanlu.py
+++ b/tests/test_parser_rasanlu.py
@@ -415,33 +415,25 @@ async def test__get_intents_fingerprint(self):
)
async def test__build_training_url(self):
- config = {}
- with self.assertRaises(KeyError):
- await rasanlu._build_training_url(config)
-
- config = {"model": "helloworld"}
- url = await rasanlu._build_training_url(config)
- self.assertTrue("helloworld" in url)
-
- config = {"model": "helloworld", "token": "abc123"}
+ config = {"token": "abc123"}
url = await rasanlu._build_training_url(config)
self.assertTrue("&token=abc123" in url)
config = {
"url": "http://example.com",
- "project": "myproject",
- "model": "helloworld",
}
url = await rasanlu._build_training_url(config)
self.assertTrue("http://example.com" in url)
- self.assertTrue("myproject" in url)
- self.assertTrue("helloworld" in url)
async def test__build_status_url(self):
config = {"url": "http://example.com"}
url = await rasanlu._build_status_url(config)
self.assertTrue("http://example.com" in url)
+ config = {"url": "http://example.com", "token": "token123"}
+ url = await rasanlu._build_status_url(config)
+ self.assertTrue("&token=token123" in url)
+
async def test__init_model(self):
with amock.patch.object(rasanlu, "call_rasanlu") as mocked_call:
mocked_call.return_value = {"data": "Some data"}
@@ -450,41 +442,135 @@ async def test__init_model(self):
mocked_call.return_value = None
self.assertEqual(await rasanlu._init_model({}), False)
- async def test__get_existing_models(self):
+ async def test__get_rasa_nlu_version(self):
result = amock.Mock()
result.status = 200
+ result.text = amock.CoroutineMock()
result.json = amock.CoroutineMock()
- result.json.return_value = {
- "available_projects": {
- "default": {"available_models": ["fallback"], "status": "ready"},
- "opsdroid": {"available_models": ["hello", "world"], "status": "ready"},
- }
- }
+
with amock.patch("aiohttp.ClientSession.get") as patched_request:
+ patched_request.side_effect = (
+ aiohttp.client_exceptions.ClientConnectorError("key", amock.Mock())
+ )
+ self.assertEqual(await rasanlu._get_rasa_nlu_version({}), None)
+
+ patched_request.side_effect = None
+ result.content_type = "application/json"
+ result.json.return_value = {
+ "version": "1.0.0",
+ "minimum_compatible_version": "1.0.0",
+ }
+ patched_request.return_value = asyncio.Future()
+ patched_request.return_value.set_result(result)
+ self.assertEqual(
+ await rasanlu._get_rasa_nlu_version({}), result.json.return_value
+ )
+
+ patched_request.side_effect = None
+ result.status = 500
+ result.text.return_value = "Some error happened"
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(result)
- models = await rasanlu._get_existing_models({"project": "opsdroid"})
- self.assertEqual(models, ["hello", "world"])
+ self.assertEqual(
+ await rasanlu._get_rasa_nlu_version({}), result.text.return_value
+ )
- async def test__get_existing_models_exception(self):
+ async def test__check_rasanlu_compatibility(self):
+ with amock.patch.object(rasanlu, "_get_rasa_nlu_version") as mock_crc:
+ mock_crc.return_value = {
+ "version": "1.0.0",
+ "minimum_compatible_version": "1.0.0",
+ }
+ self.assertEqual(await rasanlu._check_rasanlu_compatibility({}), False)
- with amock.patch("aiohttp.ClientSession.get") as patched_request:
+ mock_crc.return_value = {
+ "version": "2.6.2",
+ "minimum_compatible_version": "2.6.0",
+ }
+ self.assertEqual(await rasanlu._check_rasanlu_compatibility({}), True)
+
+ mock_crc.return_value = {
+ "version": "3.1.2",
+ "minimum_compatible_version": "3.0.0",
+ }
+ self.assertEqual(await rasanlu._check_rasanlu_compatibility({}), True)
+
+ async def test__load_model(self):
+ result = amock.Mock()
+ result.status = 204
+ result.text = amock.CoroutineMock()
+ result.json = amock.CoroutineMock()
+
+ with amock.patch("aiohttp.ClientSession.put") as patched_request:
+ patched_request.side_effect = None
+ result.json.return_value = {}
patched_request.return_value = asyncio.Future()
- patched_request.side_effect = ClientOSError()
- models = await rasanlu._get_existing_models({"project": "opsdroid"})
- self.assertRaises(ClientOSError)
- self.assertEqual(models, [])
+ patched_request.return_value.set_result(result)
+ self.assertEqual(
+ await rasanlu._load_model({"model_filename": "model.tar.gz"}), {}
+ )
+ self.assertEqual(
+ await rasanlu._load_model(
+ {"model_filename": "model.tar.gz", "token": "12345"}
+ ),
+ {},
+ )
+
+ result.status = 500
+ result.text.return_value = "some weird error"
+ self.assertEqual(
+ await rasanlu._load_model({"model_filename": "model.tar.gz"}),
+ result.text.return_value,
+ )
+
+ patched_request.side_effect = (
+ aiohttp.client_exceptions.ClientConnectorError("key", amock.Mock())
+ )
+ self.assertEqual(
+ await rasanlu._load_model({"model_filename": "model.tar.gz"}), None
+ )
- async def test__get_existing_models_fails(self):
+ async def test__is_model_loaded(self):
result = amock.Mock()
- result.status = 404
+ result.status = 200
result.json = amock.CoroutineMock()
- result.json.return_value = {}
+
with amock.patch("aiohttp.ClientSession.get") as patched_request:
+ result.json.return_value = {
+ "fingerprint": {
+ "config": ["7625d69d93053ac8520a544d0852c626"],
+ "domain": ["229b51e41876bbcbbbfbeddf79548d5a"],
+ "messages": ["cf7eda7edcae128a75ee8c95d3bbd680"],
+ "stories": ["b5facea681fd00bc7ecc6818c70d9639"],
+ "trained_at": 1556527123.42784,
+ "version": "2.6.2",
+ },
+ "model_file": "/app/models/model.tar.gz",
+ "num_active_training_jobs": 2,
+ }
+ patched_request.side_effect = None
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(result)
- models = await rasanlu._get_existing_models({})
- self.assertEqual(models, [])
+ self.assertEqual(
+ await rasanlu._is_model_loaded({"model_filename": "model.tar.gz"}), True
+ )
+ self.assertEqual(
+ await rasanlu._is_model_loaded(
+ {"model_filename": "model.tar.gz", "token": "12345"}
+ ),
+ True,
+ )
+ result.status = 500
+ self.assertEqual(
+ await rasanlu._is_model_loaded({"model_filename": "model.tar.gz"}),
+ False,
+ )
+ patched_request.side_effect = (
+ aiohttp.client_exceptions.ClientConnectorError("key", amock.Mock())
+ )
+ self.assertEqual(
+ await rasanlu._is_model_loaded({"model_filename": "model.tar.gz"}), None
+ )
async def test_train_rasanlu_fails(self):
result = amock.Mock()
@@ -498,31 +584,27 @@ async def test_train_rasanlu_fails(self):
) as patched_request, amock.patch.object(
rasanlu, "_get_all_intents"
) as mock_gai, amock.patch.object(
- rasanlu, "_init_model"
- ) as mock_im, amock.patch.object(
rasanlu, "_build_training_url"
) as mock_btu, amock.patch.object(
- rasanlu, "_get_existing_models"
- ) as mock_gem, amock.patch.object(
rasanlu, "_get_intents_fingerprint"
- ) as mock_gif:
+ ) as mock_gif, amock.patch.object(
+ rasanlu, "_check_rasanlu_compatibility"
+ ) as mock_crc, amock.patch.object(
+ rasanlu, "_load_model"
+ ) as mock_lmo, amock.patch.object(
+ rasanlu, "_is_model_loaded"
+ ) as mock_iml:
mock_gai.return_value = None
self.assertEqual(await rasanlu.train_rasanlu({}, {}), False)
- mock_gai.return_value = "Hello World"
- mock_gem.return_value = ["abc123"]
- mock_gif.return_value = "abc123"
- self.assertEqual(await rasanlu.train_rasanlu({}, {}), True)
- self.assertTrue(mock_im.called)
- self.assertFalse(mock_btu.called)
-
- mock_gem.return_value = []
+ # _build_training_url
mock_btu.return_value = "http://example.com"
- patched_request.side_effect = (
- aiohttp.client_exceptions.ClientConnectorError("key", amock.Mock())
- )
+
+ # Test if no intents specified
self.assertEqual(await rasanlu.train_rasanlu({}, {}), False)
+ self.assertFalse(mock_btu.called)
+ self.assertTrue(mock_gai.called)
patched_request.side_effect = None
patched_request.return_value = asyncio.Future()
@@ -535,49 +617,87 @@ async def test_train_rasanlu_fails(self):
patched_request.return_value.set_result(result)
self.assertEqual(await rasanlu.train_rasanlu({}, {}), False)
+ # Test Rasa client connection error
+ # _get_all_intents
+ mock_gai.return_value = "Hello World"
+ # _get_intents_fingerprint
+ mock_gif.return_value = "abc1234"
+ # _check_rasanlu_compatibility
+ mock_crc.return_value = True
+ patched_request.side_effect = (
+ aiohttp.client_exceptions.ClientConnectorError("key", amock.Mock())
+ )
+ self.assertEqual(await rasanlu.train_rasanlu({}, {}), False)
+ self.assertTrue(mock_btu.called)
+ self.assertFalse(mock_lmo.called)
+
+ # Test if the trained model is not loaded
+ # _load_model
+ mock_lmo.return_value = "{}"
+ # _is_model_loaded
+ mock_iml.return_value = False
+ result.content_type = "application/x-tar"
+ result.content_disposition.type = "attachment"
+ result.content_disposition.filename = "model.tar.gz"
+ result.json.return_value = "Tar file content..."
+ result.status = 200
+ patched_request.side_effect = None
+ self.assertEqual(await rasanlu.train_rasanlu({}, {}), False)
+ self.assertTrue(mock_lmo.called)
+ self.assertTrue(mock_iml.called)
+
async def test_train_rasanlu_succeeded(self):
result = amock.Mock()
result.text = amock.CoroutineMock()
result.json = amock.CoroutineMock()
result.status = 200
- result.json.return_value = {"info": "new model trained: abc1234"}
+ result.json.return_value = {}
with amock.patch(
"aiohttp.ClientSession.post"
) as patched_request, amock.patch.object(
rasanlu, "_get_all_intents"
) as mock_gai, amock.patch.object(
- rasanlu, "_init_model"
- ), amock.patch.object(
rasanlu, "_build_training_url"
) as mock_btu, amock.patch.object(
- rasanlu, "_get_existing_models"
- ) as mock_gem, amock.patch.object(
rasanlu, "_get_intents_fingerprint"
- ) as mock_gif:
-
- mock_gem.return_value = ["abc123"]
+ ) as mock_gif, amock.patch.object(
+ rasanlu, "_check_rasanlu_compatibility"
+ ) as mock_crc, amock.patch.object(
+ rasanlu, "_load_model"
+ ) as mock_lmo, amock.patch.object(
+ rasanlu, "_is_model_loaded"
+ ) as mock_iml:
+
+ # _build_training_url
mock_btu.return_value = "http://example.com"
+ # _get_all_intents
mock_gai.return_value = "Hello World"
+ # _get_intents_fingerprint
mock_gif.return_value = "abc1234"
- result.content_type = "application/json"
+ # _check_rasanlu_compatibility
+ mock_crc.return_value = True
+ # _load_model
+ mock_lmo.return_value = "{}"
+ # _is_model_loaded
+ mock_iml.return_value = True
+ result.content_type = "application/x-tar"
+ result.content_disposition.type = "attachment"
+ result.content_disposition.filename = "model.tar.gz"
+ result.json.return_value = "Tar file content..."
patched_request.side_effect = None
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(result)
self.assertEqual(await rasanlu.train_rasanlu({}, {}), True)
- result.json.return_value = {}
patched_request.side_effect = None
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(result)
- self.assertEqual(await rasanlu.train_rasanlu({}, {}), False)
-
- result.content_type = "application/zip"
- result.content_disposition.type = "attachment"
- result.json.return_value = {"info": "new model trained: abc1234"}
+ self.assertEqual(await rasanlu.train_rasanlu({}, {}), True)
+ result.status = 500
patched_request.side_effect = None
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(result)
- self.assertEqual(await rasanlu.train_rasanlu({}, {}), True)
+ self.assertEqual(await rasanlu.train_rasanlu({}, {}), False)
| Update rasa parser to work with rasa 2
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://app.element.io/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
I am still investigating but it looks like Rasa 2 has a different http API and our matcher does not work with it.
| 2021-06-03T23:44:12 |
|
opsdroid/opsdroid | 1,822 | opsdroid__opsdroid-1822 | [
"1787"
] | c6643daf1a51e7cf87f320d9e08080c9c281105a | diff --git a/opsdroid/connector/slack/connector.py b/opsdroid/connector/slack/connector.py
--- a/opsdroid/connector/slack/connector.py
+++ b/opsdroid/connector/slack/connector.py
@@ -130,6 +130,10 @@ async def listen(self):
"""Listen for and parse new messages."""
async def event_handler(self, payload):
+ """Handle different payload types and parse the resulting events"""
+
+ if "command" in payload:
+ payload["type"] = "command"
if "type" in payload:
if payload["type"] == "event_callback":
@@ -137,12 +141,12 @@ async def event_handler(self, payload):
else:
event = await self._event_creator.create_event(payload, None)
- if not event:
- _LOGGER.info(
- f"Payload: {payload['type']} is not implemented. Event wont be parsed"
- )
+ if not event:
+ _LOGGER.error(
+ "Payload: %s is not implemented. Event wont be parsed", payload
+ )
- return
+ return
if isinstance(event, list):
for e in event:
@@ -180,15 +184,18 @@ async def web_event_handler(self, request):
if request.content_type == "application/x-www-form-urlencoded":
req = await request.post()
- payload = json.loads(req["payload"])
+
+ if "payload" in req:
+ payload = json.loads(req["payload"])
+ else:
+ payload = dict(req)
elif request.content_type == "application/json":
payload = await request.json()
- if "type" in payload:
- if payload["type"] == "url_verification":
- return aiohttp.web.json_response({"challenge": payload["challenge"]})
- else:
- await self.event_handler(payload)
+ if payload.get("type") == "url_verification":
+ return aiohttp.web.json_response({"challenge": payload["challenge"]})
+
+ await self.event_handler(payload)
return aiohttp.web.Response(text=json.dumps("Received"), status=200)
@@ -288,13 +295,12 @@ async def _send_message(self, message):
}
if message.linked_event:
- if "thread_ts" in message.linked_event.raw_event:
- if (
- message.linked_event.event_id
- != message.linked_event.raw_event["thread_ts"]
- ):
+ raw_event = message.linked_event.raw_event
+
+ if isinstance(raw_event, dict) and "thread_ts" in raw_event:
+ if message.linked_event.event_id != raw_event["thread_ts"]:
# Linked Event is inside a thread
- data["thread_ts"] = message.linked_event.raw_event["thread_ts"]
+ data["thread_ts"] = raw_event["thread_ts"]
elif self.start_thread:
data["thread_ts"] = message.linked_event.event_id
diff --git a/opsdroid/connector/slack/create_events.py b/opsdroid/connector/slack/create_events.py
--- a/opsdroid/connector/slack/create_events.py
+++ b/opsdroid/connector/slack/create_events.py
@@ -27,6 +27,7 @@ def __init__(self, connector, *args, **kwargs):
self.event_types["message_action"] = self.message_action_triggered
self.event_types["view_submission"] = self.view_submission_triggered
self.event_types["view_closed"] = self.view_closed_triggered
+ self.event_types["command"] = self.slash_command
self.message_subtypes = defaultdict(lambda: self.create_message)
self.message_subtypes.update(
@@ -257,3 +258,15 @@ async def view_closed_triggered(self, event, channel):
target=event["user"]["id"],
connector=self.connector,
)
+
+ async def slash_command(self, event, channel):
+ """Send a Slash command event"""
+
+ command = slack_events.SlashCommand(
+ payload=event,
+ user=event["user_id"],
+ target=event["channel_id"],
+ connector=self.connector,
+ )
+ command.update_entity("command", event["command"])
+ return command
diff --git a/opsdroid/connector/slack/events.py b/opsdroid/connector/slack/events.py
--- a/opsdroid/connector/slack/events.py
+++ b/opsdroid/connector/slack/events.py
@@ -6,7 +6,6 @@
import aiohttp
import certifi
-
from opsdroid import events
_LOGGER = logging.getLogger(__name__)
@@ -89,7 +88,11 @@ async def respond(self, response_event):
headers=headers,
ssl=self.ssl_context,
)
- response_txt = await response.json()
+
+ if response.content_type == "application/json":
+ response_txt = await response.json()
+ elif response.content_type == "text/html":
+ response_txt = await response.text()
else:
response_txt = {"error": "Response URL not available in payload."}
else:
@@ -125,9 +128,32 @@ def __init__(self, payload, *args, **kwargs):
class ViewClosed(InteractiveAction):
"""Event class to represent view_closed in Slack."""
- def __init__(self, payload, *args, **kwargs):
- """Create object with minimum properties."""
- super().__init__(payload, *args, **kwargs)
+
+class SlashCommand(InteractiveAction):
+ """
+ Event class to represent a slash command.
+
+ args:
+ payload: Incomming payload from the Slack API
+
+ **Basic Usage in a Skill:**
+
+ .. code-block:: python
+
+ from opsdroid.skill import Skill
+ from opsdroid.matchers import match_regex
+
+ class CommandsSkill(Skill):
+ @match_event(SlashCommand, command="/testcommand")
+ async def slash_command(self, event):
+
+ cmd = event.payload["command"]
+
+ # event.payload["text"] holds the arguments from the command
+ arguments = event.payload["text"]
+
+ await message.respond(f"{cmd} {arguments}")
+ """
class ChannelArchived(events.Event):
| diff --git a/opsdroid/connector/slack/tests/responses/payload_slash_command.urlencoded b/opsdroid/connector/slack/tests/responses/payload_slash_command.urlencoded
new file mode 100644
--- /dev/null
+++ b/opsdroid/connector/slack/tests/responses/payload_slash_command.urlencoded
@@ -0,0 +1 @@
+token=here-comes-some-token&team_id=T01ND2P8N91&team_domain=opsdroidtests&channel_id=C01N639ECTY&channel_name=random&user_id=U01NK1K9L68&user_name=opsdroid.test&command=%2Ftestcommand&text=&api_app_id=A01NK2M4ABE&is_enterprise_install=false&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2FT01ND2P8N91%2F2086715431956%2FxyP8iEhnQ0BjWLowcMLSPaSX&trigger_id=2093168434705.1761091294307.7f8d01a322363a013721e32e83af484b
diff --git a/opsdroid/connector/slack/tests/test_create_events.py b/opsdroid/connector/slack/tests/test_create_events.py
--- a/opsdroid/connector/slack/tests/test_create_events.py
+++ b/opsdroid/connector/slack/tests/test_create_events.py
@@ -4,6 +4,7 @@
import json
import pytest
+
from opsdroid.connector.slack.create_events import SlackEventCreator
from opsdroid.testing import MINIMAL_CONFIG, call_endpoint, run_unit_test
@@ -157,6 +158,30 @@ async def receive_message_action():
assert await run_unit_test(opsdroid, receive_message_action)
[email protected]
[email protected]_response(*USERS_INFO)
[email protected]_response(*AUTH_TEST)
+async def test_receive_slash_command(opsdroid, connector, mock_api):
+ await opsdroid.load(config=MINIMAL_CONFIG)
+
+ async def receive_slash_command():
+ headers, data = get_webhook_payload(
+ "payload_slash_command.urlencoded", "urlencoded"
+ )
+ resp = await call_endpoint(
+ opsdroid,
+ CONNECTOR_ENDPOINT,
+ "POST",
+ data=data,
+ headers=headers,
+ )
+ assert resp.status == 200
+
+ return True
+
+ assert await run_unit_test(opsdroid, receive_slash_command)
+
+
@pytest.mark.asyncio
@pytest.mark.add_response(*USERS_INFO)
@pytest.mark.add_response(*AUTH_TEST)
diff --git a/opsdroid/connector/slack/tests/test_events.py b/opsdroid/connector/slack/tests/test_events.py
--- a/opsdroid/connector/slack/tests/test_events.py
+++ b/opsdroid/connector/slack/tests/test_events.py
@@ -14,6 +14,14 @@ async def test_respond_response_url_exists(mock_api_obj, mock_api):
assert response["ok"]
[email protected]
[email protected]_response("/", "POST", "ok", 200)
+async def test_respond_response_text_content_type(mock_api_obj, mock_api):
+ action = InteractiveAction({"response_url": mock_api_obj.base_url})
+ response = await action.respond("this is a test response")
+ assert response == "ok"
+
+
@pytest.mark.asyncio
async def test_respond_event_response_url_does_not_exist(mock_api_obj, mock_api):
action = InteractiveAction({})
diff --git a/opsdroid/testing/external_api.py b/opsdroid/testing/external_api.py
--- a/opsdroid/testing/external_api.py
+++ b/opsdroid/testing/external_api.py
@@ -105,6 +105,8 @@ async def _handler(self, request: web.Request) -> web.Response:
self._payloads[route].append(await request.post())
status, response = self.responses[(route, method)].pop(0)
+ if isinstance(response, str):
+ return web.Response(text=response, status=status, content_type="text/html")
return web.json_response(response, status=status)
@property
| Slash commands do not work
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://app.element.io/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
Using slash commands do not work. There is no event type for them, no docs on using them and opsdroid seems to error if you try.
## Steps to Reproduce
- Create a slash command for your bot
- Use the slash command in Slack
- See opsdroid output
## Expected Functionality
An event should be triggered which can be matched with `match_event`.
## Experienced Functionality
```
EBUG slack_sdk.socket_mode.aiohttp: Received message (type: TEXT, data: {"envelope_id":"c98bb0d2-2522-49e4-ae77-f453bc25055a","payload":{"token":"uLr3No9RxHh6kKW2DbbPMrtK","team_id":"T033XLNMP","team_domain":"jacobtomlinson","channel_id":"D01RFGW6QN9","channel_name":"directmessage","user_id":"U033XLNMR","user_name":"jacobtomlinson","command":"\/opsdroid","text":"","api_app_id":"A01R3RSRBMM","is_enterprise_install":"false","response_url":"https:\/\/hooks.slack.com\/commands\/T033XLNMP\/2212151098501\/CWmAvXOf6OphspoPEPaLyjVz","trigger_id":"2227832050993.3133702737.e40bf7f6909be8a7b97c5cda5b226627"},"type":"slash_commands","accepts_response_payload":true}, extra: )
DEBUG slack_sdk.socket_mode.aiohttp: A new message enqueued (current queue size: 1)
DEBUG slack_sdk.socket_mode.aiohttp: Message processing started (type: slash_commands, envelope_id: c98bb0d2-2522-49e4-ae77-f453bc25055a)
DEBUG slack_sdk.socket_mode.aiohttp: Sending a message: {"envelope_id": "c98bb0d2-2522-49e4-ae77-f453bc25055a"}
ERROR slack_sdk.socket_mode.aiohttp: Failed to run a request listener: local variable 'event' referenced before assignment
Traceback (most recent call last):
File "/Users/jacob/mambaforge/envs/opsdroid/lib/python3.8/site-packages/slack_sdk/socket_mode/async_client.py", line 133, in run_message_listeners
await listener(self, request)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/connector/slack/connector.py", line 166, in socket_event_handler
await self.event_handler(payload)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/connector/slack/connector.py", line 147, in event_handler
if isinstance(event, list):
UnboundLocalError: local variable 'event' referenced before assignment
DEBUG slack_sdk.socket_mode.aiohttp: Message processing completed (type: slash_commands, envelope_id: c98bb0d2-2522-49e4-ae77-f453bc25055a)
```
## Versions
- **Opsdroid version:** 0.22.0
- **Python version:** 0.3.8
- **OS/Docker version:** macos 11.2.3
## Configuration File
Please include your version of the configuration file below.
```yaml
# Your code goes here.
```
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| 2021-08-15T09:10:46 |
|
opsdroid/opsdroid | 1,835 | opsdroid__opsdroid-1835 | [
"1810"
] | d8e985c9983a7b24a862ecb15a882147e2105e0d | diff --git a/opsdroid/database/redis/__init__.py b/opsdroid/database/redis/__init__.py
--- a/opsdroid/database/redis/__init__.py
+++ b/opsdroid/database/redis/__init__.py
@@ -2,8 +2,7 @@
import json
import logging
-import aioredis
-from aioredis import parser
+from aioredis import Redis
from voluptuous import Any
from opsdroid.database import Database
@@ -46,12 +45,13 @@ async def connect(self):
"""
try:
- self.client = await aioredis.create_pool(
- address=(self.host, int(self.port)),
+ self.client = Redis(
+ host=self.host,
+ port=int(self.port),
db=self.database,
password=self.password,
- parser=parser.PyReader,
)
+ await self.client.ping() # to actually initiate a connection
_LOGGER.info(
_("Connected to Redis database %s from %s on port %s."),
@@ -76,7 +76,9 @@ async def put(self, key, data):
"""
if self.client:
_LOGGER.debug(_("Putting %s into Redis."), key)
- await self.client.execute("SET", key, json.dumps(data, cls=JSONEncoder))
+ await self.client.execute_command(
+ "SET", key, json.dumps(data, cls=JSONEncoder)
+ )
async def get(self, key):
"""Get data from Redis for a given key.
@@ -91,7 +93,7 @@ async def get(self, key):
"""
if self.client:
_LOGGER.debug(_("Getting %s from Redis."), key)
- data = await self.client.execute("GET", key)
+ data = await self.client.execute_command("GET", key)
if data:
return json.loads(data, object_hook=JSONDecoder())
@@ -107,9 +109,9 @@ async def delete(self, key):
"""
if self.client:
_LOGGER.debug(_("Deleting %s from Redis."), key)
- await self.client.execute("DEL", key)
+ await self.client.execute_command("DEL", key)
async def disconnect(self):
"""Disconnect from the database."""
if self.client:
- self.client.close()
+ await self.client.close()
| diff --git a/opsdroid/database/redis/tests/test_redis.py b/opsdroid/database/redis/tests/test_redis.py
--- a/opsdroid/database/redis/tests/test_redis.py
+++ b/opsdroid/database/redis/tests/test_redis.py
@@ -31,7 +31,9 @@ def test_init(caplog):
async def test_connect(mocker, caplog):
caplog.set_level(logging.DEBUG)
database = RedisDatabase({})
- mocked_connection = mocker.patch("aioredis.create_pool")
+ mocked_connection = mocker.patch(
+ "aioredis.Redis.ping", return_value=return_async_value(True)
+ )
await database.connect()
@@ -43,7 +45,7 @@ async def test_connect(mocker, caplog):
async def test_connect_failure(mocker, caplog):
caplog.set_level(logging.DEBUG)
database = RedisDatabase({})
- mocked_connection = mocker.patch("aioredis.create_pool", side_effect=OSError)
+ mocked_connection = mocker.patch("aioredis.Redis.ping", side_effect=OSError)
with suppress(OSError):
await database.connect()
@@ -57,13 +59,15 @@ async def test_get(mocker, caplog):
caplog.set_level(logging.DEBUG)
database = RedisDatabase({})
database.client = mocker.Mock()
- attrs = {"execute.return_value": return_async_value('{"data_key":"data_value"}')}
+ attrs = {
+ "execute_command.return_value": return_async_value('{"data_key":"data_value"}')
+ }
database.client.configure_mock(**attrs)
result = await database.get("key")
assert result == dict(data_key="data_value")
- database.client.execute.assert_called_with("GET", "key")
+ database.client.execute_command.assert_called_with("GET", "key")
assert "Getting" in caplog.text
@@ -72,7 +76,7 @@ async def test_get_return_none(mocker, caplog):
caplog.set_level(logging.DEBUG)
database = RedisDatabase({})
database.client = mocker.Mock()
- attrs = {"execute.return_value": return_async_value(None)}
+ attrs = {"execute_command.return_value": return_async_value(None)}
database.client.configure_mock(**attrs)
result = await database.get("key")
@@ -86,12 +90,12 @@ async def test_put(mocker, caplog):
caplog.set_level(logging.DEBUG)
database = RedisDatabase({})
database.client = mocker.Mock()
- attrs = {"execute.return_value": return_async_value("None")}
+ attrs = {"execute_command.return_value": return_async_value("None")}
database.client.configure_mock(**attrs)
await database.put("key", dict(data_key="data_value"))
- database.client.execute.assert_called_with(
+ database.client.execute_command.assert_called_with(
"SET", "key", json.dumps(dict(data_key="data_value"), cls=JSONEncoder)
)
assert "Putting" in caplog.text
@@ -102,12 +106,12 @@ async def test_delete(mocker, caplog):
caplog.set_level(logging.DEBUG)
database = RedisDatabase({})
database.client = mocker.Mock()
- attrs = {"execute.return_value": return_async_value("None")}
+ attrs = {"execute_command.return_value": return_async_value("None")}
database.client.configure_mock(**attrs)
await database.delete("key")
- database.client.execute.assert_called_with("DEL", "key")
+ database.client.execute_command.assert_called_with("DEL", "key")
assert "Deleting" in caplog.text
| Upgrade redis database backend to use aioredis v2
Looks like v2 of `aioredis` is out and has breaking changes which affect us. In #1809 I've pinned us to v1 for now but we should upgrade things to work with v2.
Specifically importing the parser fails
https://github.com/opsdroid/opsdroid/blob/a45490d1bdceca39b49880e20262b55ea0be101d/opsdroid/database/redis/__init__.py#L6
```python-traceback
ImportError while importing test module '/home/runner/work/opsdroid/opsdroid/opsdroid/database/redis/tests/test_redis.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/opt/hostedtoolcache/Python/3.7.11/x64/lib/python3.7/importlib/__init__.py:127: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
opsdroid/database/redis/tests/test_redis.py:8: in <module>
from opsdroid.database.redis import RedisDatabase
opsdroid/database/redis/__init__.py:6: in <module>
from aioredis import parser
E ImportError: cannot import name 'parser' from 'aioredis' (/home/runner/work/opsdroid/opsdroid/.tox/py37-e2e/lib/python3.7/site-packages/aioredis/__init__.py)
```
| Hello! I would like to take it up. Hacktoberfest is coming and it's becoming my good tradition to visit opsdroid and help a bit (:
One question before starting:
https://github.com/opsdroid/opsdroid/blob/a45490d1bdceca39b49880e20262b55ea0be101d/opsdroid/database/redis/__init__.py#L49-L54
Is the pure python parser setting intentional (it is slower)? Aioredis 2.0 uses hiredis parser if hiredis is installed, pure-python fallback otherwise
Another question: I guess it's safe to remove `disconnect` method as [the docs](https://aioredis.readthedocs.io/en/latest/migration/#cleaning-up) say it should be cleaned up automatically?
Oh actually, hactoberfest has already started: let's go! Opening the PR
| 2021-09-30T17:51:14 |
opsdroid/opsdroid | 1,855 | opsdroid__opsdroid-1855 | [
"1853"
] | 6551c734be0102961856a288c038572345098547 | diff --git a/opsdroid/core.py b/opsdroid/core.py
--- a/opsdroid/core.py
+++ b/opsdroid/core.py
@@ -1,39 +1,39 @@
"""Core components of OpsDroid."""
+import asyncio
+import contextlib
import copy
+import inspect
import logging
import os
import signal
import sys
import weakref
-import asyncio
-import contextlib
-import inspect
-from watchgod import awatch, PythonWatcher
+
+from watchgod import PythonWatcher, awatch
from opsdroid import events
-from opsdroid.const import DEFAULT_CONFIG_LOCATIONS
-from opsdroid.memory import Memory
-from opsdroid.connector import Connector
from opsdroid.configuration import load_config_file
+from opsdroid.connector import Connector
+from opsdroid.const import DEFAULT_CONFIG_LOCATIONS
from opsdroid.database import Database, InMemoryDatabase
-from opsdroid.skill import Skill
+from opsdroid.helper import get_parser_config
from opsdroid.loader import Loader
-from opsdroid.web import Web
+from opsdroid.memory import Memory
from opsdroid.parsers.always import parse_always
from opsdroid.parsers.catchall import parse_catchall
-from opsdroid.parsers.event_type import parse_event_type
-from opsdroid.parsers.regex import parse_regex
-from opsdroid.parsers.parseformat import parse_format
+from opsdroid.parsers.crontab import parse_crontab
from opsdroid.parsers.dialogflow import parse_dialogflow
+from opsdroid.parsers.event_type import parse_event_type
from opsdroid.parsers.luisai import parse_luisai
+from opsdroid.parsers.parseformat import parse_format
+from opsdroid.parsers.rasanlu import parse_rasanlu, train_rasanlu
+from opsdroid.parsers.regex import parse_regex
from opsdroid.parsers.sapcai import parse_sapcai
-from opsdroid.parsers.witai import parse_witai
from opsdroid.parsers.watson import parse_watson
-from opsdroid.parsers.rasanlu import parse_rasanlu, train_rasanlu
-from opsdroid.parsers.crontab import parse_crontab
-from opsdroid.helper import get_parser_config
-
+from opsdroid.parsers.witai import parse_witai
+from opsdroid.skill import Skill
+from opsdroid.web import Web
_LOGGER = logging.getLogger(__name__)
@@ -351,7 +351,7 @@ async def train_parsers(self, skills):
if "parsers" in self.modules:
parsers = self.modules.get("parsers", {})
rasanlu = get_parser_config("rasanlu", parsers)
- if rasanlu and rasanlu["enabled"]:
+ if rasanlu and rasanlu["enabled"] and rasanlu.get("train", True):
await train_rasanlu(rasanlu, skills)
async def setup_connectors(self, connectors):
| Use pre-trained Rasa model.
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://app.element.io/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
There is no option to take a pre-trained Rasa model (perhaps trained on a more powerful machine) and use that for predictions instead of training a new model each time opsdroid is started.
## Expected Functionality
There should be a configuration option under something such as `parsers->rasanlu->no-train` which by default is false, but can be set to true in order to prevent opsdroid sending the request to re-train each time.
## Experienced Functionality
No such option exists.
## Versions
- **Opsdroid version:**0.23.0
- **Python version:**3.9.2
- **OS/Docker version:**Debian 11
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| Thank you for raising this issue @DAMO238 is this still the case? I'm just catching up on the convo in our community channel
Yes, this is still an issue. I used a work around by commenting out the line of code responsible for training rasa in my installation, but this is more of a hacky work around than a solution. There seem to already be functions for loading a model and checking if rasa already has a model loaded. I propose that opsdroid should check if rasa has a model loaded, and then, only if there is no model, check the configuration to see if a model should be loaded and then finally, fallback to training the model (current functionality).
Ah gotcha thank you again for raising this and for the clarification 👍
Can I ask you for an example on your configuration? Are you providing an intentions yaml file with your rasa config?
Looking at the docs it seems that we only train the model if you provide the intents yaml file. | 2021-10-31T16:39:31 |
|
opsdroid/opsdroid | 1,860 | opsdroid__opsdroid-1860 | [
"1859"
] | ee43c560560bc5cff08062839200e77724945e6b | diff --git a/opsdroid/database/mongo/__init__.py b/opsdroid/database/mongo/__init__.py
--- a/opsdroid/database/mongo/__init__.py
+++ b/opsdroid/database/mongo/__init__.py
@@ -44,17 +44,18 @@ def __init__(self, config, opsdroid=None):
async def connect(self):
"""Connect to the database."""
host = self.config.get("host", "localhost")
+ protocol = self.config.get("protocol", "mongodb").replace("://", "")
port = self.config.get("port", "27017")
+ if port != "27017":
+ host = f"{host}:{port}"
database = self.config.get("database", "opsdroid")
user = self.config.get("user")
pwd = self.config.get("password")
if user and pwd:
- path = "mongodb://{user}:{pwd}@{host}:{port}".format(
- user=user, pwd=pwd, host=host, port=port
- )
+ self.db_url = f"{protocol}://{user}:{pwd}@{host}"
else:
- path = "mongodb://{host}:{port}".format(host=host, port=port)
- self.client = AsyncIOMotorClient(path)
+ self.db_url = f"{protocol}://{host}"
+ self.client = AsyncIOMotorClient(self.db_url)
self.database = self.client[database]
_LOGGER.info("Connected to MongoDB.")
| diff --git a/opsdroid/database/mongo/tests/test_mongo.py b/opsdroid/database/mongo/tests/test_mongo.py
--- a/opsdroid/database/mongo/tests/test_mongo.py
+++ b/opsdroid/database/mongo/tests/test_mongo.py
@@ -44,6 +44,8 @@ def test_init(database):
{
"database": "test_db",
"collection": "test_collection",
+ "protocol": "mongodb://",
+ "port": "1234",
"user": "root",
"password": "mongo",
},
@@ -53,6 +55,7 @@ async def test_connect(database):
"""Test that the mongo database has implemented connect function properly"""
try:
await database.connect()
+ assert "mongodb://" in database.db_url
except NotImplementedError:
raise Exception
else:
| User configurable connection for mongo-based databases
So the pymongo client has a multitude of ways for connecting to different mongo services
So for MongoDB Atlas users the connection string is given as such
for python connections to the mongo db atlas
`mongodb+srv://<username>:<password>@<cluster-name>.mongodb.net/myFirstDatabase`
In making the mongo connection to be user configurable we can specify different types of mongo services versus
just asking for the basic connection arguments like port, user name, pass, and also we can give users an easier way to connect versus making assumptions about the type of mongodb the kinds of credentials they might have.
As long as the pymongo client accepts the connection and connects the user to the database and the collection they want I think this would be great!
Thanks again guys!
| 2021-11-05T10:06:29 |
|
opsdroid/opsdroid | 1,864 | opsdroid__opsdroid-1864 | [
"1863"
] | a9b638f766884ff6ce7c7c64f2bdc0a75b940348 | diff --git a/opsdroid/core.py b/opsdroid/core.py
--- a/opsdroid/core.py
+++ b/opsdroid/core.py
@@ -184,8 +184,8 @@ async def start(self):
if len(self.skills) == 0:
self.critical(_("No skills in configuration, at least 1 required"), 1)
+ await self.start_databases()
await self.start_connectors()
- self.create_task(self.start_databases())
self.create_task(self.watch_paths())
self.create_task(parse_crontab(self))
self.create_task(self.web_server.start())
| Looking for Teams Service Endpoints in Mongo database forces error when no endpoints found within specified Mongo collection
Hi all,
So I'm getting an error when using both teams and a mongo database. The database uses the new SRV protocol which has been added recently, much thanks to @jacobtomlinson and @FabioRosado for helping by adding functionality for that. The teams connector also goes through the new developer portal. So my bot and app are done through that versus the former app studio method they used before.
I'm also doing my opsdroid deployment through docker swarm.
For some reason Microsoft teams is looking for teams service endpoints within the specified collection I use within my config.
The error pasted below errors out when opsdroid is looking for those endpoints but can't find them within the mongodb collection.

| I'm not exactly sure what might be causing the error, if it's something teams related due to the new developer portal or mongo-related.
Ah this is interesting. This is happening because connectors are started before databases, and teams is trying to use a database during startup. | 2021-11-12T09:55:14 |
|
opsdroid/opsdroid | 1,886 | opsdroid__opsdroid-1886 | [
"1853"
] | be0e004a9176436e3789e60a241bb85bec95cb9c | diff --git a/opsdroid/const.py b/opsdroid/const.py
--- a/opsdroid/const.py
+++ b/opsdroid/const.py
@@ -33,6 +33,7 @@
RASANLU_DEFAULT_URL = "http://localhost:5000"
RASANLU_DEFAULT_MODELS_PATH = "models"
+RASANLU_DEFAULT_TRAIN_MODEL = True
LUISAI_DEFAULT_URL = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/"
diff --git a/opsdroid/core.py b/opsdroid/core.py
--- a/opsdroid/core.py
+++ b/opsdroid/core.py
@@ -27,7 +27,11 @@
from opsdroid.parsers.event_type import parse_event_type
from opsdroid.parsers.luisai import parse_luisai
from opsdroid.parsers.parseformat import parse_format
-from opsdroid.parsers.rasanlu import parse_rasanlu, train_rasanlu
+from opsdroid.parsers.rasanlu import (
+ parse_rasanlu,
+ train_rasanlu,
+ has_compatible_version_rasanlu,
+)
from opsdroid.parsers.regex import parse_regex
from opsdroid.parsers.sapcai import parse_sapcai
from opsdroid.parsers.watson import parse_watson
@@ -351,7 +355,12 @@ async def train_parsers(self, skills):
if "parsers" in self.modules:
parsers = self.modules.get("parsers", {})
rasanlu = get_parser_config("rasanlu", parsers)
- if rasanlu and rasanlu["enabled"] and rasanlu.get("train", True):
+ if rasanlu and rasanlu["enabled"]:
+ rasa_version_is_compatible = await has_compatible_version_rasanlu(
+ rasanlu
+ )
+ if rasa_version_is_compatible is False:
+ self.critical("Rasa version is not compatible", 5)
await train_rasanlu(rasanlu, skills)
async def setup_connectors(self, connectors):
diff --git a/opsdroid/parsers/rasanlu.py b/opsdroid/parsers/rasanlu.py
--- a/opsdroid/parsers/rasanlu.py
+++ b/opsdroid/parsers/rasanlu.py
@@ -9,10 +9,20 @@
import aiohttp
import arrow
-from opsdroid.const import RASANLU_DEFAULT_URL, RASANLU_DEFAULT_MODELS_PATH
+from opsdroid.const import (
+ RASANLU_DEFAULT_URL,
+ RASANLU_DEFAULT_MODELS_PATH,
+ RASANLU_DEFAULT_TRAIN_MODEL,
+)
_LOGGER = logging.getLogger(__name__)
-CONFIG_SCHEMA = {"url": str, "token": str, "models-path": str, "min-score": float}
+CONFIG_SCHEMA = {
+ "url": str,
+ "token": str,
+ "models-path": str,
+ "min-score": float,
+ "train": bool,
+}
async def _get_all_intents(skills):
@@ -84,7 +94,7 @@ async def _get_rasa_nlu_version(config):
return result
-async def _check_rasanlu_compatibility(config):
+async def has_compatible_version_rasanlu(config):
"""Check if Rasa NLU is compatible with the API we implement"""
_LOGGER.debug(_("Checking Rasa NLU version."))
json_object = await _get_rasa_nlu_version(config)
@@ -152,14 +162,17 @@ async def _is_model_loaded(config):
async def train_rasanlu(config, skills):
"""Train a Rasa NLU model based on the loaded skills."""
+ train = config.get("train", RASANLU_DEFAULT_TRAIN_MODEL)
+ if train is False:
+ _LOGGER.info(_("Skipping Rasa NLU model training as specified in the config."))
+ return False
+
_LOGGER.info(_("Starting Rasa NLU training."))
intents = await _get_all_intents(skills)
if intents is None:
_LOGGER.warning(_("No intents found, skipping training."))
return False
- await _check_rasanlu_compatibility(config)
-
"""
TODO: think about how to correlate intent with trained model
so we can just load the model without training it again if it wasn't changed
| diff --git a/tests/test_core.py b/tests/test_core.py
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -556,11 +556,23 @@ async def test_start_databases(self):
self.assertEqual(1, len(opsdroid.memory.databases))
async def test_train_rasanlu(self):
- with OpsDroid() as opsdroid:
+ with OpsDroid() as opsdroid, amock.patch(
+ "opsdroid.parsers.rasanlu._get_rasa_nlu_version"
+ ) as mock_crc:
opsdroid.modules = {
"parsers": [{"config": {"name": "rasanlu", "enabled": True}}]
}
- with amock.patch("opsdroid.parsers.rasanlu.train_rasanlu"):
+ mock_crc.return_value = {
+ "version": "2.0.0",
+ "minimum_compatible_version": "2.0.0",
+ }
+ await opsdroid.train_parsers({})
+
+ mock_crc.return_value = {
+ "version": "1.0.0",
+ "minimum_compatible_version": "1.0.0",
+ }
+ with self.assertRaises(SystemExit):
await opsdroid.train_parsers({})
async def test_watchdog_works(self):
diff --git a/tests/test_parser_rasanlu.py b/tests/test_parser_rasanlu.py
--- a/tests/test_parser_rasanlu.py
+++ b/tests/test_parser_rasanlu.py
@@ -475,25 +475,25 @@ async def test__get_rasa_nlu_version(self):
await rasanlu._get_rasa_nlu_version({}), result.text.return_value
)
- async def test__check_rasanlu_compatibility(self):
+ async def test_has_compatible_version_rasanlu(self):
with amock.patch.object(rasanlu, "_get_rasa_nlu_version") as mock_crc:
mock_crc.return_value = {
"version": "1.0.0",
"minimum_compatible_version": "1.0.0",
}
- self.assertEqual(await rasanlu._check_rasanlu_compatibility({}), False)
+ self.assertEqual(await rasanlu.has_compatible_version_rasanlu({}), False)
mock_crc.return_value = {
"version": "2.6.2",
"minimum_compatible_version": "2.6.0",
}
- self.assertEqual(await rasanlu._check_rasanlu_compatibility({}), True)
+ self.assertEqual(await rasanlu.has_compatible_version_rasanlu({}), True)
mock_crc.return_value = {
"version": "3.1.2",
"minimum_compatible_version": "3.0.0",
}
- self.assertEqual(await rasanlu._check_rasanlu_compatibility({}), True)
+ self.assertEqual(await rasanlu.has_compatible_version_rasanlu({}), True)
async def test__load_model(self):
result = amock.Mock()
@@ -588,7 +588,7 @@ async def test_train_rasanlu_fails(self):
) as mock_btu, amock.patch.object(
rasanlu, "_get_intents_fingerprint"
) as mock_gif, amock.patch.object(
- rasanlu, "_check_rasanlu_compatibility"
+ rasanlu, "has_compatible_version_rasanlu"
) as mock_crc, amock.patch.object(
rasanlu, "_load_model"
) as mock_lmo, amock.patch.object(
@@ -662,7 +662,7 @@ async def test_train_rasanlu_succeeded(self):
) as mock_btu, amock.patch.object(
rasanlu, "_get_intents_fingerprint"
) as mock_gif, amock.patch.object(
- rasanlu, "_check_rasanlu_compatibility"
+ rasanlu, "has_compatible_version_rasanlu"
) as mock_crc, amock.patch.object(
rasanlu, "_load_model"
) as mock_lmo, amock.patch.object(
@@ -691,13 +691,16 @@ async def test_train_rasanlu_succeeded(self):
patched_request.return_value.set_result(result)
self.assertEqual(await rasanlu.train_rasanlu({}, {}), True)
- patched_request.side_effect = None
- patched_request.return_value = asyncio.Future()
- patched_request.return_value.set_result(result)
- self.assertEqual(await rasanlu.train_rasanlu({}, {}), True)
-
result.status = 500
patched_request.side_effect = None
patched_request.return_value = asyncio.Future()
patched_request.return_value.set_result(result)
self.assertEqual(await rasanlu.train_rasanlu({}, {}), False)
+
+ config = {
+ "name": "rasanlu",
+ "min-score": 0.3,
+ "token": "12345",
+ "train": False,
+ }
+ self.assertEqual(await rasanlu.train_rasanlu(config, {}), False)
| Use pre-trained Rasa model.
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://app.element.io/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
There is no option to take a pre-trained Rasa model (perhaps trained on a more powerful machine) and use that for predictions instead of training a new model each time opsdroid is started.
## Expected Functionality
There should be a configuration option under something such as `parsers->rasanlu->no-train` which by default is false, but can be set to true in order to prevent opsdroid sending the request to re-train each time.
## Experienced Functionality
No such option exists.
## Versions
- **Opsdroid version:**0.23.0
- **Python version:**3.9.2
- **OS/Docker version:**Debian 11
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| Thank you for raising this issue @DAMO238 is this still the case? I'm just catching up on the convo in our community channel
Yes, this is still an issue. I used a work around by commenting out the line of code responsible for training rasa in my installation, but this is more of a hacky work around than a solution. There seem to already be functions for loading a model and checking if rasa already has a model loaded. I propose that opsdroid should check if rasa has a model loaded, and then, only if there is no model, check the configuration to see if a model should be loaded and then finally, fallback to training the model (current functionality).
Ah gotcha thank you again for raising this and for the clarification 👍
Can I ask you for an example on your configuration? Are you providing an intentions yaml file with your rasa config?
Looking at the docs it seems that we only train the model if you provide the intents yaml file.
I am not providing an intentions yaml file, as I trained my model on a different computer and then copied it onto my server. Here is the rasa section of my opsdroid config:
```
parsers:
rasanlu:
url: http://localhost:5005
models-path: models
token: SUPER_SECRET_TOKEN
min-score: 0.8
```
Then my rasa config:
```
# Configuration for Rasa NLU.
# https://rasa.com/docs/rasa/nlu/components/
language: en
pipeline:
- name: SpacyNLP
model: en_core_web_md
case_sensitive: False
- name: SpacyTokenizer
- name: SpacyFeaturizer
- name: SpacyEntityExtractor
- name: RegexFeaturizer
# - name: RegexEntityExtractor
- name: LexicalSyntacticFeaturizer
- name: CountVectorsFeaturizer
- name: CountVectorsFeaturizer
analyzer: char_wb
min_ngram: 1
max_ngram: 4
- name: DIETClassifier
epochs: 100
constrain_similarities: true
- name: EntitySynonymMapper
- name: ResponseSelector
epochs: 100
constrain_similarities: true
- name: FallbackClassifier
threshold: 0.3
ambiguity_threshold: 0.1
# Configuration for Rasa Core.
# https://rasa.com/docs/rasa/core/policies/
policies:
# # No configuration for policies was provided. The following default policies were used to train your model.
# # If you'd like to customize them, uncomment and adjust the policies.
# # See https://rasa.com/docs/rasa/policies for more information.
# - name: MemoizationPolicy
# - name: RulePolicy
# - name: UnexpecTEDIntentPolicy
# max_history: 5
# epochs: 100
# - name: TEDPolicy
# max_history: 5
# epochs: 100
# constrain_similarities: true
```
This is an exact clone of the config used to create the model so that rasa can load the model trained on my laptop. | 2022-02-09T00:11:35 |
opsdroid/opsdroid | 1,888 | opsdroid__opsdroid-1888 | [
"1887"
] | 4ac4464910e1f67a67d6123aa366dde8beeb06f9 | diff --git a/opsdroid/parsers/rasanlu.py b/opsdroid/parsers/rasanlu.py
--- a/opsdroid/parsers/rasanlu.py
+++ b/opsdroid/parsers/rasanlu.py
@@ -289,9 +289,18 @@ async def parse_rasanlu(opsdroid, skills, message, config):
if matcher["rasanlu_intent"] == result["intent"]["name"]:
message.rasanlu = result
for entity in result["entities"]:
- message.update_entity(
- entity["entity"], entity["value"], entity["confidence"]
- )
+ if "confidence_entity" in entity:
+ message.update_entity(
+ entity["entity"],
+ entity["value"],
+ entity["confidence_entity"],
+ )
+ elif "extractor" in entity:
+ message.update_entity(
+ entity["entity"],
+ entity["value"],
+ entity["extractor"],
+ )
matched_skills.append(
{
"score": confidence,
| diff --git a/tests/test_parser_rasanlu.py b/tests/test_parser_rasanlu.py
--- a/tests/test_parser_rasanlu.py
+++ b/tests/test_parser_rasanlu.py
@@ -131,7 +131,7 @@ async def test_parse_rasanlu(self):
"end": 32,
"entity": "state",
"extractor": "ner_crf",
- "confidence": 0.854,
+ "confidence_entity": 0.854,
"start": 25,
"value": "running",
}
@@ -175,7 +175,7 @@ async def test_parse_rasanlu_entities(self):
"value": "chinese",
"entity": "cuisine",
"extractor": "CRFEntityExtractor",
- "confidence": 0.854,
+ "confidence_entity": 0.854,
"processors": [],
}
],
@@ -190,6 +190,30 @@ async def test_parse_rasanlu_entities(self):
skill["message"].entities["cuisine"]["value"], "chinese"
)
+ with amock.patch.object(rasanlu, "call_rasanlu") as mocked_call_rasanlu:
+ mocked_call_rasanlu.return_value = {
+ "text": "show me chinese restaurants",
+ "intent": {"name": "restaurant_search", "confidence": 0.98343},
+ "entities": [
+ {
+ "start": 8,
+ "end": 15,
+ "value": "chinese",
+ "entity": "cuisine",
+ "extractor": "RegexEntityExtractor",
+ }
+ ],
+ }
+ [skill] = await rasanlu.parse_rasanlu(
+ opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
+ )
+
+ self.assertEqual(len(skill["message"].entities.keys()), 1)
+ self.assertTrue("cuisine" in skill["message"].entities.keys())
+ self.assertEqual(
+ skill["message"].entities["cuisine"]["value"], "chinese"
+ )
+
async def test_parse_rasanlu_raises(self):
with OpsDroid() as opsdroid:
opsdroid.config["parsers"] = [
@@ -215,7 +239,7 @@ async def test_parse_rasanlu_raises(self):
"end": 32,
"entity": "state",
"extractor": "ner_crf",
- "confidence": 0.854,
+ "confidence_entity": 0.854,
"start": 25,
"value": "running",
}
| KeyError: 'confidence'
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://app.element.io/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
I am trying to build chatbot using opsdroid, matrix and rasanlu but I am not able to extract entities. getting following error: ```
entity["entity"], entity["value"], entity["confidence"]
KeyError: 'confidence'
```
## Expected Functionality
When user give message "Current price of GOOGLE" it should extract the entity [GOOG]
## Experienced Functionality
Getting `KeyEroor: 'confidence'`
## Versions
- **Opsdroid version:** v0.25.0
- **Python version:** 3.8.12
- **OS/Docker version:** 20.10.7
- **RASA version:** 2.8.1
## Configuration File
Please include your version of the configuration file below.
```
configuration.yaml
welcome-message: false
logging:
level: info
connectors:
matrix:
# Required
homeserver: $MATRIX_SERVER
mxid: $MATRIX_MXID
access_token: $MATRIX_TOKEN
device_name: "opsdroid"
enable_encryption: true
device_id: $DEVICE_ID # A unique string to use as an ID for a persistent opsdroid device
store_path: "/home/woyce-1-5/opsdroid/e2ee-keys" # Path to the directory where the matrix store will be saved
rooms:
main:
alias: $MATRIX_ROOM_MAIN
# Send messages as msgType: m.notice
send_m_notice: True
parsers:
rasanlu:
url: http://rasa:5005
#models-path: models
token: ###########
#min-score: 0.99999
min-score: 0.9999
skills:
fortune:
path: /skills/fortune
config:
mxid: $MATRIX_MXID
cmd_joke: '/home/opsdroid/.local/bin/fortune /skills/fortune/computers'
cmd_cookie: '/home/opsdroid/.local/bin/fortune /skills/fortune/cookies'
```
```
intents.yml
version: "2.0"
intents:
- greetings
- add
- bye
- tell_a_joke
- price:
use_entities:
- ticker
- add stock
entities:
- ticker
nlu:
- intent: greetings
examples: |
- Hii
- hi
- hey
- Hello
- Heya
- wassup
- intent: add
examples: |
- add stock AAPL for 9 days
- add stock MSFT 12 to monitor list
- add my stock GOOG 19
- add TSLA 14 days
- intent: Bye
examples: |
- Bye
- bie
- by
- see you
- see ya
- intent: tell_a_joke
examples: |
- Tell me a joke
- One more joke
- Do you know jokes
- Can you tell a joke
- Can you say something funny
- Would you entertain me
- What about a joke
- intent: this_is_funny
examples: |
- This is funny
- That's a funny one
- Hahaha
- That's a good one
- intent: price
examples: |
- current price of [TSLA]{"entity":"ticker"}
- tell me current price of [AMZN]{"entity":"ticker"}
- I want to know the current price of [NSRGY]{"entity":"ticker"}
- tell me about the current price of [AAPL]{"entity":"ticker"}```
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->

| The [Rasa API](https://rasa.com/docs/rasa/pages/http-api#operation/parseModelMessage) states the key is `confidence` but the fact is the key is `confidence_entity`. 🙂 | 2022-02-11T08:53:21 |
opsdroid/opsdroid | 1,892 | opsdroid__opsdroid-1892 | [
"1890"
] | 1bdafbd48748143aad0ece42537b5bb1366165f2 | diff --git a/opsdroid/connector/slack/connector.py b/opsdroid/connector/slack/connector.py
--- a/opsdroid/connector/slack/connector.py
+++ b/opsdroid/connector/slack/connector.py
@@ -1,4 +1,5 @@
"""A connector for Slack."""
+import asyncio
import json
import logging
import os
@@ -71,6 +72,16 @@ def __init__(self, config, opsdroid=None):
self.known_users = {}
self._event_creator = SlackEventCreator(self)
+ self._event_queue = asyncio.Queue()
+ self._event_queue_task = None
+
+ async def _queue_worker(self):
+ while True:
+ payload = await self._event_queue.get()
+ try:
+ await self.event_handler(payload)
+ finally:
+ self._event_queue.task_done()
async def connect(self):
"""Connect to the chat service."""
@@ -108,6 +119,10 @@ async def connect(self):
await self.socket_mode_client.connect()
_LOGGER.info(_("Connected successfully with socket mode"))
else:
+ # Create a task for background processing events received by
+ # the web event handler.
+ self._event_queue_task = asyncio.create_task(self._queue_worker())
+
self.opsdroid.web_server.web_app.router.add_post(
f"/connector/{self.name}",
self.web_event_handler,
@@ -119,8 +134,13 @@ async def connect(self):
_LOGGER.debug(_("Default room is %s."), self.default_target)
async def disconnect(self):
- """Disconnect from Slack. Only needed when socket_mode_client is used
- as the Events API uses the aiohttp server"""
+ """Disconnect from Slack.
+
+ Cancels the event queue worker task and disconnects the
+ socket_mode_client if socket mode was enabled."""
+ if self._event_queue_task:
+ self._event_queue_task.cancel()
+ await asyncio.gather(self._event_queue_task, return_exceptions=True)
if self.socket_mode_client:
await self.socket_mode_client.disconnect()
@@ -195,7 +215,13 @@ async def web_event_handler(self, request):
if payload.get("type") == "url_verification":
return aiohttp.web.json_response({"challenge": payload["challenge"]})
- await self.event_handler(payload)
+ # Put the event in the queue to process it in the background and
+ # immediately acknowledge the reception by returning status code 200.
+ # Slack will resend events that have not been acknowledged within 3
+ # seconds and we want to avoid that.
+ #
+ # https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
+ self._event_queue.put_nowait(payload)
return aiohttp.web.Response(text=json.dumps("Received"), status=200)
| Get multiple responses for one slack input command
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://app.element.io/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
Using opsdroid with slack connector, there will be multiple responses for one slack input command. From the debugging log, the same command is been detected and parsed for several times by opsdroid.
After investigation, it seems the slack will retry if the server took longer than 3 seconds to respond to the previous event delivery attempt (https://api.slack.com/apis/connections/events-api#graceful_retries). Similar with the issue mentioned here https://github.com/slackapi/python-slack-sdk/issues/335
## Steps to Reproduce
Please also include relevant information and steps to reproduce the bug/issue.
## Expected Functionality
Expect opsdroid could provide a config setting for slack to acknowledge the slack API once the command is detected.
## Experienced Functionality
Get multiple responses for one slack input command.
## Versions
- **Opsdroid version:** 0.24.1
- **Python version:** 3.8
- **OS/Docker version:** Redhat 8
## Configuration File
Please include your version of the configuration file below.
```yaml
# Your code goes here.
```
## Additional Details
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| We also ran into this issue. The slack docs note that one should ack the event before processing it. Right now, it's the other way around in opsdroid:
> Respond to events with a HTTP 200 OK as soon as you can. Avoid actually processing and reacting to events within the same process. Implement a queue to handle inbound events after they are received.
https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events
This is especially problematic if a skill errors after > 3sec in which case slack retries the event multiple times leading quite a bit of error spam in the slack channel. | 2022-03-02T08:44:59 |
|
opsdroid/opsdroid | 1,902 | opsdroid__opsdroid-1902 | [
"1900"
] | 2082c843a50f626c10c5fbe06146367c0aca3cc0 | diff --git a/opsdroid/parsers/witai.py b/opsdroid/parsers/witai.py
--- a/opsdroid/parsers/witai.py
+++ b/opsdroid/parsers/witai.py
@@ -68,8 +68,16 @@ async def parse_witai(opsdroid, skills, message, config):
message.witai = result
for key, entity in result["entities"].items():
if key != "intent":
+ witai_entity_value = ""
+ if "value" in entity[0]:
+ witai_entity_value = entity[0]["value"]
+ elif "values" in entity[0]:
+ # we never know which data are important for user,
+ # so we return list with all values
+ witai_entity_value = entity[0]["values"]
+
message.update_entity(
- key, entity[0]["value"], entity[0]["confidence"]
+ key, witai_entity_value, entity[0]["confidence"]
)
matched_skills.append(
{
| diff --git a/tests/test_parser_witai.py b/tests/test_parser_witai.py
--- a/tests/test_parser_witai.py
+++ b/tests/test_parser_witai.py
@@ -256,7 +256,7 @@ async def test_parse_witai_raise_ClientOSError(self):
self.assertFalse(mock_skill.called)
self.assertTrue(mocked_call.called)
- async def test_parse_witai_entities(self):
+ async def test_parse_witai_entities_single_value(self):
with OpsDroid() as opsdroid:
opsdroid.config["parsers"] = [
{"name": "witai", "token": "test", "min-score": 0.3}
@@ -343,3 +343,96 @@ async def test_parse_witai_entities(self):
self.assertEqual(len(skill["message"].entities.keys()), 1)
self.assertTrue("location" in skill["message"].entities.keys())
self.assertEqual(skill["message"].entities["location"]["value"], "london")
+
+ async def test_parse_witai_entities_multiple_values(self):
+ with OpsDroid() as opsdroid:
+ opsdroid.config["parsers"] = [
+ {"name": "witai", "token": "test", "min-score": 0.3}
+ ]
+ mock_skill = await self.getMockSkill()
+ opsdroid.skills.append(match_witai("aws_cost")(mock_skill))
+
+ mock_connector = amock.CoroutineMock()
+ message = Message(
+ text="aws cost since december",
+ user="user",
+ target="default",
+ connector=mock_connector,
+ )
+
+ with amock.patch.object(witai, "call_witai") as mocked_call_witai:
+ mocked_call_witai.return_value = {
+ "_text": "aws cost since december",
+ "entities": {
+ "intent": [
+ {"confidence": 0.99965322126667, "value": "aws_cost"}
+ ],
+ "datetime": [
+ {
+ "confidence": 0.9995,
+ "type": "interval",
+ "from": {
+ "grain": "month",
+ "value": "2022-12-01T00:00:00.000-08:00",
+ },
+ "values": [
+ {
+ "type": "interval",
+ "from": {
+ "grain": "month",
+ "value": "2022-12-01T00:00:00.000-08:00",
+ },
+ },
+ {
+ "type": "interval",
+ "from": {
+ "grain": "month",
+ "value": "2023-12-01T00:00:00.000-08:00",
+ },
+ },
+ {
+ "type": "interval",
+ "from": {
+ "grain": "month",
+ "value": "2024-12-01T00:00:00.000-08:00",
+ },
+ },
+ ],
+ }
+ ],
+ },
+ "WARNING": "DEPRECATED",
+ "msg_id": "051qg0BBGn4O7xZDj",
+ }
+ [skill] = await witai.parse_witai(
+ opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
+ )
+
+ self.assertEqual(len(skill["message"].entities.keys()), 1)
+ self.assertTrue("datetime" in skill["message"].entities.keys())
+ self.assertEqual(
+ skill["message"].entities["datetime"]["value"],
+ [
+ {
+ "type": "interval",
+ "from": {
+ "grain": "month",
+ "value": "2022-12-01T00:00:00.000-08:00",
+ },
+ },
+ {
+ "type": "interval",
+ "from": {
+ "grain": "month",
+ "value": "2023-12-01T00:00:00.000-08:00",
+ },
+ },
+ {
+ "type": "interval",
+ "from": {
+ "grain": "month",
+ "value": "2024-12-01T00:00:00.000-08:00",
+ },
+ },
+ ],
+ )
| Unhandled exception in wit.ai matcher (wrong wit.ai response parsing)
# Description
Opsdroid doesn't understand wit.ai time range response
## Steps to Reproduce
Please also include relevant information and steps to reproduce the bug/issue.
1. Connect with wit.ai app
2. Create new indent
3. Train indent to understand `wit/datetime`
4. Send message like `aws cost since december`
5. Opsdroid will fail to understand wit.ai api response
```
INFO opsdroid.parsers.witai.call_witai(): wit.ai response - {"_text": "aws cost since december", "entities": {"intent": [{"confidence": 0.99986626506986, "value": "aws_cost"}], "datetime": [{"confidence": 0.9995, "type": "interval", "from": {"grain": "month", "value": "2022-12-01T00:00:00.000-08:00"}, "values": [{"type": "interval", "from": {"grain": "month", "value": "2022-12-01T00:00:00.000-08:00"}}, {"type": "interval", "from": {"grain": "month", "value": "2023-12-01T00:00:00.000-08:00"}}, {"type": "interval", "from": {"grain": "month", "value": "2024-12-01T00:00:00.000-08:00"}}]}]}, "WARNING": "DEPRECATED", "msg_id": "0eanvH01TmiwU0Era"}.
ERROR aiohttp.server.log_exception(): Error handling request
Traceback (most recent call last):
File "C:\Users\jakub\Documents\venvs\chatops\lib\site-packages\aiohttp\web_protocol.py", line 435, in _handle_request
resp = await request_handler(request)
File "C:\Users\jakub\Documents\venvs\chatops\lib\site-packages\aiohttp\web_app.py", line 504, in _handle
resp = await handler(request)
File "C:\Users\jakub\Documents\venvs\chatops\lib\site-packages\opsdroid\connector\websocket\__init__.py", line 99, in websocket_handler
await self.opsdroid.parse(message)
File "C:\Users\jakub\Documents\venvs\chatops\lib\site-packages\opsdroid\core.py", line 627, in parse
ranked_skills = await self.get_ranked_skills(unconstrained_skills, event)
File "C:\Users\jakub\Documents\venvs\chatops\lib\site-packages\opsdroid\core.py", line 516, in get_ranked_skills
ranked_skills += await parse_witai(self, skills, message, witai)
File "C:\Users\jakub\Documents\venvs\chatops\lib\site-packages\opsdroid\parsers\witai.py", line 72, in parse_witai
key, entity[0]["value"], entity[0]["confidence"]
KeyError: 'value'
```
## Expected Functionality
There should be no exception
## Experienced Functionality
Thrown exception
## Versions
- **Opsdroid version:** 0.25.0
- **Python version:** 3.9.5
- **OS/Docker version:** Windows 10
## Configuration File
Please include your version of the configuration file below.
```yaml
# Your code goes here.
parsers:
- name: witai
access-token: [REDACTED]
min-score: 0.6
```
## Additional Details
Raw wit.ai response for `aws cost since december`
```json
{
"_text": "aws cost since december",
"entities": {
"intent": [
{
"confidence": 0.99965322126667,
"value": "aws_cost"
}
],
"datetime": [
{
"confidence": 0.9995,
"type": "interval",
"from": {
"grain": "month",
"value": "2022-12-01T00:00:00.000-08:00"
},
"values": [
{
"type": "interval",
"from": {
"grain": "month",
"value": "2022-12-01T00:00:00.000-08:00"
}
},
{
"type": "interval",
"from": {
"grain": "month",
"value": "2023-12-01T00:00:00.000-08:00"
}
},
{
"type": "interval",
"from": {
"grain": "month",
"value": "2024-12-01T00:00:00.000-08:00"
}
}
]
}
]
},
"WARNING": "DEPRECATED",
"msg_id": "051qg0BBGn4O7xZDj"
}
```
Here we can see that wit.ai sends `values` in `datetime[0]` dict.
Opsdroid expects it to be `value` (without **s**):
https://github.com/opsdroid/opsdroid/blob/c5dad210fe3d9068c75cd4fac9762fcc353335d3/opsdroid/parsers/witai.py#L69-L73
Which is fine for simple response without any matched intents (excluded by `if` in L70):
```json
{
"_text": "aws",
"entities": {
"intent": [
{
"confidence": 0.99692494474705,
"value": "aws_cost"
}
]
},
"WARNING": "DEPRECATED",
"msg_id": "0lbTZJcwDL5RoT2Wi"
}
```
Simple query `aws cost today`. If there is only one field in `values` wit.ai will rewrite it to short version to `values`
```json
{
"_text": "aws cost today",
"entities": {
"intent": [
{
"confidence": 0.99965536553564,
"value": "aws_cost"
}
],
"datetime": [
{
"confidence": 0.9995,
"type": "value",
"grain": "day",
"value": "2022-04-16T00:00:00.000-07:00",
"values": [
{
"type": "value",
"grain": "day",
"value": "2022-04-16T00:00:00.000-07:00"
}
]
}
]
},
"WARNING": "DEPRECATED",
"msg_id": "05vACT9WHhDUmAy9u"
}
```
| 2022-04-17T14:41:17 |
|
opsdroid/opsdroid | 1,903 | opsdroid__opsdroid-1903 | [
"1896"
] | c310d45a2ea9fe95fe87858646b53345d5e92b8e | diff --git a/opsdroid/connector/slack/connector.py b/opsdroid/connector/slack/connector.py
--- a/opsdroid/connector/slack/connector.py
+++ b/opsdroid/connector/slack/connector.py
@@ -9,6 +9,7 @@
import aiohttp
import certifi
from emoji import demojize
+
from slack_sdk.errors import SlackApiError
from slack_sdk.socket_mode.aiohttp import SocketModeClient
from slack_sdk.socket_mode.request import SocketModeRequest
@@ -149,6 +150,35 @@ async def disconnect(self):
async def listen(self):
"""Listen for and parse new messages."""
+ def _generate_base_data(self, event: opsdroid.events.Event) -> dict:
+ """Generate a base data dict to send to the slack API.
+
+ The data dictionary will always contain `channel`, `username`
+ and `icon_emoj` which can be derived from the event or the
+ slack config.
+
+ If we want to send messages in a thread, we need to include
+ thread_ts from the linked event (the message received by opsdroid) and the slack api will know that this new message
+ should be included in a thread and not in the channel.
+
+ """
+ data = {
+ "channel": event.target,
+ "username": self.bot_name,
+ "icon_emoji": self.icon_emoji,
+ }
+
+ if event.linked_event:
+ raw_event = event.linked_event.raw_event
+
+ if isinstance(raw_event, dict) and "thread_ts" in raw_event:
+ if event.linked_event.event_id != raw_event["thread_ts"]:
+ # Linked Event is inside a thread
+ data["thread_ts"] = raw_event["thread_ts"]
+ elif self.start_thread:
+ data["thread_ts"] = event.linked_event.event_id
+ return data
+
async def event_handler(self, payload):
"""Handle different payload types and parse the resulting events"""
@@ -313,22 +343,9 @@ async def _send_message(self, message):
_LOGGER.debug(
_("Responding with: '%s' in room %s."), message.text, message.target
)
- data = {
- "channel": message.target,
- "text": message.text,
- "username": self.bot_name,
- "icon_emoji": self.icon_emoji,
- }
- if message.linked_event:
- raw_event = message.linked_event.raw_event
-
- if isinstance(raw_event, dict) and "thread_ts" in raw_event:
- if message.linked_event.event_id != raw_event["thread_ts"]:
- # Linked Event is inside a thread
- data["thread_ts"] = raw_event["thread_ts"]
- elif self.start_thread:
- data["thread_ts"] = message.linked_event.event_id
+ data = self._generate_base_data(message)
+ data["text"] = message.text
return await self.slack_web_client.api_call(
"chat.postMessage",
@@ -361,16 +378,10 @@ async def _send_blocks(self, blocks):
_LOGGER.debug(
_("Responding with interactive blocks in room %s."), blocks.target
)
+ data = self._generate_base_data(blocks)
+ data["blocks"] = blocks.blocks
- return await self.slack_web_client.api_call(
- "chat.postMessage",
- data={
- "channel": blocks.target,
- "username": self.bot_name,
- "blocks": blocks.blocks,
- "icon_emoji": self.icon_emoji,
- },
- )
+ return await self.slack_web_client.api_call("chat.postMessage", data=data)
@register_event(EditedBlocks)
async def _edit_blocks(self, blocks):
| Message replies using Blocks in a thread end up outside of the thread even when start-thread: true
# Description
When start-thread: true in configuration.yaml, regular text replies do end up in the thread. Fine.
However, the same reply inside of Blocks() construct, end up outside of the thread in a new message in the channel.
This is not expected.
## Steps to Reproduce
1) Set start-thread: true in configuration.yaml
2) Write the first message, then, create a thread inside of this message saying "hi" with the following code:
message.respond here will reply in a thread as expected:
```python
import random
from opsdroid.matchers import match_regex
from opsdroid.skill import Skill
class HelloSkill(Skill):
@match_regex(r'hi|hello|hey|hallo', case_sensitive=False)
async def hello(self, message):
await message.respond('Hello!')
```
message.respond here will NOT reply in a thread (just because we're. using "Blocks"?):
```python
import random
from opsdroid.matchers import match_regex
from opsdroid.skill import Skill
class HelloSkill(Skill):
@match_regex(r'hi|hello|hey|hallo', case_sensitive=False)
async def hello(self, message):
await message.respond(Blocks([
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Hey! I'm opsdroid.\nI'm a natural language event driven automation bot framework.\n*What a mouthful!*"
},
"accessory": {
"type": "image",
"image_url": "https://raw.githubusercontent.com/opsdroid/style-guidelines/master/logos/logo-light.png",
"alt_text": "opsdroid logo"
}
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {
"type": "plain_text",
"text": "Visit website",
"emoji": True
},
"url": "https://opsdroid.dev"
}
]
}
]
))
```
## Expected Functionality
message.respond(Blocks[...]) should reply in a thread when user types "hi" inside of a thread and start-thread: true is set in configuration.yaml
| I started working on this, but I can't give you a date were I will have it done by.
Just wondering, would it make sense to add another config arg to set "start-thread-blocks" to true/false so users can stop opsdroid from replying to blocks only if they want?
If there's a use case for this then yeah but in my case the reason I set start-thread: true is because I want *ALL* replies within a thread. No exceptions. I'm not sure who would want a thread not to be started just because they're using blocks. However, if you feel like there's a good use case for this kind of implementation, then go for it :) | 2022-04-18T18:54:13 |
|
opsdroid/opsdroid | 1,906 | opsdroid__opsdroid-1906 | [
"1891"
] | 2f2034a2a38f91329c3fdd1489a703adecfd229f | diff --git a/opsdroid/connector/slack/connector.py b/opsdroid/connector/slack/connector.py
--- a/opsdroid/connector/slack/connector.py
+++ b/opsdroid/connector/slack/connector.py
@@ -5,14 +5,13 @@
import os
import re
import ssl
+import urllib.parse
import aiohttp
import certifi
-import opsdroid.events
from emoji import demojize
-from opsdroid.connector import Connector, register_event
-from opsdroid.connector.slack.create_events import SlackEventCreator
-from opsdroid.connector.slack.events import Blocks, EditedBlocks
+
+
from slack_sdk.errors import SlackApiError
from slack_sdk.socket_mode.aiohttp import SocketModeClient
from slack_sdk.socket_mode.request import SocketModeRequest
@@ -20,6 +19,19 @@
from slack_sdk.web.async_client import AsyncWebClient
from voluptuous import Required
+
+import opsdroid.events
+from opsdroid.connector import Connector, register_event
+from opsdroid.connector.slack.create_events import SlackEventCreator
+from opsdroid.connector.slack.events import (
+ Blocks,
+ EditedBlocks,
+ ModalOpen,
+ ModalPush,
+ ModalUpdate,
+)
+
+
_LOGGER = logging.getLogger(__name__)
_USE_BOT_TOKEN_MSG = (
@@ -212,7 +224,6 @@ async def socket_event_handler(
response = SocketModeResponse(envelope_id=req.envelope_id)
await client.send_socket_mode_response(response)
-
payload = req.payload
await self.event_handler(payload)
@@ -236,7 +247,19 @@ async def web_event_handler(self, request):
if "payload" in req:
payload = json.loads(req["payload"])
else:
- payload = dict(req)
+ # Some payloads (ie: view_submission) don't come with proper formatting
+ # Convert the request to text, and later attempt to load the json
+
+ if len(req.keys()) == 1:
+ req = await request.text()
+ req = urllib.parse.unquote(req)
+
+ if "payload={" in req:
+ req = req.replace("payload=", "")
+ payload = json.loads(req)
+ else:
+ payload = dict(req)
+
elif request.content_type == "application/json":
payload = await request.json()
@@ -400,6 +423,46 @@ async def _edit_blocks(self, blocks):
data=data,
)
+ @register_event(ModalOpen)
+ async def _open_modal(self, modal):
+ """Respond with opening a Modal.
+
+ https://api.slack.com/methods/views.open
+ """
+ _LOGGER.debug(_("Opening modal with trigger id: %s."), modal.trigger_id)
+
+ return await self.slack_web_client.api_call(
+ "views.open",
+ data={"trigger_id": modal.trigger_id, "view": modal.view},
+ )
+
+ @register_event(ModalUpdate)
+ async def _update_modal(self, modal):
+ """Respond an update to a Modal.
+
+ https://api.slack.com/methods/views.update
+ """
+ _LOGGER.debug(_("Opening modal with trigger id: %s."), modal.external_id)
+ data = {"external_id": modal.external_id, "view": modal.view}
+
+ if modal.hash:
+ data["hash"] = modal.hash
+
+ return await self.slack_web_client.api_call("views.update", data=data)
+
+ @register_event(ModalPush)
+ async def _push_modal(self, modal):
+ """Respond by pushing a view onto the stack of a root view.
+
+ https://api.slack.com/methods/views.push
+ """
+ _LOGGER.debug(_("Pushing modal with trigger id: %s."), modal.trigger_id)
+
+ return await self.slack_web_client.api_call(
+ "views.push",
+ data={"trigger_id": modal.trigger_id, "view": modal.view},
+ )
+
@register_event(opsdroid.events.Reaction)
async def send_reaction(self, reaction):
"""React to a message."""
diff --git a/opsdroid/connector/slack/create_events.py b/opsdroid/connector/slack/create_events.py
--- a/opsdroid/connector/slack/create_events.py
+++ b/opsdroid/connector/slack/create_events.py
@@ -58,6 +58,7 @@ async def _get_user_name(self, event):
async def handle_bot_message(self, event, channel):
"""Check that a bot message is opsdroid if not create the message"""
+
if event["bot_id"] != self.connector.bot_id:
return await self.create_message(event, channel)
@@ -248,13 +249,18 @@ async def message_action_triggered(self, event, channel):
async def view_submission_triggered(self, event, channel):
"""Send a ViewSubmission event."""
- return slack_events.ViewSubmission(
+ view_submission = slack_events.ViewSubmission(
event,
user=event["user"]["id"],
target=event["user"]["id"],
connector=self.connector,
)
+ if callback_id := event.get("view", {}).get("callback_id"):
+ view_submission.update_entity("callback_id", callback_id)
+
+ return view_submission
+
async def view_closed_triggered(self, event, channel):
"""Send a ViewClosed event."""
diff --git a/opsdroid/connector/slack/events.py b/opsdroid/connector/slack/events.py
--- a/opsdroid/connector/slack/events.py
+++ b/opsdroid/connector/slack/events.py
@@ -117,6 +117,93 @@ def __init__(self, payload, *args, **kwargs):
super().__init__(payload, *args, **kwargs)
+class Modal(events.Event):
+ """Base Event class to represent a Modal in Slack.
+
+ Modals are the Slack app equivalent of alert boxes, pop-ups, or dialog boxes.
+ https://api.slack.com/surfaces/modals/using
+
+ args:
+ view: a view payload. this can be a dict or a json encoded string
+ """
+
+ def __init__(self, view, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ self.view = view
+
+ if isinstance(self.view, dict):
+ self.view = json.dumps(self.view)
+
+
+class ModalOpen(Modal):
+ """Event class to represent a new Modal in Slack.
+
+ args:
+ trigger_id: trigger to post to a user
+
+ **Basic Usage in a Skill:**
+
+ .. code-block:: python
+
+ from opsdroid.skill import Skill
+ from opsdroid.matchers import match_event
+
+ class ModalSkill(Skill):
+ @match_event(SlashCommand, command="/testcommand")
+ async def open_modal(self, event):
+ view = {
+ "type": "modal",
+ "title": {"type": "plain_text", "text": "Modal title"},
+ "blocks": [
+ {
+ "type": "input",
+ "label": {"type": "plain_text", "text": "Input label"},
+ "element": {
+ "type": "plain_text_input",
+ "action_id": "input1",
+ "placeholder": {
+ "type": "plain_text",
+ "text": "Type in here",
+ },
+ "multiline": False,
+ },
+ "optional": False,
+ },
+ ],
+ "close": {"type": "plain_text", "text": "Cancel"},
+ "submit": {"type": "plain_text", "text": "Save"},
+ "private_metadata": "Shhhhhhhh",
+ "callback_id": "view_identifier_12",
+ }
+ await self.opsdroid.send(
+ ModalOpen(view=view, trigger_id=event.payload["trigger_id"])
+ )
+ """
+
+ def __init__(self, trigger_id, view, *args, **kwargs):
+ super().__init__(view, *args, **kwargs)
+ self.trigger_id = trigger_id
+
+
+class ModalUpdate(Modal):
+ """Event class to represent a Modal Update in Slack
+
+ args:
+ external_id: A unique identifier of the view set by the developer
+ _hash: A string that represents view state to protect against possible race conditions
+ """
+
+ def __init__(self, external_id, view, *args, hash_=None, **kwargs):
+ self.external_id = external_id
+ self.hash = hash_
+ super().__init__(view, *args, **kwargs)
+
+
+class ModalPush(ModalOpen):
+ """Event class to represent a Modal Push in Slack."""
+
+
class ViewSubmission(InteractiveAction):
"""Event class to represent view_submission in Slack."""
@@ -141,7 +228,7 @@ class SlashCommand(InteractiveAction):
.. code-block:: python
from opsdroid.skill import Skill
- from opsdroid.matchers import match_regex
+ from opsdroid.matchers import match_event
class CommandsSkill(Skill):
@match_event(SlashCommand, command="/testcommand")
| diff --git a/opsdroid/connector/slack/tests/responses/payload_view_submission.urlencoded b/opsdroid/connector/slack/tests/responses/payload_view_submission.urlencoded
--- a/opsdroid/connector/slack/tests/responses/payload_view_submission.urlencoded
+++ b/opsdroid/connector/slack/tests/responses/payload_view_submission.urlencoded
@@ -1 +1 @@
-payload=%7B%22type%22%3A%22view_submission%22%2C%22team%22%3A%7B%22id%22%3A%22T01ND2P8N91%22%2C%22domain%22%3A%22opsdroidtests%22%7D%2C%22user%22%3A%7B%22id%22%3A%22U01NK1K9L68%22%2C%22username%22%3A%22opsdroid.test%22%2C%22name%22%3A%22opsdroid.test%22%2C%22team_id%22%3A%22T01ND2P8N91%22%7D%2C%22api_app_id%22%3A%22A01NK2M4ABE%22%2C%22token%22%3A%22gAGOclMod3fTpSTaxBjyCjCT%22%2C%22trigger_id%22%3A%221835952449765.1761091294307.f04f465a970c18de583c065d0043875e%22%2C%22view%22%3A%7B%22id%22%3A%22V01QKTZBFMK%22%2C%22team_id%22%3A%22T01ND2P8N91%22%2C%22type%22%3A%22modal%22%2C%22blocks%22%3A%5B%7B%22type%22%3A%22input%22%2C%22block_id%22%3A%221%3DzGH%22%2C%22label%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Label%22%2C%22emoji%22%3Atrue%7D%2C%22hint%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Hint+text%22%2C%22emoji%22%3Atrue%7D%2C%22optional%22%3Afalse%2C%22dispatch_action%22%3Afalse%2C%22element%22%3A%7B%22type%22%3A%22plain_text_input%22%2C%22action_id%22%3A%22sl_input%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Placeholder+text+for+single-line+input%22%2C%22emoji%22%3Atrue%7D%2C%22dispatch_action_config%22%3A%7B%22trigger_actions_on%22%3A%5B%22on_enter_pressed%22%5D%7D%7D%7D%2C%7B%22type%22%3A%22input%22%2C%22block_id%22%3A%227Zh%22%2C%22label%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Label%22%2C%22emoji%22%3Atrue%7D%2C%22hint%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Hint+text%22%2C%22emoji%22%3Atrue%7D%2C%22optional%22%3Afalse%2C%22dispatch_action%22%3Afalse%2C%22element%22%3A%7B%22type%22%3A%22plain_text_input%22%2C%22action_id%22%3A%22ml_input%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Placeholder+text+for+multi-line+input%22%2C%22emoji%22%3Atrue%7D%2C%22multiline%22%3Atrue%2C%22dispatch_action_config%22%3A%7B%22trigger_actions_on%22%3A%5B%22on_enter_pressed%22%5D%7D%7D%7D%2C%7B%22type%22%3A%22actions%22%2C%22block_id%22%3A%22cbQh%22%2C%22elements%22%3A%5B%7B%22type%22%3A%22conversations_select%22%2C%22action_id%22%3A%22actionId-0%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Select+a+conversation%22%2C%22emoji%22%3Atrue%7D%7D%2C%7B%22type%22%3A%22channels_select%22%2C%22action_id%22%3A%22actionId-1%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Select+a+channel%22%2C%22emoji%22%3Atrue%7D%7D%2C%7B%22type%22%3A%22users_select%22%2C%22action_id%22%3A%22actionId-2%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Select+a+user%22%2C%22emoji%22%3Atrue%7D%7D%2C%7B%22type%22%3A%22static_select%22%2C%22action_id%22%3A%22actionId-3%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Select+an+item%22%2C%22emoji%22%3Atrue%7D%2C%22options%22%3A%5B%7B%22text%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22%2Athis+is+plain_text+text%2A%22%2C%22emoji%22%3Atrue%7D%2C%22value%22%3A%22value-0%22%7D%2C%7B%22text%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22%2Athis+is+plain_text+text%2A%22%2C%22emoji%22%3Atrue%7D%2C%22value%22%3A%22value-1%22%7D%2C%7B%22text%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22%2Athis+is+plain_text+text%2A%22%2C%22emoji%22%3Atrue%7D%2C%22value%22%3A%22value-2%22%7D%5D%7D%5D%7D%2C%7B%22type%22%3A%22actions%22%2C%22block_id%22%3A%22an8gR%22%2C%22elements%22%3A%5B%7B%22type%22%3A%22conversations_select%22%2C%22action_id%22%3A%22actionId-0%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Select+private+conversation%22%2C%22emoji%22%3Atrue%7D%2C%22filter%22%3A%7B%22include%22%3A%5B%22private%22%5D%7D%7D%5D%7D%2C%7B%22type%22%3A%22actions%22%2C%22block_id%22%3A%22YWJ%22%2C%22elements%22%3A%5B%7B%22type%22%3A%22datepicker%22%2C%22action_id%22%3A%22actionId-0%22%2C%22initial_date%22%3A%221990-04-28%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Select+a+date%22%2C%22emoji%22%3Atrue%7D%7D%2C%7B%22type%22%3A%22timepicker%22%2C%22action_id%22%3A%22actionId-1%22%2C%22initial_time%22%3A%2213%3A37%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Select+time%22%2C%22emoji%22%3Atrue%7D%7D%5D%7D%5D%2C%22private_metadata%22%3A%22%22%2C%22callback_id%22%3A%22%22%2C%22state%22%3A%7B%22values%22%3A%7B%221%3DzGH%22%3A%7B%22sl_input%22%3A%7B%22type%22%3A%22plain_text_input%22%2C%22value%22%3A%22ddd%22%7D%7D%2C%227Zh%22%3A%7B%22ml_input%22%3A%7B%22type%22%3A%22plain_text_input%22%2C%22value%22%3A%22dddd%22%7D%7D%2C%22cbQh%22%3A%7B%22actionId-0%22%3A%7B%22type%22%3A%22conversations_select%22%2C%22selected_conversation%22%3Anull%7D%2C%22actionId-1%22%3A%7B%22type%22%3A%22channels_select%22%2C%22selected_channel%22%3Anull%7D%2C%22actionId-2%22%3A%7B%22type%22%3A%22users_select%22%2C%22selected_user%22%3Anull%7D%2C%22actionId-3%22%3A%7B%22type%22%3A%22static_select%22%2C%22selected_option%22%3Anull%7D%7D%2C%22an8gR%22%3A%7B%22actionId-0%22%3A%7B%22type%22%3A%22conversations_select%22%2C%22selected_conversation%22%3Anull%7D%7D%2C%22YWJ%22%3A%7B%22actionId-0%22%3A%7B%22type%22%3A%22datepicker%22%2C%22selected_date%22%3A%221990-04-28%22%7D%2C%22actionId-1%22%3A%7B%22type%22%3A%22timepicker%22%2C%22selected_time%22%3A%2202%3A00%22%7D%7D%7D%7D%2C%22hash%22%3A%221615311191.RKSmr8cX%22%2C%22title%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Modal+Title%22%2C%22emoji%22%3Atrue%7D%2C%22clear_on_close%22%3Afalse%2C%22notify_on_close%22%3Afalse%2C%22close%22%3Anull%2C%22submit%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Submit%22%2C%22emoji%22%3Atrue%7D%2C%22previous_view_id%22%3Anull%2C%22root_view_id%22%3A%22V01QKTZBFMK%22%2C%22app_id%22%3A%22A01NK2M4ABE%22%2C%22external_id%22%3A%22%22%2C%22app_installed_team_id%22%3A%22T01ND2P8N91%22%2C%22bot_id%22%3A%22B01MY4ZRP5M%22%7D%2C%22response_urls%22%3A%5B%5D%2C%22is_enterprise_install%22%3Afalse%2C%22enterprise%22%3Anull%7D
+payload%3D%7B%22type%22%3A%22view_submission%22%2C%22team%22%3A%7B%22id%22%3A%22T01ND2P8N91%22%2C%22domain%22%3A%22opsdroidtests%22%7D%2C%22user%22%3A%7B%22id%22%3A%22U01NK1K9L68%22%2C%22username%22%3A%22opsdroid.test%22%2C%22name%22%3A%22opsdroid.test%22%2C%22team_id%22%3A%22T01ND2P8N91%22%7D%2C%22api_app_id%22%3A%22A01NK2M4ABE%22%2C%22token%22%3A%22here-comes-some-token%22%2C%22trigger_id%22%3A%221835952449765.1761091294307.f04f465a970c18de583c065d0043875e%22%2C%22view%22%3A%7B%22id%22%3A%22V01QKTZBFMK%22%2C%22team_id%22%3A%22T01ND2P8N91%22%2C%22type%22%3A%22modal%22%2C%22blocks%22%3A%5B%7B%22type%22%3A%22input%22%2C%22block_id%22%3A%221%3DzGH%22%2C%22label%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Label%22%2C%22emoji%22%3Atrue%7D%2C%22hint%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Hint%2Btext%22%2C%22emoji%22%3Atrue%7D%2C%22optional%22%3Afalse%2C%22dispatch_action%22%3Afalse%2C%22element%22%3A%7B%22type%22%3A%22plain_text_input%22%2C%22action_id%22%3A%22sl_input%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Placeholder%2Btext%2Bfor%2Bsingle-line%2Binput%22%2C%22emoji%22%3Atrue%7D%2C%22dispatch_action_config%22%3A%7B%22trigger_actions_on%22%3A%5B%22on_enter_pressed%22%5D%7D%7D%7D%2C%7B%22type%22%3A%22input%22%2C%22block_id%22%3A%227Zh%22%2C%22label%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Label%22%2C%22emoji%22%3Atrue%7D%2C%22hint%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Hint%2Btext%22%2C%22emoji%22%3Atrue%7D%2C%22optional%22%3Afalse%2C%22dispatch_action%22%3Afalse%2C%22element%22%3A%7B%22type%22%3A%22plain_text_input%22%2C%22action_id%22%3A%22ml_input%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Placeholder%2Btext%2Bfor%2Bmulti-line%2Binput%22%2C%22emoji%22%3Atrue%7D%2C%22multiline%22%3Atrue%2C%22dispatch_action_config%22%3A%7B%22trigger_actions_on%22%3A%5B%22on_enter_pressed%22%5D%7D%7D%7D%2C%7B%22type%22%3A%22actions%22%2C%22block_id%22%3A%22cbQh%22%2C%22elements%22%3A%5B%7B%22type%22%3A%22conversations_select%22%2C%22action_id%22%3A%22actionId-0%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Select%2Ba%2Bconversation%22%2C%22emoji%22%3Atrue%7D%7D%2C%7B%22type%22%3A%22channels_select%22%2C%22action_id%22%3A%22actionId-1%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Select%2Ba%2Bchannel%22%2C%22emoji%22%3Atrue%7D%7D%2C%7B%22type%22%3A%22users_select%22%2C%22action_id%22%3A%22actionId-2%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Select%2Ba%2Buser%22%2C%22emoji%22%3Atrue%7D%7D%2C%7B%22type%22%3A%22static_select%22%2C%22action_id%22%3A%22actionId-3%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Select%2Ban%2Bitem%22%2C%22emoji%22%3Atrue%7D%2C%22options%22%3A%5B%7B%22text%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22*this%2Bis%2Bplain_text%2Btext*%22%2C%22emoji%22%3Atrue%7D%2C%22value%22%3A%22value-0%22%7D%2C%7B%22text%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22*this%2Bis%2Bplain_text%2Btext*%22%2C%22emoji%22%3Atrue%7D%2C%22value%22%3A%22value-1%22%7D%2C%7B%22text%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22*this%2Bis%2Bplain_text%2Btext*%22%2C%22emoji%22%3Atrue%7D%2C%22value%22%3A%22value-2%22%7D%5D%7D%5D%7D%2C%7B%22type%22%3A%22actions%22%2C%22block_id%22%3A%22an8gR%22%2C%22elements%22%3A%5B%7B%22type%22%3A%22conversations_select%22%2C%22action_id%22%3A%22actionId-0%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Select%2Bprivate%2Bconversation%22%2C%22emoji%22%3Atrue%7D%2C%22filter%22%3A%7B%22include%22%3A%5B%22private%22%5D%7D%7D%5D%7D%2C%7B%22type%22%3A%22actions%22%2C%22block_id%22%3A%22YWJ%22%2C%22elements%22%3A%5B%7B%22type%22%3A%22datepicker%22%2C%22action_id%22%3A%22actionId-0%22%2C%22initial_date%22%3A%221990-04-28%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Select%2Ba%2Bdate%22%2C%22emoji%22%3Atrue%7D%7D%2C%7B%22type%22%3A%22timepicker%22%2C%22action_id%22%3A%22actionId-1%22%2C%22initial_time%22%3A%2213%3A37%22%2C%22placeholder%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Select%2Btime%22%2C%22emoji%22%3Atrue%7D%7D%5D%7D%5D%2C%22private_metadata%22%3A%22%22%2C%22callback_id%22%3A%22simple_callback_id%22%2C%22state%22%3A%7B%22values%22%3A%7B%221%3DzGH%22%3A%7B%22sl_input%22%3A%7B%22type%22%3A%22plain_text_input%22%2C%22value%22%3A%22ddd%22%7D%7D%2C%227Zh%22%3A%7B%22ml_input%22%3A%7B%22type%22%3A%22plain_text_input%22%2C%22value%22%3A%22dddd%22%7D%7D%2C%22cbQh%22%3A%7B%22actionId-0%22%3A%7B%22type%22%3A%22conversations_select%22%2C%22selected_conversation%22%3Anull%7D%2C%22actionId-1%22%3A%7B%22type%22%3A%22channels_select%22%2C%22selected_channel%22%3Anull%7D%2C%22actionId-2%22%3A%7B%22type%22%3A%22users_select%22%2C%22selected_user%22%3Anull%7D%2C%22actionId-3%22%3A%7B%22type%22%3A%22static_select%22%2C%22selected_option%22%3Anull%7D%7D%2C%22an8gR%22%3A%7B%22actionId-0%22%3A%7B%22type%22%3A%22conversations_select%22%2C%22selected_conversation%22%3Anull%7D%7D%2C%22YWJ%22%3A%7B%22actionId-0%22%3A%7B%22type%22%3A%22datepicker%22%2C%22selected_date%22%3A%221990-04-28%22%7D%2C%22actionId-1%22%3A%7B%22type%22%3A%22timepicker%22%2C%22selected_time%22%3A%2202%3A00%22%7D%7D%7D%7D%2C%22hash%22%3A%221615311191.RKSmr8cX%22%2C%22title%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Modal%2BTitle%22%2C%22emoji%22%3Atrue%7D%2C%22clear_on_close%22%3Afalse%2C%22notify_on_close%22%3Afalse%2C%22close%22%3Anull%2C%22submit%22%3A%7B%22type%22%3A%22plain_text%22%2C%22text%22%3A%22Submit%22%2C%22emoji%22%3Atrue%7D%2C%22previous_view_id%22%3Anull%2C%22root_view_id%22%3A%22V01QKTZBFMK%22%2C%22app_id%22%3A%22A01NK2M4ABE%22%2C%22external_id%22%3A%22%22%2C%22app_installed_team_id%22%3A%22T01ND2P8N91%22%2C%22bot_id%22%3A%22B01MY4ZRP5M%22%7D%2C%22response_urls%22%3A%5B%5D%2C%22is_enterprise_install%22%3Afalse%2C%22enterprise%22%3Anull%7D
diff --git a/opsdroid/connector/slack/tests/test_connector.py b/opsdroid/connector/slack/tests/test_connector.py
--- a/opsdroid/connector/slack/tests/test_connector.py
+++ b/opsdroid/connector/slack/tests/test_connector.py
@@ -3,11 +3,16 @@
import asynctest.mock as amock
import pytest
-from slack_sdk.socket_mode.request import SocketModeRequest
-
from opsdroid import events
from opsdroid.connector.slack.connector import SlackApiError
-from opsdroid.connector.slack.events import Blocks, EditedBlocks
+from opsdroid.connector.slack.events import (
+ Blocks,
+ EditedBlocks,
+ ModalOpen,
+ ModalPush,
+ ModalUpdate,
+)
+from slack_sdk.socket_mode.request import SocketModeRequest
from .conftest import get_path
@@ -15,6 +20,9 @@
AUTH_TEST = ("/auth.test", "POST", get_path("method_auth.test.json"), 200)
CHAT_POST_MESSAGE = ("/chat.postMessage", "POST", {"ok": True}, 200)
CHAT_UPDATE_MESSAGE = ("/chat.update", "POST", {"ok": True}, 200)
+VIEWS_OPEN = ("/views.open", "POST", {"ok": True}, 200)
+VIEWS_UPDATE = ("/views.update", "POST", {"ok": True}, 200)
+VIEWS_PUSH = ("/views.push", "POST", {"ok": True}, 200)
REACTIONS_ADD = ("/reactions.add", "POST", {"ok": True}, 200)
CONVERSATIONS_HISTORY = (
"/conversations.history",
@@ -312,6 +320,47 @@ async def test_edit_blocks(send_event, connector):
assert response["ok"]
[email protected]
[email protected]_response(*VIEWS_OPEN)
+async def test_open_modal(send_event, connector):
+ event = ModalOpen(trigger_id="123456", view={"key1": "value1", "key2": "value2"})
+ payload, response = await send_event(VIEWS_OPEN, event)
+ assert payload == {
+ "trigger_id": "123456",
+ "view": '{"key1": "value1", "key2": "value2"}',
+ }
+ assert response["ok"]
+
+
[email protected]
[email protected]_response(*VIEWS_UPDATE)
+async def test_update_modal(send_event, connector):
+ event = ModalUpdate(
+ external_id="123456",
+ view={"key1": "value1", "key2": "value2"},
+ hash_="12345678",
+ )
+ payload, response = await send_event(VIEWS_UPDATE, event)
+ assert payload == {
+ "external_id": "123456",
+ "view": '{"key1": "value1", "key2": "value2"}',
+ "hash": "12345678",
+ }
+ assert response["ok"]
+
+
[email protected]
[email protected]_response(*VIEWS_PUSH)
+async def test_push_modal(send_event, connector):
+ event = ModalPush(trigger_id="123456", view={"key1": "value1", "key2": "value2"})
+ payload, response = await send_event(VIEWS_PUSH, event)
+ assert payload == {
+ "trigger_id": "123456",
+ "view": '{"key1": "value1", "key2": "value2"}',
+ }
+ assert response["ok"]
+
+
@pytest.mark.asyncio
@pytest.mark.add_response(*REACTIONS_ADD)
async def test_send_reaction(send_event, connector):
diff --git a/opsdroid/connector/slack/tests/test_create_events.py b/opsdroid/connector/slack/tests/test_create_events.py
--- a/opsdroid/connector/slack/tests/test_create_events.py
+++ b/opsdroid/connector/slack/tests/test_create_events.py
@@ -188,7 +188,7 @@ async def receive_slash_command():
async def test_receive_view_submission(opsdroid, connector, mock_api):
await opsdroid.load(config=MINIMAL_CONFIG)
- async def receive_message_action():
+ async def receive_view_submission():
headers, data = get_webhook_payload(
"payload_view_submission.urlencoded", "urlencoded"
)
@@ -203,7 +203,7 @@ async def receive_message_action():
return True
- assert await run_unit_test(opsdroid, receive_message_action)
+ assert await run_unit_test(opsdroid, receive_view_submission)
@pytest.mark.asyncio
| Feature Request: Suggest implementing 'modal' support for the Slack connector
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://app.element.io/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
I'm developing the skill with slack connector, and need to using 'modal' type in the skill to temporarily displaying dynamic and interactive information. So suggest opsdroid slack connector to have the capability to send a message as 'modal' type and handle the respond of the modal.
## Expected Functionality
The slack connector is able to send a message as 'modal' type and handle the respond of the modal.
## Experienced Functionality
when I attempted to send message using the type `Modal` which is provided by Slack, I got the error as below. It seems the modal type is not supported yet.
```
The server responded with: {'ok': False, 'error': 'invalid_blocks', 'errors': ['unsupported type: modal [json-pointer:/blocks/0/type]'], 'response_metadata': {'messages': ['[ERROR] unsupported type: modal [json-pointer:/blocks/0/type]']}}
```
## Versions
- **Opsdroid version:** 0.24.1
- **Python version:** 3.8
- **OS/Docker version:** Redhat 8
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| 2022-04-28T14:57:37 |
|
opsdroid/opsdroid | 1,908 | opsdroid__opsdroid-1908 | [
"1699"
] | 5de6faa6f495ce439346f13563bfdf8c7faed56a | diff --git a/opsdroid/connector/slack/connector.py b/opsdroid/connector/slack/connector.py
--- a/opsdroid/connector/slack/connector.py
+++ b/opsdroid/connector/slack/connector.py
@@ -5,13 +5,14 @@
import os
import re
import ssl
+import time
import urllib.parse
import aiohttp
+import arrow
import certifi
from emoji import demojize
-
from slack_sdk.errors import SlackApiError
from slack_sdk.socket_mode.aiohttp import SocketModeClient
from slack_sdk.socket_mode.request import SocketModeRequest
@@ -19,7 +20,6 @@
from slack_sdk.web.async_client import AsyncWebClient
from voluptuous import Required
-
import opsdroid.events
from opsdroid.connector import Connector, register_event
from opsdroid.connector.slack.create_events import SlackEventCreator
@@ -48,6 +48,8 @@
"default-room": str,
"icon-emoji": str,
"start-thread": bool,
+ "refresh-interval": int,
+ "channel-limit": int,
}
@@ -66,6 +68,8 @@ def __init__(self, config, opsdroid=None):
self.start_thread = config.get("start-thread", False)
self.socket_mode = config.get("socket-mode", True)
self.app_token = config.get("app-token")
+ self.channel_limit = config.get("channel-limit", 100)
+ self.refresh_interval = config.get("refresh-interval", 600)
self.ssl_context = ssl.create_default_context(cafile=certifi.where())
self.slack_web_client = AsyncWebClient(
token=self.bot_token,
@@ -81,6 +85,7 @@ def __init__(self, config, opsdroid=None):
self.user_info = None
self.bot_id = None
self.known_users = {}
+ self.known_channels = {}
self._event_creator = SlackEventCreator(self)
self._event_queue = asyncio.Queue()
@@ -108,6 +113,7 @@ async def connect(self):
)
).data
self.bot_id = self.user_info["user"]["profile"]["bot_id"]
+ self.opsdroid.create_task(self._get_channels())
except SlackApiError as error:
_LOGGER.error(
_(
@@ -191,6 +197,28 @@ def _generate_base_data(self, event: opsdroid.events.Event) -> dict:
return data
+ async def _get_channels(self):
+ """Grab all the channels from the Slack API"""
+
+ while self.opsdroid.eventloop.is_running():
+ _LOGGER.info(_("Updating Channels from Slack API at %s."), time.asctime())
+ channels = await self.slack_web_client.conversations_list(
+ limit=self.channel_limit
+ )
+ cursor = channels["response_metadata"].get("next_cursor")
+
+ while cursor:
+ self.known_channels.update({c["name"]: c for c in channels["channels"]})
+
+ channels = await self.slack_web_client.conversations_list(
+ cursor=cursor, limit=self.channel_limit
+ )
+ cursor = channels["response_metadata"].get("next_cursor")
+
+ channel_count = len(self.known_channels.keys())
+ _LOGGER.info("Grabbed a total of %s channels from Slack", channel_count)
+ await asyncio.sleep(self.refresh_interval - arrow.now().time().second)
+
async def event_handler(self, payload):
"""Handle different payload types and parse the resulting events"""
@@ -276,6 +304,36 @@ async def web_event_handler(self, request):
return aiohttp.web.Response(text=json.dumps("Received"), status=200)
+ async def find_channel(self, channel_name):
+ """
+ Given a channel name return the channel properties.
+
+ args:
+ channel_name: the name of the channel. ie: general
+
+ returns:
+ dict with channel details
+
+ **Basic Usage Example in a Skill:**
+
+ .. code-block:: python
+
+ from opsdroid.skill import Skill
+ from opsdroid.matchers import match_regex
+
+ class SearchMessagesSkill(Skill):
+ @match_regex(r"find channel")
+ async def find_channel(self, message):
+ """ """
+ slack = self.opsdroid.get_connector("slack")
+ channel = await slack.find_channel(channel_name="general")
+ await message.respond(str(channel))
+ """
+
+ if channel_name in self.known_channels:
+ return self.known_channels[channel_name]
+ _LOGGER.info(_("Channel with name %s not found"), channel_name)
+
async def search_history_messages(self, channel, start_time, end_time, limit=100):
"""
Search for messages in a conversation given the intial and end timestamp.
@@ -304,7 +362,7 @@ async def search_messages(self, message):
messages = await slack.search_history_messages(
"CHANEL_ID", start_time="1512085950.000216", end_time="1512104434.000490"
)
- await message.respond(messages)
+ await message.respond(str(messages))
"""
messages = []
history = await self.slack_web_client.conversations_history(
| diff --git a/opsdroid/connector/slack/tests/responses/method_conversations.list_first_page.json b/opsdroid/connector/slack/tests/responses/method_conversations.list_first_page.json
new file mode 100644
--- /dev/null
+++ b/opsdroid/connector/slack/tests/responses/method_conversations.list_first_page.json
@@ -0,0 +1,74 @@
+{
+ "ok": true,
+ "channels": [
+ {
+ "id": "C012AB3CD",
+ "name": "general",
+ "is_channel": true,
+ "is_group": false,
+ "is_im": false,
+ "created": 1449252889,
+ "creator": "U012A3CDE",
+ "is_archived": false,
+ "is_general": true,
+ "unlinked": 0,
+ "name_normalized": "general",
+ "is_shared": false,
+ "is_ext_shared": false,
+ "is_org_shared": false,
+ "pending_shared": [],
+ "is_pending_ext_shared": false,
+ "is_member": true,
+ "is_private": false,
+ "is_mpim": false,
+ "topic": {
+ "value": "Company-wide announcements and work-based matters",
+ "creator": "",
+ "last_set": 0
+ },
+ "purpose": {
+ "value": "This channel is for team-wide communication and announcements. All team members are in this channel.",
+ "creator": "",
+ "last_set": 0
+ },
+ "previous_names": [],
+ "num_members": 4
+ },
+ {
+ "id": "C061EG9T2",
+ "name": "random",
+ "is_channel": true,
+ "is_group": false,
+ "is_im": false,
+ "created": 1449252889,
+ "creator": "U061F7AUR",
+ "is_archived": false,
+ "is_general": false,
+ "unlinked": 0,
+ "name_normalized": "random",
+ "is_shared": false,
+ "is_ext_shared": false,
+ "is_org_shared": false,
+ "pending_shared": [],
+ "is_pending_ext_shared": false,
+ "is_member": true,
+ "is_private": false,
+ "is_mpim": false,
+ "topic": {
+ "value": "Non-work banter and water cooler conversation",
+ "creator": "",
+ "last_set": 0
+ },
+ "purpose": {
+ "value": "A place for non-work-related flimflam, faffing, hodge-podge or jibber-jabber you'd prefer to keep out of more focused work-related channels.",
+ "creator": "",
+ "last_set": 0
+ },
+ "previous_names": [],
+ "num_members": 4
+ }
+ ],
+ "response_metadata": {
+ "next_cursor": "dGVhbTpDMDYxRkE1UEI="
+ }
+}
diff --git a/opsdroid/connector/slack/tests/responses/method_conversations.list_last_page.json b/opsdroid/connector/slack/tests/responses/method_conversations.list_last_page.json
new file mode 100644
--- /dev/null
+++ b/opsdroid/connector/slack/tests/responses/method_conversations.list_last_page.json
@@ -0,0 +1,72 @@
+{
+ "ok": true,
+ "channels": [
+ {
+ "id": "C012AB3CD",
+ "name": "general",
+ "is_channel": true,
+ "is_group": false,
+ "is_im": false,
+ "created": 1449252889,
+ "creator": "U012A3CDE",
+ "is_archived": false,
+ "is_general": true,
+ "unlinked": 0,
+ "name_normalized": "general",
+ "is_shared": false,
+ "is_ext_shared": false,
+ "is_org_shared": false,
+ "pending_shared": [],
+ "is_pending_ext_shared": false,
+ "is_member": true,
+ "is_private": false,
+ "is_mpim": false,
+ "topic": {
+ "value": "Company-wide announcements and work-based matters",
+ "creator": "",
+ "last_set": 0
+ },
+ "purpose": {
+ "value": "This channel is for team-wide communication and announcements. All team members are in this channel.",
+ "creator": "",
+ "last_set": 0
+ },
+ "previous_names": [],
+ "num_members": 4
+ },
+ {
+ "id": "C061EG9T2",
+ "name": "random",
+ "is_channel": true,
+ "is_group": false,
+ "is_im": false,
+ "created": 1449252889,
+ "creator": "U061F7AUR",
+ "is_archived": false,
+ "is_general": false,
+ "unlinked": 0,
+ "name_normalized": "random",
+ "is_shared": false,
+ "is_ext_shared": false,
+ "is_org_shared": false,
+ "pending_shared": [],
+ "is_pending_ext_shared": false,
+ "is_member": true,
+ "is_private": false,
+ "is_mpim": false,
+ "topic": {
+ "value": "Non-work banter and water cooler conversation",
+ "creator": "",
+ "last_set": 0
+ },
+ "purpose": {
+ "value": "A place for non-work-related flimflam, faffing, hodge-podge or jibber-jabber you'd prefer to keep out of more focused work-related channels.",
+ "creator": "",
+ "last_set": 0
+ },
+ "previous_names": [],
+ "num_members": 4
+ }
+ ],
+ "response_metadata": {"next_cursor": ""}
+}
diff --git a/opsdroid/connector/slack/tests/test_connector.py b/opsdroid/connector/slack/tests/test_connector.py
--- a/opsdroid/connector/slack/tests/test_connector.py
+++ b/opsdroid/connector/slack/tests/test_connector.py
@@ -12,6 +12,7 @@
ModalPush,
ModalUpdate,
)
+
from slack_sdk.socket_mode.request import SocketModeRequest
from .conftest import get_path
@@ -30,6 +31,12 @@
get_path("method_conversations.history.json"),
200,
)
+CONVERSATIONS_LIST_LAST_PAGE = (
+ "/conversations.list",
+ "GET",
+ get_path("method_conversations.list_last_page.json"),
+ 200,
+)
CONVERSATIONS_CREATE = ("/conversations.create", "POST", {"ok": True}, 200)
CONVERSATIONS_RENAME = ("/conversations.rename", "POST", {"ok": True}, 200)
CONVERSATIONS_JOIN = ("/conversations.join", "POST", {"ok": True}, 200)
@@ -188,6 +195,26 @@ async def test_search_history_messages_more_than_one_api_request(connector, mock
assert isinstance(history, list)
[email protected]
[email protected]_response(*CONVERSATIONS_LIST_LAST_PAGE)
+async def test_find_channel(connector, mock_api):
+ connector.known_channels = {"general": {"name": "general", "id": "C012AB3CD"}}
+
+ channel = await connector.find_channel("general")
+ assert channel["id"] == "C012AB3CD"
+ assert channel["name"] == "general"
+
+
[email protected]
[email protected]_response(*CONVERSATIONS_LIST_LAST_PAGE)
+async def test_find_channel_not_found(connector, mock_api, caplog):
+ connector.known_channels = {"general": {"name": "general", "id": "C012AB3CD"}}
+
+ caplog.set_level(logging.INFO)
+ await connector.find_channel("another-channel")
+ assert "Channel with name another-channel not found" in caplog.text
+
+
@pytest.mark.asyncio
async def test_replace_usernames(connector):
connector.known_users = {"U01NK1K9L68": {"name": "Test User"}}
diff --git a/opsdroid/connector/slack/tests/test_create_events.py b/opsdroid/connector/slack/tests/test_create_events.py
--- a/opsdroid/connector/slack/tests/test_create_events.py
+++ b/opsdroid/connector/slack/tests/test_create_events.py
@@ -4,7 +4,6 @@
import json
import pytest
-
from opsdroid.connector.slack.create_events import SlackEventCreator
from opsdroid.testing import MINIMAL_CONFIG, call_endpoint, run_unit_test
@@ -26,35 +25,29 @@ def get_webhook_payload(file_name, _type):
CONNECTOR_ENDPOINT = "/connector/slack"
+
+# The following are sample responses from the Slack API, when the Slack connector is initializing
USERS_INFO = ("/users.info", "GET", get_path("method_users.info.json"), 200)
AUTH_TEST = ("/auth.test", "POST", get_path("method_auth.test.json"), 200)
+CONVERSATIONS_LIST_LAST_PAGE = (
+ "/conversations.list",
+ "GET",
+ get_path("method_conversations.list_last_page.json"),
+ 200,
+)
+CONVERSATIONS_LIST_FIRST_PAGE = (
+ "/conversations.list",
+ "GET",
+ get_path("method_conversations.list_first_page.json"),
+ 200,
+)
@pytest.mark.asyncio
[email protected]_response(*USERS_INFO)
[email protected]_response(*AUTH_TEST)
-async def test_receive_url_verification(opsdroid, connector, mock_api):
- await opsdroid.load(config=MINIMAL_CONFIG)
-
- async def receive_message_action():
- headers, data = get_webhook_payload("payload_url_verification.json", "json")
- resp = await call_endpoint(
- opsdroid,
- CONNECTOR_ENDPOINT,
- "POST",
- data=data,
- headers=headers,
- )
- assert resp.status == 200
-
- return True
-
- assert await run_unit_test(opsdroid, receive_message_action)
-
-
@pytest.mark.parametrize(
"payload",
[
+ "payload_url_verification.json",
"payload_message.json",
"payload_message_bot_message.json",
"payload_message_message_changed.json",
@@ -66,12 +59,21 @@ async def receive_message_action():
"payload_channel_rename.json",
"payload_pin_added.json",
"payload_pin_removed.json",
+ "payload_block_action_button.urlencoded",
+ "payload_block_action_overflow.urlencoded",
+ "payload_block_action_static_select.urlencoded",
+ "payload_block_action_datepicker.urlencoded",
+ "payload_block_action_multi_static_select.urlencoded",
+ "payload_message_action.urlencoded",
+ "payload_slash_command.urlencoded",
+ "payload_view_submission.urlencoded",
],
)
@pytest.mark.add_response(*USERS_INFO)
@pytest.mark.add_response(*AUTH_TEST)
[email protected]
-async def test_receive_event_callback(opsdroid, connector, mock_api, payload):
[email protected]_response(*CONVERSATIONS_LIST_LAST_PAGE)
[email protected]_response(*CONVERSATIONS_LIST_FIRST_PAGE)
+async def test_events_from_slack(opsdroid, connector, mock_api, payload):
"""Mocks receiving a payload event from the Slack API.
Run unit test against an opsdroid instance
parameter:
@@ -86,64 +88,9 @@ async def test_receive_event_callback(opsdroid, connector, mock_api, payload):
}
async def receive_event(payload):
- headers, data = get_webhook_payload(payload, "json")
- resp = await call_endpoint(
- opsdroid,
- CONNECTOR_ENDPOINT,
- "POST",
- data=data,
- headers=headers,
- )
-
- assert resp.status == 200
-
- return True
-
- assert await run_unit_test(opsdroid, receive_event, payload)
-
-
[email protected](
- "payload",
- [
- "payload_block_action_button.urlencoded",
- "payload_block_action_overflow.urlencoded",
- "payload_block_action_static_select.urlencoded",
- "payload_block_action_datepicker.urlencoded",
- "payload_block_action_multi_static_select.urlencoded",
- ],
-)
[email protected]_response(*USERS_INFO)
[email protected]_response(*AUTH_TEST)
[email protected]
-async def test_receive_block_action(opsdroid, connector, mock_api, payload):
- await opsdroid.load(config=MINIMAL_CONFIG)
-
- async def receive_block_action(payload):
- headers, data = get_webhook_payload(payload, "urlencoded")
- resp = await call_endpoint(
- opsdroid,
- CONNECTOR_ENDPOINT,
- "POST",
- data=data,
- headers=headers,
- )
- assert resp.status == 200
+ payload_type = payload.split(".")[1]
- return True
-
- assert await run_unit_test(opsdroid, receive_block_action, payload)
-
-
[email protected]
[email protected]_response(*USERS_INFO)
[email protected]_response(*AUTH_TEST)
-async def test_receive_message_action(opsdroid, connector, mock_api):
- await opsdroid.load(config=MINIMAL_CONFIG)
-
- async def receive_message_action():
- headers, data = get_webhook_payload(
- "payload_message_action.urlencoded", "urlencoded"
- )
+ headers, data = get_webhook_payload(payload, payload_type)
resp = await call_endpoint(
opsdroid,
CONNECTOR_ENDPOINT,
@@ -155,76 +102,7 @@ async def receive_message_action():
return True
- assert await run_unit_test(opsdroid, receive_message_action)
-
-
[email protected]
[email protected]_response(*USERS_INFO)
[email protected]_response(*AUTH_TEST)
-async def test_receive_slash_command(opsdroid, connector, mock_api):
- await opsdroid.load(config=MINIMAL_CONFIG)
-
- async def receive_slash_command():
- headers, data = get_webhook_payload(
- "payload_slash_command.urlencoded", "urlencoded"
- )
- resp = await call_endpoint(
- opsdroid,
- CONNECTOR_ENDPOINT,
- "POST",
- data=data,
- headers=headers,
- )
- assert resp.status == 200
-
- return True
-
- assert await run_unit_test(opsdroid, receive_slash_command)
-
-
[email protected]
[email protected]_response(*USERS_INFO)
[email protected]_response(*AUTH_TEST)
-async def test_receive_view_submission(opsdroid, connector, mock_api):
- await opsdroid.load(config=MINIMAL_CONFIG)
-
- async def receive_view_submission():
- headers, data = get_webhook_payload(
- "payload_view_submission.urlencoded", "urlencoded"
- )
- resp = await call_endpoint(
- opsdroid,
- CONNECTOR_ENDPOINT,
- "POST",
- data=data,
- headers=headers,
- )
- assert resp.status == 200
-
- return True
-
- assert await run_unit_test(opsdroid, receive_view_submission)
-
-
[email protected]
[email protected]_response(*USERS_INFO)
[email protected]_response(*AUTH_TEST)
-async def test_receive_unknown_payload(opsdroid, connector, mock_api, caplog):
- await opsdroid.load(config=MINIMAL_CONFIG)
-
- async def receive_message_action():
- resp = await call_endpoint(
- opsdroid,
- CONNECTOR_ENDPOINT,
- "POST",
- data=json.dumps({"type": "another_unknown type"}),
- headers={"content-type": "application/json"},
- )
- assert resp.status == 200
-
- return True
-
- assert await run_unit_test(opsdroid, receive_message_action)
+ assert await run_unit_test(opsdroid, receive_event, payload)
@pytest.mark.asyncio
| Slack Connector, search a channel ID, by its name
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://riot.im/app/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
Currently, if we need to send any message to a Slack Channel, we have to know the channel ID. Unfortunately, this is not always possible, and it would be nice to have a way that Opsdroid translates channel names to channel ids.
I have been searching on the Slack API and there is no method that would do this, so the only thing I can think of, is iterating over all the channels. (probably when Opsdroid starts the connector?) https://api.slack.com/methods/conversations.list
I would like to submit a PR for this, and I would love your thoughts, suggestions on how could this be better implemented.
## Steps to Reproduce
N/A
## Expected Functionality
```
await self.opsdroid.send(Message("Hello", target="test-channel"))
```
## Experienced Functionality
This will throw an error:
```
await self.opsdroid.send(Message("Hello", target="test-channel"))
```
Only works when channel ID is mentioned:
```
await self.opsdroid.send(Message("Hello", target="CF3ZP8KS8"))
```
## Versions
- **Opsdroid version:** All versions
- **Python version:** All Versions
- **OS/Docker version:** All Versions
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| Does this work for you?
```python
await self.opsdroid.send(Message("Hello", target="#test-channel"))
```
I think this behavior has changed very recently on the Slack API. (Unless opsdroid is doing something in the background that I was not able to catch)
The following methods are working now:
```
await self.opsdroid.send(Message("Hello", target="test-channel"))
await self.opsdroid.send(Message("Hello", target="#test-channel"))
```
I am saying very recently because this has been an issue that I have been trying to tackle for a while, and it was not working on the past.
I see that not even the documentation of https://api.slack.com/methods/chat.postMessage#channels has been updated yet
> Post to a public channel
> Pass the channel's ID (C024BE91L) to the channel parameter and the message will be posted to that channel. The channel's ID can be retrieved through the conversations.list API method.
I am not sure if this issue is relevant now, I have found another method, with the same problem (https://api.slack.com/methods/conversations.setTopic) where the ID is required, and the channel name won't work
Does it make sense for opsdroid to have a channel list, with its channel ids and other details?
I've always used the `#` prefixed version with no issues.
I don't think opsdroid supports `setTopic` right now. But yes I see that this could be a problem in other places.
I would be very happy to review a PR which grabs the channel list and automatically converts names to IDs as part of the send methods. | 2022-05-03T05:38:59 |
opsdroid/opsdroid | 1,911 | opsdroid__opsdroid-1911 | [
"1910"
] | 33241f2d74940e061fada8eee8d8238230593295 | diff --git a/opsdroid/connector/slack/connector.py b/opsdroid/connector/slack/connector.py
--- a/opsdroid/connector/slack/connector.py
+++ b/opsdroid/connector/slack/connector.py
@@ -8,8 +8,11 @@
import aiohttp
import certifi
+import opsdroid.events
from emoji import demojize
-
+from opsdroid.connector import Connector, register_event
+from opsdroid.connector.slack.create_events import SlackEventCreator
+from opsdroid.connector.slack.events import Blocks, EditedBlocks
from slack_sdk.errors import SlackApiError
from slack_sdk.socket_mode.aiohttp import SocketModeClient
from slack_sdk.socket_mode.request import SocketModeRequest
@@ -17,11 +20,6 @@
from slack_sdk.web.async_client import AsyncWebClient
from voluptuous import Required
-import opsdroid.events
-from opsdroid.connector import Connector, register_event
-from opsdroid.connector.slack.create_events import SlackEventCreator
-from opsdroid.connector.slack.events import Blocks, EditedBlocks
-
_LOGGER = logging.getLogger(__name__)
_USE_BOT_TOKEN_MSG = (
@@ -139,6 +137,7 @@ async def disconnect(self):
Cancels the event queue worker task and disconnects the
socket_mode_client if socket mode was enabled."""
+
if self._event_queue_task:
self._event_queue_task.cancel()
await asyncio.gather(self._event_queue_task, return_exceptions=True)
@@ -177,6 +176,7 @@ def _generate_base_data(self, event: opsdroid.events.Event) -> dict:
data["thread_ts"] = raw_event["thread_ts"]
elif self.start_thread:
data["thread_ts"] = event.linked_event.event_id
+
return data
async def event_handler(self, payload):
@@ -191,21 +191,19 @@ async def event_handler(self, payload):
else:
event = await self._event_creator.create_event(payload, None)
- if not event:
- _LOGGER.error(
- "Payload: %s is not implemented. Event wont be parsed", payload
- )
+ if event:
+ if isinstance(event, list):
+ for e in event:
+ _LOGGER.debug(f"Got slack event: {e}")
+ await self.opsdroid.parse(e)
- return
-
- if isinstance(event, list):
- for e in event:
- _LOGGER.debug(f"Got slack event: {e}")
- await self.opsdroid.parse(e)
-
- if isinstance(event, opsdroid.events.Event):
- _LOGGER.debug(f"Got slack event: {event}")
- await self.opsdroid.parse(event)
+ if isinstance(event, opsdroid.events.Event):
+ _LOGGER.debug(f"Got slack event: {event}")
+ await self.opsdroid.parse(event)
+ else:
+ _LOGGER.debug(
+ "Event returned empty for payload: %s. Event was not parsed", payload
+ )
async def socket_event_handler(
self, client: SocketModeClient, req: SocketModeRequest
| Slack Connector is logging an error which is not really an error
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://app.element.io/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
Every time opsdroid responds in a thread for the slack connector, the log is throwing an error in the following form:
```code
ERROR Payload: {...} is not implemented. Event wont be parsed
```
This is not really an error, but just a misplaced log message that should be a debug message.
The [create_event](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/connector/slack/connector.py#L190) method from the slack connector is returning an empty event. The [event_handler](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/connector/slack/connector.py#L195) checks that the event is not empty and throws the error, which should not be. If the event returns empty (which is valid) the event handler should not parse the event.
Since it's labeled as an error, every time there is a response in a thread from opsdroid, the ERROR is logged, which creates a lot of false entries in a production log.
## Steps to Reproduce
Create a skill where opsdroid replies inside a thread
## Expected Functionality
The error log should not appear as it's not really an error
## Experienced Functionality
The logger is longing an ERROR message which is not really an error
## Versions
- **0.26:**
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| 2022-05-05T15:59:42 |
||
opsdroid/opsdroid | 1,923 | opsdroid__opsdroid-1923 | [
"1909"
] | 2f2034a2a38f91329c3fdd1489a703adecfd229f | diff --git a/opsdroid/connector/telegram/__init__.py b/opsdroid/connector/telegram/__init__.py
--- a/opsdroid/connector/telegram/__init__.py
+++ b/opsdroid/connector/telegram/__init__.py
@@ -305,7 +305,7 @@ async def handle_messages(self, message, user, user_id, update_id):
if message.get("reply_to_message"):
event = Reply(
- text=emoji.demojize(message["text"]),
+ text=emoji.demojize(message.get("text", "")),
user=user,
user_id=user_id,
event_id=message["message_id"],
@@ -317,7 +317,7 @@ async def handle_messages(self, message, user, user_id, update_id):
if message.get("text"):
event = Message(
- text=emoji.demojize(message["text"]),
+ text=emoji.demojize(message.get("text", "")),
user=user,
user_id=user_id,
target=message["chat"]["id"],
| Telegram connector stops working after a reply with just a GIF
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://app.element.io/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
Bot stops working when a certain event occurs in the chat. It tries to handle a message but fails and does not react to subsequent messages.
## Steps to Reproduce
EDIT: A reply with just a gif is sufficient to trigger this. Send a GIF via `@gif something` as a reply to a message from the bot.
Not perfectly sure, but the error below points me to:
https://github.com/opsdroid/opsdroid/blob/33241f2d74940e061fada8eee8d8238230593295/opsdroid/connector/telegram/__init__.py#L308
```
if message.get("reply_to_message"):
event = Reply(
text=emoji.demojize(message["text"]),
user=user,
user_id=user_id,
event_id=message["message_id"],
linked_event=message["reply_to_message"]["message_id"],
target=message["chat"]["id"],
connector=self,
raw_event=message,
)
```
So the best way of trying to reproduce it would be to sent a reply that does not contain a text (maybe just a sticker or emoji?)
## Expected Functionality
If there is a message that can not be handled the bot should skip it (and log the error) and continue.
## Experienced Functionality
The Bot logs an error and does not handle subsequent messages.
```
[05/05/22 05:42:19] ERROR Error handling request web_protocol.py:405
╭─ Traceback (most recent cal─╮
│ │
│ /usr/local/lib/python3.9/si │
│ te-packages/aiohttp/web_pro │
│ tocol.py:435 in │
│ _handle_request │
│ │
│ 432 │ │ try: │
│ 433 │ │ │ try: │
│ 434 │ │ │ │ self. │
│ ❱ 435 │ │ │ │ resp │
│ 436 │ │ │ finally: │
│ 437 │ │ │ │ self. │
│ 438 │ │ except HTTPEx │
│ /usr/local/lib/python3.9/si │
│ te-packages/aiohttp/web_app │
│ .py:504 in _handle │
│ │
│ 501 │ │ │ │ │ │ │
│ 502 │ │ │ │ │ │ │
│ 503 │ │ │ │
│ ❱ 504 │ │ │ resp = aw │
│ 505 │ │ │
│ 506 │ │ return resp │
│ 507 │
│ │
│ /usr/local/lib/python3.9/si │
│ te-packages/opsdroid/connec │
│ tor/telegram/__init__.py:22 │
│ 8 in │
│ telegram_webhook_handler │
│ │
│ 225 │ │ │ ) │
│ 226 │ │ │
│ 227 │ │ if payload.ge │
│ ❱ 228 │ │ │ event = a │
│ 229 │ │ │ │ paylo │
│ 230 │ │ │ ) │
│ 231 │
│ │
│ /usr/local/lib/python3.9/si │
│ te-packages/opsdroid/connec │
│ tor/telegram/__init__.py:30 │
│ 8 in handle_messages │
│ │
│ 305 │ │ │
│ 306 │ │ if message.ge │
│ 307 │ │ │ event = R │
│ ❱ 308 │ │ │ │ text= │
│ 309 │ │ │ │ user= │
│ 310 │ │ │ │ user_ │
│ 311 │ │ │ │ event │
╰─────────────────────────────╯
KeyError: 'text'
```
## Versions
- OpsDroid 0.26.0
- OpsDroid helm chart: opsdroid-0.1.6
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| 2022-05-14T18:50:55 |
||
opsdroid/opsdroid | 1,931 | opsdroid__opsdroid-1931 | [
"1930"
] | 8b20dd634467097e2dc75af2371e7dec4bbb8960 | diff --git a/opsdroid/connector/websocket/__init__.py b/opsdroid/connector/websocket/__init__.py
--- a/opsdroid/connector/websocket/__init__.py
+++ b/opsdroid/connector/websocket/__init__.py
@@ -9,12 +9,49 @@
from aiohttp import WSCloseCode
from opsdroid.connector import Connector, register_event
from opsdroid.events import Message
+import dataclasses
+from typing import Optional
_LOGGER = logging.getLogger(__name__)
HEADERS = {"Access-Control-Allow-Origin": "*"}
CONFIG_SCHEMA = {"bot-name": str, "max-connections": int, "connection-timeout": int}
[email protected]
+class WebsocketMessage:
+ """A message received from a websocket connection."""
+
+ message: str
+ user: Optional[str]
+ socket: Optional[str]
+
+ @classmethod
+ def parse_payload(cls, payload: str):
+ """Parse the payload of a websocket message.
+
+ We will try to parse the payload as a json string.
+ If that fails, we will use the default values which are:
+
+ message: str
+ user: None
+ socket: None
+
+ """
+ try:
+ data = json.loads(payload)
+ return cls(
+ message=data.get("message"),
+ user=data.get("user"),
+ socket=data.get("socket"),
+ )
+ except json.JSONDecodeError:
+ return cls(
+ message=payload,
+ user=None,
+ socket=None,
+ )
+
+
class ConnectorWebsocket(Connector):
"""A connector which allows websocket connections."""
@@ -29,6 +66,7 @@ def __init__(self, config, opsdroid=None):
self.active_connections = {}
self.available_connections = []
self.bot_name = self.config.get("bot-name", "opsdroid")
+ self.authorization_token = self.config.get("token")
async def connect(self):
"""Connect to the chat service."""
@@ -53,6 +91,7 @@ async def disconnect(self):
async def new_websocket_handler(self, request):
"""Handle for aiohttp creating websocket connections."""
+ await self.validate_request(request)
if (
len(self.active_connections) + len(self.available_connections)
< self.max_connections
@@ -95,7 +134,13 @@ async def websocket_handler(self, request):
self.active_connections[socket] = websocket
async for msg in websocket:
if msg.type == aiohttp.WSMsgType.TEXT:
- message = Message(text=msg.data, user=None, target=None, connector=self)
+ payload = WebsocketMessage.parse_payload(msg.data)
+ message = Message(
+ text=payload.message,
+ user=payload.user,
+ target=payload.socket,
+ connector=self,
+ )
await self.opsdroid.parse(message)
elif msg.type == aiohttp.WSMsgType.ERROR:
_LOGGER.error(
@@ -108,6 +153,20 @@ async def websocket_handler(self, request):
return websocket
+ async def validate_request(self, request):
+ """Validate the request by looking at headers and the connector token.
+
+ If the token does not exist in the header, but exists in the configuration,
+ then we will simply return a Forbidden error.
+
+ """
+ client_token = request.headers.get("Authorization")
+ if self.authorization_token and (
+ client_token is None or client_token != self.authorization_token
+ ):
+ raise aiohttp.web.HTTPUnauthorized()
+ return True
+
async def listen(self):
"""Listen for and parse new messages.
@@ -117,7 +176,7 @@ async def listen(self):
"""
@register_event(Message)
- async def send_message(self, message):
+ async def send_message(self, message: Message):
"""Respond with a message."""
try:
if message.target is None:
| diff --git a/tests/test_connector_websocket.py b/tests/test_connector_websocket.py
--- a/tests/test_connector_websocket.py
+++ b/tests/test_connector_websocket.py
@@ -1,10 +1,14 @@
import asyncio
import unittest
+import pytest
+import json
import asynctest
import asynctest.mock as amock
+from aiohttp.web import HTTPUnauthorized
+
from opsdroid.cli.start import configure_lang
-from opsdroid.connector.websocket import ConnectorWebsocket
+from opsdroid.connector.websocket import ConnectorWebsocket, WebsocketMessage
from opsdroid.core import OpsDroid
from opsdroid.events import Message
@@ -73,12 +77,14 @@ async def test_new_websocket_handler(self):
connector.max_connections = 1
self.assertEqual(len(connector.available_connections), 0)
- response = await connector.new_websocket_handler(None)
+ mocked_request = amock.Mock()
+
+ response = await connector.new_websocket_handler(mocked_request)
self.assertTrue(isinstance(response, aiohttp.web.Response))
self.assertEqual(len(connector.available_connections), 1)
self.assertEqual(response.status, 200)
- fail_response = await connector.new_websocket_handler(None)
+ fail_response = await connector.new_websocket_handler(mocked_request)
self.assertTrue(isinstance(fail_response, aiohttp.web.Response))
self.assertEqual(fail_response.status, 429)
@@ -165,3 +171,46 @@ async def test_websocket_handler(self):
self.assertEqual(type(response), aiohttp.web.Response)
self.assertEqual(response.status, 408)
self.assertFalse(connector.available_connections)
+
+
+def test_ConnectorMessage_dataclass():
+ payload = json.dumps({"message": "Hello, world!", "user": "Bob", "socket": "12345"})
+ data = WebsocketMessage.parse_payload(payload)
+
+ assert data.message == "Hello, world!"
+ assert data.user == "Bob"
+ assert data.socket == "12345"
+
+ text_message = WebsocketMessage.parse_payload("Hello, world!")
+ assert text_message.message == "Hello, world!"
+ assert text_message.user is None
+ assert text_message.socket is None
+
+
[email protected]
+async def test_validate_request():
+ config = {"token": "secret"}
+ connector = ConnectorWebsocket(config, opsdroid=OpsDroid())
+
+ request = amock.CoroutineMock()
+ request.headers = {"Authorization": "secret"}
+
+ is_valid = await connector.validate_request(request)
+ assert is_valid
+
+ request = amock.CoroutineMock()
+ request.headers = {}
+
+ with pytest.raises(HTTPUnauthorized):
+ await connector.validate_request(request)
+
+
[email protected]
+async def test_new_websocket_handler_no_token():
+ config = {"token": "secret"}
+ connector = ConnectorWebsocket(config, opsdroid=OpsDroid())
+
+ with pytest.raises(HTTPUnauthorized):
+ request = amock.CoroutineMock()
+ request.headers = {}
+ await connector.new_websocket_handler(request)
| Add token to websockets connector
Currently, anyone that knows opdroid url and endpoint will be able to request a socket to initialize a websocket connection.
Ideally, we should allow users to select a token in the configuration settings. When opsdroid gets a request, if the token doesn't exist then we just reject the request.
This will also a nice feature to implement along side opsdroid-web v2
| 2022-06-15T18:07:45 |
|
opsdroid/opsdroid | 1,934 | opsdroid__opsdroid-1934 | [
"1932"
] | a280177d40be894f9cc0006c85ec5c6d674ca2a3 | diff --git a/opsdroid/web.py b/opsdroid/web.py
--- a/opsdroid/web.py
+++ b/opsdroid/web.py
@@ -12,6 +12,7 @@
from aiohttp import web
from aiohttp.web import HTTPForbidden
from aiohttp.web_exceptions import HTTPBadRequest
+from aiohttp_middlewares.cors import cors_middleware, DEFAULT_ALLOW_HEADERS
from opsdroid import __version__
from opsdroid.const import EXCLUDED_CONFIG_KEYS
@@ -19,6 +20,23 @@
_LOGGER = logging.getLogger(__name__)
+DEFAULT_HEADERS = list(
+ DEFAULT_ALLOW_HEADERS
+ + (
+ "Host",
+ "Content-Type",
+ "Origin",
+ "Content-Length",
+ "Connection",
+ "Accept",
+ "User-Agent",
+ "Referer",
+ "Accept-Language",
+ "Accept-Encoding",
+ "Authorization",
+ )
+)
+
@dataclasses.dataclass
class Payload:
@@ -76,7 +94,16 @@ def __init__(self, opsdroid):
self.config = self.opsdroid.config["web"]
except KeyError:
self.config = {}
- self.web_app = web.Application()
+ self.cors = self.config.get("cors", {})
+ self.web_app = web.Application(
+ middlewares=[
+ cors_middleware(
+ allow_all=self.cors.get("allow-all", True),
+ origins=self.cors.get("origins", ["*"]),
+ allow_headers=DEFAULT_HEADERS + self.cors.get("allow-headers", []),
+ )
+ ]
+ )
self.runner = web.AppRunner(self.web_app)
self.site = None
self.command_center = self.config.get("command-center", {})
| Add possibility to configure CORS in routes
While testing #1930 with opsdroid-web I've realised that we aren't handling CORS at all. This means that any request that we will try to do from the app will fail since we can't include an `Authorization` header when using `no-cors` and if we use `cors` then opsdroid will reply with `OPTIONS`.
We should probably expand opsdroid web to allow users to configure cors on every route. I've been playing around with `aiohttp_cors` and seems to be pretty straightforward. For example:
```python
cors = aiohttp_cors.setup(self.web_app)
for route in self.web_app.router.routes():
cors.add(route, {
"*": aiohttp_cors.ResourceOptions(
allow_headers=("Content-Type", "Authorization"),
allow_methods="*",
allow_credentials=True,
)}
)
```
Perhaps we could allow users to override some of these settings 🤔
Let me know what you think
| Annoyingly, this doesn't seem to be as simple as that. The request goes through, but then something breaks. Will need to figure it out before deciding on this
```python
Traceback (most recent call last):
File "/opt/homebrew/lib/python3.9/site-packages/aiohttp/web_protocol.py", line 514, in start
resp, reset = await task
File "/opt/homebrew/lib/python3.9/site-packages/aiohttp/web_protocol.py", line 460, in _handle_request
reset = await self.finish_response(request, resp, start_time)
File "/opt/homebrew/lib/python3.9/site-packages/aiohttp/web_protocol.py", line 613, in finish_response
await prepare_meth(request)
File "/opt/homebrew/lib/python3.9/site-packages/aiohttp/web_response.py", line 421, in prepare
return await self._start(request)
File "/opt/homebrew/lib/python3.9/site-packages/aiohttp/web_response.py", line 764, in _start
return await super()._start(request)
File "/opt/homebrew/lib/python3.9/site-packages/aiohttp/web_response.py", line 428, in _start
await request._prepare_hook(self)
File "/opt/homebrew/lib/python3.9/site-packages/aiohttp/web_request.py", line 874, in _prepare_hook
await app.on_response_prepare.send(self, response)
File "/opt/homebrew/lib/python3.9/site-packages/aiosignal/__init__.py", line 36, in send
await receiver(*args, **kwargs) # type: ignore
File "/opt/homebrew/lib/python3.9/site-packages/aiohttp_cors/cors_config.py", line 171, in _on_response_prepare
assert hdrs.ACCESS_CONTROL_ALLOW_ORIGIN not in response.headers
``` | 2022-06-20T22:10:03 |
|
opsdroid/opsdroid | 1,963 | opsdroid__opsdroid-1963 | [
"1962"
] | 37e2c5cc24de69d1773212e2d817756db3ce540d | diff --git a/opsdroid/parsers/rasanlu.py b/opsdroid/parsers/rasanlu.py
--- a/opsdroid/parsers/rasanlu.py
+++ b/opsdroid/parsers/rasanlu.py
@@ -134,7 +134,10 @@ async def _load_model(config):
_LOGGER.error(_("Unable to connect to Rasa NLU."))
return None
if resp.status == 204:
- result = await resp.json()
+ try:
+ result = await resp.json()
+ except aiohttp.client_exceptions.ContentTypeError:
+ return {}
else:
result = await resp.text()
_LOGGER.error(_("Bad Rasa NLU response - %s."), result)
@@ -155,7 +158,7 @@ async def _is_model_loaded(config):
return None
if resp.status == 200:
result = await resp.json()
- if result["model_file"].find(config["model_filename"]):
+ if config["model_filename"] in result["model_file"]:
return True
return False
| diff --git a/tests/test_parser_rasanlu.py b/tests/test_parser_rasanlu.py
--- a/tests/test_parser_rasanlu.py
+++ b/tests/test_parser_rasanlu.py
@@ -520,12 +520,11 @@ async def test_has_compatible_version_rasanlu(self):
self.assertEqual(await rasanlu.has_compatible_version_rasanlu({}), True)
async def test__load_model(self):
- result = amock.Mock()
- result.status = 204
- result.text = amock.CoroutineMock()
- result.json = amock.CoroutineMock()
-
with amock.patch("aiohttp.ClientSession.put") as patched_request:
+ result = amock.Mock()
+ result.status = 204
+ result.text = amock.CoroutineMock()
+ result.json = amock.CoroutineMock()
patched_request.side_effect = None
result.json.return_value = {}
patched_request.return_value = asyncio.Future()
@@ -554,6 +553,24 @@ async def test__load_model(self):
await rasanlu._load_model({"model_filename": "model.tar.gz"}), None
)
+ with amock.patch("aiohttp.ClientSession.put") as patched_request:
+ result = amock.Mock()
+ result.status = 204
+ result.content = aiohttp.streams.EmptyStreamReader()
+ result.reason = "No Content"
+ result.text = amock.CoroutineMock(
+ side_effect=aiohttp.ContentTypeError(None, None)
+ )
+ result.json = amock.CoroutineMock(
+ side_effect=aiohttp.ContentTypeError(None, None)
+ )
+ patched_request.return_value = asyncio.Future()
+ patched_request.return_value.set_result(result)
+ patched_request.side_effect = None
+ self.assertEqual(
+ await rasanlu._load_model({"model_filename": "model.tar.gz"}), {}
+ )
+
async def test__is_model_loaded(self):
result = amock.Mock()
result.status = 200
| Compatibility with Rasa >= 3.0
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://app.element.io/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
When running Opsdroid agains Rasa >= 3.x the model training fails.
## Steps to Reproduce
1. Run the latest Rasa (3.3.3) on some host `docker run --rm -ti -p 5005:5005 --name rasa rasa/rasa:3.3.3-full run --enable-api --auth-token very-secure-rasa-auth-token -vv`
2. Create a skill with the provided configuration files (see configuration section)
3. Run Opsdroid with this skill
## Expected Functionality
Opsdroid will trigger Rasa to train and load the model provided in `intents.yml`.
## Experienced Functionality
The model training is triggered and the model is loaded but Opsdroid terminates with the stacktrace:
```
DEBUG opsdroid.parsers.rasanlu Checking Rasa NLU version.
DEBUG opsdroid.parsers.rasanlu Rasa NLU response - {"version": "3.3.3", "minimum_compatible_version": "3.0.0"}.
DEBUG opsdroid.parsers.rasanlu Rasa NLU version 3.3.3.
INFO opsdroid.parsers.rasanlu Starting Rasa NLU training.
INFO opsdroid.parsers.rasanlu Now training the model. This may take a while...
INFO opsdroid.parsers.rasanlu Rasa NLU training completed in 9 seconds.
DEBUG asyncio Using selector: EpollSelector
Traceback (most recent call last):
File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "/home/user/PyCharm/opsdroid_rasa_3.3.3_compatibility/opsdroid/__main__.py", line 12, in <module>
init()
File "/home/user/PyCharm/opsdroid_rasa_3.3.3_compatibility/opsdroid/__main__.py", line 9, in init
opsdroid.cli.cli()
File "/home/user/PyCharm/opsdroid_rasa_3.3.3_compatibility/venv/lib/python3.8/site-packages/click/core.py", line 1130, in __call__
return self.main(*args, **kwargs)
File "/home/user/PyCharm/opsdroid_rasa_3.3.3_compatibility/venv/lib/python3.8/site-packages/click/core.py", line 1055, in main
rv = self.invoke(ctx)
File "/home/user/PyCharm/opsdroid_rasa_3.3.3_compatibility/venv/lib/python3.8/site-packages/click/core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/user/PyCharm/opsdroid_rasa_3.3.3_compatibility/venv/lib/python3.8/site-packages/click/core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/user/PyCharm/opsdroid_rasa_3.3.3_compatibility/venv/lib/python3.8/site-packages/click/core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "/home/user/PyCharm/opsdroid_rasa_3.3.3_compatibility/opsdroid/cli/start.py", line 41, in start
opsdroid.run()
File "/home/user/PyCharm/opsdroid_rasa_3.3.3_compatibility/opsdroid/core.py", line 170, in run
self.sync_load()
File "/home/user/PyCharm/opsdroid_rasa_3.3.3_compatibility/opsdroid/core.py", line 219, in sync_load
self.eventloop.run_until_complete(self.load())
File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/home/user/PyCharm/opsdroid_rasa_3.3.3_compatibility/opsdroid/core.py", line 232, in load
await self.train_parsers(self.modules["skills"])
File "/home/user/PyCharm/opsdroid_rasa_3.3.3_compatibility/opsdroid/core.py", line 365, in train_parsers
await train_rasanlu(rasanlu, skills)
File "/home/user/PyCharm/opsdroid_rasa_3.3.3_compatibility/opsdroid/parsers/rasanlu.py", line 221, in train_rasanlu
await _load_model(config)
File "/home/user/PyCharm/opsdroid_rasa_3.3.3_compatibility/opsdroid/parsers/rasanlu.py", line 137, in _load_model
result = await resp.json()
File "/home/user/PyCharm/opsdroid_rasa_3.3.3_compatibility/venv/lib/python3.8/site-packages/aiohttp/client_reqrep.py", line 1104, in json
raise ContentTypeError(
aiohttp.client_exceptions.ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: ', url=URL('http://rasa-host:5005/model?token=very-secure-rasa-auth-token')
```
## Versions
- **Opsdroid version: 73da764ca72581a506f05117ec9690ca34b15400**
- **Python version: 3.8.5**
- **OS/Docker version: Linux Docker 20.10.6 (for Rasa)**
## Configuration File
`configuration.yaml`:
```:YAML
welcome-message: false
logging:
level: debug
connectors:
websocket:
parsers:
rasanlu:
url: http://rasa-host:5005
token: very-secure-rasa-auth-token
skills:
rasa-test:
path: /home/user/PyCharm/opsdroid_rasa_3.3.3_compatibility/rasa_test_skill
```
`__init__.py`:
```:python
from opsdroid.skill import Skill
from opsdroid.matchers import match_rasanlu
class MySkill(Skill):
@match_rasanlu('greet')
async def hello(self, message):
await message.respond("Hello there!")
@match_rasanlu('bye')
async def bye(self, message):
await message.respond("See ya!")
```
`intents.yml`:
```:YAML
version: "3.1"
intents:
- greet
- bye
nlu:
- intent: greet
examples: |
- Hey
- Hi
- hey there
- hello
- intent: bye
examples: |
- googbye
- bye
- ciao
- see you
```
| Seem that Rasa 3.X doesn't return any content (and we are expecting it) when loading a model. Just HTTP code 204.
https://rasa.com/docs/rasa/pages/http-api#operation/replaceModel | 2022-12-11T14:40:18 |
opsdroid/opsdroid | 1,964 | opsdroid__opsdroid-1964 | [
"1959"
] | 06edf0cff76ccdb4dd7eca332690c42ec608cb46 | diff --git a/opsdroid/parsers/rasanlu.py b/opsdroid/parsers/rasanlu.py
--- a/opsdroid/parsers/rasanlu.py
+++ b/opsdroid/parsers/rasanlu.py
@@ -292,15 +292,18 @@ async def parse_rasanlu(opsdroid, skills, message, config):
if matcher["rasanlu_intent"] == result["intent"]["name"]:
message.rasanlu = result
for entity in result["entities"]:
+ entity_name = entity["entity"]
+ if "role" in entity:
+ entity_name = entity["entity"] + "_" + entity["role"]
if "confidence_entity" in entity:
message.update_entity(
- entity["entity"],
+ entity_name,
entity["value"],
entity["confidence_entity"],
)
elif "extractor" in entity:
message.update_entity(
- entity["entity"],
+ entity_name,
entity["value"],
entity["extractor"],
)
| diff --git a/tests/test_parser_rasanlu.py b/tests/test_parser_rasanlu.py
--- a/tests/test_parser_rasanlu.py
+++ b/tests/test_parser_rasanlu.py
@@ -214,6 +214,74 @@ async def test_parse_rasanlu_entities(self):
skill["message"].entities["cuisine"]["value"], "chinese"
)
+ async def test_parse_rasanlu_multiple_entities_with_same_name(self):
+ with OpsDroid() as opsdroid:
+ opsdroid.config["parsers"] = [
+ {"name": "rasanlu", "token": "test", "min-score": 0.3}
+ ]
+ mock_skill = await self.getMockSkill()
+ opsdroid.skills.append(match_rasanlu("knowledge")(mock_skill))
+
+ mock_connector = amock.CoroutineMock()
+ message = Message(
+ text="i want to travel from Berlin to San Fransisco",
+ user="user",
+ target="default",
+ connector=mock_connector,
+ )
+ with amock.patch.object(rasanlu, "call_rasanlu") as mocked_call_rasanlu:
+ mocked_call_rasanlu.return_value = {
+ "text": "i want to travel from Berlin to San Fransisco",
+ "intent": {"name": "knowledge", "confidence": 0.9999788999557495},
+ "entities": [
+ {
+ "entity": "city",
+ "start": 22,
+ "end": 28,
+ "confidence_entity": 0.9633104801177979,
+ "role": "departure",
+ "confidence_role": 0.9610307812690735,
+ "value": "Berlin",
+ "extractor": "DIETClassifier",
+ },
+ {
+ "entity": "city",
+ "start": 32,
+ "end": 45,
+ "confidence_entity": 0.7566294074058533,
+ "role": "destination",
+ "confidence_role": 0.8198645114898682,
+ "value": "San Fransisco",
+ "extractor": "DIETClassifier",
+ },
+ ],
+ "text_tokens": [
+ [0, 1],
+ [2, 6],
+ [7, 9],
+ [10, 16],
+ [17, 21],
+ [22, 28],
+ [29, 31],
+ [32, 35],
+ [36, 45],
+ ],
+ }
+
+ [skill] = await rasanlu.parse_rasanlu(
+ opsdroid, opsdroid.skills, message, opsdroid.config["parsers"][0]
+ )
+
+ self.assertEqual(len(skill["message"].entities.keys()), 2)
+ self.assertTrue("city_departure" in skill["message"].entities.keys())
+ self.assertTrue("city_destination" in skill["message"].entities.keys())
+ self.assertEqual(
+ skill["message"].entities["city_departure"]["value"], "Berlin"
+ )
+ self.assertEqual(
+ skill["message"].entities["city_destination"]["value"], "San Fransisco"
+ )
+
async def test_parse_rasanlu_raises(self):
with OpsDroid() as opsdroid:
opsdroid.config["parsers"] = [
| Extracting multiple entities with same name from user message.
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://app.element.io/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
Hi, I am trying to build chatbot with opsdroid, matrix and rasanlu. When I try to extract entities from user message, if message contains multiple entities with same name we are able to extract single entity with highest confidence.
For example:
user_message: I want to travel from Berlin to San Francisco.
## Expected Functionality
Desired output: extract both entities i.e. {'Berlin' & 'San Francisco'}
The RASA NLU is able to extract all entities correctly, but opsdroid returns single entity only.
Rasa nlu response:
`{"text": "i want to travel from Berlin to San Fransisco", "intent": {"name": "knowledge", "confidence": 0.9999788999557495}, "entities": [{"entity": "city", "start": 22, "end": 28, "confidence_entity": 0.9633104801177979, "role": "departure", "confidence_role": 0.9610307812690735, "value": "Berlin", "extractor": "DIETClassifier"}, {"entity": "city", "start": 32, "end": 45, "confidence_entity": 0.7566294074058533, "role": "destination", "confidence_role": 0.8198645114898682, "value": "San Fransisco", "extractor": "DIETClassifier"}], "text_tokens": [[0, 1], [2, 6], [7, 9], [10, 16], [17, 21], [22, 28], [29, 31], [32, 35], [36, 45]] }}`
## Experienced Functionality
on `message.entities` am able extract only single value for entity city.
`{"city":{"value":"San Francisco", "confidence": 0.9977127313613892}}`
## Versions
- **Opsdroid version: v0.28.0**
- **Python version:3.9.15**
- **OS/Docker version: 20.10.21**
## Configuration File
Please include your version of the configuration file below.
```yaml
welcome-message: false
logging:
level: debug
path: false
rich: false # to get rich formated logs but does not work in the docker container
console: true #true - remove all colours and rich styles
timestamp: true # to keep or remove timestamp in the logs
extended: true # to enable/disable log location
connectors:
test-bot:
repo: $TEST_REPO_URL
homeserver: $TEST_HOMESERVER_URL
mxid: $MXID
access_token: $ACCESS_TOKEN
rooms:
main: $ROOM_MAIN
bot_name: $BOT_NAME
parsers:
regex:
enabled: true
rasanlu:
url: $RASA_URL
token: $RASA_TOKEN
min-score: 0.6
models-path: /rasa_model/path
model_filename: $RASA_MODEL_NAME
train: False
skills:
common:
path: /path/to/skills/__init__.py
```
## Additional Details
intents.yml
```
version: "3.1"
intents:
- greetings
- bye
- help
- travel
entities:
- city:
roles:
- departure
- destination
- intent: travel
examples: |
- I want to fly from [Berlin]{"entity": "city","role":"departure"} to [San Francisco]{"entity": "city","role":"destination"}
- I want to fly from [Berlin]{"entity": "city","role":"departure"} to [San Francisco]{"entity": "city","role":"destination"}
- I want to fly from [Berlin]{"entity": "city","role":"departure"} to [San Francisco]{"entity": "city","role":"destination"}
- I want to fly from [Berlin]{"entity": "city","role":"departure"} to [San Francisco]{"entity": "city","role":"destination"}
- I want to fly from [Berlin]{"entity": "city","role":"departure"} to [San Francisco]{"entity": "city","role":"destination"}
```
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| I checked the rasanlu matcher and found the issue.
That's what happening:
* The entity extraction in rasanlu matcher is happening [here](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/parsers/rasanlu.py#L293)
* which calls the [entity update function](https://github.com/opsdroid/opsdroid/blob/master/opsdroid/events.py#L171)
* which overwrites the key `city` in `message.entities`
This is common to Opsdroid in general, that`message.entities` is a dictionary. A dictionary cannot contain duplicate entries.
Any ideas how to fix this without breaking every skill depending on it? | 2022-12-12T10:04:52 |
opsdroid/opsdroid | 1,969 | opsdroid__opsdroid-1969 | [
"1968"
] | 06edf0cff76ccdb4dd7eca332690c42ec608cb46 | diff --git a/opsdroid/parsers/rasanlu.py b/opsdroid/parsers/rasanlu.py
--- a/opsdroid/parsers/rasanlu.py
+++ b/opsdroid/parsers/rasanlu.py
@@ -31,7 +31,7 @@ async def _get_all_intents(skills):
if not intents:
return None
intents = "\n\n".join(intents)
- return unicodedata.normalize("NFKD", intents).encode("ascii")
+ return unicodedata.normalize("NFKD", intents)
async def _get_intents_fingerprint(intents):
| diff --git a/tests/test_parser_rasanlu.py b/tests/test_parser_rasanlu.py
--- a/tests/test_parser_rasanlu.py
+++ b/tests/test_parser_rasanlu.py
@@ -411,8 +411,8 @@ async def test__get_all_intents(self):
skills[1] = {"intents": None}
skills[2] = {"intents": "World"}
intents = await rasanlu._get_all_intents(skills)
- self.assertEqual(type(intents), type(b""))
- self.assertEqual(intents, b"Hello\n\nWorld")
+ self.assertEqual(type(intents), type(""))
+ self.assertEqual(intents, "Hello\n\nWorld")
async def test__get_all_intents_fails(self):
skills = []
| Rasa intents multilanguage support
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://app.element.io/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
When using non-alphanumeric characters (non English language) in `intents.yml` with `rasanlu` parser Opsdroid exits with the following error:
```
DEBUG opsdroid.parsers.rasanlu Checking Rasa NLU version.
DEBUG opsdroid.parsers.rasanlu Rasa NLU response - {"version": "3.3.3", "minimum_compatible_version": "3.0.0"}.
DEBUG opsdroid.parsers.rasanlu Rasa NLU version 3.3.3.
INFO opsdroid.parsers.rasanlu Starting Rasa NLU training.
DEBUG asyncio Using selector: KqueueSelector
Traceback (most recent call last):
File "/usr/local/Cellar/[email protected]/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/local/Cellar/[email protected]/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "/Users/olegfiksel/opsdroid/opsdroid/__main__.py", line 12, in <module>
init()
File "/Users/olegfiksel/opsdroid/opsdroid/__main__.py", line 9, in init
opsdroid.cli.cli()
File "/Users/olegfiksel/opsdroid/venv/lib/python3.9/site-packages/click/core.py", line 1130, in __call__
return self.main(*args, **kwargs)
File "/Users/olegfiksel/opsdroid/venv/lib/python3.9/site-packages/click/core.py", line 1055, in main
rv = self.invoke(ctx)
File "/Users/olegfiksel/opsdroid/venv/lib/python3.9/site-packages/click/core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/olegfiksel/opsdroid/venv/lib/python3.9/site-packages/click/core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/olegfiksel/opsdroid/venv/lib/python3.9/site-packages/click/core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "/Users/olegfiksel/opsdroid/opsdroid/cli/start.py", line 41, in start
opsdroid.run()
File "/Users/olegfiksel/opsdroid/opsdroid/core.py", line 170, in run
self.sync_load()
File "/Users/olegfiksel/opsdroid/opsdroid/core.py", line 219, in sync_load
self.eventloop.run_until_complete(self.load())
File "/usr/local/Cellar/[email protected]/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
return future.result()
File "/Users/olegfiksel/opsdroid/opsdroid/core.py", line 232, in load
await self.train_parsers(self.modules["skills"])
File "/Users/olegfiksel/opsdroid/opsdroid/core.py", line 365, in train_parsers
await train_rasanlu(rasanlu, skills)
File "/Users/olegfiksel/opsdroid/opsdroid/parsers/rasanlu.py", line 174, in train_rasanlu
intents = await _get_all_intents(skills)
File "/Users/olegfiksel/opsdroid/opsdroid/parsers/rasanlu.py", line 35, in _get_all_intents
return unicodedata.normalize("NFKD", intents).encode("ascii")
UnicodeEncodeError: 'ascii' codec can't encode character '\xdf' in position 118: ordinal not in range(128)
```
## Steps to Reproduce
* Create `intents.yml` and run Opsdroid agains a Rasa instance with this configuration
## Expected Functionality
* Opsdroid would send the content of `intents.yml` to Rasa to train a model
## Experienced Functionality
* Opsdroid exits with an error before sending the content of `intents.yml` to Rasa
## Versions
- **Opsdroid version: master (d6d23f32fadf289f692f7d6a24d9a62478e921a2)**
- **Python version: 3.9.9**
- **OS/Docker version: MacOS 12.6 for Opsdroid & Docker 20.10.6 for Rasa (3.3.3)**
## Configuration File
`configuration.yml`
```yaml
welcome-message: false
logging:
level: debug
connectors:
websocket:
parsers:
rasanlu:
url: http://rasa-host:5005
token: very-secure-rasa-auth-token
skills:
rasa-test:
path: /Users/olegfiksel/opsdroid/rasa_test_skill
```
`intents.yml`
```yaml
version: "3.1"
language: "de"
intents:
- hi
- bye
nlu:
- intent: hi
examples: |
- Hallo
- Gruß
- Grüße
- intent: bye
examples: |
- tschüß
- Aufwiedersehen
- ciao
- bis später
- bis demnächst
```
`__init__.py`
```python
from opsdroid.skill import Skill
from opsdroid.matchers import match_rasanlu
class MySkill(Skill):
@match_rasanlu("hi")
async def hello(self, message):
await message.respond("Hallo!")
@match_rasanlu("bye")
async def bye(self, message):
await message.respond("Tschüß!")
```
| 2022-12-17T16:44:31 |
|
opsdroid/opsdroid | 1,971 | opsdroid__opsdroid-1971 | [
"1970"
] | 1b392dd96d9d5ba16b0cd6d7e757dd1f061a4a9b | diff --git a/opsdroid/core.py b/opsdroid/core.py
--- a/opsdroid/core.py
+++ b/opsdroid/core.py
@@ -30,7 +30,7 @@
from opsdroid.parsers.rasanlu import (
parse_rasanlu,
train_rasanlu,
- has_compatible_version_rasanlu,
+ rasa_usable,
)
from opsdroid.parsers.regex import parse_regex
from opsdroid.parsers.sapcai import parse_sapcai
@@ -357,11 +357,11 @@ async def train_parsers(self, skills):
parsers = self.modules.get("parsers", {})
rasanlu = get_parser_config("rasanlu", parsers)
if rasanlu and rasanlu["enabled"]:
- rasa_version_is_compatible = await has_compatible_version_rasanlu(
- rasanlu
- )
- if rasa_version_is_compatible is False:
- self.critical("Rasa version is not compatible", 5)
+ if await rasa_usable(rasanlu) is False:
+ self.critical(
+ "Cannot connect to Rasa or the Rasa version is not compatible.",
+ 5,
+ )
await train_rasanlu(rasanlu, skills)
async def setup_connectors(self, connectors):
diff --git a/opsdroid/parsers/rasanlu.py b/opsdroid/parsers/rasanlu.py
--- a/opsdroid/parsers/rasanlu.py
+++ b/opsdroid/parsers/rasanlu.py
@@ -94,10 +94,12 @@ async def _get_rasa_nlu_version(config):
return result
-async def has_compatible_version_rasanlu(config):
- """Check if Rasa NLU is compatible with the API we implement"""
+async def rasa_usable(config):
+ """Check if can connect to Rasa NLU and the version is compatible with the API we implement"""
_LOGGER.debug(_("Checking Rasa NLU version."))
json_object = await _get_rasa_nlu_version(config)
+ if json_object is None:
+ return False
version = json_object["version"]
minimum_compatible_version = json_object["minimum_compatible_version"]
# Make sure we don't run against a 1.x.x Rasa NLU because it has a different API
| diff --git a/tests/test_parser_rasanlu.py b/tests/test_parser_rasanlu.py
--- a/tests/test_parser_rasanlu.py
+++ b/tests/test_parser_rasanlu.py
@@ -499,25 +499,28 @@ async def test__get_rasa_nlu_version(self):
await rasanlu._get_rasa_nlu_version({}), result.text.return_value
)
- async def test_has_compatible_version_rasanlu(self):
+ async def test_rasa_usable(self):
with amock.patch.object(rasanlu, "_get_rasa_nlu_version") as mock_crc:
mock_crc.return_value = {
"version": "1.0.0",
"minimum_compatible_version": "1.0.0",
}
- self.assertEqual(await rasanlu.has_compatible_version_rasanlu({}), False)
+ self.assertEqual(await rasanlu.rasa_usable({}), False)
mock_crc.return_value = {
"version": "2.6.2",
"minimum_compatible_version": "2.6.0",
}
- self.assertEqual(await rasanlu.has_compatible_version_rasanlu({}), True)
+ self.assertEqual(await rasanlu.rasa_usable({}), True)
mock_crc.return_value = {
"version": "3.1.2",
"minimum_compatible_version": "3.0.0",
}
- self.assertEqual(await rasanlu.has_compatible_version_rasanlu({}), True)
+ self.assertEqual(await rasanlu.rasa_usable({}), True)
+
+ mock_crc.return_value = None
+ self.assertEqual(await rasanlu.rasa_usable({}), False)
async def test__load_model(self):
with amock.patch("aiohttp.ClientSession.put") as patched_request:
@@ -629,7 +632,7 @@ async def test_train_rasanlu_fails(self):
) as mock_btu, amock.patch.object(
rasanlu, "_get_intents_fingerprint"
) as mock_gif, amock.patch.object(
- rasanlu, "has_compatible_version_rasanlu"
+ rasanlu, "rasa_usable"
) as mock_crc, amock.patch.object(
rasanlu, "_load_model"
) as mock_lmo, amock.patch.object(
@@ -703,7 +706,7 @@ async def test_train_rasanlu_succeeded(self):
) as mock_btu, amock.patch.object(
rasanlu, "_get_intents_fingerprint"
) as mock_gif, amock.patch.object(
- rasanlu, "has_compatible_version_rasanlu"
+ rasanlu, "rasa_usable"
) as mock_crc, amock.patch.object(
rasanlu, "_load_model"
) as mock_lmo, amock.patch.object(
| Opsdroid exits with a weird error when Rasa is not reachable
# Description
When using Opsdroid with Rasa (`rasanlu` parser) and Rasa is not reachable, then Opsdroid exits with an exception, which doesn't describe directly the cause of the error.
Also described here: https://github.com/opsdroid/opsdroid/pull/1785#pullrequestreview-701831106
## Steps to Reproduce
* Make sure Opsdroid cannot connect to Rasa (shut it down or use non-existent hostname)
* Run Opsdroid with a sample skill and `intents.yml` for Rasa
## Expected Functionality
* Opsdroid exits with a non-zero error code and a appropriate error message stating, what caused the error.
## Experienced Functionality
Opsdroid exits with a stack trace:
```
...
DEBUG opsdroid.core Loaded 1 skills.
DEBUG opsdroid.connector.websocket Starting Websocket connector.
DEBUG opsdroid.parsers.rasanlu Checking Rasa NLU version.
ERROR opsdroid.parsers.rasanlu Unable to connect to Rasa NLU.
DEBUG asyncio Using selector: KqueueSelector
Traceback (most recent call last):
File "/usr/local/Cellar/[email protected]/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/local/Cellar/[email protected]/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "/Users/olegfiksel/opsdroid/opsdroid/__main__.py", line 12, in <module>
init()
File "/Users/olegfiksel/opsdroid/opsdroid/__main__.py", line 9, in init
opsdroid.cli.cli()
File "/Users/olegfiksel/opsdroid/venv/lib/python3.9/site-packages/click/core.py", line 1130, in __call__
return self.main(*args, **kwargs)
File "/Users/olegfiksel/opsdroid/venv/lib/python3.9/site-packages/click/core.py", line 1055, in main
rv = self.invoke(ctx)
File "/Users/olegfiksel/opsdroid/venv/lib/python3.9/site-packages/click/core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/olegfiksel/opsdroid/venv/lib/python3.9/site-packages/click/core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/olegfiksel/opsdroid/venv/lib/python3.9/site-packages/click/core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "/Users/olegfiksel/opsdroid/opsdroid/cli/start.py", line 41, in start
opsdroid.run()
File "/Users/olegfiksel/opsdroid/opsdroid/core.py", line 170, in run
self.sync_load()
File "/Users/olegfiksel/opsdroid/opsdroid/core.py", line 219, in sync_load
self.eventloop.run_until_complete(self.load())
File "/usr/local/Cellar/[email protected]/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
return future.result()
File "/Users/olegfiksel/opsdroid/opsdroid/core.py", line 232, in load
await self.train_parsers(self.modules["skills"])
File "/Users/olegfiksel/opsdroid/opsdroid/core.py", line 360, in train_parsers
rasa_version_is_compatible = await has_compatible_version_rasanlu(
File "/Users/olegfiksel/opsdroid/opsdroid/parsers/rasanlu.py", line 103, in has_compatible_version_rasanlu
version = json_object["version"]
TypeError: 'NoneType' object is not subscriptable
```
## Versions
- **Opsdroid version: master (1b392dd96d9d5ba16b0cd6d7e757dd1f061a4a9b)**
- **Python version: 3.9.9**
- **OS/Docker version: MacOS 12.6**
## Configuration File
```yaml
welcome-message: false
logging:
level: debug
connectors:
websocket:
parsers:
rasanlu:
url: http://non-existent-host:5005
token: very-secure-rasa-auth-token
skills:
rasa-test:
path: /Users/olegfiksel/opsdroid/rasa_test_skill
```
Skill file and `intents.yml` are irrelevant because Opsdroid doesn't get to this point.
| 2022-12-17T17:54:48 |
|
opsdroid/opsdroid | 1,985 | opsdroid__opsdroid-1985 | [
"1737"
] | 2a823256b812ad986d29f32385253ddee0c2c0b6 | diff --git a/opsdroid/connector/slack/connector.py b/opsdroid/connector/slack/connector.py
--- a/opsdroid/connector/slack/connector.py
+++ b/opsdroid/connector/slack/connector.py
@@ -444,7 +444,8 @@ async def replace_usernames(self, message):
for userid in userids:
user_info = await self.lookup_username(userid)
message = message.replace(
- "<@{userid}>".format(userid=userid), user_info["name"]
+ "<@{userid}>".format(userid=userid),
+ "@{username}".format(username=user_info["name"]),
)
return message
| diff --git a/opsdroid/connector/slack/tests/test_connector.py b/opsdroid/connector/slack/tests/test_connector.py
--- a/opsdroid/connector/slack/tests/test_connector.py
+++ b/opsdroid/connector/slack/tests/test_connector.py
@@ -295,7 +295,7 @@ async def test_replace_usernames(connector):
connector.known_users = {"U01NK1K9L68": {"name": "Test User"}}
message = "hello <@U01NK1K9L68>"
replaced_message = await connector.replace_usernames(message)
- assert replaced_message == "hello Test User"
+ assert replaced_message == "hello @Test User"
@pytest.mark.anyio
| Match @mention regex
Hi,
This is a general question, and I couldn't find any information in the documentation.
I would like the bot to capture a user/team mention in slack - "@devopsteam" for example.
The channel user mention a group (which is not the bot), and I would like to capture the message and create a ticket based on that. I tried to do a @match_regex(r"@devopsteam"), and It does not work as expected.
Appreciate your comments
| Hello, @omers thank you for raising this issue, could I ask you what you get from the logs if you set this as debug? From your example things should work, I am keen on knowing if we need to escape the `@` although I don't think that's the case 🤔
If you don't have the time, I'll try to test things and debug the issue tomorrow 👍
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
Turns out I have the same issue here.
What I have noticed if I extend the regular expression to match the mention is that this is logged (our bot's name in this case is `@guido`):
```
2023-02-24 17:19:26,436 DEBUG slack_sdk.socket_mode.aiohttp A new message enqueued (current queue size: 1, session: s_8783087079229)
23
2023-02-24 17:19:26,436 DEBUG slack_sdk.socket_mode.aiohttp Message processing started (type: events_api, envelope_id: 99a20b47-8dda-4fc4-a819-cdedd2801019, session: s_8783087079229)
22
2023-02-24 17:19:26,436 DEBUG slack_sdk.socket_mode.aiohttp Sending a message: {"envelope_id": "99a20b47-8dda-4fc4-a819-cdedd2801019"} from session: s_8783087079229
21
2023-02-24 17:19:26,436 DEBUG opsdroid.connector.slack.create_events Replacing userids in message with usernames
20
2023-02-24 17:19:26,436 DEBUG opsdroid.connector.slack.connector Got slack event: <opsdroid.events.Message(text=guido my message is here)>
19
2023-02-24 17:19:26,436 DEBUG opsdroid.core Parsing input: <opsdroid.events.Message(text=guido my message is here)>.
18
2023-02-24 17:19:26,437 DEBUG opsdroid.core Processing parsers...
17
2023-02-24 17:19:26,437 INFO root my_skill: message <opsdroid.events.Message(text=guido my message is here)>
```
I wrote in a slack channel: `@guido my message is here` and what I get back as a result of the invocation of my skill method as `message` attribute is `guido my message is here`, so the `@` character is stripped away.
I'm not sure why this is the behaviour, but this is what I'm seeing. There seems to be no way to distinguish the `@guido do something` from `guido do something`. The version of opsdroid we're using based on the helm chart is v0.25.0.
Perhaps this patch could retain the `@` characters for usernames before replacing them:
```
diff --git a/opsdroid/connector/slack/connector.py b/opsdroid/connector/slack/connector.py
index c35adf3..93fbfb0 100644
--- a/opsdroid/connector/slack/connector.py
+++ b/opsdroid/connector/slack/connector.py
@@ -431,31 +431,32 @@ class ConnectorSlack(Connector):
self.known_users[userid] = user_info
return user_info
elif "bot" in response.data:
bot_info = response.data["bot"]
if isinstance(bot_info, dict):
self.known_bots[userid] = bot_info
return bot_info
async def replace_usernames(self, message):
"""Replace User ID with username in message text."""
userids = re.findall(r"\<\@([A-Z0-9]+)(?:\|.+)?\>", message)
for userid in userids:
user_info = await self.lookup_username(userid)
message = message.replace(
- "<@{userid}>".format(userid=userid), user_info["name"]
+ "<@{userid}>".format(userid=userid),
+ "@{username}".format(username=user_info["name"])
)
return message
@register_event(opsdroid.events.Message)
async def _send_message(self, message):
"""Respond with a message."""
_LOGGER.debug(
_("Responding with: '%s' in room %s."), message.text, message.target
)
data = self._generate_base_data(message)
data["text"] = message.text
return await self.slack_web_client.api_call(
```
| 2023-02-24T17:50:00 |
opsdroid/opsdroid | 1,998 | opsdroid__opsdroid-1998 | [
"1784",
"1784"
] | 3fff308450e4b74b4cad31920b8c629d02107a72 | diff --git a/opsdroid/connector/matrix/connector.py b/opsdroid/connector/matrix/connector.py
--- a/opsdroid/connector/matrix/connector.py
+++ b/opsdroid/connector/matrix/connector.py
@@ -514,7 +514,10 @@ async def _file_to_mxc_url(self, file_event):
mimetype = await file_event.get_mimetype()
response = await self.connection.upload(
- lambda x, y: upload_file, content_type=mimetype, encrypt=encrypt_file
+ lambda x, y: upload_file,
+ content_type=mimetype,
+ encrypt=encrypt_file,
+ filesize=len(upload_file),
)
response, file_dict = response
| opdroid error when try send an pdf in matrix
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://app.element.io/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
Please include a summary of the issue.
Try to send an pdf file with opsdroid in matrix
Use code from https://github.com/Tyagdit/opsdroid-demo-skill
My code is
@match_regex(r'acord', case_sensitive=False)
async def send_file(self, message):
with open("/home/mike/documente/acord.pdf", "rb") as send_file:
#pdfReader=PyPDF2.PdfFileReader(send_file)
send_file = send_file.read()
send_event = File(name="file", file_bytes=send_file, mimetype="application/x-pdf")
#send_event = File(name="pic", url="https://docs.opsdroid.dev/en/stable/_static/logo.png", mimetype="image/png")
await message.respond(send_event)
## Steps to Reproduce
Please also include relevant information and steps to reproduce the bug/issue.
when type acord
obtain this error in opsdroid
ERROR opsdroid.connector.matrix.connector: Error while sending the file. Reason: Request must specify a Content-Length (status code M_UNKNOWN)
## Expected Functionality
Explain what should happen.
## Experienced Functionality
Explain what happened instead(Please include the debug log).
## Versions
- **Opsdroid version:** latest
- **Python version:** 3.9
- **OS/Docker version:**
## Configuration File
Please include your version of the configuration file below.
```yaml
# Your code goes here.
```
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
opdroid error when try send an pdf in matrix
<!-- Before you post an issue or if you are unsure about something join our matrix channel https://app.element.io/#/room/#opsdroid-general:matrix.org and ask away! We are more than happy to help you. -->
# Description
Please include a summary of the issue.
Try to send an pdf file with opsdroid in matrix
Use code from https://github.com/Tyagdit/opsdroid-demo-skill
My code is
@match_regex(r'acord', case_sensitive=False)
async def send_file(self, message):
with open("/home/mike/documente/acord.pdf", "rb") as send_file:
#pdfReader=PyPDF2.PdfFileReader(send_file)
send_file = send_file.read()
send_event = File(name="file", file_bytes=send_file, mimetype="application/x-pdf")
#send_event = File(name="pic", url="https://docs.opsdroid.dev/en/stable/_static/logo.png", mimetype="image/png")
await message.respond(send_event)
## Steps to Reproduce
Please also include relevant information and steps to reproduce the bug/issue.
when type acord
obtain this error in opsdroid
ERROR opsdroid.connector.matrix.connector: Error while sending the file. Reason: Request must specify a Content-Length (status code M_UNKNOWN)
## Expected Functionality
Explain what should happen.
## Experienced Functionality
Explain what happened instead(Please include the debug log).
## Versions
- **Opsdroid version:** latest
- **Python version:** 3.9
- **OS/Docker version:**
## Configuration File
Please include your version of the configuration file below.
```yaml
# Your code goes here.
```
## Additional Details
Any other details you wish to include such as screenshots, console messages, etc.
<!-- Love opsdroid? Please consider supporting our collective:
+👉 https://opencollective.com/opsdroid/donate -->
| Well ok that's weird. I am kinda surprised this hasn't been an issue before. What homeserver are you using?
Synapse with postgres
This is config for opsdroid
```
## Matrix (core)
matrix:
# # Required
mxid: "@robot:matrix.somedomain"
password: "somepassword"
# # A dictionary of multiple rooms
# # One of these should be named 'main'
rooms:
'main': "#ocpisv:matrix.somedomain"
# 'other': '#element-web:matrix.org'
# # Optional
homeserver: "https://matrix.somedomain"
nick: "Robot" # The nick will be set on startup
enable_encryption: True
# room_specific_nicks: True # Look up room specific nicknames of senders (expensive in large rooms)
device_name: "opsdroid"
device_id: "opsdroid" # A unique string to use as an ID for a persistent opsdroid device
# store_path: "path/to/store/" # Path to the directory where the matrix store will be saved
#
```
Do you happen to know if your synapse is using the built in media store, or if it's using a third party media store?
Also can you send images ok?
don't try with png, but at jpg is same error. (mimetype images/jpg)
I will try tomorow with an png and update this
Do you happen to know if your synapse is using the built in media store, or if it's using a third party media store?
this is from homeserver
media_store_path: "/var/lib/matrix-synapse/media"
with matrix there is no pb to send an receive files
limitation at 10MB(if count)
file is 4MB dimension (but jpg have same KB)
Same error with png
I think I see a issue
at opsdroid -configuration.yaml
i see this line
# store_path: "path/to/store/" # Path to the directory where the matrix store will be saved
In matrix, I have default location for saving files, but matrix, and opsdroid aren't running on same machine, so opsdroid never can't reach matrix storelocation.
They are different `store_paths`, the opsdroid store path stores a database of cryptographic keys when end to end encryption is enabled. This is presumably because of a recent change to synapse.
Well ok that's weird. I am kinda surprised this hasn't been an issue before. What homeserver are you using?
Synapse with postgres
This is config for opsdroid
```
## Matrix (core)
matrix:
# # Required
mxid: "@robot:matrix.somedomain"
password: "somepassword"
# # A dictionary of multiple rooms
# # One of these should be named 'main'
rooms:
'main': "#ocpisv:matrix.somedomain"
# 'other': '#element-web:matrix.org'
# # Optional
homeserver: "https://matrix.somedomain"
nick: "Robot" # The nick will be set on startup
enable_encryption: True
# room_specific_nicks: True # Look up room specific nicknames of senders (expensive in large rooms)
device_name: "opsdroid"
device_id: "opsdroid" # A unique string to use as an ID for a persistent opsdroid device
# store_path: "path/to/store/" # Path to the directory where the matrix store will be saved
#
```
Do you happen to know if your synapse is using the built in media store, or if it's using a third party media store?
Also can you send images ok?
don't try with png, but at jpg is same error. (mimetype images/jpg)
I will try tomorow with an png and update this
Do you happen to know if your synapse is using the built in media store, or if it's using a third party media store?
this is from homeserver
media_store_path: "/var/lib/matrix-synapse/media"
with matrix there is no pb to send an receive files
limitation at 10MB(if count)
file is 4MB dimension (but jpg have same KB)
Same error with png
I think I see a issue
at opsdroid -configuration.yaml
i see this line
# store_path: "path/to/store/" # Path to the directory where the matrix store will be saved
In matrix, I have default location for saving files, but matrix, and opsdroid aren't running on same machine, so opsdroid never can't reach matrix storelocation.
They are different `store_paths`, the opsdroid store path stores a database of cryptographic keys when end to end encryption is enabled. This is presumably because of a recent change to synapse. | 2023-06-16T13:54:34 |
|
google/etils | 159 | google__etils-159 | [
"143"
] | a72cedc0b8b53d48301f3f1ee70831b43ac090a0 | diff --git a/etils/edc/dataclass_utils.py b/etils/edc/dataclass_utils.py
--- a/etils/edc/dataclass_utils.py
+++ b/etils/edc/dataclass_utils.py
@@ -18,6 +18,7 @@
import dataclasses
import functools
+import inspect
import reprlib
import typing
from typing import Any, Callable, TypeVar
@@ -196,7 +197,8 @@ def has_default_repr(cls: _Cls) -> bool:
# Use `cls.__dict__` and not `hasattr` to ignore parent classes
'__repr__' not in cls.__dict__
# `__repr__` exists but is the default dataclass implementation
- or cls.__repr__.__qualname__ == '__create_fn__.<locals>.__repr__'
+ or inspect.unwrap(cls.__repr__).__qualname__
+ == '__create_fn__.<locals>.__repr__'
)
diff --git a/etils/epath/gpath.py b/etils/epath/gpath.py
--- a/etils/epath/gpath.py
+++ b/etils/epath/gpath.py
@@ -133,6 +133,7 @@ def expanduser(self: _P) -> _P:
def resolve(self: _P, strict: bool = False) -> _P:
"""Returns the abolute path."""
+ # TODO(epot): In pathlib, `resolve` also resolve the symlinks
return self._new(self._PATH.abspath(self._path_str))
def glob(self: _P, pattern: str) -> Iterator[_P]:
diff --git a/etils/epath/resource_utils.py b/etils/epath/resource_utils.py
--- a/etils/epath/resource_utils.py
+++ b/etils/epath/resource_utils.py
@@ -17,8 +17,8 @@
from __future__ import annotations
import itertools
-import os
import pathlib
+import posixpath
import sys
import types
import typing
@@ -26,7 +26,6 @@
from etils.epath import abstract_path
from etils.epath import register
-from etils.epath.typing import PathLike
# pylint: disable=g-import-not-at-top
if sys.version_info >= (3, 9): # `importlib.resources.files` was added in 3.9
@@ -64,19 +63,31 @@ def __fspath__(self) -> str:
"""
raise NotImplementedError('zipapp not supported. Please send us a PR.')
+ # zipfile.Path do not define `__eq__` nor `__hash__`. See:
+ # https://discuss.python.org/t/missing-zipfile-path-eq-and-zipfile-path-hash/16519
+ def __eq__(self, other) -> bool:
+ # pyformat:disable
+ return (
+ type(self) == type(other) # pylint: disable=unidiomatic-typecheck
+ and self.root == other.root # pytype: disable=attribute-error
+ and self.at == other.at # pytype: disable=attribute-error
+ )
+ # pyformat:enable
+
+ def __hash__(self) -> int:
+ return hash((self.root, self.at)) # pytype: disable=attribute-error
+
if sys.version_info < (3, 10):
# Required due to: https://bugs.python.org/issue42043
def _next(self, at) -> 'ResourcePath':
- return type(self)(self.root, at) # pytype: disable=attribute-error # py39-upgrade
+ return type(self)(self.root, at) # pytype: disable=attribute-error
# Before 3.10, joinpath only accept a single arg
- def joinpath(self, *parts: PathLike) -> 'ResourcePath':
+ def joinpath(self, *other):
"""Overwrite `joinpath` to be consistent with `pathlib.Path`."""
- if not parts:
- return self
- else:
- return super().joinpath(os.path.join(*parts)) # pylint: disable=no-value-for-parameter # pytype: disable=bad-return-type # py39-upgrade
+ next_ = posixpath.join(self.at, *other) # pytype: disable=attribute-error
+ return self._next(self.root.resolve_dir(next_)) # pytype: disable=attribute-error
def resource_path(package: Union[str, types.ModuleType]) -> abstract_path.Path:
| diff --git a/etils/epath/resource_utils_test.py b/etils/epath/resource_utils_test.py
--- a/etils/epath/resource_utils_test.py
+++ b/etils/epath/resource_utils_test.py
@@ -50,6 +50,8 @@ def _make_zip_file() -> zipfile.ZipFile:
def test_resource_path():
path = epath.resource_utils.ResourcePath(_make_zip_file())
assert isinstance(path, os.PathLike)
+ assert path.joinpath('b/c.txt') == path / 'b' / 'c.txt'
+ assert hash(path.joinpath('b/c.txt')) == hash(path / 'b' / 'c.txt')
assert path.joinpath('b/c.txt').read_text() == 'content of c'
sub_dirs = list(path.joinpath('b').iterdir())
assert len(sub_dirs) == 3
| Tests fail on Python 3.10
There are two test failures with Python 3.10. With Python 3.9 everything seems fine. Could you have a look?
```
================================================================================== FAILURES ==================================================================================
_________________________________________________________________________________ test_repr __________________________________________________________________________________
def test_repr():
> assert repr(R(123, R11(y='abc'))) == epy.dedent("""
R(
x=123,
y=R11(
x=None,
y='abc',
z=None,
),
)
""")
E assert "R(x=123, y=R...bc', z=None))" == 'R(\n x=12...e,\n ),\n)'
E + R(x=123, y=R11(x=None, y='abc', z=None))
E - R(
E - x=123,
E - y=R11(
E - x=None,
E - y='abc',
E - z=None,...
E
E ...Full output truncated (3 lines hidden), use '-vv' to show
etils/edc/dataclass_utils_test.py:108: AssertionError
_____________________________________________________________________________ test_resource_path _____________________________________________________________________________
def test_resource_path():
path = epath.resource_utils.ResourcePath(_make_zip_file())
assert isinstance(path, os.PathLike)
assert path.joinpath('b/c.txt').read_text() == 'content of c'
sub_dirs = list(path.joinpath('b').iterdir())
assert len(sub_dirs) == 3
for p in sub_dirs: # Childs should be `ResourcePath` instances
assert isinstance(p, epath.resource_utils.ResourcePath)
# Forwarded to `Path` keep the resource.
path = epath.Path(path)
assert isinstance(path, epath.resource_utils.ResourcePath)
> assert path.joinpath() == path
E AssertionError: assert ResourcePath('alpharep.zip', '') == ResourcePath('alpharep.zip', '')
E + where ResourcePath('alpharep.zip', '') = <bound method Path.joinpath of ResourcePath('alpharep.zip', '')>()
E + where <bound method Path.joinpath of ResourcePath('alpharep.zip', '')> = ResourcePath('alpharep.zip', '').joinpath
```
For `test_repr`, apparently custom `__repr__` is not applied as [`__qualname__`](https://github.com/google/etils/blob/3b7bc11f103bf62d3f9e8f48ede035a292a51ff0/etils/edc/dataclass_utils.py#L199) is changed in Python 3.10.
For `test_resource_path`, `joinpath()` returns a new object for Python >= 3.10 as that function is [not overridden](https://github.com/google/etils/blob/3b7bc11f103bf62d3f9e8f48ede035a292a51ff0/etils/epath/resource_utils.py#L74).
I noticed those failures when I'm creating a unofficial package python-etils for Arch Linux as a new dependency for the latest [python-tensorflow-datasets](https://aur.archlinux.org/packages/python-tensorflow-datasets).
Environment: Arch Linux x86_64, Python 3.10.4
| Thank you for reporting and finding those bugs. Your info are very helpful.
Don't hesitate to send a PR. Otherwise I'll have a look this week
Thanks for the suggestion! I didn't send a PR yet as I'm not sure how to fix the issues. The `__qualname__` issue involves Python internals and I may not be able to find a good fix soon. The joinpath issue is more like an incorrect test - apparently `zipfile.Path.joinpath()` still creates a new object when paths to join are empty. I'm not sure if epath should match the behavior of zipfile.Path or not.
Thanks for the answer. I fixed those issues in https://github.com/google/etils/pull/159.
For the `zipfile`, it looks like the issue is that `__eq__` and `__hash__` are missing from `zipfile.Path`. Opened an issue in python: https://discuss.python.org/t/missing-zipfile-path-eq-and-zipfile-path-hash/16519
Thanks, that works!
> it looks like the issue is that `__eq__` and `__hash__` are missing from zipfile.Path
Yeah, that sounds reasonable. I found a more ambitious attempt https://github.com/python/cpython/pull/31085: "It could also be used to make zipfile.Path objects fully pathlib-compatible (no missing methods!)" | 2022-06-14T12:46:29 |
google/etils | 525 | google__etils-525 | [
"520"
] | e244ac07f1e8f5afcf358c8477c0aa0eadf69b85 | diff --git a/etils/epath/abstract_path.py b/etils/epath/abstract_path.py
--- a/etils/epath/abstract_path.py
+++ b/etils/epath/abstract_path.py
@@ -19,7 +19,7 @@
import os
import pathlib
import typing
-from typing import Any, AnyStr, Iterator, Optional, Type, TypeVar
+from typing import Any, AnyStr, Iterator, Optional, Type, TypeVar, Callable
from etils.epath import register
from etils.epath import stat_utils
@@ -112,6 +112,15 @@ def rglob(self: _T, pattern: str) -> Iterator[_T]:
"""Yields all matching files recursively (of any kind)."""
return self.glob(f'**/{pattern}')
+ @abstractmethod
+ def walk(
+ self: _T,
+ top_down: bool = True,
+ on_error: Callable[[OSError], object] | None = None,
+ follow_symlinks: bool = False,
+ ) -> Iterator[tuple[_T, list[str], list[str]]]:
+ raise NotImplementedError
+
def expanduser(self: _T) -> _T:
"""Returns a new path with expanded `~` and `~user` constructs."""
if '~' not in self.parts: # pytype: disable=attribute-error
@@ -218,4 +227,5 @@ def replace(self: _T, target: PathLike) -> _T:
@abstractmethod
def copy(self: _T, dst: PathLike, overwrite: bool = False) -> _T:
"""Copy the current file to the given destination."""
+
# pytype: enable=bad-return-type
diff --git a/etils/epath/backend.py b/etils/epath/backend.py
--- a/etils/epath/backend.py
+++ b/etils/epath/backend.py
@@ -24,8 +24,7 @@
import shutil
import stat as stat_lib
import typing
-from typing import Iterator, NoReturn, Optional, Union
-
+from typing import Iterator, NoReturn, Optional, Union, Callable
from etils.epath import stat_utils
from etils.epath.typing import PathLike # pylint: disable=g-importing-member
@@ -105,6 +104,16 @@ def copy(self, path: PathLike, dst: PathLike, overwrite: bool) -> None:
def stat(self, path: PathLike) -> stat_utils.StatResult:
raise NotImplementedError
+ @abc.abstractmethod
+ def walk(
+ self,
+ top: PathLike,
+ top_down: bool = True,
+ on_error: Callable[[OSError], object] | None = None,
+ follow_symlinks: bool = False,
+ ) -> Iterator[tuple[PathLike, list[str], list[str]]]:
+ raise NotImplementedError
+
class _OsPathBackend(Backend):
"""`os.path` backend."""
@@ -218,6 +227,23 @@ def stat(self, path: PathLike) -> stat_utils.StatResult:
mode=st.st_mode,
)
+ def walk(
+ self,
+ top: PathLike,
+ top_down: bool = True,
+ on_error: Callable[[OSError], object] | None = None,
+ follow_symlinks: bool = False,
+ ) -> Iterator[tuple[PathLike, list[str], list[str]]]:
+ for path, dirnames, filenames in os.walk(
+ top, topdown=top_down, onerror=on_error, followlinks=follow_symlinks
+ ):
+ # Unlike os.walk(), Path.walk() lists symlinks to directories in filenames if follow_symlinks is false
+ if follow_symlinks is False:
+ symlinks = {dirname for dirname in dirnames if os.path.islink(os.path.join(path, dirname))}
+ dirnames[:] = list(dirname for dirname in dirnames if dirname not in symlinks) # we need to keep the reference to the original dirnames object
+ filenames.extend(symlinks)
+ yield path, dirnames, filenames
+
class _TfBackend(Backend):
"""TensorFlow backend."""
@@ -381,6 +407,17 @@ def stat(self, path: PathLike) -> stat_utils.StatResult:
mode=None,
)
+ def walk(
+ self,
+ top: PathLike,
+ top_down: bool = True,
+ on_error: Callable[[OSError], object] | None = None,
+ follow_symlinks: bool = False,
+ ) -> Iterator[tuple[PathLike, list[str], list[str]]]:
+ yield from self.gfile.walk(
+ top, topdown=top_down, onerror=on_error
+ )
+
class _FileSystemSpecBackend(Backend):
"""FileSystemSpec backend entirely relying on fsspec."""
@@ -538,7 +575,21 @@ def stat(self, path: PathLike) -> stat_utils.StatResult:
mtime=mtime,
owner=info.get('owner'),
group=info.get('group'),
- mode=info.get('mode')
+ mode=info.get('mode'),
+ )
+
+ def walk(
+ self,
+ top: PathLike,
+ top_down: bool = True,
+ on_error: Callable[[OSError], object] | None = None,
+ follow_symlinks: bool = False,
+ ) -> Iterator[tuple[PathLike, list[str], list[str]]]:
+
+ if on_error is None:
+ on_error = 'omit' # default behavior for pathlib.Path.walk
+ yield from self.fs(top).walk(
+ path=top, topdown=top_down, on_error=on_error, max_depth=None
)
diff --git a/etils/epath/gpath.py b/etils/epath/gpath.py
--- a/etils/epath/gpath.py
+++ b/etils/epath/gpath.py
@@ -24,7 +24,7 @@
import posixpath
import types
import typing
-from typing import Any, ClassVar, Iterator, Optional, Type, TypeVar, Union
+from typing import Any, ClassVar, Iterator, Optional, Type, TypeVar, Union, Callable, Iterable
from etils import epy
from etils.epath import abstract_path
@@ -270,6 +270,20 @@ def stat(self) -> stat_utils.StatResult:
"""Returns metadata for the file/directory."""
return self._backend.stat(self._path_str)
+ def walk(
+ self: _P,
+ top_down: bool = True,
+ on_error: Callable[[OSError], object] | None = None,
+ follow_symlinks: bool = False,
+ ) -> Iterator[tuple[_P, list[str], list[str]]]:
+ for root, dirs, files in self._backend.walk(
+ top=self._path_str,
+ top_down=top_down,
+ on_error=on_error,
+ follow_symlinks=follow_symlinks,
+ ):
+ yield self._new(root), dirs, files
+
def _get_backend(p0: _GPath, p1: _GPath) -> backend_lib.Backend:
"""When composing with another backend, GCS win.
| diff --git a/etils/epath/backend_test.py b/etils/epath/backend_test.py
--- a/etils/epath/backend_test.py
+++ b/etils/epath/backend_test.py
@@ -150,6 +150,47 @@ def _test_glob(
]
+def _test_walk(backend: epath.backend.Backend, tmp_path):
+ nested = (tmp_path / 'abc/nested/')
+ nested.mkdir(parents=True)
+ other_nested = (tmp_path / 'abc/other_nested/')
+ other_nested.mkdir(parents=True)
+ (nested / '001').touch()
+ (nested / '002').touch()
+ (nested / '003').touch()
+ linked_dir = (tmp_path / 'abc/link_dir')
+ linked_dir.symlink_to(nested)
+
+ bottom_up_walk = list(backend.walk(tmp_path, top_down=False, follow_symlinks=False))
+
+
+ assert bottom_up_walk == [
+ (str(other_nested), [], []),
+ (str(nested), [], ['003', '002', '001']),
+ (str(tmp_path / 'abc'), [ 'other_nested', 'nested'], ['link_dir']),
+ (str(tmp_path), ['abc'], [])
+ ]
+
+ top_down_walk = list(backend.walk(tmp_path, top_down=True, follow_symlinks=False))
+
+ assert top_down_walk == [
+ (str(tmp_path), ['abc'], []),
+ (str(tmp_path / 'abc'), [ 'other_nested', 'nested'], ['link_dir']),
+ (str(other_nested), [], []),
+ (str(nested), [], ['003', '002', '001']),
+ ]
+
+ if isinstance(backend, epath.backend._OsPathBackend):
+ follow_symlinks_walk = list(backend.walk(tmp_path, follow_symlinks=True))
+ assert follow_symlinks_walk == [
+ (str(tmp_path), ['abc'], []),
+ (str(tmp_path / 'abc'), ['link_dir', 'other_nested', 'nested'], []),
+ (str(linked_dir), [], ['003', '002', '001']),
+ (str(other_nested), [], []),
+ (str(nested), [], ['003', '002', '001']),
+ ]
+
+
def _test_listdir(
backend: epath.backend.Backend,
tmp_path: pathlib.Path,
@@ -513,6 +554,7 @@ def _test_stat(
_test_copy,
_test_copy_with_overwrite,
_test_stat,
+ _test_walk,
],
)
def test_backend(
diff --git a/etils/epath/gpath_test.py b/etils/epath/gpath_test.py
--- a/etils/epath/gpath_test.py
+++ b/etils/epath/gpath_test.py
@@ -69,6 +69,7 @@ def new_fn(_, p, **kwargs):
mkdir=_call(backend.mkdir),
remove=_call(backend.remove),
rmtree=_call(backend.rmtree),
+ walk=_call(backend.walk),
# Mock _is_tf_installed in order not to default to tf_backend:
), mock.patch.object(epath.gpath, '_is_tf_installed', return_value=False):
yield tmp_path
@@ -398,6 +399,22 @@ def test_rglob():
with pytest.raises(NotImplementedError, match='Recursive'):
list(epath.Path('/tmp/nonexisting/test').glob('folder/**/img.jpg'))
+def test_walk(gcs_mocked_path: pathlib.Path):
+ root_path = epath.Path(gcs_mocked_path)
+ result = list((root_path / '/nonexisting/test').walk())
+ assert len(result) == 0
+
+ subdir = (root_path / 'subdir')
+ subdir.mkdir()
+ (root_path / '001').touch()
+ (root_path / '002').touch()
+ (root_path / '003').touch()
+
+ result = list(root_path.walk(top_down=True, follow_symlinks=False))
+ assert result == [
+ (root_path, ['subdir'], ['003', '002', '001']),
+ (subdir, [], [])
+ ]
def test_default():
path = epath.Path()
diff --git a/etils/epath/testing.py b/etils/epath/testing.py
--- a/etils/epath/testing.py
+++ b/etils/epath/testing.py
@@ -123,6 +123,7 @@ def mock_epath(
replace: Optional[_MockFn] = None,
rmtree: Optional[_MockFn] = None,
stat: Optional[_MockFn] = None,
+ walk: Optional[_MockFn] = None,
) -> Iterator[None]:
"""Mock epath.
@@ -163,7 +164,7 @@ def mock_epath(
replace=replace,
rmtree=rmtree,
stat=stat,
- # 'walk',
+ walk = walk,
)
mock_backend = _MockBackend(mock_fns=mock_fns)
| Support walk in epath?
hi there!
is there a plan to support `walk` in epath for different backends? i can contribute if this feels like a good idea.
| Hi, yes, this sounds like a good addition for parity with `pathlib`. Feel free to send a PR, happy to review :) | 2023-12-26T15:12:40 |
pyodide/pyodide | 55 | pyodide__pyodide-55 | [
"28",
"28"
] | d562ed97441ad19775178e400a90aa2845a7922c | diff --git a/tools/buildpkg.py b/tools/buildpkg.py
--- a/tools/buildpkg.py
+++ b/tools/buildpkg.py
@@ -144,7 +144,8 @@ def package_files(buildpath, srcpath, pkg, args):
'--js-output={}'.format(os.path.join(buildpath, name + '.js')),
'--export-name=pyodide',
'--exclude', '*.wasm.pre',
- '--exclude', '__pycache__'], check=True)
+ '--exclude', '__pycache__',
+ '--use-preload-plugins'], check=True)
subprocess.run([
'uglifyjs',
os.path.join(buildpath, name + '.js'),
| Make work on Chrome
Make work on Chrome
| Reopening. While this now works for the MAIN_MODULE, it's failing for SIDE_MODULES still, with no obvious resolution yet.
Reopening. While this now works for the MAIN_MODULE, it's failing for SIDE_MODULES still, with no obvious resolution yet. | 2018-06-20T13:29:50 |
|
pyodide/pyodide | 74 | pyodide__pyodide-74 | [
"39"
] | b5e9630f0d2df55efcec7e8807f3f05518ed3791 | diff --git a/src/pyodide.py b/src/pyodide.py
--- a/src/pyodide.py
+++ b/src/pyodide.py
@@ -4,6 +4,7 @@
from js import XMLHttpRequest
+import ast
import io
@@ -17,4 +18,23 @@ def open_url(url):
return io.StringIO(req.response)
-__all__ = ['open_url']
+def eval_code(code, ns):
+ """
+ Runs a string of code, the last part of which may be an expression.
+ """
+ mod = ast.parse(code)
+ if isinstance(mod.body[-1], ast.Expr):
+ expr = ast.Expression(mod.body[-1].value)
+ del mod.body[-1]
+ else:
+ expr = None
+
+ if len(mod.body):
+ exec(compile(mod, '<exec>', mode='exec'), ns, ns)
+ if expr is not None:
+ return eval(compile(expr, '<eval>', mode='eval'), ns, ns)
+ else:
+ return None
+
+
+__all__ = ['open_url', 'eval_code']
| Improve parsing of result line
The parsing of the input Python to find the last line which will be evaluated (rather than executed) to provide the result is probably a little brittle in certain corner cases. We should look at what IPython does here and copy that.
| 2018-07-17T17:55:44 |
||
pyodide/pyodide | 77 | pyodide__pyodide-77 | [
"71"
] | d4660f1a1fd171b16c07672bb489a52db01ffc30 | diff --git a/tools/buildpkg.py b/tools/buildpkg.py
--- a/tools/buildpkg.py
+++ b/tools/buildpkg.py
@@ -79,25 +79,6 @@ def patch(path, srcpath, pkg, args):
fd.write(b'\n')
-def get_libdir(srcpath, args):
- # Get the name of the build/lib.XXX directory that distutils wrote its
- # output to
- slug = subprocess.check_output([
- str(Path(args.host) / 'bin' / 'python3'),
- '-c',
- 'import sysconfig, sys; '
- 'print("{}-{}.{}".format('
- 'sysconfig.get_platform(), '
- 'sys.version_info[0], '
- 'sys.version_info[1]))']).decode('ascii').strip()
- purelib = srcpath / 'build' / 'lib'
- if purelib.is_dir():
- libdir = purelib
- else:
- libdir = srcpath / 'build' / ('lib.' + slug)
- return libdir
-
-
def compile(path, srcpath, pkg, args):
if (srcpath / '.built').is_file():
return
@@ -121,10 +102,11 @@ def compile(path, srcpath, pkg, args):
post = pkg.get('build', {}).get('post')
if post is not None:
- libdir = get_libdir(srcpath, args)
+ site_packages_dir = (
+ srcpath / 'install' / 'lib' / 'python3.7' / 'site-packages')
pkgdir = path.parent.resolve()
env = {
- 'BUILD': libdir,
+ 'SITEPACKAGES': site_packages_dir,
'PKGDIR': pkgdir
}
subprocess.run([
diff --git a/tools/common.py b/tools/common.py
--- a/tools/common.py
+++ b/tools/common.py
@@ -2,8 +2,8 @@
ROOTDIR = Path(__file__).parent.resolve()
-HOSTPYTHON = ROOTDIR / '..' / 'cpython' / 'build' / '3.6.4' / 'host'
-TARGETPYTHON = ROOTDIR / '..' / 'cpython' / 'installs' / 'python-3.6.4'
+HOSTPYTHON = ROOTDIR / '..' / 'cpython' / 'build' / '3.7.0' / 'host'
+TARGETPYTHON = ROOTDIR / '..' / 'cpython' / 'installs' / 'python-3.7.0'
DEFAULTCFLAGS = ''
DEFAULTLDFLAGS = ' '.join([
'-O3',
| diff --git a/cpython/patches/testing.patch b/cpython/patches/testing.patch
--- a/cpython/patches/testing.patch
+++ b/cpython/patches/testing.patch
@@ -1,5 +1,5 @@
diff --git a/Lib/platform.py b/Lib/platform.py
-index cc2db9870d..ac4e3c538f 100755
+index 20f9817f4f..bcf96874c0 100755
--- a/Lib/platform.py
+++ b/Lib/platform.py
@@ -748,7 +748,7 @@ def _syscmd_uname(option, default=''):
@@ -21,18 +21,18 @@ index cc2db9870d..ac4e3c538f 100755
return default
target = _follow_symlinks(target)
diff --git a/Lib/test/support/script_helper.py b/Lib/test/support/script_helper.py
-index ca5f9c20dd..97934039ee 100644
+index 64b25aab80..7cf67fd149 100644
--- a/Lib/test/support/script_helper.py
+++ b/Lib/test/support/script_helper.py
-@@ -11,6 +11,7 @@ import subprocess
+@@ -9,6 +9,7 @@ import os.path
+ import subprocess
import py_compile
- import contextlib
- import shutil
-+import unittest
import zipfile
++import unittest
from importlib.util import source_from_cache
-@@ -37,6 +38,8 @@ def interpreter_requires_environment():
+ from test.support import make_legacy_pyc, strip_python_stderr
+@@ -34,6 +35,8 @@ def interpreter_requires_environment():
situation. PYTHONPATH or PYTHONUSERSITE are other common environment
variables that might impact whether or not the interpreter can start.
"""
@@ -40,16 +40,16 @@ index ca5f9c20dd..97934039ee 100644
+
global __cached_interp_requires_environment
if __cached_interp_requires_environment is None:
- # Try running an interpreter with -E to see if it works or not.
-@@ -165,6 +168,8 @@ def spawn_python(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw):
+ # If PYTHONHOME is set, assume that we need it
+@@ -172,6 +175,8 @@ def spawn_python(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw):
kw is extra keyword args to pass to subprocess.Popen. Returns a Popen
object.
"""
+ raise unittest.SkipTest("no subprocess")
+
- cmd_line = [sys.executable, '-E']
- cmd_line.extend(args)
- # Under Fedora (?), GNU readline can output junk on stderr when initialized,
+ cmd_line = [sys.executable]
+ if not interpreter_requires_environment():
+ cmd_line.append('-E')
diff --git a/Lib/test/test_code.py b/Lib/test/test_code.py
index 55faf4c427..b2201c09e7 100644
--- a/Lib/test/test_code.py
@@ -67,7 +67,7 @@ index 55faf4c427..b2201c09e7 100644
import weakref
try:
diff --git a/Lib/test/test_import/__init__.py b/Lib/test/test_import/__init__.py
-index b73a96f757..0d1c411f9a 100644
+index 1fc4de11e1..e6c91707ae 100644
--- a/Lib/test/test_import/__init__.py
+++ b/Lib/test/test_import/__init__.py
@@ -10,7 +10,10 @@ import py_compile
diff --git a/test/make_test_list.py b/test/make_test_list.py
--- a/test/make_test_list.py
+++ b/test/make_test_list.py
@@ -7,7 +7,7 @@
TEST_DIR = (Path(__file__).parent
- / "cpython/build/3.6.4/host/lib/python3.6/test")
+ / "cpython/build/3.6.4/host/lib/python3.7/test")
def collect_tests(base_dir):
diff --git a/test/python_tests.txt b/test/python_tests.txt
--- a/test/python_tests.txt
+++ b/test/python_tests.txt
@@ -4,8 +4,10 @@
# Following reason codes are skipped:
# - platform-specific: This is testing something about a particular platform
# that isn't relevant here
+# - async: relies on async
# - audioop: Requires the audioop module
# - floating point: Failures caused by floating-point differences
+# - threading: Failures due to lack of a threading implementation
# - subprocess: Failures caused by no subprocess module. Some of these are
# because the underlying functionality depends on subprocess, and others are
# just a side-effect of the way the test is written. The latter should
@@ -17,7 +19,8 @@
# - strftime: Failures due to differences / shortcomings in WebAssembly's
# implementation of date/time formatting in strftime and strptime
# - permissions: Issues with the test writing to the virtual filesystem
-# - locale: Fails due to include locale implementation.
+# - locale: Fails due to limitations in the included locale implementation.
+# - multiprocessing: Fails due to no multiprocessing implementation.
# - nonsense: This functionality doesn't make sense in this context. Includes
# things like `pip`, `distutils`
#
@@ -28,7 +31,7 @@
# - crash-chrome: Same as crash but only affecting Chrome
# - crash-firefox: Same as crash but only affecting Firefox
-test___all__
+test___all__ multiprocessing
test___future__
test__locale locale
test__opcode
@@ -40,30 +43,31 @@ test_argparse
test_array
test_asdl_parser
test_ast
-test_asyncgen
-test_asynchat
-test_asyncio.test_base_events
-test_asyncio.test_events
-test_asyncio.test_futures
-test_asyncio.test_locks
-test_asyncio.test_pep492
-test_asyncio.test_proactor_events
-test_asyncio.test_queues
-test_asyncio.test_selector_events
-test_asyncio.test_sslproto
-test_asyncio.test_streams
-test_asyncio.test_subprocess
-test_asyncio.test_tasks
-test_asyncio.test_transports
-test_asyncio.test_unix_events
-test_asyncio.test_windows_events
-test_asyncio.test_windows_utils
-test_asyncore bad ioctl syscall
+test_asyncgen async
+test_asynchat async
+test_asyncio.test_base_events async
+test_asyncio.test_events async
+test_asyncio.test_futures async
+test_asyncio.test_locks async
+test_asyncio.test_pep492 async
+test_asyncio.test_proactor_events async
+test_asyncio.test_queues async
+test_asyncio.test_selector_events async
+test_asyncio.test_sslproto async
+test_asyncio.test_streams async
+test_asyncio.test_subprocess async
+test_asyncio.test_tasks async
+test_asyncio.test_transports async
+test_asyncio.test_unix_events async
+test_asyncio.test_windows_events async
+test_asyncio.test_windows_utils async
+test_asyncore bad ioctl syscall async
test_atexit
test_audioop audioop
test_augassign
test_base64
test_baseexception
+test_bdb
test_bigaddrspace
test_bigmem
test_binascii
@@ -76,6 +80,7 @@ test_bufio
test_builtin floating point
test_bytes
test_bz2
+test_c_locale_coercion
test_calendar
test_call
test_capi
@@ -112,16 +117,19 @@ test_complex
test_concurrent_futures
test_configparser
test_contains
+test_context
test_contextlib
+test_contextlib_async async
test_copy
test_copyreg dbm
-test_coroutines
+test_coroutines async
test_cprofile _lsprof
test_crashers
test_crypt
test_csv
test_ctypes
test_curses
+test_dataclasses
test_datetime strftime
test_dbm permissions
test_dbm_dumb permissions
@@ -143,7 +151,7 @@ test_dis
test_distutils crash
test_doctest subprocess
test_doctest2
-test_docxmlrpc
+test_docxmlrpc socket
test_dtrace platform
test_dummy_thread
test_dummy_threading
@@ -155,7 +163,7 @@ test_email.test__header_value_parser
test_email.test_asian_codecs
test_email.test_contentmanager
test_email.test_defect_handling
-test_email.test_email
+test_email.test_email threading
test_email.test_generator
test_email.test_headerregistry
test_email.test_inversion
@@ -164,8 +172,9 @@ test_email.test_parser
test_email.test_pickleable
test_email.test_policy
test_email.test_utils
+test_embed
test_ensurepip nonsense
-test_enum
+test_enum threading
test_enumerate
test_eof
test_epoll crash
@@ -185,14 +194,15 @@ test_finalization
test_float floating point
test_flufl
test_fnmatch
-test_fork1
+test_fork1 threading
test_format
test_fractions
test_frame
+test_frozen
test_fstring
-test_ftplib
+test_ftplib syscall 21537
test_funcattrs
-test_functools
+test_functools threading
test_future
test_future3
test_future4
@@ -201,6 +211,7 @@ test_gc
test_gdb
test_generator_stop
test_generators
+test_genericclass
test_genericpath permissions
test_genexps
test_getargs2
@@ -213,7 +224,7 @@ test_grammar
test_grp
test_gzip
test_hash
-test_hashlib
+test_hashlib threading
test_heapq
test_hmac
test_html
@@ -221,9 +232,9 @@ test_htmlparser
test_http_cookiejar
test_http_cookies
test_httplib socket
-test_httpservers
+test_httpservers threading
test_idle
-test_imaplib
+test_imaplib socket
test_imghdr
test_imp crash
test_importlib.builtin.test_finder
@@ -244,15 +255,19 @@ test_importlib.import_.test_packages
test_importlib.import_.test_path
test_importlib.import_.test_relative_imports
test_importlib.source.test_case_sensitivity
-test_importlib.source.test_file_loader
+test_importlib.source.test_file_loader unittest has no attribute mock
test_importlib.source.test_finder
test_importlib.source.test_path_hook
test_importlib.source.test_source_encoding
test_importlib.test_abc
test_importlib.test_api
test_importlib.test_lazy
-test_importlib.test_locks
+test_importlib.test_locks threading
test_importlib.test_namespace_pkgs
+test_importlib.test_open
+test_importlib.test_path
+test_importlib.test_read
+test_importlib.test_resource
test_importlib.test_spec
test_importlib.test_util
test_importlib.test_windows platform-specific
@@ -298,7 +313,6 @@ test_long
test_longexp
test_lzma
test_macpath platform-specific
-test_macurl2path
test_mailbox crash
test_mailcap nonsense
test_marshal
@@ -338,14 +352,14 @@ test_peepholer
test_pickle dbm
test_pickletools dbm
test_pipes platform-specific
-test_pkg
+test_pkg unknown
test_pkgimport
test_pkgutil
test_platform subprocess
test_plistlib
test_poll subprocess
test_popen subprocess
-test_poplib
+test_poplib bad ioctl syscall 21537
test_posix crash
test_posixpath crash
test_pow
@@ -361,10 +375,10 @@ test_py_compile
test_pyclbr
test_pydoc crash
test_pyexpat
-test_queue
+test_queue threading
test_quopri subprocess
test_raise
-test_random
+test_random subprocess
test_range
test_re locale
test_readline
@@ -374,10 +388,10 @@ test_reprlib
test_resource
test_richcmp
test_rlcompleter crash
-test_robotparser
+test_robotparser socket
test_runpy
test_sax
-test_sched
+test_sched threading
test_scope
test_script_helper
test_secrets
@@ -392,7 +406,7 @@ test_signal
test_site subprocess
test_slice
test_smtpd
-test_smtplib
+test_smtplib baad ioctl syscall 21537
test_smtpnet
test_sndhdr audioop
test_socket
@@ -425,20 +439,20 @@ test_symtable
test_syntax
test_sys subprocess
test_sys_setprofile
-test_sys_settrace
+test_sys_settrace async
test_sysconfig nonsense
test_syslog
test_tarfile crash
test_tcl
-test_telnetlib
+test_telnetlib bad ioctl syscall 21537
test_tempfile crash
test_textwrap
-test_thread
-test_threaded_import
-test_threadedtempfile
-test_threading
-test_threading_local
-test_threadsignals
+test_thread threading
+test_threaded_import floating point
+test_threadedtempfile threading
+test_threading threading
+test_threading_local threading
+test_threadsignals threading
test_time
test_timeit
test_timeout
@@ -477,7 +491,7 @@ test_unpack
test_unpack_ex
test_urllib crash
test_urllib2 subprocess
-test_urllib2_localnet
+test_urllib2_localnet socket
test_urllib2net
test_urllib_response
test_urllibnet
@@ -485,14 +499,15 @@ test_urlparse
test_userdict
test_userlist
test_userstring
+test_utf8_mode
test_utf8source
test_uu
test_uuid subprocess
test_venv crash
-test_wait3
-test_wait4
+test_wait3 threading
+test_wait4 threading
test_wave crash
-test_weakref
+test_weakref threading
test_weakset
test_webbrowser replaced
test_winconsoleio
@@ -506,6 +521,7 @@ test_xml_etree
test_xml_etree_c
test_xmlrpc networking
test_xmlrpc_net
+test_xxtestfuzz
test_yield_from
test_zipapp
test_zipfile
diff --git a/test/test_common.py b/test/test_common.py
--- a/test/test_common.py
+++ b/test/test_common.py
@@ -43,4 +43,7 @@ def test_import(name, selenium_standalone):
for import_name in meta.get('test', {}).get('imports', []):
selenium_standalone.load_package(name)
- selenium_standalone.run('import %s' % import_name)
+ try:
+ selenium_standalone.run('import %s' % import_name)
+ except Exception as e:
+ print(selenium_standalone.logs)
diff --git a/test/test_pandas.py b/test/test_pandas.py
--- a/test/test_pandas.py
+++ b/test/test_pandas.py
@@ -6,7 +6,7 @@ def test_pandas(selenium, request):
request.applymarker(pytest.mark.xfail(
run=False, reason='chrome not supported'))
selenium.load_package("pandas")
- assert len(selenium.run("import pandas\ndir(pandas)")) == 179
+ assert len(selenium.run("import pandas\ndir(pandas)")) == 140
def test_extra_import(selenium, request):
diff --git a/test/test_python.py b/test/test_python.py
--- a/test/test_python.py
+++ b/test/test_python.py
@@ -297,9 +297,15 @@ def test_run_core_python_test(python_test, selenium, request):
try:
selenium.run(
"from test.libregrtest import main\n"
- "main(['{}'], verbose=True, verbose3=True)".format(name))
+ "try:\n"
+ " main(['{}'], verbose=True, verbose3=True)\n"
+ "except SystemExit as e:\n"
+ " if e.code != 0:\n"
+ " raise RuntimeError(f'Failed with code: {{e.code}}')\n"
+ .format(name))
except selenium.JavascriptException as e:
- assert 'SystemExit: 0' in str(e)
+ print(selenium.logs)
+ raise
def pytest_generate_tests(metafunc):
@@ -326,18 +332,6 @@ def pytest_generate_tests(metafunc):
ids=test_modules_ids)
-def test_recursive_repr(selenium):
- assert not selenium.run(
- "d = {}\n"
- "d[42] = d.values()\n"
- "result = True\n"
- "try:\n"
- " repr(d)\n"
- "except RecursionError:\n"
- " result = False\n"
- "result")
-
-
def test_load_package_after_convert_string(selenium):
"""
See #93.
| Update to Python 3.7
Python 3.7 is out.
| What I have to do on this Issue. This is first time I will work on issue.
The basic steps would be to update the `Makefile` in `cpython/Makefile` to download and build Python 3.7 instead of 3.6. If we're lucky, the patches in `cpython/patches` will still apply cleanly against Python 3.7. If not, they will need to be updated, and any new compiler errors will need to be resolved with new patches. Experience with building C libraries from source would be helpful here.
It would quiet bigger task for beginner. | 2018-07-18T17:29:12 |
pyodide/pyodide | 101 | pyodide__pyodide-101 | [
"100"
] | ef8da067be942220e493be105d99bafd8430fa4d | diff --git a/benchmark/benchmark.py b/benchmark/benchmark.py
--- a/benchmark/benchmark.py
+++ b/benchmark/benchmark.py
@@ -1,11 +1,12 @@
import json
-import os
+from pathlib import Path
import re
import subprocess
import sys
-sys.path.insert(0, os.path.abspath(
- os.path.join(os.path.dirname(__file__), '..', 'test')))
+sys.path.insert(
+ 0, str((Path(__file__).resolve().parents[1] / 'test')))
+
import conftest
@@ -14,11 +15,12 @@
def run_native(hostpython, code):
output = subprocess.check_output(
- [os.path.abspath(hostpython), '-c', code],
- cwd=os.path.dirname(__file__),
+ [hostpython.resolve(), '-c', code],
+ cwd=Path(__file__).resolve().parent,
env={
'PYTHONPATH':
- os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'src'))}
+ str(Path(__file__).resolve().parents[1] / 'src')
+ }
)
return float(output.strip().split()[-1])
@@ -72,12 +74,12 @@ def parse_numpy_benchmark(filename):
def get_numpy_benchmarks():
- root = '../numpy-benchmarks/benchmarks'
- for filename in os.listdir(root):
- name = os.path.splitext(filename)[0]
+ root = Path('../numpy-benchmarks/benchmarks')
+ for filename in root.iterdir():
+ name = filename.name
if name in SKIP:
continue
- content = parse_numpy_benchmark(os.path.join(root, filename))
+ content = parse_numpy_benchmark(filename)
content += (
"import numpy as np\n"
"_ = np.empty(())\n"
@@ -103,6 +105,6 @@ def main(hostpython):
if __name__ == '__main__':
- results = main(sys.argv[-2])
+ results = main(Path(sys.argv[-2]).resolve())
with open(sys.argv[-1], 'w') as fp:
json.dump(results, fp)
diff --git a/tools/buildpkg.py b/tools/buildpkg.py
--- a/tools/buildpkg.py
+++ b/tools/buildpkg.py
@@ -7,6 +7,7 @@
import argparse
import hashlib
import os
+from pathlib import Path
import shutil
import subprocess
@@ -14,7 +15,7 @@
import common
-ROOTDIR = os.path.abspath(os.path.dirname(__file__))
+ROOTDIR = Path(__file__).parent.resolve()
def check_checksum(path, pkg):
@@ -37,40 +38,39 @@ def check_checksum(path, pkg):
def download_and_extract(buildpath, packagedir, pkg, args):
- tarballpath = os.path.join(
- buildpath, os.path.basename(pkg['source']['url']))
- if not os.path.isfile(tarballpath):
+ tarballpath = buildpath / Path(pkg['source']['url']).name
+ if not tarballpath.is_file():
subprocess.run([
- 'wget', '-q', '-O', tarballpath, pkg['source']['url']
+ 'wget', '-q', '-O', str(tarballpath), pkg['source']['url']
], check=True)
check_checksum(tarballpath, pkg)
- srcpath = os.path.join(buildpath, packagedir)
- if not os.path.isdir(srcpath):
- shutil.unpack_archive(tarballpath, buildpath)
+ srcpath = buildpath / packagedir
+ if not srcpath.is_dir():
+ shutil.unpack_archive(str(tarballpath), str(buildpath))
return srcpath
def patch(path, srcpath, pkg, args):
- if os.path.isfile(os.path.join(srcpath, '.patched')):
+ if (srcpath / '.patched').is_file():
return
# Apply all of the patches
- orig_dir = os.getcwd()
- pkgdir = os.path.abspath(os.path.dirname(path))
+ orig_dir = Path.cwd()
+ pkgdir = path.parent.resolve()
os.chdir(srcpath)
try:
for patch in pkg['source'].get('patches', []):
subprocess.run([
- 'patch', '-p1', '--binary', '-i', os.path.join(pkgdir, patch)
+ 'patch', '-p1', '--binary', '-i', pkgdir / patch
], check=True)
finally:
os.chdir(orig_dir)
# Add any extra files
for src, dst in pkg['source'].get('extras', []):
- shutil.copyfile(os.path.join(pkgdir, src), os.path.join(srcpath, dst))
+ shutil.copyfile(pkgdir / src, srcpath / dst)
- with open(os.path.join(srcpath, '.patched'), 'wb') as fd:
+ with open(srcpath / '.patched', 'wb') as fd:
fd.write(b'\n')
@@ -78,31 +78,31 @@ def get_libdir(srcpath, args):
# Get the name of the build/lib.XXX directory that distutils wrote its
# output to
slug = subprocess.check_output([
- os.path.join(args.host, 'bin', 'python3'),
+ str(Path(args.host) / 'bin' / 'python3'),
'-c',
'import sysconfig, sys; '
'print("{}-{}.{}".format('
'sysconfig.get_platform(), '
'sys.version_info[0], '
'sys.version_info[1]))']).decode('ascii').strip()
- purelib = os.path.join(srcpath, 'build', 'lib')
- if os.path.isdir(purelib):
+ purelib = srcpath / 'build' / 'lib'
+ if purelib.is_dir():
libdir = purelib
else:
- libdir = os.path.join(srcpath, 'build', 'lib.' + slug)
+ libdir = srcpath / 'build' / ('lib.' + slug)
return libdir
def compile(path, srcpath, pkg, args):
- if os.path.isfile(os.path.join(srcpath, '.built')):
+ if (srcpath / '.built').is_file():
return
- orig_dir = os.getcwd()
+ orig_dir = Path.cwd()
os.chdir(srcpath)
try:
subprocess.run([
- os.path.join(args.host, 'bin', 'python3'),
- os.path.join(ROOTDIR, 'pywasmcross'),
+ str(Path(args.host) / 'bin' / 'python3'),
+ str(ROOTDIR / 'pywasmcross'),
'--cflags',
args.cflags + ' ' +
pkg.get('build', {}).get('cflags', ''),
@@ -117,7 +117,7 @@ def compile(path, srcpath, pkg, args):
post = pkg.get('build', {}).get('post')
if post is not None:
libdir = get_libdir(srcpath, args)
- pkgdir = os.path.abspath(os.path.dirname(path))
+ pkgdir = path.parent.resolve()
env = {
'BUILD': libdir,
'PKGDIR': pkgdir
@@ -125,46 +125,46 @@ def compile(path, srcpath, pkg, args):
subprocess.run([
'bash', '-c', post], env=env, check=True)
- with open(os.path.join(srcpath, '.built'), 'wb') as fd:
+ with open(srcpath / '.built', 'wb') as fd:
fd.write(b'\n')
def package_files(buildpath, srcpath, pkg, args):
- if os.path.isfile(os.path.join(buildpath, '.packaged')):
+ if (buildpath / '.pacakaged').is_file():
return
name = pkg['package']['name']
libdir = get_libdir(srcpath, args)
subprocess.run([
'python2',
- os.path.join(os.environ['EMSCRIPTEN'], 'tools', 'file_packager.py'),
- os.path.join(buildpath, name + '.data'),
+ Path(os.environ['EMSCRIPTEN']) / 'tools' / 'file_packager.py',
+ buildpath / (name + '.data'),
'--preload',
'{}@/lib/python3.6/site-packages'.format(libdir),
- '--js-output={}'.format(os.path.join(buildpath, name + '.js')),
+ '--js-output={}'.format(buildpath / (name + '.js')),
'--export-name=pyodide',
'--exclude', '*.wasm.pre',
'--exclude', '__pycache__',
'--use-preload-plugins'], check=True)
subprocess.run([
'uglifyjs',
- os.path.join(buildpath, name + '.js'),
+ buildpath / (name + '.js'),
'-o',
- os.path.join(buildpath, name + '.js')], check=True)
+ buildpath / (name + '.js')], check=True)
- with open(os.path.join(buildpath, '.packaged'), 'wb') as fd:
+ with open(buildpath / '.packaged', 'wb') as fd:
fd.write(b'\n')
def build_package(path, args):
pkg = common.parse_package(path)
packagedir = pkg['package']['name'] + '-' + pkg['package']['version']
- dirpath = os.path.dirname(path)
- orig_path = os.getcwd()
+ dirpath = path.parent
+ orig_path = Path.cwd()
os.chdir(dirpath)
try:
- buildpath = os.path.join(dirpath, 'build')
- if not os.path.exists(buildpath):
+ buildpath = dirpath / 'build'
+ if not buildpath.is_dir():
os.makedirs(buildpath)
srcpath = download_and_extract(buildpath, packagedir, pkg, args)
patch(path, srcpath, pkg, args)
@@ -195,7 +195,7 @@ def parse_args():
def main(args):
- path = os.path.abspath(args.package[0])
+ path = Path(args.package[0]).resolve()
build_package(path, args)
diff --git a/tools/common.py b/tools/common.py
--- a/tools/common.py
+++ b/tools/common.py
@@ -1,11 +1,9 @@
-import os
+from pathlib import Path
-ROOTDIR = os.path.abspath(os.path.dirname(__file__))
-HOSTPYTHON = os.path.abspath(
- os.path.join(ROOTDIR, '..', 'cpython', 'build', '3.6.4', 'host'))
-TARGETPYTHON = os.path.abspath(
- os.path.join(ROOTDIR, '..', 'cpython', 'installs', 'python-3.6.4'))
+ROOTDIR = Path(__file__).parent.resolve()
+HOSTPYTHON = ROOTDIR / '..' / 'cpython' / 'build' / '3.6.4' / 'host'
+TARGETPYTHON = ROOTDIR / '..' / 'cpython' / 'installs' / 'python-3.6.4'
DEFAULTCFLAGS = ''
DEFAULTLDFLAGS = ' '.join([
'-O3',
| diff --git a/test/make_test_list.py b/test/make_test_list.py
--- a/test/make_test_list.py
+++ b/test/make_test_list.py
@@ -3,21 +3,24 @@
"""
import os
+from pathlib import Path
tests = []
-TEST_DIR = "../cpython/build/3.6.4/host/lib/python3.6/test"
+TEST_DIR = Path("../cpython/build/3.6.4/host/lib/python3.6/test")
+
for root, dirs, files in os.walk(
"../cpython/build/3.6.4/host/lib/python3.6/test"):
- root = os.path.relpath(root, TEST_DIR)
+ root = Path(root).relative_to(TEST_DIR)
if root == '.':
root = ''
else:
root = '.'.join(root.split('/')) + '.'
for filename in files:
- if filename.startswith("test_") and filename.endswith(".py"):
- tests.append(root + os.path.splitext(filename)[0])
+ filename = Path(filename)
+ if str(filename).startswith("test_") and filename.suffix == ".py":
+ tests.append(str(root / filename.stem))
tests.sort()
with open("python_tests.txt", "w") as fp:
diff --git a/test/test_python.py b/test/test_python.py
--- a/test/test_python.py
+++ b/test/test_python.py
@@ -1,5 +1,5 @@
import os
-import pathlib
+from pathlib import Path
import time
@@ -295,8 +295,7 @@ def pytest_generate_tests(metafunc):
test_modules = []
if 'CIRCLECI' not in os.environ or True:
with open(
- str(pathlib.Path(__file__).parents[0] /
- "python_tests.txt")) as fp:
+ Path(__file__).parent / "python_tests.txt") as fp:
for line in fp:
line = line.strip()
if line.startswith('#'):
| It's 2018, let's use `pathlib`
`pathlib` is cool. Should update the tools to use it.
| 2018-08-03T16:48:48 |
|
pyodide/pyodide | 123 | pyodide__pyodide-123 | [
"122"
] | ae15fa88c0fe5ad93e8819f9d048b2b2064c98b8 | diff --git a/tools/buildpkg.py b/tools/buildpkg.py
--- a/tools/buildpkg.py
+++ b/tools/buildpkg.py
@@ -143,14 +143,15 @@ def package_files(buildpath, srcpath, pkg, args):
subprocess.run([
'python',
Path(os.environ['EMSCRIPTEN']) / 'tools' / 'file_packager.py',
- buildpath / (name + '.data'),
+ name + '.data',
'--preload',
'{}@/lib/python3.6/site-packages'.format(libdir),
- '--js-output={}'.format(buildpath / (name + '.js')),
+ '--js-output={}'.format(name + '.js'),
'--export-name=pyodide',
'--exclude', '*.wasm.pre',
'--exclude', '__pycache__',
- '--use-preload-plugins'], check=True)
+ '--use-preload-plugins'],
+ cwd=buildpath, check=True)
subprocess.run([
'uglifyjs',
buildpath / (name + '.js'),
| Full build path is included in package `.js` files
As @rth pointed out in #121, the full build path to the `.data` file is included in the `.js` file for each package. This is *really* a problem, since it doesn't prevent the packages from being deployed anywhere, but it is leaking information we probably don't want to and makes the builds less reproducible.
| 2018-08-21T15:30:32 |
Subsets and Splits