after_merge
stringlengths 28
79.6k
| before_merge
stringlengths 20
79.6k
| url
stringlengths 38
71
| full_traceback
stringlengths 43
922k
| traceback_type
stringclasses 555
values |
|---|---|---|---|---|
def start_loop(self):
"""Start the event loop."""
connectors, databases, skills = self.loader.load_modules_from_config(self.config)
_LOGGER.debug("Loaded %i skills", len(skills))
if databases is not None:
self.start_databases(databases)
self.setup_skills(skills)
self.start_connector_tasks(connectors)
self.eventloop.create_task(parse_crontab(self))
self.web_server.start()
try:
pending = asyncio.Task.all_tasks()
self.eventloop.run_until_complete(asyncio.gather(*pending))
except RuntimeError as error:
if str(error) != "Event loop is closed":
raise error
finally:
self.eventloop.close()
|
def start_loop(self):
"""Start the event loop."""
connectors, databases, skills = self.loader.load_modules_from_config(self.config)
_LOGGER.debug("Loaded %i skills", len(skills))
if databases is not None:
self.start_databases(databases)
self.setup_skills(skills)
self.start_connector_tasks(connectors)
self.eventloop.create_task(parse_crontab(self))
self.web_server.start()
try:
pending = asyncio.Task.all_tasks()
self.eventloop.run_until_complete(asyncio.gather(*pending))
except (KeyboardInterrupt, EOFError):
print("") # Prints a character return for return to shell
self.stop()
_LOGGER.info("Keyboard interrupt, exiting.")
except RuntimeError as error:
if str(error) != "Event loop is closed":
raise error
finally:
self.eventloop.close()
|
https://github.com/opsdroid/opsdroid/issues/247
|
^CERROR asyncio: Task exception was never retrieved
future: <Task finished coro=<ConnectorShell.listen() done, defined at /root/.opsdroid/modules/opsdroid-modules/connector/shell/__init__.py:57> exception=ConnectionResetError('Connection lost',)>
Traceback (most recent call last):
File "/usr/local/lib/python3.5/asyncio/tasks.py", line 240, in _step
result = coro.send(None)
File "/root/.opsdroid/modules/opsdroid-modules/connector/shell/__init__.py", line 63, in listen
user_input = await async_input('', opsdroid.eventloop)
File "/root/.opsdroid/modules/opsdroid-modules/connector/shell/__init__.py", line 37, in async_input
await writer.drain()
File "/usr/local/lib/python3.5/asyncio/streams.py", line 333, in drain
yield from self._protocol._drain_helper()
File "/usr/local/lib/python3.5/asyncio/streams.py", line 204, in _drain_helper
raise ConnectionResetError('Connection lost')
ConnectionResetError: Connection lost
ERROR asyncio: Exception in default exception handler
Traceback (most recent call last):
File "/usr/local/lib/python3.5/asyncio/base_events.py", line 1284, in call_exception_handler
self.default_exception_handler(context)
File "/usr/local/lib/python3.5/asyncio/base_events.py", line 1259, in default_exception_handler
logger.error('\n'.join(log_lines), exc_info=exc_info)
File "/usr/local/lib/python3.5/logging/__init__.py", line 1314, in error
self._log(ERROR, msg, args, **kwargs)
File "/usr/local/lib/python3.5/logging/__init__.py", line 1421, in _log
self.handle(record)
File "/usr/local/lib/python3.5/logging/__init__.py", line 1431, in handle
self.callHandlers(record)
File "/usr/local/lib/python3.5/logging/__init__.py", line 1493, in callHandlers
hdlr.handle(record)
File "/usr/local/lib/python3.5/logging/__init__.py", line 861, in handle
self.emit(record)
File "/usr/local/lib/python3.5/logging/__init__.py", line 1053, in emit
self.stream = self._open()
File "/usr/local/lib/python3.5/logging/__init__.py", line 1043, in _open
return open(self.baseFilename, self.mode, encoding=self.encoding)
NameError: name 'open' is not defined
Exception ignored in: <bound method Task.__del__ of <Task finished coro=<ConnectorShell.listen() done, defined at /root/.opsdroid/modules/opsdroid-modules/connector/shell/__init__.py:57> exception=ConnectionResetError('Connection lost',)>>
Traceback (most recent call last):
File "/usr/local/lib/python3.5/asyncio/tasks.py", line 93, in __del__
File "/usr/local/lib/python3.5/asyncio/futures.py", line 234, in __del__
File "/usr/local/lib/python3.5/asyncio/base_events.py", line 1290, in call_exception_handler
File "/usr/local/lib/python3.5/logging/__init__.py", line 1314, in error
File "/usr/local/lib/python3.5/logging/__init__.py", line 1421, in _log
File "/usr/local/lib/python3.5/logging/__init__.py", line 1431, in handle
File "/usr/local/lib/python3.5/logging/__init__.py", line 1493, in callHandlers
File "/usr/local/lib/python3.5/logging/__init__.py", line 861, in handle
File "/usr/local/lib/python3.5/logging/__init__.py", line 1053, in emit
File "/usr/local/lib/python3.5/logging/__init__.py", line 1043, in _open
NameError: name 'open' is not defined
ERROR asyncio: Task was destroyed but it is pending!
task: <Task pending coro=<parse_crontab() running at /usr/src/app/opsdroid/parsers/crontab.py:20> wait_for=<Future pending cb=[Task._wakeup()]>>
ERROR asyncio: Exception in default exception handler
Traceback (most recent call last):
File "/usr/local/lib/python3.5/asyncio/base_events.py", line 1284, in call_exception_handler
self.default_exception_handler(context)
File "/usr/local/lib/python3.5/asyncio/base_events.py", line 1259, in default_exception_handler
logger.error('\n'.join(log_lines), exc_info=exc_info)
File "/usr/local/lib/python3.5/logging/__init__.py", line 1314, in error
self._log(ERROR, msg, args, **kwargs)
File "/usr/local/lib/python3.5/logging/__init__.py", line 1421, in _log
self.handle(record)
File "/usr/local/lib/python3.5/logging/__init__.py", line 1431, in handle
self.callHandlers(record)
File "/usr/local/lib/python3.5/logging/__init__.py", line 1493, in callHandlers
hdlr.handle(record)
File "/usr/local/lib/python3.5/logging/__init__.py", line 861, in handle
self.emit(record)
File "/usr/local/lib/python3.5/logging/__init__.py", line 1053, in emit
self.stream = self._open()
File "/usr/local/lib/python3.5/logging/__init__.py", line 1043, in _open
return open(self.baseFilename, self.mode, encoding=self.encoding)
NameError: name 'open' is not defined
Exception ignored in: <bound method Task.__del__ of <Task pending coro=<parse_crontab() running at /usr/src/app/opsdroid/parsers/crontab.py:20> wait_for=<Future pending cb=[Task._wakeup()]>>>
Traceback (most recent call last):
File "/usr/local/lib/python3.5/asyncio/tasks.py", line 92, in __del__
File "/usr/local/lib/python3.5/asyncio/base_events.py", line 1290, in call_exception_handler
File "/usr/local/lib/python3.5/logging/__init__.py", line 1314, in error
File "/usr/local/lib/python3.5/logging/__init__.py", line 1421, in _log
File "/usr/local/lib/python3.5/logging/__init__.py", line 1431, in handle
File "/usr/local/lib/python3.5/logging/__init__.py", line 1493, in callHandlers
File "/usr/local/lib/python3.5/logging/__init__.py", line 861, in handle
File "/usr/local/lib/python3.5/logging/__init__.py", line 1053, in emit
File "/usr/local/lib/python3.5/logging/__init__.py", line 1043, in _open
NameError: name 'open' is not defined
|
ConnectionResetError
|
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 with aiohttp.ClientSession() as session:
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 []
|
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 with aiohttp.ClientSession() as session:
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"]
return []
|
https://github.com/opsdroid/opsdroid/issues/412
|
INFO opsdroid.parsers.rasanlu: Starting Rasa NLU training.
DEBUG asyncio: Using selector: KqueueSelector
Traceback (most recent call last):
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/site-packages/aiohttp/connector.py", line 797, in _wrap_create_connection
return (yield from self._loop.create_connection(*args, **kwargs))
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/asyncio/base_events.py", line 776, in create_connection
raise exceptions[0]
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/asyncio/base_events.py", line 763, in create_connection
yield from self.sock_connect(sock, address)
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/asyncio/selector_events.py", line 451, in sock_connect
return (yield from fut)
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/asyncio/futures.py", line 381, in __iter__
yield self # This tells Task to wait for completion.
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/asyncio/tasks.py", line 310, in _wakeup
future.result()
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/asyncio/futures.py", line 294, in result
raise self._exception
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/asyncio/selector_events.py", line 481, in _sock_connect_cb
raise OSError(err, 'Connect call failed %s' % (address,))
ConnectionRefusedError: [Errno 61] Connect call failed ('127.0.0.1', 5000)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/__main__.py", line 140, in <module>
init()
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/__main__.py", line 137, in init
main()
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/__main__.py", line 130, in main
opsdroid.start_loop()
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/core.py", line 141, in start_loop
self.train_parsers(skills)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/core.py", line 176, in train_parsers
asyncio.gather(*tasks, loop=self.eventloop))
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/asyncio/base_events.py", line 467, in run_until_complete
return future.result()
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/asyncio/futures.py", line 294, in result
raise self._exception
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/asyncio/tasks.py", line 242, in _step
result = coro.throw(exc)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/parsers/rasanlu.py", line 89, in train_rasanlu
if config["model"] in await _get_existing_models(config):
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/parsers/rasanlu.py", line 71, in _get_existing_models
resp = await session.get(await _build_status_url(config))
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/site-packages/aiohttp/helpers.py", line 104, in __await__
ret = yield from self._coro
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/site-packages/aiohttp/client.py", line 267, in _request
conn = yield from self._connector.connect(req)
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/site-packages/aiohttp/connector.py", line 402, in connect
proto = yield from self._create_connection(req)
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/site-packages/aiohttp/connector.py", line 749, in _create_connection
_, proto = yield from self._create_direct_connection(req)
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/site-packages/aiohttp/connector.py", line 860, in _create_direct_connection
raise last_exc
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/site-packages/aiohttp/connector.py", line 832, in _create_direct_connection
req=req, client_error=client_error)
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/site-packages/aiohttp/connector.py", line 804, in _wrap_create_connection
raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host localhost:5000 ssl:False [Connect call failed ('127.0.0.1', 5000)]
|
ConnectionRefusedError
|
def pip_install_deps(requirements_path):
"""Pip install a requirements.txt file and wait for finish."""
process = None
command = [
"pip",
"install",
"--target={}".format(DEFAULT_MODULE_DEPS_PATH),
"--ignore-installed",
"-r",
requirements_path,
]
try:
process = subprocess.Popen(
command, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
except FileNotFoundError:
_LOGGER.debug(
"Couldn't find the command 'pip', trying again with command 'pip3'"
)
try:
command[0] = "pip3"
process = subprocess.Popen(
command, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
except FileNotFoundError:
_LOGGER.debug(
"Couldn't find the command 'pip3', install of %s will be skipped.",
str(requirements_path),
)
if not process:
raise OSError("Pip and pip3 not found, exiting...")
for output in process.communicate():
if output != "":
for line in output.splitlines():
_LOGGER.debug(str(line).strip())
process.wait()
return True
|
def pip_install_deps(requirements_path):
"""Pip install a requirements.txt file and wait for finish."""
process = subprocess.Popen(
[
"pip",
"install",
"--target={}".format(DEFAULT_MODULE_DEPS_PATH),
"--ignore-installed",
"-r",
requirements_path,
],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
for output in process.communicate():
if output != "":
for line in output.splitlines():
_LOGGER.debug(str(line).strip())
process.wait()
|
https://github.com/opsdroid/opsdroid/issues/385
|
INFO opsdroid: ========================================
INFO opsdroid: Started application
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.
Traceback (most recent call last):
File "/Users/fabiorosado/Documents/GitHub/opsdroid/opsdroid/__main__.py", line 140, in <module>
init()
File "/Users/fabiorosado/Documents/GitHub/opsdroid/opsdroid/__main__.py", line 137, in init
main()
File "/Users/fabiorosado/Documents/GitHub/opsdroid/opsdroid/__main__.py", line 130, in main
opsdroid.start_loop()
File "/Users/fabiorosado/Documents/GitHub/opsdroid/opsdroid/core.py", line 134, in start_loop
self.loader.load_modules_from_config(self.config)
File "/Users/fabiorosado/Documents/GitHub/opsdroid/opsdroid/loader.py", line 222, in load_modules_from_config
skills = self._load_modules('skill', config['skills'])
File "/Users/fabiorosado/Documents/GitHub/opsdroid/opsdroid/loader.py", line 271, in _load_modules
self._install_module(config)
File "/Users/fabiorosado/Documents/GitHub/opsdroid/opsdroid/loader.py", line 317, in _install_module
"/requirements.txt")
File "/Users/fabiorosado/Documents/GitHub/opsdroid/opsdroid/loader.py", line 112, in pip_install_deps
stderr=subprocess.PIPE)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 707, in __init__
restore_signals, start_new_session)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1326, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'pip'
Exception ignored in: <bound method BaseEventLoop.__del__ of <_UnixSelectorEventLoop running=False closed=True debug=False>>
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 511, in __del__
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/unix_events.py", line 65, in close
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/unix_events.py", line 146, in remove_signal_handler
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/signal.py", line 47, in signal
TypeError: signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object
|
FileNotFoundError
|
async def get_ranked_skills(self, message):
"""Take a message and return a ranked list of matching skills."""
skills = []
skills = skills + await parse_regex(self, message)
if "parsers" in self.config:
_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"
)
if len(dialogflow) == 1 and (
"enabled" not in dialogflow[0] or dialogflow[0]["enabled"] is not False
):
_LOGGER.debug("Checking dialogflow...")
skills = skills + await parse_dialogflow(self, message, dialogflow[0])
luisai = [p for p in parsers if p["name"] == "luisai"]
if len(luisai) == 1 and (
"enabled" not in luisai[0] or luisai[0]["enabled"] is not False
):
_LOGGER.debug("Checking luisai...")
skills = skills + await parse_luisai(self, message, luisai[0])
recastai = [p for p in parsers if p["name"] == "recastai"]
if len(recastai) == 1 and (
"enabled" not in recastai[0] or recastai[0]["enabled"] is not False
):
_LOGGER.debug("Checking Recast.AI...")
skills = skills + await parse_recastai(self, message, recastai[0])
witai = [p for p in parsers if p["name"] == "witai"]
if len(witai) == 1 and (
"enabled" not in witai[0] or witai[0]["enabled"] is not False
):
_LOGGER.debug("Checking wit.ai...")
skills = skills + await parse_witai(self, message, witai[0])
return sorted(skills, key=lambda k: k["score"], reverse=True)
|
async def get_ranked_skills(self, message):
"""Take a message and return a ranked list of matching skills."""
skills = []
skills = skills + await parse_regex(self, message)
if "parsers" in self.config:
_LOGGER.debug("Processing parsers...")
parsers = self.config["parsers"]
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"
)
if len(dialogflow) == 1 and (
"enabled" not in dialogflow[0] or dialogflow[0]["enabled"] is not False
):
_LOGGER.debug("Checking dialogflow...")
skills = skills + await parse_dialogflow(self, message, dialogflow[0])
luisai = [p for p in parsers if p["name"] == "luisai"]
if len(luisai) == 1 and (
"enabled" not in luisai[0] or luisai[0]["enabled"] is not False
):
_LOGGER.debug("Checking luisai...")
skills = skills + await parse_luisai(self, message, luisai[0])
recastai = [p for p in parsers if p["name"] == "recastai"]
if len(recastai) == 1 and (
"enabled" not in recastai[0] or recastai[0]["enabled"] is not False
):
_LOGGER.debug("Checking Recast.AI...")
skills = skills + await parse_recastai(self, message, recastai[0])
witai = [p for p in parsers if p["name"] == "witai"]
if len(witai) == 1 and (
"enabled" not in witai[0] or witai[0]["enabled"] is not False
):
_LOGGER.debug("Checking wit.ai...")
skills = skills + await parse_witai(self, message, witai[0])
return sorted(skills, key=lambda k: k["score"], reverse=True)
|
https://github.com/opsdroid/opsdroid/issues/378
|
DEBUG opsdroid.core: Parsing input: hi
DEBUG opsdroid.core: Processing parsers...
ERROR aiohttp.server: Error handling request
Traceback (most recent call last):
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/site-packages/aiohttp/web_protocol.py", line 416, in start
resp = yield from self._request_handler(request)
File "/Users/jacob/.pyenv/versions/3.5.4/lib/python3.5/site-packages/aiohttp/web.py", line 325, in _handle
resp = yield from handler(request)
File "/Users/jacob/.opsdroid/modules/opsdroid-modules/connector/websocket/__init__.py", line 77, in websocket_handler
await self.opsdroid.parse(message)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/core.py", line 273, in parse
ranked_skills = await self.get_ranked_skills(message)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/core.py", line 218, in get_ranked_skills
dialogflow = [p for p in parsers if p["name"] == "dialogflow"
TypeError: 'NoneType' object is not iterable
|
TypeError
|
def import_module(config):
"""Import module namespace as variable and return it."""
# Check if the module can be imported and proceed with import
# Proceed only if config.name is specified
# and parent module can be imported
if config["name"] and importlib.util.find_spec(config["module_path"]):
module_spec = importlib.util.find_spec(
config["module_path"] + "." + config["name"]
)
if module_spec:
module = Loader.import_module_from_spec(module_spec)
_LOGGER.debug("Loaded %s: %s", config["type"], config["module_path"])
return module
module_spec = importlib.util.find_spec(config["module_path"])
if module_spec:
module = Loader.import_module_from_spec(module_spec)
_LOGGER.debug("Loaded %s: %s", config["type"], config["module_path"])
return module
_LOGGER.error("Failed to load %s: %s", config["type"], config["module_path"])
return None
|
def import_module(config):
"""Import module namespace as variable and return it."""
try:
module = importlib.import_module(config["module_path"] + "." + config["name"])
_LOGGER.debug("Loaded %s: %s", config["type"], config["module_path"])
return module
except ImportError as error:
_LOGGER.debug(
"Failed to load %s.%s. ERROR: %s",
config["module_path"],
config["name"],
error,
)
try:
module = importlib.import_module(config["module_path"])
_LOGGER.debug("Loaded %s: %s", config["type"], config["module_path"])
return module
except ImportError as error:
_LOGGER.error("Failed to load %s: %s", config["type"], config["module_path"])
_LOGGER.debug(error)
return None
|
https://github.com/opsdroid/opsdroid/issues/290
|
Traceback (most recent call last):
File "/Users/jacob/.pyenv/versions/3.5.1/lib/python3.5/runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "/Users/jacob/.pyenv/versions/3.5.1/lib/python3.5/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/__main__.py", line 134, in <module>
main()
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/__main__.py", line 129, in main
opsdroid.start_loop()
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/core.py", line 123, in start_loop
self.loader.load_modules_from_config(self.config)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/loader.py", line 206, in load_modules_from_config
self._reload_modules(skills)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/loader.py", line 128, in _reload_modules
importlib.reload(module["module"])
File "/Users/jacob/.pyenv/versions/3.5.1/lib/python3.5/importlib/__init__.py", line 147, in reload
raise ImportError(msg.format(name), name=name)
ImportError: module opsdroid-modules.skill.hello not in sys.modules
|
ImportError
|
def _reload_modules(self, modules):
"""Reload modules in namespace. Queries sys.modules."""
for module in modules:
self.current_import_config = module["config"]
if isinstance(module["module"], ModuleType):
module_name = module["module"].__name__
if sys.modules.get(module_name):
_LOGGER.debug("Reloading module %s", module_name)
importlib.reload(sys.modules[module_name])
|
def _reload_modules(self, modules):
for module in modules:
self.current_import_config = module["config"]
importlib.reload(module["module"])
|
https://github.com/opsdroid/opsdroid/issues/290
|
Traceback (most recent call last):
File "/Users/jacob/.pyenv/versions/3.5.1/lib/python3.5/runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "/Users/jacob/.pyenv/versions/3.5.1/lib/python3.5/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/__main__.py", line 134, in <module>
main()
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/__main__.py", line 129, in main
opsdroid.start_loop()
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/core.py", line 123, in start_loop
self.loader.load_modules_from_config(self.config)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/loader.py", line 206, in load_modules_from_config
self._reload_modules(skills)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/loader.py", line 128, in _reload_modules
importlib.reload(module["module"])
File "/Users/jacob/.pyenv/versions/3.5.1/lib/python3.5/importlib/__init__.py", line 147, in reload
raise ImportError(msg.format(name), name=name)
ImportError: module opsdroid-modules.skill.hello not in sys.modules
|
ImportError
|
async def parse_apiai(opsdroid, message, config):
"""Parse a message against all apiai skills."""
# pylint: disable=broad-except
# We want to catch all exceptions coming from a skill module and not
# halt the application. If a skill throws an exception it just doesn't
# give a response to the user, so an error response should be given.
if "access-token" in config:
try:
result = await call_apiai(message, config)
except aiohttp.ClientOSError:
_LOGGER.error("No response from api.ai, check your network.")
return
if result["status"]["code"] >= 300:
_LOGGER.error(
"api.ai error - "
+ str(result["status"]["code"])
+ " "
+ result["status"]["errorType"]
)
return
if "min-score" in config and result["result"]["score"] < config["min-score"]:
_LOGGER.debug("api.ai score lower than min-score")
return
if result:
for skill in opsdroid.skills:
if "apiai_action" in skill or "apiai_intent" in skill:
if (
"action" in result["result"]
and skill["apiai_action"] in result["result"]["action"]
) or (
"intentName" in result["result"]
and skill["apiai_intent"] in result["result"]["intentName"]
):
message.apiai = result
try:
await skill["skill"](opsdroid, skill["config"], message)
except Exception:
await message.respond("Whoops there has been an error")
await message.respond("Check the log for details")
_LOGGER.exception(
"Exception when parsing '"
+ message.text
+ "' against skill '"
+ result["result"]["action"]
+ "'"
)
|
async def parse_apiai(opsdroid, message, config):
"""Parse a message against all apiai skills."""
# pylint: disable=broad-except
# We want to catch all exceptions coming from a skill module and not
# halt the application. If a skill throws an exception it just doesn't
# give a response to the user, so an error response should be given.
if "access-token" in config:
result = await call_apiai(message, config)
if result["status"]["code"] >= 300:
_LOGGER.error(
"api.ai error - "
+ str(result["status"]["code"])
+ " "
+ result["status"]["errorType"]
)
return
if "min-score" in config and result["result"]["score"] < config["min-score"]:
_LOGGER.debug("api.ai score lower than min-score")
return
if result:
for skill in opsdroid.skills:
if "apiai_action" in skill or "apiai_intent" in skill:
if (
"action" in result["result"]
and skill["apiai_action"] in result["result"]["action"]
) or (
"intentName" in result["result"]
and skill["apiai_intent"] in result["result"]["intentName"]
):
message.apiai = result
try:
await skill["skill"](opsdroid, skill["config"], message)
except Exception:
await message.respond("Whoops there has been an error")
await message.respond("Check the log for details")
_LOGGER.exception(
"Exception when parsing '"
+ message.text
+ "' against skill '"
+ result["result"]["action"]
+ "'"
)
|
https://github.com/opsdroid/opsdroid/issues/132
|
ERROR asyncio: Task exception was never retrieved
future: <Task finished coro=<parse_apiai() done, defined at /Users/jacob/Projects/opsdroid/opsdroid/opsdroid/parsers/apiai.py:34> exception=ClientConnectorError(8, 'Cannot connect to host api.api.ai:443 ssl:True [nodename nor servname provided, or not known]')>
Traceback (most recent call last):
File "/Users/jacob/Projects/opsdroid/opsdroid/venv/lib/python3.6/site-packages/aiohttp/connector.py", line 375, in connect
proto = yield from self._create_connection(req)
File "/Users/jacob/Projects/opsdroid/opsdroid/venv/lib/python3.6/site-packages/aiohttp/connector.py", line 632, in _create_connection
_, proto = yield from self._create_direct_connection(req)
File "/Users/jacob/Projects/opsdroid/opsdroid/venv/lib/python3.6/site-packages/aiohttp/connector.py", line 643, in _create_direct_connection
hosts = yield from self._resolve_host(req.url.raw_host, req.port)
File "/Users/jacob/Projects/opsdroid/opsdroid/venv/lib/python3.6/site-packages/aiohttp/connector.py", line 615, in _resolve_host
self._resolver.resolve(host, port, family=self._family)
File "/Users/jacob/Projects/opsdroid/opsdroid/venv/lib/python3.6/site-packages/aiohttp/resolver.py", line 30, in resolve
host, port, type=socket.SOCK_STREAM, family=family)
File "/opt/boxen/homebrew/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/concurrent/futures/thread.py", line 55, in run
result = self.fn(*self.args, **self.kwargs)
File "/opt/boxen/homebrew/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 743, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/parsers/apiai.py", line 42, in parse_apiai
result = await call_apiai(message, config)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/parsers/apiai.py", line 27, in call_apiai
headers=headers)
File "/Users/jacob/Projects/opsdroid/opsdroid/venv/lib/python3.6/site-packages/aiohttp/client.py", line 621, in __await__
resp = yield from self._coro
File "/Users/jacob/Projects/opsdroid/opsdroid/venv/lib/python3.6/site-packages/aiohttp/client.py", line 225, in _request
conn = yield from self._connector.connect(req)
File "/Users/jacob/Projects/opsdroid/opsdroid/venv/lib/python3.6/site-packages/aiohttp/connector.py", line 380, in connect
.format(key, exc.strerror)) from exc
aiohttp.client_exceptions.ClientConnectorError: [Errno 8] Cannot connect to host api.api.ai:443 ssl:True [nodename nor servname provided, or not known]
|
aiohttp.client_exceptions.ClientConnectorError
|
def _createDetachedPanel(self, *args, **kwargs):
panel = _DetachedPanel(self, *args, **kwargs)
panel.__removeOnCloseConnection = panel.closedSignal().connect(
lambda w: w.parent()._removeDetachedPanel(w)
)
scriptWindow = self.ancestor(GafferUI.ScriptWindow)
if scriptWindow:
panel.setTitle(scriptWindow.getTitle())
weakSetTitle = Gaffer.WeakMethod(panel.setTitle)
panel.__titleChangedConnection = scriptWindow.titleChangedSignal().connect(
lambda w, t: weakSetTitle(t)
)
self.__detachedPanels.append(panel)
return panel
|
def _createDetachedPanel(self, *args, **kwargs):
panel = _DetachedPanel(self, *args, **kwargs)
panel.__removeOnCloseConnection = panel.closedSignal().connect(
lambda w: w.parent()._removeDetachedPanel(w)
)
scriptWindow = self.ancestor(GafferUI.ScriptWindow)
if scriptWindow:
panel.setTitle(scriptWindow.getTitle())
weakSetTitle = Gaffer.WeakMethod(panel.setTitle)
scriptWindow.titleChangedSignal().connect(
lambda w, t: weakSetTitle(t), scoped=False
)
self.__detachedPanels.append(panel)
return panel
|
https://github.com/GafferHQ/gaffer/issues/3281
|
Traceback (most recent call last):
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/Gaffer/WeakMethod.py", line 67, in __call__
return m( *args, **kwArgs )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 226, in __scriptPlugChanged
self.__updateTitle()
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 221, in __updateTitle
w._setTitle( "Gaffer : %s%s%s%s" % ( f, ro, u, d ) )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 101, in _setTitle
self.__titleChangedSignal( self, title )
IECore.Exception: Traceback (most recent call last):
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/CompoundEditor.py", line 130, in <lambda>
scriptWindow.titleChangedSignal().connect( lambda w, t : weakSetTitle( t ), scoped = False )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/Gaffer/WeakMethod.py", line 64, in __call__
raise ReferenceError( "Instance referenced by WeakMethod %s.%s() no longer exists" % ( self.__method.__module__, self.__method.__name__ ) )
ReferenceError: Instance referenced by WeakMethod GafferUI.Window.setTitle() no longer exists
|
ReferenceError
|
def _removeDetachedPanel(self, panel):
self.__detachedPanels.remove(panel)
panel.__removeOnCloseConnection = None
panel.__titleChangedConnection = None
panel._applyVisibility()
|
def _removeDetachedPanel(self, panel):
self.__detachedPanels.remove(panel)
panel.__removeOnCloseConnection = None
panel._applyVisibility()
|
https://github.com/GafferHQ/gaffer/issues/3281
|
Traceback (most recent call last):
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/Gaffer/WeakMethod.py", line 67, in __call__
return m( *args, **kwArgs )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 226, in __scriptPlugChanged
self.__updateTitle()
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 221, in __updateTitle
w._setTitle( "Gaffer : %s%s%s%s" % ( f, ro, u, d ) )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 101, in _setTitle
self.__titleChangedSignal( self, title )
IECore.Exception: Traceback (most recent call last):
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/CompoundEditor.py", line 130, in <lambda>
scriptWindow.titleChangedSignal().connect( lambda w, t : weakSetTitle( t ), scoped = False )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/Gaffer/WeakMethod.py", line 64, in __call__
raise ReferenceError( "Instance referenced by WeakMethod %s.%s() no longer exists" % ( self.__method.__module__, self.__method.__name__ ) )
ReferenceError: Instance referenced by WeakMethod GafferUI.Window.setTitle() no longer exists
|
ReferenceError
|
def __setTabDragConstraints(self, qTabBar, event):
# We need to work out some min/max X coordinates (in the tab bars local
# space) such that when the user drags left/right the left/right edges
# of the tab never leave the TabBar.
barRect = qTabBar.rect()
tabRect = qTabBar.tabRect(qTabBar.tabAt(event.pos()))
mouseX = event.pos().x()
self.__dragMinX = mouseX - tabRect.x() # cursorToTabLeftEdge
tabRightEdge = tabRect.x() + tabRect.width()
if tabRightEdge > barRect.width():
# Already as far right as it can go
self.__dragMaxX = mouseX
else:
cursorToTabRightEdge = tabRightEdge - mouseX
self.__dragMaxX = barRect.width() - cursorToTabRightEdge
|
def __setTabDragConstraints(self, qTabBar, event):
# We need to work out some min/max X coordinates (in the tab bars local
# space) such that when the user drags left/rigth the left/right edges
# of the tab never leave the TabBar.
tabRect = qTabBar.tabRect(qTabBar.currentIndex())
self.__dragMinX = event.pos().x() - tabRect.x() # cursorToTabLeftEdge
cursorToTabRightEdge = tabRect.x() + tabRect.width() - event.pos().x()
self.__dragMaxX = qTabBar.width() - cursorToTabRightEdge
|
https://github.com/GafferHQ/gaffer/issues/3281
|
Traceback (most recent call last):
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/Gaffer/WeakMethod.py", line 67, in __call__
return m( *args, **kwArgs )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 226, in __scriptPlugChanged
self.__updateTitle()
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 221, in __updateTitle
w._setTitle( "Gaffer : %s%s%s%s" % ( f, ro, u, d ) )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 101, in _setTitle
self.__titleChangedSignal( self, title )
IECore.Exception: Traceback (most recent call last):
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/CompoundEditor.py", line 130, in <lambda>
scriptWindow.titleChangedSignal().connect( lambda w, t : weakSetTitle( t ), scoped = False )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/Gaffer/WeakMethod.py", line 64, in __call__
raise ReferenceError( "Instance referenced by WeakMethod %s.%s() no longer exists" % ( self.__method.__module__, self.__method.__name__ ) )
ReferenceError: Instance referenced by WeakMethod GafferUI.Window.setTitle() no longer exists
|
ReferenceError
|
def _popupMenuDefinition(self):
menuDefinition = IECore.MenuDefinition()
if self.getPlug().getInput() is not None:
menuDefinition.append(
"/Edit input...", {"command": Gaffer.WeakMethod(self.__editInput)}
)
menuDefinition.append("/EditInputDivider", {"divider": True})
menuDefinition.append(
"/Remove input",
{
"command": Gaffer.WeakMethod(self.__removeInput),
"active": self.getPlug().acceptsInput(None) and not self.getReadOnly(),
},
)
if (
hasattr(self.getPlug(), "defaultValue")
and self.getPlug().direction() == Gaffer.Plug.Direction.In
):
menuDefinition.append(
"/Default",
{
"command": IECore.curry(
Gaffer.WeakMethod(self.__setValue), self.getPlug().defaultValue()
),
"active": self._editable(),
},
)
if (
Gaffer.NodeAlgo.hasUserDefault(self.getPlug())
and self.getPlug().direction() == Gaffer.Plug.Direction.In
):
menuDefinition.append(
"/User Default",
{
"command": Gaffer.WeakMethod(self.__applyUserDefault),
"active": self._editable(),
},
)
with self.getContext():
currentPreset = Gaffer.NodeAlgo.currentPreset(self.getPlug())
for presetName in Gaffer.NodeAlgo.presets(self.getPlug()):
menuDefinition.append(
"/Preset/" + presetName,
{
"command": IECore.curry(
Gaffer.WeakMethod(self.__applyPreset), presetName
),
"active": self._editable(),
"checkBox": presetName == currentPreset,
},
)
self.popupMenuSignal()(menuDefinition, self)
return menuDefinition
|
def _popupMenuDefinition(self):
menuDefinition = IECore.MenuDefinition()
if self.getPlug().getInput() is not None:
menuDefinition.append(
"/Edit input...", {"command": Gaffer.WeakMethod(self.__editInput)}
)
menuDefinition.append("/EditInputDivider", {"divider": True})
menuDefinition.append(
"/Remove input",
{
"command": Gaffer.WeakMethod(self.__removeInput),
"active": self.getPlug().acceptsInput(None) and not self.getReadOnly(),
},
)
if (
hasattr(self.getPlug(), "defaultValue")
and self.getPlug().direction() == Gaffer.Plug.Direction.In
):
menuDefinition.append(
"/Default",
{
"command": IECore.curry(
Gaffer.WeakMethod(self.__setValue), self.getPlug().defaultValue()
),
"active": self._editable(),
},
)
if (
Gaffer.NodeAlgo.hasUserDefault(self.getPlug())
and self.getPlug().direction() == Gaffer.Plug.Direction.In
):
menuDefinition.append(
"/User Default",
{
"command": Gaffer.WeakMethod(self.__applyUserDefault),
"active": self._editable(),
},
)
currentPreset = Gaffer.NodeAlgo.currentPreset(self.getPlug())
for presetName in Gaffer.NodeAlgo.presets(self.getPlug()):
menuDefinition.append(
"/Preset/" + presetName,
{
"command": IECore.curry(
Gaffer.WeakMethod(self.__applyPreset), presetName
),
"active": self._editable(),
"checkBox": presetName == currentPreset,
},
)
self.popupMenuSignal()(menuDefinition, self)
return menuDefinition
|
https://github.com/GafferHQ/gaffer/issues/1121
|
Traceback (most recent call last):
File "/home/andrewk/apps/gaffer/0.6.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/Widget.py", line 879, in eventFilter
return self.__contextMenu( qObject, qEvent )
File "/home/andrewk/apps/gaffer/0.6.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/Widget.py", line 1053, in __contextMenu
return widget._contextMenuSignal( widget )
RuntimeError: Exception : Traceback (most recent call last):
File "/software/apps/cortex/9.0.0-a11/cent6.x86_64/base/python/2.7/gcc/4.1.2/IECore/curry.py", line 48, in curriedFunction
return func( *args, **kwds )
File "/home/andrewk/apps/gaffer/0.6.0.0dev/cent6.x86_64/cortex/9/gaffer/python/Gaffer/WeakMethod.py", line 67, in __call__
return m( *args, **kwArgs )
File "/home/andrewk/apps/gaffer/0.6.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/PlugValueWidget.py", line 410, in __contextMenu
menuDefinition = self._popupMenuDefinition()
File "/home/andrewk/apps/gaffer/0.6.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/PlugValueWidget.py", line 232, in _popupMenuDefinition
currentPreset = Gaffer.NodeAlgo.currentPreset( self.getPlug() )
File "/home/andrewk/apps/gaffer/0.6.0.0dev/cent6.x86_64/cortex/9/gaffer/python/Gaffer/NodeAlgo.py", line 60, in currentPreset
value = plug.getValue()
RuntimeError: Exception : Traceback (most recent call last):
File "/home/andrewk/apps/gaffer/0.6.0.0dev/cent6.x86_64/cortex/9/gaffer/python/Gaffer/PythonExpressionEngine.py", line 89, in execute
exec( self.__expression, executionDict, executionDict )
File "<string>", line 1, in <module>
RuntimeError: Exception : Context has no entry named "custom"
|
RuntimeError
|
def acquire(jobPool):
assert isinstance(jobPool, Gaffer.LocalDispatcher.JobPool)
window = getattr(jobPool, "_window", None)
if window is not None and window():
return window()
window = _LocalJobsWindow(jobPool)
jobPool._window = weakref.ref(window)
return window
|
def acquire(jobPool):
assert isinstance(jobPool, Gaffer.LocalDispatcher.JobPool)
window = getattr(jobPool, "_window", None)
if window:
return window
window = _LocalJobsWindow(jobPool)
jobPool._window = window
return window
|
https://github.com/GafferHQ/gaffer/issues/1064
|
Traceback (most recent call last):
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/Gaffer/WeakMethod.py", line 67, in __call__
return m( *args, **kwArgs )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/Button.py", line 138, in __clicked
self.clickedSignal()( self )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/Gaffer/WeakMethod.py", line 67, in __call__
return m( *args, **kwArgs )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/DispatcherUI.py", line 239, in __executeClicked
_showDispatcherWindow( [ self.getPlug().node() ] )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/DispatcherUI.py", line 450, in _showDispatcherWindow
window = __dispatcherWindow( nodes[0].scriptNode() )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/DispatcherUI.py", line 444, in __dispatcherWindow
scriptWindow.addChildWindow( window )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/Window.py", line 171, in addChildWindow
oldParent = childWindow.parent()
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/Widget.py", line 290, in parent
parentWidget = q.parentWidget()
RuntimeError: underlying C/C++ object has been deleted
|
RuntimeError
|
def __showLocalDispatcherWindow(menu):
window = _LocalJobsWindow.acquire(Gaffer.LocalDispatcher.defaultJobPool())
scriptWindow = menu.ancestor(GafferUI.ScriptWindow)
scriptWindow.addChildWindow(window)
window.setVisible(True)
|
def __showLocalDispatcherWindow(menu):
window = _LocalJobsWindow.acquire(Gaffer.LocalDispatcher.defaultJobPool())
window.setVisible(True)
|
https://github.com/GafferHQ/gaffer/issues/1064
|
Traceback (most recent call last):
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/Gaffer/WeakMethod.py", line 67, in __call__
return m( *args, **kwArgs )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/Button.py", line 138, in __clicked
self.clickedSignal()( self )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/Gaffer/WeakMethod.py", line 67, in __call__
return m( *args, **kwArgs )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/DispatcherUI.py", line 239, in __executeClicked
_showDispatcherWindow( [ self.getPlug().node() ] )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/DispatcherUI.py", line 450, in _showDispatcherWindow
window = __dispatcherWindow( nodes[0].scriptNode() )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/DispatcherUI.py", line 444, in __dispatcherWindow
scriptWindow.addChildWindow( window )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/Window.py", line 171, in addChildWindow
oldParent = childWindow.parent()
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/Widget.py", line 290, in parent
parentWidget = q.parentWidget()
RuntimeError: underlying C/C++ object has been deleted
|
RuntimeError
|
def __show(self):
# we rebuild each menu every time it's shown, to support the use of callable items to provide
# dynamic submenus and item states.
self.__build(self._qtWidget(), self.__definition)
if self.__searchable:
# Searchable menus need to initialize a search structure so they can be searched without
# expanding each submenu. The definition is fully expanded, so dynamic submenus that
# exist will be expanded and searched.
self.__searchStructure = {}
self.__initSearch(self.__definition)
# Searchable menus require an extra submenu to display the search results.
searchWidget = QtGui.QWidgetAction(self._qtWidget())
searchWidget.setObjectName("GafferUI.Menu.__searchWidget")
self.__searchMenu = _Menu(self._qtWidget(), "")
self.__searchMenu.aboutToShow.connect(Gaffer.WeakMethod(self.__searchMenuShow))
self.__searchLine = QtGui.QLineEdit()
self.__searchLine.textEdited.connect(Gaffer.WeakMethod(self.__updateSearchMenu))
self.__searchLine.returnPressed.connect(
Gaffer.WeakMethod(self.__searchReturnPressed)
)
self.__searchLine.setObjectName("search")
if hasattr(self.__searchLine, "setPlaceholderText"):
# setPlaceHolderText appeared in qt 4.7, nuke (6.3 at time of writing) is stuck on 4.6.
self.__searchLine.setPlaceholderText("Search...")
if self.__lastAction:
self.__searchLine.setText(self.__lastAction.text())
self.__searchMenu.setDefaultAction(self.__lastAction)
self.__searchLine.selectAll()
searchWidget.setDefaultWidget(self.__searchLine)
firstAction = (
self._qtWidget().actions()[0] if len(self._qtWidget().actions()) else None
)
self._qtWidget().insertAction(firstAction, searchWidget)
self._qtWidget().insertSeparator(firstAction)
self._qtWidget().setActiveAction(searchWidget)
self.__searchLine.setFocus()
|
def __show(self):
# we rebuild each menu every time it's shown, to support the use of callable items to provide
# dynamic submenus and item states.
self.__build(self._qtWidget(), self.__definition)
if self.__searchable:
# Searchable menus need to initialize a search structure so they can be searched without
# expanding each submenu. The definition is fully expanded, so dynamic submenus that
# exist will be expanded and searched.
self.__searchStructure = {}
self.__initSearch(self.__definition)
# Searchable menus require an extra submenu to display the search results.
searchWidget = QtGui.QWidgetAction(self._qtWidget())
searchWidget.setObjectName("GafferUI.Menu.__searchWidget")
self.__searchMenu = _Menu(self._qtWidget(), "")
self.__searchMenu.aboutToShow.connect(Gaffer.WeakMethod(self.__searchMenuShow))
self.__searchLine = QtGui.QLineEdit()
self.__searchLine.textEdited.connect(Gaffer.WeakMethod(self.__updateSearchMenu))
self.__searchLine.returnPressed.connect(
Gaffer.WeakMethod(self.__searchReturnPressed)
)
self.__searchLine.setObjectName("search")
if hasattr(self.__searchLine, "setPlaceholderText"):
# setPlaceHolderText appeared in qt 4.7, nuke (6.3 at time of writing) is stuck on 4.6.
self.__searchLine.setPlaceholderText("Search...")
if self.__lastAction:
self.__searchLine.setText(self.__lastAction.text())
self.__searchMenu.setDefaultAction(self.__lastAction)
self.__searchLine.selectAll()
searchWidget.setDefaultWidget(self.__searchLine)
firstAction = self._qtWidget().actions()[0]
self._qtWidget().insertAction(firstAction, searchWidget)
self._qtWidget().insertSeparator(firstAction)
self._qtWidget().setActiveAction(searchWidget)
self.__searchLine.setFocus()
|
https://github.com/GafferHQ/gaffer/issues/527
|
Traceback (most recent call last):
File ".../python/Gaffer/WeakMethod.py", line 57, in __call__
return m( *args, **kwArgs )
File ".../python/GafferUI/Menu.py", line 182, in __show
firstAction = self._qtWidget().actions()[0]
IndexError: list index out of range
|
IndexError
|
def __init__(self, plug, **kw):
GafferUI.CompoundNumericPlugValueWidget.__init__(self, plug, **kw)
self.__swatch = GafferUI.ColorSwatch()
## \todo How do set maximum height with a public API?
self.__swatch._qtWidget().setMaximumHeight(20)
self._row().append(self.__swatch, expand=True)
self.__buttonPressConnection = self.__swatch.buttonPressSignal().connect(
Gaffer.WeakMethod(self.__buttonPress)
)
self.__colorChooserDialogue = None
self.__blinkBehaviour = None
self._updateFromPlug()
|
def __init__(self, plug, **kw):
GafferUI.CompoundNumericPlugValueWidget.__init__(self, plug, **kw)
self.__swatch = GafferUI.ColorSwatch()
## \todo How do set maximum height with a public API?
self.__swatch._qtWidget().setMaximumHeight(20)
self._row().append(self.__swatch, expand=True)
self.__buttonPressConnection = self.__swatch.buttonPressSignal().connect(
Gaffer.WeakMethod(self.__buttonPress)
)
self.__colorChooserDialogue = None
self._updateFromPlug()
|
https://github.com/GafferHQ/gaffer/issues/185
|
# Traceback (most recent call last):
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/Widget.py", line 1458, in eventFilter
# return self.__mouseMove( qObject, qEvent )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/Widget.py", line 1603, in __mouseMove
# return widget._mouseMoveSignal( widget, event )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/Gaffer/WeakMethod.py", line 57, in __call__
# return m( *args, **kwArgs )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/Slider.py", line 146, in __mouseMove
# self.setPosition( float( event.line.p0.x ) / self.size().x )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/NumericSlider.py", line 73, in setPosition
# self.setValue( self.__min + position * ( self.__max - self.__min ) )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/NumericSlider.py", line 90, in setValue
# signal( self )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/Gaffer/WeakMethod.py", line 57, in __call__
# return m( *args, **kwArgs )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/ColorChooser.py", line 203, in __sliderChanged
# self.setColor( newColor )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/ColorChooser.py", line 174, in setColor
# self.__colorChangedSignal( self )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/Gaffer/WeakMethod.py", line 57, in __call__
# return m( *args, **kwArgs )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/ColorPlugValueWidget.py", line 131, in __colorChanged
# self.__plug.setValue( self.colorChooser().getColor() )
# RuntimeError: Exception : Cannot set value for plug "ShaderGraphApp.scripts.ScriptNode.PublicParameters.ieSimpleSurface.parameters.diffuseTint.r" except during computation.
|
RuntimeError
|
def __buttonPress(self, widget, event):
if not self._editable():
if self.__blinkBehaviour is not None:
self.__blinkBehaviour.stop()
widgets = [w for w in self._row()[: len(self.getPlug())] if not w._editable()]
self.__blinkBehaviour = _BlinkBehaviour(widgets)
self.__blinkBehaviour.start()
return False
# we only store a weak reference to the dialogue, because we want to allow it
# to manage its own lifetime. this allows it to exist after we've died, which
# can be useful for the user - they can bring up a node editor to get access to
# the color chooser, and then close the node editor but keep the floating color
# chooser. the only reason we keep a reference to the dialogue at all is so that
# we can avoid opening two at the same time.
if self.__colorChooserDialogue is None or self.__colorChooserDialogue() is None:
self.__colorChooserDialogue = weakref.ref(
_ColorPlugValueDialogue(self.getPlug(), self.ancestor(GafferUI.Window))
)
self.__colorChooserDialogue().setVisible(True)
return True
|
def __buttonPress(self, widget, event):
if not self._editable():
return False
# we only store a weak reference to the dialogue, because we want to allow it
# to manage its own lifetime. this allows it to exist after we've died, which
# can be useful for the user - they can bring up a node editor to get access to
# the color chooser, and then close the node editor but keep the floating color
# chooser. the only reason we keep a reference to the dialogue at all is so that
# we can avoid opening two at the same time.
if self.__colorChooserDialogue is None or self.__colorChooserDialogue() is None:
self.__colorChooserDialogue = weakref.ref(
_ColorPlugValueDialogue(self.getPlug(), self.ancestor(GafferUI.Window))
)
self.__colorChooserDialogue().setVisible(True)
return True
|
https://github.com/GafferHQ/gaffer/issues/185
|
# Traceback (most recent call last):
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/Widget.py", line 1458, in eventFilter
# return self.__mouseMove( qObject, qEvent )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/Widget.py", line 1603, in __mouseMove
# return widget._mouseMoveSignal( widget, event )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/Gaffer/WeakMethod.py", line 57, in __call__
# return m( *args, **kwArgs )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/Slider.py", line 146, in __mouseMove
# self.setPosition( float( event.line.p0.x ) / self.size().x )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/NumericSlider.py", line 73, in setPosition
# self.setValue( self.__min + position * ( self.__max - self.__min ) )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/NumericSlider.py", line 90, in setValue
# signal( self )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/Gaffer/WeakMethod.py", line 57, in __call__
# return m( *args, **kwArgs )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/ColorChooser.py", line 203, in __sliderChanged
# self.setColor( newColor )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/ColorChooser.py", line 174, in setColor
# self.__colorChangedSignal( self )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/Gaffer/WeakMethod.py", line 57, in __call__
# return m( *args, **kwArgs )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/ColorPlugValueWidget.py", line 131, in __colorChanged
# self.__plug.setValue( self.colorChooser().getColor() )
# RuntimeError: Exception : Cannot set value for plug "ShaderGraphApp.scripts.ScriptNode.PublicParameters.ieSimpleSurface.parameters.diffuseTint.r" except during computation.
|
RuntimeError
|
def __init__(self, targetWidgets, blinks=2):
self.__targetWidgets = [weakref.ref(w) for w in targetWidgets]
self.__initialStates = [w.getHighlighted() for w in targetWidgets]
self.__blinks = blinks
self.__toggleCount = 0
self.__timer = QtCore.QTimer()
self.__timer.timeout.connect(self.__blink)
|
def __init__(self, plug, parentWindow):
GafferUI.ColorChooserDialogue.__init__(
self,
title=plug.relativeName(plug.ancestor(Gaffer.ScriptNode.staticTypeId())),
color=plug.getValue(),
)
self.__plug = plug
node = plug.node()
self.__nodeParentChangedConnection = node.parentChangedSignal().connect(
Gaffer.WeakMethod(self.__destroy)
)
self.__plugSetConnection = (
plug.node().plugSetSignal().connect(Gaffer.WeakMethod(self.__plugSet))
)
self.__closedConnection = self.closedSignal().connect(
Gaffer.WeakMethod(self.__destroy)
)
self.__colorChangedConnection = (
self.colorChooser()
.colorChangedSignal()
.connect(Gaffer.WeakMethod(self.__colorChanged))
)
self.__confirmClickedConnection = self.confirmButton.clickedSignal().connect(
Gaffer.WeakMethod(self.__buttonClicked)
)
self.__cancelClickedConnection = self.cancelButton.clickedSignal().connect(
Gaffer.WeakMethod(self.__buttonClicked)
)
parentWindow.addChildWindow(self)
|
https://github.com/GafferHQ/gaffer/issues/185
|
# Traceback (most recent call last):
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/Widget.py", line 1458, in eventFilter
# return self.__mouseMove( qObject, qEvent )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/Widget.py", line 1603, in __mouseMove
# return widget._mouseMoveSignal( widget, event )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/Gaffer/WeakMethod.py", line 57, in __call__
# return m( *args, **kwArgs )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/Slider.py", line 146, in __mouseMove
# self.setPosition( float( event.line.p0.x ) / self.size().x )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/NumericSlider.py", line 73, in setPosition
# self.setValue( self.__min + position * ( self.__max - self.__min ) )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/NumericSlider.py", line 90, in setValue
# signal( self )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/Gaffer/WeakMethod.py", line 57, in __call__
# return m( *args, **kwArgs )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/ColorChooser.py", line 203, in __sliderChanged
# self.setColor( newColor )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/ColorChooser.py", line 174, in setColor
# self.__colorChangedSignal( self )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/Gaffer/WeakMethod.py", line 57, in __call__
# return m( *args, **kwArgs )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/ColorPlugValueWidget.py", line 131, in __colorChanged
# self.__plug.setValue( self.colorChooser().getColor() )
# RuntimeError: Exception : Cannot set value for plug "ShaderGraphApp.scripts.ScriptNode.PublicParameters.ieSimpleSurface.parameters.diffuseTint.r" except during computation.
|
RuntimeError
|
def main():
execution_dir = getcwd()
# By default insert the execution path (useful to be able to execute Errbot from
# the source tree directly without installing it.
sys.path.insert(0, execution_dir)
parser = argparse.ArgumentParser(description="The main entry point of the errbot.")
parser.add_argument(
"-c",
"--config",
default=None,
help="Full path to your config.py (default: config.py in current working directory).",
)
mode_selection = parser.add_mutually_exclusive_group()
mode_selection.add_argument(
"-v", "--version", action="version", version=f"Errbot version {VERSION}"
)
mode_selection.add_argument(
"-r",
"--restore",
nargs="?",
default=None,
const="default",
help="restore a bot from backup.py (default: backup.py from the bot data directory)",
)
mode_selection.add_argument(
"-l", "--list", action="store_true", help="list all available backends"
)
mode_selection.add_argument(
"--new-plugin",
nargs="?",
default=None,
const="current_dir",
help="create a new plugin in the specified directory",
)
mode_selection.add_argument(
"-i",
"--init",
nargs="?",
default=None,
const=".",
help="Initialize a simple bot minimal configuration in the optionally "
"given directory (otherwise it will be the working directory). "
"This will create a data subdirectory for the bot data dir and a plugins directory"
" for your plugin development with an example in it to get you started.",
)
# storage manipulation
mode_selection.add_argument(
"--storage-set",
nargs=1,
help="DANGER: Delete the given storage namespace "
"and set the python dictionary expression "
"passed on stdin.",
)
mode_selection.add_argument(
"--storage-merge",
nargs=1,
help="DANGER: Merge in the python dictionary expression "
"passed on stdin into the given storage namespace.",
)
mode_selection.add_argument(
"--storage-get",
nargs=1,
help="Dump the given storage namespace in a "
"format compatible for --storage-set and "
"--storage-merge.",
)
mode_selection.add_argument(
"-T",
"--text",
dest="backend",
action="store_const",
const="Text",
help="force local text backend",
)
if not ON_WINDOWS:
option_group = parser.add_argument_group("optional daemonization arguments")
option_group.add_argument(
"-d",
"--daemon",
action="store_true",
help="Detach the process from the console",
)
option_group.add_argument(
"-p",
"--pidfile",
default=None,
help="Specify the pid file for the daemon (default: current bot data directory)",
)
args = vars(parser.parse_args()) # create a dictionary of args
if args["init"]:
try:
import pathlib
import shutil
import jinja2
base_dir = pathlib.Path.cwd() if args["init"] == "." else Path(args["init"])
if not base_dir.exists():
print(f"Target directory {base_dir} must exist. Please create it.")
data_dir = base_dir / "data"
extra_plugin_dir = base_dir / "plugins"
example_plugin_dir = base_dir / extra_plugin_dir / "err-example"
log_path = base_dir / "errbot.log"
templates_dir = Path(os.path.dirname(__file__)) / "templates" / "initdir"
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(str(templates_dir)), autoescape=True
)
config_template = env.get_template("config.py.tmpl")
data_dir.mkdir(exist_ok=True)
extra_plugin_dir.mkdir(exist_ok=True)
example_plugin_dir.mkdir(exist_ok=True)
with open(base_dir / "config.py", "w") as f:
f.write(
config_template.render(
data_dir=str(data_dir),
extra_plugin_dir=str(extra_plugin_dir),
log_path=str(log_path),
)
)
shutil.copyfile(
templates_dir / "example.plug", example_plugin_dir / "example.plug"
)
shutil.copyfile(
templates_dir / "example.py", example_plugin_dir / "example.py"
)
print("Your Errbot directory has been correctly initialized!")
if base_dir == pathlib.Path.cwd():
print('Just do "errbot" and it should start in text/development mode.')
else:
print(
f'Just do "cd {args["init"]}" then "errbot" and it should start in text/development mode.'
)
sys.exit(0)
except Exception as e:
print(f"The initialization of your errbot directory failed: {e}.")
sys.exit(1)
# This must come BEFORE the config is loaded below, to avoid printing
# logs as a side effect of config loading.
if args["new_plugin"]:
directory = (
os.getcwd() if args["new_plugin"] == "current_dir" else args["new_plugin"]
)
for handler in logging.getLogger().handlers:
root_logger.removeHandler(handler)
try:
new_plugin_wizard(directory)
except KeyboardInterrupt:
sys.exit(1)
except Exception as e:
sys.stderr.write(str(e) + "\n")
sys.exit(1)
finally:
sys.exit(0)
config_path = args["config"]
# setup the environment to be able to import the config.py
if config_path:
# appends the current config in order to find config.py
sys.path.insert(0, path.dirname(path.abspath(config_path)))
else:
config_path = execution_dir + sep + "config.py"
config = get_config(config_path) # will exit if load fails
# Extra backend is expected to be a list type, convert string to list.
extra_backend = getattr(config, "BOT_EXTRA_BACKEND_DIR", [])
if isinstance(extra_backend, str):
extra_backend = [extra_backend]
if args["list"]:
from errbot.backend_plugin_manager import enumerate_backend_plugins
print("Available backends:")
roots = [CORE_BACKENDS] + extra_backend
for backend in enumerate_backend_plugins(collect_roots(roots)):
print(f"\t\t{backend.name}")
sys.exit(0)
def storage_action(namespace, fn):
# Used to defer imports until it is really necessary during the loading time.
from errbot.bootstrap import get_storage_plugin
from errbot.storage import StoreMixin
try:
with StoreMixin() as sdm:
sdm.open_storage(get_storage_plugin(config), namespace)
fn(sdm)
return 0
except Exception as e:
print(str(e), file=sys.stderr)
return -3
if args["storage_get"]:
def p(sdm):
print(repr(dict(sdm)))
err_value = storage_action(args["storage_get"][0], p)
sys.exit(err_value)
if args["storage_set"]:
def replace(sdm):
new_dict = (
_read_dict()
) # fail early and don't erase the storage if the input is invalid.
sdm.clear()
sdm.update(new_dict)
err_value = storage_action(args["storage_set"][0], replace)
sys.exit(err_value)
if args["storage_merge"]:
def merge(sdm):
from deepmerge import always_merger
new_dict = _read_dict()
for key, value in new_dict.items():
with sdm.mutable(key, {}) as conf:
always_merger.merge(conf, value)
err_value = storage_action(args["storage_merge"][0], merge)
sys.exit(err_value)
if args["restore"]:
backend = "Null" # we don't want any backend when we restore
elif args["backend"] is None:
if not hasattr(config, "BACKEND"):
log.fatal("The BACKEND configuration option is missing in config.py")
sys.exit(1)
backend = config.BACKEND
else:
backend = args["backend"]
log.info(f"Selected backend {backend}.")
# Check if at least we can start to log something before trying to start
# the bot (esp. daemonize it).
log.info(f"Checking for {config.BOT_DATA_DIR}...")
if not path.exists(config.BOT_DATA_DIR):
raise Exception(
f'The data directory "{config.BOT_DATA_DIR}" for the bot does not exist.'
)
if not access(config.BOT_DATA_DIR, W_OK):
raise Exception(
f'The data directory "{config.BOT_DATA_DIR}" should be writable for the bot.'
)
if (not ON_WINDOWS) and args["daemon"]:
if args["backend"] == "Text":
raise Exception("You cannot run in text and daemon mode at the same time")
if args["restore"]:
raise Exception("You cannot restore a backup in daemon mode.")
if args["pidfile"]:
pid = args["pidfile"]
else:
pid = config.BOT_DATA_DIR + sep + "err.pid"
# noinspection PyBroadException
try:
def action():
from errbot.bootstrap import bootstrap
bootstrap(backend, root_logger, config)
daemon = Daemonize(app="err", pid=pid, action=action, chdir=os.getcwd())
log.info("Daemonizing")
daemon.start()
except Exception:
log.exception("Failed to daemonize the process")
exit(0)
from errbot.bootstrap import bootstrap
restore = args["restore"]
if restore == "default": # restore with no argument, get the default location
restore = path.join(config.BOT_DATA_DIR, "backup.py")
bootstrap(backend, root_logger, config, restore)
log.info("Process exiting")
|
def main():
execution_dir = getcwd()
# By default insert the execution path (useful to be able to execute Errbot from
# the source tree directly without installing it.
sys.path.insert(0, execution_dir)
parser = argparse.ArgumentParser(description="The main entry point of the errbot.")
parser.add_argument(
"-c",
"--config",
default=None,
help="Full path to your config.py (default: config.py in current working directory).",
)
mode_selection = parser.add_mutually_exclusive_group()
mode_selection.add_argument(
"-v", "--version", action="version", version=f"Errbot version {VERSION}"
)
mode_selection.add_argument(
"-r",
"--restore",
nargs="?",
default=None,
const="default",
help="restore a bot from backup.py (default: backup.py from the bot data directory)",
)
mode_selection.add_argument(
"-l", "--list", action="store_true", help="list all available backends"
)
mode_selection.add_argument(
"--new-plugin",
nargs="?",
default=None,
const="current_dir",
help="create a new plugin in the specified directory",
)
mode_selection.add_argument(
"-i",
"--init",
nargs="?",
default=None,
const=".",
help="Initialize a simple bot minimal configuration in the optionally "
"given directory (otherwise it will be the working directory). "
"This will create a data subdirectory for the bot data dir and a plugins directory"
" for your plugin development with an example in it to get you started.",
)
# storage manipulation
mode_selection.add_argument(
"--storage-set",
nargs=1,
help="DANGER: Delete the given storage namespace "
"and set the python dictionary expression "
"passed on stdin.",
)
mode_selection.add_argument(
"--storage-merge",
nargs=1,
help="DANGER: Merge in the python dictionary expression "
"passed on stdin into the given storage namespace.",
)
mode_selection.add_argument(
"--storage-get",
nargs=1,
help="Dump the given storage namespace in a "
"format compatible for --storage-set and "
"--storage-merge.",
)
mode_selection.add_argument(
"-T",
"--text",
dest="backend",
action="store_const",
const="Text",
help="force local text backend",
)
mode_selection.add_argument(
"-G",
"--graphic",
dest="backend",
action="store_const",
const="Graphic",
help="force local graphical backend",
)
if not ON_WINDOWS:
option_group = parser.add_argument_group("optional daemonization arguments")
option_group.add_argument(
"-d",
"--daemon",
action="store_true",
help="Detach the process from the console",
)
option_group.add_argument(
"-p",
"--pidfile",
default=None,
help="Specify the pid file for the daemon (default: current bot data directory)",
)
args = vars(parser.parse_args()) # create a dictionary of args
if args["init"]:
try:
import pathlib
import shutil
import jinja2
base_dir = pathlib.Path.cwd() if args["init"] == "." else Path(args["init"])
if not base_dir.exists():
print(f"Target directory {base_dir} must exist. Please create it.")
data_dir = base_dir / "data"
extra_plugin_dir = base_dir / "plugins"
example_plugin_dir = base_dir / extra_plugin_dir / "err-example"
log_path = base_dir / "errbot.log"
templates_dir = Path(os.path.dirname(__file__)) / "templates" / "initdir"
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(str(templates_dir)), autoescape=True
)
config_template = env.get_template("config.py.tmpl")
data_dir.mkdir(exist_ok=True)
extra_plugin_dir.mkdir(exist_ok=True)
example_plugin_dir.mkdir(exist_ok=True)
with open(base_dir / "config.py", "w") as f:
f.write(
config_template.render(
data_dir=str(data_dir),
extra_plugin_dir=str(extra_plugin_dir),
log_path=str(log_path),
)
)
shutil.copyfile(
templates_dir / "example.plug", example_plugin_dir / "example.plug"
)
shutil.copyfile(
templates_dir / "example.py", example_plugin_dir / "example.py"
)
print("Your Errbot directory has been correctly initialized!")
if base_dir == pathlib.Path.cwd():
print('Just do "errbot" and it should start in text/development mode.')
else:
print(
f'Just do "cd {args["init"]}" then "errbot" and it should start in text/development mode.'
)
sys.exit(0)
except Exception as e:
print(f"The initialization of your errbot directory failed: {e}.")
sys.exit(1)
# This must come BEFORE the config is loaded below, to avoid printing
# logs as a side effect of config loading.
if args["new_plugin"]:
directory = (
os.getcwd() if args["new_plugin"] == "current_dir" else args["new_plugin"]
)
for handler in logging.getLogger().handlers:
root_logger.removeHandler(handler)
try:
new_plugin_wizard(directory)
except KeyboardInterrupt:
sys.exit(1)
except Exception as e:
sys.stderr.write(str(e) + "\n")
sys.exit(1)
finally:
sys.exit(0)
config_path = args["config"]
# setup the environment to be able to import the config.py
if config_path:
# appends the current config in order to find config.py
sys.path.insert(0, path.dirname(path.abspath(config_path)))
else:
config_path = execution_dir + sep + "config.py"
config = get_config(config_path) # will exit if load fails
# Extra backend is expected to be a list type, convert string to list.
extra_backend = getattr(config, "BOT_EXTRA_BACKEND_DIR", [])
if isinstance(extra_backend, str):
extra_backend = [extra_backend]
if args["list"]:
from errbot.backend_plugin_manager import enumerate_backend_plugins
print("Available backends:")
roots = [CORE_BACKENDS] + extra_backend
for backend in enumerate_backend_plugins(collect_roots(roots)):
print(f"\t\t{backend.name}")
sys.exit(0)
def storage_action(namespace, fn):
# Used to defer imports until it is really necessary during the loading time.
from errbot.bootstrap import get_storage_plugin
from errbot.storage import StoreMixin
try:
with StoreMixin() as sdm:
sdm.open_storage(get_storage_plugin(config), namespace)
fn(sdm)
return 0
except Exception as e:
print(str(e), file=sys.stderr)
return -3
if args["storage_get"]:
def p(sdm):
print(repr(dict(sdm)))
err_value = storage_action(args["storage_get"][0], p)
sys.exit(err_value)
if args["storage_set"]:
def replace(sdm):
new_dict = (
_read_dict()
) # fail early and don't erase the storage if the input is invalid.
sdm.clear()
sdm.update(new_dict)
err_value = storage_action(args["storage_set"][0], replace)
sys.exit(err_value)
if args["storage_merge"]:
def merge(sdm):
from deepmerge import always_merger
new_dict = _read_dict()
for key, value in new_dict.items():
with sdm.mutable(key, {}) as conf:
always_merger.merge(conf, value)
err_value = storage_action(args["storage_merge"][0], merge)
sys.exit(err_value)
if args["restore"]:
backend = "Null" # we don't want any backend when we restore
elif args["backend"] is None:
if not hasattr(config, "BACKEND"):
log.fatal("The BACKEND configuration option is missing in config.py")
sys.exit(1)
backend = config.BACKEND
else:
backend = args["backend"]
log.info(f"Selected backend {backend}.")
# Check if at least we can start to log something before trying to start
# the bot (esp. daemonize it).
log.info(f"Checking for {config.BOT_DATA_DIR}...")
if not path.exists(config.BOT_DATA_DIR):
raise Exception(
f'The data directory "{config.BOT_DATA_DIR}" for the bot does not exist.'
)
if not access(config.BOT_DATA_DIR, W_OK):
raise Exception(
f'The data directory "{config.BOT_DATA_DIR}" should be writable for the bot.'
)
if (not ON_WINDOWS) and args["daemon"]:
if args["backend"] == "Text":
raise Exception("You cannot run in text and daemon mode at the same time")
if args["restore"]:
raise Exception("You cannot restore a backup in daemon mode.")
if args["pidfile"]:
pid = args["pidfile"]
else:
pid = config.BOT_DATA_DIR + sep + "err.pid"
# noinspection PyBroadException
try:
def action():
from errbot.bootstrap import bootstrap
bootstrap(backend, root_logger, config)
daemon = Daemonize(app="err", pid=pid, action=action, chdir=os.getcwd())
log.info("Daemonizing")
daemon.start()
except Exception:
log.exception("Failed to daemonize the process")
exit(0)
from errbot.bootstrap import bootstrap
restore = args["restore"]
if restore == "default": # restore with no argument, get the default location
restore = path.join(config.BOT_DATA_DIR, "backup.py")
bootstrap(backend, root_logger, config, restore)
log.info("Process exiting")
|
https://github.com/errbotio/errbot/issues/1491
|
2020-12-18 16:30:28,869 INFO errbot.bootstrap Found Storage plugin: Shelf.
2020-12-18 16:30:28,874 INFO errbot.bootstrap Found Backend plugin: Graphic
Bot-Kennedy
2020-12-18 16:30:28,946 ERROR errbot.backends.graphic Could not start the graphical backend
Traceback (most recent call last):
File "...\venv\lib\site-packages\errbot\backends\graphic.py", line 18, in <module>
from PySide import QtCore, QtGui, QtWebKit
ModuleNotFoundError: No module named 'PySide'
2020-12-18 16:30:28,946 CRITICAL errbot.backends.graphic To install graphic support use:
pip install errbot[graphic]
|
ModuleNotFoundError
|
def uninstall_repo(self, name):
repo_path = path.join(self.plugin_dir, name)
shutil.rmtree(
repo_path, ignore_errors=True
) # ignore errors because the DB can be desync'ed from the file tree.
repos = self.get_installed_plugin_repos()
del repos[name]
self.set_plugin_repos(repos)
|
def uninstall_repo(self, name):
repo_path = path.join(self.plugin_dir, name)
shutil.rmtree(repo_path)
repos = self.get_installed_plugin_repos().pop(name)
self.set_plugin_repos(repos)
|
https://github.com/errbotio/errbot/issues/674
|
20:25:29 DEBUG errbot.errBot Initializing backend storage
20:25:29 DEBUG errbot.storage Opening storage telegram_backend
20:25:29 DEBUG errbot.storage.shelf Open shelf storage /tmp/errbot-data/telegram_backend.db
Traceback (most recent call last):
File "/home/zoni/.virtualenvs/err/bin/errbot", line 9, in <module>
load_entry_point('errbot', 'console_scripts', 'errbot')()
File "/home/zoni/Workspace/Projects/err/errbot/err.py", line 261, in main
main(backend, logger, config, restore)
File "/home/zoni/Workspace/Projects/err/errbot/main.py", line 134, in main
bot = setup_bot(bot_class, logger, config, restore)
File "/home/zoni/Workspace/Projects/err/errbot/main.py", line 108, in setup_bot
errors = bot.plugin_manager.update_dynamic_plugins()
File "/home/zoni/Workspace/Projects/err/errbot/plugin_manager.py", line 423, in update_dynamic_plugins
return self.update_plugin_places(self.repo_manager.get_all_repos_paths(), self.extra, self.autoinstall_deps)
File "/home/zoni/Workspace/Projects/err/errbot/repo_manager.py", line 170, in get_all_repos_paths
return [os.path.join(self.plugin_dir, d) for d in self.get(INSTALLED_REPOS, {}).keys()]
AttributeError: 'str' object has no attribute 'keys'
|
AttributeError
|
def __init__(self, config):
super().__init__(config)
identity = config.BOT_IDENTITY
self.token = identity.get("token", None)
if not self.token:
log.fatal(
'You need to set your token (found under "Bot Integration" on Slack) in '
"the BOT_IDENTITY setting in your configuration. Without this token I "
"cannot connect to Slack."
)
sys.exit(1)
self.sc = None # Will be initialized in serve_once
|
def __init__(self, config):
super().__init__(config)
identity = config.BOT_IDENTITY
self.token = identity.get("token", None)
if not self.token:
log.fatal(
'You need to set your token (found under "Bot Integration" on Slack) in '
"the BOT_IDENTITY setting in your configuration. Without this token I "
"cannot connect to Slack."
)
sys.exit(1)
self.sc = SlackClient(self.token)
|
https://github.com/errbotio/errbot/issues/379
|
(err)whiskeyriver@whiskeyriver-VirtualBox:~/Code/err$ err.py -S
15:30:01 INFO __main__ Config check passed...
15:30:02 INFO __main__ Checking for '/home/whiskeyriver/Code/err/data'...
15:30:02 DEBUG errbot.errBot ErrBot init.
15:30:02 INFO errbot.storage Opened shelf of SlackBackend at /home/whiskeyriver/Code/err/data/core.db
15:30:02 DEBUG errbot.backends.base created the thread pool<errbot.bundled.threadpool.ThreadPool object at 0x7f453284e8d0>
15:30:02 DEBUG errbot.plugin_manager check dependencies of /home/whiskeyriver/Code/err/errbot/core_plugins
15:30:02 DEBUG errbot.plugin_manager /home/whiskeyriver/Code/err/errbot/core_plugins has no requirements.txt file
15:30:02 DEBUG errbot.plugin_manager plugin __init__(args=['self', 'bot'], argslist=None, kwargs=None)
15:30:02 INFO errbot.storage Init shelf of ChatRoom
15:30:02 DEBUG errbot.plugin_manager plugin __init__(args=['self', 'bot'], argslist=None, kwargs=None)
15:30:02 INFO errbot.storage Init shelf of Backup
15:30:02 DEBUG errbot.plugin_manager plugin __init__(args=['self', 'bot'], argslist=None, kwargs=None)
15:30:02 INFO errbot.storage Init shelf of VersionChecker
15:30:02 INFO errbot.decorators webhooks: Flag to bind /echo/ to echo
15:30:02 DEBUG errbot.plugin_manager plugin __init__(args=['self', 'bot'], argslist=None, kwargs=None)
15:30:02 INFO errbot.storage Init shelf of Webserver
15:30:02 DEBUG errbot.main serve from <errbot.backends.slack.SlackBackend object at 0x7f453284e710>
15:30:02 INFO errbot.backends.slack Verifying authentication token
15:30:03 DEBUG errbot.backends.slack Token accepted
15:30:03 INFO errbot.backends.slack Connecting to Slack real-time-messaging API
15:30:04 INFO errbot.backends.slack Connected
15:30:05 DEBUG errbot.backends.slack Processing slack event: {'type': 'hello'}
15:30:05 INFO errbot.errBot Activate internal commands
15:30:05 INFO errbot.errBot Activating all the plugins...
15:30:05 INFO errbot.errBot Activate plugin: Webserver
15:30:05 INFO errbot.plugin_manager Activating Webserver with min_err_version = 2.2.1 and max_version = 2.2.1
15:30:05 DEBUG errbot.templating Templates directory found for this plugin [/home/whiskeyriver/Code/err/errbot/core_plugins/templates]
15:30:05 INFO yapsy_loaded_plugin_Webse Webserver is not configured. Forbid activation
15:30:05 INFO errbot.core_plugins.wsvie Checking Webserver for webhooks
15:30:05 INFO errbot.core_plugins.wsvie ... Routing echo
15:30:05 INFO errbot.errBot Activate plugin: Backup
15:30:05 INFO errbot.plugin_manager Activating Backup with min_err_version = None and max_version = None
15:30:05 DEBUG errbot.templating Templates directory found for this plugin [/home/whiskeyriver/Code/err/errbot/core_plugins/templates]
15:30:05 DEBUG errbot.botplugin Init storage for Backup
15:30:05 DEBUG errbot.botplugin Loading /home/whiskeyriver/Code/err/data/plugins/Backup.db
15:30:05 INFO errbot.storage Opened shelf of Backup at /home/whiskeyriver/Code/err/data/plugins/Backup.db
15:30:05 DEBUG errbot.backends.base Adding command : backup -> backup
15:30:05 INFO errbot.core_plugins.wsvie Checking Backup for webhooks
15:30:05 INFO errbot.errBot Activate plugin: ChatRoom
15:30:05 INFO errbot.plugin_manager Activating ChatRoom with min_err_version = 2.2.1 and max_version = 2.2.1
15:30:05 DEBUG errbot.templating Templates directory found for this plugin [/home/whiskeyriver/Code/err/errbot/core_plugins/templates]
15:30:05 DEBUG errbot.botplugin Init storage for ChatRoom
15:30:05 DEBUG errbot.botplugin Loading /home/whiskeyriver/Code/err/data/plugins/ChatRoom.db
15:30:05 INFO errbot.storage Opened shelf of ChatRoom at /home/whiskeyriver/Code/err/data/plugins/ChatRoom.db
15:30:05 DEBUG errbot.backends.base Adding command : gtalk_room_create -> gtalk_room_create
15:30:05 DEBUG errbot.backends.base Adding command : room_create -> room_create
15:30:05 DEBUG errbot.backends.base Adding command : room_destroy -> room_destroy
15:30:05 DEBUG errbot.backends.base Adding command : room_invite -> room_invite
15:30:05 DEBUG errbot.backends.base Adding command : room_join -> room_join
15:30:05 DEBUG errbot.backends.base Adding command : room_leave -> room_leave
15:30:05 DEBUG errbot.backends.base Adding command : room_list -> room_list
15:30:05 DEBUG errbot.backends.base Adding command : room_occupants -> room_occupants
15:30:05 DEBUG errbot.backends.base Adding command : room_topic -> room_topic
15:30:05 INFO errbot.core_plugins.wsvie Checking ChatRoom for webhooks
15:30:05 INFO errbot.errBot Activate plugin: VersionChecker
15:30:05 INFO errbot.plugin_manager Activating VersionChecker with min_err_version = 2.2.1 and max_version = 2.2.1
15:30:05 DEBUG errbot.templating Templates directory found for this plugin [/home/whiskeyriver/Code/err/errbot/core_plugins/templates]
15:30:05 DEBUG yapsy_loaded_plugin_Versi Checking version
15:30:06 DEBUG errbot.botplugin Programming the polling of version_check every 86400 seconds with args [] and kwargs {}
15:30:06 DEBUG errbot.botplugin Init storage for VersionChecker
15:30:06 DEBUG errbot.botplugin Loading /home/whiskeyriver/Code/err/data/plugins/VersionChecker.db
15:30:06 INFO errbot.storage Opened shelf of VersionChecker at /home/whiskeyriver/Code/err/data/plugins/VersionChecker.db
15:30:06 INFO errbot.core_plugins.wsvie Checking VersionChecker for webhooks
15:30:06 INFO errbot.errBot
15:30:06 INFO errbot.errBot Notifying connection to all the plugins...
15:30:06 DEBUG errbot.errBot Trigger callback_connect on Backup
15:30:06 DEBUG errbot.errBot Trigger callback_connect on ChatRoom
15:30:06 INFO yapsy_loaded_plugin_ChatR Callback_connect
15:30:06 DEBUG errbot.errBot Trigger callback_connect on VersionChecker
15:30:06 INFO errbot.errBot Plugin activation done.
15:30:06 DEBUG errbot.backends.base Adding command : about -> about
15:30:06 DEBUG errbot.backends.base Adding command : apropos -> apropos
15:30:06 DEBUG errbot.backends.base Adding command : blacklist -> blacklist
15:30:06 DEBUG errbot.backends.base Adding command : config -> config
15:30:06 DEBUG errbot.backends.base Adding command : echo -> echo
15:30:06 DEBUG errbot.backends.base Adding command : help -> help
15:30:06 DEBUG errbot.backends.base Adding command : history -> history
15:30:06 DEBUG errbot.backends.base Adding command : load -> load
15:30:06 DEBUG errbot.backends.base Adding command : log_tail -> log_tail
15:30:06 DEBUG errbot.backends.base Adding command : reload -> reload
15:30:06 DEBUG errbot.backends.base Adding command : repos -> repos
15:30:06 DEBUG errbot.backends.base Adding command : repos_install -> repos_install
15:30:06 DEBUG errbot.backends.base Adding command : repos_uninstall -> repos_uninstall
15:30:06 DEBUG errbot.backends.base Adding command : repos_update -> repos_update
15:30:06 DEBUG errbot.backends.base Adding command : restart -> restart
15:30:06 DEBUG errbot.backends.base Adding command : status -> status
15:30:06 DEBUG errbot.backends.base Adding command : status_gc -> status_gc
15:30:06 DEBUG errbot.backends.base Adding command : status_load -> status_load
15:30:06 DEBUG errbot.backends.base Adding command : status_plugins -> status_plugins
15:30:06 DEBUG errbot.backends.base Adding command : unblacklist -> unblacklist
15:30:06 DEBUG errbot.backends.base Adding command : unload -> unload
15:30:06 DEBUG errbot.backends.base Adding command : uptime -> uptime
15:30:06 DEBUG errbot.errBot Triggering callback_presence on Backup
15:30:06 DEBUG errbot.errBot Triggering callback_presence on ChatRoom
15:30:06 DEBUG errbot.errBot Triggering callback_presence on VersionChecker
15:30:07 DEBUG errbot.backends.slack Processing slack event: {'user': 'U00ERRBOT', 'text': 'Command "needs" / "needs some" not found.', 'reply_to': None, 'channel': 'C00000001', 'ts': '1433881703.000186', 'type': 'message'}
15:30:07 DEBUG errbot.backends.slack Handling message from a public channel
15:30:07 DEBUG errbot.backends.base *** jid = deployment@shinyservers/deploybot
15:30:07 DEBUG errbot.backends.base *** username = deploybot
15:30:07 DEBUG errbot.backends.base *** type = groupchat
15:30:07 DEBUG errbot.backends.base *** text = Command "needs" / "needs some" not found.
15:30:07 DEBUG errbot.errBot Trigger callback_message on Backup
15:30:07 DEBUG errbot.errBot Trigger callback_message on ChatRoom
15:30:07 DEBUG errbot.errBot Trigger callback_message on VersionChecker
15:30:10 DEBUG errbot.backends.slack No event handler available for user_typing, ignoring this event
15:30:12 DEBUG errbot.backends.slack Processing slack event: {'user': 'UWHSKYRVR', 'text': '!status', 'team': 'TSHNYSRVR', 'channel': 'G00000002', 'ts': '1433881812.000007', 'type': 'message'}
15:30:12 DEBUG errbot.backends.slack Handling message from a private group
15:30:12 DEBUG errbot.backends.base *** jid = test_deploy_bot@shinyservers/whiskeyriver
15:30:12 DEBUG errbot.backends.base *** username = whiskeyriver
15:30:12 DEBUG errbot.backends.base *** type = groupchat
15:30:12 DEBUG errbot.backends.base *** text = !status
15:30:12 INFO errbot.backends.base Processing command 'status' with parameters '' from test_deploy_bot@shinyservers/whiskeyriver/whiskeyriver
15:30:12 DEBUG errbot.errBot Trigger callback_message on Backup
15:30:12 DEBUG errbot.errBot Trigger callback_message on ChatRoom
15:30:12 DEBUG errbot.errBot Trigger callback_message on VersionChecker
15:30:12 DEBUG errbot.backends.slack Sending groupchat message to test_deploy_bot (G00000002)
15:30:13 DEBUG errbot.backends.slack Ignoring non-event message: {'ts': '1433881813.000008', 'ok': True, 'text': 'Yes I am alive... \n \n With these plugins (L=Loaded, U=Unloaded, B=Blacklisted, C=Needs to be configured):\n [L] Backup\n [L] ChatRoom\n [L] VersionChecker\n [C] Webserver\n \n Load 0.07, 0.04, 0.05\n GC 0-&gt;66 1-&gt;4 2-&gt;6', 'reply_to': None}
15:30:43 ERROR errbot.backends.slack Error reading from RTM stream:
Traceback (most recent call last):
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 142, in serve_once
for message in self.sc.rtm_read():
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/slackclient/_client.py", line 27, in rtm_read
json_data = self.server.websocket_safe_read()
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/slackclient/_server.py", line 109, in websocket_safe_read
data += "{}\n".format(self.websocket.recv())
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_core.py", line 348, in recv
opcode, data = self.recv_data()
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_core.py", line 365, in recv_data
opcode, frame = self.recv_data_frame(control_frame)
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_core.py", line 378, in recv_data_frame
frame = self.recv_frame()
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_core.py", line 410, in recv_frame
return self.frame_buffer.recv_frame()
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_abnf.py", line 300, in recv_frame
self.recv_header()
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_abnf.py", line 249, in recv_header
header = self.recv_strict(2)
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_abnf.py", line 334, in recv_strict
bytes = self.recv(min(16384, shortage))
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_core.py", line 476, in _recv
return recv(self.sock, bufsize)
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_socket.py", line 77, in recv
bytes = sock.recv(bufsize)
File "/usr/lib/python3.4/ssl.py", line 731, in recv
return self.read(buflen)
File "/usr/lib/python3.4/ssl.py", line 620, in read
v = self._sslobj.read(len or 1024)
ConnectionResetError: [Errno 104] Connection reset by peer
15:30:43 DEBUG errbot.backends.slack Triggering disconnect callback
15:30:43 INFO errbot.errBot Disconnect callback, deactivating all the plugins.
15:30:43 DEBUG errbot.storage Closed shelf of Backup
15:30:43 DEBUG errbot.storage Closed shelf of ChatRoom
15:30:43 DEBUG errbot.botplugin You still have active pollers at deactivation stage, I cleaned them up for you.
15:30:43 DEBUG errbot.storage Closed shelf of VersionChecker
15:30:43 INFO errbot.backends.base Reconnecting in 1 seconds (0 attempted reconnections so far)
15:30:44 INFO errbot.backends.slack Verifying authentication token
15:30:44 DEBUG errbot.backends.slack Token accepted
15:30:44 INFO errbot.backends.slack Connecting to Slack real-time-messaging API
15:30:45 INFO errbot.backends.slack Connected
15:30:46 DEBUG errbot.backends.slack Processing slack event: {'type': 'hello'}
15:30:46 INFO errbot.errBot Activate internal commands
15:30:46 INFO errbot.errBot Activating all the plugins...
15:30:46 INFO errbot.errBot Activate plugin: Webserver
15:30:46 INFO errbot.plugin_manager Activating Webserver with min_err_version = 2.2.1 and max_version = 2.2.1
15:30:46 DEBUG errbot.templating Templates directory found for this plugin [/home/whiskeyriver/Code/err/errbot/core_plugins/templates]
15:30:46 INFO yapsy_loaded_plugin_Webse Webserver is not configured. Forbid activation
15:30:46 INFO errbot.core_plugins.wsvie Checking Webserver for webhooks
15:30:46 INFO errbot.core_plugins.wsvie ... Routing echo
15:30:46 INFO errbot.errBot Activate plugin: Backup
15:30:46 INFO errbot.plugin_manager Activating Backup with min_err_version = None and max_version = None
15:30:46 DEBUG errbot.templating Templates directory found for this plugin [/home/whiskeyriver/Code/err/errbot/core_plugins/templates]
15:30:46 DEBUG errbot.botplugin Init storage for Backup
15:30:46 DEBUG errbot.botplugin Loading /home/whiskeyriver/Code/err/data/plugins/Backup.db
15:30:46 INFO errbot.storage Opened shelf of Backup at /home/whiskeyriver/Code/err/data/plugins/Backup.db
15:30:46 DEBUG errbot.backends.base Adding command : backup -> backup
15:30:46 INFO errbot.core_plugins.wsvie Checking Backup for webhooks
15:30:46 INFO errbot.errBot Activate plugin: ChatRoom
15:30:46 INFO errbot.plugin_manager Activating ChatRoom with min_err_version = 2.2.1 and max_version = 2.2.1
15:30:46 DEBUG errbot.templating Templates directory found for this plugin [/home/whiskeyriver/Code/err/errbot/core_plugins/templates]
15:30:46 DEBUG errbot.botplugin Init storage for ChatRoom
15:30:46 DEBUG errbot.botplugin Loading /home/whiskeyriver/Code/err/data/plugins/ChatRoom.db
15:30:46 INFO errbot.storage Opened shelf of ChatRoom at /home/whiskeyriver/Code/err/data/plugins/ChatRoom.db
15:30:46 DEBUG errbot.backends.base Adding command : gtalk_room_create -> gtalk_room_create
15:30:46 DEBUG errbot.backends.base Adding command : room_create -> room_create
15:30:46 DEBUG errbot.backends.base Adding command : room_destroy -> room_destroy
15:30:46 DEBUG errbot.backends.base Adding command : room_invite -> room_invite
15:30:46 DEBUG errbot.backends.base Adding command : room_join -> room_join
15:30:46 DEBUG errbot.backends.base Adding command : room_leave -> room_leave
15:30:46 DEBUG errbot.backends.base Adding command : room_list -> room_list
15:30:46 DEBUG errbot.backends.base Adding command : room_occupants -> room_occupants
15:30:46 DEBUG errbot.backends.base Adding command : room_topic -> room_topic
15:30:46 INFO errbot.core_plugins.wsvie Checking ChatRoom for webhooks
15:30:46 INFO errbot.errBot Activate plugin: VersionChecker
15:30:46 INFO errbot.plugin_manager Activating VersionChecker with min_err_version = 2.2.1 and max_version = 2.2.1
15:30:46 DEBUG errbot.templating Templates directory found for this plugin [/home/whiskeyriver/Code/err/errbot/core_plugins/templates]
15:30:46 DEBUG yapsy_loaded_plugin_Versi Checking version
15:30:47 DEBUG errbot.botplugin Programming the polling of version_check every 86400 seconds with args [] and kwargs {}
15:30:47 DEBUG errbot.botplugin Init storage for VersionChecker
15:30:47 DEBUG errbot.botplugin Loading /home/whiskeyriver/Code/err/data/plugins/VersionChecker.db
15:30:47 INFO errbot.storage Opened shelf of VersionChecker at /home/whiskeyriver/Code/err/data/plugins/VersionChecker.db
15:30:47 INFO errbot.core_plugins.wsvie Checking VersionChecker for webhooks
15:30:47 INFO errbot.errBot
15:30:47 INFO errbot.errBot Notifying connection to all the plugins...
15:30:47 DEBUG errbot.errBot Trigger callback_connect on Backup
15:30:47 DEBUG errbot.errBot Trigger callback_connect on ChatRoom
15:30:47 INFO yapsy_loaded_plugin_ChatR Callback_connect
15:30:47 DEBUG errbot.errBot Trigger callback_connect on VersionChecker
15:30:47 INFO errbot.errBot Plugin activation done.
15:30:47 DEBUG errbot.backends.base Adding command : about -> about
15:30:47 DEBUG errbot.backends.base Adding command : apropos -> apropos
15:30:47 DEBUG errbot.backends.base Adding command : blacklist -> blacklist
15:30:47 DEBUG errbot.backends.base Adding command : config -> config
15:30:47 DEBUG errbot.backends.base Adding command : echo -> echo
15:30:47 DEBUG errbot.backends.base Adding command : help -> help
15:30:47 DEBUG errbot.backends.base Adding command : history -> history
15:30:47 DEBUG errbot.backends.base Adding command : load -> load
15:30:47 DEBUG errbot.backends.base Adding command : log_tail -> log_tail
15:30:47 DEBUG errbot.backends.base Adding command : reload -> reload
15:30:47 DEBUG errbot.backends.base Adding command : repos -> repos
15:30:47 DEBUG errbot.backends.base Adding command : repos_install -> repos_install
15:30:47 DEBUG errbot.backends.base Adding command : repos_uninstall -> repos_uninstall
15:30:47 DEBUG errbot.backends.base Adding command : repos_update -> repos_update
15:30:47 DEBUG errbot.backends.base Adding command : restart -> restart
15:30:47 DEBUG errbot.backends.base Adding command : status -> status
15:30:47 DEBUG errbot.backends.base Adding command : status_gc -> status_gc
15:30:47 DEBUG errbot.backends.base Adding command : status_load -> status_load
15:30:47 DEBUG errbot.backends.base Adding command : status_plugins -> status_plugins
15:30:47 DEBUG errbot.backends.base Adding command : unblacklist -> unblacklist
15:30:47 DEBUG errbot.backends.base Adding command : unload -> unload
15:30:47 DEBUG errbot.backends.base Adding command : uptime -> uptime
15:30:47 DEBUG errbot.errBot Triggering callback_presence on Backup
15:30:47 DEBUG errbot.errBot Triggering callback_presence on ChatRoom
15:30:47 DEBUG errbot.errBot Triggering callback_presence on VersionChecker
15:30:48 DEBUG errbot.backends.slack Processing slack event: {'user': 'U00ERRBOT', 'text': 'Yes I am alive... \n \n With these plugins (L=Loaded, U=Unloaded, B=Blacklisted, C=Needs to be configured):\n [L] Backup\n [L] ChatRoom\n [L] VersionChecker\n [C] Webserver\n \n Load 0.07, 0.04, 0.05\n GC 0-&gt;66 1-&gt;4 2-&gt;6', 'reply_to': None, 'channel': 'G00000002', 'ts': '1433881813.000008', 'type': 'message'}
15:30:48 DEBUG errbot.backends.slack Handling message from a private group
15:30:48 ERROR errbot.backends.slack message event handler raised an exception
Traceback (most recent call last):
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 154, in serve_once
event_handler(message)
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 210, in _message_event_handler
node=self.channelid_to_channelname(event['channel']),
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 241, in channelid_to_channelname
return channel.name
AttributeError: 'list' object has no attribute 'name'
15:30:52 DEBUG errbot.backends.slack No event handler available for user_typing, ignoring this event
15:30:53 DEBUG errbot.backends.slack Processing slack event: {'user': 'UWHSKYRVR', 'text': '!status', 'team': 'TSHNYSRVR', 'channel': 'G00000002', 'ts': '1433881853.000010', 'type': 'message'}
15:30:53 DEBUG errbot.backends.slack Handling message from a private group
15:30:53 ERROR errbot.backends.slack message event handler raised an exception
Traceback (most recent call last):
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 154, in serve_once
event_handler(message)
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 210, in _message_event_handler
node=self.channelid_to_channelname(event['channel']),
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 241, in channelid_to_channelname
return channel.name
AttributeError: 'list' object has no attribute 'name'
15:31:25 DEBUG errbot.backends.slack Processing slack event: {'user': 'U00000003', 'type': 'presence_change', 'presence': 'away'}
15:31:25 DEBUG errbot.errBot Triggering callback_presence on Backup
15:31:25 DEBUG errbot.errBot Triggering callback_presence on ChatRoom
15:31:25 DEBUG errbot.errBot Triggering callback_presence on VersionChecker
15:32:25 DEBUG errbot.backends.slack Processing slack event: {'user': 'U00000004', 'type': 'presence_change', 'presence': 'away'}
15:32:25 DEBUG errbot.errBot Triggering callback_presence on Backup
15:32:25 DEBUG errbot.errBot Triggering callback_presence on ChatRoom
15:32:25 DEBUG errbot.errBot Triggering callback_presence on VersionChecker
15:32:59 DEBUG errbot.backends.slack No event handler available for user_typing, ignoring this event
15:33:00 DEBUG errbot.backends.slack Processing slack event: {'user': 'UWHSKYRVR', 'text': '!status', 'team': 'TSHNYSRVR', 'channel': 'G00000002', 'ts': '1433881980.000011', 'type': 'message'}
15:33:00 DEBUG errbot.backends.slack Handling message from a private group
15:33:00 ERROR errbot.backends.slack message event handler raised an exception
Traceback (most recent call last):
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 154, in serve_once
event_handler(message)
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 210, in _message_event_handler
node=self.channelid_to_channelname(event['channel']),
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 241, in channelid_to_channelname
return channel.name
AttributeError: 'list' object has no attribute 'name'
15:33:10 DEBUG errbot.backends.slack No event handler available for user_typing, ignoring this event
15:33:12 DEBUG errbot.backends.slack Processing slack event: {'user': 'UWHSKYRVR', 'text': '<@U00ERRBOT>: die', 'team': 'TSHNYSRVR', 'channel': 'C00000001', 'ts': '1433881993.000187', 'type': 'message'}
15:33:12 DEBUG errbot.backends.slack Handling message from a public channel
15:33:12 ERROR errbot.backends.slack message event handler raised an exception
Traceback (most recent call last):
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 154, in serve_once
event_handler(message)
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 210, in _message_event_handler
node=self.channelid_to_channelname(event['channel']),
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 241, in channelid_to_channelname
return channel.name
AttributeError: 'list' object has no attribute 'name'
^C15:33:20 INFO errbot.backends.slack Interrupt received, shutting down..
15:33:20 DEBUG errbot.backends.slack Triggering disconnect callback
15:33:20 INFO errbot.errBot Disconnect callback, deactivating all the plugins.
15:33:20 DEBUG errbot.storage Closed shelf of Backup
15:33:20 DEBUG errbot.storage Closed shelf of ChatRoom
15:33:20 DEBUG errbot.botplugin You still have active pollers at deactivation stage, I cleaned them up for you.
15:33:20 DEBUG errbot.storage Closed shelf of VersionChecker
15:33:20 INFO errbot.backends.base Trigger shutdown
15:33:20 INFO errbot.errBot Shutdown.
15:33:20 DEBUG errbot.storage Closed shelf of SlackBackend
15:33:20 INFO errbot.errBot Bye.
15:33:20 INFO __main__ Process exiting
|
ConnectionResetError
|
def serve_once(self):
self.sc = SlackClient(self.token)
log.info("Verifying authentication token")
self.auth = self.api_call("auth.test", raise_errors=False)
if not self.auth["ok"]:
log.error(
"Couldn't authenticate with Slack. Server said: %s" % self.auth["error"]
)
log.debug("Token accepted")
self.jid = SlackIdentifier(
node=self.auth["user_id"],
domain=self.sc.server.domain,
resource=self.auth["user_id"],
)
log.info("Connecting to Slack real-time-messaging API")
if self.sc.rtm_connect():
log.info("Connected")
self.reset_reconnection_count()
try:
while True:
for message in self.sc.rtm_read():
if "type" not in message:
log.debug("Ignoring non-event message: %s" % message)
continue
event_type = message["type"]
event_handler = getattr(
self, "_%s_event_handler" % event_type, None
)
if event_handler is None:
log.debug(
"No event handler available for %s, ignoring this event"
% event_type
)
continue
try:
log.debug("Processing slack event: %s" % message)
event_handler(message)
except Exception:
log.exception(
"%s event handler raised an exception" % event_type
)
time.sleep(1)
except KeyboardInterrupt:
log.info("Interrupt received, shutting down..")
return True
except:
log.exception("Error reading from RTM stream:")
finally:
log.debug("Triggering disconnect callback")
self.disconnect_callback()
else:
raise Exception("Connection failed, invalid token ?")
|
def serve_once(self):
log.info("Verifying authentication token")
self.auth = self.api_call("auth.test", raise_errors=False)
if not self.auth["ok"]:
log.error(
"Couldn't authenticate with Slack. Server said: %s" % self.auth["error"]
)
log.debug("Token accepted")
self.jid = SlackIdentifier(
node=self.auth["user_id"],
domain=self.sc.server.domain,
resource=self.auth["user_id"],
)
log.info("Connecting to Slack real-time-messaging API")
if self.sc.rtm_connect():
log.info("Connected")
self.reset_reconnection_count()
try:
while True:
for message in self.sc.rtm_read():
if "type" not in message:
log.debug("Ignoring non-event message: %s" % message)
continue
event_type = message["type"]
event_handler = getattr(
self, "_%s_event_handler" % event_type, None
)
if event_handler is None:
log.debug(
"No event handler available for %s, ignoring this event"
% event_type
)
continue
try:
log.debug("Processing slack event: %s" % message)
event_handler(message)
except Exception:
log.exception(
"%s event handler raised an exception" % event_type
)
time.sleep(1)
except KeyboardInterrupt:
log.info("Interrupt received, shutting down..")
return True
except:
log.exception("Error reading from RTM stream:")
finally:
log.debug("Triggering disconnect callback")
self.disconnect_callback()
else:
raise Exception("Connection failed, invalid token ?")
|
https://github.com/errbotio/errbot/issues/379
|
(err)whiskeyriver@whiskeyriver-VirtualBox:~/Code/err$ err.py -S
15:30:01 INFO __main__ Config check passed...
15:30:02 INFO __main__ Checking for '/home/whiskeyriver/Code/err/data'...
15:30:02 DEBUG errbot.errBot ErrBot init.
15:30:02 INFO errbot.storage Opened shelf of SlackBackend at /home/whiskeyriver/Code/err/data/core.db
15:30:02 DEBUG errbot.backends.base created the thread pool<errbot.bundled.threadpool.ThreadPool object at 0x7f453284e8d0>
15:30:02 DEBUG errbot.plugin_manager check dependencies of /home/whiskeyriver/Code/err/errbot/core_plugins
15:30:02 DEBUG errbot.plugin_manager /home/whiskeyriver/Code/err/errbot/core_plugins has no requirements.txt file
15:30:02 DEBUG errbot.plugin_manager plugin __init__(args=['self', 'bot'], argslist=None, kwargs=None)
15:30:02 INFO errbot.storage Init shelf of ChatRoom
15:30:02 DEBUG errbot.plugin_manager plugin __init__(args=['self', 'bot'], argslist=None, kwargs=None)
15:30:02 INFO errbot.storage Init shelf of Backup
15:30:02 DEBUG errbot.plugin_manager plugin __init__(args=['self', 'bot'], argslist=None, kwargs=None)
15:30:02 INFO errbot.storage Init shelf of VersionChecker
15:30:02 INFO errbot.decorators webhooks: Flag to bind /echo/ to echo
15:30:02 DEBUG errbot.plugin_manager plugin __init__(args=['self', 'bot'], argslist=None, kwargs=None)
15:30:02 INFO errbot.storage Init shelf of Webserver
15:30:02 DEBUG errbot.main serve from <errbot.backends.slack.SlackBackend object at 0x7f453284e710>
15:30:02 INFO errbot.backends.slack Verifying authentication token
15:30:03 DEBUG errbot.backends.slack Token accepted
15:30:03 INFO errbot.backends.slack Connecting to Slack real-time-messaging API
15:30:04 INFO errbot.backends.slack Connected
15:30:05 DEBUG errbot.backends.slack Processing slack event: {'type': 'hello'}
15:30:05 INFO errbot.errBot Activate internal commands
15:30:05 INFO errbot.errBot Activating all the plugins...
15:30:05 INFO errbot.errBot Activate plugin: Webserver
15:30:05 INFO errbot.plugin_manager Activating Webserver with min_err_version = 2.2.1 and max_version = 2.2.1
15:30:05 DEBUG errbot.templating Templates directory found for this plugin [/home/whiskeyriver/Code/err/errbot/core_plugins/templates]
15:30:05 INFO yapsy_loaded_plugin_Webse Webserver is not configured. Forbid activation
15:30:05 INFO errbot.core_plugins.wsvie Checking Webserver for webhooks
15:30:05 INFO errbot.core_plugins.wsvie ... Routing echo
15:30:05 INFO errbot.errBot Activate plugin: Backup
15:30:05 INFO errbot.plugin_manager Activating Backup with min_err_version = None and max_version = None
15:30:05 DEBUG errbot.templating Templates directory found for this plugin [/home/whiskeyriver/Code/err/errbot/core_plugins/templates]
15:30:05 DEBUG errbot.botplugin Init storage for Backup
15:30:05 DEBUG errbot.botplugin Loading /home/whiskeyriver/Code/err/data/plugins/Backup.db
15:30:05 INFO errbot.storage Opened shelf of Backup at /home/whiskeyriver/Code/err/data/plugins/Backup.db
15:30:05 DEBUG errbot.backends.base Adding command : backup -> backup
15:30:05 INFO errbot.core_plugins.wsvie Checking Backup for webhooks
15:30:05 INFO errbot.errBot Activate plugin: ChatRoom
15:30:05 INFO errbot.plugin_manager Activating ChatRoom with min_err_version = 2.2.1 and max_version = 2.2.1
15:30:05 DEBUG errbot.templating Templates directory found for this plugin [/home/whiskeyriver/Code/err/errbot/core_plugins/templates]
15:30:05 DEBUG errbot.botplugin Init storage for ChatRoom
15:30:05 DEBUG errbot.botplugin Loading /home/whiskeyriver/Code/err/data/plugins/ChatRoom.db
15:30:05 INFO errbot.storage Opened shelf of ChatRoom at /home/whiskeyriver/Code/err/data/plugins/ChatRoom.db
15:30:05 DEBUG errbot.backends.base Adding command : gtalk_room_create -> gtalk_room_create
15:30:05 DEBUG errbot.backends.base Adding command : room_create -> room_create
15:30:05 DEBUG errbot.backends.base Adding command : room_destroy -> room_destroy
15:30:05 DEBUG errbot.backends.base Adding command : room_invite -> room_invite
15:30:05 DEBUG errbot.backends.base Adding command : room_join -> room_join
15:30:05 DEBUG errbot.backends.base Adding command : room_leave -> room_leave
15:30:05 DEBUG errbot.backends.base Adding command : room_list -> room_list
15:30:05 DEBUG errbot.backends.base Adding command : room_occupants -> room_occupants
15:30:05 DEBUG errbot.backends.base Adding command : room_topic -> room_topic
15:30:05 INFO errbot.core_plugins.wsvie Checking ChatRoom for webhooks
15:30:05 INFO errbot.errBot Activate plugin: VersionChecker
15:30:05 INFO errbot.plugin_manager Activating VersionChecker with min_err_version = 2.2.1 and max_version = 2.2.1
15:30:05 DEBUG errbot.templating Templates directory found for this plugin [/home/whiskeyriver/Code/err/errbot/core_plugins/templates]
15:30:05 DEBUG yapsy_loaded_plugin_Versi Checking version
15:30:06 DEBUG errbot.botplugin Programming the polling of version_check every 86400 seconds with args [] and kwargs {}
15:30:06 DEBUG errbot.botplugin Init storage for VersionChecker
15:30:06 DEBUG errbot.botplugin Loading /home/whiskeyriver/Code/err/data/plugins/VersionChecker.db
15:30:06 INFO errbot.storage Opened shelf of VersionChecker at /home/whiskeyriver/Code/err/data/plugins/VersionChecker.db
15:30:06 INFO errbot.core_plugins.wsvie Checking VersionChecker for webhooks
15:30:06 INFO errbot.errBot
15:30:06 INFO errbot.errBot Notifying connection to all the plugins...
15:30:06 DEBUG errbot.errBot Trigger callback_connect on Backup
15:30:06 DEBUG errbot.errBot Trigger callback_connect on ChatRoom
15:30:06 INFO yapsy_loaded_plugin_ChatR Callback_connect
15:30:06 DEBUG errbot.errBot Trigger callback_connect on VersionChecker
15:30:06 INFO errbot.errBot Plugin activation done.
15:30:06 DEBUG errbot.backends.base Adding command : about -> about
15:30:06 DEBUG errbot.backends.base Adding command : apropos -> apropos
15:30:06 DEBUG errbot.backends.base Adding command : blacklist -> blacklist
15:30:06 DEBUG errbot.backends.base Adding command : config -> config
15:30:06 DEBUG errbot.backends.base Adding command : echo -> echo
15:30:06 DEBUG errbot.backends.base Adding command : help -> help
15:30:06 DEBUG errbot.backends.base Adding command : history -> history
15:30:06 DEBUG errbot.backends.base Adding command : load -> load
15:30:06 DEBUG errbot.backends.base Adding command : log_tail -> log_tail
15:30:06 DEBUG errbot.backends.base Adding command : reload -> reload
15:30:06 DEBUG errbot.backends.base Adding command : repos -> repos
15:30:06 DEBUG errbot.backends.base Adding command : repos_install -> repos_install
15:30:06 DEBUG errbot.backends.base Adding command : repos_uninstall -> repos_uninstall
15:30:06 DEBUG errbot.backends.base Adding command : repos_update -> repos_update
15:30:06 DEBUG errbot.backends.base Adding command : restart -> restart
15:30:06 DEBUG errbot.backends.base Adding command : status -> status
15:30:06 DEBUG errbot.backends.base Adding command : status_gc -> status_gc
15:30:06 DEBUG errbot.backends.base Adding command : status_load -> status_load
15:30:06 DEBUG errbot.backends.base Adding command : status_plugins -> status_plugins
15:30:06 DEBUG errbot.backends.base Adding command : unblacklist -> unblacklist
15:30:06 DEBUG errbot.backends.base Adding command : unload -> unload
15:30:06 DEBUG errbot.backends.base Adding command : uptime -> uptime
15:30:06 DEBUG errbot.errBot Triggering callback_presence on Backup
15:30:06 DEBUG errbot.errBot Triggering callback_presence on ChatRoom
15:30:06 DEBUG errbot.errBot Triggering callback_presence on VersionChecker
15:30:07 DEBUG errbot.backends.slack Processing slack event: {'user': 'U00ERRBOT', 'text': 'Command "needs" / "needs some" not found.', 'reply_to': None, 'channel': 'C00000001', 'ts': '1433881703.000186', 'type': 'message'}
15:30:07 DEBUG errbot.backends.slack Handling message from a public channel
15:30:07 DEBUG errbot.backends.base *** jid = deployment@shinyservers/deploybot
15:30:07 DEBUG errbot.backends.base *** username = deploybot
15:30:07 DEBUG errbot.backends.base *** type = groupchat
15:30:07 DEBUG errbot.backends.base *** text = Command "needs" / "needs some" not found.
15:30:07 DEBUG errbot.errBot Trigger callback_message on Backup
15:30:07 DEBUG errbot.errBot Trigger callback_message on ChatRoom
15:30:07 DEBUG errbot.errBot Trigger callback_message on VersionChecker
15:30:10 DEBUG errbot.backends.slack No event handler available for user_typing, ignoring this event
15:30:12 DEBUG errbot.backends.slack Processing slack event: {'user': 'UWHSKYRVR', 'text': '!status', 'team': 'TSHNYSRVR', 'channel': 'G00000002', 'ts': '1433881812.000007', 'type': 'message'}
15:30:12 DEBUG errbot.backends.slack Handling message from a private group
15:30:12 DEBUG errbot.backends.base *** jid = test_deploy_bot@shinyservers/whiskeyriver
15:30:12 DEBUG errbot.backends.base *** username = whiskeyriver
15:30:12 DEBUG errbot.backends.base *** type = groupchat
15:30:12 DEBUG errbot.backends.base *** text = !status
15:30:12 INFO errbot.backends.base Processing command 'status' with parameters '' from test_deploy_bot@shinyservers/whiskeyriver/whiskeyriver
15:30:12 DEBUG errbot.errBot Trigger callback_message on Backup
15:30:12 DEBUG errbot.errBot Trigger callback_message on ChatRoom
15:30:12 DEBUG errbot.errBot Trigger callback_message on VersionChecker
15:30:12 DEBUG errbot.backends.slack Sending groupchat message to test_deploy_bot (G00000002)
15:30:13 DEBUG errbot.backends.slack Ignoring non-event message: {'ts': '1433881813.000008', 'ok': True, 'text': 'Yes I am alive... \n \n With these plugins (L=Loaded, U=Unloaded, B=Blacklisted, C=Needs to be configured):\n [L] Backup\n [L] ChatRoom\n [L] VersionChecker\n [C] Webserver\n \n Load 0.07, 0.04, 0.05\n GC 0-&gt;66 1-&gt;4 2-&gt;6', 'reply_to': None}
15:30:43 ERROR errbot.backends.slack Error reading from RTM stream:
Traceback (most recent call last):
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 142, in serve_once
for message in self.sc.rtm_read():
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/slackclient/_client.py", line 27, in rtm_read
json_data = self.server.websocket_safe_read()
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/slackclient/_server.py", line 109, in websocket_safe_read
data += "{}\n".format(self.websocket.recv())
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_core.py", line 348, in recv
opcode, data = self.recv_data()
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_core.py", line 365, in recv_data
opcode, frame = self.recv_data_frame(control_frame)
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_core.py", line 378, in recv_data_frame
frame = self.recv_frame()
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_core.py", line 410, in recv_frame
return self.frame_buffer.recv_frame()
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_abnf.py", line 300, in recv_frame
self.recv_header()
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_abnf.py", line 249, in recv_header
header = self.recv_strict(2)
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_abnf.py", line 334, in recv_strict
bytes = self.recv(min(16384, shortage))
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_core.py", line 476, in _recv
return recv(self.sock, bufsize)
File "/home/whiskeyriver/Code/virtualenv/err/lib/python3.4/site-packages/websocket/_socket.py", line 77, in recv
bytes = sock.recv(bufsize)
File "/usr/lib/python3.4/ssl.py", line 731, in recv
return self.read(buflen)
File "/usr/lib/python3.4/ssl.py", line 620, in read
v = self._sslobj.read(len or 1024)
ConnectionResetError: [Errno 104] Connection reset by peer
15:30:43 DEBUG errbot.backends.slack Triggering disconnect callback
15:30:43 INFO errbot.errBot Disconnect callback, deactivating all the plugins.
15:30:43 DEBUG errbot.storage Closed shelf of Backup
15:30:43 DEBUG errbot.storage Closed shelf of ChatRoom
15:30:43 DEBUG errbot.botplugin You still have active pollers at deactivation stage, I cleaned them up for you.
15:30:43 DEBUG errbot.storage Closed shelf of VersionChecker
15:30:43 INFO errbot.backends.base Reconnecting in 1 seconds (0 attempted reconnections so far)
15:30:44 INFO errbot.backends.slack Verifying authentication token
15:30:44 DEBUG errbot.backends.slack Token accepted
15:30:44 INFO errbot.backends.slack Connecting to Slack real-time-messaging API
15:30:45 INFO errbot.backends.slack Connected
15:30:46 DEBUG errbot.backends.slack Processing slack event: {'type': 'hello'}
15:30:46 INFO errbot.errBot Activate internal commands
15:30:46 INFO errbot.errBot Activating all the plugins...
15:30:46 INFO errbot.errBot Activate plugin: Webserver
15:30:46 INFO errbot.plugin_manager Activating Webserver with min_err_version = 2.2.1 and max_version = 2.2.1
15:30:46 DEBUG errbot.templating Templates directory found for this plugin [/home/whiskeyriver/Code/err/errbot/core_plugins/templates]
15:30:46 INFO yapsy_loaded_plugin_Webse Webserver is not configured. Forbid activation
15:30:46 INFO errbot.core_plugins.wsvie Checking Webserver for webhooks
15:30:46 INFO errbot.core_plugins.wsvie ... Routing echo
15:30:46 INFO errbot.errBot Activate plugin: Backup
15:30:46 INFO errbot.plugin_manager Activating Backup with min_err_version = None and max_version = None
15:30:46 DEBUG errbot.templating Templates directory found for this plugin [/home/whiskeyriver/Code/err/errbot/core_plugins/templates]
15:30:46 DEBUG errbot.botplugin Init storage for Backup
15:30:46 DEBUG errbot.botplugin Loading /home/whiskeyriver/Code/err/data/plugins/Backup.db
15:30:46 INFO errbot.storage Opened shelf of Backup at /home/whiskeyriver/Code/err/data/plugins/Backup.db
15:30:46 DEBUG errbot.backends.base Adding command : backup -> backup
15:30:46 INFO errbot.core_plugins.wsvie Checking Backup for webhooks
15:30:46 INFO errbot.errBot Activate plugin: ChatRoom
15:30:46 INFO errbot.plugin_manager Activating ChatRoom with min_err_version = 2.2.1 and max_version = 2.2.1
15:30:46 DEBUG errbot.templating Templates directory found for this plugin [/home/whiskeyriver/Code/err/errbot/core_plugins/templates]
15:30:46 DEBUG errbot.botplugin Init storage for ChatRoom
15:30:46 DEBUG errbot.botplugin Loading /home/whiskeyriver/Code/err/data/plugins/ChatRoom.db
15:30:46 INFO errbot.storage Opened shelf of ChatRoom at /home/whiskeyriver/Code/err/data/plugins/ChatRoom.db
15:30:46 DEBUG errbot.backends.base Adding command : gtalk_room_create -> gtalk_room_create
15:30:46 DEBUG errbot.backends.base Adding command : room_create -> room_create
15:30:46 DEBUG errbot.backends.base Adding command : room_destroy -> room_destroy
15:30:46 DEBUG errbot.backends.base Adding command : room_invite -> room_invite
15:30:46 DEBUG errbot.backends.base Adding command : room_join -> room_join
15:30:46 DEBUG errbot.backends.base Adding command : room_leave -> room_leave
15:30:46 DEBUG errbot.backends.base Adding command : room_list -> room_list
15:30:46 DEBUG errbot.backends.base Adding command : room_occupants -> room_occupants
15:30:46 DEBUG errbot.backends.base Adding command : room_topic -> room_topic
15:30:46 INFO errbot.core_plugins.wsvie Checking ChatRoom for webhooks
15:30:46 INFO errbot.errBot Activate plugin: VersionChecker
15:30:46 INFO errbot.plugin_manager Activating VersionChecker with min_err_version = 2.2.1 and max_version = 2.2.1
15:30:46 DEBUG errbot.templating Templates directory found for this plugin [/home/whiskeyriver/Code/err/errbot/core_plugins/templates]
15:30:46 DEBUG yapsy_loaded_plugin_Versi Checking version
15:30:47 DEBUG errbot.botplugin Programming the polling of version_check every 86400 seconds with args [] and kwargs {}
15:30:47 DEBUG errbot.botplugin Init storage for VersionChecker
15:30:47 DEBUG errbot.botplugin Loading /home/whiskeyriver/Code/err/data/plugins/VersionChecker.db
15:30:47 INFO errbot.storage Opened shelf of VersionChecker at /home/whiskeyriver/Code/err/data/plugins/VersionChecker.db
15:30:47 INFO errbot.core_plugins.wsvie Checking VersionChecker for webhooks
15:30:47 INFO errbot.errBot
15:30:47 INFO errbot.errBot Notifying connection to all the plugins...
15:30:47 DEBUG errbot.errBot Trigger callback_connect on Backup
15:30:47 DEBUG errbot.errBot Trigger callback_connect on ChatRoom
15:30:47 INFO yapsy_loaded_plugin_ChatR Callback_connect
15:30:47 DEBUG errbot.errBot Trigger callback_connect on VersionChecker
15:30:47 INFO errbot.errBot Plugin activation done.
15:30:47 DEBUG errbot.backends.base Adding command : about -> about
15:30:47 DEBUG errbot.backends.base Adding command : apropos -> apropos
15:30:47 DEBUG errbot.backends.base Adding command : blacklist -> blacklist
15:30:47 DEBUG errbot.backends.base Adding command : config -> config
15:30:47 DEBUG errbot.backends.base Adding command : echo -> echo
15:30:47 DEBUG errbot.backends.base Adding command : help -> help
15:30:47 DEBUG errbot.backends.base Adding command : history -> history
15:30:47 DEBUG errbot.backends.base Adding command : load -> load
15:30:47 DEBUG errbot.backends.base Adding command : log_tail -> log_tail
15:30:47 DEBUG errbot.backends.base Adding command : reload -> reload
15:30:47 DEBUG errbot.backends.base Adding command : repos -> repos
15:30:47 DEBUG errbot.backends.base Adding command : repos_install -> repos_install
15:30:47 DEBUG errbot.backends.base Adding command : repos_uninstall -> repos_uninstall
15:30:47 DEBUG errbot.backends.base Adding command : repos_update -> repos_update
15:30:47 DEBUG errbot.backends.base Adding command : restart -> restart
15:30:47 DEBUG errbot.backends.base Adding command : status -> status
15:30:47 DEBUG errbot.backends.base Adding command : status_gc -> status_gc
15:30:47 DEBUG errbot.backends.base Adding command : status_load -> status_load
15:30:47 DEBUG errbot.backends.base Adding command : status_plugins -> status_plugins
15:30:47 DEBUG errbot.backends.base Adding command : unblacklist -> unblacklist
15:30:47 DEBUG errbot.backends.base Adding command : unload -> unload
15:30:47 DEBUG errbot.backends.base Adding command : uptime -> uptime
15:30:47 DEBUG errbot.errBot Triggering callback_presence on Backup
15:30:47 DEBUG errbot.errBot Triggering callback_presence on ChatRoom
15:30:47 DEBUG errbot.errBot Triggering callback_presence on VersionChecker
15:30:48 DEBUG errbot.backends.slack Processing slack event: {'user': 'U00ERRBOT', 'text': 'Yes I am alive... \n \n With these plugins (L=Loaded, U=Unloaded, B=Blacklisted, C=Needs to be configured):\n [L] Backup\n [L] ChatRoom\n [L] VersionChecker\n [C] Webserver\n \n Load 0.07, 0.04, 0.05\n GC 0-&gt;66 1-&gt;4 2-&gt;6', 'reply_to': None, 'channel': 'G00000002', 'ts': '1433881813.000008', 'type': 'message'}
15:30:48 DEBUG errbot.backends.slack Handling message from a private group
15:30:48 ERROR errbot.backends.slack message event handler raised an exception
Traceback (most recent call last):
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 154, in serve_once
event_handler(message)
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 210, in _message_event_handler
node=self.channelid_to_channelname(event['channel']),
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 241, in channelid_to_channelname
return channel.name
AttributeError: 'list' object has no attribute 'name'
15:30:52 DEBUG errbot.backends.slack No event handler available for user_typing, ignoring this event
15:30:53 DEBUG errbot.backends.slack Processing slack event: {'user': 'UWHSKYRVR', 'text': '!status', 'team': 'TSHNYSRVR', 'channel': 'G00000002', 'ts': '1433881853.000010', 'type': 'message'}
15:30:53 DEBUG errbot.backends.slack Handling message from a private group
15:30:53 ERROR errbot.backends.slack message event handler raised an exception
Traceback (most recent call last):
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 154, in serve_once
event_handler(message)
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 210, in _message_event_handler
node=self.channelid_to_channelname(event['channel']),
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 241, in channelid_to_channelname
return channel.name
AttributeError: 'list' object has no attribute 'name'
15:31:25 DEBUG errbot.backends.slack Processing slack event: {'user': 'U00000003', 'type': 'presence_change', 'presence': 'away'}
15:31:25 DEBUG errbot.errBot Triggering callback_presence on Backup
15:31:25 DEBUG errbot.errBot Triggering callback_presence on ChatRoom
15:31:25 DEBUG errbot.errBot Triggering callback_presence on VersionChecker
15:32:25 DEBUG errbot.backends.slack Processing slack event: {'user': 'U00000004', 'type': 'presence_change', 'presence': 'away'}
15:32:25 DEBUG errbot.errBot Triggering callback_presence on Backup
15:32:25 DEBUG errbot.errBot Triggering callback_presence on ChatRoom
15:32:25 DEBUG errbot.errBot Triggering callback_presence on VersionChecker
15:32:59 DEBUG errbot.backends.slack No event handler available for user_typing, ignoring this event
15:33:00 DEBUG errbot.backends.slack Processing slack event: {'user': 'UWHSKYRVR', 'text': '!status', 'team': 'TSHNYSRVR', 'channel': 'G00000002', 'ts': '1433881980.000011', 'type': 'message'}
15:33:00 DEBUG errbot.backends.slack Handling message from a private group
15:33:00 ERROR errbot.backends.slack message event handler raised an exception
Traceback (most recent call last):
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 154, in serve_once
event_handler(message)
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 210, in _message_event_handler
node=self.channelid_to_channelname(event['channel']),
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 241, in channelid_to_channelname
return channel.name
AttributeError: 'list' object has no attribute 'name'
15:33:10 DEBUG errbot.backends.slack No event handler available for user_typing, ignoring this event
15:33:12 DEBUG errbot.backends.slack Processing slack event: {'user': 'UWHSKYRVR', 'text': '<@U00ERRBOT>: die', 'team': 'TSHNYSRVR', 'channel': 'C00000001', 'ts': '1433881993.000187', 'type': 'message'}
15:33:12 DEBUG errbot.backends.slack Handling message from a public channel
15:33:12 ERROR errbot.backends.slack message event handler raised an exception
Traceback (most recent call last):
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 154, in serve_once
event_handler(message)
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 210, in _message_event_handler
node=self.channelid_to_channelname(event['channel']),
File "/home/whiskeyriver/Code/err/errbot/backends/slack.py", line 241, in channelid_to_channelname
return channel.name
AttributeError: 'list' object has no attribute 'name'
^C15:33:20 INFO errbot.backends.slack Interrupt received, shutting down..
15:33:20 DEBUG errbot.backends.slack Triggering disconnect callback
15:33:20 INFO errbot.errBot Disconnect callback, deactivating all the plugins.
15:33:20 DEBUG errbot.storage Closed shelf of Backup
15:33:20 DEBUG errbot.storage Closed shelf of ChatRoom
15:33:20 DEBUG errbot.botplugin You still have active pollers at deactivation stage, I cleaned them up for you.
15:33:20 DEBUG errbot.storage Closed shelf of VersionChecker
15:33:20 INFO errbot.backends.base Trigger shutdown
15:33:20 INFO errbot.errBot Shutdown.
15:33:20 DEBUG errbot.storage Closed shelf of SlackBackend
15:33:20 INFO errbot.errBot Bye.
15:33:20 INFO __main__ Process exiting
|
ConnectionResetError
|
def _warn_if_text_is_missing(endpoint: str, kwargs: Dict[str, Any]) -> None:
attachments = kwargs.get("attachments")
if attachments and isinstance(attachments, list):
if all(
[
attachment.get("fallback")
and len(attachment.get("fallback").strip()) != 0
for attachment in attachments
]
):
return
missing = "fallback"
else:
text = kwargs.get("text")
if text and len(text.strip()) != 0:
return
missing = "text"
message = (
f"The `{missing}` argument is missing in the request payload for a {endpoint} call - "
f"It's a best practice to always provide a `{missing}` argument when posting a message. "
f"The `{missing}` argument is used in places where content cannot be rendered such as: "
"system push notifications, assistive technology such as screen readers, etc."
)
# for unit tests etc.
skip_deprecation = os.environ.get("SKIP_SLACK_SDK_WARNING")
if skip_deprecation:
return
warnings.warn(message, UserWarning)
|
def _warn_if_text_is_missing(endpoint: str, kwargs: Dict[str, Any]) -> None:
attachments = kwargs.get("attachments")
if attachments:
if all(
[
attachment.get("fallback")
and len(attachment.get("fallback").strip()) != 0
for attachment in attachments
]
):
return
missing = "fallback"
else:
text = kwargs.get("text")
if text and len(text.strip()) != 0:
return
missing = "text"
message = (
f"The `{missing}` argument is missing in the request payload for a {endpoint} call - "
f"It's a best practice to always provide a `{missing}` argument when posting a message. "
f"The `{missing}` argument is used in places where content cannot be rendered such as: "
"system push notifications, assistive technology such as screen readers, etc."
)
# for unit tests etc.
skip_deprecation = os.environ.get("SKIP_SLACK_SDK_WARNING")
if skip_deprecation:
return
warnings.warn(message, UserWarning)
|
https://github.com/slackapi/python-slack-sdk/issues/971
|
Traceback (most recent call last):
...SNIP...
File "/usr/local/lib/python3.9/site-packages/slack_sdk/web/client.py", line 1185, in chat_update
"Developer": ":large_blue_square: Developer",
_warn_if_text_is_missing("chat.update", kwargs)
File "/usr/local/lib/python3.9/site-packages/slack_sdk/web/internal_utils.py", line 237, in _warn_if_text_is_missing
[
File "/usr/local/lib/python3.9/site-packages/slack_sdk/web/internal_utils.py", line 238, in <listcomp>
attachment.get("fallback")
AttributeError: 'str' object has no attribute 'get'
|
AttributeError
|
def __init__(
self,
*,
token: Optional[str] = None,
web_client: Optional[WebClient] = None,
auto_reconnect_enabled: bool = True,
ssl: Optional[SSLContext] = None,
proxy: Optional[str] = None,
timeout: int = 30,
base_url: str = WebClient.BASE_URL,
headers: Optional[dict] = None,
ping_interval: int = 5,
concurrency: int = 10,
logger: Optional[logging.Logger] = None,
on_message_listeners: Optional[List[Callable[[str], None]]] = None,
on_error_listeners: Optional[List[Callable[[Exception], None]]] = None,
on_close_listeners: Optional[List[Callable[[int, Optional[str]], None]]] = None,
trace_enabled: bool = False,
all_message_trace_enabled: bool = False,
ping_pong_trace_enabled: bool = False,
):
self.token = token.strip() if token is not None else None
self.bot_id = None
self.default_auto_reconnect_enabled = auto_reconnect_enabled
# You may want temporarily turn off the auto_reconnect as necessary
self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
self.ssl = ssl
self.proxy = proxy
self.timeout = timeout
self.base_url = base_url
self.headers = headers
self.ping_interval = ping_interval
self.logger = logger or logging.getLogger(__name__)
if self.proxy is None or len(self.proxy.strip()) == 0:
env_variable = load_http_proxy_from_env(self.logger)
if env_variable is not None:
self.proxy = env_variable
self.web_client = web_client or WebClient(
token=self.token,
base_url=self.base_url,
timeout=self.timeout,
ssl=self.ssl,
proxy=self.proxy,
headers=self.headers,
logger=logger,
)
self.on_message_listeners = on_message_listeners or []
self.on_error_listeners = on_error_listeners or []
self.on_close_listeners = on_close_listeners or []
self.trace_enabled = trace_enabled
self.all_message_trace_enabled = all_message_trace_enabled
self.ping_pong_trace_enabled = ping_pong_trace_enabled
self.message_queue = Queue()
def goodbye_listener(_self, event: dict):
if event.get("type") == "goodbye":
message = "Got a goodbye message. Reconnecting to the server ..."
self.logger.info(message)
self.connect_to_new_endpoint(force=True)
self.message_listeners = [goodbye_listener]
self.socket_mode_request_listeners = []
self.current_session = None
self.current_session_state = ConnectionState()
self.current_session_runner = IntervalRunner(self._run_current_session, 0.1).start()
self.wss_uri = None
self.current_app_monitor_started = False
self.current_app_monitor = IntervalRunner(
self._monitor_current_session,
self.ping_interval,
)
self.closed = False
self.connect_operation_lock = Lock()
self.message_processor = IntervalRunner(self.process_messages, 0.001).start()
self.message_workers = ThreadPoolExecutor(max_workers=concurrency)
|
def __init__(
self,
*,
token: Optional[str] = None,
web_client: Optional[WebClient] = None,
auto_reconnect_enabled: bool = True,
ssl: Optional[SSLContext] = None,
proxy: Optional[str] = None,
timeout: int = 30,
base_url: str = WebClient.BASE_URL,
headers: Optional[dict] = None,
ping_interval: int = 5,
concurrency: int = 10,
logger: Optional[logging.Logger] = None,
on_message_listeners: Optional[List[Callable[[str], None]]] = None,
on_error_listeners: Optional[List[Callable[[Exception], None]]] = None,
on_close_listeners: Optional[List[Callable[[int, Optional[str]], None]]] = None,
trace_enabled: bool = False,
all_message_trace_enabled: bool = False,
ping_pong_trace_enabled: bool = False,
):
self.token = token.strip() if token is not None else None
self.bot_id = None
self.default_auto_reconnect_enabled = auto_reconnect_enabled
# You may want temporarily turn off the auto_reconnect as necessary
self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
self.ssl = ssl
self.proxy = proxy
self.timeout = timeout
self.base_url = base_url
self.headers = headers
self.ping_interval = ping_interval
self.logger = logger or logging.getLogger(__name__)
if self.proxy is None or len(self.proxy.strip()) == 0:
env_variable = load_http_proxy_from_env(self.logger)
if env_variable is not None:
self.proxy = env_variable
self.web_client = web_client or WebClient(
token=self.token,
base_url=self.base_url,
timeout=self.timeout,
ssl=self.ssl,
proxy=self.proxy,
headers=self.headers,
logger=logger,
)
self.on_message_listeners = on_message_listeners or []
self.on_error_listeners = on_error_listeners or []
self.on_close_listeners = on_close_listeners or []
self.trace_enabled = trace_enabled
self.all_message_trace_enabled = all_message_trace_enabled
self.ping_pong_trace_enabled = ping_pong_trace_enabled
self.message_queue = Queue()
def goodbye_listener(_self, event: dict):
if event.get("type") == "goodbye":
message = "Got a goodbye message. Reconnecting to the server ..."
self.logger.info(message)
self.connect_to_new_endpoint(force=True)
self.message_listeners = [goodbye_listener]
self.socket_mode_request_listeners = []
self.current_session = None
self.current_session_state = ConnectionState()
self.current_session_runner = IntervalRunner(self._run_current_session, 0.5).start()
self.wss_uri = None
self.current_app_monitor_started = False
self.current_app_monitor = IntervalRunner(
self._monitor_current_session,
self.ping_interval,
)
self.closed = False
self.connect_operation_lock = Lock()
self.message_processor = IntervalRunner(self.process_messages, 0.001).start()
self.message_workers = ThreadPoolExecutor(max_workers=concurrency)
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def connect(self):
"""Starts talking to the RTM server through a WebSocket connection"""
if self.bot_id is None:
self.bot_id = self.web_client.auth_test()["bot_id"]
old_session: Optional[Connection] = self.current_session
old_current_session_state: ConnectionState = self.current_session_state
if self.wss_uri is None:
self.wss_uri = self.issue_new_wss_url()
current_session = Connection(
url=self.wss_uri,
logger=self.logger,
ping_interval=self.ping_interval,
trace_enabled=self.trace_enabled,
all_message_trace_enabled=self.all_message_trace_enabled,
ping_pong_trace_enabled=self.ping_pong_trace_enabled,
receive_buffer_size=1024,
proxy=self.proxy,
on_message_listener=self.run_all_message_listeners,
on_error_listener=self.run_all_error_listeners,
on_close_listener=self.run_all_close_listeners,
connection_type_name="RTM",
)
current_session.connect()
if old_current_session_state is not None:
old_current_session_state.terminated = True
if old_session is not None:
old_session.close()
self.current_session = current_session
self.current_session_state = ConnectionState()
self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
if not self.current_app_monitor_started:
self.current_app_monitor_started = True
self.current_app_monitor.start()
self.logger.info(
f"A new session has been established (session id: {self.session_id()})"
)
|
def connect(self):
"""Starts talking to the RTM server through a WebSocket connection"""
if self.bot_id is None:
self.bot_id = self.web_client.auth_test()["bot_id"]
old_session: Optional[Connection] = self.current_session
if self.wss_uri is None:
self.wss_uri = self.issue_new_wss_url()
self.current_session = Connection(
url=self.wss_uri,
logger=self.logger,
ping_interval=self.ping_interval,
trace_enabled=self.trace_enabled,
all_message_trace_enabled=self.all_message_trace_enabled,
ping_pong_trace_enabled=self.ping_pong_trace_enabled,
receive_buffer_size=1024,
proxy=self.proxy,
on_message_listener=self.run_all_message_listeners,
on_error_listener=self.run_all_error_listeners,
on_close_listener=self.run_all_close_listeners,
connection_type_name="RTM",
)
self.current_session.connect()
self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
if old_session is not None:
old_session.close()
self.current_session_state.terminated = True
if not self.current_app_monitor_started:
self.current_app_monitor_started = True
self.current_app_monitor.start()
self.logger.info(
f"A new session has been established (session id: {self.session_id()})"
)
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def _run_current_session(self):
if self.current_session is not None and self.current_session.is_active():
session_id = self.session_id()
try:
self.logger.info(
"Starting to receive messages from a new connection"
f" (session id: {session_id})"
)
self.current_session_state.terminated = False
self.current_session.run_until_completion(self.current_session_state)
self.logger.info(
"Stopped receiving messages from a connection"
f" (session id: {session_id})"
)
except Exception as e:
self.logger.exception(
"Failed to start or stop the current session"
f" (session id: {session_id}, error: {e})"
)
|
def _run_current_session(self):
try:
if self.current_session is not None and self.current_session.is_active():
self.logger.info(
"Starting to receive messages from a new connection"
f" (session id: {self.session_id()})"
)
self.current_session_state.terminated = False
self.current_session.run_until_completion(self.current_session_state)
self.logger.info(
"Stopped receiving messages from a connection"
f" (session id: {self.session_id()})"
)
except Exception as e:
self.logger.exception(
"Failed to start or stop the current session"
f" (session id: {self.session_id()}, error: {e})"
)
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def __init__(
self,
app_token: str,
logger: Optional[Logger] = None,
web_client: Optional[WebClient] = None,
auto_reconnect_enabled: bool = True,
trace_enabled: bool = False,
all_message_trace_enabled: bool = False,
ping_pong_trace_enabled: bool = False,
ping_interval: float = 5,
receive_buffer_size: int = 1024,
concurrency: int = 10,
proxy: Optional[str] = None,
proxy_headers: Optional[Dict[str, str]] = None,
on_message_listeners: Optional[List[Callable[[str], None]]] = None,
on_error_listeners: Optional[List[Callable[[Exception], None]]] = None,
on_close_listeners: Optional[List[Callable[[int, Optional[str]], None]]] = None,
):
self.app_token = app_token
self.logger = logger or logging.getLogger(__name__)
self.web_client = web_client or WebClient()
self.default_auto_reconnect_enabled = auto_reconnect_enabled
self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
self.trace_enabled = trace_enabled
self.all_message_trace_enabled = all_message_trace_enabled
self.ping_pong_trace_enabled = ping_pong_trace_enabled
self.ping_interval = ping_interval
self.receive_buffer_size = receive_buffer_size
if self.receive_buffer_size < 16:
raise SlackClientConfigurationError("Too small receive_buffer_size detected.")
self.wss_uri = None
self.message_queue = Queue()
self.message_listeners = []
self.socket_mode_request_listeners = []
self.current_session = None
self.current_session_state = ConnectionState()
self.current_session_runner = IntervalRunner(self._run_current_session, 0.1).start()
self.current_app_monitor_started = False
self.current_app_monitor = IntervalRunner(
self._monitor_current_session, self.ping_interval
)
self.closed = False
self.connect_operation_lock = Lock()
self.message_processor = IntervalRunner(self.process_messages, 0.001).start()
self.message_workers = ThreadPoolExecutor(max_workers=concurrency)
self.proxy = proxy
if self.proxy is None or len(self.proxy.strip()) == 0:
env_variable = load_http_proxy_from_env(self.logger)
if env_variable is not None:
self.proxy = env_variable
self.proxy_headers = proxy_headers
self.on_message_listeners = on_message_listeners or []
self.on_error_listeners = on_error_listeners or []
self.on_close_listeners = on_close_listeners or []
|
def __init__(
self,
app_token: str,
logger: Optional[Logger] = None,
web_client: Optional[WebClient] = None,
auto_reconnect_enabled: bool = True,
trace_enabled: bool = False,
all_message_trace_enabled: bool = False,
ping_pong_trace_enabled: bool = False,
ping_interval: float = 5,
receive_buffer_size: int = 1024,
concurrency: int = 10,
proxy: Optional[str] = None,
proxy_headers: Optional[Dict[str, str]] = None,
on_message_listeners: Optional[List[Callable[[str], None]]] = None,
on_error_listeners: Optional[List[Callable[[Exception], None]]] = None,
on_close_listeners: Optional[List[Callable[[int, Optional[str]], None]]] = None,
):
self.app_token = app_token
self.logger = logger or logging.getLogger(__name__)
self.web_client = web_client or WebClient()
self.default_auto_reconnect_enabled = auto_reconnect_enabled
self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
self.trace_enabled = trace_enabled
self.all_message_trace_enabled = all_message_trace_enabled
self.ping_pong_trace_enabled = ping_pong_trace_enabled
self.ping_interval = ping_interval
self.receive_buffer_size = receive_buffer_size
if self.receive_buffer_size < 16:
raise SlackClientConfigurationError("Too small receive_buffer_size detected.")
self.wss_uri = None
self.message_queue = Queue()
self.message_listeners = []
self.socket_mode_request_listeners = []
self.current_session = None
self.current_session_state = ConnectionState()
self.current_session_runner = IntervalRunner(self._run_current_session, 0.5).start()
self.current_app_monitor_started = False
self.current_app_monitor = IntervalRunner(
self._monitor_current_session, self.ping_interval
)
self.closed = False
self.connect_operation_lock = Lock()
self.message_processor = IntervalRunner(self.process_messages, 0.001).start()
self.message_workers = ThreadPoolExecutor(max_workers=concurrency)
self.proxy = proxy
if self.proxy is None or len(self.proxy.strip()) == 0:
env_variable = load_http_proxy_from_env(self.logger)
if env_variable is not None:
self.proxy = env_variable
self.proxy_headers = proxy_headers
self.on_message_listeners = on_message_listeners or []
self.on_error_listeners = on_error_listeners or []
self.on_close_listeners = on_close_listeners or []
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def connect(self) -> None:
old_session: Optional[Connection] = self.current_session
old_current_session_state: ConnectionState = self.current_session_state
if self.wss_uri is None:
self.wss_uri = self.issue_new_wss_url()
current_session = Connection(
url=self.wss_uri,
logger=self.logger,
ping_interval=self.ping_interval,
trace_enabled=self.trace_enabled,
all_message_trace_enabled=self.all_message_trace_enabled,
ping_pong_trace_enabled=self.ping_pong_trace_enabled,
receive_buffer_size=self.receive_buffer_size,
proxy=self.proxy,
proxy_headers=self.proxy_headers,
on_message_listener=self._on_message,
on_error_listener=self._on_error,
on_close_listener=self._on_close,
)
current_session.connect()
if old_current_session_state is not None:
old_current_session_state.terminated = True
if old_session is not None:
old_session.close()
self.current_session = current_session
self.current_session_state = ConnectionState()
self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
if not self.current_app_monitor_started:
self.current_app_monitor_started = True
self.current_app_monitor.start()
self.logger.info(
f"A new session has been established (session id: {self.session_id()})"
)
|
def connect(self) -> None:
old_session: Optional[Connection] = self.current_session
if self.wss_uri is None:
self.wss_uri = self.issue_new_wss_url()
self.current_session = Connection(
url=self.wss_uri,
logger=self.logger,
ping_interval=self.ping_interval,
trace_enabled=self.trace_enabled,
all_message_trace_enabled=self.all_message_trace_enabled,
ping_pong_trace_enabled=self.ping_pong_trace_enabled,
receive_buffer_size=self.receive_buffer_size,
proxy=self.proxy,
proxy_headers=self.proxy_headers,
on_message_listener=self._on_message,
on_error_listener=self._on_error,
on_close_listener=self._on_close,
)
self.current_session.connect()
self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
if old_session is not None:
old_session.close()
self.current_session_state.terminated = True
if not self.current_app_monitor_started:
self.current_app_monitor_started = True
self.current_app_monitor.start()
self.logger.info(
f"A new session has been established (session id: {self.session_id()})"
)
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def __init__(
self,
*,
token: Optional[str] = None,
web_client: Optional[WebClient] = None,
auto_reconnect_enabled: bool = True,
ssl: Optional[SSLContext] = None,
proxy: Optional[str] = None,
timeout: int = 30,
base_url: str = WebClient.BASE_URL,
headers: Optional[dict] = None,
ping_interval: int = 5,
concurrency: int = 10,
logger: Optional[logging.Logger] = None,
on_message_listeners: Optional[List[Callable[[str], None]]] = None,
on_error_listeners: Optional[List[Callable[[Exception], None]]] = None,
on_close_listeners: Optional[List[Callable[[int, Optional[str]], None]]] = None,
trace_enabled: bool = False,
all_message_trace_enabled: bool = False,
ping_pong_trace_enabled: bool = False,
):
self.token = token.strip() if token is not None else None
self.bot_id = None
self.default_auto_reconnect_enabled = auto_reconnect_enabled
# You may want temporarily turn off the auto_reconnect as necessary
self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
self.ssl = ssl
self.proxy = proxy
self.timeout = timeout
self.base_url = base_url
self.headers = headers
self.ping_interval = ping_interval
self.logger = logger or logging.getLogger(__name__)
if self.proxy is None or len(self.proxy.strip()) == 0:
env_variable = load_http_proxy_from_env(self.logger)
if env_variable is not None:
self.proxy = env_variable
self.web_client = web_client or WebClient(
token=self.token,
base_url=self.base_url,
timeout=self.timeout,
ssl=self.ssl,
proxy=self.proxy,
headers=self.headers,
logger=logger,
)
self.on_message_listeners = on_message_listeners or []
self.on_error_listeners = on_error_listeners or []
self.on_close_listeners = on_close_listeners or []
self.trace_enabled = trace_enabled
self.all_message_trace_enabled = all_message_trace_enabled
self.ping_pong_trace_enabled = ping_pong_trace_enabled
self.message_queue = Queue()
self.message_listeners = []
self.socket_mode_request_listeners = []
self.current_session = None
self.current_session_state = ConnectionState()
self.current_session_runner = IntervalRunner(self._run_current_session, 0.5).start()
self.wss_uri = None
self.current_app_monitor_started = False
self.current_app_monitor = IntervalRunner(
self._monitor_current_session,
self.ping_interval,
)
self.closed = False
self.connect_operation_lock = Lock()
self.message_processor = IntervalRunner(self.process_messages, 0.001).start()
self.message_workers = ThreadPoolExecutor(max_workers=concurrency)
|
def __init__(
self,
*,
token: Optional[str] = None,
web_client: Optional[WebClient] = None,
auto_reconnect_enabled: bool = True,
ssl: Optional[SSLContext] = None,
proxy: Optional[str] = None,
timeout: int = 30,
base_url: str = WebClient.BASE_URL,
headers: Optional[dict] = None,
ping_interval: int = 10,
concurrency: int = 10,
logger: Optional[logging.Logger] = None,
on_message_listeners: Optional[List[Callable[[str], None]]] = None,
on_error_listeners: Optional[List[Callable[[Exception], None]]] = None,
on_close_listeners: Optional[List[Callable[[int, Optional[str]], None]]] = None,
trace_enabled: bool = False,
all_message_trace_enabled: bool = False,
ping_pong_trace_enabled: bool = False,
):
self.token = token.strip() if token is not None else None
self.bot_id = None
self.default_auto_reconnect_enabled = auto_reconnect_enabled
# You may want temporarily turn off the auto_reconnect as necessary
self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
self.ssl = ssl
self.proxy = proxy
self.timeout = timeout
self.base_url = base_url
self.headers = headers
self.ping_interval = ping_interval
self.logger = logger or logging.getLogger(__name__)
if self.proxy is None or len(self.proxy.strip()) == 0:
env_variable = load_http_proxy_from_env(self.logger)
if env_variable is not None:
self.proxy = env_variable
self.web_client = web_client or WebClient(
token=self.token,
base_url=self.base_url,
timeout=self.timeout,
ssl=self.ssl,
proxy=self.proxy,
headers=self.headers,
logger=logger,
)
self.on_message_listeners = on_message_listeners or []
self.on_error_listeners = on_error_listeners or []
self.on_close_listeners = on_close_listeners or []
self.trace_enabled = trace_enabled
self.all_message_trace_enabled = all_message_trace_enabled
self.ping_pong_trace_enabled = ping_pong_trace_enabled
self.message_queue = Queue()
self.message_listeners = []
self.socket_mode_request_listeners = []
self.current_session = None
self.current_session_state = ConnectionState()
self.current_session_runner = IntervalRunner(self._run_current_session, 0.5).start()
self.current_app_monitor_started = False
self.current_app_monitor = IntervalRunner(
self._monitor_current_session,
self.ping_interval,
)
self.closed = False
self.connect_operation_lock = Lock()
self.message_processor = IntervalRunner(self.process_messages, 0.001).start()
self.message_workers = ThreadPoolExecutor(max_workers=concurrency)
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def issue_new_wss_url(self) -> str:
"""Acquires a new WSS URL using rtm.connect API method"""
try:
api_response = self.web_client.rtm_connect()
return api_response["url"]
except SlackApiError as e:
if e.response["error"] == "ratelimited":
delay = int(e.response.headers.get("Retry-After", "30")) # Tier1
self.logger.info(f"Rate limited. Retrying in {delay} seconds...")
time.sleep(delay)
# Retry to issue a new WSS URL
return self.issue_new_wss_url()
else:
# other errors
self.logger.error(f"Failed to retrieve WSS URL: {e}")
raise e
|
def issue_new_wss_url(self) -> str:
"""Acquires a new WSS URL using rtm.connect API method"""
try:
api_response = self.web_client.rtm_connect()
return api_response["url"]
except SlackApiError as e:
self.logger.error(f"Failed to retrieve WSS URL: {e}")
raise e
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def connect_to_new_endpoint(self, force: bool = False):
"""Acquires a new WSS URL and tries to connect to the endpoint."""
with self.connect_operation_lock:
if force or not self.is_connected():
self.logger.info("Connecting to a new endpoint...")
self.wss_uri = self.issue_new_wss_url()
self.connect()
self.logger.info("Connected to a new endpoint...")
|
def connect_to_new_endpoint(self, force: bool = False):
"""Acquires a new WSS URL and tries to connect to the endpoint."""
try:
self.connect_operation_lock.acquire(blocking=True, timeout=5)
if force or not self.is_connected():
self.logger.info("Connecting to a new endpoint...")
self.wss_uri = self.issue_new_wss_url()
self.connect()
self.logger.info("Connected to a new endpoint...")
finally:
self.connect_operation_lock.release()
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def connect(self):
"""Starts talking to the RTM server through a WebSocket connection"""
if self.bot_id is None:
self.bot_id = self.web_client.auth_test()["bot_id"]
old_session: Optional[Connection] = self.current_session
if self.wss_uri is None:
self.wss_uri = self.issue_new_wss_url()
self.current_session = Connection(
url=self.wss_uri,
logger=self.logger,
ping_interval=self.ping_interval,
trace_enabled=self.trace_enabled,
all_message_trace_enabled=self.all_message_trace_enabled,
ping_pong_trace_enabled=self.ping_pong_trace_enabled,
receive_buffer_size=1024,
proxy=self.proxy,
on_message_listener=self.run_all_message_listeners,
on_error_listener=self.run_all_error_listeners,
on_close_listener=self.run_all_close_listeners,
connection_type_name="RTM",
)
self.current_session.connect()
self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
if old_session is not None:
old_session.close()
self.current_session_state.terminated = True
if not self.current_app_monitor_started:
self.current_app_monitor_started = True
self.current_app_monitor.start()
self.logger.info(
f"A new session has been established (session id: {self.session_id()})"
)
|
def connect(self):
"""Starts talking to the RTM server through a WebSocket connection"""
if self.bot_id is None:
self.bot_id = self.web_client.auth_test()["bot_id"]
old_session: Optional[Connection] = self.current_session
self.current_session = Connection(
url=self.issue_new_wss_url(),
logger=self.logger,
ping_interval=self.ping_interval,
trace_enabled=self.trace_enabled,
all_message_trace_enabled=self.all_message_trace_enabled,
ping_pong_trace_enabled=self.ping_pong_trace_enabled,
receive_buffer_size=1024,
proxy=self.proxy,
on_message_listener=self.run_all_message_listeners,
on_error_listener=self.run_all_error_listeners,
on_close_listener=self.run_all_close_listeners,
connection_type_name="RTM",
)
self.current_session.connect()
self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
if old_session is not None:
old_session.close()
self.current_session_state.terminated = True
if not self.current_app_monitor_started:
self.current_app_monitor_started = True
self.current_app_monitor.start()
self.logger.info(
f"A new session has been established (session id: {self.session_id()})"
)
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
async def issue_new_wss_url(self) -> str:
try:
response = await self.web_client.apps_connections_open(app_token=self.app_token)
return response["url"]
except SlackApiError as e:
if e.response["error"] == "ratelimited":
# NOTE: ratelimited errors rarely occur with this endpoint
delay = int(e.response.headers.get("Retry-After", "30")) # Tier1
self.logger.info(f"Rate limited. Retrying in {delay} seconds...")
await asyncio.sleep(delay)
# Retry to issue a new WSS URL
return await self.issue_new_wss_url()
else:
# other errors
self.logger.error(f"Failed to retrieve WSS URL: {e}")
raise e
|
async def issue_new_wss_url(self) -> str:
try:
response = await self.web_client.apps_connections_open(app_token=self.app_token)
return response["url"]
except SlackApiError as e:
self.logger.error(f"Failed to retrieve Socket Mode URL: {e}")
raise e
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def __init__(
self,
app_token: str,
logger: Optional[Logger] = None,
web_client: Optional[WebClient] = None,
auto_reconnect_enabled: bool = True,
trace_enabled: bool = False,
all_message_trace_enabled: bool = False,
ping_pong_trace_enabled: bool = False,
ping_interval: float = 5,
receive_buffer_size: int = 1024,
concurrency: int = 10,
proxy: Optional[str] = None,
proxy_headers: Optional[Dict[str, str]] = None,
on_message_listeners: Optional[List[Callable[[str], None]]] = None,
on_error_listeners: Optional[List[Callable[[Exception], None]]] = None,
on_close_listeners: Optional[List[Callable[[int, Optional[str]], None]]] = None,
):
self.app_token = app_token
self.logger = logger or logging.getLogger(__name__)
self.web_client = web_client or WebClient()
self.default_auto_reconnect_enabled = auto_reconnect_enabled
self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
self.trace_enabled = trace_enabled
self.all_message_trace_enabled = all_message_trace_enabled
self.ping_pong_trace_enabled = ping_pong_trace_enabled
self.ping_interval = ping_interval
self.receive_buffer_size = receive_buffer_size
if self.receive_buffer_size < 16:
raise SlackClientConfigurationError("Too small receive_buffer_size detected.")
self.wss_uri = None
self.message_queue = Queue()
self.message_listeners = []
self.socket_mode_request_listeners = []
self.current_session = None
self.current_session_state = ConnectionState()
self.current_session_runner = IntervalRunner(self._run_current_session, 0.5).start()
self.current_app_monitor_started = False
self.current_app_monitor = IntervalRunner(
self._monitor_current_session, self.ping_interval
)
self.closed = False
self.connect_operation_lock = Lock()
self.message_processor = IntervalRunner(self.process_messages, 0.001).start()
self.message_workers = ThreadPoolExecutor(max_workers=concurrency)
self.proxy = proxy
if self.proxy is None or len(self.proxy.strip()) == 0:
env_variable = load_http_proxy_from_env(self.logger)
if env_variable is not None:
self.proxy = env_variable
self.proxy_headers = proxy_headers
self.on_message_listeners = on_message_listeners or []
self.on_error_listeners = on_error_listeners or []
self.on_close_listeners = on_close_listeners or []
|
def __init__(
self,
app_token: str,
logger: Optional[Logger] = None,
web_client: Optional[WebClient] = None,
auto_reconnect_enabled: bool = True,
trace_enabled: bool = False,
all_message_trace_enabled: bool = False,
ping_pong_trace_enabled: bool = False,
ping_interval: float = 10,
receive_buffer_size: int = 1024,
concurrency: int = 10,
proxy: Optional[str] = None,
proxy_headers: Optional[Dict[str, str]] = None,
on_message_listeners: Optional[List[Callable[[str], None]]] = None,
on_error_listeners: Optional[List[Callable[[Exception], None]]] = None,
on_close_listeners: Optional[List[Callable[[int, Optional[str]], None]]] = None,
):
self.app_token = app_token
self.logger = logger or logging.getLogger(__name__)
self.web_client = web_client or WebClient()
self.default_auto_reconnect_enabled = auto_reconnect_enabled
self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
self.trace_enabled = trace_enabled
self.all_message_trace_enabled = all_message_trace_enabled
self.ping_pong_trace_enabled = ping_pong_trace_enabled
self.ping_interval = ping_interval
self.receive_buffer_size = receive_buffer_size
if self.receive_buffer_size < 16:
raise SlackClientConfigurationError("Too small receive_buffer_size detected.")
self.wss_uri = None
self.message_queue = Queue()
self.message_listeners = []
self.socket_mode_request_listeners = []
self.current_session = None
self.current_session_state = ConnectionState()
self.current_session_runner = IntervalRunner(self._run_current_session, 0.5).start()
self.current_app_monitor_started = False
self.current_app_monitor = IntervalRunner(
self._monitor_current_session, self.ping_interval
)
self.closed = False
self.connect_operation_lock = Lock()
self.message_processor = IntervalRunner(self.process_messages, 0.001).start()
self.message_workers = ThreadPoolExecutor(max_workers=concurrency)
self.proxy = proxy
if self.proxy is None or len(self.proxy.strip()) == 0:
env_variable = load_http_proxy_from_env(self.logger)
if env_variable is not None:
self.proxy = env_variable
self.proxy_headers = proxy_headers
self.on_message_listeners = on_message_listeners or []
self.on_error_listeners = on_error_listeners or []
self.on_close_listeners = on_close_listeners or []
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def __init__(
self,
url: str,
logger: Logger,
proxy: Optional[str] = None,
proxy_headers: Optional[Dict[str, str]] = None,
ping_interval: float = 5, # seconds
receive_timeout: float = 3,
receive_buffer_size: int = 1024,
trace_enabled: bool = False,
all_message_trace_enabled: bool = False,
ping_pong_trace_enabled: bool = False,
on_message_listener: Optional[Callable[[str], None]] = None,
on_error_listener: Optional[Callable[[Exception], None]] = None,
on_close_listener: Optional[Callable[[int, Optional[str]], None]] = None,
connection_type_name: str = "Socket Mode",
):
self.url = url
self.logger = logger
self.proxy = proxy
self.proxy_headers = proxy_headers
self.ping_interval = ping_interval
self.receive_timeout = receive_timeout
self.receive_buffer_size = receive_buffer_size
if self.receive_buffer_size < 16:
raise SlackClientConfigurationError("Too small receive_buffer_size detected.")
self.session_id = str(uuid4())
self.trace_enabled = trace_enabled
self.all_message_trace_enabled = all_message_trace_enabled
self.ping_pong_trace_enabled = ping_pong_trace_enabled
self.last_ping_pong_time = None
self.consecutive_check_state_error_count = 0
self.sock = None
# To avoid ssl.SSLError: [SSL: BAD_LENGTH] bad length
self.sock_receive_lock = Lock()
self.sock_send_lock = Lock()
self.on_message_listener = on_message_listener
self.on_error_listener = on_error_listener
self.on_close_listener = on_close_listener
self.connection_type_name = connection_type_name
|
def __init__(
self,
url: str,
logger: Logger,
proxy: Optional[str] = None,
proxy_headers: Optional[Dict[str, str]] = None,
ping_interval: float = 10, # seconds
receive_timeout: float = 5,
receive_buffer_size: int = 1024,
trace_enabled: bool = False,
all_message_trace_enabled: bool = False,
ping_pong_trace_enabled: bool = False,
on_message_listener: Optional[Callable[[str], None]] = None,
on_error_listener: Optional[Callable[[Exception], None]] = None,
on_close_listener: Optional[Callable[[int, Optional[str]], None]] = None,
connection_type_name: str = "Socket Mode",
):
self.url = url
self.logger = logger
self.proxy = proxy
self.proxy_headers = proxy_headers
self.ping_interval = ping_interval
self.receive_timeout = receive_timeout
self.receive_buffer_size = receive_buffer_size
if self.receive_buffer_size < 16:
raise SlackClientConfigurationError("Too small receive_buffer_size detected.")
self.session_id = str(uuid4())
self.trace_enabled = trace_enabled
self.all_message_trace_enabled = all_message_trace_enabled
self.ping_pong_trace_enabled = ping_pong_trace_enabled
self.last_ping_pong_time = None
self.consecutive_check_state_error_count = 0
self.sock = None
self.on_message_listener = on_message_listener
self.on_error_listener = on_error_listener
self.on_close_listener = on_close_listener
self.connection_type_name = connection_type_name
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def connect(self) -> None:
try:
parsed_url = urlparse(self.url.strip())
hostname: str = parsed_url.hostname
port: int = parsed_url.port or (443 if parsed_url.scheme == "wss" else 80)
if self.trace_enabled:
self.logger.debug(
f"Connecting to the address for handshake: {hostname}:{port} "
f"(session id: {self.session_id})"
)
sock: Union[ssl.SSLSocket, socket] = _establish_new_socket_connection(
session_id=self.session_id,
server_hostname=hostname,
server_port=port,
logger=self.logger,
sock_send_lock=self.sock_send_lock,
receive_timeout=self.receive_timeout,
proxy=self.proxy,
proxy_headers=self.proxy_headers,
trace_enabled=self.trace_enabled,
)
# WebSocket handshake
try:
path = f"{parsed_url.path}?{parsed_url.query}"
sec_websocket_key = _generate_sec_websocket_key()
message = f"""GET {path} HTTP/1.1
Host: {parsed_url.hostname}
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: {sec_websocket_key}
Sec-WebSocket-Version: 13
"""
req: str = "\r\n".join([line.lstrip() for line in message.split("\n")])
if self.trace_enabled:
self.logger.debug(
f"{self.connection_type_name} handshake request (session id: {self.session_id}):\n{req}"
)
with self.sock_send_lock:
sock.send(req.encode("utf-8"))
status, headers, text = _parse_handshake_response(sock)
if self.trace_enabled:
self.logger.debug(
f"{self.connection_type_name} handshake response (session id: {self.session_id}):\n{text}"
)
# HTTP/1.1 101 Switching Protocols
if status == 101:
if not _validate_sec_websocket_accept(sec_websocket_key, headers):
raise SlackClientNotConnectedError(
f"Invalid response header detected in {self.connection_type_name} handshake response"
f" (session id: {self.session_id})"
)
# set this successfully connected socket
self.sock = sock
self.ping(f"{self.session_id}:{time.time()}")
else:
message = (
f"Received an unexpected response for handshake "
f"(status: {status}, response: {text}, session id: {self.session_id})"
)
self.logger.warning(message)
except socket.error as e:
code: Optional[int] = None
if e.args and len(e.args) > 1 and isinstance(e.args[0], int):
code = e.args[0]
if code is not None:
self.logger.exception(
f"Error code: {code} (session id: {self.session_id}, error: {e})"
)
raise
except Exception as e:
self.logger.exception(
f"Failed to establish a connection (session id: {self.session_id}, error: {e})"
)
self.disconnect()
|
def connect(self) -> None:
try:
parsed_url = urlparse(self.url.strip())
hostname: str = parsed_url.hostname
port: int = parsed_url.port or (443 if parsed_url.scheme == "wss" else 80)
if self.trace_enabled:
self.logger.debug(
f"Connecting to the address for handshake: {hostname}:{port} "
f"(session id: {self.session_id})"
)
sock: Union[ssl.SSLSocket, socket] = _establish_new_socket_connection(
session_id=self.session_id,
server_hostname=hostname,
server_port=port,
logger=self.logger,
receive_timeout=self.receive_timeout,
proxy=self.proxy,
proxy_headers=self.proxy_headers,
trace_enabled=self.trace_enabled,
)
# WebSocket handshake
try:
path = f"{parsed_url.path}?{parsed_url.query}"
sec_websocket_key = _generate_sec_websocket_key()
message = f"""GET {path} HTTP/1.1
Host: {parsed_url.hostname}
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: {sec_websocket_key}
Sec-WebSocket-Version: 13
"""
req: str = "\r\n".join([line.lstrip() for line in message.split("\n")])
if self.trace_enabled:
self.logger.debug(
f"{self.connection_type_name} handshake request (session id: {self.session_id}):\n{req}"
)
sock.send(req.encode("utf-8"))
sock.settimeout(self.receive_timeout)
status, headers, text = _parse_handshake_response(sock)
if self.trace_enabled:
self.logger.debug(
f"{self.connection_type_name} handshake response (session id: {self.session_id}):\n{text}"
)
# HTTP/1.1 101 Switching Protocols
if status == 101:
if not _validate_sec_websocket_accept(sec_websocket_key, headers):
raise SlackClientNotConnectedError(
f"Invalid response header detected in {self.connection_type_name} handshake response"
f" (session id: {self.session_id})"
)
# set this successfully connected socket
self.sock = sock
self.ping(f"{self.session_id}:{time.time()}")
else:
message = (
f"Received an unexpected response for handshake "
f"(status: {status}, response: {text}, session id: {self.session_id})"
)
self.logger.warning(message)
except socket.error as e:
code: Optional[int] = None
if e.args and len(e.args) > 1 and isinstance(e.args[0], int):
code = e.args[0]
if code is not None:
self.logger.exception(
f"Error code: {code} (session id: {self.session_id}, error: {e})"
)
raise
except Exception as e:
self.logger.exception(
f"Failed to establish a connection (session id: {self.session_id}, error: {e})"
)
self.disconnect()
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def ping(self, payload: Union[str, bytes] = "") -> None:
if self.trace_enabled and self.ping_pong_trace_enabled:
if isinstance(payload, bytes):
payload = payload.decode("utf-8")
self.logger.debug(
"Sending a ping data frame "
f"(session id: {self.session_id}, payload: {payload})"
)
data = _build_data_frame_for_sending(payload, FrameHeader.OPCODE_PING)
with self.sock_send_lock:
self.sock.send(data)
|
def ping(self, payload: Union[str, bytes] = "") -> None:
if self.trace_enabled and self.ping_pong_trace_enabled:
if isinstance(payload, bytes):
payload = payload.decode("utf-8")
self.logger.debug(
"Sending a ping data frame "
f"(session id: {self.session_id}, payload: {payload})"
)
data = _build_data_frame_for_sending(payload, FrameHeader.OPCODE_PING)
self.sock.send(data)
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def pong(self, payload: Union[str, bytes] = "") -> None:
if self.trace_enabled and self.ping_pong_trace_enabled:
if isinstance(payload, bytes):
payload = payload.decode("utf-8")
self.logger.debug(
"Sending a pong data frame "
f"(session id: {self.session_id}, payload: {payload})"
)
data = _build_data_frame_for_sending(payload, FrameHeader.OPCODE_PONG)
with self.sock_send_lock:
self.sock.send(data)
|
def pong(self, payload: Union[str, bytes] = "") -> None:
if self.trace_enabled and self.ping_pong_trace_enabled:
if isinstance(payload, bytes):
payload = payload.decode("utf-8")
self.logger.debug(
"Sending a pong data frame "
f"(session id: {self.session_id}, payload: {payload})"
)
data = _build_data_frame_for_sending(payload, FrameHeader.OPCODE_PONG)
self.sock.send(data)
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def send(self, payload: str) -> None:
if self.trace_enabled:
if isinstance(payload, bytes):
payload = payload.decode("utf-8")
self.logger.debug(
"Sending a text data frame "
f"(session id: {self.session_id}, payload: {payload})"
)
data = _build_data_frame_for_sending(payload, FrameHeader.OPCODE_TEXT)
with self.sock_send_lock:
self.sock.send(data)
|
def send(self, payload: str) -> None:
if self.trace_enabled:
if isinstance(payload, bytes):
payload = payload.decode("utf-8")
self.logger.debug(
"Sending a text data frame "
f"(session id: {self.session_id}, payload: {payload})"
)
data = _build_data_frame_for_sending(payload, FrameHeader.OPCODE_TEXT)
self.sock.send(data)
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def check_state(self) -> None:
try:
if self.sock is not None:
try:
self.ping(f"{self.session_id}:{time.time()}")
except ssl.SSLZeroReturnError as e:
self.logger.info(
"Unable to send a ping message. Closing the connection..."
f" (session id: {self.session_id}, reason: {e})"
)
self.disconnect()
return
if self.last_ping_pong_time is not None:
disconnected_seconds = int(time.time() - self.last_ping_pong_time)
if self.trace_enabled and disconnected_seconds > self.ping_interval:
message = (
f"{disconnected_seconds} seconds have passed "
f"since this client last received a pong response from the server "
f"(session id: {self.session_id})"
)
self.logger.debug(message)
is_stale = disconnected_seconds > self.ping_interval * 4
if is_stale:
self.logger.info(
"The connection seems to be stale. Disconnecting..."
f" (session id: {self.session_id},"
f" reason: disconnected for {disconnected_seconds}+ seconds)"
)
self.disconnect()
return
else:
self.logger.debug(
f"This connection is already closed. (session id: {self.session_id})"
)
self.consecutive_check_state_error_count = 0
except Exception as e:
self.logger.exception(
"Failed to check the state of sock "
f"(session id: {self.session_id}, error: {type(e).__name__}, message: {e})"
)
self.consecutive_check_state_error_count += 1
if self.consecutive_check_state_error_count >= 5:
self.disconnect()
|
def check_state(self) -> None:
try:
if self.sock is not None:
is_stale = (
self.last_ping_pong_time is not None
and time.time() - self.last_ping_pong_time > self.ping_interval * 2
)
if is_stale:
self.logger.info(
"The connection seems to be stale. Disconnecting..."
f" (session id: {self.session_id})"
)
self.disconnect()
else:
self.ping(f"{self.session_id}:{time.time()}")
else:
self.logger.debug(
f"This connection is already closed. (session id: {self.session_id})"
)
self.consecutive_check_state_error_count = 0
except Exception as e:
self.logger.exception(
"Failed to check the state of sock "
f"(session id: {self.session_id}, error: {type(e).__name__}, message: {e})"
)
self.consecutive_check_state_error_count += 1
if self.consecutive_check_state_error_count >= 5:
self.disconnect()
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def run_until_completion(self, state: ConnectionState) -> None:
repeated_messages = {"payload": 0}
ping_count = 0
pong_count = 0
ping_pong_log_summary_size = 1000
while not state.terminated:
try:
if self.is_active():
received_messages: List[Tuple[Optional[FrameHeader], bytes]] = (
_receive_messages(
sock=self.sock,
sock_receive_lock=self.sock_receive_lock,
logger=self.logger,
receive_buffer_size=self.receive_buffer_size,
all_message_trace_enabled=self.all_message_trace_enabled,
)
)
for message in received_messages:
header, data = message
# -----------------
# trace logging
if self.trace_enabled is True:
opcode: str = (
_to_readable_opcode(header.opcode) if header else "-"
)
payload: str = _parse_text_payload(data, self.logger)
count: Optional[int] = repeated_messages.get(payload)
if count is None:
count = 1
else:
count += 1
repeated_messages = {payload: count}
if (
not self.ping_pong_trace_enabled
and header is not None
and header.opcode is not None
):
if header.opcode == FrameHeader.OPCODE_PING:
ping_count += 1
if ping_count % ping_pong_log_summary_size == 0:
self.logger.debug(
f"Received {ping_pong_log_summary_size} ping data frame "
f"(session id: {self.session_id})"
)
ping_count = 0
if header.opcode == FrameHeader.OPCODE_PONG:
pong_count += 1
if pong_count % ping_pong_log_summary_size == 0:
self.logger.debug(
f"Received {ping_pong_log_summary_size} pong data frame "
f"(session id: {self.session_id})"
)
pong_count = 0
ping_pong_to_skip = (
header is not None
and header.opcode is not None
and (
header.opcode == FrameHeader.OPCODE_PING
or header.opcode == FrameHeader.OPCODE_PONG
)
and not self.ping_pong_trace_enabled
)
if not ping_pong_to_skip and count < 5:
# if so many same payloads came in, the trace logging should be skipped.
# e.g., after receiving "UNAUTHENTICATED: cache_error", many "opcode: -, payload: "
self.logger.debug(
"Received a new data frame "
f"(session id: {self.session_id}, opcode: {opcode}, payload: {payload})"
)
if header is None:
# Skip no header message
continue
# -----------------
# message with opcode
if header.opcode == FrameHeader.OPCODE_PING:
self.pong(data)
elif header.opcode == FrameHeader.OPCODE_PONG:
str_message = data.decode("utf-8")
elements = str_message.split(":")
if len(elements) >= 2:
session_id, ping_time = elements[0], elements[1]
if self.session_id == session_id:
try:
self.last_ping_pong_time = float(ping_time)
except Exception as e:
self.logger.debug(
"Failed to parse a pong message "
f" (message: {str_message}, error: {e}"
)
elif header.opcode == FrameHeader.OPCODE_TEXT:
if self.on_message_listener is not None:
text = data.decode("utf-8")
self.on_message_listener(text)
elif header.opcode == FrameHeader.OPCODE_CLOSE:
if self.on_close_listener is not None:
if len(data) >= 2:
(code,) = struct.unpack("!H", data[:2])
reason = data[2:].decode("utf-8")
self.on_close_listener(code, reason)
else:
self.on_close_listener(1005, "")
self.disconnect()
state.terminated = True
else:
# Just warn logging
opcode = _to_readable_opcode(header.opcode) if header else "-"
payload: Union[bytes, str] = data
if header.opcode != FrameHeader.OPCODE_BINARY:
try:
payload = (
data.decode("utf-8") if data is not None else ""
)
except Exception as e:
self.logger.info(
f"Failed to convert the data to text {e}"
)
message = (
"Received an unsupported data frame "
f"(session id: {self.session_id}, opcode: {opcode}, payload: {payload})"
)
self.logger.warning(message)
else:
time.sleep(0.2)
except socket.timeout:
time.sleep(0.01)
except OSError as e:
# getting errno.EBADF and the socket is no longer available
if e.errno == 9 and state.terminated:
self.logger.debug(
"The reason why you got [Errno 9] Bad file descriptor here is "
"the socket is no longer available."
)
else:
if self.on_error_listener is not None:
self.on_error_listener(e)
else:
self.logger.exception(
"Got an OSError while receiving data"
f" (session id: {self.session_id}, error: {e})"
)
# As this connection no longer works in any way, terminating it
if self.is_active():
try:
self.disconnect()
except Exception as disconnection_error:
self.logger.exception(
"Failed to disconnect"
f" (session id: {self.session_id}, error: {disconnection_error})"
)
state.terminated = True
break
except Exception as e:
if self.on_error_listener is not None:
self.on_error_listener(e)
else:
self.logger.exception(
"Got an exception while receiving data"
f" (session id: {self.session_id}, error: {e})"
)
state.terminated = True
|
def run_until_completion(self, state: ConnectionState) -> None:
repeated_messages = {"payload": 0}
ping_count = 0
pong_count = 0
ping_pong_log_summary_size = 1000
while not state.terminated:
try:
if self.is_active():
received_messages: List[Tuple[Optional[FrameHeader], bytes]] = (
_receive_messages(
sock=self.sock,
logger=self.logger,
receive_buffer_size=self.receive_buffer_size,
all_message_trace_enabled=self.all_message_trace_enabled,
)
)
for message in received_messages:
header, data = message
# -----------------
# trace logging
if self.trace_enabled is True:
opcode: str = (
_to_readable_opcode(header.opcode) if header else "-"
)
payload: str = _parse_text_payload(data, self.logger)
count: Optional[int] = repeated_messages.get(payload)
if count is None:
count = 1
else:
count += 1
repeated_messages = {payload: count}
if (
not self.ping_pong_trace_enabled
and header is not None
and header.opcode is not None
):
if header.opcode == FrameHeader.OPCODE_PING:
ping_count += 1
if ping_count % ping_pong_log_summary_size == 0:
self.logger.debug(
f"Received {ping_pong_log_summary_size} ping data frame "
f"(session id: {self.session_id})"
)
ping_count = 0
if header.opcode == FrameHeader.OPCODE_PONG:
pong_count += 1
if pong_count % ping_pong_log_summary_size == 0:
self.logger.debug(
f"Received {ping_pong_log_summary_size} pong data frame "
f"(session id: {self.session_id})"
)
pong_count = 0
ping_pong_to_skip = (
header is not None
and header.opcode is not None
and (
header.opcode == FrameHeader.OPCODE_PING
or header.opcode == FrameHeader.OPCODE_PONG
)
and not self.ping_pong_trace_enabled
)
if not ping_pong_to_skip and count < 5:
# if so many same payloads came in, the trace logging should be skipped.
# e.g., after receiving "UNAUTHENTICATED: cache_error", many "opcode: -, payload: "
self.logger.debug(
"Received a new data frame "
f"(session id: {self.session_id}, opcode: {opcode}, payload: {payload})"
)
if header is None:
# Skip no header message
continue
# -----------------
# message with opcode
if header.opcode == FrameHeader.OPCODE_PING:
self.pong(data)
elif header.opcode == FrameHeader.OPCODE_PONG:
str_message = data.decode("utf-8")
elements = str_message.split(":")
if len(elements) >= 2:
session_id, ping_time = elements[0], elements[1]
if self.session_id == session_id:
try:
self.last_ping_pong_time = float(ping_time)
except Exception as e:
self.logger.debug(
"Failed to parse a pong message "
f" (message: {str_message}, error: {e}"
)
elif header.opcode == FrameHeader.OPCODE_TEXT:
if self.on_message_listener is not None:
text = data.decode("utf-8")
self.on_message_listener(text)
elif header.opcode == FrameHeader.OPCODE_CLOSE:
if self.on_close_listener is not None:
if len(data) >= 2:
(code,) = struct.unpack("!H", data[:2])
reason = data[2:].decode("utf-8")
self.on_close_listener(code, reason)
else:
self.on_close_listener(1005, "")
self.disconnect()
state.terminated = True
else:
# Just warn logging
opcode = _to_readable_opcode(header.opcode) if header else "-"
payload: Union[bytes, str] = data
if header.opcode != FrameHeader.OPCODE_BINARY:
try:
payload = (
data.decode("utf-8") if data is not None else ""
)
except Exception as e:
self.logger.info(
f"Failed to convert the data to text {e}"
)
message = (
"Received an unsupported data frame "
f"(session id: {self.session_id}, opcode: {opcode}, payload: {payload})"
)
self.logger.warning(message)
else:
time.sleep(0.2)
except socket.timeout:
time.sleep(0.01)
except OSError as e:
# getting errno.EBADF and the socket is no longer available
if e.errno == 9 and state.terminated:
self.logger.debug(
"The reason why you got [Errno 9] Bad file descriptor here is "
"the socket is no longer available."
)
else:
if self.on_error_listener is not None:
self.on_error_listener(e)
else:
self.logger.exception(
"Got an OSError while receiving data"
f" (session id: {self.session_id}, error: {e})"
)
# As this connection no longer works in any way, terminating it
if self.is_active():
try:
self.disconnect()
except Exception as disconnection_error:
self.logger.exception(
"Failed to disconnect"
f" (session id: {self.session_id}, error: {disconnection_error})"
)
state.terminated = True
break
except Exception as e:
if self.on_error_listener is not None:
self.on_error_listener(e)
else:
self.logger.exception(
"Got an exception while receiving data"
f" (session id: {self.session_id}, error: {e})"
)
state.terminated = True
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def _establish_new_socket_connection(
session_id: str,
server_hostname: str,
server_port: int,
logger: Logger,
sock_send_lock: Lock,
receive_timeout: float,
proxy: Optional[str],
proxy_headers: Optional[Dict[str, str]],
trace_enabled: bool,
) -> Union[ssl.SSLSocket, Socket]:
if proxy is not None:
parsed_proxy = urlparse(proxy)
proxy_host, proxy_port = parsed_proxy.hostname, parsed_proxy.port or 80
proxy_addr = socket.getaddrinfo(
proxy_host,
proxy_port,
0,
socket.SOCK_STREAM,
socket.SOL_TCP,
)[0]
sock = socket.socket(proxy_addr[0], proxy_addr[1], proxy_addr[2])
if hasattr(socket, "TCP_NODELAY"):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if hasattr(socket, "SO_KEEPALIVE"):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
sock.settimeout(receive_timeout)
sock.connect(proxy_addr[4]) # proxy address
message = [f"CONNECT {server_hostname}:{server_port} HTTP/1.0"]
if parsed_proxy.username is not None and parsed_proxy.password is not None:
# In the case where the proxy is "http://{username}:{password}@{hostname}:{port}"
raw_value = f"{parsed_proxy.username}:{parsed_proxy.password}"
auth = b64encode(raw_value.encode("utf-8")).decode("ascii")
message.append(f"Proxy-Authorization: Basic {auth}")
if proxy_headers is not None:
for k, v in proxy_headers.items():
message.append(f"{k}: {v}")
message.append("")
message.append("")
req: str = "\r\n".join([line.lstrip() for line in message])
if trace_enabled:
logger.debug(f"Proxy connect request (session id: {session_id}):\n{req}")
with sock_send_lock:
sock.send(req.encode("utf-8"))
status, text = _parse_connect_response(sock)
if trace_enabled:
log_message = f"Proxy connect response (session id: {session_id}):\n{text}"
logger.debug(log_message)
if status != 200:
raise Exception(
f"Failed to connect to the proxy (proxy: {proxy}, connect status code: {status})"
)
sock = ssl.SSLContext(ssl.PROTOCOL_SSLv23).wrap_socket(
sock,
do_handshake_on_connect=True,
suppress_ragged_eofs=True,
server_hostname=server_hostname,
)
return sock
if server_port != 443:
addr = socket.getaddrinfo(
server_hostname, server_port, 0, socket.SOCK_STREAM, socket.SOL_TCP
)[0]
# only for library testing
logger.info(
f"Using non-ssl socket to connect ({server_hostname}:{server_port})"
)
sock = Socket(addr[0], addr[1], addr[2])
sock.settimeout(3)
sock.connect((server_hostname, server_port))
return sock
sock = Socket(type=ssl.SOCK_STREAM)
sock = ssl.SSLContext(ssl.PROTOCOL_SSLv23).wrap_socket(
sock,
do_handshake_on_connect=True,
suppress_ragged_eofs=True,
server_hostname=server_hostname,
)
sock.settimeout(receive_timeout)
sock.connect((server_hostname, server_port))
return sock
|
def _establish_new_socket_connection(
session_id: str,
server_hostname: str,
server_port: int,
logger: Logger,
receive_timeout: float,
proxy: Optional[str],
proxy_headers: Optional[Dict[str, str]],
trace_enabled: bool,
) -> Union[ssl.SSLSocket, Socket]:
if proxy is not None:
parsed_proxy = urlparse(proxy)
proxy_host, proxy_port = parsed_proxy.hostname, parsed_proxy.port or 80
proxy_addr = socket.getaddrinfo(
proxy_host,
proxy_port,
0,
socket.SOCK_STREAM,
socket.SOL_TCP,
)[0]
sock = socket.socket(proxy_addr[0], proxy_addr[1], proxy_addr[2])
sock.settimeout(receive_timeout)
sock.connect(proxy_addr[4]) # proxy address
message = [f"CONNECT {server_hostname}:{server_port} HTTP/1.0"]
if parsed_proxy.username is not None and parsed_proxy.password is not None:
# In the case where the proxy is "http://{username}:{password}@{hostname}:{port}"
raw_value = f"{parsed_proxy.username}:{parsed_proxy.password}"
auth = b64encode(raw_value.encode("utf-8")).decode("ascii")
message.append(f"Proxy-Authorization: Basic {auth}")
if proxy_headers is not None:
for k, v in proxy_headers.items():
message.append(f"{k}: {v}")
message.append("")
message.append("")
req: str = "\r\n".join([line.lstrip() for line in message])
if trace_enabled:
logger.debug(f"Proxy connect request (session id: {session_id}):\n{req}")
sock.send(req.encode("utf-8"))
status, text = _parse_connect_response(sock)
if trace_enabled:
log_message = f"Proxy connect response (session id: {session_id}):\n{text}"
logger.debug(log_message)
if status != 200:
raise Exception(
f"Failed to connect to the proxy (proxy: {proxy}, connect status code: {status})"
)
sock = ssl.SSLContext(ssl.PROTOCOL_SSLv23).wrap_socket(
sock,
do_handshake_on_connect=True,
suppress_ragged_eofs=True,
server_hostname=server_hostname,
)
return sock
if server_port != 443:
addr = socket.getaddrinfo(
server_hostname, server_port, 0, socket.SOCK_STREAM, socket.SOL_TCP
)[0]
# only for library testing
logger.info(
f"Using non-ssl socket to connect ({server_hostname}:{server_port})"
)
sock = Socket(addr[0], addr[1], addr[2])
sock.settimeout(3)
sock.connect((server_hostname, server_port))
return sock
sock = Socket(type=ssl.SOCK_STREAM)
sock = ssl.SSLContext(ssl.PROTOCOL_SSLv23).wrap_socket(
sock,
do_handshake_on_connect=True,
suppress_ragged_eofs=True,
server_hostname=server_hostname,
)
sock.settimeout(receive_timeout)
sock.connect((server_hostname, server_port))
return sock
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def _receive_messages(
sock: ssl.SSLSocket,
sock_receive_lock: Lock,
logger: Logger,
receive_buffer_size: int = 1024,
all_message_trace_enabled: bool = False,
) -> List[Tuple[Optional[FrameHeader], bytes]]:
def receive(specific_buffer_size: Optional[int] = None):
size = (
specific_buffer_size
if specific_buffer_size is not None
else receive_buffer_size
)
with sock_receive_lock:
try:
received_bytes = sock.recv(size)
if all_message_trace_enabled:
if len(received_bytes) > 0:
logger.debug(f"Received bytes: {received_bytes}")
return received_bytes
except OSError as e:
if e.errno == errno.EBADF:
logger.debug("The connection seems to be already closed.")
return bytes()
raise e
return _fetch_messages(
messages=[],
receive=receive,
remaining_bytes=None,
current_mask_key=None,
current_header=None,
current_data=bytes(),
logger=logger,
)
|
def _receive_messages(
sock: ssl.SSLSocket,
logger: Logger,
receive_buffer_size: int = 1024,
all_message_trace_enabled: bool = False,
) -> List[Tuple[Optional[FrameHeader], bytes]]:
def receive(specific_buffer_size: Optional[int] = None):
size = (
specific_buffer_size
if specific_buffer_size is not None
else receive_buffer_size
)
received_bytes = sock.recv(size)
if all_message_trace_enabled:
if len(received_bytes) > 0:
logger.debug(f"Received bytes: {received_bytes}")
return received_bytes
return _fetch_messages(
messages=[],
receive=receive,
remaining_bytes=None,
current_mask_key=None,
current_header=None,
current_data=bytes(),
logger=logger,
)
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def receive(specific_buffer_size: Optional[int] = None):
size = (
specific_buffer_size
if specific_buffer_size is not None
else receive_buffer_size
)
with sock_receive_lock:
try:
received_bytes = sock.recv(size)
if all_message_trace_enabled:
if len(received_bytes) > 0:
logger.debug(f"Received bytes: {received_bytes}")
return received_bytes
except OSError as e:
if e.errno == errno.EBADF:
logger.debug("The connection seems to be already closed.")
return bytes()
raise e
|
def receive(specific_buffer_size: Optional[int] = None):
size = (
specific_buffer_size
if specific_buffer_size is not None
else receive_buffer_size
)
received_bytes = sock.recv(size)
if all_message_trace_enabled:
if len(received_bytes) > 0:
logger.debug(f"Received bytes: {received_bytes}")
return received_bytes
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def issue_new_wss_url(self) -> str:
try:
response = self.web_client.apps_connections_open(app_token=self.app_token)
return response["url"]
except SlackApiError as e:
if e.response["error"] == "ratelimited":
# NOTE: ratelimited errors rarely occur with this endpoint
delay = int(e.response.headers.get("Retry-After", "30")) # Tier1
self.logger.info(f"Rate limited. Retrying in {delay} seconds...")
time.sleep(delay)
# Retry to issue a new WSS URL
return self.issue_new_wss_url()
else:
# other errors
self.logger.error(f"Failed to retrieve WSS URL: {e}")
raise e
|
def issue_new_wss_url(self) -> str:
try:
response = self.web_client.apps_connections_open(app_token=self.app_token)
return response["url"]
except SlackApiError as e:
self.logger.error(f"Failed to retrieve Socket Mode URL: {e}")
raise e
|
https://github.com/slackapi/python-slack-sdk/issues/960
|
2021-02-14 18:19:49,579 ERROR slack_sdk.rtm.v2 Failed to establish a connection (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: _ssl.c:1108: The handshake operation timed out)
Traceback (most recent call last):
File "/opt/errbot/lib/python3.8/site-packages/slack_sdk/socket_mode/builtin/connection.py", line 109, in connect
sock.connect((hostname, port))
File "/usr/lib/python3.8/ssl.py", line 1342, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.8/ssl.py", line 1333, in _real_connect
self.do_handshake()
File "/usr/lib/python3.8/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
socket.timeout: _ssl.c:1108: The handshake operation timed out
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 The connection has been closed (session id: b88f63ee-d644-45a8-bf18-be36c8673728)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 A new session has been established (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:49,579 INFO slack_sdk.rtm.v2 Connected to a new endpoint...
2021-02-14 18:19:59,590 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:19:59,590 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:00,075 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:10,092 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,117 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:10,121 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:10,339 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:20,350 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:20,350 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
2021-02-14 18:20:20,556 ERROR slack_sdk.rtm.v2 Failed to retrieve WSS URL: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'}
2021-02-14 18:20:20,557 ERROR slack_sdk.rtm.v2 Failed to check the current session or reconnect to the server (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81, error: SlackApiError, message: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'ratelimited'})
2021-02-14 18:20:30,567 DEBUG slack_sdk.rtm.v2 This connection is already closed. (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 The session seems to be already closed. Going to reconnect... (session id: 18e8f520-5e64-443c-98ed-089ab1ef6f81)
2021-02-14 18:20:30,567 INFO slack_sdk.rtm.v2 Connecting to a new endpoint...
|
SlackApiError
|
def _build_req_args(
*,
token: Optional[str],
http_verb: str,
files: dict,
data: dict,
default_params: dict,
params: dict,
json: dict, # skipcq: PYL-W0621
headers: dict,
auth: dict,
ssl: Optional[SSLContext],
proxy: Optional[str],
) -> dict:
has_json = json is not None
has_files = files is not None
if has_json and http_verb != "POST":
msg = "Json data can only be submitted as POST requests. GET requests should use the 'params' argument."
raise SlackRequestError(msg)
if data is not None and isinstance(data, dict):
data = {k: v for k, v in data.items() if v is not None}
_set_default_params(data, default_params)
if files is not None and isinstance(files, dict):
files = {k: v for k, v in files.items() if v is not None}
# NOTE: We do not need to all #_set_default_params here
# because other parameters in binary data requests can exist
# only in either data or params, not in files.
if params is not None and isinstance(params, dict):
params = {k: v for k, v in params.items() if v is not None}
_set_default_params(params, default_params)
if json is not None and isinstance(json, dict):
_set_default_params(json, default_params)
token: Optional[str] = token
if params is not None and "token" in params:
token = params.pop("token")
if json is not None and "token" in json:
token = json.pop("token")
req_args = {
"headers": _get_headers(
headers=headers,
token=token,
has_json=has_json,
has_files=has_files,
request_specific_headers=headers,
),
"data": data,
"files": files,
"params": params,
"json": json,
"ssl": ssl,
"proxy": proxy,
"auth": auth,
}
return req_args
|
def _build_req_args(
*,
token: Optional[str],
http_verb: str,
files: dict,
data: dict,
default_params: dict,
params: dict,
json: dict, # skipcq: PYL-W0621
headers: dict,
auth: dict,
ssl: Optional[SSLContext],
proxy: Optional[str],
) -> dict:
has_json = json is not None
has_files = files is not None
if has_json and http_verb != "POST":
msg = "Json data can only be submitted as POST requests. GET requests should use the 'params' argument."
raise SlackRequestError(msg)
if data is not None and isinstance(data, dict):
data = {k: v for k, v in data.items() if v is not None}
_set_default_params(data, default_params)
if files is not None and isinstance(files, dict):
files = {k: v for k, v in files.items() if v is not None}
_set_default_params(files, default_params)
if params is not None and isinstance(params, dict):
params = {k: v for k, v in params.items() if v is not None}
_set_default_params(params, default_params)
if json is not None and isinstance(json, dict):
_set_default_params(json, default_params)
token: Optional[str] = token
if params is not None and "token" in params:
token = params.pop("token")
if json is not None and "token" in json:
token = json.pop("token")
req_args = {
"headers": _get_headers(
headers=headers,
token=token,
has_json=has_json,
has_files=has_files,
request_specific_headers=headers,
),
"data": data,
"files": files,
"params": params,
"json": json,
"ssl": ssl,
"proxy": proxy,
"auth": auth,
}
return req_args
|
https://github.com/slackapi/python-slack-sdk/issues/900
|
Traceback (most recent call last):
File "test.py", line 19, in <module>
response = client.files_upload(channels="#random", file=io.BytesIO(file))
File "../lib/python3.8/site-packages/slack_sdk/web/client.py", line 1482, in files_upload
return self.api_call("files.upload", files={"file": file}, data=kwargs)
File "../lib/python3.8/site-packages/slack_sdk/web/base_client.py", line 127, in api_call
return self._sync_send(api_url=api_url, req_args=req_args)
File "../lib/python3.8/site-packages/slack_sdk/web/base_client.py", line 163, in _sync_send
return self._urllib_api_call(
File "../lib/python3.8/site-packages/slack_sdk/web/base_client.py", line 249, in _urllib_api_call
f: BinaryIO = open(v.encode("utf-8", "ignore"), "rb")
FileNotFoundError: [Errno 2] No such file or directory: b'fake'
|
FileNotFoundError
|
def onboarding_message(payload):
"""Create and send an onboarding welcome message to new users. Save the
time stamp of this message so we can update this message in the future.
"""
event = payload.get("event", {})
# Get the id of the Slack user associated with the incoming event
user_id = event.get("user", {}).get("id")
# Open a DM with the new user.
response = slack_web_client.conversations_open(users=user_id)
channel = response["channel"]["id"]
# Post the onboarding message.
start_onboarding(user_id, channel)
|
def onboarding_message(payload):
"""Create and send an onboarding welcome message to new users. Save the
time stamp of this message so we can update this message in the future.
"""
event = payload.get("event", {})
# Get the id of the Slack user associated with the incoming event
user_id = event.get("user", {}).get("id")
# Open a DM with the new user.
response = slack_web_client.im_open(user=user_id)
channel = response["channel"]["id"]
# Post the onboarding message.
start_onboarding(user_id, channel)
|
https://github.com/slackapi/python-slack-sdk/issues/889
|
Traceback (most recent call last):
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\slackeventsapi\server.py", line 120, in event
self.emitter.emit(event_type, event_data)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\pyee\_base.py", line 113, in emit
handled = self._call_handlers(event, args, kwargs)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\pyee\_base.py", line 96, in _call_handlers
self._emit_run(f, args, kwargs)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\pyee\_base.py", line 81, in _emit_run
f(*args, **kwargs)
File "D:/_pyCharm/mySlackWebClient2/app.py", line 57, in onboarding_message
response = slack_web_client.conversations_open(user=user_id)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\slack_sdk\web\client.py", line 1224, in conversations_open
return self.api_call("conversations.open", json=kwargs)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\slack_sdk\web\base_client.py", line 121, in api_call
return self._sync_send(api_url=api_url, req_args=req_args)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\slack_sdk\web\base_client.py", line 164, in _sync_send
additional_headers=headers,
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\slack_sdk\web\base_client.py", line 292, in _urllib_api_call
status_code=response["status"],
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\slack_sdk\web\slack_response.py", line 201, in validate
raise e.SlackApiError(message=msg, response=self)
slack_sdk.errors.SlackApiError: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'channel_not_found'}
127.0.0.1 - - [06/Dec/2020 03:50:07] "POST /slack/events HTTP/1.1" 500 -
|
slack_sdk.errors.SlackApiError
|
async def onboarding_message(**payload):
"""Create and send an onboarding welcome message to new users. Save the
time stamp of this message so we can update this message in the future.
"""
# Get WebClient so you can communicate back to Slack.
web_client = payload["web_client"]
# Get the id of the Slack user associated with the incoming event
user_id = payload["data"]["user"]["id"]
# Open a DM with the new user.
response = web_client.conversations_open(users=user_id)
channel = response["channel"]["id"]
# Post the onboarding message.
await start_onboarding(web_client, user_id, channel)
|
async def onboarding_message(**payload):
"""Create and send an onboarding welcome message to new users. Save the
time stamp of this message so we can update this message in the future.
"""
# Get WebClient so you can communicate back to Slack.
web_client = payload["web_client"]
# Get the id of the Slack user associated with the incoming event
user_id = payload["data"]["user"]["id"]
# Open a DM with the new user.
response = web_client.im_open(user_id)
channel = response["channel"]["id"]
# Post the onboarding message.
await start_onboarding(web_client, user_id, channel)
|
https://github.com/slackapi/python-slack-sdk/issues/889
|
Traceback (most recent call last):
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\slackeventsapi\server.py", line 120, in event
self.emitter.emit(event_type, event_data)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\pyee\_base.py", line 113, in emit
handled = self._call_handlers(event, args, kwargs)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\pyee\_base.py", line 96, in _call_handlers
self._emit_run(f, args, kwargs)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\pyee\_base.py", line 81, in _emit_run
f(*args, **kwargs)
File "D:/_pyCharm/mySlackWebClient2/app.py", line 57, in onboarding_message
response = slack_web_client.conversations_open(user=user_id)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\slack_sdk\web\client.py", line 1224, in conversations_open
return self.api_call("conversations.open", json=kwargs)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\slack_sdk\web\base_client.py", line 121, in api_call
return self._sync_send(api_url=api_url, req_args=req_args)
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\slack_sdk\web\base_client.py", line 164, in _sync_send
additional_headers=headers,
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\slack_sdk\web\base_client.py", line 292, in _urllib_api_call
status_code=response["status"],
File "D:\_pyCharm\mySlackWebClient2\venv\lib\site-packages\slack_sdk\web\slack_response.py", line 201, in validate
raise e.SlackApiError(message=msg, response=self)
slack_sdk.errors.SlackApiError: The request to the Slack API failed.
The server responded with: {'ok': False, 'error': 'channel_not_found'}
127.0.0.1 - - [06/Dec/2020 03:50:07] "POST /slack/events HTTP/1.1" 500 -
|
slack_sdk.errors.SlackApiError
|
def __init__(
self,
*,
token: str,
run_async: Optional[bool] = False,
auto_reconnect: Optional[bool] = True,
ssl: Optional[SSLContext] = None,
proxy: Optional[str] = None,
timeout: Optional[int] = 30,
base_url: Optional[str] = WebClient.BASE_URL,
connect_method: Optional[str] = None,
ping_interval: Optional[int] = 30,
loop: Optional[asyncio.AbstractEventLoop] = None,
headers: Optional[dict] = {},
):
self.token = token.strip()
self.run_async = run_async
self.auto_reconnect = auto_reconnect
self.ssl = ssl
self.proxy = proxy
self.timeout = timeout
self.base_url = base_url
self.connect_method = connect_method
self.ping_interval = ping_interval
self.headers = headers
self._event_loop = loop or asyncio.get_event_loop()
self._web_client = None
self._websocket = None
self._session = None
self._logger = logging.getLogger(__name__)
self._last_message_id = 0
self._connection_attempts = 0
self._stopped = False
self._web_client = WebClient(
token=self.token,
base_url=self.base_url,
timeout=self.timeout,
ssl=self.ssl,
proxy=self.proxy,
run_async=self.run_async,
loop=self._event_loop,
session=self._session,
headers=self.headers,
)
|
def __init__(
self,
*,
token: str,
run_async: Optional[bool] = False,
auto_reconnect: Optional[bool] = True,
ssl: Optional[SSLContext] = None,
proxy: Optional[str] = None,
timeout: Optional[int] = 30,
base_url: Optional[str] = WebClient.BASE_URL,
connect_method: Optional[str] = None,
ping_interval: Optional[int] = 30,
loop: Optional[asyncio.AbstractEventLoop] = None,
headers: Optional[dict] = {},
):
self.token = token.strip()
self.run_async = run_async
self.auto_reconnect = auto_reconnect
self.ssl = ssl
self.proxy = proxy
self.timeout = timeout
self.base_url = base_url
self.connect_method = connect_method
self.ping_interval = ping_interval
self.headers = headers
self._event_loop = loop or asyncio.get_event_loop()
self._web_client = None
self._websocket = None
self._session = None
self._logger = logging.getLogger(__name__)
self._last_message_id = 0
self._connection_attempts = 0
self._stopped = False
self._web_client = WebClient(
token=self.token,
base_url=self.base_url,
ssl=self.ssl,
proxy=self.proxy,
run_async=self.run_async,
loop=self._event_loop,
session=self._session,
headers=self.headers,
)
|
https://github.com/slackapi/python-slack-sdk/issues/846
|
`Traceback (most recent call last):`
` File "/Volumes/X5/survival_bot/Util/westland_bot/slack_bot.py", line 40, in rtm_client_run_on`
` self.process_bots(web_client, sender, data['text'], channel, is_group_channel)`
` File "/Volumes/X5/survival_bot/Util/westland_bot/slack_bot.py", line 82, in process_bots`
` web_client.files_upload(`
` File "/usr/local/lib/python3.8/site-packages/slack/web/client.py", line 1533, in files_upload`
` return self.api_call("files.upload", files={"file": file}, data=kwargs)`
` File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 150, in api_call`
` return self._sync_send(api_url=api_url, req_args=req_args)`
` File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 241, in _sync_send`
` return self._urllib_api_call(`
` File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 352, in _urllib_api_call`
` response = self._perform_urllib_http_request(url=url, args=request_args)`
` File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 495, in _perform_urllib_http_request`
` raise err`
` File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 475, in _perform_urllib_http_request`
` resp = urlopen( # skipcq: BAN-B310`
` File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 222, in urlopen`
` return opener.open(url, data, timeout)`
` File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 525, in open`
` response = self._open(req, data)`
` File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 542, in _open`
` result = self._call_chain(self.handle_open, protocol, protocol +`
` File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 502, in _call_chain`
` result = func(*args)`
` File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 1393, in https_open`
` return self.do_open(http.client.HTTPSConnection, req,`
` File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 1353, in do_open`
`18:36`
`raise URLError(err)`
`urllib.error.URLError: <urlopen error The write operation timed out>`
|
URLError
|
async def _retrieve_websocket_info(self):
"""Retrieves the WebSocket info from Slack.
Returns:
A tuple of websocket information.
e.g.
(
"wss://...",
{
"self": {"id": "U01234ABC","name": "robotoverlord"},
"team": {
"domain": "exampledomain",
"id": "T123450FP",
"name": "ExampleName"
}
}
)
Raises:
SlackApiError: Unable to retrieve RTM URL from Slack.
"""
if self._web_client is None:
self._web_client = WebClient(
token=self.token,
base_url=self.base_url,
timeout=self.timeout,
ssl=self.ssl,
proxy=self.proxy,
run_async=True,
loop=self._event_loop,
session=self._session,
headers=self.headers,
)
self._logger.debug("Retrieving websocket info.")
use_rtm_start = self.connect_method in ["rtm.start", "rtm_start"]
if self.run_async:
if use_rtm_start:
resp = await self._web_client.rtm_start()
else:
resp = await self._web_client.rtm_connect()
else:
if use_rtm_start:
resp = self._web_client.rtm_start()
else:
resp = self._web_client.rtm_connect()
url = resp.get("url")
if url is None:
msg = "Unable to retrieve RTM URL from Slack."
raise client_err.SlackApiError(message=msg, response=resp)
return url, resp.data
|
async def _retrieve_websocket_info(self):
"""Retrieves the WebSocket info from Slack.
Returns:
A tuple of websocket information.
e.g.
(
"wss://...",
{
"self": {"id": "U01234ABC","name": "robotoverlord"},
"team": {
"domain": "exampledomain",
"id": "T123450FP",
"name": "ExampleName"
}
}
)
Raises:
SlackApiError: Unable to retrieve RTM URL from Slack.
"""
if self._web_client is None:
self._web_client = WebClient(
token=self.token,
base_url=self.base_url,
ssl=self.ssl,
proxy=self.proxy,
run_async=True,
loop=self._event_loop,
session=self._session,
headers=self.headers,
)
self._logger.debug("Retrieving websocket info.")
use_rtm_start = self.connect_method in ["rtm.start", "rtm_start"]
if self.run_async:
if use_rtm_start:
resp = await self._web_client.rtm_start()
else:
resp = await self._web_client.rtm_connect()
else:
if use_rtm_start:
resp = self._web_client.rtm_start()
else:
resp = self._web_client.rtm_connect()
url = resp.get("url")
if url is None:
msg = "Unable to retrieve RTM URL from Slack."
raise client_err.SlackApiError(message=msg, response=resp)
return url, resp.data
|
https://github.com/slackapi/python-slack-sdk/issues/846
|
`Traceback (most recent call last):`
` File "/Volumes/X5/survival_bot/Util/westland_bot/slack_bot.py", line 40, in rtm_client_run_on`
` self.process_bots(web_client, sender, data['text'], channel, is_group_channel)`
` File "/Volumes/X5/survival_bot/Util/westland_bot/slack_bot.py", line 82, in process_bots`
` web_client.files_upload(`
` File "/usr/local/lib/python3.8/site-packages/slack/web/client.py", line 1533, in files_upload`
` return self.api_call("files.upload", files={"file": file}, data=kwargs)`
` File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 150, in api_call`
` return self._sync_send(api_url=api_url, req_args=req_args)`
` File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 241, in _sync_send`
` return self._urllib_api_call(`
` File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 352, in _urllib_api_call`
` response = self._perform_urllib_http_request(url=url, args=request_args)`
` File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 495, in _perform_urllib_http_request`
` raise err`
` File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 475, in _perform_urllib_http_request`
` resp = urlopen( # skipcq: BAN-B310`
` File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 222, in urlopen`
` return opener.open(url, data, timeout)`
` File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 525, in open`
` response = self._open(req, data)`
` File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 542, in _open`
` result = self._call_chain(self.handle_open, protocol, protocol +`
` File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 502, in _call_chain`
` result = func(*args)`
` File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 1393, in https_open`
` return self.do_open(http.client.HTTPSConnection, req,`
` File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 1353, in do_open`
`18:36`
`raise URLError(err)`
`urllib.error.URLError: <urlopen error The write operation timed out>`
|
URLError
|
def _perform_urllib_http_request(
self, *, url: str, args: Dict[str, Dict[str, any]]
) -> Dict[str, any]:
"""Performs an HTTP request and parses the response.
:param url: a complete URL (e.g., https://www.slack.com/api/chat.postMessage)
:param args: args has "headers", "data", "params", and "json"
"headers": Dict[str, str]
"data": Dict[str, any]
"params": Dict[str, str],
"json": Dict[str, any],
:return: dict {status: int, headers: Headers, body: str}
"""
headers = args["headers"]
if args["json"]:
body = json.dumps(args["json"])
headers["Content-Type"] = "application/json;charset=utf-8"
elif args["data"]:
boundary = f"--------------{uuid.uuid4()}"
sep_boundary = b"\r\n--" + boundary.encode("ascii")
end_boundary = sep_boundary + b"--\r\n"
body = io.BytesIO()
data = args["data"]
for key, value in data.items():
readable = getattr(value, "readable", None)
if readable and value.readable():
filename = "Uploaded file"
name_attr = getattr(value, "name", None)
if name_attr:
filename = (
name_attr.decode("utf-8")
if isinstance(name_attr, bytes)
else name_attr
)
if "filename" in data:
filename = data["filename"]
mimetype = (
mimetypes.guess_type(filename)[0] or "application/octet-stream"
)
title = (
f'\r\nContent-Disposition: form-data; name="{key}"; filename="{filename}"\r\n'
+ f"Content-Type: {mimetype}\r\n"
)
value = value.read()
else:
title = f'\r\nContent-Disposition: form-data; name="{key}"\r\n'
value = str(value).encode("utf-8")
body.write(sep_boundary)
body.write(title.encode("utf-8"))
body.write(b"\r\n")
body.write(value)
body.write(end_boundary)
body = body.getvalue()
headers["Content-Type"] = f"multipart/form-data; boundary={boundary}"
headers["Content-Length"] = len(body)
elif args["params"]:
body = urlencode(args["params"])
headers["Content-Type"] = "application/x-www-form-urlencoded"
else:
body = None
if isinstance(body, str):
body = body.encode("utf-8")
# NOTE: Intentionally ignore the `http_verb` here
# Slack APIs accepts any API method requests with POST methods
try:
# urllib not only opens http:// or https:// URLs, but also ftp:// and file://.
# With this it might be possible to open local files on the executing machine
# which might be a security risk if the URL to open can be manipulated by an external user.
# (BAN-B310)
if url.lower().startswith("http"):
req = Request(method="POST", url=url, data=body, headers=headers)
opener: Optional[OpenerDirector] = None
if self.proxy is not None:
if isinstance(self.proxy, str):
opener = urllib.request.build_opener(
ProxyHandler({"http": self.proxy, "https": self.proxy}),
HTTPSHandler(context=self.ssl),
)
else:
raise SlackRequestError(
f"Invalid proxy detected: {self.proxy} must be a str value"
)
# NOTE: BAN-B310 is already checked above
resp: Optional[HTTPResponse] = None
if opener:
resp = opener.open(req, timeout=self.timeout) # skipcq: BAN-B310
else:
resp = urlopen( # skipcq: BAN-B310
req, context=self.ssl, timeout=self.timeout
)
charset = resp.headers.get_content_charset()
body: str = resp.read().decode(charset) # read the response body here
return {"status": resp.code, "headers": resp.headers, "body": body}
raise SlackRequestError(f"Invalid URL detected: {url}")
except HTTPError as e:
resp = {"status": e.code, "headers": e.headers}
if e.code == 429:
# for compatibility with aiohttp
resp["headers"]["Retry-After"] = resp["headers"]["retry-after"]
charset = e.headers.get_content_charset()
body: str = e.read().decode(charset) # read the response body here
resp["body"] = body
return resp
except Exception as err:
self._logger.error(f"Failed to send a request to Slack API server: {err}")
raise err
|
def _perform_urllib_http_request(
self, *, url: str, args: Dict[str, Dict[str, any]]
) -> Dict[str, any]:
"""Performs an HTTP request and parses the response.
:param url: a complete URL (e.g., https://www.slack.com/api/chat.postMessage)
:param args: args has "headers", "data", "params", and "json"
"headers": Dict[str, str]
"data": Dict[str, any]
"params": Dict[str, str],
"json": Dict[str, any],
:return: dict {status: int, headers: Headers, body: str}
"""
headers = args["headers"]
if args["json"]:
body = json.dumps(args["json"])
headers["Content-Type"] = "application/json;charset=utf-8"
elif args["data"]:
boundary = f"--------------{uuid.uuid4()}"
sep_boundary = b"\r\n--" + boundary.encode("ascii")
end_boundary = sep_boundary + b"--\r\n"
body = io.BytesIO()
data = args["data"]
for key, value in data.items():
readable = getattr(value, "readable", None)
if readable and value.readable():
filename = "Uploaded file"
name_attr = getattr(value, "name", None)
if name_attr:
filename = (
name_attr.decode("utf-8")
if isinstance(name_attr, bytes)
else name_attr
)
if "filename" in data:
filename = data["filename"]
mimetype = (
mimetypes.guess_type(filename)[0] or "application/octet-stream"
)
title = (
f'\r\nContent-Disposition: form-data; name="{key}"; filename="{filename}"\r\n'
+ f"Content-Type: {mimetype}\r\n"
)
value = value.read()
else:
title = f'\r\nContent-Disposition: form-data; name="{key}"\r\n'
value = str(value).encode("utf-8")
body.write(sep_boundary)
body.write(title.encode("utf-8"))
body.write(b"\r\n")
body.write(value)
body.write(end_boundary)
body = body.getvalue()
headers["Content-Type"] = f"multipart/form-data; boundary={boundary}"
headers["Content-Length"] = len(body)
elif args["params"]:
body = urlencode(args["params"])
headers["Content-Type"] = "application/x-www-form-urlencoded"
else:
body = None
if isinstance(body, str):
body = body.encode("utf-8")
# NOTE: Intentionally ignore the `http_verb` here
# Slack APIs accepts any API method requests with POST methods
try:
# urllib not only opens http:// or https:// URLs, but also ftp:// and file://.
# With this it might be possible to open local files on the executing machine
# which might be a security risk if the URL to open can be manipulated by an external user.
# (BAN-B310)
if url.lower().startswith("http"):
req = Request(method="POST", url=url, data=body, headers=headers)
if self.proxy is not None:
if isinstance(self.proxy, str):
host = re.sub("^https?://", "", self.proxy)
req.set_proxy(host, "http")
req.set_proxy(host, "https")
else:
raise SlackRequestError(
f"Invalid proxy detected: {self.proxy} must be a str value"
)
# NOTE: BAN-B310 is already checked above
resp: HTTPResponse = urlopen( # skipcq: BAN-B310
req, context=self.ssl, timeout=self.timeout
)
charset = resp.headers.get_content_charset()
body: str = resp.read().decode(charset) # read the response body here
return {"status": resp.code, "headers": resp.headers, "body": body}
raise SlackRequestError(f"Invalid URL detected: {url}")
except HTTPError as e:
resp = {"status": e.code, "headers": e.headers}
if e.code == 429:
# for compatibility with aiohttp
resp["headers"]["Retry-After"] = resp["headers"]["retry-after"]
charset = e.headers.get_content_charset()
body: str = e.read().decode(charset) # read the response body here
resp["body"] = body
return resp
except Exception as err:
self._logger.error(f"Failed to send a request to Slack API server: {err}")
raise err
|
https://github.com/slackapi/python-slack-sdk/issues/820
|
Traceback (most recent call last):
File "/usr/local/lib/python3.8/urllib/request.py", line 1350, in do_open
h.request(req.get_method(), req.selector, req.data, headers,
File "/usr/local/lib/python3.8/http/client.py", line 1255, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/usr/local/lib/python3.8/http/client.py", line 1301, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/usr/local/lib/python3.8/http/client.py", line 1250, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/usr/local/lib/python3.8/http/client.py", line 1010, in _send_output
self.send(msg)
File "/usr/local/lib/python3.8/http/client.py", line 950, in send
self.connect()
File "/usr/local/lib/python3.8/http/client.py", line 1417, in connect
super().connect()
File "/usr/local/lib/python3.8/http/client.py", line 921, in connect
self.sock = self._create_connection(
File "/usr/local/lib/python3.8/socket.py", line 787, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
File "/usr/local/lib/python3.8/socket.py", line 918, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.8/site-packages/slack/web/client.py", line 881, in chat_postMessage
return self.api_call("chat.postMessage", json=kwargs)
File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 150, in api_call
return self._sync_send(api_url=api_url, req_args=req_args)
File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 241, in _sync_send
return self._urllib_api_call(
File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 352, in _urllib_api_call
response = self._perform_urllib_http_request(url=url, args=request_args)
File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 489, in _perform_urllib_http_request
raise err
File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 469, in _perform_urllib_http_request
resp: HTTPResponse = urlopen( # skipcq: BAN-B310
File "/usr/local/lib/python3.8/urllib/request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "/usr/local/lib/python3.8/urllib/request.py", line 531, in open
response = meth(req, response)
File "/usr/local/lib/python3.8/urllib/request.py", line 640, in http_response
response = self.parent.error(
File "/usr/local/lib/python3.8/urllib/request.py", line 563, in error
result = self._call_chain(*args)
File "/usr/local/lib/python3.8/urllib/request.py", line 502, in _call_chain
result = func(*args)
File "/usr/local/lib/python3.8/urllib/request.py", line 755, in http_error_302
return self.parent.open(new, timeout=req.timeout)
File "/usr/local/lib/python3.8/urllib/request.py", line 525, in open
response = self._open(req, data)
File "/usr/local/lib/python3.8/urllib/request.py", line 542, in _open
result = self._call_chain(self.handle_open, protocol, protocol +
File "/usr/local/lib/python3.8/urllib/request.py", line 502, in _call_chain
result = func(*args)
File "/usr/local/lib/python3.8/urllib/request.py", line 1393, in https_open
return self.do_open(http.client.HTTPSConnection, req,
File "/usr/local/lib/python3.8/urllib/request.py", line 1353, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>
|
urllib.error.URLError
|
def _perform_http_request(
self, *, body: Dict[str, any], headers: Dict[str, str]
) -> WebhookResponse:
"""Performs an HTTP request and parses the response.
:param url: a complete URL to send data (e.g., https://hooks.slack.com/XXX)
:param body: request body data
:param headers: complete set of request headers
:return: API response
"""
body = json.dumps(body)
headers["Content-Type"] = "application/json;charset=utf-8"
if self.logger.level <= logging.DEBUG:
self.logger.debug(
f"Sending a request - url: {self.url}, body: {body}, headers: {headers}"
)
try:
url = self.url
opener: Optional[OpenerDirector] = None
# for security (BAN-B310)
if url.lower().startswith("http"):
req = Request(
method="POST", url=url, data=body.encode("utf-8"), headers=headers
)
if self.proxy is not None:
if isinstance(self.proxy, str):
opener = urllib.request.build_opener(
ProxyHandler({"http": self.proxy, "https": self.proxy}),
HTTPSHandler(context=self.ssl),
)
else:
raise SlackRequestError(
f"Invalid proxy detected: {self.proxy} must be a str value"
)
else:
raise SlackRequestError(f"Invalid URL detected: {url}")
# NOTE: BAN-B310 is already checked above
resp: Optional[HTTPResponse] = None
if opener:
resp = opener.open(req, timeout=self.timeout) # skipcq: BAN-B310
else:
resp = urlopen( # skipcq: BAN-B310
req, context=self.ssl, timeout=self.timeout
)
charset: str = resp.headers.get_content_charset() or "utf-8"
response_body: str = resp.read().decode(charset)
resp = WebhookResponse(
url=url,
status_code=resp.status,
body=response_body,
headers=resp.headers,
)
_debug_log_response(self.logger, resp)
return resp
except HTTPError as e:
charset = e.headers.get_content_charset()
body: str = e.read().decode(charset) # read the response body here
resp = WebhookResponse(
url=url,
status_code=e.code,
body=body,
headers=e.headers,
)
if e.code == 429:
# for backward-compatibility with WebClient (v.2.5.0 or older)
resp.headers["Retry-After"] = resp.headers["retry-after"]
_debug_log_response(self.logger, resp)
return resp
except Exception as err:
self.logger.error(f"Failed to send a request to Slack API server: {err}")
raise err
|
def _perform_http_request(
self, *, body: Dict[str, any], headers: Dict[str, str]
) -> WebhookResponse:
"""Performs an HTTP request and parses the response.
:param url: a complete URL to send data (e.g., https://hooks.slack.com/XXX)
:param body: request body data
:param headers: complete set of request headers
:return: API response
"""
body = json.dumps(body)
headers["Content-Type"] = "application/json;charset=utf-8"
if self.logger.level <= logging.DEBUG:
self.logger.debug(
f"Sending a request - url: {self.url}, body: {body}, headers: {headers}"
)
try:
url = self.url
# for security (BAN-B310)
if url.lower().startswith("http"):
req = Request(
method="POST", url=url, data=body.encode("utf-8"), headers=headers
)
if self.proxy is not None:
host = re.sub("^https?://", "", self.proxy)
req.set_proxy(host, "http")
req.set_proxy(host, "https")
else:
raise SlackRequestError(f"Invalid URL detected: {url}")
# NOTE: BAN-B310 is already checked above
resp: HTTPResponse = urlopen( # skipcq: BAN-B310
req,
context=self.ssl,
timeout=self.timeout,
)
charset: str = resp.headers.get_content_charset() or "utf-8"
response_body: str = resp.read().decode(charset)
resp = WebhookResponse(
url=url,
status_code=resp.status,
body=response_body,
headers=resp.headers,
)
_debug_log_response(self.logger, resp)
return resp
except HTTPError as e:
charset = e.headers.get_content_charset()
body: str = e.read().decode(charset) # read the response body here
resp = WebhookResponse(
url=url,
status_code=e.code,
body=body,
headers=e.headers,
)
if e.code == 429:
# for backward-compatibility with WebClient (v.2.5.0 or older)
resp.headers["Retry-After"] = resp.headers["retry-after"]
_debug_log_response(self.logger, resp)
return resp
except Exception as err:
self.logger.error(f"Failed to send a request to Slack API server: {err}")
raise err
|
https://github.com/slackapi/python-slack-sdk/issues/820
|
Traceback (most recent call last):
File "/usr/local/lib/python3.8/urllib/request.py", line 1350, in do_open
h.request(req.get_method(), req.selector, req.data, headers,
File "/usr/local/lib/python3.8/http/client.py", line 1255, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/usr/local/lib/python3.8/http/client.py", line 1301, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/usr/local/lib/python3.8/http/client.py", line 1250, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/usr/local/lib/python3.8/http/client.py", line 1010, in _send_output
self.send(msg)
File "/usr/local/lib/python3.8/http/client.py", line 950, in send
self.connect()
File "/usr/local/lib/python3.8/http/client.py", line 1417, in connect
super().connect()
File "/usr/local/lib/python3.8/http/client.py", line 921, in connect
self.sock = self._create_connection(
File "/usr/local/lib/python3.8/socket.py", line 787, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
File "/usr/local/lib/python3.8/socket.py", line 918, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.8/site-packages/slack/web/client.py", line 881, in chat_postMessage
return self.api_call("chat.postMessage", json=kwargs)
File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 150, in api_call
return self._sync_send(api_url=api_url, req_args=req_args)
File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 241, in _sync_send
return self._urllib_api_call(
File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 352, in _urllib_api_call
response = self._perform_urllib_http_request(url=url, args=request_args)
File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 489, in _perform_urllib_http_request
raise err
File "/usr/local/lib/python3.8/site-packages/slack/web/base_client.py", line 469, in _perform_urllib_http_request
resp: HTTPResponse = urlopen( # skipcq: BAN-B310
File "/usr/local/lib/python3.8/urllib/request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "/usr/local/lib/python3.8/urllib/request.py", line 531, in open
response = meth(req, response)
File "/usr/local/lib/python3.8/urllib/request.py", line 640, in http_response
response = self.parent.error(
File "/usr/local/lib/python3.8/urllib/request.py", line 563, in error
result = self._call_chain(*args)
File "/usr/local/lib/python3.8/urllib/request.py", line 502, in _call_chain
result = func(*args)
File "/usr/local/lib/python3.8/urllib/request.py", line 755, in http_error_302
return self.parent.open(new, timeout=req.timeout)
File "/usr/local/lib/python3.8/urllib/request.py", line 525, in open
response = self._open(req, data)
File "/usr/local/lib/python3.8/urllib/request.py", line 542, in _open
result = self._call_chain(self.handle_open, protocol, protocol +
File "/usr/local/lib/python3.8/urllib/request.py", line 502, in _call_chain
result = func(*args)
File "/usr/local/lib/python3.8/urllib/request.py", line 1393, in https_open
return self.do_open(http.client.HTTPSConnection, req,
File "/usr/local/lib/python3.8/urllib/request.py", line 1353, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>
|
urllib.error.URLError
|
async def files_upload(
self, *, file: Union[str, IOBase] = None, content: str = None, **kwargs
) -> AsyncSlackResponse:
"""Uploads or creates a file.
Args:
file (str): Supply a file path.
when you'd like to upload a specific file. e.g. 'dramacat.gif'
content (str): Supply content when you'd like to create an
editable text file containing the specified text. e.g. 'launch plan'
Raises:
SlackRequestError: If niether or both the `file` and `content` args are specified.
"""
if file is None and content is None:
raise e.SlackRequestError("The file or content argument must be specified.")
if file is not None and content is not None:
raise e.SlackRequestError(
"You cannot specify both the file and the content argument."
)
if file:
if "filename" not in kwargs and isinstance(file, str):
# use the local filename if filename is missing
kwargs["filename"] = file.split(os.path.sep)[-1]
return await self.api_call("files.upload", files={"file": file}, data=kwargs)
data = kwargs.copy()
data.update({"content": content})
return await self.api_call("files.upload", data=data)
|
async def files_upload(
self, *, file: Union[str, IOBase] = None, content: str = None, **kwargs
) -> AsyncSlackResponse:
"""Uploads or creates a file.
Args:
file (str): Supply a file path.
when you'd like to upload a specific file. e.g. 'dramacat.gif'
content (str): Supply content when you'd like to create an
editable text file containing the specified text. e.g. 'launch plan'
Raises:
SlackRequestError: If niether or both the `file` and `content` args are specified.
"""
if file is None and content is None:
raise e.SlackRequestError("The file or content argument must be specified.")
if file is not None and content is not None:
raise e.SlackRequestError(
"You cannot specify both the file and the content argument."
)
if file:
if "filename" not in kwargs:
# use the local filename if filename is missing
kwargs["filename"] = file.split(os.path.sep)[-1]
return await self.api_call("files.upload", files={"file": file}, data=kwargs)
data = kwargs.copy()
data.update({"content": content})
return await self.api_call("files.upload", data=data)
|
https://github.com/slackapi/python-slack-sdk/issues/809
|
Traceback (most recent call last):
File "/afs/ThisCell/data/vlsi/eclipz/ct6/verif/p10d2/pscripts/user_modules/change_stats.py", line 456, in <module>
rc = main()
File "/afs/ThisCell/data/vlsi/eclipz/ct6/verif/p10d2/pscripts/user_modules/change_stats.py", line 356, in main
plotter(df)
File "/afs/ThisCell/data/vlsi/eclipz/ct6/verif/p10d2/pscripts/user_modules/change_stats.py", line 286, in plotter
initial_comment='')
File "/afs/ThisCell/func/vlsi/eclipz/ct6/verif/p10d1/.pscripts/pong/user_modules/site-packages/slack/web/client.py", line 1305, in files_upload
kwargs["filename"] = file.split(os.path.sep)[-1]
AttributeError: '_io.BufferedReader' object has no attribute 'split'
|
AttributeError
|
def files_upload(
self, *, file: Union[str, IOBase] = None, content: str = None, **kwargs
) -> Union[Future, SlackResponse]:
"""Uploads or creates a file.
Args:
file (str): Supply a file path.
when you'd like to upload a specific file. e.g. 'dramacat.gif'
content (str): Supply content when you'd like to create an
editable text file containing the specified text. e.g. 'launch plan'
Raises:
SlackRequestError: If niether or both the `file` and `content` args are specified.
"""
if file is None and content is None:
raise e.SlackRequestError("The file or content argument must be specified.")
if file is not None and content is not None:
raise e.SlackRequestError(
"You cannot specify both the file and the content argument."
)
if file:
if "filename" not in kwargs and isinstance(file, str):
# use the local filename if filename is missing
kwargs["filename"] = file.split(os.path.sep)[-1]
return self.api_call("files.upload", files={"file": file}, data=kwargs)
data = kwargs.copy()
data.update({"content": content})
return self.api_call("files.upload", data=data)
|
def files_upload(
self, *, file: Union[str, IOBase] = None, content: str = None, **kwargs
) -> Union[Future, SlackResponse]:
"""Uploads or creates a file.
Args:
file (str): Supply a file path.
when you'd like to upload a specific file. e.g. 'dramacat.gif'
content (str): Supply content when you'd like to create an
editable text file containing the specified text. e.g. 'launch plan'
Raises:
SlackRequestError: If niether or both the `file` and `content` args are specified.
"""
if file is None and content is None:
raise e.SlackRequestError("The file or content argument must be specified.")
if file is not None and content is not None:
raise e.SlackRequestError(
"You cannot specify both the file and the content argument."
)
if file:
if "filename" not in kwargs:
# use the local filename if filename is missing
kwargs["filename"] = file.split(os.path.sep)[-1]
return self.api_call("files.upload", files={"file": file}, data=kwargs)
data = kwargs.copy()
data.update({"content": content})
return self.api_call("files.upload", data=data)
|
https://github.com/slackapi/python-slack-sdk/issues/809
|
Traceback (most recent call last):
File "/afs/ThisCell/data/vlsi/eclipz/ct6/verif/p10d2/pscripts/user_modules/change_stats.py", line 456, in <module>
rc = main()
File "/afs/ThisCell/data/vlsi/eclipz/ct6/verif/p10d2/pscripts/user_modules/change_stats.py", line 356, in main
plotter(df)
File "/afs/ThisCell/data/vlsi/eclipz/ct6/verif/p10d2/pscripts/user_modules/change_stats.py", line 286, in plotter
initial_comment='')
File "/afs/ThisCell/func/vlsi/eclipz/ct6/verif/p10d1/.pscripts/pong/user_modules/site-packages/slack/web/client.py", line 1305, in files_upload
kwargs["filename"] = file.split(os.path.sep)[-1]
AttributeError: '_io.BufferedReader' object has no attribute 'split'
|
AttributeError
|
async def _read_messages(self):
"""Process messages received on the WebSocket connection."""
text_message_callback_executions: List[Future] = []
while not self._stopped and self._websocket is not None:
for future in text_message_callback_executions:
if future.done():
text_message_callback_executions.remove(future)
try:
# Wait for a message to be received, but timeout after a second so that
# we can check if the socket has been closed, or if self._stopped is
# True
message = await self._websocket.receive(timeout=1)
except asyncio.TimeoutError:
if not self._websocket.closed:
# We didn't receive a message within the timeout interval, but
# aiohttp hasn't closed the socket, so ping responses must still be
# returning
continue
self._logger.warning(
"Websocket was closed (%s).", self._websocket.close_code
)
await self._dispatch_event(event="error", data=self._websocket.exception())
self._websocket = None
await self._dispatch_event(event="close")
num_of_running_callbacks = len(text_message_callback_executions)
if num_of_running_callbacks > 0:
self._logger.info(
"WebSocket connection has been closed "
f"though {num_of_running_callbacks} callback executions were still in progress"
)
return
if message.type == aiohttp.WSMsgType.TEXT:
payload = message.json()
event = payload.pop("type", "Unknown")
async def run_dispatch_event():
try:
await self._dispatch_event(event, data=payload)
except Exception as err:
data = message.data if message else message
self._logger.info(
f"Caught a raised exception ({err}) while dispatching a TEXT message ({data})"
)
# Raised exceptions here happen in users' code and were just unhandled.
# As they're not intended for closing current WebSocket connection,
# this exception should not be propagated to higher level (#_connect_and_read()).
return
# Asynchronously run callbacks to handle simultaneous incoming messages from Slack
f = asyncio.ensure_future(run_dispatch_event())
text_message_callback_executions.append(f)
elif message.type == aiohttp.WSMsgType.ERROR:
self._logger.error("Received an error on the websocket: %r", message)
await self._dispatch_event(event="error", data=message)
elif message.type in (
aiohttp.WSMsgType.CLOSE,
aiohttp.WSMsgType.CLOSING,
aiohttp.WSMsgType.CLOSED,
):
self._logger.warning("Websocket was closed.")
self._websocket = None
await self._dispatch_event(event="close")
else:
self._logger.debug("Received unhandled message type: %r", message)
|
async def _read_messages(self):
"""Process messages received on the WebSocket connection."""
text_message_callback_executions: List[Future] = []
while not self._stopped and self._websocket is not None:
for future in text_message_callback_executions:
if future.done():
text_message_callback_executions.remove(future)
try:
# Wait for a message to be received, but timeout after a second so that
# we can check if the socket has been closed, or if self._stopped is
# True
message = await self._websocket.receive(timeout=1)
except asyncio.TimeoutError:
if not self._websocket.closed:
# We didn't receive a message within the timeout interval, but
# aiohttp hasn't closed the socket, so ping responses must still be
# returning
continue
self._logger.warning(
"Websocket was closed (%s).", self._websocket.close_code
)
await self._dispatch_event(event="error", data=self._websocket.exception())
self._websocket = None
await self._dispatch_event(event="close")
num_of_running_callbacks = len(text_message_callback_executions)
if num_of_running_callbacks > 0:
self._logger.info(
"WebSocket connection has been closed "
f"though {num_of_running_callbacks} callback executions were still in progress"
)
return
if message.type == aiohttp.WSMsgType.TEXT:
payload = message.json()
event = payload.pop("type", "Unknown")
# Asynchronously run callbacks to handle simultaneous incoming messages from Slack
f = asyncio.ensure_future(self._dispatch_event(event, data=payload))
text_message_callback_executions.append(f)
elif message.type == aiohttp.WSMsgType.ERROR:
self._logger.error("Received an error on the websocket: %r", message)
await self._dispatch_event(event="error", data=message)
elif message.type in (
aiohttp.WSMsgType.CLOSE,
aiohttp.WSMsgType.CLOSING,
aiohttp.WSMsgType.CLOSED,
):
self._logger.warning("Websocket was closed.")
self._websocket = None
await self._dispatch_event(event="close")
else:
self._logger.debug("Received unhandled message type: %r", message)
|
https://github.com/slackapi/python-slack-sdk/issues/611
|
2020-02-03 06:20:43,937 slack.rtm.client DEBUG [client.py:427]: Running 1 callbacks for event: 'error'
2020-02-03 06:20:43,937 slack.rtm.client ERROR [client.py:445]: When calling '#_event_error()' in the 'slackminion.bot' module the following error was raised: 'coroutine' object has no attribute '__dict__'
2020-02-03 06:20:43,938 asyncio ERROR [base_events.py:1604]: Task exception was never retrieved
future: <Task finished coro=<RTMClient._connect_and_read() done, defined at /root/.pex/install/slackclient-2.4.0-py2.py3-none-any.whl.18e6eaa75092884787122451d86752135e246402/slackclient-2.4.0-py2.py3-none-any.whl/slack/rtm/client.py:307> exception=AttributeError("'coroutine' object has no attribute '__dict__'") crea
ted at /root/.pex/install/slackclient-2.4.0-py2.py3-none-any.whl.18e6eaa75092884787122451d86752135e246402/slackclient-2.4.0-py2.py3-none-any.whl/slack/rtm/client.py:193>
source_traceback: Object created at (most recent call last):
File "/usr/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "__main__.py", line 32, in <module>
bootstrap_pex(__entry_point__)
File ".bootstrap/pex/pex_bootstrapper.py", line 155, in bootstrap_pex
pex.PEX(entry_point).execute()
File ".bootstrap/pex/pex.py", line 352, in execute
exit_code = self._wrap_coverage(self._wrap_profiling, self._execute)
File ".bootstrap/pex/pex.py", line 284, in _wrap_coverage
return runner(*args)
File ".bootstrap/pex/pex.py", line 315, in _wrap_profiling
return runner(*args)
File ".bootstrap/pex/pex.py", line 397, in _execute
return self.execute_entry(self._pex_info.entry_point)
File ".bootstrap/pex/pex.py", line 495, in execute_entry
return runner(entry_point)
File ".bootstrap/pex/pex.py", line 510, in execute_pkg_resources
return runner()
File "/root/.pex/code/7488d2d5788cc31e1aaa013c3e6ea8e9b6b2ad2a/pinterest/srebot/bot.py", line 61, in main
asyncio.run(srebot(), debug=True)
File "/usr/lib/python3.7/asyncio/runners.py", line 43, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.7/asyncio/base_events.py", line 566, in run_until_complete
self.run_forever()
File "/usr/lib/python3.7/asyncio/base_events.py", line 534, in run_forever
self._run_once()
File "/usr/lib/python3.7/asyncio/base_events.py", line 1763, in _run_once
handle._run()
File "/usr/lib/python3.7/asyncio/events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "/root/.pex/code/7488d2d5788cc31e1aaa013c3e6ea8e9b6b2ad2a/pinterest/srebot/bot.py", line 50, in srebot
await bot.run()
File "/root/.pex/install/slackminion-0.10.28-py3-none-any.whl.55516cd422c7f852e172cf07bc46de807f9fcf27/slackminion-0.10.28-py3-none-any.whl/slackminion/bot.py", line 156, in run
self.rtm_client.start()
File "/root/.pex/install/slackclient-2.4.0-py2.py3-none-any.whl.18e6eaa75092884787122451d86752135e246402/slackclient-2.4.0-py2.py3-none-any.whl/slack/rtm/client.py", line 193, in start
future = asyncio.ensure_future(self._connect_and_read(), loop=self._event_loop)
Traceback (most recent call last):
File "/root/.pex/install/aiohttp-3.6.2-cp37-cp37m-manylinux1_x86_64.whl.ac8c04b4809f61b5e7d7d38dec8668ddf99c226d/aiohttp-3.6.2-cp37-cp37m-manylinux1_x86_64.whl/aiohttp/client_ws.py", line 227, in receive
msg = await self._reader.read()
File "/root/.pex/install/aiohttp-3.6.2-cp37-cp37m-manylinux1_x86_64.whl.ac8c04b4809f61b5e7d7d38dec8668ddf99c226d/aiohttp-3.6.2-cp37-cp37m-manylinux1_x86_64.whl/aiohttp/streams.py", line 631, in read
return await super().read()
File "/root/.pex/install/aiohttp-3.6.2-cp37-cp37m-manylinux1_x86_64.whl.ac8c04b4809f61b5e7d7d38dec8668ddf99c226d/aiohttp-3.6.2-cp37-cp37m-manylinux1_x86_64.whl/aiohttp/streams.py", line 591, in read
await self._waiter
concurrent.futures._base.CancelledError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/root/.pex/install/slackclient-2.4.0-py2.py3-none-any.whl.18e6eaa75092884787122451d86752135e246402/slackclient-2.4.0-py2.py3-none-any.whl/slack/rtm/client.py", line 371, in _read_messages
message = await self._websocket.receive(timeout=1)
File "/root/.pex/install/aiohttp-3.6.2-cp37-cp37m-manylinux1_x86_64.whl.ac8c04b4809f61b5e7d7d38dec8668ddf99c226d/aiohttp-3.6.2-cp37-cp37m-manylinux1_x86_64.whl/aiohttp/client_ws.py", line 227, in receive
msg = await self._reader.read()
File "/root/.pex/install/async_timeout-3.0.1-py3-none-any.whl.71cea41869a7c1638badbd9362a317bfeccf5203/async_timeout-3.0.1-py3-none-any.whl/async_timeout/__init__.py", line 45, in __exit__
self._do_exit(exc_type)
File "/root/.pex/install/async_timeout-3.0.1-py3-none-any.whl.71cea41869a7c1638badbd9362a317bfeccf5203/async_timeout-3.0.1-py3-none-any.whl/async_timeout/__init__.py", line 92, in _do_exit
raise asyncio.TimeoutError
concurrent.futures._base.TimeoutError
|
AttributeError
|
async def _connect_and_read(self):
"""Retreives the WS url and connects to Slack's RTM API.
Makes an authenticated call to Slack's Web API to retrieve
a websocket URL. Then connects to the message server and
reads event messages as they come in.
If 'auto_reconnect' is specified we
retrieve a new url and reconnect any time the connection
is lost unintentionally or an exception is thrown.
Raises:
SlackApiError: Unable to retreive RTM URL from Slack.
websockets.exceptions: Errors thrown by the 'websockets' library.
"""
while not self._stopped:
try:
self._connection_attempts += 1
async with aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=self.timeout),
) as session:
self._session = session
url, data = await self._retreive_websocket_info()
async with session.ws_connect(
url,
heartbeat=self.ping_interval,
ssl=self.ssl,
proxy=self.proxy,
) as websocket:
self._logger.debug("The Websocket connection has been opened.")
self._websocket = websocket
await self._dispatch_event(event="open", data=data)
await self._read_messages()
# The websocket has been disconnected, or self._stopped is True
if not self._stopped and not self.auto_reconnect:
self._logger.warning(
"Not reconnecting the Websocket because auto_reconnect is False"
)
return
# No need to wait exponentially here, since the connection was
# established OK, but timed out, or was closed remotely
except (
client_err.SlackClientNotConnectedError,
client_err.SlackApiError,
# TODO: Catch websocket exceptions thrown by aiohttp.
) as exception:
self._logger.debug(str(exception))
await self._dispatch_event(event="error", data=exception)
if self.auto_reconnect and not self._stopped:
await self._wait_exponentially(exception)
continue
self._logger.exception(
"The Websocket encountered an error. Closing the connection..."
)
self._close_websocket()
raise
|
async def _connect_and_read(self):
"""Retreives the WS url and connects to Slack's RTM API.
Makes an authenticated call to Slack's Web API to retrieve
a websocket URL. Then connects to the message server and
reads event messages as they come in.
If 'auto_reconnect' is specified we
retrieve a new url and reconnect any time the connection
is lost unintentionally or an exception is thrown.
Raises:
SlackApiError: Unable to retreive RTM URL from Slack.
websockets.exceptions: Errors thrown by the 'websockets' library.
"""
while not self._stopped:
try:
self._connection_attempts += 1
async with aiohttp.ClientSession(
loop=self._event_loop,
timeout=aiohttp.ClientTimeout(total=self.timeout),
) as session:
self._session = session
url, data = await self._retreive_websocket_info()
async with session.ws_connect(
url,
heartbeat=self.ping_interval,
ssl=self.ssl,
proxy=self.proxy,
) as websocket:
self._logger.debug("The Websocket connection has been opened.")
self._websocket = websocket
await self._dispatch_event(event="open", data=data)
await self._read_messages()
# The websocket has been disconnected, or self._stopped is True
if not self._stopped and not self.auto_reconnect:
self._logger.warning(
"Not reconnecting the Websocket because auto_reconnect is False"
)
return
# No need to wait exponentially here, since the connection was
# established OK, but timed out, or was closed remotely
except (
client_err.SlackClientNotConnectedError,
client_err.SlackApiError,
# TODO: Catch websocket exceptions thrown by aiohttp.
) as exception:
self._logger.debug(str(exception))
await self._dispatch_event(event="error", data=exception)
if self.auto_reconnect and not self._stopped:
await self._wait_exponentially(exception)
continue
self._logger.exception(
"The Websocket encountered an error. Closing the connection..."
)
self._close_websocket()
raise
|
https://github.com/slackapi/python-slack-sdk/issues/535
|
slackbot
Traceback (most recent call last):
File "foo.py", line 4, in <module>
for page in client.users_list(limit=1):
File "/home/foo/.pyenv/versions/3.7.2/lib/python3.7/site-packages/slack/web/slack_response.py", line 139, in __next__
req_args=self.req_args,
File "/home/foo/.pyenv/versions/3.7.2/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
return future.result()
File "/home/foo/.pyenv/versions/3.7.2/lib/python3.7/site-packages/slack/web/base_client.py", line 258, in _request
auth=req_args.pop("auth"),
KeyError: 'auth'
|
KeyError
|
async def _request(self, *, http_verb, api_url, req_args):
"""Submit the HTTP request with the running session or a new session.
Returns:
A dictionary of the response data.
"""
session = None
if self.session and not self.session.closed:
session = self.session
else:
session = aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=self.timeout),
auth=req_args.pop("auth", None),
)
response = None
async with session.request(http_verb, api_url, **req_args) as res:
data = {}
try:
data = await res.json()
except aiohttp.ContentTypeError:
self._logger.debug(
f"No response data returned from the following API call: {api_url}."
)
response = {"data": data, "headers": res.headers, "status_code": res.status}
await session.close()
return response
|
async def _request(self, *, http_verb, api_url, req_args):
"""Submit the HTTP request with the running session or a new session.
Returns:
A dictionary of the response data.
"""
if self.session and not self.session.closed:
async with self.session.request(http_verb, api_url, **req_args) as res:
return {
"data": await res.json(),
"headers": res.headers,
"status_code": res.status,
}
async with aiohttp.ClientSession(
loop=self._event_loop,
timeout=aiohttp.ClientTimeout(total=self.timeout),
auth=req_args.pop("auth"),
) as session:
async with session.request(http_verb, api_url, **req_args) as res:
return {
"data": await res.json(),
"headers": res.headers,
"status_code": res.status,
}
|
https://github.com/slackapi/python-slack-sdk/issues/535
|
slackbot
Traceback (most recent call last):
File "foo.py", line 4, in <module>
for page in client.users_list(limit=1):
File "/home/foo/.pyenv/versions/3.7.2/lib/python3.7/site-packages/slack/web/slack_response.py", line 139, in __next__
req_args=self.req_args,
File "/home/foo/.pyenv/versions/3.7.2/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
return future.result()
File "/home/foo/.pyenv/versions/3.7.2/lib/python3.7/site-packages/slack/web/base_client.py", line 258, in _request
auth=req_args.pop("auth"),
KeyError: 'auth'
|
KeyError
|
def run_on(*, event: str):
"""A decorator to store and link a callback to an event."""
def decorator(callback):
RTMClient.on(event=event, callback=callback)
return callback
return decorator
|
def run_on(*, event: str):
"""A decorator to store and link a callback to an event."""
def decorator(callback):
RTMClient.on(event=event, callback=callback)
return decorator
|
https://github.com/slackapi/python-slack-sdk/issues/485
|
Traceback (most recent call last):
File "a.py", line 7, in <module>
foo()
TypeError: 'NoneType' object is not callable
|
TypeError
|
def decorator(callback):
RTMClient.on(event=event, callback=callback)
return callback
|
def decorator(callback):
RTMClient.on(event=event, callback=callback)
|
https://github.com/slackapi/python-slack-sdk/issues/485
|
Traceback (most recent call last):
File "a.py", line 7, in <module>
foo()
TypeError: 'NoneType' object is not callable
|
TypeError
|
def __str__(self) -> str:
if self == AdexEventType.BOND:
return "deposit"
if self == AdexEventType.UNBOND:
return "withdraw"
if self == AdexEventType.UNBOND_REQUEST:
return "withdraw request"
if self == AdexEventType.CHANNEL_WITHDRAW:
return "claim"
raise AssertionError(f"Corrupt value {self} for EventType -- Should never happen")
|
def __str__(self) -> str:
if self == AdexEventType.BOND:
return "deposit"
if self == AdexEventType.UNBOND:
return "withdraw"
if self == AdexEventType.UNBOND_REQUEST:
return "withdraw request"
if self == AdexEventType.CHANNEL_WITHDRAW:
return "claim"
raise AttributeError(f"Corrupt value {self} for EventType -- Should never happen")
|
https://github.com/rotki/rotki/issues/2116
|
2021-01-17T09:45:53.929Z: Starting packaged python subprocess: /tmp/lefteris/.mount_rotki-bd0Awo/resources/rotkehlchen_py_dist/rotkehlchen-1.12.1-linux --api-port 4242 --loglevel debug --api-cors app://* --logfile /home/lefteris/.config/rotki/logs/rotkehlchen.log
2021-01-17T09:45:53.935Z: The Python sub-process started on port: 4242 (PID: 19124)
^C2021-01-17T09:54:44.510Z: Exiting the application
2021-01-17T09:54:44.675Z: Traceback (most recent call last):
File "rotkehlchen/chain/substrate/manager.py", line 408, in _get_node_interface
File "site-packages/substrateinterface/base.py", line 450, in __init__
ValueError: Type registry preset 'kusama' not found
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 818, in gevent._greenlet.Greenlet.run
File "rotkehlchen/chain/substrate/manager.py", line 240, in _connect_node
File "rotkehlchen/chain/substrate/manager.py", line 418, in _get_node_interface
AttributeError: Invalid SubstrateInterface instantiation
2021-01-17T09:47:30Z <Greenlet at 0x7fcc0ff06cb0: <bound method SubstrateManager._connect_node of <rotkehlchen.chain.substrate.manager.SubstrateManager object at 0x7fcc167b5f90>>(node=<KusamaNodeName.OWN: 0>, endpoint='http://localhost:9933')> failed with AttributeError
Traceback (most recent call last):
File "rotkehlchen/chain/substrate/manager.py", line 408, in _get_node_interface
File "site-packages/substrateinterface/base.py", line 450, in __init__
ValueError: Type registry preset 'kusama' not found
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 818, in gevent._greenlet.Greenlet.run
File "rotkehlchen/chain/substrate/manager.py", line 240, in _connect_node
File "rotkehlchen/chain/substrate/manager.py", line 418, in _get_node_interface
AttributeError: Invalid SubstrateInterface instantiation
2021-01-17T09:47:30Z <Greenlet at 0x7fcc0fe8d5f0: <bound method SubstrateManager._connect_node of <rotkehlchen.chain.substrate.manager.SubstrateManager object at 0x7fcc167b5f90>>(node=<KusamaNodeName.PARITY: 1>, endpoint='https://kusama-rpc.polkadot.io/')> failed with AttributeError
|
ValueError
|
def __init__(
self,
chain: SubstrateChain,
greenlet_manager: GreenletManager,
msg_aggregator: MessagesAggregator,
connect_at_start: Sequence[NodeName],
connect_on_startup: bool,
own_rpc_endpoint: str,
) -> None:
"""An interface to any Substrate chain supported by Rotki.
It uses Polkascan py-substrate-interface for interacting with the
substrate blockchains and the Subscan API as a chain explorer.
Official substrate chains documentation:
https://substrate.dev/rustdocs/v2.0.0/sc_service/index.html
https://guide.kusama.network/docs/en/kusama-index
https://wiki.polkadot.network/en/
External Address Format (SS58) documentation:
https://github.com/paritytech/substrate/wiki/External-Address-Format-(SS58)
Polkascan py-scale-codec:
https://github.com/polkascan/py-scale-codec/tree/master
Polkascan py-substrate-interface:
https://github.com/polkascan/py-substrate-interface
https://polkascan.github.io/py-substrate-interface/base.html
Subscan API documentation:
https://docs.api.subscan.io
"""
if chain not in SubstrateChain:
raise AssertionError(f"Unexpected SubstrateManager chain: {chain}")
log.debug(f"Initializing {chain} manager")
self.chain = chain
self.greenlet_manager = greenlet_manager
self.msg_aggregator = msg_aggregator
self.connect_at_start = connect_at_start
self.own_rpc_endpoint = own_rpc_endpoint
self.available_node_attributes_map: DictNodeNameNodeAttributes = {}
self.available_nodes_call_order: NodesCallOrder = []
self.chain_properties: SubstrateChainProperties
if connect_on_startup and len(connect_at_start) != 0:
self.attempt_connections()
else:
log.warning(
f"{self.chain} manager won't attempt to connect to nodes",
connect_at_start=connect_at_start,
connect_on_startup=connect_on_startup,
own_rpc_endpoint=own_rpc_endpoint,
)
|
def __init__(
self,
chain: SubstrateChain,
greenlet_manager: GreenletManager,
msg_aggregator: MessagesAggregator,
connect_at_start: Sequence[NodeName],
connect_on_startup: bool,
own_rpc_endpoint: str,
) -> None:
"""An interface to any Substrate chain supported by Rotki.
It uses Polkascan py-substrate-interface for interacting with the
substrate blockchains and the Subscan API as a chain explorer.
Official substrate chains documentation:
https://substrate.dev/rustdocs/v2.0.0/sc_service/index.html
https://guide.kusama.network/docs/en/kusama-index
https://wiki.polkadot.network/en/
External Address Format (SS58) documentation:
https://github.com/paritytech/substrate/wiki/External-Address-Format-(SS58)
Polkascan py-scale-codec:
https://github.com/polkascan/py-scale-codec/tree/master
Polkascan py-substrate-interface:
https://github.com/polkascan/py-substrate-interface
https://polkascan.github.io/py-substrate-interface/base.html
Subscan API documentation:
https://docs.api.subscan.io
"""
if chain not in SubstrateChain:
raise AttributeError(f"Unexpected SubstrateManager chain: {chain}")
log.debug(f"Initializing {chain} manager")
self.chain = chain
self.greenlet_manager = greenlet_manager
self.msg_aggregator = msg_aggregator
self.connect_at_start = connect_at_start
self.own_rpc_endpoint = own_rpc_endpoint
self.available_node_attributes_map: DictNodeNameNodeAttributes = {}
self.available_nodes_call_order: NodesCallOrder = []
self.chain_properties: SubstrateChainProperties
if connect_on_startup and len(connect_at_start) != 0:
self.attempt_connections()
else:
log.warning(
f"{self.chain} manager won't attempt to connect to nodes",
connect_at_start=connect_at_start,
connect_on_startup=connect_on_startup,
own_rpc_endpoint=own_rpc_endpoint,
)
|
https://github.com/rotki/rotki/issues/2116
|
2021-01-17T09:45:53.929Z: Starting packaged python subprocess: /tmp/lefteris/.mount_rotki-bd0Awo/resources/rotkehlchen_py_dist/rotkehlchen-1.12.1-linux --api-port 4242 --loglevel debug --api-cors app://* --logfile /home/lefteris/.config/rotki/logs/rotkehlchen.log
2021-01-17T09:45:53.935Z: The Python sub-process started on port: 4242 (PID: 19124)
^C2021-01-17T09:54:44.510Z: Exiting the application
2021-01-17T09:54:44.675Z: Traceback (most recent call last):
File "rotkehlchen/chain/substrate/manager.py", line 408, in _get_node_interface
File "site-packages/substrateinterface/base.py", line 450, in __init__
ValueError: Type registry preset 'kusama' not found
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 818, in gevent._greenlet.Greenlet.run
File "rotkehlchen/chain/substrate/manager.py", line 240, in _connect_node
File "rotkehlchen/chain/substrate/manager.py", line 418, in _get_node_interface
AttributeError: Invalid SubstrateInterface instantiation
2021-01-17T09:47:30Z <Greenlet at 0x7fcc0ff06cb0: <bound method SubstrateManager._connect_node of <rotkehlchen.chain.substrate.manager.SubstrateManager object at 0x7fcc167b5f90>>(node=<KusamaNodeName.OWN: 0>, endpoint='http://localhost:9933')> failed with AttributeError
Traceback (most recent call last):
File "rotkehlchen/chain/substrate/manager.py", line 408, in _get_node_interface
File "site-packages/substrateinterface/base.py", line 450, in __init__
ValueError: Type registry preset 'kusama' not found
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 818, in gevent._greenlet.Greenlet.run
File "rotkehlchen/chain/substrate/manager.py", line 240, in _connect_node
File "rotkehlchen/chain/substrate/manager.py", line 418, in _get_node_interface
AttributeError: Invalid SubstrateInterface instantiation
2021-01-17T09:47:30Z <Greenlet at 0x7fcc0fe8d5f0: <bound method SubstrateManager._connect_node of <rotkehlchen.chain.substrate.manager.SubstrateManager object at 0x7fcc167b5f90>>(node=<KusamaNodeName.PARITY: 1>, endpoint='https://kusama-rpc.polkadot.io/')> failed with AttributeError
|
ValueError
|
def _get_node_interface(self, endpoint: str) -> SubstrateInterface:
"""Get an instance of SubstrateInterface, a specialized class in
interfacing with a Substrate node that deals with SCALE encoding/decoding,
metadata parsing, type registry management and versioning of types.
May raise (most common):
- RemoteError: from RequestException, problems requesting the url.
- FileNotFound: via `load_type_registry_preset()` if it doesn't exist
a preset file for the given `type_registry_preset` argument.
- ValueError and TypeError: invalid constructor arguments.
"""
si_attributes = self.chain.substrate_interface_attributes()
try:
node_interface = SubstrateInterface(
url=endpoint,
type_registry_preset=si_attributes.type_registry_preset,
)
except requests.exceptions.RequestException as e:
message = (
f"{self.chain} could not connect to node at endpoint: {endpoint}. "
f"Connection error: {str(e)}."
)
log.error(message)
raise RemoteError(message) from e
except (FileNotFoundError, ValueError, TypeError) as e:
message = (
f"{self.chain} could not connect to node at endpoint: {endpoint}. "
f"Unexpected error during SubstrateInterface instantiation: {str(e)}."
)
log.error(message)
raise RemoteError("Invalid SubstrateInterface instantiation") from e
return node_interface
|
def _get_node_interface(self, endpoint: str) -> SubstrateInterface:
"""Get an instance of SubstrateInterface, a specialized class in
interfacing with a Substrate node that deals with SCALE encoding/decoding,
metadata parsing, type registry management and versioning of types.
May raise (most common):
- RemoteError: from RequestException, problems requesting the url.
- FileNotFound: via `load_type_registry_preset()` if it doesn't exist
a preset file for the given `type_registry_preset` argument.
- ValueError and TypeError: invalid constructor arguments.
"""
si_attributes = self.chain.substrate_interface_attributes()
try:
node_interface = SubstrateInterface(
url=endpoint,
type_registry_preset=si_attributes.type_registry_preset,
)
except requests.exceptions.RequestException as e:
message = (
f"{self.chain} could not connect to node at endpoint: {endpoint}. "
f"Connection error: {str(e)}.",
)
log.error(message)
raise RemoteError(message) from e
except (FileNotFoundError, ValueError, TypeError) as e:
raise AttributeError("Invalid SubstrateInterface instantiation") from e
return node_interface
|
https://github.com/rotki/rotki/issues/2116
|
2021-01-17T09:45:53.929Z: Starting packaged python subprocess: /tmp/lefteris/.mount_rotki-bd0Awo/resources/rotkehlchen_py_dist/rotkehlchen-1.12.1-linux --api-port 4242 --loglevel debug --api-cors app://* --logfile /home/lefteris/.config/rotki/logs/rotkehlchen.log
2021-01-17T09:45:53.935Z: The Python sub-process started on port: 4242 (PID: 19124)
^C2021-01-17T09:54:44.510Z: Exiting the application
2021-01-17T09:54:44.675Z: Traceback (most recent call last):
File "rotkehlchen/chain/substrate/manager.py", line 408, in _get_node_interface
File "site-packages/substrateinterface/base.py", line 450, in __init__
ValueError: Type registry preset 'kusama' not found
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 818, in gevent._greenlet.Greenlet.run
File "rotkehlchen/chain/substrate/manager.py", line 240, in _connect_node
File "rotkehlchen/chain/substrate/manager.py", line 418, in _get_node_interface
AttributeError: Invalid SubstrateInterface instantiation
2021-01-17T09:47:30Z <Greenlet at 0x7fcc0ff06cb0: <bound method SubstrateManager._connect_node of <rotkehlchen.chain.substrate.manager.SubstrateManager object at 0x7fcc167b5f90>>(node=<KusamaNodeName.OWN: 0>, endpoint='http://localhost:9933')> failed with AttributeError
Traceback (most recent call last):
File "rotkehlchen/chain/substrate/manager.py", line 408, in _get_node_interface
File "site-packages/substrateinterface/base.py", line 450, in __init__
ValueError: Type registry preset 'kusama' not found
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 818, in gevent._greenlet.Greenlet.run
File "rotkehlchen/chain/substrate/manager.py", line 240, in _connect_node
File "rotkehlchen/chain/substrate/manager.py", line 418, in _get_node_interface
AttributeError: Invalid SubstrateInterface instantiation
2021-01-17T09:47:30Z <Greenlet at 0x7fcc0fe8d5f0: <bound method SubstrateManager._connect_node of <rotkehlchen.chain.substrate.manager.SubstrateManager object at 0x7fcc167b5f90>>(node=<KusamaNodeName.PARITY: 1>, endpoint='https://kusama-rpc.polkadot.io/')> failed with AttributeError
|
ValueError
|
def _request_chain_metadata(self) -> Dict[str, Any]:
"""Subscan API metadata documentation:
https://docs.api.subscan.io/#metadata
"""
response = self._request_explorer_api(endpoint="metadata")
if response.status_code != HTTPStatus.OK:
message = (
f"{self.chain} chain metadata request was not successful. "
f"Response status code: {response.status_code}. "
f"Response text: {response.text}."
)
log.error(message)
raise RemoteError(message)
try:
result = rlk_jsonloads_dict(response.text)
except JSONDecodeError as e:
message = (
f"{self.chain} chain metadata request returned invalid JSON "
f"response: {response.text}."
)
log.error(message)
raise RemoteError(message) from e
log.debug(f"{self.chain} subscan API metadata", result=result)
return result
|
def _request_chain_metadata(self) -> Dict[str, Any]:
"""Subscan API metadata documentation:
https://docs.api.subscan.io/#metadata
"""
response = self._request_explorer_api(endpoint="metadata")
if response.status_code != HTTPStatus.OK:
message = (
f"{self.chain} chain metadata request was not successful. "
f"Response status code: {response.status_code}. "
f"Response text: {response.text}.",
)
log.error(message)
raise RemoteError(message)
try:
result = rlk_jsonloads_dict(response.text)
except JSONDecodeError as e:
message = (
f"{self.chain} chain metadata request returned invalid JSON "
f"response: {response.text}.",
)
log.error(message)
raise RemoteError(message) from e
log.debug(f"{self.chain} subscan API metadata", result=result)
return result
|
https://github.com/rotki/rotki/issues/2116
|
2021-01-17T09:45:53.929Z: Starting packaged python subprocess: /tmp/lefteris/.mount_rotki-bd0Awo/resources/rotkehlchen_py_dist/rotkehlchen-1.12.1-linux --api-port 4242 --loglevel debug --api-cors app://* --logfile /home/lefteris/.config/rotki/logs/rotkehlchen.log
2021-01-17T09:45:53.935Z: The Python sub-process started on port: 4242 (PID: 19124)
^C2021-01-17T09:54:44.510Z: Exiting the application
2021-01-17T09:54:44.675Z: Traceback (most recent call last):
File "rotkehlchen/chain/substrate/manager.py", line 408, in _get_node_interface
File "site-packages/substrateinterface/base.py", line 450, in __init__
ValueError: Type registry preset 'kusama' not found
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 818, in gevent._greenlet.Greenlet.run
File "rotkehlchen/chain/substrate/manager.py", line 240, in _connect_node
File "rotkehlchen/chain/substrate/manager.py", line 418, in _get_node_interface
AttributeError: Invalid SubstrateInterface instantiation
2021-01-17T09:47:30Z <Greenlet at 0x7fcc0ff06cb0: <bound method SubstrateManager._connect_node of <rotkehlchen.chain.substrate.manager.SubstrateManager object at 0x7fcc167b5f90>>(node=<KusamaNodeName.OWN: 0>, endpoint='http://localhost:9933')> failed with AttributeError
Traceback (most recent call last):
File "rotkehlchen/chain/substrate/manager.py", line 408, in _get_node_interface
File "site-packages/substrateinterface/base.py", line 450, in __init__
ValueError: Type registry preset 'kusama' not found
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 818, in gevent._greenlet.Greenlet.run
File "rotkehlchen/chain/substrate/manager.py", line 240, in _connect_node
File "rotkehlchen/chain/substrate/manager.py", line 418, in _get_node_interface
AttributeError: Invalid SubstrateInterface instantiation
2021-01-17T09:47:30Z <Greenlet at 0x7fcc0fe8d5f0: <bound method SubstrateManager._connect_node of <rotkehlchen.chain.substrate.manager.SubstrateManager object at 0x7fcc167b5f90>>(node=<KusamaNodeName.PARITY: 1>, endpoint='https://kusama-rpc.polkadot.io/')> failed with AttributeError
|
ValueError
|
def __init__(
self,
name: str,
api_key: ApiKey,
secret: ApiSecret,
database: "DBHandler",
):
assert isinstance(api_key, T_ApiKey), "api key for {} should be a string".format(
name
)
assert isinstance(secret, T_ApiSecret), (
"secret for {} should be a bytestring".format(name)
)
super().__init__()
self.name = name
self.db = database
self.api_key = api_key
self.secret = secret
self.first_connection_made = False
self.session = requests.session()
self.session.headers.update({"User-Agent": "rotkehlchen"})
log.info(f"Initialized {name} exchange")
|
def __init__(
self,
name: str,
api_key: ApiKey,
secret: ApiSecret,
database: "DBHandler",
):
print("Exchange interface ctor called")
assert isinstance(api_key, T_ApiKey), "api key for {} should be a string".format(
name
)
assert isinstance(secret, T_ApiSecret), (
"secret for {} should be a bytestring".format(name)
)
super().__init__()
self.name = name
self.db = database
self.api_key = api_key
self.secret = secret
self.first_connection_made = False
self.session = requests.session()
self.session.headers.update({"User-Agent": "rotkehlchen"})
log.info(f"Initialized {name} exchange")
|
https://github.com/rotki/rotki/issues/2116
|
2021-01-17T09:45:53.929Z: Starting packaged python subprocess: /tmp/lefteris/.mount_rotki-bd0Awo/resources/rotkehlchen_py_dist/rotkehlchen-1.12.1-linux --api-port 4242 --loglevel debug --api-cors app://* --logfile /home/lefteris/.config/rotki/logs/rotkehlchen.log
2021-01-17T09:45:53.935Z: The Python sub-process started on port: 4242 (PID: 19124)
^C2021-01-17T09:54:44.510Z: Exiting the application
2021-01-17T09:54:44.675Z: Traceback (most recent call last):
File "rotkehlchen/chain/substrate/manager.py", line 408, in _get_node_interface
File "site-packages/substrateinterface/base.py", line 450, in __init__
ValueError: Type registry preset 'kusama' not found
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 818, in gevent._greenlet.Greenlet.run
File "rotkehlchen/chain/substrate/manager.py", line 240, in _connect_node
File "rotkehlchen/chain/substrate/manager.py", line 418, in _get_node_interface
AttributeError: Invalid SubstrateInterface instantiation
2021-01-17T09:47:30Z <Greenlet at 0x7fcc0ff06cb0: <bound method SubstrateManager._connect_node of <rotkehlchen.chain.substrate.manager.SubstrateManager object at 0x7fcc167b5f90>>(node=<KusamaNodeName.OWN: 0>, endpoint='http://localhost:9933')> failed with AttributeError
Traceback (most recent call last):
File "rotkehlchen/chain/substrate/manager.py", line 408, in _get_node_interface
File "site-packages/substrateinterface/base.py", line 450, in __init__
ValueError: Type registry preset 'kusama' not found
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 818, in gevent._greenlet.Greenlet.run
File "rotkehlchen/chain/substrate/manager.py", line 240, in _connect_node
File "rotkehlchen/chain/substrate/manager.py", line 418, in _get_node_interface
AttributeError: Invalid SubstrateInterface instantiation
2021-01-17T09:47:30Z <Greenlet at 0x7fcc0fe8d5f0: <bound method SubstrateManager._connect_node of <rotkehlchen.chain.substrate.manager.SubstrateManager object at 0x7fcc167b5f90>>(node=<KusamaNodeName.PARITY: 1>, endpoint='https://kusama-rpc.polkadot.io/')> failed with AttributeError
|
ValueError
|
def _is_token_non_standard(symbol: str, address: ChecksumEthAddress) -> bool:
"""ignore some assets we do not query directly as token balances"""
if symbol in ("UNI-V2",):
return True
if address in ("0xCb2286d9471cc185281c4f763d34A962ED212962",): # Sushi LP token
return True
return False
|
def _is_token_non_standard(symbol: str, address: ChecksumEthAddress) -> bool:
"""ignore some assets we do not yet support and don't want to spam warnings with"""
if symbol in ("UNI-V2", "swUSD", "crCRV"):
return True
if address in ("0xCb2286d9471cc185281c4f763d34A962ED212962",): # Sushi LP token
return True
return False
|
https://github.com/rotki/rotki/issues/1777
|
2020-11-23T14:53:52.590Z: Traceback (most recent call last):
File "src/gevent/greenlet.py", line 818, in gevent._greenlet.Greenlet.run
File "rotkehlchen/api/rest.py", line 235, in _do_query_async
result = getattr(self, command)(**kwargs)
File "rotkehlchen/api/rest.py", line 1576, in _eth_module_query
result = getattr(module_obj, method)(**kwargs)
File "rotkehlchen/chain/ethereum/uniswap/uniswap.py", line 944, in get_balances
protocol_balance = self.get_balances_chain(addresses)
File "rotkehlchen/chain/ethereum/uniswap/uniswap.py", line 309, in get_balances_chain
lp_addresses = get_latest_lp_addresses(self.data_directory)
File "rotkehlchen/chain/ethereum/uniswap/utils.py", line 152, in get_latest_lp_addresses
with open(local_meta_file, 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/lefteris/_MEI4E2fsg/rotkehlchen/data/uniswapv2_lp_tokens.meta'
2020-11-23T14:49:58Z <Greenlet at 0x7fef149a8a70: <bound method RestAPI._do_query_async of <rotkehlchen.api.rest.RestAPI object at 0x7fef1cd87090>>('_eth_module_query', 9, module='uniswap', method='get_balances', query_specific_balances_before=None, addresses=['0x8F1aa25822F4DE42089970c55E6Ab1111e134012', '0x)> failed with FileNotFoundError
|
FileNotFoundError
|
def pull_data(self) -> Dict:
"""Pulls data from the server and returns the response dict
Returns None if there is no DB saved in the server.
Raises RemoteError if there are problems reaching the server or if
there is an error returned by the server
"""
signature, data = self.sign("get_saved_data")
self.session.headers.update(
{
"API-SIGN": base64.b64encode(signature.digest()), # type: ignore
}
)
try:
response = self.session.get(
self.uri + "get_saved_data",
data=data,
timeout=ROTKEHLCHEN_SERVER_TIMEOUT,
)
except requests.exceptions.ConnectionError:
raise RemoteError("Could not connect to rotki server")
return _process_dict_response(response)
|
def pull_data(self) -> Dict:
"""Pulls data from the server and returns the response dict
Raises RemoteError if there are problems reaching the server or if
there is an error returned by the server
"""
signature, data = self.sign("get_saved_data")
self.session.headers.update(
{
"API-SIGN": base64.b64encode(signature.digest()), # type: ignore
}
)
try:
response = self.session.get(
self.uri + "get_saved_data",
data=data,
timeout=ROTKEHLCHEN_SERVER_TIMEOUT,
)
except requests.exceptions.ConnectionError:
raise RemoteError("Could not connect to rotki server")
return _process_dict_response(response)
|
https://github.com/rotki/rotki/issues/1571
|
[07/10/2020 10:06:45 CEST] ERROR rotkehlchen.api.server: Exception on /api/1/users [PUT]
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkipy37/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/home/lefteris/.virtualenvs/rotkipy37/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/lefteris/.virtualenvs/rotkipy37/lib/python3.7/site-packages/flask_restful/__init__.py", line 458, in wrapper
resp = resource(*args, **kwargs)
File "/home/lefteris/.virtualenvs/rotkipy37/lib/python3.7/site-packages/flask/views.py", line 89, in view
return self.dispatch_request(*args, **kwargs)
File "/home/lefteris/.virtualenvs/rotkipy37/lib/python3.7/site-packages/flask_restful/__init__.py", line 573, in dispatch_request
resp = meth(*args, **kwargs)
File "/home/lefteris/.virtualenvs/rotkipy37/lib/python3.7/site-packages/webargs/core.py", line 366, in wrapper
return func(*args, **kwargs)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/api/v1/resources.py", line 511, in put
initial_settings=initial_settings,
File "/home/lefteris/w/rotkehlchen/rotkehlchen/api/rest.py", line 812, in create_new_user
initial_settings=initial_settings,
File "/home/lefteris/w/rotkehlchen/rotkehlchen/rotkehlchen.py", line 194, in unlock_user
sync_approval=sync_approval,
File "/home/lefteris/w/rotkehlchen/rotkehlchen/premium/sync.py", line 267, in try_premium_at_start
if self._sync_data_from_server_and_replace_local():
File "/home/lefteris/w/rotkehlchen/rotkehlchen/premium/sync.py", line 128, in _sync_data_from_server_and_replace_local
self.data.decompress_and_decrypt_db(self.password, result['data'])
File "/home/lefteris/w/rotkehlchen/rotkehlchen/data_handler.py", line 229, in decompress_and_decrypt_db
decrypted_data = decrypt(password.encode(), encrypted_data)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/crypto.py", line 34, in decrypt
assert isinstance(given_source, str), 'source should be given in string'
AssertionError: source should be given in string
[07/10/2020 10:06:45 CEST] INFO rotkehlchen.api.server.pywsgi: 127.0.0.1 - - "PUT /api/1/users HTTP/1.1" 500 216 0.627664
|
AssertionError
|
def _sync_data_from_server_and_replace_local(self) -> bool:
"""
Performs syncing of data from server and replaces local db
Returns true for success and False for error/failure
May raise:
- PremiumAuthenticationError due to an UnableToDecryptRemoteData
coming from decompress_and_decrypt_db. This happens when the given password
does not match the one on the saved DB.
"""
assert self.premium, "This function has to be called with a not None premium"
try:
result = self.premium.pull_data()
except RemoteError as e:
log.debug("sync from server -- pulling failed.", error=str(e))
return False
if result["data"] is None:
log.debug("sync from server -- no data found.")
return False
try:
self.data.decompress_and_decrypt_db(self.password, result["data"])
except UnableToDecryptRemoteData:
raise PremiumAuthenticationError(
"The given password can not unlock the database that was retrieved from "
"the server. Make sure to use the same password as when the account was created.",
)
return True
|
def _sync_data_from_server_and_replace_local(self) -> bool:
"""
Performs syncing of data from server and replaces local db
Returns true for success and False for error/failure
May raise:
- PremiumAuthenticationError due to an UnableToDecryptRemoteData
coming from decompress_and_decrypt_db. This happens when the given password
does not match the one on the saved DB.
"""
assert self.premium, "This function has to be called with a not None premium"
try:
result = self.premium.pull_data()
except RemoteError as e:
log.debug("sync from server -- pulling failed.", error=str(e))
return False
try:
self.data.decompress_and_decrypt_db(self.password, result["data"])
except UnableToDecryptRemoteData:
raise PremiumAuthenticationError(
"The given password can not unlock the database that was retrieved from "
"the server. Make sure to use the same password as when the account was created.",
)
return True
|
https://github.com/rotki/rotki/issues/1571
|
[07/10/2020 10:06:45 CEST] ERROR rotkehlchen.api.server: Exception on /api/1/users [PUT]
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkipy37/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/home/lefteris/.virtualenvs/rotkipy37/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/lefteris/.virtualenvs/rotkipy37/lib/python3.7/site-packages/flask_restful/__init__.py", line 458, in wrapper
resp = resource(*args, **kwargs)
File "/home/lefteris/.virtualenvs/rotkipy37/lib/python3.7/site-packages/flask/views.py", line 89, in view
return self.dispatch_request(*args, **kwargs)
File "/home/lefteris/.virtualenvs/rotkipy37/lib/python3.7/site-packages/flask_restful/__init__.py", line 573, in dispatch_request
resp = meth(*args, **kwargs)
File "/home/lefteris/.virtualenvs/rotkipy37/lib/python3.7/site-packages/webargs/core.py", line 366, in wrapper
return func(*args, **kwargs)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/api/v1/resources.py", line 511, in put
initial_settings=initial_settings,
File "/home/lefteris/w/rotkehlchen/rotkehlchen/api/rest.py", line 812, in create_new_user
initial_settings=initial_settings,
File "/home/lefteris/w/rotkehlchen/rotkehlchen/rotkehlchen.py", line 194, in unlock_user
sync_approval=sync_approval,
File "/home/lefteris/w/rotkehlchen/rotkehlchen/premium/sync.py", line 267, in try_premium_at_start
if self._sync_data_from_server_and_replace_local():
File "/home/lefteris/w/rotkehlchen/rotkehlchen/premium/sync.py", line 128, in _sync_data_from_server_and_replace_local
self.data.decompress_and_decrypt_db(self.password, result['data'])
File "/home/lefteris/w/rotkehlchen/rotkehlchen/data_handler.py", line 229, in decompress_and_decrypt_db
decrypted_data = decrypt(password.encode(), encrypted_data)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/crypto.py", line 34, in decrypt
assert isinstance(given_source, str), 'source should be given in string'
AssertionError: source should be given in string
[07/10/2020 10:06:45 CEST] INFO rotkehlchen.api.server.pywsgi: 127.0.0.1 - - "PUT /api/1/users HTTP/1.1" 500 216 0.627664
|
AssertionError
|
def query(
self,
querystr: str,
param_types: Optional[Dict[str, Any]],
param_values: Optional[Dict[str, Any]],
) -> Dict[str, Any]:
"""Queries The Graph for a particular query
May raise:
- RemoteError: If there is a problem querying
"""
prefix = "query "
if param_types is not None:
prefix += (
json.dumps(param_types).replace('"', "").replace("{", "(").replace("}", ")")
)
prefix += "{"
log.debug(f"Querying The Graph for {querystr}")
try:
result = self.client.execute(
gql(prefix + querystr), variable_values=param_values
)
except (requests.exceptions.RequestException, Exception) as e:
raise RemoteError(f"Failed to query the graph for {querystr} due to {str(e)}")
log.debug("Got result from The Graph query")
return result
|
def query(
self,
querystr: str,
param_types: Optional[Dict[str, Any]],
param_values: Optional[Dict[str, Any]],
) -> Dict[str, Any]:
"""Queries The Graph for a particular query
May raise:
- RemoteError: If there is a problem querying
"""
prefix = "query "
if param_types is not None:
prefix += (
json.dumps(param_types).replace('"', "").replace("{", "(").replace("}", ")")
)
prefix += "{"
log.debug(f"Querying The Graph for {querystr}")
try:
result = self.client.execute(
gql(prefix + querystr), variable_values=param_values
)
except requests.exceptions.RequestException:
raise RemoteError(f"Failed to query the graph for {querystr}")
log.debug("Got result from The Graph query")
return result
|
https://github.com/rotki/rotki/issues/1482
|
[16/09/2020 17:41:40 Mitteleuropäische Sommerzeit] rotkehlchen.exchanges.binance: Binance API request request_url=https://api.binance.com/api/v3/account?recvWindow=10000&timestamp=1600270900071&signature=[REDACTED]
[16/09/2020 17:41:40 Mitteleuropäische Sommerzeit] rotkehlchen.api.server: Exception on /api/1/exchanges [PUT]
Traceback (most recent call last):
File "site-packages\flask\app.py", line 1949, in full_dispatch_request
File "site-packages\flask\app.py", line 1935, in dispatch_request
File "site-packages\flask_restful\__init__.py", line 458, in wrapper
File "site-packages\flask\views.py", line 89, in view
File "site-packages\flask_restful\__init__.py", line 573, in dispatch_request
File "site-packages\webargs\core.py", line 366, in wrapper
File "rotkehlchen\api\v1\resources.py", line 197, in put
File "rotkehlchen\api\rest.py", line 125, in wrapper
File "rotkehlchen\api\rest.py", line 393, in setup_exchange
File "rotkehlchen\rotkehlchen.py", line 810, in setup_exchange
File "rotkehlchen\exchanges\manager.py", line 94, in setup_exchange
File "rotkehlchen\exchanges\binance.py", line 204, in validate_api_key
File "rotkehlchen\exchanges\binance.py", line 295, in api_query_dict
File "rotkehlchen\exchanges\binance.py", line 273, in api_query
rotkehlchen.errors.RemoteError: Binance API request https://api.binance.com/api/v3/account?recvWindow=10000&timestamp=1600270900071&signature=[SIGNATURE] for account failed with HTTP status code: 400, error code: -1021 and error message: Timestamp for this request was 1000ms ahead of the server's time.
[16/09/2020 17:41:40 Mitteleuropäische Sommerzeit] rotkehlchen.api.server.pywsgi: 127.0.0.1 - - "PUT /api/1/exchanges HTTP/1.1" 500 216 0.373099
[16/09/2020 17:41:43 Mitteleuropäische Sommerzeit] rotkehlchen.api.rest: Request successful response={"result": {"warnings": [], "errors": []}, "message": ""}, status_code=200
|
rotkehlchen.errors.RemoteError
|
def validate_api_key(self) -> Tuple[bool, str]:
try:
# We know account endpoint returns a dict
self.api_query_dict("account")
except RemoteError as e:
error = str(e)
if "API-key format invalid" in error:
return False, "Provided API Key is in invalid Format"
elif "Signature for this request is not valid" in error:
return False, "Provided API Secret is malformed"
elif "Invalid API-key, IP, or permissions for action" in error:
return False, "API Key does not match the given secret"
elif "Timestamp for this request was" in error:
return False, (
"Local system clock is not in sync with binance server. "
"Try syncing your system's clock"
)
else:
raise
return True, ""
|
def validate_api_key(self) -> Tuple[bool, str]:
try:
# We know account endpoint returns a dict
self.api_query_dict("account")
except RemoteError as e:
error = str(e)
if "API-key format invalid" in error:
return False, "Provided API Key is in invalid Format"
elif "Signature for this request is not valid" in error:
return False, "Provided API Secret is malformed"
elif "Invalid API-key, IP, or permissions for action" in error:
return False, "API Key does not match the given secret"
else:
raise
return True, ""
|
https://github.com/rotki/rotki/issues/1482
|
[16/09/2020 17:41:40 Mitteleuropäische Sommerzeit] rotkehlchen.exchanges.binance: Binance API request request_url=https://api.binance.com/api/v3/account?recvWindow=10000&timestamp=1600270900071&signature=[REDACTED]
[16/09/2020 17:41:40 Mitteleuropäische Sommerzeit] rotkehlchen.api.server: Exception on /api/1/exchanges [PUT]
Traceback (most recent call last):
File "site-packages\flask\app.py", line 1949, in full_dispatch_request
File "site-packages\flask\app.py", line 1935, in dispatch_request
File "site-packages\flask_restful\__init__.py", line 458, in wrapper
File "site-packages\flask\views.py", line 89, in view
File "site-packages\flask_restful\__init__.py", line 573, in dispatch_request
File "site-packages\webargs\core.py", line 366, in wrapper
File "rotkehlchen\api\v1\resources.py", line 197, in put
File "rotkehlchen\api\rest.py", line 125, in wrapper
File "rotkehlchen\api\rest.py", line 393, in setup_exchange
File "rotkehlchen\rotkehlchen.py", line 810, in setup_exchange
File "rotkehlchen\exchanges\manager.py", line 94, in setup_exchange
File "rotkehlchen\exchanges\binance.py", line 204, in validate_api_key
File "rotkehlchen\exchanges\binance.py", line 295, in api_query_dict
File "rotkehlchen\exchanges\binance.py", line 273, in api_query
rotkehlchen.errors.RemoteError: Binance API request https://api.binance.com/api/v3/account?recvWindow=10000&timestamp=1600270900071&signature=[SIGNATURE] for account failed with HTTP status code: 400, error code: -1021 and error message: Timestamp for this request was 1000ms ahead of the server's time.
[16/09/2020 17:41:40 Mitteleuropäische Sommerzeit] rotkehlchen.api.server.pywsgi: 127.0.0.1 - - "PUT /api/1/exchanges HTTP/1.1" 500 216 0.373099
[16/09/2020 17:41:43 Mitteleuropäische Sommerzeit] rotkehlchen.api.rest: Request successful response={"result": {"warnings": [], "errors": []}, "message": ""}, status_code=200
|
rotkehlchen.errors.RemoteError
|
def _check_and_get_response(response: Response, method: str) -> Union[str, Dict]:
"""Checks the kraken response and if it's succesfull returns the result.
If there is recoverable error a string is returned explaining the error
May raise:
- RemoteError if there is an unrecoverable/unexpected remote error
"""
if response.status_code in (520, 525, 504):
log.debug(f"Kraken returned status code {response.status_code}")
return "Usual kraken 5xx shenanigans"
elif response.status_code != 200:
raise RemoteError(
"Kraken API request {} for {} failed with HTTP status code: {}".format(
response.url,
method,
response.status_code,
)
)
try:
decoded_json = rlk_jsonloads_dict(response.text)
except json.decoder.JSONDecodeError as e:
raise RemoteError(f"Invalid JSON in Kraken response. {e}")
try:
if decoded_json["error"]:
if isinstance(decoded_json["error"], list):
error = decoded_json["error"][0]
else:
error = decoded_json["error"]
if "Rate limit exceeded" in error:
log.debug(f"Kraken: Got rate limit exceeded error: {error}")
return "Rate limited exceeded"
else:
raise RemoteError(error)
result = decoded_json["result"]
except KeyError as e:
raise RemoteError(f"Unexpected format of Kraken response. Missing key: {e}")
return result
|
def _check_and_get_response(response: Response, method: str) -> Union[str, Dict]:
"""Checks the kraken response and if it's succesfull returns the result.
If there is recoverable error a string is returned explaining the error
May raise:
- RemoteError if there is an unrecoverable/unexpected remote error
"""
if response.status_code in (520, 525, 504):
log.debug(f"Kraken returned status code {response.status_code}")
return "Usual kraken 5xx shenanigans"
elif response.status_code != 200:
raise RemoteError(
"Kraken API request {} for {} failed with HTTP status code: {}".format(
response.url,
method,
response.status_code,
)
)
result = rlk_jsonloads_dict(response.text)
if result["error"]:
if isinstance(result["error"], list):
error = result["error"][0]
else:
error = result["error"]
if "Rate limit exceeded" in error:
log.debug(f"Kraken: Got rate limit exceeded error: {error}")
return "Rate limited exceeded"
else:
raise RemoteError(error)
return result["result"]
|
https://github.com/rotki/rotki/issues/943
|
27/04/2020 17:06:16 W. Europe Daylight Time -- INFO:rotkehlchen.exchanges.exchange:Initialized kraken exchange
27/04/2020 17:06:16 W. Europe Daylight Time -- DEBUG:rotkehlchen.exchanges.kraken:Kraken API query method=Balance, data=None, call_counter=0
27/04/2020 17:06:16 W. Europe Daylight Time -- ERROR:rotkehlchen.api.server:Exception on /api/1/exchanges [PUT]
Traceback (most recent call last):
File "C:\Users\Gebruiker\Envs\rotkehlchen\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Gebruiker\Envs\rotkehlchen\lib\site-packages\flask\app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Gebruiker\Envs\rotkehlchen\lib\site-packages\flask_restful\__init__.py", line 458, in wrapper
resp = resource(*args, **kwargs)
File "C:\Users\Gebruiker\Envs\rotkehlchen\lib\site-packages\flask\views.py", line 89, in view
return self.dispatch_request(*args, **kwargs)
File "C:\Users\Gebruiker\Envs\rotkehlchen\lib\site-packages\flask_restful\__init__.py", line 573, in dispatch_request
resp = meth(*args, **kwargs)
File "C:\Users\Gebruiker\Envs\rotkehlchen\lib\site-packages\webargs\core.py", line 366, in wrapper
return func(*args, **kwargs)
File "c:\users\gebruiker\source\repos\rotki\rotkehlchen\api\v1\resources.py", line 215, in put
return self.rest_api.setup_exchange(name, api_key, api_secret, passphrase)
File "c:\users\gebruiker\source\repos\rotki\rotkehlchen\api\rest.py", line 109, in wrapper
return f(wrappingobj, *args, **kwargs)
File "c:\users\gebruiker\source\repos\rotki\rotkehlchen\api\rest.py", line 377, in setup_exchange
result, message = self.rotkehlchen.setup_exchange(name, api_key, api_secret, passphrase)
File "c:\users\gebruiker\source\repos\rotki\rotkehlchen\rotkehlchen.py", line 635, in setup_exchange
passphrase=passphrase,
File "c:\users\gebruiker\source\repos\rotki\rotkehlchen\exchanges\manager.py", line 78, in setup_exchange
result, message = exchange.validate_api_key()
File "c:\users\gebruiker\source\repos\rotki\rotkehlchen\exchanges\kraken.py", line 318, in validate_api_key
valid, msg = self._validate_single_api_key_action('Balance')
File "c:\users\gebruiker\source\repos\rotki\rotkehlchen\exchanges\kraken.py", line 341, in _validate_single_api_key_action
self.api_query(method_str, req)
File "c:\users\gebruiker\source\repos\rotki\rotkehlchen\exchanges\kraken.py", line 419, in api_query
result = query_method(method, req)
File "c:\users\gebruiker\source\repos\rotki\rotkehlchen\exchanges\kraken.py", line 471, in _query_private
return _check_and_get_response(response, method)
File "c:\users\gebruiker\source\repos\rotki\rotkehlchen\exchanges\kraken.py", line 246, in _check_and_get_response
return result['result']
KeyError: 'result'
... (and later if i try to register it again I get this)
27/04/2020 17:06:33 W. Europe Daylight Time -- INFO:rotkehlchen.api.server.pywsgi:127.0.0.1 - - [2020-04-27 17:06:33] "OPTIONS /api/1/exchanges HTTP/1.1" 200 327 0.001009
27/04/2020 17:06:33 W. Europe Daylight Time -- DEBUG:rotkehlchen.api.rest:Request successful response={"result": null, "message": "Exchange kraken is already registered"}, status_code=409
|
KeyError
|
def _query_blockchain_balances(
self,
blockchain: Optional[SupportedBlockchain],
ignore_cache: bool,
) -> Dict[str, Any]:
msg = ""
status_code = HTTPStatus.OK
result = None
try:
balances = self.rotkehlchen.chain_manager.query_balances(
blockchain=blockchain,
ignore_cache=ignore_cache,
)
except EthSyncError as e:
msg = str(e)
status_code = HTTPStatus.CONFLICT
except RemoteError as e:
msg = str(e)
status_code = HTTPStatus.BAD_GATEWAY
else:
result = balances.serialize()
# If only specific input blockchain was given ignore other results
if blockchain == SupportedBlockchain.ETHEREUM:
result["per_account"].pop("BTC", None)
result["totals"].pop("BTC", None)
elif blockchain == SupportedBlockchain.BITCOIN:
val = result["per_account"].get("BTC", None)
per_account = {"BTC": val} if val else {}
val = result["totals"].get("BTC", None)
totals = {"BTC": val} if val else {}
result = {"per_account": per_account, "totals": totals}
return {"result": result, "message": msg, "status_code": status_code}
|
def _query_blockchain_balances(
self,
blockchain: Optional[SupportedBlockchain],
ignore_cache: bool,
) -> Dict[str, Any]:
msg = ""
status_code = HTTPStatus.OK
result = None
try:
balances = self.rotkehlchen.chain_manager.query_balances(
blockchain=blockchain,
ignore_cache=ignore_cache,
)
except EthSyncError as e:
msg = str(e)
status_code = HTTPStatus.CONFLICT
except RemoteError as e:
msg = str(e)
status_code = HTTPStatus.BAD_GATEWAY
else:
result = balances.serialize()
# If only specific input blockchain was given ignore other results
if blockchain == SupportedBlockchain.ETHEREUM:
result["per_account"].pop("BTC", None)
result["totals"].pop("BTC", None)
elif blockchain == SupportedBlockchain.BITCOIN:
per_account = {"BTC": result["per_account"]["BTC"]}
totals = {"BTC": result["totals"]["BTC"]}
result = {"per_account": per_account, "totals": totals}
return {"result": result, "message": msg, "status_code": status_code}
|
https://github.com/rotki/rotki/issues/848
|
06/04/2020 19:32:00 W. Europe Daylight Time -- ERROR:rotkehlchen.api.server:Exception on /api/1/balances/blockchains/btc [GET]
Traceback (most recent call last):
File "C:\Users\Gebruiker\Envs\rotkehlchen\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Gebruiker\Envs\rotkehlchen\lib\site-packages\flask\app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Gebruiker\Envs\rotkehlchen\lib\site-packages\flask_restful\__init__.py", line 458, in wrapper
resp = resource(*args, **kwargs)
File "C:\Users\Gebruiker\Envs\rotkehlchen\lib\site-packages\flask\views.py", line 89, in view
return self.dispatch_request(*args, **kwargs)
File "C:\Users\Gebruiker\Envs\rotkehlchen\lib\site-packages\flask_restful\__init__.py", line 573, in dispatch_request
resp = meth(*args, **kwargs)
File "C:\Users\Gebruiker\Envs\rotkehlchen\lib\site-packages\webargs\core.py", line 366, in wrapper
return func(*args, **kwargs)
File "C:\Users\Gebruiker\Source\Repos\rotki\rotkehlchen\api\v1\resources.py", line 302, in get
ignore_cache=ignore_cache,
File "C:\Users\Gebruiker\Source\Repos\rotki\rotkehlchen\api\rest.py", line 101, in wrapper
return f(wrappingobj, *args, **kwargs)
File "C:\Users\Gebruiker\Source\Repos\rotki\rotkehlchen\api\rest.py", line 575, in query_blockchain_balances
ignore_cache=ignore_cache,
File "C:\Users\Gebruiker\Source\Repos\rotki\rotkehlchen\api\rest.py", line 553, in _query_blockchain_balances
per_account = {'BTC': result['per_account']['BTC']}
KeyError: 'BTC'
06/04/2020 19:32:00 W. Europe Daylight Time -- INFO:rotkehlchen.api.server.pywsgi:127.0.0.1 - - [2020-04-06 19:32:00] "GET /api/1/balances/blockchains/btc HTTP/1.1" 500 164 0.001981
|
KeyError
|
def request_get(uri, timeout=ALL_REMOTES_TIMEOUT):
# TODO make this a bit more smart. Perhaps conditional on the type of request.
# Not all requests would need repeated attempts
response = retry_calls(
5,
"",
uri,
requests.get,
uri,
)
if response.status_code != 200:
raise RemoteError(
"Get {} returned status code {}".format(uri, response.status_code)
)
try:
result = rlk_jsonloads(response.text)
except json.decoder.JSONDecodeError:
raise ValueError("{} returned malformed json".format(uri))
return result
|
def request_get(uri, timeout=ALL_REMOTES_TIMEOUT):
response = requests.get(uri)
if response.status_code != 200:
raise RemoteError(
"Get {} returned status code {}".format(uri, response.status_code)
)
try:
result = rlk_jsonloads(response.text)
except json.decoder.JSONDecodeError:
raise ValueError("{} returned malformed json".format(uri))
return result
|
https://github.com/rotki/rotki/issues/170
|
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/bin/zerorpc", line 11, in <module>
sys.exit(main())
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/zerorpc/cli.py", line 310, in main
return run_client(args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/zerorpc/cli.py", line 269, in run_client
results = client(args.command, *call_args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/zerorpc/core.py", line 270, in __call__
return self._process_response(request_event, bufchan, timeout)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/zerorpc/core.py", line 238, in _process_response
reply_event, self._handle_remote_error)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/zerorpc/patterns.py", line 45, in process_answer
raise exception
zerorpc.exceptions.RemoteError: Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/urllib3/connection.py", line 141, in _new_conn
(self.host, self.port), self.timeout, **extra_kw)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/urllib3/util/connection.py", line 60, in create_connection
for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/gevent/_socketcommon.py", line 208, in getaddrinfo
return get_hub().resolver.getaddrinfo(host, port, family, type, proto, flags)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/gevent/resolver/thread.py", line 65, in getaddrinfo
return self.pool.apply(_socket.getaddrinfo, args, kwargs)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/gevent/pool.py", line 159, in apply [0/172]
return self.spawn(func, *args, **kwds).get()
File "src/gevent/event.py", line 381, in gevent._event.AsyncResult.get
File "src/gevent/event.py", line 409, in gevent._event.AsyncResult.get
File "src/gevent/event.py", line 399, in gevent._event.AsyncResult.get
File "src/gevent/event.py", line 379, in gevent._event.AsyncResult._raise_exception
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/gevent/_compat.py", line 47, in reraise
raise value.with_traceback(tb)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/gevent/threadpool.py", line 281, in _worker
value = func(*args, **kwargs)
socket.gaierror: [Errno -2] Name or service not known
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/urllib3/connectionpool.py", line 601, in urlopen
chunked=chunked)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/urllib3/connectionpool.py", line 346, in _make_request
self._validate_conn(conn)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/urllib3/connectionpool.py", line 850, in _validate_conn
conn.connect()
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/urllib3/connection.py", line 284, in connect
conn = self._new_conn()
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/urllib3/connection.py", line 150, in _new_conn
self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x7f4a9b736470>: Failed to establish a new connection: [Errno -2] Name or service not known
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/requests/adapters.py", line 440, in send
timeout=timeout
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/urllib3/connectionpool.py", line 639, in urlopen
_stacktrace=sys.exc_info()[2])
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/urllib3/util/retry.py", line 388, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.etherscan.io', port=443): Max retries exceeded with url: /api?module=account&action=tokenbalance&contractaddress=0xXX&address=0xXX (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f4a9b736470>: Failed to establish a new connection: [Errno -2] Name or service not known'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/zerorpc/core.py", line 153, in _async_task
functor.pattern.process_call(self._context, bufchan, event, functor)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/zerorpc/patterns.py", line 30, in process_call
result = functor(*req_event.args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/zerorpc/decorators.py", line 44, in __call__
return self._functor(*args, **kargs)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/server.py", line 225, in query_balances
result = self.rotkehlchen.query_balances(save_data)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/rotkehlchen.py", line 429, in query_balances
result, error_or_empty = self.blockchain.query_balances()
File "/home/lefteris/w/rotkehlchen/rotkehlchen/utils.py", line 92, in wrapper
result = f(wrappingobj, *args)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 83, in query_balances
self.query_ethereum_balances()
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 354, in query_ethereum_balances
self.query_ethereum_tokens(self.owned_eth_tokens, eth_balances)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 319, in query_ethereum_tokens
self.accounts.eth,
File "/home/lefteris/w/rotkehlchen/rotkehlchen/ethchain.py", line 191, in get_multitoken_balance
account,
File "/home/lefteris/w/rotkehlchen/rotkehlchen/utils.py", line 201, in request_get
response = requests.get(uri)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/requests/api.py", line 72, in get
return request('get', url, params=params, **kwargs)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/requests/api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/requests/sessions.py", line 508, in request
resp = self.send(prep, **send_kwargs)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/requests/sessions.py", line 618, in send
r = adapter.send(request, **kwargs)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.7/site-packages/requests/adapters.py", line 508, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.etherscan.io', port=443): Max retries exceeded with url: /api?module=account&action=tokenbalance&contractaddress=0xXX&address=0xXX (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f4a9b736470>: Failed to establish a new connection: [Errno -2] Name or service not known'))
|
zerorpc.exceptions.RemoteError
|
def query_balances(self) -> Tuple[Dict[str, Dict], str]:
try:
self.query_ethereum_balances()
except BadFunctionCallOutput as e:
logger.error(
"Assuming unsynced chain. Got web3 BadFunctionCallOutput "
"exception: {}".format(str(e))
)
msg = (
"Tried to use the ethereum chain of a local client to query "
"an eth account but the chain is not synced."
)
return {}, msg
self.query_btc_balances()
return {"per_account": self.balances, "totals": self.totals}, ""
|
def query_balances(self) -> Dict[str, Dict]:
self.query_ethereum_balances()
self.query_btc_balances()
return {"per_account": self.balances, "totals": self.totals}
|
https://github.com/rotki/rotki/issues/101
|
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/bin/zerorpc", line 11, in <module>
load_entry_point('zerorpc==0.6.1', 'console_scripts', 'zerorpc')()
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/cli.py", line 310, in main
return run_client(args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/cli.py", line 269, in run_client
results = client(args.command, *call_args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 270, in __call__
return self._process_response(request_event, bufchan, timeout)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 238, in _process_response
reply_event, self._handle_remote_error)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/patterns.py", line 45, in process_answer
raise exception
zerorpc.exceptions.RemoteError: Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 1214, in call_contract_function
output_data = decode_abi(output_types, return_data)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/abi.py", line 96, in decode_abi
return decoder(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 118, in __call__
return self.decode(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_utils/functional.py", line 22, in inner
return callback(fn(*args, **kwargs))
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 164, in decode
yield decoder(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 118, in __call__
return self.decode(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 186, in decode
raw_data = self.read_data_from_stream(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 279, in read_data_from_stream
len(data),
eth_abi.exceptions.InsufficientDataBytes: Tried to read 32 bytes. Only got 0 bytes
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 153, in _async_task
functor.pattern.process_call(self._context, bufchan, event, functor)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/patterns.py", line 30, in process_call
result = functor(*req_event.args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/decorators.py", line 44, in __call__
return self._functor(*args, **kargs)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/server.py", line 229, in query_balances
result = self.rotkehlchen.query_balances(save_data)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/rotkehlchen.py", line 417, in query_balances
result = self.blockchain.query_balances()['totals']
File "/home/lefteris/w/rotkehlchen/rotkehlchen/utils.py", line 83, in wrapper
result = f(wrappingobj, *args)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 79, in query_balances
self.query_ethereum_balances()
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 321, in query_ethereum_balances
self.query_ethereum_tokens(self.owned_eth_tokens, eth_balances)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 286, in query_ethereum_tokens
self.accounts[S_ETH],
File "/home/lefteris/w/rotkehlchen/rotkehlchen/ethchain.py", line 142, in get_multitoken_balance
token_amount = FVal(token_contract.functions.balanceOf(account).call())
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 979, in call
**self.kwargs)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 1236, in call_contract_function
raise BadFunctionCallOutput(msg) from e
web3.exceptions.BadFunctionCallOutput: Could not transact with/call contract function, is contract deployed correctly and chain synced?
|
zerorpc.exceptions.RemoteError
|
def modify_blockchain_account(
self,
blockchain: str,
account: typing.BlockchainAddress,
append_or_remove: str,
add_or_sub: Callable[[FVal, FVal], FVal],
) -> BlockchainBalancesUpdate:
if blockchain == S_BTC:
if append_or_remove == "remove" and account not in self.accounts[S_BTC]:
raise InputError("Tried to remove a non existing BTC account")
self.modify_btc_account(account, append_or_remove, add_or_sub)
elif blockchain == S_ETH:
if append_or_remove == "remove" and account not in self.accounts[S_ETH]:
raise InputError("Tried to remove a non existing ETH account")
try:
self.modify_eth_account(account, append_or_remove, add_or_sub)
except BadFunctionCallOutput as e:
logger.error(
"Assuming unsynced chain. Got web3 BadFunctionCallOutput "
"exception: {}".format(str(e))
)
raise EthSyncError(
"Tried to use the ethereum chain of a local client to edit "
"an eth account but the chain is not synced."
)
else:
raise InputError(
"Unsupported blockchain {} provided at remove_blockchain_account".format(
blockchain
)
)
return {"per_account": self.balances, "totals": self.totals}
|
def modify_blockchain_account(
self,
blockchain: str,
account: typing.BlockchainAddress,
append_or_remove: str,
add_or_sub: Callable[[FVal, FVal], FVal],
) -> BlockchainBalancesUpdate:
if blockchain == S_BTC:
if append_or_remove == "remove" and account not in self.accounts[S_BTC]:
raise InputError("Tried to remove a non existing BTC account")
self.modify_btc_account(account, append_or_remove, add_or_sub)
elif blockchain == S_ETH:
if append_or_remove == "remove" and account not in self.accounts[S_ETH]:
raise InputError("Tried to remove a non existing ETH account")
self.modify_eth_account(account, append_or_remove, add_or_sub)
else:
raise InputError(
"Unsupported blockchain {} provided at remove_blockchain_account".format(
blockchain
)
)
return {"per_account": self.balances, "totals": self.totals}
|
https://github.com/rotki/rotki/issues/101
|
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/bin/zerorpc", line 11, in <module>
load_entry_point('zerorpc==0.6.1', 'console_scripts', 'zerorpc')()
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/cli.py", line 310, in main
return run_client(args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/cli.py", line 269, in run_client
results = client(args.command, *call_args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 270, in __call__
return self._process_response(request_event, bufchan, timeout)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 238, in _process_response
reply_event, self._handle_remote_error)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/patterns.py", line 45, in process_answer
raise exception
zerorpc.exceptions.RemoteError: Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 1214, in call_contract_function
output_data = decode_abi(output_types, return_data)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/abi.py", line 96, in decode_abi
return decoder(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 118, in __call__
return self.decode(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_utils/functional.py", line 22, in inner
return callback(fn(*args, **kwargs))
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 164, in decode
yield decoder(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 118, in __call__
return self.decode(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 186, in decode
raw_data = self.read_data_from_stream(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 279, in read_data_from_stream
len(data),
eth_abi.exceptions.InsufficientDataBytes: Tried to read 32 bytes. Only got 0 bytes
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 153, in _async_task
functor.pattern.process_call(self._context, bufchan, event, functor)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/patterns.py", line 30, in process_call
result = functor(*req_event.args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/decorators.py", line 44, in __call__
return self._functor(*args, **kargs)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/server.py", line 229, in query_balances
result = self.rotkehlchen.query_balances(save_data)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/rotkehlchen.py", line 417, in query_balances
result = self.blockchain.query_balances()['totals']
File "/home/lefteris/w/rotkehlchen/rotkehlchen/utils.py", line 83, in wrapper
result = f(wrappingobj, *args)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 79, in query_balances
self.query_ethereum_balances()
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 321, in query_ethereum_balances
self.query_ethereum_tokens(self.owned_eth_tokens, eth_balances)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 286, in query_ethereum_tokens
self.accounts[S_ETH],
File "/home/lefteris/w/rotkehlchen/rotkehlchen/ethchain.py", line 142, in get_multitoken_balance
token_amount = FVal(token_contract.functions.balanceOf(account).call())
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 979, in call
**self.kwargs)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 1236, in call_contract_function
raise BadFunctionCallOutput(msg) from e
web3.exceptions.BadFunctionCallOutput: Could not transact with/call contract function, is contract deployed correctly and chain synced?
|
zerorpc.exceptions.RemoteError
|
def add_blockchain_account(self, blockchain, account):
try:
new_data = self.blockchain.add_blockchain_account(blockchain, account)
except (InputError, EthSyncError) as e:
return simple_result(False, str(e))
self.data.add_blockchain_account(blockchain, account)
return accounts_result(new_data["per_account"], new_data["totals"])
|
def add_blockchain_account(self, blockchain, account):
try:
new_data = self.blockchain.add_blockchain_account(blockchain, account)
except InputError as e:
return simple_result(False, str(e))
self.data.add_blockchain_account(blockchain, account)
return accounts_result(new_data["per_account"], new_data["totals"])
|
https://github.com/rotki/rotki/issues/101
|
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/bin/zerorpc", line 11, in <module>
load_entry_point('zerorpc==0.6.1', 'console_scripts', 'zerorpc')()
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/cli.py", line 310, in main
return run_client(args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/cli.py", line 269, in run_client
results = client(args.command, *call_args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 270, in __call__
return self._process_response(request_event, bufchan, timeout)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 238, in _process_response
reply_event, self._handle_remote_error)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/patterns.py", line 45, in process_answer
raise exception
zerorpc.exceptions.RemoteError: Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 1214, in call_contract_function
output_data = decode_abi(output_types, return_data)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/abi.py", line 96, in decode_abi
return decoder(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 118, in __call__
return self.decode(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_utils/functional.py", line 22, in inner
return callback(fn(*args, **kwargs))
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 164, in decode
yield decoder(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 118, in __call__
return self.decode(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 186, in decode
raw_data = self.read_data_from_stream(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 279, in read_data_from_stream
len(data),
eth_abi.exceptions.InsufficientDataBytes: Tried to read 32 bytes. Only got 0 bytes
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 153, in _async_task
functor.pattern.process_call(self._context, bufchan, event, functor)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/patterns.py", line 30, in process_call
result = functor(*req_event.args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/decorators.py", line 44, in __call__
return self._functor(*args, **kargs)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/server.py", line 229, in query_balances
result = self.rotkehlchen.query_balances(save_data)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/rotkehlchen.py", line 417, in query_balances
result = self.blockchain.query_balances()['totals']
File "/home/lefteris/w/rotkehlchen/rotkehlchen/utils.py", line 83, in wrapper
result = f(wrappingobj, *args)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 79, in query_balances
self.query_ethereum_balances()
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 321, in query_ethereum_balances
self.query_ethereum_tokens(self.owned_eth_tokens, eth_balances)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 286, in query_ethereum_tokens
self.accounts[S_ETH],
File "/home/lefteris/w/rotkehlchen/rotkehlchen/ethchain.py", line 142, in get_multitoken_balance
token_amount = FVal(token_contract.functions.balanceOf(account).call())
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 979, in call
**self.kwargs)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 1236, in call_contract_function
raise BadFunctionCallOutput(msg) from e
web3.exceptions.BadFunctionCallOutput: Could not transact with/call contract function, is contract deployed correctly and chain synced?
|
zerorpc.exceptions.RemoteError
|
def remove_blockchain_account(self, blockchain, account):
try:
new_data = self.blockchain.remove_blockchain_account(blockchain, account)
except (InputError, EthSyncError) as e:
return simple_result(False, str(e))
self.data.remove_blockchain_account(blockchain, account)
return accounts_result(new_data["per_account"], new_data["totals"])
|
def remove_blockchain_account(self, blockchain, account):
try:
new_data = self.blockchain.remove_blockchain_account(blockchain, account)
except InputError as e:
return simple_result(False, str(e))
self.data.remove_blockchain_account(blockchain, account)
return accounts_result(new_data["per_account"], new_data["totals"])
|
https://github.com/rotki/rotki/issues/101
|
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/bin/zerorpc", line 11, in <module>
load_entry_point('zerorpc==0.6.1', 'console_scripts', 'zerorpc')()
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/cli.py", line 310, in main
return run_client(args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/cli.py", line 269, in run_client
results = client(args.command, *call_args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 270, in __call__
return self._process_response(request_event, bufchan, timeout)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 238, in _process_response
reply_event, self._handle_remote_error)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/patterns.py", line 45, in process_answer
raise exception
zerorpc.exceptions.RemoteError: Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 1214, in call_contract_function
output_data = decode_abi(output_types, return_data)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/abi.py", line 96, in decode_abi
return decoder(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 118, in __call__
return self.decode(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_utils/functional.py", line 22, in inner
return callback(fn(*args, **kwargs))
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 164, in decode
yield decoder(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 118, in __call__
return self.decode(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 186, in decode
raw_data = self.read_data_from_stream(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 279, in read_data_from_stream
len(data),
eth_abi.exceptions.InsufficientDataBytes: Tried to read 32 bytes. Only got 0 bytes
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 153, in _async_task
functor.pattern.process_call(self._context, bufchan, event, functor)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/patterns.py", line 30, in process_call
result = functor(*req_event.args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/decorators.py", line 44, in __call__
return self._functor(*args, **kargs)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/server.py", line 229, in query_balances
result = self.rotkehlchen.query_balances(save_data)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/rotkehlchen.py", line 417, in query_balances
result = self.blockchain.query_balances()['totals']
File "/home/lefteris/w/rotkehlchen/rotkehlchen/utils.py", line 83, in wrapper
result = f(wrappingobj, *args)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 79, in query_balances
self.query_ethereum_balances()
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 321, in query_ethereum_balances
self.query_ethereum_tokens(self.owned_eth_tokens, eth_balances)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 286, in query_ethereum_tokens
self.accounts[S_ETH],
File "/home/lefteris/w/rotkehlchen/rotkehlchen/ethchain.py", line 142, in get_multitoken_balance
token_amount = FVal(token_contract.functions.balanceOf(account).call())
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 979, in call
**self.kwargs)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 1236, in call_contract_function
raise BadFunctionCallOutput(msg) from e
web3.exceptions.BadFunctionCallOutput: Could not transact with/call contract function, is contract deployed correctly and chain synced?
|
zerorpc.exceptions.RemoteError
|
def add_owned_eth_tokens(self, tokens):
try:
new_data = self.blockchain.track_new_tokens(tokens)
except (InputError, EthSyncError) as e:
return simple_result(False, str(e))
self.data.write_owned_eth_tokens(self.blockchain.owned_eth_tokens)
return accounts_result(new_data["per_account"], new_data["totals"])
|
def add_owned_eth_tokens(self, tokens):
try:
new_data = self.blockchain.track_new_tokens(tokens)
except InputError as e:
return simple_result(False, str(e))
self.data.write_owned_eth_tokens(self.blockchain.owned_eth_tokens)
return accounts_result(new_data["per_account"], new_data["totals"])
|
https://github.com/rotki/rotki/issues/101
|
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/bin/zerorpc", line 11, in <module>
load_entry_point('zerorpc==0.6.1', 'console_scripts', 'zerorpc')()
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/cli.py", line 310, in main
return run_client(args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/cli.py", line 269, in run_client
results = client(args.command, *call_args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 270, in __call__
return self._process_response(request_event, bufchan, timeout)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 238, in _process_response
reply_event, self._handle_remote_error)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/patterns.py", line 45, in process_answer
raise exception
zerorpc.exceptions.RemoteError: Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 1214, in call_contract_function
output_data = decode_abi(output_types, return_data)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/abi.py", line 96, in decode_abi
return decoder(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 118, in __call__
return self.decode(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_utils/functional.py", line 22, in inner
return callback(fn(*args, **kwargs))
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 164, in decode
yield decoder(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 118, in __call__
return self.decode(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 186, in decode
raw_data = self.read_data_from_stream(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 279, in read_data_from_stream
len(data),
eth_abi.exceptions.InsufficientDataBytes: Tried to read 32 bytes. Only got 0 bytes
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 153, in _async_task
functor.pattern.process_call(self._context, bufchan, event, functor)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/patterns.py", line 30, in process_call
result = functor(*req_event.args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/decorators.py", line 44, in __call__
return self._functor(*args, **kargs)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/server.py", line 229, in query_balances
result = self.rotkehlchen.query_balances(save_data)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/rotkehlchen.py", line 417, in query_balances
result = self.blockchain.query_balances()['totals']
File "/home/lefteris/w/rotkehlchen/rotkehlchen/utils.py", line 83, in wrapper
result = f(wrappingobj, *args)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 79, in query_balances
self.query_ethereum_balances()
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 321, in query_ethereum_balances
self.query_ethereum_tokens(self.owned_eth_tokens, eth_balances)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 286, in query_ethereum_tokens
self.accounts[S_ETH],
File "/home/lefteris/w/rotkehlchen/rotkehlchen/ethchain.py", line 142, in get_multitoken_balance
token_amount = FVal(token_contract.functions.balanceOf(account).call())
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 979, in call
**self.kwargs)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 1236, in call_contract_function
raise BadFunctionCallOutput(msg) from e
web3.exceptions.BadFunctionCallOutput: Could not transact with/call contract function, is contract deployed correctly and chain synced?
|
zerorpc.exceptions.RemoteError
|
def query_balances(self, requested_save_data=False):
balances = {}
problem_free = True
for exchange in self.connected_exchanges:
exchange_balances, msg = getattr(self, exchange).query_balances()
# If we got an error, disregard that exchange but make sure we don't save data
if not exchange_balances:
problem_free = False
else:
balances[exchange] = exchange_balances
result, error_or_empty = self.blockchain.query_balances()
if error_or_empty == "":
balances["blockchain"] = result["totals"]
else:
problem_free = False
result = self.query_fiat_balances()
if result != {}:
balances["banks"] = result
combined = combine_stat_dicts([v for k, v in balances.items()])
total_usd_per_location = [
(k, dict_get_sumof(v, "usd_value")) for k, v in balances.items()
]
# calculate net usd value
net_usd = FVal(0)
for k, v in combined.items():
net_usd += FVal(v["usd_value"])
stats = {"location": {}, "net_usd": net_usd}
for entry in total_usd_per_location:
name = entry[0]
total = entry[1]
stats["location"][name] = {
"usd_value": total,
"percentage_of_net_value": (total / net_usd).to_percentage(),
}
for k, v in combined.items():
combined[k]["percentage_of_net_value"] = (
v["usd_value"] / net_usd
).to_percentage()
result_dict = merge_dicts(combined, stats)
allowed_to_save = requested_save_data or self.data.should_save_balances()
if problem_free and allowed_to_save:
self.data.save_balances_data(result_dict)
# After adding it to the saved file we can overlay additional data that
# is not required to be saved in the history file
try:
details = self.data.accountant.details
for asset, (tax_free_amount, average_buy_value) in details.items():
if asset not in result_dict:
continue
result_dict[asset]["tax_free_amount"] = tax_free_amount
result_dict[asset]["average_buy_value"] = average_buy_value
current_price = (
result_dict[asset]["usd_value"] / result_dict[asset]["amount"]
)
if average_buy_value != FVal(0):
result_dict[asset]["percent_change"] = (
(current_price - average_buy_value) / average_buy_value
) * 100
else:
result_dict[asset]["percent_change"] = "INF"
except AttributeError:
pass
return result_dict
|
def query_balances(self, requested_save_data=False):
balances = {}
problem_free = True
for exchange in self.connected_exchanges:
exchange_balances, msg = getattr(self, exchange).query_balances()
# If we got an error, disregard that exchange but make sure we don't save data
if not exchange_balances:
problem_free = False
else:
balances[exchange] = exchange_balances
result = self.blockchain.query_balances()["totals"]
if result != {}:
balances["blockchain"] = result
result = self.query_fiat_balances()
if result != {}:
balances["banks"] = result
combined = combine_stat_dicts([v for k, v in balances.items()])
total_usd_per_location = [
(k, dict_get_sumof(v, "usd_value")) for k, v in balances.items()
]
# calculate net usd value
net_usd = FVal(0)
for k, v in combined.items():
net_usd += FVal(v["usd_value"])
stats = {"location": {}, "net_usd": net_usd}
for entry in total_usd_per_location:
name = entry[0]
total = entry[1]
stats["location"][name] = {
"usd_value": total,
"percentage_of_net_value": (total / net_usd).to_percentage(),
}
for k, v in combined.items():
combined[k]["percentage_of_net_value"] = (
v["usd_value"] / net_usd
).to_percentage()
result_dict = merge_dicts(combined, stats)
allowed_to_save = requested_save_data or self.data.should_save_balances()
if problem_free and allowed_to_save:
self.data.save_balances_data(result_dict)
# After adding it to the saved file we can overlay additional data that
# is not required to be saved in the history file
try:
details = self.data.accountant.details
for asset, (tax_free_amount, average_buy_value) in details.items():
if asset not in result_dict:
continue
result_dict[asset]["tax_free_amount"] = tax_free_amount
result_dict[asset]["average_buy_value"] = average_buy_value
current_price = (
result_dict[asset]["usd_value"] / result_dict[asset]["amount"]
)
if average_buy_value != FVal(0):
result_dict[asset]["percent_change"] = (
(current_price - average_buy_value) / average_buy_value
) * 100
else:
result_dict[asset]["percent_change"] = "INF"
except AttributeError:
pass
return result_dict
|
https://github.com/rotki/rotki/issues/101
|
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/bin/zerorpc", line 11, in <module>
load_entry_point('zerorpc==0.6.1', 'console_scripts', 'zerorpc')()
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/cli.py", line 310, in main
return run_client(args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/cli.py", line 269, in run_client
results = client(args.command, *call_args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 270, in __call__
return self._process_response(request_event, bufchan, timeout)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 238, in _process_response
reply_event, self._handle_remote_error)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/patterns.py", line 45, in process_answer
raise exception
zerorpc.exceptions.RemoteError: Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 1214, in call_contract_function
output_data = decode_abi(output_types, return_data)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/abi.py", line 96, in decode_abi
return decoder(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 118, in __call__
return self.decode(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_utils/functional.py", line 22, in inner
return callback(fn(*args, **kwargs))
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 164, in decode
yield decoder(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 118, in __call__
return self.decode(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 186, in decode
raw_data = self.read_data_from_stream(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 279, in read_data_from_stream
len(data),
eth_abi.exceptions.InsufficientDataBytes: Tried to read 32 bytes. Only got 0 bytes
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 153, in _async_task
functor.pattern.process_call(self._context, bufchan, event, functor)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/patterns.py", line 30, in process_call
result = functor(*req_event.args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/decorators.py", line 44, in __call__
return self._functor(*args, **kargs)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/server.py", line 229, in query_balances
result = self.rotkehlchen.query_balances(save_data)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/rotkehlchen.py", line 417, in query_balances
result = self.blockchain.query_balances()['totals']
File "/home/lefteris/w/rotkehlchen/rotkehlchen/utils.py", line 83, in wrapper
result = f(wrappingobj, *args)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 79, in query_balances
self.query_ethereum_balances()
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 321, in query_ethereum_balances
self.query_ethereum_tokens(self.owned_eth_tokens, eth_balances)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 286, in query_ethereum_tokens
self.accounts[S_ETH],
File "/home/lefteris/w/rotkehlchen/rotkehlchen/ethchain.py", line 142, in get_multitoken_balance
token_amount = FVal(token_contract.functions.balanceOf(account).call())
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 979, in call
**self.kwargs)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 1236, in call_contract_function
raise BadFunctionCallOutput(msg) from e
web3.exceptions.BadFunctionCallOutput: Could not transact with/call contract function, is contract deployed correctly and chain synced?
|
zerorpc.exceptions.RemoteError
|
def query_blockchain_balances(self):
result, empty_or_error = self.rotkehlchen.blockchain.query_balances()
return process_result({"result": result, "message": empty_or_error})
|
def query_blockchain_balances(self):
balances = self.rotkehlchen.blockchain.query_balances()
return process_result(balances)
|
https://github.com/rotki/rotki/issues/101
|
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/bin/zerorpc", line 11, in <module>
load_entry_point('zerorpc==0.6.1', 'console_scripts', 'zerorpc')()
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/cli.py", line 310, in main
return run_client(args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/cli.py", line 269, in run_client
results = client(args.command, *call_args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 270, in __call__
return self._process_response(request_event, bufchan, timeout)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 238, in _process_response
reply_event, self._handle_remote_error)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/patterns.py", line 45, in process_answer
raise exception
zerorpc.exceptions.RemoteError: Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 1214, in call_contract_function
output_data = decode_abi(output_types, return_data)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/abi.py", line 96, in decode_abi
return decoder(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 118, in __call__
return self.decode(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_utils/functional.py", line 22, in inner
return callback(fn(*args, **kwargs))
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 164, in decode
yield decoder(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 118, in __call__
return self.decode(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 186, in decode
raw_data = self.read_data_from_stream(stream)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/eth_abi/decoding.py", line 279, in read_data_from_stream
len(data),
eth_abi.exceptions.InsufficientDataBytes: Tried to read 32 bytes. Only got 0 bytes
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/core.py", line 153, in _async_task
functor.pattern.process_call(self._context, bufchan, event, functor)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/patterns.py", line 30, in process_call
result = functor(*req_event.args)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/zerorpc/decorators.py", line 44, in __call__
return self._functor(*args, **kargs)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/server.py", line 229, in query_balances
result = self.rotkehlchen.query_balances(save_data)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/rotkehlchen.py", line 417, in query_balances
result = self.blockchain.query_balances()['totals']
File "/home/lefteris/w/rotkehlchen/rotkehlchen/utils.py", line 83, in wrapper
result = f(wrappingobj, *args)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 79, in query_balances
self.query_ethereum_balances()
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 321, in query_ethereum_balances
self.query_ethereum_tokens(self.owned_eth_tokens, eth_balances)
File "/home/lefteris/w/rotkehlchen/rotkehlchen/blockchain.py", line 286, in query_ethereum_tokens
self.accounts[S_ETH],
File "/home/lefteris/w/rotkehlchen/rotkehlchen/ethchain.py", line 142, in get_multitoken_balance
token_amount = FVal(token_contract.functions.balanceOf(account).call())
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 979, in call
**self.kwargs)
File "/home/lefteris/.virtualenvs/rotkehlchen/lib/python3.6/site-packages/web3/contract.py", line 1236, in call_contract_function
raise BadFunctionCallOutput(msg) from e
web3.exceptions.BadFunctionCallOutput: Could not transact with/call contract function, is contract deployed correctly and chain synced?
|
zerorpc.exceptions.RemoteError
|
def meshgrid(self):
"""Return a meshgrid of numpy arrays for this mesh.
This simply returns a ``numpy.meshgrid`` of the coordinates for this
mesh in ``ij`` indexing. These are a copy of the points of this mesh.
"""
return np.meshgrid(self.x, self.y, self.z, indexing="ij")
|
def meshgrid(self):
"""Return the a meshgrid of numpy arrays for this mesh.
This simply returns a ``numpy.meshgrid`` of the coordinates for this
mesh in ``ij`` indexing.
"""
return np.meshgrid(self.x, self.y, self.z, indexing="ij")
|
https://github.com/pyvista/pyvista/issues/713
|
Traceback (most recent call last):
...
...
File "/Users/Daniel/opt/anaconda3/lib/python3.7/site-packages/pyvista/core/grid.py", line 435, in _from_specs
self.SetSpacing(xs, ys, zs)
TypeError: SetSpacing argument 1: only size-1 arrays can be converted to Python scalars
|
TypeError
|
def points(self, points):
"""Points must be set along each axial direction.
Please set the point coordinates with the ``x``, ``y``, and ``z``
setters.
This setter overrides the base class's setter to ensure a user does not
attempt to set them.
"""
raise AttributeError(
"The points cannot be set. The points of "
"`RectilinearGrid` are defined in each axial direction. Please "
"use the `x`, `y`, and `z` setters individually."
)
|
def points(self, points):
"""Set points without copying."""
if not isinstance(points, np.ndarray):
raise TypeError("Points must be a numpy array")
# get the unique coordinates along each axial direction
x = np.unique(points[:, 0])
y = np.unique(points[:, 1])
z = np.unique(points[:, 2])
# Set the vtk coordinates
self._from_arrays(x, y, z)
# self._point_ref = points
self.Modified()
|
https://github.com/pyvista/pyvista/issues/713
|
Traceback (most recent call last):
...
...
File "/Users/Daniel/opt/anaconda3/lib/python3.7/site-packages/pyvista/core/grid.py", line 435, in _from_specs
self.SetSpacing(xs, ys, zs)
TypeError: SetSpacing argument 1: only size-1 arrays can be converted to Python scalars
|
TypeError
|
def points(self, points):
"""Points cannot be set.
This setter overrides the base class's setter to ensure a user does not
attempt to set them. See https://github.com/pyvista/pyvista/issues/713.
"""
raise AttributeError(
"The points cannot be set. The points of "
"`UniformGrid`/`vtkImageData` are implicitly defined by the "
"`origin`, `spacing`, and `dimensions` of the grid."
)
|
def points(self, points):
"""Set points without copying."""
if not isinstance(points, np.ndarray):
raise TypeError("Points must be a numpy array")
# get the unique coordinates along each axial direction
x = np.unique(points[:, 0])
y = np.unique(points[:, 1])
z = np.unique(points[:, 2])
nx, ny, nz = len(x), len(y), len(z)
# diff returns an empty array if the input is constant
dx, dy, dz = [np.diff(d) if len(np.diff(d)) > 0 else d for d in (x, y, z)]
# TODO: this needs to be tested (unique might return a tuple)
dx, dy, dz = np.unique(dx), np.unique(dy), np.unique(dz)
ox, oy, oz = np.min(x), np.min(y), np.min(z)
# Build the vtk object
self._from_specs((nx, ny, nz), (dx, dy, dz), (ox, oy, oz))
# self._point_ref = points
self.Modified()
|
https://github.com/pyvista/pyvista/issues/713
|
Traceback (most recent call last):
...
...
File "/Users/Daniel/opt/anaconda3/lib/python3.7/site-packages/pyvista/core/grid.py", line 435, in _from_specs
self.SetSpacing(xs, ys, zs)
TypeError: SetSpacing argument 1: only size-1 arrays can be converted to Python scalars
|
TypeError
|
def points(self, points):
"""Set points without copying."""
if not isinstance(points, np.ndarray):
raise TypeError("Points must be a numpy array")
# get the unique coordinates along each axial direction
x = np.unique(points[:, 0])
y = np.unique(points[:, 1])
z = np.unique(points[:, 2])
nx, ny, nz = len(x), len(y), len(z)
# diff returns an empty array if the input is constant
dx, dy, dz = [np.diff(d) if len(np.diff(d)) > 0 else d for d in (x, y, z)]
# TODO: this needs to be tested (unique might return a tuple)
dx, dy, dz = np.unique(dx), np.unique(dy), np.unique(dz)
ox, oy, oz = np.min(x), np.min(y), np.min(z)
# Build the vtk object
self._from_specs((nx, ny, nz), (dx, dy, dz), (ox, oy, oz))
# self._point_ref = points
self.Modified()
|
def points(self, points):
"""Set points without copying."""
if not isinstance(points, np.ndarray):
raise TypeError("Points must be a numpy array")
# get the unique coordinates along each axial direction
x = np.unique(points[:, 0])
y = np.unique(points[:, 1])
z = np.unique(points[:, 2])
nx, ny, nz = len(x), len(y), len(z)
# TODO: this needs to be tested (unique might return a tuple)
dx, dy, dz = np.unique(np.diff(x)), np.unique(np.diff(y)), np.unique(np.diff(z))
ox, oy, oz = np.min(x), np.min(y), np.min(z)
# Build the vtk object
self._from_specs((nx, ny, nz), (dx, dy, dz), (ox, oy, oz))
# self._point_ref = points
self.Modified()
|
https://github.com/pyvista/pyvista/issues/642
|
Traceback (most recent call last):
File "C:\Users\camramez\Documents\Meshing\gen_terrain.py", line 28, in <module>
grid.points=np.array([x_surf,y_surf,z_surf]).transpose()
File "C:\ProgramData\Anaconda3\envs\mesh\lib\site-packages\pyvista\core\grid.py", line 470, in points
self._from_specs((nx,ny,nz), (dx,dy,dz), (ox,oy,oz))
File "C:\ProgramData\Anaconda3\envs\mesh\lib\site-packages\pyvista\core\grid.py", line 435, in _from_specs
self.SetSpacing(xs, ys, zs)
TypeError: SetSpacing argument %Id: %V
|
TypeError
|
def point_arrays(self):
"""Returns the all point arrays"""
pdata = self.GetPointData()
narr = pdata.GetNumberOfArrays()
# Update data if necessary
if hasattr(self, "_point_arrays"):
keys = list(self._point_arrays.keys())
if narr == len(keys):
if keys:
if self._point_arrays[keys[0]].shape[0] == self.n_points:
return self._point_arrays
else:
return self._point_arrays
# dictionary with callbacks
self._point_arrays = PointScalarsDict(self)
for i in range(narr):
name = pdata.GetArrayName(i)
if name is None or len(name) < 1:
name = "Point Array {}".format(i)
pdata.GetArray(i).SetName(name)
self._point_arrays[name] = self._point_scalar(name)
self._point_arrays.enable_callback()
return self._point_arrays
|
def point_arrays(self):
"""Returns the all point arrays"""
pdata = self.GetPointData()
narr = pdata.GetNumberOfArrays()
# Update data if necessary
if hasattr(self, "_point_arrays"):
keys = list(self._point_arrays.keys())
if narr == len(keys):
if keys:
if self._point_arrays[keys[0]].shape[0] == self.n_points:
return self._point_arrays
else:
return self._point_arrays
# dictionary with callbacks
self._point_arrays = PointScalarsDict(self)
for i in range(narr):
name = pdata.GetArrayName(i)
self._point_arrays[name] = self._point_scalar(name)
self._point_arrays.enable_callback()
return self._point_arrays
|
https://github.com/pyvista/pyvista/issues/306
|
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
<ipython-input-15-403e4a0f4e87> in <module>
9
10 # Try to access the point arrays
---> 11 continents.point_arrays
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in point_arrays(self)
697 for i in range(narr):
698 name = pdata.GetArrayName(i)
--> 699 self._point_arrays[name] = self._point_scalar(name)
700
701 self._point_arrays.enable_callback()
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in _point_scalar(self, name)
342 if name is None:
343 # use active scalar array
--> 344 field, name = self.active_scalar_info
345 if field != POINT_DATA_FIELD:
346 raise RuntimeError('Must specify an array to fetch.')
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in active_scalar_info(self)
53
54 # rare error where scalar name isn't a valid scalar
---> 55 if name not in self.point_arrays:
56 if name not in self.cell_arrays:
57 if name in self.field_arrays:
... last 3 frames repeated, from the frame below ...
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in point_arrays(self)
697 for i in range(narr):
698 name = pdata.GetArrayName(i)
--> 699 self._point_arrays[name] = self._point_scalar(name)
700
701 self._point_arrays.enable_callback()
RecursionError: maximum recursion depth exceeded
|
RecursionError
|
def field_arrays(self):
"""Returns all field arrays"""
fdata = self.GetFieldData()
narr = fdata.GetNumberOfArrays()
# just return if unmodified
if hasattr(self, "_field_arrays"):
keys = list(self._field_arrays.keys())
if narr == len(keys):
return self._field_arrays
# dictionary with callbacks
self._field_arrays = FieldScalarsDict(self)
for i in range(narr):
name = fdata.GetArrayName(i)
if name is None or len(name) < 1:
name = "Field Array {}".format(i)
fdata.GetArray(i).SetName(name)
self._field_arrays[name] = self._field_scalar(name)
self._field_arrays.enable_callback()
return self._field_arrays
|
def field_arrays(self):
"""Returns all field arrays"""
fdata = self.GetFieldData()
narr = fdata.GetNumberOfArrays()
# just return if unmodified
if hasattr(self, "_field_arrays"):
keys = list(self._field_arrays.keys())
if narr == len(keys):
return self._field_arrays
# dictionary with callbacks
self._field_arrays = FieldScalarsDict(self)
for i in range(narr):
name = fdata.GetArrayName(i)
self._field_arrays[name] = self._field_scalar(name)
self._field_arrays.enable_callback()
return self._field_arrays
|
https://github.com/pyvista/pyvista/issues/306
|
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
<ipython-input-15-403e4a0f4e87> in <module>
9
10 # Try to access the point arrays
---> 11 continents.point_arrays
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in point_arrays(self)
697 for i in range(narr):
698 name = pdata.GetArrayName(i)
--> 699 self._point_arrays[name] = self._point_scalar(name)
700
701 self._point_arrays.enable_callback()
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in _point_scalar(self, name)
342 if name is None:
343 # use active scalar array
--> 344 field, name = self.active_scalar_info
345 if field != POINT_DATA_FIELD:
346 raise RuntimeError('Must specify an array to fetch.')
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in active_scalar_info(self)
53
54 # rare error where scalar name isn't a valid scalar
---> 55 if name not in self.point_arrays:
56 if name not in self.cell_arrays:
57 if name in self.field_arrays:
... last 3 frames repeated, from the frame below ...
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in point_arrays(self)
697 for i in range(narr):
698 name = pdata.GetArrayName(i)
--> 699 self._point_arrays[name] = self._point_scalar(name)
700
701 self._point_arrays.enable_callback()
RecursionError: maximum recursion depth exceeded
|
RecursionError
|
def cell_arrays(self):
"""Returns the all cell arrays"""
cdata = self.GetCellData()
narr = cdata.GetNumberOfArrays()
# Update data if necessary
if hasattr(self, "_cell_arrays"):
keys = list(self._cell_arrays.keys())
if narr == len(keys):
if keys:
if self._cell_arrays[keys[0]].shape[0] == self.n_cells:
return self._cell_arrays
else:
return self._cell_arrays
# dictionary with callbacks
self._cell_arrays = CellScalarsDict(self)
for i in range(narr):
name = cdata.GetArrayName(i)
if name is None or len(name) < 1:
name = "Cell Array {}".format(i)
cdata.GetArray(i).SetName(name)
self._cell_arrays[name] = self._cell_scalar(name)
self._cell_arrays.enable_callback()
return self._cell_arrays
|
def cell_arrays(self):
"""Returns the all cell arrays"""
cdata = self.GetCellData()
narr = cdata.GetNumberOfArrays()
# Update data if necessary
if hasattr(self, "_cell_arrays"):
keys = list(self._cell_arrays.keys())
if narr == len(keys):
if keys:
if self._cell_arrays[keys[0]].shape[0] == self.n_cells:
return self._cell_arrays
else:
return self._cell_arrays
# dictionary with callbacks
self._cell_arrays = CellScalarsDict(self)
for i in range(narr):
name = cdata.GetArrayName(i)
self._cell_arrays[name] = self._cell_scalar(name)
self._cell_arrays.enable_callback()
return self._cell_arrays
|
https://github.com/pyvista/pyvista/issues/306
|
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
<ipython-input-15-403e4a0f4e87> in <module>
9
10 # Try to access the point arrays
---> 11 continents.point_arrays
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in point_arrays(self)
697 for i in range(narr):
698 name = pdata.GetArrayName(i)
--> 699 self._point_arrays[name] = self._point_scalar(name)
700
701 self._point_arrays.enable_callback()
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in _point_scalar(self, name)
342 if name is None:
343 # use active scalar array
--> 344 field, name = self.active_scalar_info
345 if field != POINT_DATA_FIELD:
346 raise RuntimeError('Must specify an array to fetch.')
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in active_scalar_info(self)
53
54 # rare error where scalar name isn't a valid scalar
---> 55 if name not in self.point_arrays:
56 if name not in self.cell_arrays:
57 if name in self.field_arrays:
... last 3 frames repeated, from the frame below ...
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in point_arrays(self)
697 for i in range(narr):
698 name = pdata.GetArrayName(i)
--> 699 self._point_arrays[name] = self._point_scalar(name)
700
701 self._point_arrays.enable_callback()
RecursionError: maximum recursion depth exceeded
|
RecursionError
|
def _repr_html_(self):
"""A pretty representation for Jupyter notebooks that includes header
details and information about all scalar arrays"""
fmt = ""
if self.n_arrays > 0:
fmt += "<table>"
fmt += "<tr><th>Header</th><th>Data Arrays</th></tr>"
fmt += "<tr><td>"
# Get the header info
fmt += self.head(display=False, html=True)
# Fill out scalar arrays
if self.n_arrays > 0:
fmt += "</td><td>"
fmt += "\n"
fmt += "<table>\n"
titles = ["Name", "Field", "Type", "N Comp", "Min", "Max"]
fmt += "<tr>" + "".join(["<th>{}</th>".format(t) for t in titles]) + "</tr>\n"
row = "<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>\n"
row = "<tr>" + "".join(["<td>{}</td>" for i in range(len(titles))]) + "</tr>\n"
def format_array(name, arr, field):
"""internal helper to foramt array information for printing"""
dl, dh = self.get_data_range(arr)
dl = pyvista.FLOAT_FORMAT.format(dl)
dh = pyvista.FLOAT_FORMAT.format(dh)
if name == self.active_scalar_info[1]:
name = "<b>{}</b>".format(name)
if arr.ndim > 1:
ncomp = arr.shape[1]
else:
ncomp = 1
return row.format(name, field, arr.dtype, ncomp, dl, dh)
for key, arr in self.point_arrays.items():
fmt += format_array(key, arr, "Points")
for key, arr in self.cell_arrays.items():
fmt += format_array(key, arr, "Cells")
for key, arr in self.field_arrays.items():
fmt += format_array(key, arr, "Fields")
fmt += "</table>\n"
fmt += "\n"
fmt += "</td></tr> </table>"
return fmt
|
def _repr_html_(self):
"""A pretty representation for Jupyter notebooks that includes header
details and information about all scalar arrays"""
fmt = ""
if self.n_arrays > 0:
fmt += "<table>"
fmt += "<tr><th>Header</th><th>Data Arrays</th></tr>"
fmt += "<tr><td>"
# Get the header info
fmt += self.head(display=False, html=True)
# Fill out scalar arrays
if self.n_arrays > 0:
fmt += "</td><td>"
fmt += "\n"
fmt += "<table>\n"
titles = ["Name", "Field", "Type", "N Comp", "Min", "Max"]
fmt += "<tr>" + "".join(["<th>{}</th>".format(t) for t in titles]) + "</tr>\n"
row = "<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>\n"
row = "<tr>" + "".join(["<td>{}</td>" for i in range(len(titles))]) + "</tr>\n"
def format_array(key, field):
"""internal helper to foramt array information for printing"""
arr = get_scalar(self, key, preference=field)
dl, dh = self.get_data_range(key)
dl = pyvista.FLOAT_FORMAT.format(dl)
dh = pyvista.FLOAT_FORMAT.format(dh)
if key == self.active_scalar_info[1]:
key = "<b>{}</b>".format(key)
if arr.ndim > 1:
ncomp = arr.shape[1]
else:
ncomp = 1
return row.format(key, field, arr.dtype, ncomp, dl, dh)
for i in range(self.GetPointData().GetNumberOfArrays()):
key = self.GetPointData().GetArrayName(i)
fmt += format_array(key, field="Points")
for i in range(self.GetCellData().GetNumberOfArrays()):
key = self.GetCellData().GetArrayName(i)
fmt += format_array(key, field="Cells")
for i in range(self.GetFieldData().GetNumberOfArrays()):
key = self.GetFieldData().GetArrayName(i)
fmt += format_array(key, field="Fields")
fmt += "</table>\n"
fmt += "\n"
fmt += "</td></tr> </table>"
return fmt
|
https://github.com/pyvista/pyvista/issues/306
|
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
<ipython-input-15-403e4a0f4e87> in <module>
9
10 # Try to access the point arrays
---> 11 continents.point_arrays
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in point_arrays(self)
697 for i in range(narr):
698 name = pdata.GetArrayName(i)
--> 699 self._point_arrays[name] = self._point_scalar(name)
700
701 self._point_arrays.enable_callback()
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in _point_scalar(self, name)
342 if name is None:
343 # use active scalar array
--> 344 field, name = self.active_scalar_info
345 if field != POINT_DATA_FIELD:
346 raise RuntimeError('Must specify an array to fetch.')
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in active_scalar_info(self)
53
54 # rare error where scalar name isn't a valid scalar
---> 55 if name not in self.point_arrays:
56 if name not in self.cell_arrays:
57 if name in self.field_arrays:
... last 3 frames repeated, from the frame below ...
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in point_arrays(self)
697 for i in range(narr):
698 name = pdata.GetArrayName(i)
--> 699 self._point_arrays[name] = self._point_scalar(name)
700
701 self._point_arrays.enable_callback()
RecursionError: maximum recursion depth exceeded
|
RecursionError
|
def format_array(name, arr, field):
"""internal helper to foramt array information for printing"""
dl, dh = self.get_data_range(arr)
dl = pyvista.FLOAT_FORMAT.format(dl)
dh = pyvista.FLOAT_FORMAT.format(dh)
if name == self.active_scalar_info[1]:
name = "<b>{}</b>".format(name)
if arr.ndim > 1:
ncomp = arr.shape[1]
else:
ncomp = 1
return row.format(name, field, arr.dtype, ncomp, dl, dh)
|
def format_array(key, field):
"""internal helper to foramt array information for printing"""
arr = get_scalar(self, key, preference=field)
dl, dh = self.get_data_range(key)
dl = pyvista.FLOAT_FORMAT.format(dl)
dh = pyvista.FLOAT_FORMAT.format(dh)
if key == self.active_scalar_info[1]:
key = "<b>{}</b>".format(key)
if arr.ndim > 1:
ncomp = arr.shape[1]
else:
ncomp = 1
return row.format(key, field, arr.dtype, ncomp, dl, dh)
|
https://github.com/pyvista/pyvista/issues/306
|
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
<ipython-input-15-403e4a0f4e87> in <module>
9
10 # Try to access the point arrays
---> 11 continents.point_arrays
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in point_arrays(self)
697 for i in range(narr):
698 name = pdata.GetArrayName(i)
--> 699 self._point_arrays[name] = self._point_scalar(name)
700
701 self._point_arrays.enable_callback()
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in _point_scalar(self, name)
342 if name is None:
343 # use active scalar array
--> 344 field, name = self.active_scalar_info
345 if field != POINT_DATA_FIELD:
346 raise RuntimeError('Must specify an array to fetch.')
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in active_scalar_info(self)
53
54 # rare error where scalar name isn't a valid scalar
---> 55 if name not in self.point_arrays:
56 if name not in self.cell_arrays:
57 if name in self.field_arrays:
... last 3 frames repeated, from the frame below ...
~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in point_arrays(self)
697 for i in range(narr):
698 name = pdata.GetArrayName(i)
--> 699 self._point_arrays[name] = self._point_scalar(name)
700
701 self._point_arrays.enable_callback()
RecursionError: maximum recursion depth exceeded
|
RecursionError
|
def glyph(
dataset,
orient=True,
scale=True,
factor=1.0,
geom=None,
tolerance=0.0,
absolute=False,
):
"""
Copies a geometric representation (called a glyph) to every
point in the input dataset. The glyph may be oriented along
the input vectors, and it may be scaled according to scalar
data or vector magnitude.
Parameters
----------
orient : bool
Use the active vectors array to orient the the glyphs
scale : bool
Use the active scalars to scale the glyphs
factor : float
Scale factor applied to sclaing array
geom : vtk.vtkDataSet
The geometry to use for the glyph
tolerance : float, optional
Specify tolerance in terms of fraction of bounding box length.
Float value is between 0 and 1. Default is 0.0. If ``absolute``
is ``True`` then the tolerance can be an absolute distance.
absolute : bool, optional
Control if ``tolerance`` is an absolute distance or a fraction.
"""
# Clean the points before glyphing
small = pyvista.PolyData(dataset.points)
small.point_arrays.update(dataset.point_arrays)
dataset = small.clean(
point_merging=True,
merge_tol=tolerance,
lines_to_points=False,
polys_to_lines=False,
strips_to_polys=False,
inplace=False,
absolute=absolute,
)
# Make glyphing geometry
if geom is None:
arrow = vtk.vtkArrowSource()
arrow.Update()
geom = arrow.GetOutput()
# Run the algorithm
alg = vtk.vtkGlyph3D()
alg.SetSourceData(geom)
if isinstance(scale, str):
dataset.active_scalar_name = scale
scale = True
if scale:
if dataset.active_scalar is not None:
if dataset.active_scalar.ndim > 1:
alg.SetScaleModeToScaleByVector()
else:
alg.SetScaleModeToScaleByScalar()
else:
alg.SetScaleModeToDataScalingOff()
if isinstance(orient, str):
dataset.active_vectors_name = orient
orient = True
alg.SetOrient(orient)
alg.SetInputData(dataset)
alg.SetVectorModeToUseVector()
alg.SetScaleFactor(factor)
alg.Update()
return _get_output(alg)
|
def glyph(dataset, orient=True, scale=True, factor=1.0, geom=None, subset=None):
"""
Copies a geometric representation (called a glyph) to every
point in the input dataset. The glyph may be oriented along
the input vectors, and it may be scaled according to scalar
data or vector magnitude.
Parameters
----------
orient : bool
Use the active vectors array to orient the the glyphs
scale : bool
Use the active scalars to scale the glyphs
factor : float
Scale factor applied to sclaing array
geom : vtk.vtkDataSet
The geometry to use for the glyph
subset : float, optional
Take a percentage subset of the mesh's points. Float value is
percent subset between 0 and 1.
"""
if subset is not None:
if subset <= 0.0 or subset > 1.0:
raise RuntimeError("subset must be a percentage between 0 and 1.")
ids = np.random.randint(
low=0, high=dataset.n_points - 1, size=int(dataset.n_points * subset)
)
small = pyvista.PolyData(dataset.points[ids])
for name in dataset.point_arrays.keys():
small.point_arrays[name] = dataset.point_arrays[name][ids]
dataset = small
if geom is None:
arrow = vtk.vtkArrowSource()
arrow.Update()
geom = arrow.GetOutput()
alg = vtk.vtkGlyph3D()
alg.SetSourceData(geom)
if isinstance(scale, str):
dataset.active_scalar_name = scale
scale = True
if scale:
if dataset.active_scalar is not None:
if dataset.active_scalar.ndim > 1:
alg.SetScaleModeToScaleByVector()
else:
alg.SetScaleModeToScaleByScalar()
else:
alg.SetScaleModeToDataScalingOff()
if isinstance(orient, str):
dataset.active_vectors_name = orient
orient = True
alg.SetOrient(orient)
alg.SetInputData(dataset)
alg.SetVectorModeToUseVector()
alg.SetScaleFactor(factor)
alg.Update()
return _get_output(alg)
|
https://github.com/pyvista/pyvista/issues/301
|
Traceback (most recent call last):
File "cmap.py", line 54, in <module>
p.add_mesh(mesh, cmap="fire", lighting=True, stitle="Colorcet Fire")
File "/home/musy/soft/anaconda3/lib/python3.6/site-packages/pyvista/plotting/plotting.py", line 752, in add_mesh
cmap = get_cmap_safe(cmap)
File "/home/musy/soft/anaconda3/lib/python3.6/site-packages/pyvista/plotting/colors.py", line 391, in get_cmap_safe
cmap = get_cmap(cmap)
File "/home/musy/soft/anaconda3/lib/python3.6/site-packages/matplotlib/cm.py", line 182, in get_cmap
% (name, ', '.join(sorted(cmap_d))))
ValueError: Colormap fire is not recognized. Possible values are: Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r ...
|
ValueError
|
def clean(
self,
point_merging=True,
merge_tol=None,
lines_to_points=True,
polys_to_lines=True,
strips_to_polys=True,
inplace=False,
absolute=True,
**kwargs,
):
"""
Cleans mesh by merging duplicate points, remove unused
points, and/or remove degenerate cells.
Parameters
----------
point_merging : bool, optional
Enables point merging. On by default.
merge_tol : float, optional
Set merging tolarance. When enabled merging is set to
absolute distance. If ``absolute`` is False, then the merging
tolerance is a fraction of the bounding box legnth. The alias
``tolerance`` is also excepted.
lines_to_points : bool, optional
Turn on/off conversion of degenerate lines to points. Enabled by
default.
polys_to_lines : bool, optional
Turn on/off conversion of degenerate polys to lines. Enabled by
default.
strips_to_polys : bool, optional
Turn on/off conversion of degenerate strips to polys.
inplace : bool, optional
Updates mesh in-place while returning nothing. Default True.
absolute : bool, optional
Control if ``merge_tol`` is an absolute distance or a fraction.
Returns
-------
mesh : pyvista.PolyData
Cleaned mesh. None when inplace=True
"""
if merge_tol is None:
merge_tol = kwargs.pop("tolerance", None)
clean = vtk.vtkCleanPolyData()
clean.SetConvertLinesToPoints(lines_to_points)
clean.SetConvertPolysToLines(polys_to_lines)
clean.SetConvertStripsToPolys(strips_to_polys)
if isinstance(merge_tol, (int, float)):
if absolute:
clean.ToleranceIsAbsoluteOn()
clean.SetAbsoluteTolerance(merge_tol)
else:
clean.SetTolerance(merge_tol)
clean.SetInputData(self)
clean.Update()
output = _get_output(clean)
# Check output so no segfaults occur
if output.n_points < 1:
raise AssertionError("Clean tolerance is too high. Empty mesh returned.")
if inplace:
self.overwrite(output)
else:
return output
|
def clean(
self,
point_merging=True,
merge_tol=None,
lines_to_points=True,
polys_to_lines=True,
strips_to_polys=True,
inplace=False,
):
"""
Cleans mesh by merging duplicate points, remove unused
points, and/or remove degenerate cells.
Parameters
----------
point_merging : bool, optional
Enables point merging. On by default.
merge_tol : float, optional
Set merging tolarance. When enabled merging is set to
absolute distance
lines_to_points : bool, optional
Turn on/off conversion of degenerate lines to points. Enabled by
default.
polys_to_lines : bool, optional
Turn on/off conversion of degenerate polys to lines. Enabled by
default.
strips_to_polys : bool, optional
Turn on/off conversion of degenerate strips to polys.
inplace : bool, optional
Updates mesh in-place while returning nothing. Default True.
Returns
-------
mesh : pyvista.PolyData
Cleaned mesh. None when inplace=True
"""
clean = vtk.vtkCleanPolyData()
clean.SetConvertLinesToPoints(lines_to_points)
clean.SetConvertPolysToLines(polys_to_lines)
clean.SetConvertStripsToPolys(strips_to_polys)
if merge_tol:
clean.ToleranceIsAbsoluteOn()
clean.SetAbsoluteTolerance(merge_tol)
clean.SetInputData(self)
clean.Update()
output = _get_output(clean)
# Check output so no segfaults occur
if output.n_points < 1:
raise AssertionError("Clean tolerance is too high. Empty mesh returned.")
if inplace:
self.overwrite(output)
else:
return output
|
https://github.com/pyvista/pyvista/issues/301
|
Traceback (most recent call last):
File "cmap.py", line 54, in <module>
p.add_mesh(mesh, cmap="fire", lighting=True, stitle="Colorcet Fire")
File "/home/musy/soft/anaconda3/lib/python3.6/site-packages/pyvista/plotting/plotting.py", line 752, in add_mesh
cmap = get_cmap_safe(cmap)
File "/home/musy/soft/anaconda3/lib/python3.6/site-packages/pyvista/plotting/colors.py", line 391, in get_cmap_safe
cmap = get_cmap(cmap)
File "/home/musy/soft/anaconda3/lib/python3.6/site-packages/matplotlib/cm.py", line 182, in get_cmap
% (name, ', '.join(sorted(cmap_d))))
ValueError: Colormap fire is not recognized. Possible values are: Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r ...
|
ValueError
|
def add_volume(
self,
volume,
scalars=None,
resolution=None,
opacity="linear",
n_colors=256,
cmap=None,
flip_scalars=False,
reset_camera=None,
name=None,
ambient=0.0,
categories=False,
loc=None,
backface_culling=False,
multi_colors=False,
blending="composite",
mapper="smart",
rng=None,
stitle=None,
scalar_bar_args=None,
show_scalar_bar=None,
**kwargs,
):
"""
Adds a volume, rendered using a fixed point ray cast mapper by default.
Requires a 3D numpy.ndarray or pyvista.UniformGrid.
Parameters
----------
data: 3D numpy.ndarray or pyvista.UnformGrid
The input array to visualize, assuming the array values denote
scalar intensities.
opacity : float or string, optional
Opacity of input array. Options are: linear, linear_r, geom, geom_r.
Defaults to 'linear'. Can also be given as a scalar value between 0
and 1.
flip_scalars : bool, optional
Flip direction of cmap.
n_colors : int, optional
Number of colors to use when displaying scalars. Default
256.
cmap : str, optional
cmap string. See available matplotlib cmaps. Only applicable for when
displaying scalars. Defaults to None (jet). Requires matplotlib.
Will be overridden if multi_colors is set to True.
name : str, optional
The name for the added actor so that it can be easily
updated. If an actor of this name already exists in the
rendering window, it will be replaced by the new actor.
ambient : float, optional
The amount of light from 0 to 1 that reaches the actor when not
directed at the light source emitted from the viewer. Default 0.0.
loc : int, tuple, or list
Index of the renderer to add the actor to. For example,
``loc=2`` or ``loc=(1, 1)``. If None, selects the last
active Renderer.
backface_culling : bool optional
Does not render faces that should not be visible to the
plotter. This can be helpful for dense surface meshes,
especially when edges are visible, but can cause flat
meshes to be partially displayed. Default False.
categories : bool, optional
If fetching a colormap from matplotlib, this is the number of
categories to use in that colormap. If set to ``True``, then
the number of unique values in the scalar array will be used.
multi_colors : bool, optional
Whether or not to use multiple colors when plotting MultiBlock
object. Blocks will be colored sequentially as 'Reds', 'Greens',
'Blues', and 'Grays'.
blending : str, optional
Blending mode for visualisation of the input object(s). Can be
one of 'additive', 'maximum', 'minimum', 'composite', or
'average'. Defaults to 'additive'.
Returns
-------
actor: vtk.vtkVolume
VTK volume of the input data.
"""
# Handle default arguments
if name is None:
name = "{}({})".format(type(volume).__name__, str(hex(id(volume))))
if rng is None:
rng = kwargs.get("clim", None)
if scalar_bar_args is None:
scalar_bar_args = {}
if show_scalar_bar is None:
show_scalar_bar = rcParams["show_scalar_bar"]
# Convert the VTK data object to a pyvista wrapped object if neccessary
if not is_pyvista_obj(volume):
if isinstance(volume, np.ndarray):
volume = wrap(volume)
if resolution is None:
resolution = [1, 1, 1]
elif len(resolution) != 3:
raise ValueError("Invalid resolution dimensions.")
volume.spacing = resolution
else:
volume = wrap(volume)
else:
# HACK: Make a copy so the original object is not altered
volume = volume.copy()
if isinstance(volume, pyvista.MultiBlock):
from itertools import cycle
cycler = cycle(["Reds", "Greens", "Blues", "Greys", "Oranges", "Purples"])
# Now iteratively plot each element of the multiblock dataset
actors = []
for idx in range(volume.GetNumberOfBlocks()):
if volume[idx] is None:
continue
# Get a good name to use
next_name = "{}-{}".format(name, idx)
# Get the data object
block = wrap(volume.GetBlock(idx))
if resolution is None:
try:
block_resolution = block.GetSpacing()
except:
block_resolution = resolution
else:
block_resolution = resolution
if multi_colors:
color = next(cycler)
else:
color = cmap
a = self.add_volume(
block,
resolution=block_resolution,
opacity=opacity,
n_colors=n_colors,
cmap=color,
flip_scalars=flip_scalars,
reset_camera=reset_camera,
name=next_name,
ambient=ambient,
categories=categories,
loc=loc,
backface_culling=backface_culling,
rng=rng,
mapper=mapper,
**kwargs,
)
actors.append(a)
return actors
if not isinstance(volume, pyvista.UniformGrid):
raise TypeError(
"Type ({}) not supported for volume rendering at this time. Use `pyvista.UniformGrid`."
)
if scalars is None:
# Make sure scalar components are not vectors/tuples
scalars = volume.active_scalar
# Don't allow plotting of string arrays by default
if scalars is not None and np.issubdtype(scalars.dtype, np.number):
if stitle is None:
stitle = volume.active_scalar_info[1]
else:
raise RuntimeError("No scalars to use for volume rendering.")
elif isinstance(scalars, str):
pass
##############
title = "Data" if stitle is None else stitle
append_scalars = False
if isinstance(scalars, str):
title = scalars
scalars = get_scalar(
volume, scalars, preference=kwargs.get("preference", "point"), err=True
)
if stitle is None:
stitle = title
else:
append_scalars = True
if not isinstance(scalars, np.ndarray):
scalars = np.asarray(scalars)
if not np.issubdtype(scalars.dtype, np.number):
raise TypeError("Non-numeric scalars are currently not supported for plotting.")
if scalars.ndim != 1:
scalars = scalars.ravel()
if scalars.dtype == np.bool or scalars.dtype == np.uint8:
scalars = scalars.astype(np.float)
# Define mapper, volume, and add the correct properties
mappers = {
"fixed_point": vtk.vtkFixedPointVolumeRayCastMapper,
"gpu": vtk.vtkGPUVolumeRayCastMapper,
"open_gl": vtk.vtkOpenGLGPUVolumeRayCastMapper,
"smart": vtk.vtkSmartVolumeMapper,
}
if not isinstance(mapper, str) or mapper not in mappers.keys():
raise RuntimeError(
"Mapper ({}) unknown. Available volume mappers include: {}".format(
mapper, ", ".join(mappers.keys())
)
)
self.mapper = make_mapper(mappers[mapper])
# Scalar interpolation approach
if scalars.shape[0] == volume.n_points:
volume._add_point_scalar(scalars, title, append_scalars)
self.mapper.SetScalarModeToUsePointData()
elif scalars.shape[0] == volume.n_cells:
volume._add_cell_scalar(scalars, title, append_scalars)
self.mapper.SetScalarModeToUseCellData()
else:
raise_not_matching(scalars, volume)
# Set scalar range
if rng is None:
rng = [np.nanmin(scalars), np.nanmax(scalars)]
elif isinstance(rng, float) or isinstance(rng, int):
rng = [-rng, rng]
###############
scalars = scalars.astype(np.float)
idxs0 = scalars < rng[0]
idxs1 = scalars > rng[1]
scalars[idxs0] = np.nan
scalars[idxs1] = np.nan
scalars = (
(scalars - np.nanmin(scalars)) / (np.nanmax(scalars) - np.nanmin(scalars))
) * 255
# scalars = scalars.astype(np.uint8)
volume[title] = scalars
self.mapper.scalar_range = rng
# Set colormap and build lookup table
table = vtk.vtkLookupTable()
# table.SetNanColor(nan_color) # NaN's are chopped out with current implementation
if cmap is None: # grab alias for cmaps: colormap
cmap = kwargs.get("colormap", None)
if cmap is None: # Set default map if matplotlib is avaialble
try:
import matplotlib
cmap = rcParams["cmap"]
except ImportError:
pass
if cmap is not None:
try:
from matplotlib.cm import get_cmap
except ImportError:
cmap = None
raise RuntimeError("Please install matplotlib for volume rendering.")
if cmap is not None:
cmap = get_cmap_safe(cmap)
if categories:
if categories is True:
n_colors = len(np.unique(scalars))
elif isinstance(categories, int):
n_colors = categories
if flip_scalars:
cmap = cmap.reversed()
color_tf = vtk.vtkColorTransferFunction()
for ii in range(n_colors):
color_tf.AddRGBPoint(ii, *cmap(ii)[:-1])
# Set opacities
if isinstance(opacity, (float, int)):
opacity_values = [opacity] * n_colors
elif isinstance(opacity, str):
opacity_values = pyvista.opacity_transfer_function(opacity, n_colors)
opacity_tf = vtk.vtkPiecewiseFunction()
for ii in range(n_colors):
opacity_tf.AddPoint(ii, opacity_values[ii] / n_colors)
# Now put color tf and opacity tf into a lookup table for the scalar bar
table.SetNumberOfTableValues(n_colors)
lut = cmap(np.array(range(n_colors))) * 255
lut[:, 3] = opacity_values
lut = lut.astype(np.uint8)
table.SetTable(VN.numpy_to_vtk(lut))
table.SetRange(*rng)
self.mapper.lookup_table = table
self.mapper.SetInputData(volume)
blending = blending.lower()
if blending in ["additive", "add", "sum"]:
self.mapper.SetBlendModeToAdditive()
elif blending in ["average", "avg", "average_intensity"]:
self.mapper.SetBlendModeToAverageIntensity()
elif blending in ["composite", "comp"]:
self.mapper.SetBlendModeToComposite()
elif blending in ["maximum", "max", "maximum_intensity"]:
self.mapper.SetBlendModeToMaximumIntensity()
elif blending in ["minimum", "min", "minimum_intensity"]:
self.mapper.SetBlendModeToMinimumIntensity()
else:
raise ValueError(
"Blending mode '{}' invalid. ".format(blending)
+ "Please choose one "
+ "of 'additive', "
+ "'composite', 'minimum' or "
+ "'maximum'."
)
self.mapper.Update()
self.volume = vtk.vtkVolume()
self.volume.SetMapper(self.mapper)
prop = vtk.vtkVolumeProperty()
prop.SetColor(color_tf)
prop.SetScalarOpacity(opacity_tf)
prop.SetAmbient(ambient)
self.volume.SetProperty(prop)
actor, prop = self.add_actor(
self.volume,
reset_camera=reset_camera,
name=name,
loc=loc,
culling=backface_culling,
)
# Add scalar bar
if stitle is not None and show_scalar_bar:
self.add_scalar_bar(stitle, **scalar_bar_args)
return actor
|
def add_volume(
self,
volume,
scalars=None,
resolution=None,
opacity="linear",
n_colors=256,
cmap=None,
flip_scalars=False,
reset_camera=None,
name=None,
ambient=0.0,
categories=False,
loc=None,
backface_culling=False,
multi_colors=False,
blending="additive",
mapper="fixed_point",
rng=None,
stitle=None,
scalar_bar_args=None,
show_scalar_bar=None,
**kwargs,
):
"""
Adds a volume, rendered using a fixed point ray cast mapper by default.
Requires a 3D numpy.ndarray or pyvista.UniformGrid.
Parameters
----------
data: 3D numpy.ndarray or pyvista.UnformGrid
The input array to visualize, assuming the array values denote
scalar intensities.
opacity : float or string, optional
Opacity of input array. Options are: linear, linear_r, geom, geom_r.
Defaults to 'linear'. Can also be given as a scalar value between 0
and 1.
flip_scalars : bool, optional
Flip direction of cmap.
n_colors : int, optional
Number of colors to use when displaying scalars. Default
256.
cmap : str, optional
cmap string. See available matplotlib cmaps. Only applicable for when
displaying scalars. Defaults to None (jet). Requires matplotlib.
Will be overridden if multi_colors is set to True.
name : str, optional
The name for the added actor so that it can be easily
updated. If an actor of this name already exists in the
rendering window, it will be replaced by the new actor.
ambient : float, optional
The amount of light from 0 to 1 that reaches the actor when not
directed at the light source emitted from the viewer. Default 0.0.
loc : int, tuple, or list
Index of the renderer to add the actor to. For example,
``loc=2`` or ``loc=(1, 1)``. If None, selects the last
active Renderer.
backface_culling : bool optional
Does not render faces that should not be visible to the
plotter. This can be helpful for dense surface meshes,
especially when edges are visible, but can cause flat
meshes to be partially displayed. Default False.
categories : bool, optional
If fetching a colormap from matplotlib, this is the number of
categories to use in that colormap. If set to ``True``, then
the number of unique values in the scalar array will be used.
multi_colors : bool, optional
Whether or not to use multiple colors when plotting MultiBlock
object. Blocks will be colored sequentially as 'Reds', 'Greens',
'Blues', and 'Grays'.
blending : str, optional
Blending mode for visualisation of the input object(s). Can be
one of 'additive', 'maximum', 'minimum', 'composite', or
'average'. Defaults to 'additive'.
Returns
-------
actor: vtk.vtkVolume
VTK volume of the input data.
"""
# Handle default arguments
if name is None:
name = "{}({})".format(type(volume).__name__, str(hex(id(volume))))
if rng is None:
rng = kwargs.get("clim", None)
if scalar_bar_args is None:
scalar_bar_args = {}
if show_scalar_bar is None:
show_scalar_bar = rcParams["show_scalar_bar"]
# Convert the VTK data object to a pyvista wrapped object if neccessary
if not is_pyvista_obj(volume):
if isinstance(volume, np.ndarray):
volume = wrap(volume)
if resolution is None:
resolution = [1, 1, 1]
elif len(resolution) != 3:
raise ValueError("Invalid resolution dimensions.")
volume.spacing = resolution
else:
volume = wrap(volume)
else:
# HACK: Make a copy so the original object is not altered
volume = volume.copy()
if isinstance(volume, pyvista.MultiBlock):
from itertools import cycle
cycler = cycle(["Reds", "Greens", "Blues", "Greys", "Oranges", "Purples"])
# Now iteratively plot each element of the multiblock dataset
actors = []
for idx in range(volume.GetNumberOfBlocks()):
if volume[idx] is None:
continue
# Get a good name to use
next_name = "{}-{}".format(name, idx)
# Get the data object
block = wrap(volume.GetBlock(idx))
if resolution is None:
try:
block_resolution = block.GetSpacing()
except:
block_resolution = resolution
else:
block_resolution = resolution
if multi_colors:
color = next(cycler)
else:
color = cmap
a = self.add_volume(
block,
resolution=block_resolution,
opacity=opacity,
n_colors=n_colors,
cmap=color,
flip_scalars=flip_scalars,
reset_camera=reset_camera,
name=next_name,
ambient=ambient,
categories=categories,
loc=loc,
backface_culling=backface_culling,
rng=rng,
mapper=mapper,
**kwargs,
)
actors.append(a)
return actors
if not isinstance(volume, pyvista.UniformGrid):
raise TypeError(
"Type ({}) not supported for volume rendering at this time. Use `pyvista.UniformGrid`."
)
if scalars is None:
# Make sure scalar components are not vectors/tuples
scalars = volume.active_scalar
# Don't allow plotting of string arrays by default
if scalars is not None and np.issubdtype(scalars.dtype, np.number):
if stitle is None:
stitle = volume.active_scalar_info[1]
else:
raise RuntimeError("No scalars to use for volume rendering.")
elif isinstance(scalars, str):
pass
##############
title = "Data" if stitle is None else stitle
append_scalars = False
if isinstance(scalars, str):
title = scalars
scalars = get_scalar(
volume, scalars, preference=kwargs.get("preference", "point"), err=True
)
if stitle is None:
stitle = title
else:
append_scalars = True
if not isinstance(scalars, np.ndarray):
scalars = np.asarray(scalars)
if not np.issubdtype(scalars.dtype, np.number):
raise TypeError("Non-numeric scalars are currently not supported for plotting.")
if scalars.ndim != 1:
scalars = scalars.ravel()
if scalars.dtype == np.bool or scalars.dtype == np.uint8:
scalars = scalars.astype(np.float)
# Define mapper, volume, and add the correct properties
mappers = {
"fixed_point": vtk.vtkFixedPointVolumeRayCastMapper,
"gpu": vtk.vtkGPUVolumeRayCastMapper,
"open_gl": vtk.vtkOpenGLGPUVolumeRayCastMapper,
"smart": vtk.vtkSmartVolumeMapper,
}
if not isinstance(mapper, str) or mapper not in mappers.keys():
raise RuntimeError(
"Mapper ({}) unknown. Available volume mappers include: {}".format(
mapper, ", ".join(mappers.keys())
)
)
self.mapper = make_mapper(mappers[mapper])
# Scalar interpolation approach
if scalars.shape[0] == volume.n_points:
volume._add_point_scalar(scalars, title, append_scalars)
self.mapper.SetScalarModeToUsePointData()
elif scalars.shape[0] == volume.n_cells:
volume._add_cell_scalar(scalars, title, append_scalars)
self.mapper.SetScalarModeToUseCellData()
else:
raise_not_matching(scalars, volume)
# Set scalar range
if rng is None:
rng = [np.nanmin(scalars), np.nanmax(scalars)]
elif isinstance(rng, float) or isinstance(rng, int):
rng = [-rng, rng]
###############
scalars = scalars.astype(np.float)
idxs0 = scalars < rng[0]
idxs1 = scalars > rng[1]
scalars[idxs0] = np.nan
scalars[idxs1] = np.nan
scalars = (
(scalars - np.nanmin(scalars)) / (np.nanmax(scalars) - np.nanmin(scalars))
) * 255
# scalars = scalars.astype(np.uint8)
volume[title] = scalars
self.mapper.scalar_range = rng
# Set colormap and build lookup table
table = vtk.vtkLookupTable()
# table.SetNanColor(nan_color) # NaN's are chopped out with current implementation
if cmap is None: # grab alias for cmaps: colormap
cmap = kwargs.get("colormap", None)
if cmap is None: # Set default map if matplotlib is avaialble
try:
import matplotlib
cmap = rcParams["cmap"]
except ImportError:
pass
if cmap is not None:
try:
from matplotlib.cm import get_cmap
except ImportError:
cmap = None
raise RuntimeError("Please install matplotlib for volume rendering.")
if cmap is not None:
cmap = get_cmap_safe(cmap)
if categories:
if categories is True:
n_colors = len(np.unique(scalars))
elif isinstance(categories, int):
n_colors = categories
if flip_scalars:
cmap = cmap.reversed()
color_tf = vtk.vtkColorTransferFunction()
for ii in range(n_colors):
color_tf.AddRGBPoint(ii, *cmap(ii)[:-1])
# Set opacities
if isinstance(opacity, (float, int)):
opacity_values = [opacity] * n_colors
elif isinstance(opacity, str):
opacity_values = pyvista.opacity_transfer_function(opacity, n_colors)
opacity_tf = vtk.vtkPiecewiseFunction()
for ii in range(n_colors):
opacity_tf.AddPoint(ii, opacity_values[ii] / n_colors)
# Now put color tf and opacity tf into a lookup table for the scalar bar
table.SetNumberOfTableValues(n_colors)
lut = cmap(np.array(range(n_colors))) * 255
lut[:, 3] = opacity_values
lut = lut.astype(np.uint8)
table.SetTable(VN.numpy_to_vtk(lut))
table.SetRange(*rng)
self.mapper.lookup_table = table
self.mapper.SetInputData(volume)
blending = blending.lower()
if blending in ["additive", "add", "sum"]:
self.mapper.SetBlendModeToAdditive()
elif blending in ["average", "avg", "average_intensity"]:
self.mapper.SetBlendModeToAverageIntensity()
elif blending in ["composite", "comp"]:
self.mapper.SetBlendModeToComposite()
elif blending in ["maximum", "max", "maximum_intensity"]:
self.mapper.SetBlendModeToMaximumIntensity()
elif blending in ["minimum", "min", "minimum_intensity"]:
self.mapper.SetBlendModeToMinimumIntensity()
else:
raise ValueError(
"Blending mode '{}' invalid. ".format(blending)
+ "Please choose one "
+ "of 'additive', "
+ "'composite', 'minimum' or "
+ "'maximum'."
)
self.mapper.Update()
self.volume = vtk.vtkVolume()
self.volume.SetMapper(self.mapper)
prop = vtk.vtkVolumeProperty()
prop.SetColor(color_tf)
prop.SetScalarOpacity(opacity_tf)
prop.SetAmbient(ambient)
self.volume.SetProperty(prop)
actor, prop = self.add_actor(
self.volume,
reset_camera=reset_camera,
name=name,
loc=loc,
culling=backface_culling,
)
# Add scalar bar
if stitle is not None and show_scalar_bar:
self.add_scalar_bar(stitle, **scalar_bar_args)
return actor
|
https://github.com/pyvista/pyvista/issues/301
|
Traceback (most recent call last):
File "cmap.py", line 54, in <module>
p.add_mesh(mesh, cmap="fire", lighting=True, stitle="Colorcet Fire")
File "/home/musy/soft/anaconda3/lib/python3.6/site-packages/pyvista/plotting/plotting.py", line 752, in add_mesh
cmap = get_cmap_safe(cmap)
File "/home/musy/soft/anaconda3/lib/python3.6/site-packages/pyvista/plotting/colors.py", line 391, in get_cmap_safe
cmap = get_cmap(cmap)
File "/home/musy/soft/anaconda3/lib/python3.6/site-packages/matplotlib/cm.py", line 182, in get_cmap
% (name, ', '.join(sorted(cmap_d))))
ValueError: Colormap fire is not recognized. Possible values are: Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r ...
|
ValueError
|
def close(self):
"""closes render window"""
# must close out widgets first
if hasattr(self, "axes_widget"):
del self.axes_widget
if hasattr(self, "scalar_widget"):
del self.scalar_widget
# reset scalar bar stuff
self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS))
self._scalar_bar_slot_lookup = {}
self._scalar_bar_ranges = {}
self._scalar_bar_mappers = {}
self._scalar_bar_actors = {}
self._scalar_bar_widgets = {}
if hasattr(self, "ren_win"):
self.ren_win.Finalize()
del self.ren_win
if hasattr(self, "_style"):
del self._style
if hasattr(self, "iren"):
self.iren.RemoveAllObservers()
del self.iren
if hasattr(self, "textActor"):
del self.textActor
# end movie
if hasattr(self, "mwriter"):
try:
self.mwriter.close()
except BaseException:
pass
|
def close(self):
"""closes render window"""
# must close out axes marker
if hasattr(self, "axes_widget"):
del self.axes_widget
# reset scalar bar stuff
self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS))
self._scalar_bar_slot_lookup = {}
self._scalar_bar_ranges = {}
self._scalar_bar_mappers = {}
if hasattr(self, "ren_win"):
self.ren_win.Finalize()
del self.ren_win
if hasattr(self, "_style"):
del self._style
if hasattr(self, "iren"):
self.iren.RemoveAllObservers()
del self.iren
if hasattr(self, "textActor"):
del self.textActor
# end movie
if hasattr(self, "mwriter"):
try:
self.mwriter.close()
except BaseException:
pass
|
https://github.com/pyvista/pyvista/issues/301
|
Traceback (most recent call last):
File "cmap.py", line 54, in <module>
p.add_mesh(mesh, cmap="fire", lighting=True, stitle="Colorcet Fire")
File "/home/musy/soft/anaconda3/lib/python3.6/site-packages/pyvista/plotting/plotting.py", line 752, in add_mesh
cmap = get_cmap_safe(cmap)
File "/home/musy/soft/anaconda3/lib/python3.6/site-packages/pyvista/plotting/colors.py", line 391, in get_cmap_safe
cmap = get_cmap(cmap)
File "/home/musy/soft/anaconda3/lib/python3.6/site-packages/matplotlib/cm.py", line 182, in get_cmap
% (name, ', '.join(sorted(cmap_d))))
ValueError: Colormap fire is not recognized. Possible values are: Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r ...
|
ValueError
|
def __getitem__(self, index):
"""Get a block by its index or name (if the name is non-unique then
returns the first occurence)"""
if isinstance(index, str):
index = self.get_index_by_name(index)
data = self.GetBlock(index)
if data is None:
return data
if data is not None and not is_vtki_obj(data):
data = wrap(data)
if data not in self.refs:
self.refs.append(data)
return data
|
def __getitem__(self, index):
"""Get a block by its index or name (if the name is non-unique then
returns the first occurence)"""
if isinstance(index, str):
index = self.get_index_by_name(index)
data = self.GetBlock(index)
if data is None:
return data
if data is not None and not is_vtki_obj(data):
data = wrap(data)
return data
|
https://github.com/pyvista/pyvista/issues/158
|
---------------------------------------------------------------------------
ReferenceError Traceback (most recent call last)
<ipython-input-5-1ae88bf5bf88> in <module>()
1 # Add values to the meshes so colors are consistent with other data
2 # try:
----> 3 proj['temp_175c'].point_arrays['Temperature'] = np.full(proj['temp_175c'].n_points, 175.)
4 proj['temp_225c'].point_arrays['Temperature'] = np.full(proj['temp_225c'].n_points, 225.)
5 # tc = vtki.MultiBlock()
~/Documents/OpenGeoVis/Software/vtki/vtki/common.py in __setitem__(self, key, val)
883 """ overridden to assure data is contigious """
884 if self.callback_enabled:
--> 885 self.adder(val, key, deep=False)
886 dict.__setitem__(self, key, val)
887 self.modifier()
~/Documents/OpenGeoVis/Software/vtki/vtki/common.py in adder(self, scalars, name, set_active, deep)
920
921 def adder(self, scalars, name, set_active=False, deep=True):
--> 922 self.data._add_point_scalar(scalars, name, set_active=False, deep=deep)
923
924
ReferenceError: weakly-referenced object no longer exists
|
ReferenceError
|
def __setitem__(self, index, data):
"""Sets a block with a VTK data object. To set the name simultaneously,
pass a string name as the 2nd index.
Example
-------
>>> import vtki
>>> multi = vtki.MultiBlock()
>>> multi[0] = vtki.PolyData()
>>> multi[1, 'foo'] = vtki.UnstructuredGrid()
>>> multi['bar'] = vtki.PolyData()
>>> multi.n_blocks
3
"""
if isinstance(index, collections.Iterable) and not isinstance(index, str):
i, name = index[0], index[1]
elif isinstance(index, str):
try:
i = self.get_index_by_name(index)
except KeyError:
i = -1
name = index
else:
i, name = index, None
if data is not None and not is_vtki_obj(data):
data = wrap(data)
if i == -1:
self.append(data)
i = self.n_blocks - 1
else:
self.SetBlock(i, data)
if name is None:
name = "Block-{0:02}".format(i)
self.set_block_name(i, name) # Note that this calls self.Modified()
if data not in self.refs:
self.refs.append(data)
|
def __setitem__(self, index, data):
"""Sets a block with a VTK data object. To set the name simultaneously,
pass a string name as the 2nd index.
Example
-------
>>> import vtki
>>> multi = vtki.MultiBlock()
>>> multi[0] = vtki.PolyData()
>>> multi[1, 'foo'] = vtki.UnstructuredGrid()
>>> multi['bar'] = vtki.PolyData()
>>> multi.n_blocks
3
"""
if isinstance(index, collections.Iterable) and not isinstance(index, str):
i, name = index[0], index[1]
elif isinstance(index, str):
try:
i = self.get_index_by_name(index)
except KeyError:
i = -1
name = index
else:
i, name = index, None
if data is not None and not is_vtki_obj(data):
data = wrap(data)
if i == -1:
self.append(data)
i = self.n_blocks - 1
else:
self.SetBlock(i, data)
if name is None:
name = "Block-{0:02}".format(i)
self.set_block_name(i, name) # Note that this calls self.Modified()
|
https://github.com/pyvista/pyvista/issues/158
|
---------------------------------------------------------------------------
ReferenceError Traceback (most recent call last)
<ipython-input-5-1ae88bf5bf88> in <module>()
1 # Add values to the meshes so colors are consistent with other data
2 # try:
----> 3 proj['temp_175c'].point_arrays['Temperature'] = np.full(proj['temp_175c'].n_points, 175.)
4 proj['temp_225c'].point_arrays['Temperature'] = np.full(proj['temp_225c'].n_points, 225.)
5 # tc = vtki.MultiBlock()
~/Documents/OpenGeoVis/Software/vtki/vtki/common.py in __setitem__(self, key, val)
883 """ overridden to assure data is contigious """
884 if self.callback_enabled:
--> 885 self.adder(val, key, deep=False)
886 dict.__setitem__(self, key, val)
887 self.modifier()
~/Documents/OpenGeoVis/Software/vtki/vtki/common.py in adder(self, scalars, name, set_active, deep)
920
921 def adder(self, scalars, name, set_active=False, deep=True):
--> 922 self.data._add_point_scalar(scalars, name, set_active=False, deep=deep)
923
924
ReferenceError: weakly-referenced object no longer exists
|
ReferenceError
|
def __init__(self, off_screen=False, notebook=None):
"""
Initialize a vtk plotting object
"""
log.debug("Initializing")
def onTimer(iren, eventId):
if "TimerEvent" == eventId:
# TODO: python binding didn't provide
# third parameter, which indicate right timer id
# timer_id = iren.GetCommand(44)
# if timer_id != self.right_timer_id:
# return
self.iren.TerminateApp()
self._labels = []
if notebook is None:
if run_from_ipython():
notebook = type(get_ipython()).__module__.startswith("ipykernel.")
self.notebook = notebook
if self.notebook:
off_screen = True
self.off_screen = off_screen
# initialize render window
self.renderer = vtk.vtkRenderer()
self.ren_win = vtk.vtkRenderWindow()
self.ren_win.AddRenderer(self.renderer)
if self.off_screen:
self.ren_win.SetOffScreenRendering(1)
else: # Allow user to interact
self.iren = vtk.vtkRenderWindowInteractor()
self.iren.SetDesiredUpdateRate(30.0)
self.iren.SetRenderWindow(self.ren_win)
istyle = vtk.vtkInteractorStyleTrackballCamera()
self.iren.SetInteractorStyle(istyle)
self.iren.AddObserver("KeyPressEvent", self.key_press_event)
# Set background
self.set_background(DEFAULT_BACKGROUND)
# initialize image filter
self.ifilter = vtk.vtkWindowToImageFilter()
self.ifilter.SetInput(self.ren_win)
self.ifilter.SetInputBufferTypeToRGB()
self.ifilter.ReadFrontBufferOff()
# add timer event if interactive render exists
if hasattr(self, "iren"):
self.iren.AddObserver(vtk.vtkCommand.TimerEvent, onTimer)
# track if the camera has been setup
self.camera_set = False
self.first_time = True
self.bounds = [0, 1, 0, 1, 0, 1]
|
def __init__(self, off_screen=False, notebook=None):
"""
Initialize a vtk plotting object
"""
log.debug("Initializing")
def onTimer(iren, eventId):
if "TimerEvent" == eventId:
# TODO: python binding didn't provide
# third parameter, which indicate right timer id
# timer_id = iren.GetCommand(44)
# if timer_id != self.right_timer_id:
# return
self.iren.TerminateApp()
self._labels = []
if notebook is None:
notebook = type(get_ipython()).__module__.startswith("ipykernel.")
self.notebook = notebook
if self.notebook:
off_screen = True
self.off_screen = off_screen
# initialize render window
self.renderer = vtk.vtkRenderer()
self.ren_win = vtk.vtkRenderWindow()
self.ren_win.AddRenderer(self.renderer)
if self.off_screen:
self.ren_win.SetOffScreenRendering(1)
else: # Allow user to interact
self.iren = vtk.vtkRenderWindowInteractor()
self.iren.SetDesiredUpdateRate(30.0)
self.iren.SetRenderWindow(self.ren_win)
istyle = vtk.vtkInteractorStyleTrackballCamera()
self.iren.SetInteractorStyle(istyle)
self.iren.AddObserver("KeyPressEvent", self.key_press_event)
# Set background
self.set_background(DEFAULT_BACKGROUND)
# initialize image filter
self.ifilter = vtk.vtkWindowToImageFilter()
self.ifilter.SetInput(self.ren_win)
self.ifilter.SetInputBufferTypeToRGB()
self.ifilter.ReadFrontBufferOff()
# add timer event if interactive render exists
if hasattr(self, "iren"):
self.iren.AddObserver(vtk.vtkCommand.TimerEvent, onTimer)
# track if the camera has been setup
self.camera_set = False
self.first_time = True
self.bounds = [0, 1, 0, 1, 0, 1]
|
https://github.com/pyvista/pyvista/issues/1
|
Python 2.7.13 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:17:26) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
import pyansys
C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\pyansys\archive_reader.py:32: UserWarning: Unable to load vtk dependent modules
warnings.warn('Unable to load vtk dependent modules')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\pyansys\__init__.py", line 4, in <module>
from pyansys.binary_reader import *
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\pyansys\binary_reader.py", line 7, in <module>
import vtkInterface
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\vtkInterface\__init__.py", line 7, in <module>
from vtkInterface.polydata import PolyData
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\vtkInterface\polydata.py", line 22, in <module>
class PolyData(vtkPolyData, vtkInterface.Common):
ValueError: multiple inheritance is not allowed with VTK classes
|
ValueError
|
def left_button_down(self, obj, eventType):
# Get 2D click location on window
clickPos = self.iren.GetEventPosition()
# Get corresponding click location in the 3D plot
picker = vtk.vtkWorldPointPicker()
picker.Pick(clickPos[0], clickPos[1], 0, self.renderer)
self.pickpoint = np.asarray(picker.GetPickPosition()).reshape((-1, 3))
if np.any(np.isnan(self.pickpoint)):
self.pickpoint[:] = 0
|
def left_button_down(self, obj, eventType):
# Get 2D click location on window
clickPos = self.iren.GetEventPosition()
# Get corresponding click location in the 3D plot
picker = vtk.vtkWorldPointPicker()
picker.Pick(clickPos[0], clickPos[1], 0, self.renderer)
self.pickpoint = np.asarray(picker.GetPickPosition()).reshape((-1, 3))
|
https://github.com/pyvista/pyvista/issues/1
|
Python 2.7.13 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:17:26) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
import pyansys
C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\pyansys\archive_reader.py:32: UserWarning: Unable to load vtk dependent modules
warnings.warn('Unable to load vtk dependent modules')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\pyansys\__init__.py", line 4, in <module>
from pyansys.binary_reader import *
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\pyansys\binary_reader.py", line 7, in <module>
import vtkInterface
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\vtkInterface\__init__.py", line 7, in <module>
from vtkInterface.polydata import PolyData
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\vtkInterface\polydata.py", line 22, in <module>
class PolyData(vtkPolyData, vtkInterface.Common):
ValueError: multiple inheritance is not allowed with VTK classes
|
ValueError
|
def add_mesh(
self,
mesh,
color=None,
style=None,
scalars=None,
rng=None,
stitle=None,
showedges=True,
psize=5.0,
opacity=1,
linethick=None,
flipscalars=False,
lighting=False,
ncolors=256,
interpolatebeforemap=False,
colormap=None,
label=None,
**kwargs,
):
"""
Adds a unstructured, structured, or surface mesh to the plotting object.
Also accepts a 3D numpy.ndarray
Parameters
----------
mesh : vtk unstructured, structured, polymesh, or 3D numpy.ndarray
A vtk unstructured, structured, or polymesh to plot.
color : string or 3 item list, optional, defaults to white
Either a string, rgb list, or hex color string. For example:
color='white'
color='w'
color=[1, 1, 1]
color='#FFFFFF'
Color will be overridden when scalars are input.
style : string, optional
Visualization style of the vtk mesh. One for the following:
style='surface'
style='wireframe'
style='points'
Defaults to 'surface'
scalars : numpy array, optional
Scalars used to "color" the mesh. Accepts an array equal to the
number of cells or the number of points in the mesh. Array should
be sized as a single vector.
rng : 2 item list, optional
Range of mapper for scalars. Defaults to minimum and maximum of
scalars array. Example: [-1, 2]
stitle : string, optional
Scalar title. By default there is no scalar legend bar. Setting
this creates the legend bar and adds a title to it. To create a
bar with no title, use an empty string (i.e. '').
showedges : bool, optional
Shows the edges of a mesh. Does not apply to a wireframe
representation.
psize : float, optional
Point size. Applicable when style='points'. Default 5.0
opacity : float, optional
Opacity of mesh. Should be between 0 and 1. Default 1.0
linethick : float, optional
Thickness of lines. Only valid for wireframe and surface
representations. Default None.
flipscalars : bool, optional
Flip direction of colormap.
lighting : bool, optional
Enable or disable view direction lighting. Default False.
ncolors : int, optional
Number of colors to use when displaying scalars. Default
256.
interpolatebeforemap : bool, optional
Enabling makes for a smoother scalar display. Default
False
colormap : str, optional
Colormap string. See available matplotlib colormaps. Only
applicable for when displaying scalars. Defaults None
(rainbow). Requires matplotlib.
Returns
-------
actor: vtk.vtkActor
VTK actor of the mesh.
"""
if isinstance(mesh, np.ndarray):
mesh = vtki.PolyData(mesh)
style = "points"
# Convert the VTK data object to a vtki wrapped object if neccessary
if not is_vtki_obj(mesh):
mesh = wrap(mesh)
# set main values
self.mesh = mesh
self.mapper = vtk.vtkDataSetMapper()
self.mapper.SetInputData(self.mesh)
actor, prop = self.add_actor(self.mapper)
if is_vtki_obj(mesh):
self._update_bounds(mesh.GetBounds())
# Scalar formatting ===================================================
if scalars is not None:
# if scalars is a string, then get the first array found with that name
if isinstance(scalars, str):
tit = scalars
scalars = get_scalar(mesh, scalars)
if stitle is None:
stitle = tit
if not isinstance(scalars, np.ndarray):
scalars = np.asarray(scalars)
if scalars.ndim != 1:
scalars = scalars.ravel()
if scalars.dtype == np.bool:
scalars = scalars.astype(np.float)
# Scalar interpolation approach
if scalars.size == mesh.GetNumberOfPoints():
self.mesh._add_point_scalar(scalars, "", True)
self.mapper.SetScalarModeToUsePointData()
self.mapper.GetLookupTable().SetNumberOfTableValues(ncolors)
if interpolatebeforemap:
self.mapper.InterpolateScalarsBeforeMappingOn()
elif scalars.size == mesh.GetNumberOfCells():
self.mesh._add_cell_scalar(scalars, "", True)
self.mapper.SetScalarModeToUseCellData()
self.mapper.GetLookupTable().SetNumberOfTableValues(ncolors)
else:
_raise_not_matching(scalars, mesh)
# Set scalar range
if not rng:
rng = [np.nanmin(scalars), np.nanmax(scalars)]
elif isinstance(rng, float) or isinstance(rng, int):
rng = [-rng, rng]
if np.any(rng):
self.mapper.SetScalarRange(rng[0], rng[1])
# Flip if requested
table = self.mapper.GetLookupTable()
if colormap is not None:
try:
from matplotlib.cm import get_cmap
except ImportError:
raise Exception("colormap requires matplotlib")
cmap = get_cmap(colormap)
ctable = cmap(np.linspace(0, 1, ncolors)) * 255
ctable = ctable.astype(np.uint8)
if flipscalars:
ctable = np.ascontiguousarray(ctable[::-1])
table.SetTable(VN.numpy_to_vtk(ctable))
else: # no colormap specified
if flipscalars:
self.mapper.GetLookupTable().SetHueRange(0.0, 0.66667)
else:
self.mapper.GetLookupTable().SetHueRange(0.66667, 0.0)
else:
self.mapper.SetScalarModeToUseFieldData()
# select view style
if not style:
style = "surface"
style = style.lower()
if style == "wireframe":
prop.SetRepresentationToWireframe()
elif style == "points":
prop.SetRepresentationToPoints()
elif style == "surface":
prop.SetRepresentationToSurface()
else:
raise Exception(
"Invalid style. Must be one of the following:\n"
+ '\t"surface"\n'
+ '\t"wireframe"\n'
+ '\t"points"\n'
)
prop.SetPointSize(psize)
# edge display style
if showedges:
prop.EdgeVisibilityOn()
rgb_color = parse_color(color)
prop.SetColor(rgb_color)
prop.SetOpacity(opacity)
# legend label
if label:
assert isinstance(label, str), "Label must be a string"
self._labels.append([single_triangle(), label, rgb_color])
# lighting display style
if lighting is False:
prop.LightingOff()
# set line thickness
if linethick:
prop.SetLineWidth(linethick)
# Add scalar bar if available
if stitle is not None:
self.add_scalar_bar(stitle)
return actor
|
def add_mesh(
self,
mesh,
color=None,
style=None,
scalars=None,
rng=None,
stitle=None,
showedges=True,
psize=5.0,
opacity=1,
linethick=None,
flipscalars=False,
lighting=False,
ncolors=256,
interpolatebeforemap=False,
colormap=None,
label=None,
**kwargs,
):
"""
Adds a unstructured, structured, or surface mesh to the plotting object.
Also accepts a 3D numpy.ndarray
Parameters
----------
mesh : vtk unstructured, structured, polymesh, or 3D numpy.ndarray
A vtk unstructured, structured, or polymesh to plot.
color : string or 3 item list, optional, defaults to white
Either a string, rgb list, or hex color string. For example:
color='white'
color='w'
color=[1, 1, 1]
color='#FFFFFF'
Color will be overridden when scalars are input.
style : string, optional
Visualization style of the vtk mesh. One for the following:
style='surface'
style='wireframe'
style='points'
Defaults to 'surface'
scalars : numpy array, optional
Scalars used to "color" the mesh. Accepts an array equal to the
number of cells or the number of points in the mesh. Array should
be sized as a single vector.
rng : 2 item list, optional
Range of mapper for scalars. Defaults to minimum and maximum of
scalars array. Example: [-1, 2]
stitle : string, optional
Scalar title. By default there is no scalar legend bar. Setting
this creates the legend bar and adds a title to it. To create a
bar with no title, use an empty string (i.e. '').
showedges : bool, optional
Shows the edges of a mesh. Does not apply to a wireframe
representation.
psize : float, optional
Point size. Applicable when style='points'. Default 5.0
opacity : float, optional
Opacity of mesh. Should be between 0 and 1. Default 1.0
linethick : float, optional
Thickness of lines. Only valid for wireframe and surface
representations. Default None.
flipscalars : bool, optional
Flip direction of colormap.
lighting : bool, optional
Enable or disable view direction lighting. Default False.
ncolors : int, optional
Number of colors to use when displaying scalars. Default 256.
interpolatebeforemap : bool, optional
Enabling makes for a smoother scalar display. Default False
colormap : str, optional
Colormap string. See available matplotlib colormaps. Only applicable for
when displaying scalars. Defaults None (rainbow). Requires matplotlib.
Returns
-------
actor: vtk.vtkActor
VTK actor of the mesh.
"""
if isinstance(mesh, np.ndarray):
mesh = vtki.PolyData(mesh)
style = "points"
try:
if mesh._is_vtki:
pass
except:
# Convert the VTK data object to a vtki wrapped object
mesh = wrap(mesh)
# set main values
self.mesh = mesh
self.mapper = vtk.vtkDataSetMapper()
self.mapper.SetInputData(self.mesh)
actor, prop = self.add_actor(self.mapper)
self._update_bounds(mesh.GetBounds())
# Scalar formatting ===================================================
if scalars is not None:
# if scalars is a string, then get the first array found with that name
if isinstance(scalars, str):
tit = scalars
scalars = get_scalar(mesh, scalars)
if stitle is None:
stitle = tit
if not isinstance(scalars, np.ndarray):
scalars = np.asarray(scalars)
if scalars.ndim != 1:
scalars = scalars.ravel()
if scalars.dtype == np.bool:
scalars = scalars.astype(np.float)
# Scalar interpolation approach
if scalars.size == mesh.GetNumberOfPoints():
self.mesh._add_point_scalar(scalars, "", True)
self.mapper.SetScalarModeToUsePointData()
self.mapper.GetLookupTable().SetNumberOfTableValues(ncolors)
if interpolatebeforemap:
self.mapper.InterpolateScalarsBeforeMappingOn()
elif scalars.size == mesh.GetNumberOfCells():
self.mesh._add_cell_scalar(scalars, "", True)
self.mapper.SetScalarModeToUseCellData()
self.mapper.GetLookupTable().SetNumberOfTableValues(ncolors)
else:
_raise_not_matching(scalars, mesh)
# Set scalar range
if not rng:
rng = [np.nanmin(scalars), np.nanmax(scalars)]
elif isinstance(rng, float) or isinstance(rng, int):
rng = [-rng, rng]
if np.any(rng):
self.mapper.SetScalarRange(rng[0], rng[1])
# Flip if requested
table = self.mapper.GetLookupTable()
if colormap is not None:
try:
from matplotlib.cm import get_cmap
except ImportError:
raise Exception("colormap requires matplotlib")
cmap = get_cmap(colormap)
ctable = cmap(np.linspace(0, 1, ncolors)) * 255
ctable = ctable.astype(np.uint8)
if flipscalars:
ctable = np.ascontiguousarray(ctable[::-1])
table.SetTable(VN.numpy_to_vtk(ctable))
else: # no colormap specified
if flipscalars:
self.mapper.GetLookupTable().SetHueRange(0.0, 0.66667)
else:
self.mapper.GetLookupTable().SetHueRange(0.66667, 0.0)
else:
self.mapper.SetScalarModeToUseFieldData()
# select view style
if not style:
style = "surface"
style = style.lower()
if style == "wireframe":
prop.SetRepresentationToWireframe()
elif style == "points":
prop.SetRepresentationToPoints()
elif style == "surface":
prop.SetRepresentationToSurface()
else:
raise Exception(
"Invalid style. Must be one of the following:\n"
+ '\t"surface"\n'
+ '\t"wireframe"\n'
+ '\t"points"\n'
)
prop.SetPointSize(psize)
# edge display style
if showedges:
prop.EdgeVisibilityOn()
rgb_color = parse_color(color)
prop.SetColor(rgb_color)
prop.SetOpacity(opacity)
# legend label
if label:
assert isinstance(label, str), "Label must be a string"
self._labels.append([single_triangle(), label, rgb_color])
# lighting display style
if lighting is False:
prop.LightingOff()
# set line thickness
if linethick:
prop.SetLineWidth(linethick)
# Add scalar bar if available
if stitle is not None:
self.add_scalar_bar(stitle)
return actor
|
https://github.com/pyvista/pyvista/issues/1
|
Python 2.7.13 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:17:26) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
import pyansys
C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\pyansys\archive_reader.py:32: UserWarning: Unable to load vtk dependent modules
warnings.warn('Unable to load vtk dependent modules')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\pyansys\__init__.py", line 4, in <module>
from pyansys.binary_reader import *
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\pyansys\binary_reader.py", line 7, in <module>
import vtkInterface
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\vtkInterface\__init__.py", line 7, in <module>
from vtkInterface.polydata import PolyData
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\vtkInterface\polydata.py", line 22, in <module>
class PolyData(vtkPolyData, vtkInterface.Common):
ValueError: multiple inheritance is not allowed with VTK classes
|
ValueError
|
def _plot(
self,
title=None,
window_size=DEFAULT_WINDOW_SIZE,
interactive=True,
autoclose=True,
interactive_update=False,
full_screen=False,
):
"""
Creates plotting window
Parameters
----------
title : string, optional
Title of plotting window.
window_size : list, optional
Window size in pixels. Defaults to [1024, 768]
interactive : bool, optional
Enabled by default. Allows user to pan and move figure.
autoclose : bool, optional
Enabled by default. Exits plotting session when user closes the
window when interactive is True.
interactive_update: bool, optional
Disabled by default. Allows user to non-blocking draw,
user should call Update() in each iteration.
full_screen : bool, optional
Opens window in full screen. When enabled, ignores window_size.
Default False.
Returns
-------
cpos : list
List of camera position, focal point, and view up
"""
if title:
self.ren_win.SetWindowName(title)
# if full_screen:
if full_screen:
self.ren_win.SetFullScreen(True)
self.ren_win.BordersOn() # super buggy when disabled
else:
self.ren_win.SetSize(window_size[0], window_size[1])
# Render
log.debug("Rendering")
self.ren_win.Render()
if interactive and (not self.off_screen):
try: # interrupts will be caught here
log.debug("Starting iren")
self.iren.Initialize()
if not interactive_update:
self.iren.Start()
except KeyboardInterrupt:
log.debug("KeyboardInterrupt")
self.close()
raise KeyboardInterrupt
# Get camera position before closing
cpos = self.camera_position
if self.notebook:
# sanity check
try:
import IPython
except ImportError:
raise Exception("Install iPython to display image in a notebook")
img = PIL.Image.fromarray(self.screenshot())
disp = IPython.display.display(img)
if autoclose:
self.close()
if self.notebook:
return disp
return cpos
|
def _plot(
self,
title=None,
window_size=DEFAULT_WINDOW_SIZE,
interactive=True,
autoclose=True,
interactive_update=False,
full_screen=False,
):
"""
Creates plotting window
Parameters
----------
title : string, optional
Title of plotting window.
window_size : list, optional
Window size in pixels. Defaults to [1024, 768]
interactive : bool, optional
Enabled by default. Allows user to pan and move figure.
autoclose : bool, optional
Enabled by default. Exits plotting session when user closes the
window when interactive is True.
interactive_update: bool, optional
Disabled by default. Allows user to non-blocking draw,
user should call Update() in each iteration.
full_screen : bool, optional
Opens window in full screen. When enabled, ignores window_size.
Default False.
Returns
-------
cpos : list
List of camera position, focal point, and view up
"""
if title:
self.ren_win.SetWindowName(title)
# if full_screen:
if full_screen:
self.ren_win.SetFullScreen(True)
self.ren_win.BordersOn() # super buggy when disabled
else:
self.ren_win.SetSize(window_size[0], window_size[1])
# Render
log.debug("Rendering")
self.ren_win.Render()
if interactive and (not self.off_screen):
try: # interrupts will be caught here
log.debug("Starting iren")
self.iren.Initialize()
if not interactive_update:
self.iren.Start()
except KeyboardInterrupt:
log.debug("KeyboardInterrupt")
self.close()
raise KeyboardInterrupt
# Get camera position before closing
cpos = self.camera_position
if self.notebook:
try:
import IPython
except ImportError:
raise Exception("Install iPython to display image in a notebook")
img = self.screenshot()
disp = IPython.display.display(PIL.Image.fromarray(img))
if autoclose:
self.close()
if self.notebook:
return disp
return cpos
|
https://github.com/pyvista/pyvista/issues/1
|
Python 2.7.13 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:17:26) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
import pyansys
C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\pyansys\archive_reader.py:32: UserWarning: Unable to load vtk dependent modules
warnings.warn('Unable to load vtk dependent modules')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\pyansys\__init__.py", line 4, in <module>
from pyansys.binary_reader import *
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\pyansys\binary_reader.py", line 7, in <module>
import vtkInterface
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\vtkInterface\__init__.py", line 7, in <module>
from vtkInterface.polydata import PolyData
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\vtkInterface\polydata.py", line 22, in <module>
class PolyData(vtkPolyData, vtkInterface.Common):
ValueError: multiple inheritance is not allowed with VTK classes
|
ValueError
|
def process_gcov_data(data_fname, covdata, source_fname, options):
logger = Logger(options.verbose)
INPUT = open(data_fname, "r")
# Find the source file
firstline = INPUT.readline()
fname = guess_source_file_name(
firstline,
data_fname,
source_fname,
root_dir=options.root_dir,
starting_dir=options.starting_dir,
logger=logger,
)
logger.verbose_msg("Parsing coverage data for file {}", fname)
# Return if the filename does not match the filter
# Return if the filename matches the exclude pattern
filtered, excluded = apply_filter_include_exclude(
fname, options.filter, options.exclude, strip=options.root_filter
)
if filtered:
logger.verbose_msg(" Filtering coverage data for file {}", fname)
return
if excluded:
logger.verbose_msg(" Excluding coverage data for file {}", fname)
return
parser = GcovParser(fname, logger=logger)
parser.parse_all_lines(INPUT, options.exclude_unreachable_branches)
parser.update_coverage(covdata)
parser.check_unrecognized_lines()
parser.check_unclosed_exclusions()
INPUT.close()
|
def process_gcov_data(data_fname, covdata, source_fname, options):
logger = Logger(options.verbose)
INPUT = open(data_fname, "r")
# Find the source file
firstline = INPUT.readline()
fname = guess_source_file_name(
firstline,
data_fname,
source_fname,
root_dir=options.root_dir,
starting_dir=options.starting_dir,
logger=logger,
)
logger.verbose_msg("Parsing coverage data for file {}", fname)
# Return if the filename does not match the filter
# Return if the filename matches the exclude pattern
filtered, excluded = apply_filter_include_exclude(
fname, options.filter, options.exclude, strip=options.root_filter
)
if filtered:
logger.verbose_msg(" Filtering coverage data for file {}", fname)
return
if excluded:
logger.verbose_msg(" Excluding coverage data for file {}", fname)
return
parser = GcovParser(fname, logger=logger)
for line in INPUT:
parser.parse_line(line, options.exclude_unreachable_branches)
parser.update_coverage(covdata)
parser.check_unclosed_exclusions()
INPUT.close()
|
https://github.com/gcovr/gcovr/issues/226
|
Traceback (most recent call last):
File "/usr/local/bin/gcovr", line 2412, in <module>
process_datafile(file_, covdata, options)
File "/usr/local/bin/gcovr", line 884, in process_datafile
process_gcov_data(fname, covdata, abs_filename, options)
File "/usr/local/bin/gcovr", line 616, in process_gcov_data
covered[lineno] = int(segments[0].strip())
ValueError: invalid literal for int() with base 10: '1*'
|
ValueError
|
def __init__(self, fname, logger):
self.logger = logger
self.excluding = []
self.noncode = set()
self.uncovered = set()
self.uncovered_exceptional = set()
self.covered = dict()
self.branches = dict()
# self.first_record = True
self.fname = fname
self.lineno = 0
self.last_code_line = ""
self.last_code_lineno = 0
self.last_code_line_excluded = False
self.unrecognized_lines = []
self.deferred_exceptions = []
self.last_was_specialization_section_marker = False
|
def __init__(self, fname, logger):
self.logger = logger
self.excluding = []
self.noncode = set()
self.uncovered = set()
self.uncovered_exceptional = set()
self.covered = dict()
self.branches = dict()
# self.first_record = True
self.fname = fname
self.lineno = 0
self.last_code_line = ""
self.last_code_lineno = 0
self.last_code_line_excluded = False
|
https://github.com/gcovr/gcovr/issues/226
|
Traceback (most recent call last):
File "/usr/local/bin/gcovr", line 2412, in <module>
process_datafile(file_, covdata, options)
File "/usr/local/bin/gcovr", line 884, in process_datafile
process_gcov_data(fname, covdata, abs_filename, options)
File "/usr/local/bin/gcovr", line 616, in process_gcov_data
covered[lineno] = int(segments[0].strip())
ValueError: invalid literal for int() with base 10: '1*'
|
ValueError
|
def parse_line(self, line, exclude_unreachable_branches):
# If this is a tag line, we stay on the same line number
# and can return immediately after processing it.
# A tag line cannot hold exclusion markers.
if self.parse_tag_line(line, exclude_unreachable_branches):
return
# If this isn't a tag line, this is metadata or source code.
# e.g. " -: 0:Data:foo.gcda" (metadata)
# or " 3: 7: c += 1" (source code)
segments = line.split(":", 2)
if len(segments) > 1:
try:
self.lineno = int(segments[1].strip())
except ValueError:
pass # keep previous line number!
if exclude_line_flag in line:
excl_line = False
for header, flag in exclude_line_pattern.findall(line):
if self.parse_exclusion_marker(header, flag):
excl_line = True
# We buffer the line exclusion so that it is always
# the last thing added to the exclusion list (and so
# only ONE is ever added to the list). This guards
# against cases where puts a _LINE and _START (or
# _STOP) on the same line... it also guards against
# duplicate _LINE flags.
if excl_line:
self.excluding.append(False)
status = segments[0].strip()
code = segments[2] if 2 < len(segments) else ""
is_code_statement = self.parse_code_line(status, code)
if not is_code_statement:
self.unrecognized_lines.append(line)
# save the code line to use it later with branches
if is_code_statement:
self.last_code_line = "".join(segments[2:])
self.last_code_lineno = self.lineno
self.last_code_line_excluded = bool(self.excluding)
# clear the excluding flag for single-line excludes
if self.excluding and not self.excluding[-1]:
self.excluding.pop()
|
def parse_line(self, line, exclude_unreachable_branches):
# If this is a tag line, we stay on the same line number
# and can return immediately after processing it.
# A tag line cannot hold exclusion markers.
if self.parse_tag_line(line, exclude_unreachable_branches):
return
# If this isn't a tag line, this is metadata or source code.
# e.g. " -: 0:Data:foo.gcda" (metadata)
# or " 3: 7: c += 1" (source code)
segments = line.split(":", 2)
if len(segments) > 1:
try:
self.lineno = int(segments[1].strip())
except ValueError:
pass # keep previous line number!
if exclude_line_flag in line:
excl_line = False
for header, flag in exclude_line_pattern.findall(line):
if self.parse_exclusion_marker(header, flag):
excl_line = True
# We buffer the line exclusion so that it is always
# the last thing added to the exclusion list (and so
# only ONE is ever added to the list). This guards
# against cases where puts a _LINE and _START (or
# _STOP) on the same line... it also guards against
# duplicate _LINE flags.
if excl_line:
self.excluding.append(False)
status = segments[0].strip()
code = segments[2] if 2 < len(segments) else ""
is_code_statement = self.parse_code_line(status, code)
if not is_code_statement:
self.logger.verbose_msg(
"Unrecognized GCOV output: {line}\n"
"\tThis is indicitive of a gcov output parse error.\n"
"\tPlease report this to the gcovr developers.",
line=line,
)
# save the code line to use it later with branches
if is_code_statement:
self.last_code_line = "".join(segments[2:])
self.last_code_lineno = self.lineno
self.last_code_line_excluded = bool(self.excluding)
# clear the excluding flag for single-line excludes
if self.excluding and not self.excluding[-1]:
self.excluding.pop()
|
https://github.com/gcovr/gcovr/issues/226
|
Traceback (most recent call last):
File "/usr/local/bin/gcovr", line 2412, in <module>
process_datafile(file_, covdata, options)
File "/usr/local/bin/gcovr", line 884, in process_datafile
process_gcov_data(fname, covdata, abs_filename, options)
File "/usr/local/bin/gcovr", line 616, in process_gcov_data
covered[lineno] = int(segments[0].strip())
ValueError: invalid literal for int() with base 10: '1*'
|
ValueError
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.