Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async def test_react(self):
with OpsDroid() as opsdroid:
mock_connector = Connector(
{"name": "shell", "thinking-delay": 2, "type": "connector"},
opsdroid=opsdroid,
)
with amock.patch("asyncio.sleep") as mocksleep:
message = events.Message(
"Hello world", "user_id", "user", "default", mock_connector
)
with self.assertRaises(TypeError):
await message.respond(events.Reaction("emoji"))
self.assertTrue(mocksleep.called)
async def test_call_luisai(self):
opsdroid = amock.CoroutineMock()
mock_connector = Connector({}, opsdroid=opsdroid)
message = Message(
text="schedule meeting",
user="user",
target="default",
connector=mock_connector,
)
config = {"name": "luisai", "appid": "test", "appkey": "test", "verbose": True}
result = amock.Mock()
result.json = amock.CoroutineMock()
result.json.return_value = {
"query": "schedule meeting",
"topScoringIntent": {"intent": "Calendar.Add", "score": 0.900492251},
"intents": [{"intent": "Calendar.Add", "score": 0.900492251}],
"entities": [],
}
with amock.patch("aiohttp.ClientSession.get") as patched_request:
def test_connector_names(self):
with OpsDroid() as opsdroid:
with self.assertRaises(ValueError):
opsdroid._connector_names
# Ensure names are always unique
c1 = Connector({"name": "spam"}, opsdroid=opsdroid)
c2 = Connector({"name": "spam"}, opsdroid=opsdroid)
opsdroid.connectors = [c1, c2]
names = opsdroid._connector_names
assert "spam" in names
assert "spam_1" in names
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
opsdroid=opsdroid,
)
with amock.patch("opsdroid.events.Message._typing_delay") as logmock:
with amock.patch("asyncio.sleep") as mocksleep:
message = events.Message(
"hi", "user_id", "user", "default", mock_connector
)
with self.assertRaises(TypeError):
await message.respond("Hello there")
self.assertTrue(logmock.called)
self.assertTrue(mocksleep.called)
# Test thinking-delay with a list
mock_connector_list = Connector(
{
"name": "shell",
"typing-delay": [1, 4],
"type": "connector",
"module_path": "opsdroid-modules.connector.shell",
},
opsdroid=opsdroid,
)
with amock.patch("asyncio.sleep") as mocksleep_list:
message = events.Message(
"hi", "user_id", "user", "default", mock_connector_list
)
with self.assertRaises(TypeError):
await message.respond("Hello there")
if not event.target.startswith(("!", "#")):
event.target = self.room_ids[event.target]
if not event.target.startswith("!"):
event.target = await self.connection.get_room_id(event.target)
try:
return await func(self, event)
except aiohttp.client_exceptions.ServerDisconnectedError:
_LOGGER.debug(_("Server had disconnected, retrying send."))
return await func(self, event)
return ensure_room_id
class ConnectorMatrix(Connector):
"""Connector for Matrix (https://matrix.org)."""
def __init__(self, config, opsdroid=None): # noqa: D107
"""Init the config for the connector."""
super().__init__(config, opsdroid=opsdroid)
self.name = "matrix" # The name of your connector
self.rooms = self._process_rooms_dict(config["rooms"])
self.room_ids = {}
self.default_target = self.rooms["main"]["alias"]
self.mxid = config["mxid"]
self.nick = config.get("nick", None)
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)
from voluptuous import Required
from opsdroid.connector import Connector, register_event
from opsdroid.events import Message
_LOGGER = logging.getLogger(__name__)
_FACEBOOK_SEND_URL = "https://graph.facebook.com/v2.6/me/messages" "?access_token={}"
CONFIG_SCHEMA = {
Required("verify-token"): str,
Required("page-access-token"): str,
"bot-name": str,
}
class ConnectorFacebook(Connector):
"""A connector for Facebook Messenger.
It handles the incoming messages from facebook messenger and sends the user
messages. It also handles the authentication challenge by verifying the
token.
Attributes:
config: The config for this connector specified in the
`configuration.yaml` file.
name: String name of the connector.
opsdroid: opsdroid instance.
default_target: String name of default room for chat messages.
bot_name: String name for bot.
"""
import logging
import aiohttp
from voluptuous import Required
from opsdroid.connector import Connector, register_event
from opsdroid.events import Message
_LOGGER = logging.getLogger(__name__)
GITHUB_API_URL = "https://api.github.com"
CONFIG_SCHEMA = {Required("token"): str}
class ConnectorGitHub(Connector):
"""A connector for GitHub."""
def __init__(self, config, opsdroid=None):
"""Create the connector."""
super().__init__(config, opsdroid=opsdroid)
logging.debug("Loaded GitHub connector.")
try:
self.github_token = config["token"]
except KeyError:
_LOGGER.error(_("Missing auth token! You must set 'token' in your config."))
self.name = self.config.get("name", "github")
self.opsdroid = opsdroid
self.github_username = None
async def connect(self):
"""Connect to GitHub."""
from datetime import datetime
import aiohttp
import aiohttp.web
from aiohttp import WSCloseCode
from opsdroid.connector import Connector, register_event
from opsdroid.events import Message
_LOGGER = logging.getLogger(__name__)
HEADERS = {"Access-Control-Allow-Origin": "*"}
CONFIG_SCHEMA = {"bot-name": str, "max-connections": int, "connection-timeout": int}
class ConnectorWebsocket(Connector):
"""A connector which allows websocket connections."""
def __init__(self, config, opsdroid=None):
"""Create the connector."""
super().__init__(config, opsdroid=opsdroid)
_LOGGER.debug(_("Starting Websocket connector."))
self.name = "websocket"
self.max_connections = self.config.get("max-connections", 10)
self.connection_timeout = self.config.get("connection-timeout", 60)
self.accepting_connections = True
self.active_connections = {}
self.available_connections = []
self.bot_name = self.config.get("bot-name", "opsdroid")
async def connect(self):
"""Connect to the chat service."""