id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
16,100
|
plugin_info_test.py
|
errbotio_errbot/tests/plugin_info_test.py
|
import sys
from io import StringIO
from pathlib import Path
import pytest
from errbot.plugin_info import PluginInfo
plugfile_base = Path(__file__).absolute().parent / "config_plugin"
plugfile_path = plugfile_base / "config.plug"
def test_load_from_plugfile_path():
pi = PluginInfo.load(plugfile_path)
assert pi.name == "Config"
assert pi.module == "config"
assert pi.doc is None
assert pi.python_version == (3, 0, 0)
assert pi.errbot_minversion is None
assert pi.errbot_maxversion is None
@pytest.mark.parametrize(
"test_input,expected",
[
("2", (2, 0, 0)),
("2+", (3, 0, 0)),
("3", (3, 0, 0)),
("1.2.3", (1, 2, 3)),
("1.2.3-beta", (1, 2, 3)),
],
)
def test_python_version_parse(test_input, expected):
f = StringIO(
"""
[Core]
Name = Config
Module = config
[Python]
Version = %s
"""
% test_input
)
assert PluginInfo.load_file(f, None).python_version == expected
def test_doc():
f = StringIO(
"""
[Core]
Name = Config
Module = config
[Documentation]
Description = something
"""
)
assert PluginInfo.load_file(f, None).doc == "something"
def test_errbot_version():
f = StringIO(
"""
[Core]
Name = Config
Module = config
[Errbot]
Min = 1.2.3
Max = 4.5.6-beta
"""
)
info = PluginInfo.load_file(f, None)
assert info.errbot_minversion == (1, 2, 3, sys.maxsize)
assert info.errbot_maxversion == (4, 5, 6, 0)
| 1,547
|
Python
|
.py
| 62
| 19.967742
| 67
| 0.598639
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,101
|
utils_test.py
|
errbotio_errbot/tests/utils_test.py
|
# coding=utf-8
import logging
import sys
from datetime import timedelta
import pytest
from errbot.backend_plugin_manager import BackendPluginManager
from errbot.backends.test import ShallowConfig
from errbot.bootstrap import CORE_STORAGE, bot_config_defaults
from errbot.storage import StoreMixin
from errbot.storage.base import StoragePluginBase
from errbot.utils import version2tuple, format_timedelta, split_string_after
log = logging.getLogger(__name__)
@pytest.mark.parametrize(
"v1,v2",
[
("2.0.0", "2.0.1"),
("2.0.0", "2.1.0"),
("2.0.0", "3.0.0"),
("2.0.0-alpha", "2.0.0-beta"),
("2.0.0-beta", "2.0.0-rc1"),
("2.0.0-rc1", "2.0.0-rc2"),
("2.0.0-rc2", "2.0.0-rc3"),
("2.0.0-rc2", "2.0.0"),
("2.0.0-beta", "2.0.1"),
],
)
def test_version_check(v1, v2):
assert version2tuple(v1) < version2tuple(v2)
@pytest.mark.parametrize(
"version",
[
"1.2.3.4",
"1.2",
"1.2.-beta",
"1.2.3-toto",
"1.2.3-rc",
],
)
def test_version_check_negative(version):
with pytest.raises(ValueError):
version2tuple(version)
def test_formattimedelta():
td = timedelta(0, 60 * 60 + 13 * 60)
assert "1 hours and 13 minutes" == format_timedelta(td)
def test_storage():
key = "test"
__import__("errbot.config-template")
config = ShallowConfig()
config.__dict__.update(sys.modules["errbot.config-template"].__dict__)
bot_config_defaults(config)
spm = BackendPluginManager(
config, "errbot.storage", "Memory", StoragePluginBase, CORE_STORAGE
)
storage_plugin = spm.load_plugin()
persistent_object = StoreMixin()
persistent_object.open_storage(storage_plugin, "test")
persistent_object[key] = "à value"
assert persistent_object[key] == "à value"
assert key in persistent_object
del persistent_object[key]
assert key not in persistent_object
assert len(persistent_object) == 0
def test_split_string_after_returns_original_string_when_chunksize_equals_string_size():
str_ = "foobar2000" * 2
splitter = split_string_after(str_, len(str_))
split = [chunk for chunk in splitter]
assert [str_] == split
def test_split_string_after_returns_original_string_when_chunksize_equals_string_size_plus_one():
str_ = "foobar2000" * 2
splitter = split_string_after(str_, len(str_) + 1)
split = [chunk for chunk in splitter]
assert [str_] == split
def test_split_string_after_returns_two_chunks_when_chunksize_equals_string_size_minus_one():
str_ = "foobar2000" * 2
splitter = split_string_after(str_, len(str_) - 1)
split = [chunk for chunk in splitter]
assert ["foobar2000foobar200", "0"] == split
def test_split_string_after_returns_two_chunks_when_chunksize_equals_half_length_of_string():
str_ = "foobar2000" * 2
splitter = split_string_after(str_, int(len(str_) / 2))
split = [chunk for chunk in splitter]
assert ["foobar2000", "foobar2000"] == split
| 3,029
|
Python
|
.py
| 82
| 32.02439
| 97
| 0.666324
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,102
|
commands_test.py
|
errbotio_errbot/tests/commands_test.py
|
# coding=utf-8
import logging
import os
import re
import tarfile
from os import mkdir, path
from queue import Empty
from shutil import rmtree
from tempfile import mkdtemp
from unittest.mock import MagicMock
import pytest
extra_plugin_dir = path.join(path.dirname(path.realpath(__file__)), "dummy_plugin")
def test_root_help(testbot):
assert "All commands" in testbot.exec_command("!help")
def test_help(testbot):
assert "!about" in testbot.exec_command("!help Help")
assert "That command is not defined." in testbot.exec_command("!help beurk")
# Ensure that help reports on re_commands.
assert "runs foo" in testbot.exec_command("!help foo") # Part of Dummy
assert "runs re_foo" in testbot.exec_command("!help re_foo") # Part of Dummy
assert "runs re_foo" in testbot.exec_command("!help re foo") # Part of Dummy
def test_about(testbot):
assert "Errbot version" in testbot.exec_command("!about")
def test_uptime(testbot):
assert "I've been up for" in testbot.exec_command("!uptime")
def test_status(testbot):
assert "Yes I am alive" in testbot.exec_command("!status")
def test_status_plugins(testbot):
assert "A = Activated, D = Deactivated" in testbot.exec_command("!status plugins")
def test_status_load(testbot):
assert "Load " in testbot.exec_command("!status load")
def test_whoami(testbot):
assert "person" in testbot.exec_command("!whoami")
assert "gbin@localhost" in testbot.exec_command("!whoami")
def test_echo(testbot):
assert "foo" in testbot.exec_command("!echo foo")
def test_status_gc(testbot):
assert "GC 0->" in testbot.exec_command("!status gc")
def test_config_cycle(testbot):
testbot.push_message("!plugin config Webserver")
m = testbot.pop_message()
assert (
"Default configuration for this plugin (you can copy and paste this directly as a command)"
in m
)
assert "Current configuration" not in m
testbot.assertInCommand(
"!plugin config Webserver {'HOST': 'localhost', 'PORT': 3141, 'SSL': None}",
"Plugin configuration done.",
)
assert "Current configuration" in testbot.exec_command("!plugin config Webserver")
assert "localhost" in testbot.exec_command("!plugin config Webserver")
def test_apropos(testbot):
assert "!about: Return information about" in testbot.exec_command("!apropos about")
def test_logtail(testbot):
assert "DEBUG" in testbot.exec_command("!log tail")
def test_history(testbot):
assert "up" in testbot.exec_command("!uptime")
assert "uptime" in testbot.exec_command("!history")
orig_sender = testbot.bot.sender
# Pretend to be someone else. History should be empty
testbot.bot.sender = testbot.bot.build_identifier("non_default_person")
testbot.push_message("!history")
with pytest.raises(Empty):
testbot.pop_message(timeout=1)
assert "should be a separate history" in testbot.exec_command(
"!echo should be a separate history"
)
assert "should be a separate history" in testbot.exec_command("!history")
testbot.bot.sender = orig_sender
# Pretend to be the original person again. History should still contain uptime
assert "uptime" in testbot.exec_command("!history")
def test_plugin_cycle(testbot):
plugins = [
"errbotio/err-helloworld",
]
for plugin in plugins:
testbot.assertInCommand(f"!repos install {plugin}", f"Installing {plugin}..."),
assert (
"A new plugin repository has been installed correctly from errbotio/err-helloworld"
in testbot.pop_message(timeout=60)
)
assert "Plugins reloaded" in testbot.pop_message()
assert "this command says hello" in testbot.exec_command("!help hello")
assert "Hello World !" in testbot.exec_command("!hello")
testbot.push_message("!plugin reload HelloWorld")
assert "Plugin HelloWorld reloaded." == testbot.pop_message()
testbot.push_message("!hello") # should still respond
assert "Hello World !" == testbot.pop_message()
testbot.push_message("!plugin blacklist HelloWorld")
assert "Plugin HelloWorld is now blacklisted." == testbot.pop_message()
testbot.push_message("!plugin deactivate HelloWorld")
assert "HelloWorld is already deactivated." == testbot.pop_message()
testbot.push_message("!hello") # should not respond
assert 'Command "hello" not found' in testbot.pop_message()
testbot.push_message("!plugin unblacklist HelloWorld")
assert "Plugin HelloWorld removed from blacklist." == testbot.pop_message()
testbot.push_message("!plugin activate HelloWorld")
assert "HelloWorld is already activated." == testbot.pop_message()
testbot.push_message("!hello") # should respond back
assert "Hello World !" == testbot.pop_message()
testbot.push_message("!repos uninstall errbotio/err-helloworld")
assert "Repo errbotio/err-helloworld removed." == testbot.pop_message()
testbot.push_message("!hello") # should not respond
assert 'Command "hello" not found' in testbot.pop_message()
def test_broken_plugin(testbot):
borken_plugin_dir = path.join(
path.dirname(path.realpath(__file__)), "borken_plugin"
)
try:
tempd = mkdtemp()
tgz = os.path.join(tempd, "borken.tar.gz")
with tarfile.open(tgz, "w:gz") as tar:
tar.add(borken_plugin_dir, arcname="borken")
assert "Installing" in testbot.exec_command(
"!repos install file://" + tgz, timeout=120
)
assert "import borken # fails" in testbot.pop_message()
assert "as it did not load correctly." in testbot.pop_message()
assert (
"Error: Broken failed to activate: "
"'NoneType' object has no attribute 'is_activated'"
) in testbot.pop_message()
assert "Plugins reloaded." in testbot.pop_message()
finally:
rmtree(tempd)
def test_backup(testbot):
bot = testbot.bot # used while restoring
bot.push_message("!repos install https://github.com/errbotio/err-helloworld.git")
assert "Installing" in testbot.pop_message()
assert "err-helloworld" in testbot.pop_message(timeout=60)
assert "reload" in testbot.pop_message()
bot.push_message("!backup")
msg = testbot.pop_message()
assert "has been written in" in msg
filename = re.search(r'"(.*)"', msg).group(1)
# At least the backup should mention the installed plugin
assert "errbotio/err-helloworld" in open(filename).read()
# Now try to clean the bot and restore
for p in testbot.bot.plugin_manager.get_all_active_plugins():
p.close_storage()
assert "Plugin HelloWorld deactivated." in testbot.exec_command(
"!plugin deactivate HelloWorld"
)
plugins_dir = path.join(testbot.bot_config.BOT_DATA_DIR, "plugins")
bot.repo_manager["installed_repos"] = {}
bot.plugin_manager["configs"] = {}
rmtree(plugins_dir)
mkdir(plugins_dir)
from errbot.bootstrap import restore_bot_from_backup
log = logging.getLogger(__name__) # noqa
restore_bot_from_backup(filename, bot=bot, log=log)
assert "Plugin HelloWorld activated." in testbot.exec_command(
"!plugin activate HelloWorld"
)
assert "Hello World !" in testbot.exec_command("!hello")
testbot.push_message("!repos uninstall errbotio/err-helloworld")
def test_encoding_preservation(testbot):
testbot.push_message("!echo へようこそ")
assert "へようこそ" == testbot.pop_message()
def test_webserver_webhook_test(testbot):
testbot.push_message(
"!plugin config Webserver {'HOST': 'localhost', 'PORT': 3141, 'SSL': None}"
)
assert "Plugin configuration done." in testbot.pop_message()
testbot.assertInCommand("!webhook test /echo toto", "Status code: 200")
def test_activate_reload_and_deactivate(testbot):
for command in ("activate", "reload", "deactivate"):
testbot.push_message(f"!plugin {command}")
m = testbot.pop_message()
assert "Please tell me which of the following plugins to" in m
assert "ChatRoom" in m
testbot.push_message(f"!plugin {command} nosuchplugin")
m = testbot.pop_message()
assert "nosuchplugin isn't a valid plugin name. The current plugins are" in m
assert "ChatRoom" in m
testbot.push_message("!plugin reload ChatRoom")
assert "Plugin ChatRoom reloaded." == testbot.pop_message()
testbot.push_message("!status plugins")
assert "A │ ChatRoom" in testbot.pop_message()
testbot.push_message("!plugin deactivate ChatRoom")
assert "Plugin ChatRoom deactivated." == testbot.pop_message()
testbot.push_message("!status plugins")
assert "D │ ChatRoom" in testbot.pop_message()
testbot.push_message("!plugin deactivate ChatRoom")
assert "ChatRoom is already deactivated." in testbot.pop_message()
testbot.push_message("!plugin activate ChatRoom")
assert "Plugin ChatRoom activated." in testbot.pop_message()
testbot.push_message("!status plugins")
assert "A │ ChatRoom" in testbot.pop_message()
testbot.push_message("!plugin activate ChatRoom")
assert "ChatRoom is already activated." == testbot.pop_message()
testbot.push_message("!plugin deactivate ChatRoom")
assert "Plugin ChatRoom deactivated." == testbot.pop_message()
testbot.push_message("!plugin reload ChatRoom")
assert (
"Warning: plugin ChatRoom is currently not activated. Use !plugin activate ChatRoom to activate it."
== testbot.pop_message()
)
assert "Plugin ChatRoom reloaded." == testbot.pop_message()
testbot.push_message("!plugin blacklist ChatRoom")
assert "Plugin ChatRoom is now blacklisted." == testbot.pop_message()
testbot.push_message("!status plugins")
assert "B,D │ ChatRoom" in testbot.pop_message()
# Needed else configuration for this plugin gets saved which screws up
# other tests
testbot.push_message("!plugin unblacklist ChatRoom")
testbot.pop_message()
def test_unblacklist_and_blacklist(testbot):
testbot.push_message("!plugin unblacklist nosuchplugin")
m = testbot.pop_message()
assert "nosuchplugin isn't a valid plugin name. The current plugins are" in m
assert "ChatRoom" in m
testbot.push_message("!plugin blacklist nosuchplugin")
m = testbot.pop_message()
assert "nosuchplugin isn't a valid plugin name. The current plugins are" in m
assert "ChatRoom" in m
testbot.push_message("!plugin blacklist ChatRoom")
assert "Plugin ChatRoom is now blacklisted" in testbot.pop_message()
testbot.push_message("!plugin blacklist ChatRoom")
assert "Plugin ChatRoom is already blacklisted." == testbot.pop_message()
testbot.push_message("!status plugins")
assert "B,D │ ChatRoom" in testbot.pop_message()
testbot.push_message("!plugin unblacklist ChatRoom")
assert "Plugin ChatRoom removed from blacklist." == testbot.pop_message()
testbot.push_message("!plugin unblacklist ChatRoom")
assert "Plugin ChatRoom is not blacklisted." == testbot.pop_message()
testbot.push_message("!status plugins")
assert "A │ ChatRoom" in testbot.pop_message()
def test_optional_prefix(testbot):
testbot.bot_config.BOT_PREFIX_OPTIONAL_ON_CHAT = False
assert "Yes I am alive" in testbot.exec_command("!status")
testbot.bot_config.BOT_PREFIX_OPTIONAL_ON_CHAT = True
assert "Yes I am alive" in testbot.exec_command("!status")
assert "Yes I am alive" in testbot.exec_command("status")
def test_optional_prefix_re_cmd(testbot):
testbot.bot_config.BOT_PREFIX_OPTIONAL_ON_CHAT = False
assert "bar" in testbot.exec_command("!plz dont match this")
testbot.bot_config.BOT_PREFIX_OPTIONAL_ON_CHAT = True
assert "bar" in testbot.exec_command("!plz dont match this")
assert "bar" in testbot.exec_command("plz dont match this")
def test_simple_match(testbot):
assert "bar" in testbot.exec_command("match this")
def test_no_suggest_on_re_commands(testbot):
testbot.push_message("!re_ba")
# Don't suggest a regexp command.
assert "!re bar" not in testbot.pop_message()
def test_callback_no_command(testbot):
extra_plugin_dir = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "commandnotfound_plugin"
)
cmd = "!this_is_not_a_real_command_at_all"
expected_str = f"Command fell through: {cmd}"
testbot.exec_command("!plugin deactivate CommandNotFoundFilter")
testbot.bot.plugin_manager._extra_plugin_dir = extra_plugin_dir
testbot.bot.plugin_manager.update_plugin_places([])
testbot.exec_command("!plugin activate TestCommandNotFoundFilter")
assert expected_str == testbot.exec_command(cmd)
def test_subcommands(testbot):
# test single subcommand (method is run_subcommands())
cmd = "!run subcommands with these args"
cmd_underscore = "!run_subcommands with these args"
expected_args = "with these args"
assert expected_args == testbot.exec_command(cmd)
assert expected_args == testbot.exec_command(cmd_underscore)
# test multiple subcmomands (method is run_lots_of_subcommands())
cmd = "!run lots of subcommands with these args"
cmd_underscore = "!run_lots_of_subcommands with these args"
assert expected_args == testbot.exec_command(cmd)
assert expected_args == testbot.exec_command(cmd_underscore)
def test_command_not_found_with_space_in_bot_prefix(testbot):
testbot.bot_config.BOT_PREFIX = "! "
assert 'Command "blah" not found.' in testbot.exec_command("! blah")
assert 'Command "blah" / "blah toto" not found.' in testbot.exec_command(
"! blah toto"
)
def test_mock_injection(testbot):
helper_mock = MagicMock()
helper_mock.return_value = "foo"
mock_dict = {"helper_method": helper_mock}
testbot.inject_mocks("Dummy", mock_dict)
assert "foo" in testbot.exec_command("!baz")
def test_multiline_command(testbot):
testbot.assertInCommand(
"""
!bar title
first line of body
second line of body
""",
"!bar title\nfirst line of body\nsecond line of body",
dedent=True,
)
def test_plugin_info_command(testbot):
output = testbot.exec_command("!plugin info Help")
assert "name: Help" in output
assert "module: help" in output
assert "help.py" in output
assert "log level: NOTSET" in output
| 14,579
|
Python
|
.py
| 298
| 42.949664
| 108
| 0.702383
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,103
|
syntax_test.py
|
errbotio_errbot/tests/syntax_test.py
|
from os import path
extra_plugin_dir = path.join(path.dirname(path.realpath(__file__)), "syntax_plugin")
def test_nosyntax(testbot):
assert testbot.bot.commands["foo_nosyntax"]._err_command_syntax is None
def test_syntax(testbot):
assert testbot.bot.commands["foo"]._err_command_syntax == "[optional] <mandatory>"
def test_re_syntax(testbot):
assert testbot.bot.re_commands["re_foo"]._err_command_syntax == ".*"
def test_arg_syntax(testbot):
assert (
testbot.bot.commands["arg_foo"]._err_command_syntax
== "[-h] [--repeat-count REPEAT] value"
)
| 590
|
Python
|
.py
| 13
| 40.923077
| 86
| 0.698944
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,104
|
plugin_config_fail_test.py
|
errbotio_errbot/tests/plugin_config_fail_test.py
|
from os import path
extra_plugin_dir = path.join(
path.dirname(path.realpath(__file__)), "fail_config_plugin"
)
def test_failed_config(testbot):
assert (
"Incorrect plugin configuration: Message explaining why it failed."
in testbot.exec_command("!plugin config Failp {}")
)
| 306
|
Python
|
.py
| 9
| 29.555556
| 75
| 0.70068
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,105
|
md_rendering_test.py
|
errbotio_errbot/tests/md_rendering_test.py
|
# vim: ts=4:sw=4
import logging
from errbot import rendering
log = logging.getLogger(__name__)
def test_ansi():
mdc = rendering.ansi()
assert mdc.convert("*woot*") == "\x1b[4mwoot\x1b[24m\x1b[0m"
def test_text():
mdc = rendering.text()
assert mdc.convert("*woot*") == "woot"
assert mdc.convert("# woot") == "WOOT"
def test_mde2md():
mdc = rendering.md()
assert mdc.convert("woot") == "woot"
assert mdc.convert("woot{:stuff} really{:otherstuff}") == "woot really"
def test_escaping():
mdc = rendering.text()
original = "#not a title\n*not italic*\n`not code`\ntoto{not annotation}"
escaped = rendering.md_escape(original)
assert original == mdc.convert(escaped)
| 719
|
Python
|
.py
| 20
| 32.05
| 77
| 0.669086
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,106
|
matchall_test.py
|
errbotio_errbot/tests/matchall_test.py
|
# coding=utf-8
from os import path
extra_plugin_dir = path.join(path.dirname(path.realpath(__file__)), "matchall_plugin")
def test_botmatch_correct(testbot):
assert "Works!" in testbot.exec_command("hi hi hi")
def test_botmatch(testbot):
assert "Works!" in testbot.exec_command("123123")
| 301
|
Python
|
.py
| 7
| 40.142857
| 86
| 0.740484
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,107
|
circular_dependencies_test.py
|
errbotio_errbot/tests/circular_dependencies_test.py
|
import os
extra_plugin_dir = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "circular_dependent_plugins"
)
pytest_plugins = ["errbot.backends.test"]
def test_if_all_loaded_circular_dependencies(testbot):
"""https://github.com/errbotio/errbot/issues/1397"""
plug_names = testbot.bot.plugin_manager.get_all_active_plugin_names()
assert "PluginA" in plug_names
assert "PluginB" in plug_names
assert "PluginC" in plug_names
| 459
|
Python
|
.py
| 11
| 38.272727
| 77
| 0.737079
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,108
|
i18n_test.py
|
errbotio_errbot/tests/i18n_test.py
|
# -*- coding=utf-8 -*-
from os import path
# This is to test end2end i18n behavior.
extra_plugin_dir = path.join(path.dirname(path.realpath(__file__)), "i18n_plugin")
def test_i18n_return(testbot):
assert "язы́к" in testbot.exec_command("!i18n 1")
def test_i18n_simple_name(testbot):
assert "OK" in testbot.exec_command("!ру́сский")
def test_i18n_prefix(testbot):
assert "OK" in testbot.exec_command("!prefix_ру́сский")
assert "OK" in testbot.exec_command("!prefix ру́сский")
def test_i18n_suffix(testbot):
assert "OK" in testbot.exec_command("!ру́сский_suffix")
assert "OK" in testbot.exec_command("!ру́сский suffix")
| 698
|
Python
|
.py
| 14
| 43.214286
| 82
| 0.715421
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,109
|
streaming_test.py
|
errbotio_errbot/tests/streaming_test.py
|
from io import BytesIO
from errbot.backends.base import Stream
from errbot.backends.test import TestPerson
from errbot.streaming import Tee
class StreamingClient(object):
def callback_stream(self, stream):
self.response = stream.read()
def test_streaming():
canary = b"this is my test" * 1000
source = Stream(TestPerson("gbin@gootz.net"), BytesIO(canary))
clients = [StreamingClient() for _ in range(50)]
Tee(source, clients).run()
for client in clients:
assert client.response == canary
| 533
|
Python
|
.py
| 14
| 33.857143
| 66
| 0.733463
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,110
|
cascade_dependencies_test.py
|
errbotio_errbot/tests/cascade_dependencies_test.py
|
import os
import pathlib
from unittest import mock
import pytest
extra_plugin_dir = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "cascade_dependent_plugins"
)
orig_path_glob = pathlib.Path.glob
def reordered_plugin_files(self, pattern):
if self.name == "cascade_dependent_plugins":
yield pathlib.Path(extra_plugin_dir + "/parent2.plug")
yield pathlib.Path(extra_plugin_dir + "/child1.plug")
yield pathlib.Path(extra_plugin_dir + "/child2.plug")
yield pathlib.Path(extra_plugin_dir + "/parent1.plug")
return
yield from orig_path_glob(self, pattern)
@pytest.fixture
def mock_before_bot_load():
patcher = mock.patch.object(pathlib.Path, "glob", reordered_plugin_files)
patcher.start()
yield
patcher.stop()
def test_dependency_commands(mock_before_bot_load, testbot):
assert "Hello from Child1" in testbot.exec_command("!parent1 to child1")
assert "Hello from Child2" in testbot.exec_command("!parent1 to child2")
assert "Hello from Parent1" in testbot.exec_command("!parent2 to parent1")
| 1,088
|
Python
|
.py
| 26
| 37.423077
| 78
| 0.725546
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,111
|
mention_test.py
|
errbotio_errbot/tests/mention_test.py
|
from os import path
extra_plugin_dir = path.join(path.dirname(path.realpath(__file__)), "mention_plugin")
def test_foreign_mention(testbot):
assert "Somebody mentioned toto!" in testbot.exec_command(
"I am telling you something @toto"
)
def test_testbot_mention(testbot):
assert "Somebody mentioned me!" in testbot.exec_command(
"I am telling you something @Err"
)
def test_multiple_mentions(testbot):
assert "Somebody mentioned toto,titi!" in testbot.exec_command(
"I am telling you something @toto and @titi"
)
| 568
|
Python
|
.py
| 14
| 35.642857
| 85
| 0.714808
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,112
|
config-ci.py
|
errbotio_errbot/tests/config-ci.py
|
# config for continus integration testing.
# Don't use this for sensible defaults
import logging
BOT_DATA_DIR = "/tmp"
BOT_EXTRA_PLUGIN_DIR = None
AUTOINSTALL_DEPS = True
BOT_LOG_FILE = "/tmp/err.log"
BOT_LOG_LEVEL = logging.DEBUG
BOT_LOG_SENTRY = False
SENTRY_DSN = ""
SENTRY_LOGLEVEL = BOT_LOG_LEVEL
BOT_ASYNC = True
BOT_IDENTITY = {
"username": "err@localhost",
"password": "changeme",
}
BOT_ADMINS = ("gbin@localhost",)
CHATROOM_PRESENCE = ()
CHATROOM_FN = "Err"
BOT_PREFIX = "!"
DIVERT_TO_PRIVATE = ()
CHATROOM_RELAY = {}
REVERSE_CHATROOM_RELAY = {}
| 565
|
Python
|
.py
| 23
| 23.130435
| 42
| 0.724074
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,113
|
plugin_config_test.py
|
errbotio_errbot/tests/plugin_config_test.py
|
from os import path
import pytest
from errbot.botplugin import ValidationException, recurse_check_structure
extra_plugin_dir = path.join(path.dirname(path.realpath(__file__)), "config_plugin")
def test_recurse_check_structure_valid():
sample = dict(
string="Foobar",
list=["Foo", "Bar"],
dict={"foo": "Bar"},
none=None,
true=True,
false=False,
)
to_check = dict(
string="Foobar",
list=["Foo", "Bar", "Bas"],
dict={"foo": "Bar"},
none=None,
true=True,
false=False,
)
recurse_check_structure(sample, to_check)
def test_recurse_check_structure_missingitem():
sample = dict(
string="Foobar",
list=["Foo", "Bar"],
dict={"foo": "Bar"},
none=None,
true=True,
false=False,
)
to_check = dict(
string="Foobar", list=["Foo", "Bar"], dict={"foo": "Bar"}, none=None, true=True
)
with pytest.raises(ValidationException):
recurse_check_structure(sample, to_check)
def test_recurse_check_structure_extrasubitem():
sample = dict(
string="Foobar",
list=["Foo", "Bar"],
dict={"foo": "Bar"},
none=None,
true=True,
false=False,
)
to_check = dict(
string="Foobar",
list=["Foo", "Bar", "Bas"],
dict={"foo": "Bar", "Bar": "Foo"},
none=None,
true=True,
false=False,
)
with pytest.raises(ValidationException):
recurse_check_structure(sample, to_check)
def test_recurse_check_structure_missingsubitem():
sample = dict(
string="Foobar",
list=["Foo", "Bar"],
dict={"foo": "Bar"},
none=None,
true=True,
false=False,
)
to_check = dict(
string="Foobar",
list=["Foo", "Bar", "Bas"],
dict={},
none=None,
true=True,
false=False,
)
with pytest.raises(ValidationException):
recurse_check_structure(sample, to_check)
def test_recurse_check_structure_wrongtype_1():
sample = dict(
string="Foobar",
list=["Foo", "Bar"],
dict={"foo": "Bar"},
none=None,
true=True,
false=False,
)
to_check = dict(
string=None,
list=["Foo", "Bar"],
dict={"foo": "Bar"},
none=None,
true=True,
false=False,
)
with pytest.raises(ValidationException):
recurse_check_structure(sample, to_check)
def test_recurse_check_structure_wrongtype_2():
sample = dict(
string="Foobar",
list=["Foo", "Bar"],
dict={"foo": "Bar"},
none=None,
true=True,
false=False,
)
to_check = dict(
string="Foobar",
list={"foo": "Bar"},
dict={"foo": "Bar"},
none=None,
true=True,
false=False,
)
with pytest.raises(ValidationException):
recurse_check_structure(sample, to_check)
def test_recurse_check_structure_wrongtype_3():
sample = dict(
string="Foobar",
list=["Foo", "Bar"],
dict={"foo": "Bar"},
none=None,
true=True,
false=False,
)
to_check = dict(
string="Foobar",
list=["Foo", "Bar"],
dict=["Foo", "Bar"],
none=None,
true=True,
false=False,
)
with pytest.raises(ValidationException):
recurse_check_structure(sample, to_check)
def test_failed_config(testbot):
assert "Plugin configuration done." in testbot.exec_command(
'!plugin config Config {"One": "two"}'
)
| 3,630
|
Python
|
.py
| 135
| 19.555556
| 87
| 0.553797
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,114
|
webhooks_test.py
|
errbotio_errbot/tests/webhooks_test.py
|
import json
import logging
import os
import socket
from time import sleep
import pytest
import requests
log = logging.getLogger(__name__)
PYTHONOBJECT = ["foo", {"bar": ("baz", None, 1.0, 2)}]
JSONOBJECT = json.dumps(PYTHONOBJECT)
# Webserver port is picked based on the process ID so that when tests
# are run in parallel with pytest-xdist, each process runs the server
# on a different port
WEBSERVER_PORT = 5000 + (os.getpid() % 1000)
WEBSERVER_SSL_PORT = WEBSERVER_PORT + 1000
def webserver_ready(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host, port))
s.shutdown(socket.SHUT_RDWR)
s.close()
return True
except Exception:
return False
extra_plugin_dir = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "webhooks_plugin"
)
def wait_for_server(port: int):
failure_count = 10
while not webserver_ready("localhost", port):
waiting_time = 1.0 / failure_count
log.info("Webserver not ready yet, sleeping for %f second.", waiting_time)
sleep(waiting_time)
failure_count -= 1
if failure_count == 0:
raise TimeoutError("Could not start the internal Webserver to test.")
@pytest.fixture
def webhook_testbot(request, testbot):
testbot.push_message(
"!plugin config Webserver {'HOST': 'localhost', 'PORT': %s, 'SSL': None}"
% WEBSERVER_PORT
)
log.info(testbot.pop_message())
wait_for_server(WEBSERVER_PORT)
return testbot
def test_not_configured_url_returns_404(webhook_testbot):
assert (
requests.post(
"http://localhost:{}/randomness_blah".format(WEBSERVER_PORT),
"{'toto': 'titui'}",
).status_code
== 404
)
def test_webserver_plugin_ok(webhook_testbot):
assert "/echo" in webhook_testbot.exec_command("!webstatus")
def test_trailing_no_slash_ok(webhook_testbot):
assert requests.post(
"http://localhost:{}/echo".format(WEBSERVER_PORT), JSONOBJECT
).text == repr(json.loads(JSONOBJECT))
def test_trailing_slash_also_ok(webhook_testbot):
assert requests.post(
"http://localhost:{}/echo/".format(WEBSERVER_PORT), JSONOBJECT
).text == repr(json.loads(JSONOBJECT))
def test_json_is_automatically_decoded(webhook_testbot):
assert requests.post(
"http://localhost:{}/webhook1".format(WEBSERVER_PORT), JSONOBJECT
).text == repr(json.loads(JSONOBJECT))
def test_json_on_custom_url_is_automatically_decoded(webhook_testbot):
assert requests.post(
"http://localhost:{}/custom_webhook".format(WEBSERVER_PORT), JSONOBJECT
).text == repr(json.loads(JSONOBJECT))
def test_post_form_on_webhook_without_form_param_is_automatically_decoded(
webhook_testbot,
):
assert requests.post(
"http://localhost:{}/webhook1".format(WEBSERVER_PORT), data=JSONOBJECT
).text == repr(json.loads(JSONOBJECT))
def test_post_form_on_webhook_with_custom_url_and_without_form_param_is_automatically_decoded(
webhook_testbot,
):
assert requests.post(
"http://localhost:{}/custom_webhook".format(WEBSERVER_PORT), data=JSONOBJECT
).text == repr(json.loads(JSONOBJECT))
def test_webhooks_with_form_parameter_decode_json_automatically(webhook_testbot):
form = {"form": JSONOBJECT}
assert requests.post(
"http://localhost:{}/form".format(WEBSERVER_PORT), data=form
).text == repr(json.loads(JSONOBJECT))
def test_webhooks_with_form_parameter_on_custom_url_decode_json_automatically(
webhook_testbot,
):
form = {"form": JSONOBJECT}
assert requests.post(
"http://localhost:{}/custom_form".format(WEBSERVER_PORT), data=form
).text, repr(json.loads(JSONOBJECT))
def test_webhooks_with_raw_request(webhook_testbot):
form = {"form": JSONOBJECT}
assert (
"LocalProxy"
in requests.post(
"http://localhost:{}/raw".format(WEBSERVER_PORT), data=form
).text
)
def test_webhooks_with_naked_decorator_raw_request(webhook_testbot):
form = {"form": JSONOBJECT}
assert (
"LocalProxy"
in requests.post(
"http://localhost:{}/raw2".format(WEBSERVER_PORT), data=form
).text
)
def test_generate_certificate_creates_usable_cert(webhook_testbot):
d = webhook_testbot.bot.bot_config.BOT_DATA_DIR
key_path = os.sep.join((d, "webserver_key.pem"))
cert_path = os.sep.join((d, "webserver_certificate.pem"))
assert "Generating" in webhook_testbot.exec_command(
"!generate_certificate", timeout=1
)
# Generating a certificate could be slow on weak hardware, so keep a safe
# timeout on the first pop_message()
assert "successfully generated" in webhook_testbot.pop_message(timeout=60)
assert "is recommended" in webhook_testbot.pop_message(timeout=1)
assert key_path in webhook_testbot.pop_message(timeout=1)
webserver_config = {
"HOST": "localhost",
"PORT": WEBSERVER_PORT,
"SSL": {
"certificate": cert_path,
"key": key_path,
"host": "localhost",
"port": WEBSERVER_SSL_PORT,
"enabled": True,
},
}
webhook_testbot.push_message(
"!plugin config Webserver {!r}".format(webserver_config)
)
assert "Plugin configuration done." in webhook_testbot.pop_message(timeout=2)
wait_for_server(WEBSERVER_SSL_PORT)
requests.packages.urllib3.disable_warnings(
requests.packages.urllib3.exceptions.InsecureRequestWarning
)
assert requests.post(
"https://localhost:{}/webhook1".format(WEBSERVER_SSL_PORT),
JSONOBJECT,
verify=False,
).text == repr(json.loads(JSONOBJECT))
def test_custom_headers_and_status_codes(webhook_testbot):
assert (
requests.post("http://localhost:{}/webhook6".format(WEBSERVER_PORT)).headers[
"X-Powered-By"
]
== "Errbot"
)
assert (
requests.post("http://localhost:{}/webhook7".format(WEBSERVER_PORT)).status_code
== 403
)
def test_lambda_webhook(webhook_testbot):
assert (
requests.post("http://localhost:{}/lambda".format(WEBSERVER_PORT)).status_code
== 200
)
| 6,257
|
Python
|
.py
| 163
| 32.374233
| 94
| 0.677089
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,115
|
flow_e2e_test.py
|
errbotio_errbot/tests/flow_e2e_test.py
|
from os import path
from queue import Empty
import pytest
extra_plugin_dir = path.join(path.dirname(path.realpath(__file__)), "flow_plugin")
def test_list_flows(testbot):
assert len(testbot.bot.flow_executor.flow_roots) == 4
testbot.bot.push_message("!flows list")
result = testbot.pop_message()
assert "documentation of W1" in result
assert "documentation of W2" in result
assert "documentation of W3" in result
assert "documentation of W4" in result
assert "w1" in result
assert "w2" in result
assert "w3" in result
assert "w4" in result
def test_no_autotrigger(testbot):
assert "a" in testbot.exec_command("!a")
assert len(testbot.bot.flow_executor.in_flight) == 0
def test_autotrigger(testbot):
assert "c" in testbot.exec_command("!c")
flow_message = testbot.pop_message()
assert "You are in the flow w2, you can continue with" in flow_message
assert "!b" in flow_message
assert len(testbot.bot.flow_executor.in_flight) == 1
assert testbot.bot.flow_executor.in_flight[0].name == "w2"
def test_no_duplicate_autotrigger(testbot):
assert "c" in testbot.exec_command("!c")
flow_message = testbot.pop_message()
assert "You are in the flow w2, you can continue with" in flow_message
assert "c" in testbot.exec_command("!c")
assert len(testbot.bot.flow_executor.in_flight) == 1
assert testbot.bot.flow_executor.in_flight[0].name == "w2"
def test_secondary_autotrigger(testbot):
assert "e" in testbot.exec_command("!e")
second_message = testbot.pop_message()
assert "You are in the flow w2, you can continue with" in second_message
assert "!d" in second_message
assert len(testbot.bot.flow_executor.in_flight) == 1
assert testbot.bot.flow_executor.in_flight[0].name == "w2"
def test_manual_flow(testbot):
assert "Flow w1 started" in testbot.exec_command("!flows start w1")
flow_message = testbot.pop_message()
assert "You are in the flow w1, you can continue with" in flow_message
assert "!a" in flow_message
assert "a" in testbot.exec_command("!a")
flow_message = testbot.pop_message()
assert "You are in the flow w1, you can continue with" in flow_message
assert "!b" in flow_message
assert "!c" in flow_message
def test_manual_flow_with_or_without_hinting(testbot):
assert "Flow w4 started" in testbot.exec_command("!flows start w4")
assert "a" in testbot.exec_command("!a")
assert "b" in testbot.exec_command("!b")
flow_message = testbot.pop_message()
assert "You are in the flow w4, you can continue with" in flow_message
assert "!c" in flow_message
def test_no_flyby_trigger_flow(testbot):
testbot.bot.push_message("!flows start w1")
# One message or the other can arrive first.
flow_message = testbot.pop_message()
assert "Flow w1 started" in flow_message or "You are in the flow w1" in flow_message
flow_message = testbot.pop_message()
assert "Flow w1 started" in flow_message or "You are in the flow w1" in flow_message
assert "a" in testbot.exec_command("!a")
flow_message = testbot.pop_message()
assert "You are in the flow w1" in flow_message
assert "c" in testbot.exec_command(
"!c"
) # c is a trigger for w2 but it should not trigger now.
flow_message = testbot.pop_message()
assert "You are in the flow w1" in flow_message
assert len(testbot.bot.flow_executor.in_flight) == 1
def test_flow_only(testbot):
assert "a" in testbot.exec_command("!a") # non flow_only should respond.
testbot.push_message("!d")
with pytest.raises(Empty):
testbot.pop_message(timeout=1)
def test_flow_only_help(testbot):
testbot.push_message("!help")
msg = testbot.bot.pop_message()
assert "!a" in msg # non flow_only should be in help by default
assert "!d" not in msg # flow_only should not be in help by default
def test_flows_stop(testbot):
assert "c" in testbot.exec_command("!c")
flow_message = testbot.bot.pop_message()
assert "You are in the flow w2" in flow_message
assert "w2 stopped" in testbot.exec_command("!flows stop w2")
assert len(testbot.bot.flow_executor.in_flight) == 0
def test_flows_kill(testbot):
assert "c" in testbot.exec_command("!c")
flow_message = testbot.bot.pop_message()
assert "You are in the flow w2" in flow_message
assert "w2 killed" in testbot.exec_command("!flows kill gbin@localhost w2")
def test_room_flow(testbot):
assert "Flow w3 started" in testbot.exec_command("!flows start w3")
flow_message = testbot.pop_message()
assert "You are in the flow w3, you can continue with" in flow_message
assert "!a" in flow_message
assert "a" in testbot.exec_command("!a")
flow_message = testbot.pop_message()
assert "You are in the flow w3, you can continue with" in flow_message
assert "!b" in flow_message
| 4,908
|
Python
|
.py
| 103
| 42.951456
| 88
| 0.70603
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,116
|
plugin_entrypoint_test.py
|
errbotio_errbot/tests/plugin_entrypoint_test.py
|
from errbot.utils import entry_point_plugins
def test_entrypoint_paths():
plugins = entry_point_plugins("console_scripts")
match = False
for plugin in plugins:
if "errbot/errbot.cli" in plugin:
match = True
assert match
def test_entrypoint_paths_empty():
groups = ["errbot.plugins", "errbot.backend_plugins"]
for entry_point_group in groups:
plugins = entry_point_plugins(entry_point_group)
assert plugins == []
| 477
|
Python
|
.py
| 13
| 30.692308
| 57
| 0.686275
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,117
|
poller_plugin.py
|
errbotio_errbot/tests/poller_plugin/poller_plugin.py
|
from __future__ import absolute_import
from errbot import BotPlugin, botcmd
class PollerPlugin(BotPlugin):
def delayed_hello(self, frm):
self.send(frm, "Hello world! was sent 5 seconds ago")
@botcmd
def hello(self, msg, args):
"""Say hello to the world."""
self.start_poller(0.1, self.delayed_hello, times=1, kwargs={"frm": msg.frm})
return "Hello, world!"
def delayed_hello_loop(self, frm):
self.send(frm, "Hello world! was sent 5 seconds ago")
self.stop_poller(self.delayed_hello_loop, args=(frm,))
@botcmd
def hello_loop(self, msg, args):
"""Say hello to the world."""
self.start_poller(0.1, self.delayed_hello_loop, args=(msg.frm,))
return "Hello, world!"
| 762
|
Python
|
.py
| 18
| 35.666667
| 84
| 0.646341
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,118
|
dyna.py
|
errbotio_errbot/tests/dyna_plugin/dyna.py
|
from __future__ import absolute_import
from errbot import BotPlugin, Command, arg_botcmd, botcmd, botmatch
def say_foo(plugin, msg, args):
return "foo %s" % type(plugin)
class Dyna(BotPlugin):
"""Just a test plugin to see if dynamic plugin API works."""
@botcmd
def add_simple(self, _, _1):
simple1 = Command(
lambda plugin, msg, args: "yep %s" % type(plugin), name="say_yep"
)
simple2 = Command(say_foo)
self.create_dynamic_plugin(
"simple with special#", (simple1, simple2), doc="documented"
)
return "added"
@botcmd
def remove_simple(self, msg, args):
self.destroy_dynamic_plugin("simple with special#")
return "removed"
@botcmd
def add_arg(self, _, _1):
cmd1_name = "echo_to_me"
cmd1 = Command(
lambda plugin, msg, args: "string to echo is %s" % args.positional_arg,
cmd_type=arg_botcmd,
cmd_args=("positional_arg",),
cmd_kwargs={"unpack_args": False, "name": cmd1_name},
name=cmd1_name,
)
self.create_dynamic_plugin("arg", (cmd1,), doc="documented")
return "added"
@botcmd
def remove_arg(self, msg, args):
self.destroy_dynamic_plugin("arg")
return "removed"
@botcmd
def add_re(self, _, _1):
re1 = Command(
lambda plugin, msg, match: "fffound",
name="ffound",
cmd_type=botmatch,
cmd_args=(r"^.*cheese.*$",),
)
self.create_dynamic_plugin("re", (re1,))
return "added"
@botcmd
def remove_re(self, msg, args):
self.destroy_dynamic_plugin("re")
return "removed"
@botcmd
def add_saw(self, _, _1):
re1 = Command(
lambda plugin, msg, args: "+".join(args),
name="splitme",
cmd_type=botcmd,
cmd_kwargs={"split_args_with": ","},
)
self.create_dynamic_plugin("saw", (re1,))
return "added"
@botcmd
def remove_saw(self, msg, args):
self.destroy_dynamic_plugin("saw")
return "removed"
@botcmd
def clash(self, msg, args):
return "original"
@botcmd
def add_clashing(self, _, _1):
simple1 = Command(lambda plugin, msg, args: "dynamic", name="clash")
self.create_dynamic_plugin("clashing", (simple1,))
return "added"
@botcmd
def remove_clashing(self, _, _1):
self.destroy_dynamic_plugin("clashing")
return "removed"
| 2,561
|
Python
|
.py
| 76
| 25.328947
| 83
| 0.56998
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,119
|
roomtest.py
|
errbotio_errbot/tests/room_plugin/roomtest.py
|
import logging
from queue import Queue
from errbot import BotPlugin
log = logging.getLogger(__name__)
class RoomTest(BotPlugin):
def activate(self):
super().activate()
self.purge()
def callback_room_joined(self, room, user, invited_by):
log.info("join")
self.events.put(f"callback_room_joined {room}")
def callback_room_left(self, room, user, kicked_by):
self.events.put(f"callback_room_left {room}")
def callback_room_topic(self, room):
self.events.put(f"callback_room_topic {room.topic}")
def purge(self):
log.info("purge")
self.events = Queue()
| 640
|
Python
|
.py
| 18
| 29.444444
| 60
| 0.666124
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,120
|
commandnotfound.py
|
errbotio_errbot/tests/commandnotfound_plugin/commandnotfound.py
|
from errbot import BotPlugin, cmdfilter
class TestCommandNotFoundFilter(BotPlugin):
@cmdfilter(catch_unprocessed=True)
def command_not_found(self, msg, cmd, args, dry_run, emptycmd=False):
if not emptycmd:
return msg, cmd, args
return f"Command fell through: {msg}"
| 305
|
Python
|
.py
| 7
| 37
| 73
| 0.711864
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,121
|
mp.py
|
errbotio_errbot/tests/multi_plugin/mp.py
|
from errbot import BotPlugin, botcmd
class WhateverName(BotPlugin):
"""Test plugin to verify that now class names don't matter."""
@botcmd
def myname(self, msg, args):
return self.name
| 208
|
Python
|
.py
| 6
| 29.833333
| 66
| 0.713568
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,122
|
webtest.py
|
errbotio_errbot/tests/webhooks_plugin/webtest.py
|
import logging
from flask import abort, after_this_request
from errbot import BotPlugin
from errbot.core_plugins.webserver import webhook
log = logging.getLogger(__name__)
class WebTest(BotPlugin):
@webhook
def webhook1(self, payload):
log.debug(str(payload))
return str(payload)
@webhook(r"/custom_webhook")
def webhook2(self, payload):
log.debug(str(payload))
return str(payload)
@webhook(r"/form", form_param="form")
def webhook3(self, payload):
log.debug(str(payload))
return str(payload)
@webhook(r"/custom_form", form_param="form")
def webhook4(self, payload):
log.debug(str(payload))
return str(payload)
@webhook(r"/raw", raw=True)
def webhook5(self, payload):
log.debug(str(payload))
return str(type(payload))
@webhook
def webhook6(self, payload):
log.debug(str(payload))
@after_this_request
def add_header(response):
response.headers["X-Powered-By"] = "Errbot"
return response
return str(payload)
@webhook
def webhook7(self, payload):
abort(403, "Forbidden")
webhook8 = webhook(r"/lambda")(lambda x, y: str(x) + str(y))
# Just to test https://github.com/errbotio/errbot/issues/1043
@webhook(raw=True)
def raw2(self, payload):
log.debug(str(payload))
return str(type(payload))
| 1,432
|
Python
|
.py
| 43
| 26.55814
| 65
| 0.649927
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,123
|
test.py
|
errbotio_errbot/tests/template_plugin/test.py
|
from __future__ import absolute_import
from errbot import BotPlugin, arg_botcmd, botcmd
class Test(BotPlugin):
@botcmd
def test_template1(self, msg, args):
self.send_templated(msg.frm, "test", {"variable": "ok"})
@botcmd(template="test")
def test_template2(self, msg, args):
return {"variable": "ok"}
@botcmd(template="test")
def test_template3(self, msg, args):
yield {"variable": "ok"}
@arg_botcmd("my_var", type=str, template="test")
def test_template4(self, msg, my_var=None):
return {"variable": my_var}
| 579
|
Python
|
.py
| 15
| 32.933333
| 64
| 0.650538
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,124
|
text_test.py
|
errbotio_errbot/tests/backend_tests/text_test.py
|
import logging
import os
import sys
from tempfile import mkdtemp
import pytest
from errbot.backends.text import TextBackend
from errbot.bootstrap import bot_config_defaults
@pytest.fixture
def text_backend():
tempdir = mkdtemp()
# reset the config every time
sys.modules.pop("errbot.config-template", None)
__import__("errbot.config-template")
config = sys.modules["errbot.config-template"]
bot_config_defaults(config)
config.BOT_DATA_DIR = tempdir
config.BOT_LOG_FILE = os.path.join(tempdir, "log.txt")
config.BOT_EXTRA_PLUGIN_DIR = []
config.BOT_LOG_LEVEL = logging.DEBUG
config.BOT_PREFIX = "!"
config.BOT_IDENTITY["username"] = "@testme"
config.BOT_ADMINS = ["@test_admin"]
return TextBackend(config)
def test_change_presence(text_backend, caplog):
with caplog.at_level(logging.DEBUG):
text_backend.change_presence("online", "I'm online")
assert len(caplog.messages) == 1
a_message = caplog.messages[0]
assert a_message.startswith("*** Changed presence")
| 1,047
|
Python
|
.py
| 29
| 32.068966
| 60
| 0.725743
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,125
|
failp.py
|
errbotio_errbot/tests/fail_config_plugin/failp.py
|
from errbot import BotPlugin, ValidationException
class FailP(BotPlugin):
"""
Just a plugin failing at config time.
"""
def get_configuration_template(self):
return {"One": 1, "Two": 2}
def check_configuration(self, configuration):
raise ValidationException("Message explaining why it failed.")
| 335
|
Python
|
.py
| 9
| 31.777778
| 70
| 0.708075
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,126
|
i18n.py
|
errbotio_errbot/tests/i18n_plugin/i18n.py
|
# -*- coding=utf-8 -*-
from errbot import BotPlugin, botcmd
class I18nTest(BotPlugin):
"""A Just a test plugin to see if it is picked up."""
@botcmd
def i18n_1(self, msg, args):
return "язы́к"
@botcmd(name="ру́сский")
def i18n_2(self, msg, args):
return "OK"
@botcmd(name="prefix_ру́сский")
def i18n_3(self, msg, args):
return "OK"
@botcmd(name="ру́сский_suffix")
def i18n_4(self, msg, args):
return "OK"
| 508
|
Python
|
.py
| 16
| 24.3125
| 57
| 0.606127
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,127
|
parent2.py
|
errbotio_errbot/tests/cascade_dependent_plugins/parent2.py
|
from errbot import BotPlugin, botcmd
class Parent2(BotPlugin):
@botcmd
def parent2_to_parent1(self, msg, args):
return self.get_plugin("Parent1").shared_function()
| 182
|
Python
|
.py
| 5
| 31.8
| 59
| 0.731429
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,128
|
child2.py
|
errbotio_errbot/tests/cascade_dependent_plugins/child2.py
|
from errbot import BotPlugin
class Child2(BotPlugin):
def shared_function(self):
return "Hello from Child2"
| 122
|
Python
|
.py
| 4
| 26
| 34
| 0.75
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,129
|
parent1.py
|
errbotio_errbot/tests/cascade_dependent_plugins/parent1.py
|
from errbot import BotPlugin, botcmd
class Parent1(BotPlugin):
@botcmd
def parent1_to_child1(self, msg, args):
return self.get_plugin("Child1").shared_function()
@botcmd
def parent1_to_child2(self, msg, args):
return self.get_plugin("Child2").shared_function()
def shared_function(self):
return "Hello from Parent1"
| 364
|
Python
|
.py
| 10
| 30.6
| 58
| 0.694286
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,130
|
child1.py
|
errbotio_errbot/tests/cascade_dependent_plugins/child1.py
|
from errbot import BotPlugin
class Child1(BotPlugin):
def shared_function(self):
return "Hello from Child1"
| 122
|
Python
|
.py
| 4
| 26
| 34
| 0.75
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,131
|
parent1.py
|
errbotio_errbot/tests/dependent_plugins/parent1.py
|
from errbot import BotPlugin
class Parent1(BotPlugin):
def shared_function(self):
return "youpi"
| 111
|
Python
|
.py
| 4
| 23.25
| 30
| 0.742857
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,132
|
single.py
|
errbotio_errbot/tests/dependent_plugins/single.py
|
from errbot import BotPlugin, botcmd
class Single(BotPlugin):
@botcmd
def depfunc(self, msg, args):
return self.get_plugin("Parent1").shared_function()
| 170
|
Python
|
.py
| 5
| 29.4
| 59
| 0.723926
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,133
|
matchall.py
|
errbotio_errbot/tests/matchall_plugin/matchall.py
|
from errbot import BotPlugin, botmatch
class MatchAll(BotPlugin):
@botmatch(r".*")
def all(self, msg, match):
return "Works!"
| 144
|
Python
|
.py
| 5
| 24.2
| 38
| 0.678832
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,134
|
config.py
|
errbotio_errbot/tests/config_plugin/config.py
|
from errbot import BotPlugin
class Config(BotPlugin):
"""
Just a plugin with a simple string config.
"""
def get_configuration_template(self):
return {"One": "one"}
| 192
|
Python
|
.py
| 7
| 22.571429
| 46
| 0.67033
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,135
|
test.py
|
errbotio_errbot/tests/syntax_plugin/test.py
|
from __future__ import absolute_import
from errbot import BotPlugin, arg_botcmd, botcmd, re_botcmd
class Test(BotPlugin):
"""Just a test plugin to see if _err_botcmd_syntax is consistent on all types of botcmd"""
@botcmd # no syntax
def foo_nosyntax(self, msg, args):
pass
@botcmd(syntax="[optional] <mandatory>")
def foo(self, msg, args):
pass
@re_botcmd(pattern=r".*")
def re_foo(self, msg, match):
pass
@arg_botcmd("value", type=str)
@arg_botcmd("--repeat-count", dest="repeat", type=int, default=2)
def arg_foo(self, msg, value=None, repeat=None):
return value * repeat
| 654
|
Python
|
.py
| 17
| 32.823529
| 94
| 0.657143
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,136
|
flowtest_flows.py
|
errbotio_errbot/tests/flow_plugin/flowtest_flows.py
|
# ruff: noqa: F841
from __future__ import absolute_import
from errbot import BotFlow, FlowRoot, botflow
class FlowDefinitions(BotFlow):
"""A plugin to test the flows
see flowtest.png for the structure.
"""
@botflow
def w1(self, flow: FlowRoot):
"documentation of W1"
a_node = flow.connect("a") # no autotrigger
b_node = a_node.connect("b")
c_node = a_node.connect("c") # crosses the autotrigger of w2
d_node = c_node.connect("d")
assert a_node.hints
assert b_node.hints
assert c_node.hints
assert d_node.hints
@botflow
def w2(self, flow: FlowRoot):
"""documentation of W2"""
c_node = flow.connect("c", auto_trigger=True)
b_node = c_node.connect("b")
e_node = flow.connect(
"e", auto_trigger=True
) # 2 autotriggers for the same workflow
d_node = e_node.connect("d")
@botflow
def w3(self, flow: FlowRoot):
"""documentation of W3"""
c_node = flow.connect("a", room_flow=True)
b_node = c_node.connect("b")
@botflow
def w4(self, flow: FlowRoot):
"""documentation of W4"""
a_node = flow.connect("a")
b_node = a_node.connect("b")
c_node = b_node.connect("c")
c_node.connect("d")
# set some hinting.
flow.hints = False
a_node.hints = False
b_node.hints = True
c_node.hint = False
| 1,465
|
Python
|
.py
| 44
| 25.727273
| 69
| 0.584278
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,137
|
flowtest.py
|
errbotio_errbot/tests/flow_plugin/flowtest.py
|
from __future__ import absolute_import
from errbot import BotPlugin, botcmd
class FlowTest(BotPlugin):
"""A plugin to test the flows
see flowtest.png for the structure.
"""
@botcmd
def a(self, msg, args):
return "a"
@botcmd
def b(self, msg, args):
return "b"
@botcmd
def c(self, msg, args):
return "c"
@botcmd(flow_only=True)
def d(self, msg, args):
return "d"
@botcmd
def e(self, msg, args):
return "e"
| 504
|
Python
|
.py
| 21
| 18.238095
| 39
| 0.6
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,138
|
dummy.py
|
errbotio_errbot/tests/dummy_plugin/dummy.py
|
from __future__ import absolute_import
from errbot import BotPlugin, botcmd, botmatch, re_botcmd
class DummyTest(BotPlugin):
"""Just a test plugin to see if it is picked up."""
@botcmd
def foo(self, msg, args):
"""This runs foo."""
return "bar"
@re_botcmd(pattern=r"plz dont match this")
def re_foo(self, msg, match):
"""This runs re_foo."""
return "bar"
@botmatch(r"match this")
def re_bar(self, msg, match):
"""This runs re_foo."""
return "bar"
@botcmd
def run_subcommands(self, msg, args):
"""Tests a simple subcommand"""
return args
@botcmd
def run_lots_of_subcommands(self, msg, args):
"""Tests multiple subcommands"""
return args
def helper_method(self, arg):
return arg
@botcmd
def baz(self, msg, args):
"""Tests mock injection method"""
return self.helper_method("baz")
@botcmd
def bar(self, msg, args):
"""This runs bar."""
return msg
| 1,039
|
Python
|
.py
| 34
| 23.823529
| 57
| 0.600604
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,139
|
mention.py
|
errbotio_errbot/tests/mention_plugin/mention.py
|
from errbot import BotPlugin
class MentionTestPlugin(BotPlugin):
def callback_mention(self, msg, people):
if self.bot_identifier in people:
self.send(msg.frm, "Somebody mentioned me!", msg)
return
self.send(
msg.frm, "Somebody mentioned %s!" % ",".join(p.person for p in people), msg
)
| 352
|
Python
|
.py
| 9
| 30.777778
| 87
| 0.627566
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,140
|
broken.py
|
errbotio_errbot/tests/borken_plugin/broken.py
|
from errbot import BotPlugin, botcmd
import borken # fails on purpose # noqa: F401
class Broken(BotPlugin):
@botcmd
def hello(self, msg, args):
"""this command says hello"""
return "Hello World !"
| 224
|
Python
|
.py
| 7
| 27.285714
| 46
| 0.67907
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,141
|
botplugin.py
|
errbotio_errbot/errbot/botplugin.py
|
import logging
import re
import shlex
from io import IOBase
from threading import Timer, current_thread
from types import ModuleType
from typing import Any, Callable, List, Mapping, Optional, Sequence, Tuple
from errbot.backends.base import (
ONLINE,
Card,
Identifier,
Message,
Presence,
Reaction,
Room,
Stream,
)
from .storage import StoreMixin, StoreNotOpenError
log = logging.getLogger(__name__)
class ValidationException(Exception):
pass
def recurse_check_structure(sample: Any, to_check: Any) -> None:
sample_type = type(sample)
to_check_type = type(to_check)
# Skip this check if the sample is None because it will always be something
# other than NoneType when changed from the default. Raising ValidationException
# would make no sense then because it would defeat the whole purpose of having
# that key in the sample when it could only ever be None.
if sample is not None and sample_type != to_check_type:
raise ValidationException(
f"{sample} [{sample_type}] is not the same type as {to_check} [{to_check_type}]."
)
if sample_type in (list, tuple):
for element in to_check:
recurse_check_structure(sample[0], element)
return
if sample_type == dict: # noqa: E721
for key in sample:
if key not in to_check:
raise ValidationException(f"{to_check} doesn't contain the key {key}.")
for key in to_check:
if key not in sample:
raise ValidationException(f"{to_check} contains an unknown key {key}.")
for key in sample:
recurse_check_structure(sample[key], to_check[key])
return
class CommandError(Exception):
"""
Use this class to report an error condition from your commands, the command
did not proceed for a known "business" reason.
"""
def __init__(self, reason: str, template: str = None):
"""
:param reason: the reason for the error in the command.
:param template: apply this specific template to report the error.
"""
self.reason = reason
self.template = template
def __str__(self):
return str(self.reason)
class Command:
"""
This is a dynamic definition of an errbot command.
"""
def __init__(
self,
function: Callable,
cmd_type: Optional[Callable] = None,
cmd_args=None,
cmd_kwargs=None,
name: Optional[str] = None,
doc: Optional[str] = None,
):
"""
Create a Command definition.
:param function:
a function or a lambda with the correct signature for the type of command to inject for example `def
mycmd(plugin, msg, args)` for a botcmd. Note: the first parameter will be the plugin itself (equivalent to
self).
:param cmd_type:
defaults to `botcmd` but can be any decorator function used for errbot commands.
:param cmd_args: the parameters of the decorator.
:param cmd_kwargs: the kwargs parameter of the decorator.
:param name:
defaults to the name of the function you are passing if it is a first class function or needs to be set if
you use a lambda.
:param doc:
defaults to the doc of the given function if it is a first class function. It can be set for a lambda or
overridden for a function with this."""
if cmd_type is None:
from errbot import ( # TODO refactor this out of __init__ so it can be reusable.
botcmd,
)
cmd_type = botcmd
if name is None:
if function.__name__ == "<lambda>":
raise ValueError(
"function is a lambda (anonymous), parameter name needs to be set."
)
name = function.__name__
self.name = name
if cmd_kwargs is None:
cmd_kwargs = {}
if cmd_args is None:
cmd_args = ()
function.__name__ = name
if doc:
function.__doc__ = doc
self.definition = cmd_type(*((function,) + cmd_args), **cmd_kwargs)
def append_args(self, args, kwargs):
from errbot import update_wrapper
if hasattr(self.definition, "_err_command_parser"):
update_wrapper(self.definition, args, kwargs)
else:
log.warning(
f"Attempting to append arguments to {self.definition} isn't supported."
)
# noinspection PyAbstractClass
class BotPluginBase(StoreMixin):
"""
This class handle the basic needs of bot plugins like loading, unloading and creating a storage
It is the main contract between the plugins and the bot
"""
def __init__(self, bot, name=None):
self.is_activated = False
self.current_pollers = []
self.current_timers = []
self.dependencies = []
self._dynamic_plugins = {}
self.log = logging.getLogger(f"errbot.plugins.{name}")
self.log.debug("Logger for plugin %s initialized...", name)
self._bot = bot
self.plugin_dir = bot.repo_manager.plugin_dir
self._name = name
super().__init__()
@property
def name(self) -> str:
"""
Get the name of this plugin as described in its .plug file.
:return: The plugin name.
"""
return self._name
@property
def mode(self) -> str:
"""
Get the current active backend.
:return: the mode like 'tox', 'xmpp' etc...
"""
return self._bot.mode
@property
def bot_config(self) -> ModuleType:
"""
Get the bot configuration from config.py.
For example you can access:
self.bot_config.BOT_DATA_DIR
"""
# if BOT_ADMINS is just an unique string make it a tuple for backwards
# compatibility
if isinstance(self._bot.bot_config.BOT_ADMINS, str):
self._bot.bot_config.BOT_ADMINS = (self._bot.bot_config.BOT_ADMINS,)
return self._bot.bot_config
@property
def bot_identifier(self) -> Identifier:
"""
Get bot identifier on current active backend.
:return Identifier
"""
return self._bot.bot_identifier
def init_storage(self) -> None:
log.debug(f"Init storage for {self.name}.")
self.open_storage(self._bot.storage_plugin, self.name)
def activate(self) -> None:
"""
Override if you want to do something at initialization phase (don't forget to
super(Gnagna, self).activate())
"""
self.init_storage()
self._bot.inject_commands_from(self)
self._bot.inject_command_filters_from(self)
self.is_activated = True
def deactivate(self) -> None:
"""
Override if you want to do something at tear down phase (don't forget to super(Gnagna, self).deactivate())
"""
if self.current_pollers:
log.debug(
"You still have active pollers at deactivation stage, I cleaned them up for you."
)
self.current_pollers = []
for timer in self.current_timers:
timer.cancel()
try:
self.close_storage()
except StoreNotOpenError:
pass
self._bot.remove_command_filters_from(self)
self._bot.remove_commands_from(self)
self.is_activated = False
for plugin in self._dynamic_plugins.values():
self._bot.remove_command_filters_from(plugin)
self._bot.remove_commands_from(plugin)
def start_poller(
self,
interval: float,
method: Callable[..., None],
times: int = None,
args: Tuple = None,
kwargs: Mapping = None,
) -> None:
"""Starts a poller that will be called at a regular interval
:param interval: interval in seconds
:param method: targetted method
:param times:
number of times polling should happen (defaults to``None`` which
causes the polling to happen indefinitely)
:param args: args for the targetted method
:param kwargs: kwargs for the targetting method
"""
if not kwargs:
kwargs = {}
if not args:
args = []
log.debug(
f"Programming the polling of {method.__name__} every {interval} seconds "
f"with args {str(args)} and kwargs {str(kwargs)}"
)
# noinspection PyBroadException
try:
self.current_pollers.append((method, args, kwargs))
self.program_next_poll(interval, method, times, args, kwargs)
except Exception:
log.exception("Poller programming failed.")
def stop_poller(
self, method: Callable[..., None], args: Tuple = None, kwargs: Mapping = None
) -> None:
if not kwargs:
kwargs = {}
if not args:
args = []
log.debug(f"Stop polling of {method} with args {args} and kwargs {kwargs}")
self.current_pollers.remove((method, args, kwargs))
def program_next_poll(
self,
interval: float,
method: Callable[..., None],
times: int = None,
args: Tuple = None,
kwargs: Mapping = None,
) -> None:
if times is not None and times <= 0:
return
t = Timer(
interval=interval,
function=self.poller,
kwargs={
"interval": interval,
"method": method,
"times": times,
"args": args,
"kwargs": kwargs,
},
)
self.current_timers.append(t) # save the timer to be able to kill it
t.name = f"Poller thread for {type(method.__self__).__name__}"
t.daemon = True # so it is not locking on exit
t.start()
def poller(
self,
interval: float,
method: Callable[..., None],
times: int = None,
args: Tuple = None,
kwargs: Mapping = None,
) -> None:
previous_timer = current_thread()
if previous_timer in self.current_timers:
log.debug("Previous timer found and removed")
self.current_timers.remove(previous_timer)
if (method, args, kwargs) in self.current_pollers:
# noinspection PyBroadException
try:
method(*args, **kwargs)
except Exception:
log.exception("A poller crashed")
if times is not None:
times -= 1
self.program_next_poll(interval, method, times, args, kwargs)
def create_dynamic_plugin(
self, name: str, commands: Tuple[Command], doc: str = ""
) -> None:
"""
Creates a plugin dynamically and exposes its commands right away.
:param name: name of the plugin.
:param commands: a tuple of command definition.
:param doc: the main documentation of the plugin.
"""
if name in self._dynamic_plugins:
raise ValueError("Dynamic plugin %s already created.")
# cleans the name to be a valid python type.
plugin_class = type(
re.sub(r"\W|^(?=\d)", "_", name),
(BotPlugin,),
{command.name: command.definition for command in commands},
)
plugin_class.__errdoc__ = doc
plugin = plugin_class(self._bot, name=name)
self._dynamic_plugins[name] = plugin
self._bot.inject_commands_from(plugin)
def destroy_dynamic_plugin(self, name: str) -> None:
"""
Reverse operation of create_dynamic_plugin.
This allows you to dynamically refresh the list of commands for example.
:param name: the name of the dynamic plugin given to create_dynamic_plugin.
"""
if name not in self._dynamic_plugins:
raise ValueError("Dynamic plugin %s doesn't exist.", name)
plugin = self._dynamic_plugins[name]
self._bot.remove_command_filters_from(plugin)
self._bot.remove_commands_from(plugin)
del self._dynamic_plugins[name]
def get_plugin(self, name) -> "BotPlugin":
"""
Gets a plugin your plugin depends on. The name of the dependency needs to be listed in [Code] section
key DependsOn of your plug file. This method can only be used after your plugin activation
(or having called super().activate() from activate itself).
It will return a plugin object.
:param name: the name
:return: the BotPlugin object requested.
"""
if not self.is_activated:
raise Exception(
"Plugin needs to be in activated state to be able to get its dependencies."
)
if name not in self.dependencies:
raise Exception(
f"Plugin dependency {name} needs to be listed in section [Core] key "
f'"DependsOn" to be used in get_plugin.'
)
return self._bot.plugin_manager.get_plugin_obj_by_name(name)
# noinspection PyAbstractClass
class BotPlugin(BotPluginBase):
def get_configuration_template(self) -> Mapping:
"""
If your plugin needs a configuration, override this method and return
a configuration template.
For example a dictionary like:
return {'LOGIN' : 'example@example.com', 'PASSWORD' : 'password'}
Note: if this method returns None, the plugin won't be configured
"""
return None
def check_configuration(self, configuration: Mapping) -> None:
"""
By default, this method will do only a BASIC check. You need to override
it if you want to do more complex checks. It will be called before the
configure callback. Note if the config_template is None, it will never
be called.
It means recusively:
1. in case of a dictionary, it will check if all the entries and from
the same type are there and not more.
2. in case of an array or tuple, it will assume array members of the
same type of first element of the template (no mix typed is supported)
In case of validation error it should raise a errbot.ValidationException
:param configuration: the configuration to be checked.
"""
recurse_check_structure(
self.get_configuration_template(), configuration
) # default behavior
def configure(self, configuration: Mapping) -> None:
"""
By default, it will just store the current configuration in the self.config
field of your plugin. If this plugin has no configuration yet, the framework
will call this function anyway with None.
This method will be called before activation so don't expect to be activated
at that point.
:param configuration: injected configuration for the plugin.
"""
self.config = configuration
def activate(self) -> None:
"""
Triggered on plugin activation.
Override this method if you want to do something at initialization phase
(don't forget to `super().activate()`).
"""
super().activate()
def deactivate(self) -> None:
"""
Triggered on plugin deactivation.
Override this method if you want to do something at tear-down phase
(don't forget to `super().deactivate()`).
"""
super().deactivate()
def callback_connect(self) -> None:
"""
Triggered when the bot has successfully connected to the chat network.
Override this method to get notified when the bot is connected.
"""
pass
def callback_message(self, message: Message) -> None:
"""
Triggered on every message not coming from the bot itself.
Override this method to get notified on *ANY* message.
:param message:
representing the message that was received.
"""
pass
def callback_mention(
self, message: Message, mentioned_people: Sequence[Identifier]
) -> None:
"""
Triggered if there are mentioned people in message.
Override this method to get notified when someone was mentioned in message.
[Note: This might not be implemented by all backends.]
:param message:
representing the message that was received.
:param mentioned_people:
all mentioned people in this message.
"""
pass
def callback_presence(self, presence: Presence) -> None:
"""
Triggered on every presence change.
:param presence:
An instance of :class:`~errbot.backends.base.Presence`
representing the new presence state that was received.
"""
pass
def callback_reaction(self, reaction: Reaction) -> None:
"""
Triggered on every reaction event.
:param reaction:
An instance of :class:`~errbot.backends.base.Reaction`
representing the new reaction event that was received.
"""
pass
def callback_stream(self, stream: Stream) -> None:
"""
Triggered asynchronously (in a different thread context) on every incoming stream
request or file transfer request.
You can block this call until you are done with the stream.
To signal that you accept / reject the file, simply call stream.accept()
or stream.reject() and return.
:param stream:
the incoming stream request.
"""
stream.reject() # by default, reject the file as the plugin doesn't want it.
def callback_botmessage(self, message: Message) -> None:
"""
Triggered on every message coming from the bot itself.
Override this method to get notified on all messages coming from
the bot itself (including those from other plugins).
:param message:
An instance of :class:`~errbot.backends.base.Message`
representing the message that was received.
"""
pass
def callback_room_joined(
self,
room: Room,
identifier: Identifier,
invited_by: Optional[Identifier] = None,
) -> None:
"""
Triggered when a user has joined a MUC.
:param room:
An instance of :class:`~errbot.backends.base.MUCRoom`
representing the room that was joined.
:param identifier: An instance of Identifier (Person). Defaults to bot
:param invited_by: An instance of Identifier (Person). Defaults to None
"""
pass
def callback_room_left(
self, room: Room, identifier: Identifier, kicked_by: Optional[Identifier] = None
) -> None:
"""
Triggered when a user has left a MUC.
:param room:
An instance of :class:`~errbot.backends.base.MUCRoom`
representing the room that was left.
:param identifier: An instance of Identifier (Person). Defaults to bot
:param kicked_by: An instance of Identifier (Person). Defaults to None
"""
pass
def callback_room_topic(self, room: Room) -> None:
"""
Triggered when the topic in a MUC changes.
:param room:
An instance of :class:`~errbot.backends.base.MUCRoom`
representing the room for which the topic changed.
"""
pass
# Proxyfy some useful tools from the motherbot
# this is basically the contract between the plugins and the main bot
def warn_admins(self, warning: str) -> None:
"""
Send a warning to the administrators of the bot.
:param warning: The markdown-formatted text of the message to send.
"""
self._bot.warn_admins(warning)
def send(
self,
identifier: Identifier,
text: str,
in_reply_to: Message = None,
groupchat_nick_reply: bool = False,
) -> None:
"""
Send a message to a room or a user.
:param groupchat_nick_reply: if True the message will mention the user in the chatroom.
:param in_reply_to: the original message this message is a reply to (optional).
In some backends it will start a thread.
:param text: markdown formatted text to send to the user.
:param identifier: An Identifier representing the user or room to message.
Identifiers may be created with :func:`build_identifier`.
"""
if not isinstance(identifier, Identifier):
raise ValueError(
"identifier needs to be of type Identifier, the old string behavior is not supported"
)
return self._bot.send(identifier, text, in_reply_to, groupchat_nick_reply)
def send_card(
self,
body: str = "",
to: Identifier = None,
in_reply_to: Message = None,
summary: str = None,
title: str = "",
link: str = None,
image: str = None,
thumbnail: str = None,
color: str = "green",
fields: Tuple[Tuple[str, str], ...] = (),
) -> None:
"""
Sends a card.
A Card is a special type of preformatted message. If it matches with a backend similar concept like on
Slack it will be rendered natively, otherwise it will be sent as a regular formatted message.
:param body: main text of the card in markdown.
:param to: the card is sent to this identifier (Room, RoomOccupant, Person...).
:param in_reply_to: the original message this message is a reply to (optional).
:param summary: (optional) One liner summary of the card, possibly collapsed to it.
:param title: (optional) Title possibly linking.
:param link: (optional) url the title link is pointing to.
:param image: (optional) link to the main image of the card.
:param thumbnail: (optional) link to an icon / thumbnail.
:param color: (optional) background color or color indicator.
:param fields: (optional) a tuple of (key, value) pairs.
"""
frm = in_reply_to.to if in_reply_to else self.bot_identifier
if to is None:
if in_reply_to is None:
raise ValueError("Either to or in_reply_to needs to be set.")
to = in_reply_to.frm
self._bot.send_card(
Card(
body,
frm,
to,
in_reply_to,
summary,
title,
link,
image,
thumbnail,
color,
fields,
)
)
def change_presence(self, status: str = ONLINE, message: str = "") -> None:
"""
Changes the presence/status of the bot.
:param status: One of the constant defined in base.py : ONLINE, OFFLINE, DND,...
:param message: Additional message
:return: None
"""
self._bot.change_presence(status, message)
def send_templated(
self,
identifier: Identifier,
template_name: str,
template_parameters: Mapping,
in_reply_to: Message = None,
groupchat_nick_reply: bool = False,
) -> None:
"""
Sends asynchronously a message to a room or a user.
Same as send but passing a template name and parameters instead of directly the markdown text.
:param template_parameters: arguments for the template.
:param template_name: name of the template to use.
:param groupchat_nick_reply: if True it will mention the user in the chatroom.
:param in_reply_to: optionally, the original message this message is the answer to.
:param identifier: identifier of the user or room to which you want to send a message to.
"""
return self._bot.send_templated(
identifier=identifier,
template_name=template_name,
template_parameters=template_parameters,
in_reply_to=in_reply_to,
groupchat_nick_reply=groupchat_nick_reply,
)
def build_identifier(self, txtrep: str) -> Identifier:
"""
Transform a textual representation of a user identifier to the correct
Identifier object you can set in Message.to and Message.frm.
:param txtrep: the textual representation of the identifier (it is backend dependent).
:return: a user identifier.
"""
return self._bot.build_identifier(txtrep)
def send_stream_request(
self,
user: Identifier,
fsource: IOBase,
name: str = None,
size: int = None,
stream_type: str = None,
) -> Callable:
"""
Sends asynchronously a stream/file to a user.
:param user: is the identifier of the person you want to send it to.
:param fsource: is a file object you want to send.
:param name: is an optional filename for it.
:param size: is optional and is the espected size for it.
:param stream_type: is optional for the mime_type of the content.
It will return a Stream object on which you can monitor the progress of it.
"""
return self._bot.send_stream_request(user, fsource, name, size, stream_type)
def rooms(self) -> Sequence[Room]:
"""
The list of rooms the bot is currently in.
"""
return self._bot.rooms()
def query_room(self, room: str) -> Room:
"""
Query a room for information.
:param room:
The JID/identifier of the room to query for.
:returns:
An instance of :class:`~errbot.backends.base.MUCRoom`.
:raises:
:class:`~errbot.backends.base.RoomDoesNotExistError` if the room doesn't exist.
"""
return self._bot.query_room(room)
def start_poller(
self,
interval: float,
method: Callable[..., None],
times: int = None,
args: Tuple = None,
kwargs: Mapping = None,
):
"""
Start to poll a method at specific interval in seconds.
Note: it will call the method with the initial interval delay for
the first time
Also, you can program
for example : self.program_poller(self, 30, fetch_stuff)
where you have def fetch_stuff(self) in your plugin
:param interval: interval in seconds
:param method: targetted method
:param times:
number of times polling should happen (defaults to``None``
which causes the polling to happen indefinitely)
:param args: args for the targetted method
:param kwargs: kwargs for the targetting method
"""
super().start_poller(interval, method, times, args, kwargs)
def stop_poller(
self, method: Callable[..., None], args: Tuple = None, kwargs: Mapping = None
):
"""
stop poller(s).
If the method equals None -> it stops all the pollers you need to
regive the same parameters as the original start_poller to match a
specific poller to stop
:param kwargs: The initial kwargs you gave to start_poller.
:param args: The initial args you gave to start_poller.
:param method: The initial method you passed to start_poller.
"""
super().stop_poller(method, args, kwargs)
class ArgParserBase:
"""
The `ArgSplitterBase` class defines the API which is used for argument
splitting (used by the `split_args_with` parameter on
:func:`~errbot.decorators.botcmd`).
"""
def parse_args(self, args: str):
"""
This method takes a string of un-split arguments and parses it,
returning a list that is the result of splitting.
If splitting fails for any reason it should return an exception
of some kind.
:param args: string to parse
"""
raise NotImplementedError()
class SeparatorArgParser(ArgParserBase):
"""
This argument splitter splits args on a given separator, like
:func:`str.split` does.
"""
def __init__(self, separator: str = None, maxsplit: int = -1):
"""
:param separator:
The separator on which arguments should be split. If sep is
None, any whitespace string is a separator and empty strings
are removed from the result.
:param maxsplit:
If given, do at most this many splits.
"""
self.separator = separator
self.maxsplit = maxsplit
def parse_args(self, args: str) -> List:
return args.split(self.separator, self.maxsplit)
class ShlexArgParser(ArgParserBase):
"""
This argument splitter splits args using posix shell quoting rules,
like :func:`shlex.split` does.
"""
def parse_args(self, args):
return shlex.split(args)
| 29,231
|
Python
|
.py
| 718
| 31.384401
| 119
| 0.613728
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,142
|
plugin_manager.py
|
errbotio_errbot/errbot/plugin_manager.py
|
"""Logic related to plugin loading and lifecycle"""
import logging
import os
import subprocess
import sys
import traceback
from copy import deepcopy
from graphlib import CycleError
from graphlib import TopologicalSorter as BaseTopologicalSorter
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type
from errbot.flow import BotFlow, Flow
from errbot.repo_manager import check_dependencies
from errbot.storage.base import StoragePluginBase
from .botplugin import BotPlugin
from .core_plugins.wsview import route
from .plugin_info import PluginInfo
from .storage import StoreMixin
from .templating import add_plugin_templates_path, remove_plugin_templates_path
from .utils import collect_roots, entry_point_plugins, version2tuple
from .version import VERSION
PluginInstanceCallback = Callable[[str, Type[BotPlugin]], BotPlugin]
log = logging.getLogger(__name__)
CORE_PLUGINS = os.path.join(os.path.dirname(os.path.abspath(__file__)), "core_plugins")
class PluginActivationException(Exception):
pass
class IncompatiblePluginException(PluginActivationException):
pass
class PluginConfigurationException(PluginActivationException):
pass
def _ensure_sys_path_contains(paths):
"""Ensure that os.path contains paths
:param paths:
a list of base paths to walk from
elements can be a string or a list/tuple of strings
"""
for entry in paths:
if isinstance(entry, (list, tuple)):
_ensure_sys_path_contains(entry)
elif entry is not None and entry not in sys.path:
sys.path.append(entry)
def populate_doc(plugin_object: BotPlugin, plugin_info: PluginInfo) -> None:
plugin_class = type(plugin_object)
plugin_class.__errdoc__ = (
plugin_class.__doc__ if plugin_class.__doc__ else plugin_info.doc
)
def install_packages(req_path: Path):
"""Installs all the packages from the given requirements.txt
Return an exc_info if it fails otherwise None.
"""
def is_docker():
if not os.path.exists("/proc/1/cgroup"):
return False
with open("/proc/1/cgroup") as d:
return "docker" in d.read()
log.info('Installing packages from "%s".', req_path)
# use sys.executable explicitly instead of just 'pip' because depending on how the bot is deployed
# 'pip' might not be available on PATH: for example when installing errbot on a virtualenv and
# starting it with systemctl pointing directly to the executable:
# [Service]
# ExecStart=/home/errbot/.env/bin/errbot
pip_cmdline = [sys.executable, "-m", "pip"]
# noinspection PyBroadException
try:
if hasattr(sys, "real_prefix") or (
hasattr(sys, "base_prefix") and (sys.base_prefix != sys.prefix)
):
# this is a virtualenv, so we can use it directly
subprocess.check_call(
pip_cmdline + ["install", "--requirement", str(req_path)]
)
elif is_docker():
# this is a docker container, so we can use it directly
subprocess.check_call(
pip_cmdline + ["install", "--requirement", str(req_path)]
)
else:
# otherwise only install it as a user package
subprocess.check_call(
pip_cmdline + ["install", "--user", "--requirement", str(req_path)]
)
except Exception:
log.exception("Failed to execute pip install for %s.", req_path)
return sys.exc_info()
def check_python_plug_section(plugin_info: PluginInfo) -> bool:
"""Checks if we have the correct version to run this plugin.
Returns true if the plugin is loadable"""
version = plugin_info.python_version
# if the plugin doesn't restric anything, assume it is ok and try to load it.
if not version:
return True
sys_version = sys.version_info[:3]
if version < (3, 0, 0):
log.error(
"Plugin %s is made for python 2 only and Errbot is not compatible with Python 2 anymore.",
plugin_info.name,
)
log.error(
"Please contact the plugin developer or try to contribute to port the plugin."
)
return False
if version >= sys_version:
log.error(
"Plugin %s requires python >= %s and this Errbot instance runs %s.",
plugin_info.name,
".".join(str(v) for v in version),
".".join(str(v) for v in sys_version),
)
log.error("Upgrade your python interpreter if you want to use this plugin.")
return False
return True
def check_errbot_version(plugin_info: PluginInfo):
"""Checks if a plugin version between min_version and max_version is ok
for this errbot.
Raises IncompatiblePluginException if not.
"""
name, min_version, max_version = (
plugin_info.name,
plugin_info.errbot_minversion,
plugin_info.errbot_maxversion,
)
current_version = version2tuple(VERSION)
if min_version and min_version > current_version:
raise IncompatiblePluginException(
f"The plugin {name} asks for Errbot with a minimal version of "
f"{min_version} while Errbot is version {VERSION}."
)
if max_version and max_version < current_version:
raise IncompatiblePluginException(
f"The plugin {name} asks for Errbot with a maximum version of {max_version} "
f"while Errbot is version {VERSION}"
)
# Storage names
CONFIGS = "configs"
BL_PLUGINS = "bl_plugins"
class TopologicalSorter(BaseTopologicalSorter):
def find_cycle(self):
"""Wraps private method as public one."""
return self._find_cycle()
class BotPluginManager(StoreMixin):
def __init__(
self,
storage_plugin: StoragePluginBase,
extra_plugin_dir: Optional[str],
autoinstall_deps: bool,
core_plugins: Tuple[str, ...],
plugin_instance_callback: PluginInstanceCallback,
plugins_callback_order: Tuple[Optional[str], ...],
):
"""
Creates a Plugin manager
:param storage_plugin: the plugin used to store to config for this manager
:param extra_plugin_dir: an extra directory to search for plugins
:param autoinstall_deps: if True, will install also the plugin deps from requirements.txt
:param core_plugins: the list of core plugin that will be started
:param plugin_instance_callback: the callback to instantiate a plugin (to inject the dependency on the bot)
:param plugins_callback_order: the order on which the plugins will be callbacked
"""
super().__init__()
self.autoinstall_deps: bool = autoinstall_deps
self._extra_plugin_dir: str = extra_plugin_dir
self._plugin_instance_callback: PluginInstanceCallback = (
plugin_instance_callback
)
self.core_plugins: Tuple[str, ...] = core_plugins
# Make sure there is a 'None' entry in the callback order, to include
# any plugin not explicitly ordered.
self.plugins_callback_order = plugins_callback_order
if None not in self.plugins_callback_order:
self.plugins_callback_order += (None,)
self.plugin_infos: Dict[str, PluginInfo] = {}
self.plugins: Dict[str, BotPlugin] = {}
self.flow_infos: Dict[str, PluginInfo] = {}
self.flows: Dict[str, Flow] = {}
self.plugin_places = []
self.open_storage(storage_plugin, "core")
if CONFIGS not in self:
self[CONFIGS] = {}
def get_plugin_obj_by_name(self, name: str) -> BotPlugin:
return self.plugins.get(name, None)
def reload_plugin_by_name(self, name: str) -> None:
"""
Completely reload the given plugin, including reloading of the module's code
:throws PluginActivationException: needs to be taken care of by the callers.
"""
plugin = self.plugins[name]
plugin_info = self.plugin_infos[name]
if plugin.is_activated:
self.deactivate_plugin(name)
base_name = ".".join(plugin.__module__.split(".")[:-1])
classes = plugin_info.load_plugin_classes(base_name, BotPlugin)
_, new_class = classes[0]
plugin.__class__ = new_class
self.activate_plugin(name)
def _install_potential_package_dependencies(
self, path: Path, feedback: Dict[Path, str]
) -> None:
req_path = path / "requirements.txt"
if req_path.exists():
log.info("Checking package dependencies from %s.", req_path)
if self.autoinstall_deps:
exc_info = install_packages(req_path)
if exc_info is not None:
typ, value, trace = exc_info
feedback[path] = (
f'{typ}: {value}\n{"".join(traceback.format_tb(trace))}'
)
else:
msg, _ = check_dependencies(req_path)
if msg and path not in feedback: # favor the first error.
feedback[path] = msg
def _is_excluded_core_plugin(self, plugin_info: PluginInfo) -> bool:
"""Check if a plugin should be excluded based on the CORE_PLUGINS config directive"""
if (
plugin_info
and self.core_plugins
and plugin_info.core
and (plugin_info.name not in self.core_plugins)
):
return True
else:
return False
def _load_plugins_generic(
self,
path: Path,
extension: str,
base_module_name,
baseclass: Type,
dest_dict: Dict[str, Any],
dest_info_dict: Dict[str, Any],
feedback: Dict[Path, str],
):
self._install_potential_package_dependencies(path, feedback)
plugfiles = path.glob("**/*." + extension)
for plugfile in plugfiles:
try:
plugin_info = PluginInfo.load(plugfile)
name = plugin_info.name
if name in dest_info_dict:
log.warning("Plugin %s already loaded.", name)
continue
# save the plugin_info for ref.
dest_info_dict[name] = plugin_info
# Skip the core plugins not listed in CORE_PLUGINS if CORE_PLUGINS is defined.
if self._is_excluded_core_plugin(plugin_info):
log.debug(
"%s plugin will not be loaded because it's not listed in CORE_PLUGINS",
name,
)
continue
plugin_classes = plugin_info.load_plugin_classes(
base_module_name, baseclass
)
if not plugin_classes:
feedback[path] = f"Did not find any plugin in {path}."
continue
if len(plugin_classes) > 1:
# TODO: This is something we can support as "subplugins" or something similar.
feedback[path] = (
"Contains more than one plugin, only one will be loaded."
)
# instantiate the plugin object.
_, clazz = plugin_classes[0]
dest_dict[name] = self._plugin_instance_callback(name, clazz)
except Exception:
feedback[path] = traceback.format_exc()
def _load_plugins(self) -> Dict[Path, str]:
feedback = {}
for path in self.plugin_places:
self._load_plugins_generic(
path,
"plug",
"errbot.plugins",
BotPlugin,
self.plugins,
self.plugin_infos,
feedback,
)
self._load_plugins_generic(
path,
"flow",
"errbot.flows",
BotFlow,
self.flows,
self.flow_infos,
feedback,
)
return feedback
def update_plugin_places(self, path_list: str) -> Dict[Path, str]:
"""
This updates where this manager is trying to find plugins and try to load newly found ones.
:param path_list: the path list where to search for plugins.
:return: the feedback for any specific path in case of error.
"""
ep = entry_point_plugins(group="errbot.plugins")
repo_roots = (CORE_PLUGINS, self._extra_plugin_dir, path_list, ep)
all_roots = collect_roots(repo_roots)
log.debug("New entries added to sys.path:")
for entry in all_roots:
if entry not in sys.path:
log.debug(entry)
sys.path.append(entry)
# so plugins can relatively import their repos
_ensure_sys_path_contains(repo_roots)
self.plugin_places = [Path(root) for root in all_roots]
return self._load_plugins()
def get_all_active_plugins(self) -> List[BotPlugin]:
"""This returns the list of plugins in the callback ordered defined from the config."""
all_plugins = []
for name in self.plugins_callback_order:
# None is a placeholder for any plugin not having a defined order
if name is None:
all_plugins += [
plugin
for name, plugin in self.plugins.items()
if name not in self.plugins_callback_order and plugin.is_activated
]
else:
plugin = self.plugins[name]
if plugin.is_activated:
all_plugins.append(plugin)
return all_plugins
def get_all_active_plugin_names(self) -> List[str]:
return [name for name, plugin in self.plugins.items() if plugin.is_activated]
def get_all_plugin_names(self) -> List[str]:
return self.plugins.keys()
def get_plugin_by_path(self, path: str) -> Optional[str]:
for name, pi in self.plugin_infos.items():
if str(pi.location.parent) == path:
return self.plugins[name]
def get_plugins_by_path(self, path: str):
for name, pi in self.plugin_infos.items():
if str(pi.location.parent) == path:
yield self.plugins[name]
def deactivate_all_plugins(self) -> None:
for name in self.get_all_active_plugin_names():
self.deactivate_plugin(name)
# plugin blacklisting management
def get_blacklisted_plugin(self) -> List:
return self.get(BL_PLUGINS, [])
def is_plugin_blacklisted(self, name: str) -> bool:
return name in self.get_blacklisted_plugin()
def blacklist_plugin(self, name: str) -> str:
if self.is_plugin_blacklisted(name):
logging.warning("Plugin %s is already blacklisted.", name)
return f"Plugin {name} is already blacklisted."
self[BL_PLUGINS] = self.get_blacklisted_plugin() + [name]
log.info("Plugin %s is now blacklisted.", name)
return f"Plugin {name} is now blacklisted."
def unblacklist_plugin(self, name: str) -> str:
if not self.is_plugin_blacklisted(name):
logging.warning("Plugin %s is not blacklisted.", name)
return f"Plugin {name} is not blacklisted."
plugin = self.get_blacklisted_plugin()
plugin.remove(name)
self[BL_PLUGINS] = plugin
log.info("Plugin %s removed from blacklist.", name)
return f"Plugin {name} removed from blacklist."
# configurations management
def get_plugin_configuration(self, name: str) -> Optional[Any]:
configs = self[CONFIGS]
if name not in configs:
return None
return configs[name]
def set_plugin_configuration(self, name: str, obj: Any):
# TODO: port to with statement
configs = self[CONFIGS]
configs[name] = obj
self[CONFIGS] = configs
def activate_non_started_plugins(self) -> str:
"""
Activates all plugins that are not activated, respecting its dependencies.
:return: Empty string if no problem occurred or a string explaining what went wrong.
"""
log.info("Activate bot plugins...")
errors = ""
for name in self.get_plugins_activation_order():
# We need both the plugin and the corresponding PluginInfo to check if we need to skip an excluded core plugin
plugin_info = self.plugin_infos.get(name)
plugin = self.plugins.get(name)
try:
if self.is_plugin_blacklisted(name):
errors += (
f"Notice: {plugin.name} is blacklisted, "
f'use "{self.plugins["Help"]._bot.prefix}plugin unblacklist {name}" to unblacklist it.\n'
)
continue
elif self._is_excluded_core_plugin(plugin_info):
log.debug(
"%s plugin will not be activated because it's excluded from CORE_PLUGINS",
name,
)
continue
if not plugin.is_activated:
log.info("Activate plugin: %s.", name)
self.activate_plugin(name)
except Exception as e:
log.exception("Error loading %s.", name)
errors += f"Error: {name} failed to activate: {e}.\n"
log.debug("Activate flow plugins ...")
for name, flow in self.flows.items():
try:
if not flow.is_activated:
log.info("Activate flow: %s", name)
self.activate_flow(name)
except Exception as e:
log.exception(f"Error loading flow {name}.")
errors += f"Error: flow {name} failed to start: {e}.\n"
return errors
def get_plugins_activation_order(self) -> List[str]:
"""
Calculate plugin activation order, based on their dependencies.
:return: list of plugin names, in the best order to start them.
"""
plugins_graph = {
name: set(info.dependencies) for name, info in self.plugin_infos.items()
}
plugins_in_cycle = set()
while True:
plugins_sorter = TopologicalSorter(plugins_graph)
try:
# Return plugins which are part of a circular dependency at the end,
# the rest of the code expects to have all plugins returned
return list(plugins_sorter.static_order()) + list(plugins_in_cycle)
except CycleError:
# Remove cycle from the graph, and
cycle = set(plugins_sorter.find_cycle())
plugins_in_cycle.update(cycle)
for plugin_name in cycle:
plugins_graph.pop(plugin_name)
def _activate_plugin(self, plugin: BotPlugin, plugin_info: PluginInfo) -> None:
"""
Activate a specific plugin with no check.
"""
if plugin.is_activated:
raise Exception("Internal Error, invalid activated state.")
name = plugin.name
try:
config = self.get_plugin_configuration(name)
if plugin.get_configuration_template() is not None and config is not None:
log.debug("Checking configuration for %s...", name)
plugin.check_configuration(config)
log.debug("Configuration for %s checked OK.", name)
plugin.configure(config) # even if it is None we pass it on
except Exception as ex:
log.exception(
"Something is wrong with the configuration of the plugin %s", name
)
plugin.config = None
raise PluginConfigurationException(str(ex))
try:
add_plugin_templates_path(plugin_info)
populate_doc(plugin, plugin_info)
plugin.activate()
route(plugin)
plugin.callback_connect()
except Exception:
log.error("Plugin %s failed at activation stage, deactivating it...", name)
self.deactivate_plugin(name)
raise
def activate_flow(self, name: str) -> None:
if name not in self.flows:
raise PluginActivationException(f"Could not find the flow named {name}.")
flow = self.flows[name]
if flow.is_activated:
raise PluginActivationException(f"Flow {name} is already active.")
flow.activate()
def deactivate_flow(self, name: str) -> None:
flow = self.flows[name]
if not flow.is_activated:
raise PluginActivationException(f"Flow {name} is already inactive.")
flow.deactivate()
def activate_plugin(self, name: str) -> None:
"""
Activate a plugin with its dependencies.
"""
try:
if name not in self.plugins:
raise PluginActivationException(
f"Could not find the plugin named {name}."
)
plugin = self.plugins[name]
if plugin.is_activated:
raise PluginActivationException(f"Plugin {name} already activate.")
plugin_info = self.plugin_infos[name]
if not check_python_plug_section(plugin_info):
return None
check_errbot_version(plugin_info)
dep_track = set()
depends_on = self._activate_plugin_dependencies(name, dep_track)
plugin.dependencies = depends_on
self._activate_plugin(plugin, plugin_info)
except PluginActivationException:
raise
except Exception as e:
log.exception(f"Error loading {name}.")
raise PluginActivationException(f"{name} failed to start : {e}.")
def _activate_plugin_dependencies(
self, name: str, dep_track: Set[str]
) -> List[str]:
plugin_info = self.plugin_infos[name]
dep_track.add(name)
depends_on = plugin_info.dependencies
for dep_name in depends_on:
if dep_name in dep_track:
raise PluginActivationException(
f'Circular dependency in the set of plugins ({", ".join(dep_track)})'
)
if dep_name not in self.plugins:
raise PluginActivationException(
f"Unknown plugin dependency {dep_name}."
)
dep_plugin = self.plugins[dep_name]
dep_plugin_info = self.plugin_infos[dep_name]
if not dep_plugin.is_activated:
log.debug(
"%s depends on %s and %s is not activated. Activating it ...",
name,
dep_name,
dep_name,
)
sub_depends_on = self._activate_plugin_dependencies(dep_name, dep_track)
dep_plugin.dependencies = sub_depends_on
self._activate_plugin(dep_plugin, dep_plugin_info)
return depends_on
def deactivate_plugin(self, name: str) -> None:
plugin = self.plugins[name]
if not plugin.is_activated:
log.warning("Plugin already deactivated, ignore.")
return
plugin_info = self.plugin_infos[name]
plugin.deactivate()
remove_plugin_templates_path(plugin_info)
def remove_plugin(self, plugin: BotPlugin) -> None:
"""
Deactivate and remove a plugin completely.
:param plugin: the plugin to remove
:return:
"""
# First deactivate it if it was activated
if plugin.is_activated:
self.deactivate_plugin(plugin.name)
del self.plugins[plugin.name]
del self.plugin_infos[plugin.name]
def remove_plugins_from_path(self, root: str) -> None:
"""
Remove all the plugins that are in the filetree pointed by root.
"""
old_plugin_infos = deepcopy(self.plugin_infos)
for name, pi in old_plugin_infos.items():
if str(pi.location).startswith(root):
self.remove_plugin(self.plugins[name])
def shutdown(self) -> None:
log.info("Shutdown.")
self.close_storage()
log.info("Bye.")
def __hash__(self):
# Ensures this class (and subclasses) are hashable.
# Presumably the use of mixins causes __hash__ to be
# None otherwise.
return int(id(self))
| 24,665
|
Python
|
.py
| 561
| 33.012478
| 122
| 0.599167
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,143
|
config-template.py
|
errbotio_errbot/errbot/config-template.py
|
##########################################################################
# #
# This is the config-template for Err. This file should be copied and #
# renamed to config.py, then modified as you see fit to run Errbot #
# the way you like it. #
# #
# As this is a regular Python file, note that you can do variable #
# assignments and the likes as usual. This can be useful for example if #
# you use the same values in multiple places. #
# #
# Note: Various config options require a tuple to be specified, even #
# when you are configuring only a single value. An example of this is #
# the BOT_ADMINS option. Make sure you use a valid tuple here, even if #
# you are only configuring a single item, else you will get errors. #
# (So don't forget the trailing "," in these cases) #
# #
##########################################################################
import logging
##########################################################################
# Core Errbot configuration #
##########################################################################
# BACKEND selection.
# This configures the type of chat server you wish to use Errbot with.
#
# The current choices:
# Debug backends to test your plugins manually:
# "Text" - on the text console
# Commercial backends:
# "Slack" - see https://slack.com/
# "Gitter" - see https://gitter.im/ (follow instructions from https://github.com/errbotio/err-backend-gitter)
# Open protocols:
# "TOX" - see https://tox.im/ (follow instructions from https://github.com/errbotio/err-backend-tox)
# "IRC" - for classic IRC or bridged services like https://gitter.im
# "XMPP" - the Extensible Messaging and Presence Protocol (https://xmpp.org/)
# "Telegram" - cloud-based mobile and desktop messaging app with a focus
# on security and speed. (https://telegram.org/)
# BACKEND = "Text" # defaults to Text
# STORAGE selection.
# This configures the type of persistence you wish to use Errbot with.
#
# The current choices:
# Debug:
# "Memory" - local memory storage to test your bot in memory:
# Filesystem:
# "Shelf" - python shelf (default)
# STORAGE = "Shelf" # defaults to filestorage (python shelf).
# BOT_EXTRA_STORAGE_PLUGINS_DIR = None # extra search path to find custom storage plugins
# The location where all of Err's data should be stored. Make sure to set
# this to a directory that is writable by the user running the bot.
BOT_DATA_DIR = "/var/lib/err"
### Repos and plugins config.
# Set this to change from where errbot gets its installable plugin list.
# By default it gets the index from errbot.io which is a file generated by tools/plugin-gen.py.
# BOT_PLUGIN_INDEXES = "https://errbot.io/repos.json"
#
# You can also specify a local file:
# BOT_PLUGIN_INDEXES = "tools/repos.json"
#
# Or a list. note: if some plugins exists in 2 lists, only the first hit will be taken into account.
# BOT_PLUGIN_INDEXES = ("/data/repos.json", "https://my.private.tld/errbot/myrepos.json")
# Set this to a directory on your system where you want to load extra
# plugins from, which is useful mostly if you want to develop a plugin
# locally before publishing it. Note that you can specify only a single
# directory, however you are free to create subdirectories with multiple
# plugins inside this directory.
BOT_EXTRA_PLUGIN_DIR = None
# If you use an external backend as a plugin,
# this is where you tell Errbot where to find it.
# BOT_EXTRA_BACKEND_DIR = "/opt/errbackends"
# If you want only a subset of the core plugins that are bundled with errbot, you can specify them here.
# CORE_PLUGINS = None # This is default, all core plugins.
# For example CORE_PLUGINS = ("ACLs", "Backup", "Help") you get those names from the .plug files Name entry.
# For absolutely no plug: CORE_PLUGINS = ()
# Defines an order in which the plugins are getting their callbacks. Useful if you want to have plugins do
# pre- or post-processing on messages.
# The "None" tuple entry represents all the plugins that aren't to be explicitly ordered. For example, if
# you want "A" to run first, then everything else but "B", then "B", you would use ("A", None, "B").
PLUGINS_CALLBACK_ORDER = (None,)
# Should plugin dependencies be installed automatically? If this is true
# then Errbot will use pip to install any missing dependencies automatically.
#
# If you have installed Errbot in a virtualenv, this will run the equivalent
# of `pip install -r requirements.txt`.
# If no virtualenv is detected, the equivalent of `pip install --user -r
# requirements.txt` is used to ensure the package(s) is/are only installed for
# the user running Err.
# AUTOINSTALL_DEPS = True
# To use your own custom log formatter, uncomment and set BOT_LOG_FORMATTER
# to your formatter instance (inherits from logging.Formatter)
# For information on how to create a logging formatter and what it can do, see
# https://docs.python.org/3/library/logging.html#formatter-objects
# BOT_LOG_FORMATTER =
# The location of the log file. If you set this to None, then logging will
# happen to console only.
BOT_LOG_FILE = BOT_DATA_DIR + "/err.log"
# The verbosity level of logging that is done to the above logfile, and to
# the console. This takes the standard Python logging levels, DEBUG, INFO,
# WARN, ERROR. For more info, see http://docs.python.org/library/logging.html
#
# If you encounter any issues with Err, please set your log level to
# logging.DEBUG and attach a log with your bug report to aid the developers
# in debugging the issue.
BOT_LOG_LEVEL = logging.INFO
# Enable logging to sentry (find out more about sentry at www.getsentry.com).
# You can also separate Flask exceptions by enabling it. This will give more information in sentry
# This is optional and disabled by default.
BOT_LOG_SENTRY = False
BOT_LOG_SENTRY_FLASK = False
SENTRY_DSN = ""
SENTRY_LOGLEVEL = BOT_LOG_LEVEL
SENTRY_EVENTLEVEL = BOT_LOG_LEVEL
# Options that can be passed to sentry_sdk.init() at initialization time
# Note that DSN should be specified via its dedicated config option
# and that the 'integrations' setting cannot be set
# e.g: SENTRY_OPTIONS = {"environment": "production"}
SENTRY_OPTIONS = {}
# Execute commands in asynchronous mode. In this mode, Errbot will spawn 10
# separate threads to handle commands, instead of blocking on each
# single command.
# BOT_ASYNC = True
# Size of the thread pool for the asynchronous mode.
# BOT_ASYNC_POOLSIZE = 10
##########################################################################
# Account and chatroom (MUC) configuration #
##########################################################################
# The identity, or credentials, used to connect to a server
BOT_IDENTITY = {
## Text mode
"username": "@errbot", # The name for the bot
## XMPP (Jabber) mode
# "username": "err@localhost", # The JID of the user you have created for the bot
# "password": "changeme", # The corresponding password for this user
# "server": ("host.domain.tld", 5222), # server override
## Slack mode (comment the others above if using this mode)
# "token": "xoxb-4426949411-aEM7...",
## you can also include the proxy for the SlackClient connection
# "proxies": {"http": "some-http-proxy", "https": "some-https-proxy"}
## Telegram mode (comment the others above if using this mode)
# "token": "103419016:AAbcd1234...",
## IRC mode (Comment the others above if using this mode)
# "nickname": "err-chatbot",
# "username": "err-chatbot", # optional, defaults to nickname if omitted
# "password": None, # optional
# "server": "irc.freenode.net",
# "port": 6667, # optional
# "ssl": False, # optional
# "ipv6": False, # optional
# "nickserv_password": None, # optional
## Optional: Specify an IP address or hostname (vhost), and a
## port, to use when making the connection. Leave port at 0
## if you have no source port preference.
## example: "bind_address": ("my-errbot.io", 0)
# "bind_address": ("localhost", 0),
}
# Set the admins of your bot. Only these users will have access
# to the admin-only commands.
#
# Unix-style glob patterns are supported, so "gbin@localhost"
# would be considered an admin if setting "*@localhost".
BOT_ADMINS = ("gbin@localhost",)
# Set of admins that wish to receive administrative bot notifications.
# BOT_ADMINS_NOTIFICATIONS = ()
# Chatrooms your bot should join on startup. For the IRC backend you
# should include the # sign here. For XMPP rooms that are password
# protected, you can specify another tuple here instead of a string,
# using the format (RoomName, Password).
# CHATROOM_PRESENCE = ("err@conference.server.tld",)
# The FullName, or nickname, your bot should use. What you set here will
# be the nickname that Errbot shows in chatrooms. Note that some XMPP
# implementations are very picky about what name you use.
# CHATROOM_FN = "Errbot"
##########################################################################
# Prefix configuration #
##########################################################################
# Command prefix, the prefix that is expected in front of commands directed
# at the bot.
#
# Note: When writing plugins,you should always use the default "!".
# If the prefix is changed from the default, the help strings will be
# automatically adjusted for you.
#
# BOT_PREFIX = "!"
#
# Uncomment the following and set it to True if you want the prefix to be
# optional for normal chat.
# (Meaning messages sent directly to the bot as opposed to within a MUC)
# BOT_PREFIX_OPTIONAL_ON_CHAT = False
# You might wish to have your bot respond by being called with certain
# names, rather than the BOT_PREFIX above. This option allows you to
# specify alternative prefixes the bot will respond to in addition to
# the prefix above.
# BOT_ALT_PREFIXES = ("Err",)
# If you use alternative prefixes, you might want to allow users to insert
# separators like , and ; between the prefix and the command itself. This
# allows users to refer to your bot like this (Assuming "Err" is in your
# BOT_ALT_PREFIXES):
# "Err, status" or "Err: status"
#
# Note: There's no need to add spaces to the separators here
#
# BOT_ALT_PREFIX_SEPARATORS = (":", ",", ";")
# Continuing on this theme, you might want to permit your users to be
# lazy and not require correct capitalization, so they can do "Err",
# "err" or even "ERR".
# BOT_ALT_PREFIX_CASEINSENSITIVE = True
##########################################################################
# Access controls and message diversion #
##########################################################################
# Access controls, allowing commands to be restricted to specific users/rooms.
# Available filters (you can omit a filter or set it to None to disable it):
# allowusers: Allow command from these users only
# denyusers: Deny command from these users
# allowrooms: Allow command only in these rooms (and direct messages)
# denyrooms: Deny command in these rooms
# allowargs: Allow a command's argument from these users only
# denyargs: Deny a command's argument from these users
# allowprivate: Allow command from direct messages to the bot
# allowmuc: Allow command inside rooms
# Rules listed in ACCESS_CONTROLS_DEFAULT are applied by default and merged
# with any commands found in ACCESS_CONTROLS.
#
# The options allowusers, denyusers, allowrooms and denyrooms, allowargs,
# denyargs support unix-style globbing similar to BOT_ADMINS.
#
# Command names also support unix-style globs and can optionally be restricted
# to a specific plugin by prefixing the command with the name of a plugin,
# separated by a colon. For example, `Health:status` will match the `!status`
# command of the `Health` plugin and `Health:*` will match all commands defined
# by the `Health` plugin.
#
# Please note that the first command match found will be used so if you have
# overlapping patterns you must used an OrderedDict instead of a regular dict:
# https://docs.python.org/3/library/collections.html#collections.OrderedDict
#
# Example:
#
# ACCESS_CONTROLS_DEFAULT = {} # Allow everyone access by default
# ACCESS_CONTROLS = {
# "status": {
# "allowrooms": ("someroom@conference.localhost",),
# },
# "about": {
# "denyusers": ("*@evilhost",),
# "allowrooms": ("room1@conference.localhost", "room2@conference.localhost"),
# },
# "uptime": {"allowusers": BOT_ADMINS},
# "help": {"allowmuc": False},
# "ChatRoom:*": {"allowusers": BOT_ADMINS},
# }
# Uncomment and set this to True to hide the restricted commands from
# the help output.
# HIDE_RESTRICTED_COMMANDS = False
# Uncomment and set this to True to ignore commands from users that have no
# access for these instead of replying with error message.
# HIDE_RESTRICTED_ACCESS = False
# A list of commands which should be responded to in private, even if
# the command was given in a MUC. For example:
# DIVERT_TO_PRIVATE = ("help", "about", "status")
# If all commands are desired, use the specical case "ALL_COMMANDS"
DIVERT_TO_PRIVATE = ()
# A list of commands which should be responded to in a thread if the backend supports it.
# For example:
# DIVERT_TO_THREAD = ("help", "about", "status")
# If all commands are desired, use the specical case "ALL_COMMANDS"
DIVERT_TO_THREAD = ()
# Chat relay
# Can be used to relay one to one message from specific users to the bot
# to MUCs. This can be useful with XMPP notifiers like for example the
# standard Altassian Jira which don't have native support for MUC.
# For example: CHATROOM_RELAY = {"gbin@localhost" : (_TEST_ROOM,)}
CHATROOM_RELAY = {}
# Reverse chat relay
# This feature forwards whatever is said to a specific user.
# It can be useful if you client like gtalk doesn't support MUC correctly
# For example: REVERSE_CHATROOM_RELAY = {_TEST_ROOM : ("gbin@localhost",)}
REVERSE_CHATROOM_RELAY = {}
##########################################################################
# Miscellaneous configuration options #
##########################################################################
# Define the maximum length a single message may be. If a plugin tries to
# send a message longer than this length, it will be broken up into multiple
# shorter messages that do fit.
# MESSAGE_SIZE_LIMIT = 10000
# XMPP TLS certificate verification. In order to validate offered certificates,
# you must supply a path to a file containing certificate authorities. By
# default, "/etc/ssl/certs/ca-certificates.crt" is used, which on most Linux
# systems holds the default system trusted CA certificates. You might need to
# change this depending on your environment. Setting this to None disables
# certificate validation, which can be useful if you have a self-signed
# certificate for example.
# XMPP_CA_CERT_FILE = "/etc/ssl/certs/ca-certificates.crt"
# Influence the security methods used on connection with XMPP-based
# backends. You can use this to work around authentication issues with
# some buggy XMPP servers.
#
# The default is to try anything:
# XMPP_FEATURE_MECHANISMS = {}
# To use only unencrypted plain auth:
# XMPP_FEATURE_MECHANISMS = {
# "use_mech": "PLAIN",
# "unencrypted_plain": True,
# "encrypted_plain": False,
# }
# Modify the default keep-alive interval. By default, Errbot will send
# some whitespace to the XMPP server every 300 seconds to keep the TCP
# connection alive. On some servers, or when running Errbot from behind
# a NAT router, the default might not be fast enough and you will need
# to set it to a lower value.
#
# If you're having issues with your bot getting constantly disconnected,
# try to gradually lower this value until it no longer happens.
# XMPP_KEEPALIVE_INTERVAL = 300
# Modify default settings for IPv6 usage. This key affects the XMPP backend.
# XMPP_USE_IPV6 = False
# XMPP supports some formatting with XEP-0071 (http://www.xmpp.org/extensions/xep-0071.html).
# It is disabled by default because XMPP clients support has been found to be spotty.
# Switch it to True to enable XHTML-IM formatting.
# XMPP_XHTML_IM = False
# XMPP may require a specific ssl protocol version when making connections.
# This option allows the option to change that behavior.
# It uses python's built-in ssl module.
# import ssl
# XMPP_SSL_VERSION = ssl.PROTOCOL_TLSv1_2
# Message rate limiting for the IRC backend. This will delay subsequent
# messages by this many seconds (floats are supported). Setting these
# to a value of 0 effectively disables rate limiting.
# IRC_CHANNEL_RATE = 1 # Regular channel messages
# IRC_PRIVATE_RATE = 1 # Private messages
# IRC_RECONNECT_ON_KICK = 5 # Reconnect back to a channel after a kick (in seconds)
# Put it at None if you don't want the chat to
# reconnect
# IRC_RECONNECT_ON_DISCONNECT = 5 # Reconnect back to a channel after a disconnection (in seconds)
# The pattern to build a user representation from for ACL matches.
# The default is "{nick}!{user}@{host}" which results in "zoni!zoni@ams1.groenen.me"
# for the user zoni connecting from ams1.groenen.me.
# Available substitution variables:
# {nick} -> The nickname of the user
# {user} -> The username of the user
# {host} -> The hostname the user is connecting from
# IRC_ACL_PATTERN = "{nick}!{user}@{host}"
# Allow messages sent in a chatroom to be directed at requester.
# GROUPCHAT_NICK_PREFIXED = False
# Disable table borders, making output more compact (supported only on IRC, Slack and Telegram currently).
# COMPACT_OUTPUT = True
# Disables the logging output in Text mode and only outputs Ansi.
# TEXT_DEMO_MODE = False
# Prevent ErrBot from saying anything if the command is unrecognized.
# SUPPRESS_CMD_NOT_FOUND = False
| 18,339
|
Python
|
.py
| 348
| 51.227011
| 111
| 0.684122
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,144
|
flow.py
|
errbotio_errbot/errbot/flow.py
|
import atexit
import logging
from multiprocessing.pool import ThreadPool
from threading import RLock
from typing import Any, Callable, List, Mapping, Optional, Tuple, Union
from errbot import Message
from errbot.backends.base import Identifier, Room, RoomOccupant
log = logging.getLogger(__name__)
Predicate = Callable[[Mapping[str, Any]], bool]
EXECUTOR_THREADS = (
5 # the maximum number of simultaneous flows in automatic mode at the same time.
)
class FlowNode:
"""
This is a step in a Flow/conversation. It is linked to a specific botcmd and also a "predicate".
The predicate is a function that tells the flow executor if the flow can enter the step without the user
intervention (automatically). The predicates defaults to False.
The predicate is a function that takes one parameter, the context of the conversation.
"""
def __init__(self, command: str = None, hints: bool = True) -> None:
"""
Creates a FlowNone, takes the command to which the Node is linked to.
:param command: the command this Node is linked to. Can only be None if this Node is a Root.
:param hints: hints the users for the next steps in chat.
"""
self.command = command
self.children = [] # (predicate, node)
self.hints = hints
def connect(
self,
node_or_command: Union["FlowNode", str],
predicate: Predicate = lambda _: False,
hints: bool = True,
) -> "FlowNode":
"""
Construct the flow graph by connecting this node to another node or a command.
The predicate is a function that tells the flow executor if the flow can enter the step without the user
intervention (automatically).
:param node_or_command: the node or a string for a command you want to connect this Node to
(this node or command will be the follow up of this one)
:param predicate: function with one parameter, the context, to determine of the flow executor can continue
automatically this flow with no user intervention.
:param hints: hints the user on the next step possible.
:return: the newly created node if you passed a command or the node you gave it to be easily chainable.
"""
node_to_connect_to = (
node_or_command
if isinstance(node_or_command, FlowNode)
else FlowNode(node_or_command, hints=hints)
)
self.children.append((predicate, node_to_connect_to))
return node_to_connect_to
def predicate_for_node(self, node: "FlowNode") -> Optional[Predicate]:
"""
gets the predicate function for the specified child node.
:param node: the child node
:return: the predicate that allows the automatic execution of that node.
"""
for predicate, possible_node in self.children:
if node == possible_node:
return predicate
return None
def __str__(self):
return self.command
class FlowRoot(FlowNode):
"""
This represent the entry point of a flow description.
"""
def __init__(self, name: str, description: str):
"""
:param name: The name of the conversation/flow.
:param description: A human description of what this flow does.
:param hints: Hints for the next steps when triggered.
"""
super().__init__()
self.name = name
self.description = description
self.auto_triggers = set()
self.room_flow = False
def connect(
self,
node_or_command: Union["FlowNode", str],
predicate: Predicate = lambda _: False,
auto_trigger: bool = False,
room_flow: bool = False,
) -> "FlowNode":
"""
:see: FlowNode except fot auto_trigger
:param predicate: :see: FlowNode
:param node_or_command: :see: FlowNode
:param auto_trigger: Flag this root as autotriggering: it will start a flow if this command is executed
in the chat.
:param room_flow: Bind the flow to the room instead of a single person
"""
resp = super().connect(node_or_command, predicate)
if auto_trigger:
self.auto_triggers.add(node_or_command)
self.room_flow = room_flow
return resp
def __str__(self):
return self.name
class _FlowEnd(FlowNode):
def __str__(self):
return "END"
#: Flow marker indicating that the flow ends.
FLOW_END = _FlowEnd()
class InvalidState(Exception):
"""
Raised when the Flow Executor is asked to do something contrary to the contraints it has been given.
"""
pass
class Flow:
"""
This is a live Flow. It keeps context of the conversation (requestor and context).
Context is just a python dictionary representing the state of the conversation.
"""
def __init__(
self, root: FlowRoot, requestor: Identifier, initial_context: Mapping[str, Any]
):
"""
:param root: the root of this flow.
:param requestor: the user requesting this flow.
:param initial_context: any data we already have that could help executing this flow automatically.
"""
self._root = root
self._current_step = self._root
self.ctx = dict(initial_context)
self.requestor = requestor
def next_autosteps(self) -> List[FlowNode]:
"""
Get the next steps that can be automatically executed according to the set predicates.
"""
return [
node
for predicate, node in self._current_step.children
if predicate(self.ctx)
]
def next_steps(self) -> List[FlowNode]:
"""
Get all the possible next steps after this one (predicates statisfied or not).
"""
return [node for predicate, node in self._current_step.children]
def advance(self, next_step: FlowNode, enforce_predicate: bool = True):
"""
Move on along the flow.
:param next_step: Which node you want to move the flow forward to.
:param enforce_predicate: Do you want to check if the predicate is verified for this step or not.
Usually, if it is a manual step, the predicate is irrelevant because the user
will give the missing information as parameters to the command.
"""
if enforce_predicate:
predicate = self._current_step.predicate_for_node(next_step)
if predicate is None:
raise ValueError(f"There is no such children: {next_step}.")
if not predicate(self.ctx):
raise InvalidState(
"It is not possible to advance to this step because its predicate is false."
)
self._current_step = next_step
@property
def name(self) -> str:
"""
Helper property to get the name of the flow.
"""
return self._root.name
@property
def current_step(self) -> FlowNode:
"""
The current step this Flow is waiting on.
"""
return self._current_step
@property
def root(self) -> FlowRoot:
"""
The original flowroot of this flow.
"""
return self._root
def check_identifier(self, identifier: Identifier) -> bool:
is_room = isinstance(self.requestor, Room)
is_room = is_room and isinstance(identifier, RoomOccupant)
is_room = is_room and self.requestor == identifier.room
return is_room or self.requestor == identifier
def __str__(self):
return f"{self._root} ({self.requestor}) with params {dict(self.ctx)}"
class BotFlow:
"""
Defines a Flow plugin ie. a plugin that will define new flows from its methods with the @botflow decorator.
"""
def __init__(self, bot, name=None):
super().__init__()
self._bot = bot
self.is_activated = False
self._name = name
@property
def name(self) -> str:
"""
Get the name of this flow as described in its .plug file.
:return: The flow name.
"""
return self._name
def activate(self) -> None:
"""
Override if you want to do something at initialization phase (don't forget to
super(Gnagna, self).activate())
"""
self._bot.inject_flows_from(self)
self.is_activated = True
def deactivate(self) -> None:
"""
Override if you want to do something at tear down phase (don't forget to super(Gnagna, self).deactivate())
"""
self._bot.remove_flows_from(self)
self.is_activated = False
def get_command(self, command_name: str):
"""
Helper to get a specific command.
"""
self._bot.all_commands.get(command_name, None)
class FlowExecutor:
"""
This is a instance that can monitor and execute flow instances.
"""
def __init__(self, bot):
self._lock = RLock()
self.flow_roots = {}
self.in_flight = []
self._pool = ThreadPool(EXECUTOR_THREADS)
atexit.register(self._pool.close)
self._bot = bot
def add_flow(self, flow: FlowRoot) -> None:
"""
Register a flow with this executor.
"""
with self._lock:
self.flow_roots[flow.name] = flow
def trigger(
self, cmd: str, requestor: Identifier, extra_context=None
) -> Optional[Flow]:
"""
Trigger workflows that may have command cmd as a auto_trigger or an in flight flow waiting for command.
This assume cmd has been correctly executed.
:param requestor: the identifier of the person who started this flow
:param cmd: the command that has just been executed.
:param extra_context: extra context from the current conversation
:returns: The flow it triggered or None if none were matching.
"""
flow, next_step = self.check_inflight_flow_triggered(cmd, requestor)
if not flow:
flow, next_step = self._check_if_new_flow_is_triggered(cmd, requestor)
if not flow:
return None
flow.advance(next_step, enforce_predicate=False)
if extra_context:
flow.ctx = dict(extra_context)
self._enqueue_flow(flow)
return flow
def check_inflight_already_running(self, user: Identifier) -> bool:
"""
Check if user is already running a flow.
:param user: the user
"""
with self._lock:
for flow in self.in_flight:
if flow.requestor == user:
return True
return False
def check_inflight_flow_triggered(
self, cmd: str, user: Identifier
) -> Tuple[Optional[Flow], Optional[FlowNode]]:
"""
Check if a command from a specific user was expected in one of the running flow.
:param cmd: the command that has just been executed.
:param user: the identifier of the person who started this flow
:returns: The name of the flow it triggered or None if none were matching."""
log.debug("Test if the command %s is a trigger for an inflight flow ...", cmd)
# TODO: What if 2 flows wait for the same command ?
with self._lock:
for flow in self.in_flight:
if flow.check_identifier(user):
log.debug("Requestor has a flow %s in flight", flow.name)
for next_step in flow.next_steps():
if next_step.command == cmd:
log.debug(
"Requestor has a flow in flight waiting for this command!"
)
return flow, next_step
log.debug("No in flight flows matched.")
return None, None
def _check_if_new_flow_is_triggered(
self, cmd: str, user: Identifier
) -> Tuple[Optional[Flow], Optional[FlowNode]]:
"""
Trigger workflows that may have command cmd as a auto_trigger..
This assume cmd has been correctly executed.
:param cmd: the command that has just been executed.
:param user: the identifier of the person who started this flow
:returns: The name of the flow it triggered or None if none were matching.
"""
log.debug("Test if the command %s is an auto-trigger for any flow ...", cmd)
with self._lock:
for name, flow_root in self.flow_roots.items():
if (
cmd in flow_root.auto_triggers
and not self.check_inflight_already_running(user)
):
log.debug(
"Flow %s has been auto-triggered by the command %s by user %s",
name,
cmd,
user,
)
return self._create_new_flow(flow_root, user, cmd)
return None, None
@staticmethod
def _create_new_flow(
flow_root, requestor: Identifier, initial_command
) -> Tuple[Optional[Flow], Optional[FlowNode]]:
"""
Helper method to create a new FLow.
"""
empty_context = {}
flow = Flow(flow_root, requestor, empty_context)
for possible_next_step in flow.next_steps():
if possible_next_step.command == initial_command:
# The predicate is good as we just executed manually the command.
return flow, possible_next_step
return None, None
def start_flow(
self, name: str, requestor: Identifier, initial_context: Mapping[str, Any]
) -> Flow:
"""
Starts the execution of a Flow.
"""
if name not in self.flow_roots:
raise ValueError(f"Flow {name} doesn't exist")
if self.check_inflight_already_running(requestor):
raise ValueError(f"User {str(requestor)} is already running a flow.")
flow_root = self.flow_roots[name]
identity = requestor
if isinstance(requestor, RoomOccupant) and flow_root.room_flow:
identity = requestor.room
flow = Flow(self.flow_roots[name], identity, initial_context)
self._enqueue_flow(flow)
return flow
def stop_flow(self, name: str, requestor: Identifier) -> Optional[Flow]:
"""
Stops a specific flow. It is a no op if the flow doesn't exist.
Returns the stopped flow if found.
"""
with self._lock:
for flow in self.in_flight:
if flow.name == name and flow.check_identifier(requestor):
log.debug(f"Removing flow {str(flow)}.")
self.in_flight.remove(flow)
return flow
return None
def _enqueue_flow(self, flow: Flow) -> None:
with self._lock:
if flow not in self.in_flight:
self.in_flight.append(flow)
self._pool.apply_async(self.execute, (flow,))
def execute(self, flow: Flow) -> None:
"""
This is where the flow execution happens from one of the thread of the pool.
"""
while True:
autosteps = flow.next_autosteps()
steps = flow.next_steps()
if not steps:
log.debug("Flow ended correctly.Nothing left to do.")
with self._lock:
self.in_flight.remove(flow)
break
if not autosteps and flow.current_step.hints:
possible_next_steps = [
f"You are in the flow **{flow.name}**, you can continue with:\n\n"
]
for step in steps:
cmd = step.command
cmd_fnc = self._bot.all_commands[cmd]
reg_cmd = cmd_fnc._err_re_command
syntax_args = cmd_fnc._err_command_syntax
reg_prefixed = (
cmd_fnc._err_command_prefix_required if reg_cmd else True
)
syntax = self._bot.prefix if reg_prefixed else ""
if not reg_cmd:
syntax += cmd.replace("_", " ")
if syntax_args:
syntax += syntax_args
possible_next_steps.append(f"- {syntax}")
self._bot.send(flow.requestor, "\n".join(possible_next_steps))
break
log.debug(
"Steps triggered automatically %s.",
", ".join(str(node) for node in autosteps),
)
log.debug(
"All possible next steps: %s.", ", ".join(str(node) for node in steps)
)
for autostep in autosteps:
log.debug("Proceeding automatically with step %s", autostep)
if autostep == FLOW_END:
log.debug("This flow ENDED.")
with self._lock:
self.in_flight.remove(flow)
return
try:
msg = Message(frm=flow.requestor, flow=flow)
result = self._bot.commands[autostep.command](msg, None)
log.debug("Step result %s: %s", flow.requestor, result)
except Exception as e:
log.exception("%s errored at %s", flow, autostep)
self._bot.send(
flow.requestor, f'{flow} errored at {autostep} with "{e}"'
)
flow.advance(
autostep
) # TODO: this is only true for a single step, make it forkable.
log.debug("Flow execution suspended/ended normally.")
| 17,964
|
Python
|
.py
| 420
| 31.952381
| 114
| 0.588074
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,145
|
templating.py
|
errbotio_errbot/errbot/templating.py
|
import logging
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
from errbot.plugin_info import PluginInfo
log = logging.getLogger(__name__)
def make_templates_path(root: Path) -> Path:
return root / "templates"
system_templates_path = str(make_templates_path(Path(__file__).parent))
template_path = [system_templates_path]
env = Environment(
loader=FileSystemLoader(template_path),
trim_blocks=True,
keep_trailing_newline=False,
autoescape=True,
)
def tenv() -> Environment:
return env
def add_plugin_templates_path(plugin_info: PluginInfo) -> None:
global env
tmpl_path = make_templates_path(plugin_info.location.parent)
if tmpl_path.exists():
log.debug(
"Templates directory found for %s plugin [%s]", plugin_info.name, tmpl_path
)
template_path.append(str(tmpl_path)) # for webhooks
# Ditch and recreate a new templating environment
env = Environment(loader=FileSystemLoader(template_path), autoescape=True)
return
log.debug(
"No templates directory found for %s plugin in [%s]",
plugin_info.name,
tmpl_path,
)
def remove_plugin_templates_path(plugin_info: PluginInfo) -> None:
global env
tmpl_path = str(make_templates_path(plugin_info.location.parent))
if tmpl_path in template_path:
template_path.remove(tmpl_path)
# Ditch and recreate a new templating environment
env = Environment(loader=FileSystemLoader(template_path), autoescape=True)
| 1,550
|
Python
|
.py
| 40
| 33.3
| 87
| 0.713904
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,146
|
streaming.py
|
errbotio_errbot/errbot/streaming.py
|
import io
import logging
import os
from itertools import repeat, starmap
from threading import Thread
from typing import Callable, Optional
from .backends.base import STREAM_TRANSFER_IN_PROGRESS, STREAM_WAITING_TO_START
CHUNK_SIZE = 4096
log = logging.getLogger(__name__)
def repeatfunc(
func: Callable[..., None], times: Optional[int] = None, *args
): # from the itertools receipes
"""Repeat calls to func with specified arguments.
Example: repeatfunc(random.random)
:param args: params to the function to call.
:param times: number of times to repeat.
:param func: the function to repeatedly call.
"""
if times is None:
return starmap(func, repeat(args))
return starmap(func, repeat(args, times))
class Tee:
"""Tee implements a multi reader / single writer"""
def __init__(self, incoming_stream, clients):
"""clients is a list of objects implementing callback_stream"""
self.incoming_stream = incoming_stream
self.clients = clients
def start(self) -> Thread:
"""starts the transfer asynchronously"""
t = Thread(target=self.run)
t.start()
return t
def run(self):
"""streams to all the clients synchronously"""
nb_clients = len(self.clients)
pipes = [
(io.open(r, "rb"), io.open(w, "wb"))
for r, w in repeatfunc(os.pipe, nb_clients)
]
streams = [self.incoming_stream.clone(pipe[0]) for pipe in pipes]
def streamer(index):
try:
self.clients[index].callback_stream(streams[index])
if streams[index].status == STREAM_WAITING_TO_START:
streams[index].reject()
plugin = self.clients[index].name
logging.warning(
"%s did not accept nor reject the incoming file transfer",
plugin,
)
logging.warning("I reject it as a fallback.")
except Exception as _:
# internal error, mark the error.
streams[index].error()
else:
if streams[index].status == STREAM_TRANSFER_IN_PROGRESS:
# if the plugin didn't do it by itself, mark the transfer as a success.
streams[index].success()
# stop the stream if the callback_stream returns
read, write = pipes[index]
pipes[index] = (None, None) # signal the main thread to stop streaming
read.close()
write.close()
threads = [Thread(target=streamer, args=(i,)) for i in range(nb_clients)]
for thread in threads:
thread.start()
while True:
if self.incoming_stream.closed:
break
chunk = self.incoming_stream.read(CHUNK_SIZE)
log.debug("dispatch %d bytes", len(chunk))
if not chunk:
break
for _, w in pipes:
if w:
w.write(chunk)
log.debug("EOF detected")
for r, w in pipes:
if w:
w.close() # close should flush too
# we want to be sure that if we join on the main thread,
# everything is either fully transfered or errored
for thread in threads:
thread.join()
| 3,395
|
Python
|
.py
| 84
| 29.75
| 91
| 0.581791
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,147
|
cli.py
|
errbotio_errbot/errbot/cli.py
|
#!/usr/bin/env python
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import argparse
import ast
import logging
import os
import sys
from os import W_OK, access, getcwd, path, sep
from pathlib import Path
from platform import system
from errbot.bootstrap import CORE_BACKENDS
from errbot.logs import root_logger
from errbot.plugin_wizard import new_plugin_wizard
from errbot.utils import collect_roots, entry_point_plugins
from errbot.version import VERSION
log = logging.getLogger(__name__)
# noinspection PyUnusedLocal
def debug(sig, frame) -> None:
"""Interrupt running process, and provide a python prompt for
interactive debugging."""
d = {"_frame": frame} # Allow access to frame object.
d.update(frame.f_globals) # Unless shadowed by global
d.update(frame.f_locals)
i = code.InteractiveConsole(d)
message = "Signal received : entering python shell.\nTraceback:\n"
message += "".join(traceback.format_stack(frame))
i.interact(message)
ON_WINDOWS = system() == "Windows"
if not ON_WINDOWS:
import code
import signal
import traceback
from daemonize import Daemonize
signal.signal(signal.SIGUSR1, debug) # Register handler for debugging
def get_config(config_path: str):
config_fullpath = config_path
if not path.exists(config_fullpath):
log.error(f"I cannot find the config file {config_path}.")
log.error("You can change this path with the -c parameter see --help")
log.info(
f'You can use the template {os.path.realpath(os.path.join(__file__, os.pardir, "config-template.py"))}'
f" as a base and copy it to {config_path}."
)
log.info("You can then customize it.")
exit(-1)
try:
config = __import__(path.splitext(path.basename(config_fullpath))[0])
log.info("Config check passed...")
return config
except Exception:
log.exception(
f"I could not import your config from {config_fullpath}, please check the error below..."
)
exit(-1)
def _read_dict() -> dict:
from collections.abc import Mapping
new_dict = ast.literal_eval(sys.stdin.read())
if not isinstance(new_dict, Mapping):
raise ValueError(
f"A dictionary written in python is needed from stdin. "
f"Type={type(new_dict)}, Value = {repr(new_dict)}."
)
return new_dict
def main() -> None:
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"]).resolve()
)
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"
extra_backend_plugin_dir = base_dir / "backend-plugins"
example_plugin_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)
extra_backend_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),
extra_backend_plugin_dir=str(extra_backend_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]
ep = entry_point_plugins(group="errbot.backend_plugins")
extra_backend.extend(ep)
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")
if __name__ == "__main__":
main()
| 13,691
|
Python
|
.py
| 338
| 31.523669
| 115
| 0.61165
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,148
|
logs.py
|
errbotio_errbot/errbot/logs.py
|
import inspect
import logging
import sys
from typing import Optional
COLORS = {
"DEBUG": "cyan",
"INFO": "green",
"WARNING": "yellow",
"ERROR": "red",
"CRITICAL": "red",
}
NO_COLORS = {
"DEBUG": "",
"INFO": "",
"WARNING": "",
"ERROR": "",
"CRITICAL": "",
}
def ispydevd():
for frame in inspect.stack():
if frame[1].endswith("pydevd.py"):
return True
return False
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
pydev = ispydevd()
stream = sys.stdout if pydev else sys.stderr
isatty = (
pydev or stream.isatty()
) # force isatty if we are under pydev because it supports coloring anyway.
console_hdlr = logging.StreamHandler(stream)
def get_log_colors(theme_color: Optional[str] = None) -> str:
"""Return a tuple containing the log format string and a log color dict"""
if theme_color == "light":
text_color_theme = "white"
elif theme_color == "dark":
text_color_theme = "black"
else: # Anything else produces nocolor
return "%(name)-25.25s%(reset)s %(message)s%(reset)s", NO_COLORS
return f"%(name)-25.25s%(reset)s %({text_color_theme})s%(message)s%(reset)s", COLORS
def format_logs(
formatter: Optional[logging.Formatter] = None, theme_color: Optional[str] = None
) -> None:
"""
You may either use the formatter parameter to provide your own
custom formatter, or the theme_color parameter to use the
built in color scheme formatter.
"""
if formatter:
console_hdlr.setFormatter(formatter)
# if isatty and not True:
elif isatty:
from colorlog import ColoredFormatter # noqa
log_format, colors_dict = get_log_colors(theme_color)
color_formatter = ColoredFormatter(
"%(asctime)s %(log_color)s%(levelname)-8s%(reset)s " + log_format,
datefmt="%H:%M:%S",
reset=True,
log_colors=colors_dict,
)
console_hdlr.setFormatter(color_formatter)
else:
console_hdlr.setFormatter(
logging.Formatter("%(asctime)s %(levelname)-8s %(name)-25s %(message)s")
)
root_logger.addHandler(console_hdlr)
| 2,197
|
Python
|
.py
| 66
| 27.787879
| 88
| 0.645892
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,149
|
utils.py
|
errbotio_errbot/errbot/utils.py
|
import collections
import fnmatch
import inspect
import logging
import os
import re
import sys
import time
from functools import wraps
from platform import system
from typing import List, Tuple, Union
import pkg_resources
from dulwich import porcelain
log = logging.getLogger(__name__)
ON_WINDOWS = system() == "Windows"
PLUGINS_SUBDIR = "plugins"
# noinspection PyPep8Naming
class deprecated:
"""deprecated decorator. emits a warning on a call on an old method and call the new method anyway"""
def __init__(self, new=None):
self.new = new
def __call__(self, old):
@wraps(old)
def wrapper(*args, **kwds):
frame = inspect.getframeinfo(inspect.currentframe().f_back)
msg = f"{frame.filename}: {frame.lineno}: "
if len(args):
pref = (
type(args[0]).__name__ + "."
) # TODO might break for individual methods
else:
pref = ""
msg += f"call to the deprecated {pref}{old.__name__}"
if self.new is not None:
if type(self.new) is property:
msg += (
f"... use the property {pref}{self.new.fget.__name__} instead"
)
else:
msg += f"... use {pref}{self.new.__name__} instead"
msg += "."
logging.warning(msg)
if self.new:
if type(self.new) is property:
return self.new.fget(*args, **kwds)
return self.new(*args, **kwds)
return old(*args, **kwds)
wrapper.__name__ = old.__name__
wrapper.__doc__ = old.__doc__
wrapper.__dict__.update(old.__dict__)
return wrapper
def format_timedelta(timedelta) -> str:
total_seconds = timedelta.seconds + (86400 * timedelta.days)
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
if hours == 0 and minutes == 0:
return f"{seconds:d} seconds"
elif not hours:
return f"{minutes:d} minutes"
elif not minutes:
return f"{hours:d} hours"
return f"{hours:d} hours and {minutes:d} minutes"
INVALID_VERSION_EXCEPTION = 'version %s in not in format "x.y.z" or "x.y.z-{beta,alpha,rc1,rc2...}" for example "1.2.2"'
def version2tuple(version: str) -> Tuple:
vsplit = version.split("-")
if len(vsplit) == 2:
main, sub = vsplit
if sub == "alpha":
sub_int = -1
elif sub == "beta":
sub_int = 0
elif sub.startswith("rc"):
sub_int = int(sub[2:])
else:
raise ValueError(INVALID_VERSION_EXCEPTION % version)
elif len(vsplit) == 1:
main = vsplit[0]
sub_int = sys.maxsize
else:
raise ValueError(INVALID_VERSION_EXCEPTION % version)
response = [int(el) for el in main.split(".")]
response.append(sub_int)
if len(response) != 4:
raise ValueError(INVALID_VERSION_EXCEPTION % version)
return tuple(response)
REMOVE_EOL = re.compile(r"\n")
REINSERT_EOLS = re.compile(r"</p>|</li>|<br/>", re.I)
ZAP_TAGS = re.compile(r"<[^>]+>")
def rate_limited(min_interval: Union[float, int]):
"""
decorator to rate limit a function.
:param min_interval: minimum interval allowed between 2 consecutive calls.
:return: the decorated function
"""
def decorate(func):
last_time_called = [0.0]
def rate_limited_function(*args, **kargs):
elapsed = time.time() - last_time_called[0]
log.debug("Elapsed %f since last call", elapsed)
left_to_wait = min_interval - elapsed
if left_to_wait > 0:
log.debug("Wait %f due to rate limiting...", left_to_wait)
time.sleep(left_to_wait)
ret = func(*args, **kargs)
last_time_called[0] = time.time()
return ret
return rate_limited_function
return decorate
def split_string_after(str_: str, n: int) -> str:
"""Yield chunks of length `n` from the given string
:param n: length of the chunks.
:param str_: the given string.
"""
for start in range(0, max(len(str_), 1), n):
yield str_[start : start + n]
def find_roots(path: str, file_sig: str = "*.plug") -> List:
"""Collects all the paths from path recursively that contains files of type `file_sig`.
:param path:
a base path to walk from
:param file_sig:
the file pattern to look for
:return: a list of paths
"""
roots = list() # you can have several .plug per directory.
for root, dirnames, filenames in os.walk(path, followlinks=True):
for filename in fnmatch.filter(filenames, file_sig):
dir_to_add = os.path.dirname(os.path.join(root, filename))
relative = os.path.relpath(
os.path.realpath(dir_to_add), os.path.realpath(path)
)
for subelement in relative.split(os.path.sep):
# if one of the element is just a relative construct, it is ok to continue inspecting it.
if subelement in (".", ".."):
continue
# if it is an hidden directory or a python temp directory, just ignore it.
if subelement.startswith(".") or subelement == "__pycache__":
log.debug("Ignore %s.", dir_to_add)
break
else:
roots.append(dir_to_add)
return list(collections.OrderedDict.fromkeys(roots))
def collect_roots(base_paths: List, file_sig: str = "*.plug") -> List:
"""Collects all the paths from base_paths recursively that contains files of type `file_sig`.
:param base_paths:
a list of base paths to walk from
elements can be a string or a list/tuple of strings
:param file_sig:
the file pattern to look for
:return: a list of paths
"""
result = list()
for path_or_list in base_paths:
if isinstance(path_or_list, (list, tuple)):
result.extend(collect_roots(base_paths=path_or_list, file_sig=file_sig))
elif path_or_list is not None:
result.extend(find_roots(path_or_list, file_sig))
return list(collections.OrderedDict.fromkeys(result))
def entry_point_plugins(group):
paths = []
for entry_point in pkg_resources.iter_entry_points(group):
ep = next(pkg_resources.iter_entry_points(group, entry_point.name))
paths.append(f"{ep.dist.module_path}/{entry_point.module_name}")
return paths
def global_restart() -> None:
"""Restart the current process."""
python = sys.executable
os.execl(python, python, *sys.argv)
def git_clone(url: str, path: str) -> None:
"""
Clones a repository from git url to path
"""
if not os.path.exists(path):
os.makedirs(path)
repo = porcelain.clone(url, path)
config = repo.get_config()
config.set(("branch", "master"), "remote", "origin")
config.set(("branch", "master"), "merge", "refs/heads/master")
config.write_to_path()
def git_pull(repo_path: str) -> None:
"""
Does a git pull on a repository
"""
porcelain.pull(repo_path)
def git_tag_list(repo_path: str) -> List[str]:
"""
Lists git tags on a cloned repo
"""
porcelain.tag_list(repo_path)
| 7,410
|
Python
|
.py
| 188
| 31.159574
| 120
| 0.600056
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,150
|
backend_plugin_manager.py
|
errbotio_errbot/errbot/backend_plugin_manager.py
|
import logging
import sys
from pathlib import Path
from typing import Any, Iterator, List, Type, Union
from errbot.plugin_info import PluginInfo
from .utils import collect_roots, entry_point_plugins
log = logging.getLogger(__name__)
class PluginNotFoundException(Exception):
pass
def enumerate_backend_plugins(
all_plugins_paths: List[Union[str, Path]],
) -> Iterator[PluginInfo]:
plugin_places = [Path(root) for root in all_plugins_paths]
for path in plugin_places:
plugfiles = path.glob("**/*.plug")
for plugfile in plugfiles:
plugin_info = PluginInfo.load(plugfile)
yield plugin_info
class BackendPluginManager:
"""
This is a one shot plugin manager for Backends and Storage plugins.
"""
def __init__(
self,
bot_config,
base_module: str,
plugin_name: str,
base_class: Type,
base_search_dir,
extra_search_dirs=(),
):
self._config = bot_config
self._base_module = base_module
self._base_class = base_class
self.plugin_info = None
ep = entry_point_plugins(group="errbot.backend_plugins")
all_plugins_paths = collect_roots((base_search_dir, extra_search_dirs, ep))
for potential_plugin in enumerate_backend_plugins(all_plugins_paths):
if potential_plugin.name == plugin_name:
self.plugin_info = potential_plugin
return
raise PluginNotFoundException(
f"Could not find the plugin named {plugin_name} in {all_plugins_paths}."
)
def load_plugin(self) -> Any:
plugin_path = self.plugin_info.location.parent
if plugin_path not in sys.path:
# Cast pathlib.Path objects to string type for compatibility with sys.path
sys.path.append(str(plugin_path))
plugin_classes = self.plugin_info.load_plugin_classes(
self._base_module, self._base_class
)
if len(plugin_classes) != 1:
raise PluginNotFoundException(
f"Found more that one plugin for {self._base_class}."
)
_, clazz = plugin_classes[0]
return clazz(self._config)
| 2,217
|
Python
|
.py
| 58
| 30.155172
| 86
| 0.643357
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,151
|
__init__.py
|
errbotio_errbot/errbot/__init__.py
|
import argparse
import inspect
import logging
import re
import shlex
from functools import wraps
from typing import Any, Callable, Optional, Tuple
from .backends.base import AWAY, DND, OFFLINE, ONLINE, Message # noqa
from .botplugin import ( # noqa
BotPlugin,
Command,
CommandError,
SeparatorArgParser,
ShlexArgParser,
ValidationException,
)
from .core_plugins.wsview import route
from .flow import FLOW_END, BotFlow, Flow, FlowRoot
__all__ = [
"BotPlugin",
"CommandError",
"Command",
"webhook",
"webroute",
"cmdfilter",
"botcmd",
"re_botcmd",
"arg_botcmd",
"botflow",
"botmatch",
"BotFlow",
"FlowRoot",
"Flow",
"FLOW_END",
]
log = logging.getLogger(__name__)
webroute = (
route # this allows plugins to expose dynamic webpages on Errbot embedded webserver
)
# Some clients automatically convert consecutive dashes into a fancy
# hyphen, which breaks long-form arguments. Undo this conversion to
# provide a better user experience.
# Same happens with quotations marks, which are required for parsing
# complex strings in arguments
# Map of characters to sanitized equivalents
ARG_BOTCMD_CHARACTER_REPLACEMENTS = {"—": "--", "“": '"', "”": '"', "’": "'", "‘": "'"}
class ArgumentParseError(Exception):
"""Raised when ArgumentParser couldn't parse given arguments."""
class HelpRequested(Exception):
"""Signals that -h/--help was used and help should be displayed to the user."""
class ArgumentParser(argparse.ArgumentParser):
"""
The python argparse.ArgumentParser, adapted for use within Err.
"""
def error(self, message):
raise ArgumentParseError(message)
def print_help(self, file=None):
# Implementation note: Only easy way to do this appears to be
# through raising an exception which we can catch later in
# a place where we have the ability to return a message to
# the user.
raise HelpRequested()
def _tag_botcmd(
func,
hidden=None,
name=None,
split_args_with="",
admin_only=False,
historize=True,
template=None,
flow_only=False,
_re=False,
syntax=None, # botcmd_only
pattern=None, # re_cmd only
flags=0, # re_cmd only
matchall=False, # re_cmd_only
prefixed=True, # re_cmd_only
_arg=False,
command_parser=None, # arg_cmd only
re_cmd_name_help=None,
): # re_cmd_only
"""
Mark a method as a bot command.
"""
if not hasattr(func, "_err_command"): # don't override generated functions
func._err_command = True
func._err_command_name = name or func.__name__
func._err_command_split_args_with = split_args_with
func._err_command_admin_only = admin_only
func._err_command_historize = historize
func._err_command_template = template
func._err_command_syntax = syntax
func._err_command_flow_only = flow_only
func._err_command_hidden = hidden if hidden is not None else flow_only
# re_cmd
func._err_re_command = _re
if _re:
func._err_command_re_pattern = re.compile(pattern, flags=flags)
func._err_command_matchall = matchall
func._err_command_prefix_required = prefixed
func._err_command_syntax = pattern
func._err_command_re_name_help = re_cmd_name_help
# arg_cmd
func._err_arg_command = _arg
if _arg:
func._err_command_parser = command_parser
# func._err_command_syntax is set at wrapping time.
return func
def botcmd(
*args,
hidden: bool = None,
name: str = None,
split_args_with: str = "",
admin_only: bool = False,
historize: bool = True,
template: str = None,
flow_only: bool = False,
syntax: str = None,
) -> Callable[[BotPlugin, Message, Any], Any]:
"""
Decorator for bot command functions
:param hidden: Prevents the command from being shown by the built-in help command when `True`.
:param name: The name to give to the command. Defaults to name of the function itself.
:param split_args_with: Automatically split arguments on the given separator.
Behaviour of this argument is identical to :func:`str.split()`
:param admin_only: Only allow the command to be executed by admins when `True`.
:param historize: Store the command in the history list (`!history`). This is enabled
by default.
:param template: The markdown template to use.
:param syntax: The argument syntax you expect for example: '[name] <mandatory>'.
:param flow_only: Flag this command to be available only when it is part of a flow.
If True and hidden is None, it will switch hidden to True.
This decorator should be applied to methods of :class:`~errbot.botplugin.BotPlugin`
classes to turn them into commands that can be given to the bot. These methods are
expected to have a signature like the following::
@botcmd
def some_command(self, msg, args):
pass
The given `msg` will be the full message object that was received, which includes data
like sender, receiver, the plain-text and html body (if applicable), etc. `args` will
be a string or list (depending on your value of `split_args_with`) of parameters that
were given to the command by the user.
"""
def decorator(func):
return _tag_botcmd(
func,
_re=False,
_arg=False,
hidden=hidden,
name=name or func.__name__,
split_args_with=split_args_with,
admin_only=admin_only,
historize=historize,
template=template,
syntax=syntax,
flow_only=flow_only,
)
return decorator(args[0]) if args else decorator
def re_botcmd(
*args,
hidden: bool = None,
name: str = None,
admin_only: bool = False,
historize: bool = True,
template: str = None,
pattern: str = None,
flags: int = 0,
matchall: bool = False,
prefixed: bool = True,
flow_only: bool = False,
re_cmd_name_help: str = None,
) -> Callable[[BotPlugin, Message, Any], Any]:
"""
Decorator for regex-based bot command functions
:param pattern: The regular expression a message should match against in order to
trigger the command.
:param flags: The `flags` parameter which should be passed to :func:`re.compile()`. This
allows the expression's behaviour to be modified, such as making it case-insensitive
for example.
:param matchall: By default, only the first match of the regular expression is returned
(as a `re.MatchObject`). When *matchall* is `True`, all non-overlapping matches are
returned (as a list of `re.MatchObject` items).
:param prefixed: Requires user input to start with a bot prefix in order for the pattern
to be applied when `True` (the default).
:param hidden: Prevents the command from being shown by the built-in help command when `True`.
:param name: The name to give to the command. Defaults to name of the function itself.
:param admin_only: Only allow the command to be executed by admins when `True`.
:param historize: Store the command in the history list (`!history`). This is enabled
by default.
:param template: The template to use when using markdown output
:param flow_only: Flag this command to be available only when it is part of a flow.
If True and hidden is None, it will switch hidden to True.
This decorator should be applied to methods of :class:`~errbot.botplugin.BotPlugin`
classes to turn them into commands that can be given to the bot. These methods are
expected to have a signature like the following::
@re_botcmd(pattern=r'^some command$')
def some_command(self, msg, match):
pass
The given `msg` will be the full message object that was received, which includes data
like sender, receiver, the plain-text and html body (if applicable), etc. `match` will
be a :class:`re.MatchObject` containing the result of applying the regular expression on the
user's input.
"""
def decorator(func):
return _tag_botcmd(
func,
_re=True,
_arg=False,
hidden=hidden,
name=name or func.__name__,
admin_only=admin_only,
historize=historize,
template=template,
pattern=pattern,
flags=flags,
matchall=matchall,
prefixed=prefixed,
flow_only=flow_only,
re_cmd_name_help=re_cmd_name_help,
)
return decorator(args[0]) if args else decorator
def botmatch(*args, **kwargs):
"""
Decorator for regex-based message match.
:param *args: The regular expression a message should match against in order to
trigger the command.
:param flags: The `flags` parameter which should be passed to :func:`re.compile()`. This
allows the expression's behaviour to be modified, such as making it case-insensitive
for example.
:param matchall: By default, only the first match of the regular expression is returned
(as a `re.MatchObject`). When *matchall* is `True`, all non-overlapping matches are
returned (as a list of `re.MatchObject` items).
:param hidden: Prevents the command from being shown by the built-in help command when `True`.
:param name: The name to give to the command. Defaults to name of the function itself.
:param admin_only: Only allow the command to be executed by admins when `True`.
:param historize: Store the command in the history list (`!history`). This is enabled
by default.
:param template: The template to use when using Markdown output.
:param flow_only: Flag this command to be available only when it is part of a flow.
If True and hidden is None, it will switch hidden to True.
For example::
@botmatch(r'^(?:Yes|No)$')
def yes_or_no(self, msg, match):
pass
"""
def decorator(func, pattern):
return _tag_botcmd(
func,
_re=True,
_arg=False,
prefixed=False,
hidden=kwargs.get("hidden", None),
name=kwargs.get("name", func.__name__),
admin_only=kwargs.get("admin_only", False),
flow_only=kwargs.get("flow_only", False),
historize=kwargs.get("historize", True),
template=kwargs.get("template", None),
pattern=pattern,
flags=kwargs.get("flags", 0),
matchall=kwargs.get("matchall", False),
)
if len(args) == 2:
return decorator(*args)
if len(args) == 1:
return lambda f: decorator(f, args[0])
raise ValueError(
"botmatch: You need to pass the pattern as parameter to the decorator."
)
def arg_botcmd(
*args,
hidden: bool = None,
name: str = None,
admin_only: bool = False,
historize: bool = True,
template: str = None,
flow_only: bool = False,
unpack_args: bool = True,
**kwargs,
) -> Callable[[BotPlugin, Message, Any], Any]:
"""
Decorator for argparse-based bot command functions
https://docs.python.org/3/library/argparse.html
This decorator creates an argparse.ArgumentParser and uses it to parse the commands arguments.
This decorator can be used multiple times to specify multiple arguments.
Any valid argparse.add_argument() parameters can be passed into the decorator.
Each time this decorator is used it adds a new argparse argument to the command.
:param hidden: Prevents the command from being shown by the built-in help command when `True`.
:param name: The name to give to the command. Defaults to name of the function itself.
:param admin_only: Only allow the command to be executed by admins when `True`.
:param historize: Store the command in the history list (`!history`). This is enabled
by default.
:param template: The template to use when using markdown output
:param flow_only: Flag this command to be available only when it is part of a flow.
If True and hidden is None, it will switch hidden to True.
:param unpack_args: Should the argparser arguments be "unpacked" and passed on the the bot
command individually? If this is True (the default) you must define all arguments in the
function separately. If this is False you must define a single argument `args` (or
whichever name you prefer) to receive the result of `ArgumentParser.parse_args()`.
This decorator should be applied to methods of :class:`~errbot.botplugin.BotPlugin`
classes to turn them into commands that can be given to the bot. The methods will be called
with the original msg and the argparse parsed arguments. These methods are
expected to have a signature like the following (assuming `unpack_args=True`)::
@arg_botcmd('value', type=str)
@arg_botcmd('--repeat-count', dest='repeat', type=int, default=2)
def repeat_the_value(self, msg, value=None, repeat=None):
return value * repeat
The given `msg` will be the full message object that was received, which includes data
like sender, receiver, the plain-text and html body (if applicable), etc.
`value` will hold the value passed in place of the `value` argument and
`repeat` will hold the value passed in place of the `--repeat-count` argument.
If you don't like this automatic *"unpacking"* of the arguments,
you can use `unpack_args=False` like this::
@arg_botcmd('value', type=str)
@arg_botcmd('--repeat-count', dest='repeat', type=int, default=2, unpack_args=False)
def repeat_the_value(self, msg, args):
return arg.value * args.repeat
.. note::
The `unpack_args=False` only needs to be specified once, on the bottom `@args_botcmd`
statement.
"""
argparse_args = args
if len(args) >= 1 and callable(args[0]):
argparse_args = args[1:]
def decorator(func):
if not hasattr(func, "_err_command"):
err_command_parser = ArgumentParser(
prog=name or func.__name__,
description=func.__doc__,
)
@wraps(func)
def wrapper(self, msg, args):
# Attempt to sanitize arguments of bad characters
try:
sanitizer_re = re.compile(
"|".join(
re.escape(ii) for ii in ARG_BOTCMD_CHARACTER_REPLACEMENTS
)
)
args = sanitizer_re.sub(
lambda mm: ARG_BOTCMD_CHARACTER_REPLACEMENTS[mm.group()], args
)
args = shlex.split(args)
parsed_args = err_command_parser.parse_args(args)
except ArgumentParseError as e:
yield f"I couldn't parse the arguments; {e}"
yield err_command_parser.format_usage()
return
except HelpRequested:
yield err_command_parser.format_help()
return
except ValueError as ve:
yield f"I couldn't parse this command; {ve}"
yield err_command_parser.format_help()
return
if unpack_args:
func_args = []
func_kwargs = vars(parsed_args)
else:
func_args = [parsed_args]
func_kwargs = {}
if inspect.isgeneratorfunction(func):
for reply in func(self, msg, *func_args, **func_kwargs):
yield reply
else:
yield func(self, msg, *func_args, **func_kwargs)
_tag_botcmd(
wrapper,
_re=False,
_arg=True,
hidden=hidden,
name=name or wrapper.__name__,
admin_only=admin_only,
historize=historize,
template=template,
flow_only=flow_only,
command_parser=err_command_parser,
)
else:
# the function has already been wrapped
# alias it so we can update it's arguments below
wrapper = func
update_wrapper(wrapper, argparse_args, kwargs)
return wrapper
return decorator(args[0]) if callable(args[0]) else decorator
def update_wrapper(wrapper, argparse_args, kwargs):
wrapper._err_command_parser.add_argument(*argparse_args, **kwargs)
wrapper.__doc__ = wrapper._err_command_parser.format_help()
fmt = wrapper._err_command_parser.format_usage()
wrapper._err_command_syntax = fmt[
len("usage: ") + len(wrapper._err_command_parser.prog) + 1 : -1
]
def _tag_webhook(
func: Callable,
uri_rule: str,
methods: Tuple[str],
form_param: Optional[str],
raw: bool,
) -> Callable:
log.info(f"webhooks: Flag to bind {uri_rule} to {getattr(func, '__name__', func)}")
func._err_webhook_uri_rule = uri_rule
func._err_webhook_methods = methods
func._err_webhook_form_param = form_param
func._err_webhook_raw = raw
return func
def _uri_from_func(func: Callable) -> str:
return r"/" + func.__name__
def webhook(
*args,
methods: Tuple[str] = ("POST", "GET"),
form_param: str = None,
raw: bool = False,
) -> Callable[[BotPlugin, Any], str]:
"""
Decorator for webhooks
:param uri_rule:
The URL to use for this webhook, as per Flask request routing syntax.
For more information, see:
* http://flask.pocoo.org/docs/1.0/quickstart/#routing
* http://flask.pocoo.org/docs/1.0/api/#flask.Flask.route
:param methods:
A tuple of allowed HTTP methods. By default, only GET and POST
are allowed.
:param form_param:
The key who's contents will be passed to your method's `payload` parameter.
This is used for example when using the `application/x-www-form-urlencoded`
mimetype.
:param raw:
When set to true, this overrides the request decoding (including form_param) and
passes the raw http request to your method's `payload` parameter.
The value of payload will be a Flask
`Request <http://flask.pocoo.org/docs/1.0/api/#flask.Request>`_.
This decorator should be applied to methods of :class:`~errbot.botplugin.BotPlugin`
classes to turn them into webhooks which can be reached on Err's built-in webserver.
The bundled *Webserver* plugin needs to be configured before these URL's become reachable.
Methods with this decorator are expected to have a signature like the following::
@webhook
def a_webhook(self, payload):
pass
"""
if not args: # default uri_rule but with kwargs.
return lambda func: _tag_webhook(
func, _uri_from_func(func), methods=methods, form_param=form_param, raw=raw
)
if isinstance(args[0], str): # first param is uri_rule.
return lambda func: _tag_webhook(
func,
(
args[0] if args[0] == "/" else args[0].rstrip("/")
), # trailing / is also be stripped on incoming.
methods=methods,
form_param=form_param,
raw=raw,
)
return _tag_webhook(
args[0], # naked decorator so the first parameter is a function.
_uri_from_func(args[0]),
methods=methods,
form_param=form_param,
raw=raw,
)
def cmdfilter(*args, **kwargs):
"""
Decorator for command filters.
This decorator should be applied to methods of :class:`~errbot.botplugin.BotPlugin`
classes to turn them into command filters.
These filters are executed just before the execution of a command and provide
the means to add features such as custom security, logging, auditing, etc.
These methods are expected to have a signature and tuple response like the following::
@cmdfilter
def some_filter(self, msg, cmd, args, dry_run):
\"\"\"
:param msg: The original chat message.
:param cmd: The command name itself.
:param args: Arguments passed to the command.
:param dry_run: True when this is a dry-run.
Dry-runs are performed by certain commands (such as !help)
to check whether a user is allowed to perform that command
if they were to issue it. If dry_run is True then the plugin
shouldn't actually do anything beyond returning whether the
command is authorized or not.
\"\"\"
# If wishing to block the incoming command:
return None, None, None
# Otherwise pass data through to the (potential) next filter:
return msg, cmd, args
Note that a cmdfilter plugin *could* modify `cmd` or `args` above
and send that through in order to make it appear as if the user
issued a different command.
"""
def decorate(func):
if not hasattr(
func, "_err_command_filter"
): # don't override generated functions
func._err_command_filter = True
func.catch_unprocessed = kwargs.get("catch_unprocessed", False)
return func
if len(args):
return decorate(args[0])
return lambda func: decorate(func)
def botflow(*args, **kwargs):
"""
Decorator for flow of commands.
TODO(gbin): example / docs
"""
def decorate(func):
if not hasattr(func, "_err_flow"): # don't override generated functions
func._err_flow = True
return func
if len(args):
return decorate(args[0])
return lambda func: decorate(func)
| 22,197
|
Python
|
.py
| 511
| 34.90411
| 98
| 0.637126
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,152
|
plugin_info.py
|
errbotio_errbot/errbot/plugin_info.py
|
import inspect
import sys
from configparser import ConfigParser
from configparser import Error as ConfigParserError
from dataclasses import dataclass
from importlib._bootstrap import module_from_spec
from importlib._bootstrap_external import spec_from_file_location
from pathlib import Path
from typing import List, Tuple, Type
from errbot.utils import version2tuple
VersionType = Tuple[int, int, int]
@dataclass
class PluginInfo:
name: str
module: str
doc: str
core: bool
python_version: VersionType
errbot_minversion: VersionType
errbot_maxversion: VersionType
dependencies: List[str]
location: Path = None
@staticmethod
def load(plugfile_path: Path) -> "PluginInfo":
with plugfile_path.open(encoding="utf-8") as plugfile:
return PluginInfo.load_file(plugfile, plugfile_path)
@staticmethod
def load_file(plugfile, location: Path) -> "PluginInfo":
cp = ConfigParser()
cp.read_file(plugfile)
pi = PluginInfo.parse(cp)
pi.location = location
return pi
@staticmethod
def parse(config: ConfigParser) -> "PluginInfo":
"""
Throws ConfigParserError with a meaningful message if the ConfigParser doesn't contain the minimal
information required.
"""
name = config.get("Core", "Name")
module = config.get("Core", "Module")
core = config.get("Core", "Core", fallback="false").lower() == "true"
doc = config.get("Documentation", "Description", fallback=None)
python_version = config.get("Python", "Version", fallback=None)
# Old format backward compatibility
if python_version:
if python_version in ("2+", "3"):
python_version = (3, 0, 0)
elif python_version == "2":
python_version = (2, 0, 0)
else:
try:
python_version = tuple(
version2tuple(python_version)[0:3]
) # We can ignore the alpha/beta part.
except ValueError as ve:
raise ConfigParserError(
f"Invalid Python Version format: {python_version} ({ve})"
)
min_version = config.get("Errbot", "Min", fallback=None)
max_version = config.get("Errbot", "Max", fallback=None)
try:
if min_version:
min_version = version2tuple(min_version)
except ValueError as ve:
raise ConfigParserError(
f"Invalid Errbot min version format: {min_version} ({ve})"
)
try:
if max_version:
max_version = version2tuple(max_version)
except ValueError as ve:
raise ConfigParserError(
f"Invalid Errbot max version format: {max_version} ({ve})"
)
depends_on = config.get("Core", "DependsOn", fallback=None)
deps = [name.strip() for name in depends_on.split(",")] if depends_on else []
return PluginInfo(
name, module, doc, core, python_version, min_version, max_version, deps
)
def load_plugin_classes(self, base_module_name: str, baseclass: Type):
# load the module
module_name = base_module_name + "." + self.module
spec = spec_from_file_location(
module_name, self.location.parent / (self.module + ".py")
)
modu1e = module_from_spec(spec)
spec.loader.exec_module(modu1e)
sys.modules[module_name] = modu1e
# introspect the modules to find plugin classes
def is_plugin(member):
return (
inspect.isclass(member)
and issubclass(member, baseclass)
and member != baseclass
)
plugin_classes = inspect.getmembers(modu1e, is_plugin)
return plugin_classes
| 3,921
|
Python
|
.py
| 98
| 30.285714
| 106
| 0.609346
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,153
|
core.py
|
errbotio_errbot/errbot/core.py
|
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import atexit
import difflib
import inspect
import logging
import re
import traceback
from collections.abc import Mapping
from datetime import datetime
from multiprocessing.pool import ThreadPool
from threading import RLock
from typing import Any, Callable, List, Optional, Tuple
from errbot import CommandError
from errbot.flow import FlowExecutor, FlowRoot
from .backends.base import Backend, Identifier, Message, Presence, Room
from .storage import StoreMixin
from .streaming import Tee
from .templating import tenv
from .utils import split_string_after
log = logging.getLogger(__name__)
# noinspection PyAbstractClass
class ErrBot(Backend, StoreMixin):
"""ErrBot is the layer taking care of commands management and dispatching."""
__errdoc__ = """ Commands related to the bot administration """
MSG_ERROR_OCCURRED = "Computer says nooo. See logs for details"
MSG_UNKNOWN_COMMAND = 'Unknown command: "%(command)s". '
startup_time = datetime.now()
def __init__(self, bot_config):
log.debug("ErrBot init.")
super().__init__(bot_config)
self.bot_config = bot_config
self.prefix = bot_config.BOT_PREFIX
if bot_config.BOT_ASYNC:
self.thread_pool = ThreadPool(bot_config.BOT_ASYNC_POOLSIZE)
atexit.register(self.thread_pool.close)
log.debug(
"created a thread pool of size %d.", bot_config.BOT_ASYNC_POOLSIZE
)
self.commands = {} # the dynamically populated list of commands available on the bot
self.re_commands = {} # the dynamically populated list of regex-based commands available on the bot
self.command_filters = [] # the dynamically populated list of filters
self.MSG_UNKNOWN_COMMAND = (
'Unknown command: "%(command)s". '
'Type "' + bot_config.BOT_PREFIX + 'help" for available commands.'
)
if bot_config.BOT_ALT_PREFIX_CASEINSENSITIVE:
self.bot_alt_prefixes = tuple(
prefix.lower() for prefix in bot_config.BOT_ALT_PREFIXES
)
else:
self.bot_alt_prefixes = bot_config.BOT_ALT_PREFIXES
self.repo_manager = None
self.plugin_manager = None
self.storage_plugin = None
self._plugin_errors_during_startup = None
self.flow_executor = FlowExecutor(self)
self._gbl = RLock() # this protects internal structures of this class
self.set_message_size_limit()
@property
def message_size_limit(self) -> int:
return self.bot_config.MESSAGE_SIZE_LIMIT
def set_message_size_limit(
self, limit: int = 10000, hard_limit: int = 10000
) -> None:
"""
Set backends message size limit and its maximum supported message size. The
MESSAGE_SIZE_LIMIT can be overridden by setting it in the configuration file.
A historical value of 10000 is used by default.
"""
if self.bot_config.MESSAGE_SIZE_LIMIT:
self.bot_config.MESSAGE_SIZE_LIMIT = int(
self.bot_config.MESSAGE_SIZE_LIMIT
) # raise for non-int values.
else:
self.bot_config.MESSAGE_SIZE_LIMIT = limit
if self.bot_config.MESSAGE_SIZE_LIMIT > hard_limit:
log.warning(
f"Message size limit of {self.bot_config.MESSAGE_SIZE_LIMIT} exceeds "
f"backends maximum message size {hard_limit}."
" You might experience message delivery issues."
)
def attach_repo_manager(self, repo_manager) -> None:
self.repo_manager = repo_manager
def attach_plugin_manager(self, plugin_manager) -> None:
self.plugin_manager = plugin_manager
def attach_storage_plugin(self, storage_plugin) -> None:
# the storage_plugin is needed by the plugins
self.storage_plugin = storage_plugin
def initialize_backend_storage(self) -> None:
"""
Initialize storage for the backend to use.
"""
log.debug("Initializing backend storage")
assert self.plugin_manager is not None
assert self.storage_plugin is not None
self.open_storage(self.storage_plugin, f"{self.mode}_backend")
@property
def all_commands(self) -> dict:
"""Return both commands and re_commands together."""
with self._gbl:
newd = dict(**self.commands)
newd.update(self.re_commands)
return newd
def _dispatch_to_plugins(self, method: Callable, *args, **kwargs) -> None:
"""
Dispatch the given method to all active plugins.
Will catch and log any exceptions that occur.
:param method: The name of the function to dispatch.
:param *args: Passed to the callback function.
:param **kwargs: Passed to the callback function.
"""
for plugin in self.plugin_manager.get_all_active_plugins():
plugin_name = plugin.name
log.debug("Triggering %s on %s.", method, plugin_name)
# noinspection PyBroadException
try:
getattr(plugin, method)(*args, **kwargs)
except Exception:
log.exception("%s on %s crashed.", method, plugin_name)
def send(
self,
identifier: Identifier,
text: str,
in_reply_to: Optional[Message] = None,
groupchat_nick_reply: bool = False,
) -> None:
"""Sends a simple message to the specified user.
:param identifier:
an identifier from build_identifier or from an incoming message
:param in_reply_to:
the original message the bot is answering from
:param text:
the markdown text you want to send
:param groupchat_nick_reply:
authorized the prefixing with the nick form the user
"""
# protect a little bit the backends here
if not isinstance(identifier, Identifier):
raise ValueError("identifier should be an Identifier")
msg = self.build_message(text)
msg.to = identifier
msg.frm = in_reply_to.to if in_reply_to else self.bot_identifier
msg.parent = in_reply_to
nick_reply = self.bot_config.GROUPCHAT_NICK_PREFIXED
if (
isinstance(identifier, Room)
and in_reply_to
and (nick_reply or groupchat_nick_reply)
):
self.prefix_groupchat_reply(msg, in_reply_to.frm)
self.split_and_send_message(msg)
def send_templated(
self,
identifier: Identifier,
template_name,
template_parameters,
in_reply_to: Optional[Message] = None,
groupchat_nick_reply: bool = False,
) -> Callable:
"""Sends a simple message to the specified user using a template.
:param template_parameters: the parameters for the template.
:param template_name: the template name you want to use.
:param identifier:
an identifier from build_identifier or from an incoming message, a room etc.
:param in_reply_to:
the original message the bot is answering from
:param groupchat_nick_reply:
authorized the prefixing with the nick form the user
"""
text = self.process_template(template_name, template_parameters)
return self.send(identifier, text, in_reply_to, groupchat_nick_reply)
def split_and_send_message(self, msg: Message) -> None:
for part in split_string_after(msg.body, self.message_size_limit):
partial_message = msg.clone()
partial_message.body = part
partial_message.partial = True
self.send_message(partial_message)
def send_message(self, msg: Message) -> None:
"""
This needs to be overridden by the backends with a super() call.
:param msg: the message to send.
:return: None
"""
for bot in self.plugin_manager.get_all_active_plugins():
# noinspection PyBroadException
try:
bot.callback_botmessage(msg)
except Exception:
log.exception("Crash in a callback_botmessage handler")
def send_card(self, card: Message) -> None:
"""
Sends a card, this can be overriden by the backends *without* a super() call.
:param card: the card to send.
:return: None
"""
self.send_templated(card.to, "card", {"card": card})
def send_simple_reply(
self, msg: Message, text: str, private: bool = False, threaded: bool = False
) -> None:
"""Send a simple response to a given incoming message
:param private: if True will force a response in private.
:param threaded: if True and if the backend supports it, sends the response in a threaded message.
:param text: the markdown text of the message.
:param msg: the message you are replying to.
"""
reply = self.build_reply(msg, text, private=private, threaded=threaded)
if isinstance(reply.to, Room) and self.bot_config.GROUPCHAT_NICK_PREFIXED:
self.prefix_groupchat_reply(reply, msg.frm)
self.split_and_send_message(reply)
def process_message(self, msg: Message) -> bool:
"""Check if the given message is a command for the bot and act on it.
It return True for triggering the callback_messages on the .callback_messages on the plugins.
:param msg: the incoming message.
"""
# Prepare to handle either private chats or group chats
frm = msg.frm
text = msg.body
if not hasattr(msg.frm, "person"):
raise Exception(
f'msg.frm not an Identifier as it misses the "person" property.'
f" Class of frm : {msg.frm.__class__}."
)
username = msg.frm.person
user_cmd_history = self.cmd_history[username]
if msg.delayed:
log.debug("Message from history, ignore it.")
return False
if self.is_from_self(msg):
log.debug("Ignoring message from self.")
return False
log.debug("*** frm = %s", frm)
log.debug("*** username = %s", username)
log.debug("*** text = %s", text)
prefixed = False # Keeps track whether text was prefixed with a bot prefix
only_check_re_command = (
False # Becomes true if text is determed to not be a regular command
)
tomatch = (
text.lower() if self.bot_config.BOT_ALT_PREFIX_CASEINSENSITIVE else text
)
if len(self.bot_config.BOT_ALT_PREFIXES) > 0 and tomatch.startswith(
self.bot_alt_prefixes
):
# Yay! We were called by one of our alternate prefixes. Now we just have to find out
# which one... (And find the longest matching, in case you have 'err' and 'errbot' and
# someone uses 'errbot', which also matches 'err' but would leave 'bot' to be taken as
# part of the called command in that case)
prefixed = True
longest = 0
for prefix in self.bot_alt_prefixes:
length = len(prefix)
if tomatch.startswith(prefix) and length > longest:
longest = length
log.debug('Called with alternate prefix "%s"', text[:longest])
text = text[longest:]
# Now also remove the separator from the text
for sep in self.bot_config.BOT_ALT_PREFIX_SEPARATORS:
# While unlikely, one may have separators consisting of
# more than one character
length = len(sep)
if text[:length] == sep:
text = text[length:]
elif msg.is_direct and self.bot_config.BOT_PREFIX_OPTIONAL_ON_CHAT:
log.debug(
'Assuming "%s" to be a command because BOT_PREFIX_OPTIONAL_ON_CHAT is True',
text,
)
elif not text.startswith(self.bot_config.BOT_PREFIX):
only_check_re_command = True
if text.startswith(self.bot_config.BOT_PREFIX):
text = text[len(self.bot_config.BOT_PREFIX) :]
prefixed = True
text = text.strip()
text_split = text.split()
cmd = None
command = None
args = ""
if not only_check_re_command:
i = len(text_split)
while cmd is None:
command = "_".join(text_split[:i])
with self._gbl:
if command in self.commands:
cmd = command
args = " ".join(text_split[i:])
else:
i -= 1
if i <= 0:
break
if (
command == self.bot_config.BOT_PREFIX
): # we did "!!" so recall the last command
if len(user_cmd_history):
cmd, args = user_cmd_history[-1]
else:
return False # no command in history
elif command.isdigit(): # we did "!#" so we recall the specified command
index = int(command)
if len(user_cmd_history) >= index:
cmd, args = user_cmd_history[-index]
else:
return False # no command in history
# Try to match one of the regex commands if the regular commands produced no match
matched_on_re_command = False
if not cmd:
with self._gbl:
if prefixed or (
msg.is_direct and self.bot_config.BOT_PREFIX_OPTIONAL_ON_CHAT
):
commands = dict(self.re_commands)
else:
commands = {
k: self.re_commands[k]
for k in self.re_commands
if not self.re_commands[k]._err_command_prefix_required
}
for name, func in commands.items():
if func._err_command_matchall:
match = list(func._err_command_re_pattern.finditer(text))
else:
match = func._err_command_re_pattern.search(text)
if match:
log.debug(
'Matching "%s" against "%s" produced a match.',
text,
func._err_command_re_pattern.pattern,
)
matched_on_re_command = True
self._process_command(msg, name, text, match)
else:
log.debug(
'Matching "%s" against "%s" produced no match.',
text,
func._err_command_re_pattern.pattern,
)
if matched_on_re_command:
return True
if cmd:
self._process_command(msg, cmd, args, match=None)
elif not only_check_re_command:
log.debug("Command not found")
for cmd_filter in self.command_filters:
if getattr(cmd_filter, "catch_unprocessed", False):
try:
reply = cmd_filter(msg, cmd, args, False, emptycmd=True)
if reply:
self.send_simple_reply(msg, reply)
# continue processing the other unprocessed cmd filters.
except Exception:
log.exception("Exception in a command filter command.")
return True
def _process_command_filters(
self, msg: Message, cmd, args, dry_run: bool = False
) -> Tuple[Optional[Message], Optional[str], Optional[Tuple]]:
try:
for cmd_filter in self.command_filters:
msg, cmd, args = cmd_filter(msg, cmd, args, dry_run)
if msg is None:
return None, None, None
return msg, cmd, args
except Exception:
log.exception(
"Exception in a filter command, blocking the command in doubt"
)
return None, None, None
def _process_command(self, msg, cmd, args, match):
"""Process and execute a bot command"""
# first it must go through the command filters
msg, cmd, args = self._process_command_filters(msg, cmd, args, False)
if msg is None:
log.info("Command %s blocked or deferred.", cmd)
return
frm = msg.frm
username = frm.person
user_cmd_history = self.cmd_history[username]
log.info(f'Processing command "{cmd}" with parameters "{args}" from {frm}')
if (cmd, args) in user_cmd_history:
user_cmd_history.remove((cmd, args)) # Avoids duplicate history items
with self._gbl:
f = self.re_commands[cmd] if match else self.commands[cmd]
if f._err_command_admin_only and self.bot_config.BOT_ASYNC:
# If it is an admin command, wait until the queue is completely depleted so
# we don't have strange concurrency issues on load/unload/updates etc...
self.thread_pool.close()
self.thread_pool.join()
self.thread_pool = ThreadPool(self.bot_config.BOT_ASYNC_POOLSIZE)
atexit.register(self.thread_pool.close)
if f._err_command_historize:
user_cmd_history.append(
(cmd, args)
) # add it to the history only if it is authorized to be so
# Don't check for None here as None can be a valid argument to str.split.
# '' was chosen as default argument because this isn't a valid argument to str.split()
if not match and f._err_command_split_args_with != "":
try:
if hasattr(f._err_command_split_args_with, "parse_args"):
args = f._err_command_split_args_with.parse_args(args)
elif callable(f._err_command_split_args_with):
args = f._err_command_split_args_with(args)
else:
args = args.split(f._err_command_split_args_with)
except Exception as e:
self.send_simple_reply(
msg, f"Sorry, I couldn't parse your arguments. {e}"
)
return
if self.bot_config.BOT_ASYNC:
result = self.thread_pool.apply_async(
self._execute_and_send,
[],
{
"cmd": cmd,
"args": args,
"match": match,
"msg": msg,
"template_name": f._err_command_template,
},
)
if f._err_command_admin_only:
# Again, if it is an admin command, wait until the queue is completely
# depleted so we don't have strange concurrency issues.
result.wait()
else:
self._execute_and_send(
cmd=cmd,
args=args,
match=match,
msg=msg,
template_name=f._err_command_template,
)
@staticmethod
def process_template(template_name, template_parameters):
# integrated templating
# The template needs to be set and the answer from the user command needs to be a mapping
# If not just convert the answer to string.
if template_name and isinstance(template_parameters, Mapping):
return (
tenv().get_template(template_name + ".md").render(**template_parameters)
)
# Reply should be all text at this point (See https://github.com/errbotio/errbot/issues/96)
return str(template_parameters)
def _execute_and_send(self, cmd, args, match, msg, template_name=None):
"""Execute a bot command and send output back to the caller
:param cmd: The command that was given to the bot (after being expanded)
:param args: Arguments given along with cmd
:param match: A re.MatchObject if command is coming from a regex-based command, else None
:param msg: The message object
:param template_name: The name of the jinja template which should be used to render
the markdown output, if any
"""
private = (
"ALL_COMMANDS" in self.bot_config.DIVERT_TO_PRIVATE
or cmd in self.bot_config.DIVERT_TO_PRIVATE
)
threaded = (
"ALL_COMMANDS" in self.bot_config.DIVERT_TO_THREAD
or cmd in self.bot_config.DIVERT_TO_THREAD
)
commands = self.re_commands if match else self.commands
try:
with self._gbl:
method = commands[cmd]
# first check if we need to reattach a flow context
flow, _ = self.flow_executor.check_inflight_flow_triggered(cmd, msg.frm)
if flow:
log.debug(
"Reattach context from flow %s to the message", flow._root.name
)
msg.ctx = flow.ctx
elif method._err_command_flow_only:
# check if it is a flow_only command but we are not in a flow.
log.debug(
"%s is tagged flow_only and we are not in a flow. Ignores the command.",
cmd,
)
return
if inspect.isgeneratorfunction(method):
replies = method(msg, match) if match else method(msg, args)
for reply in replies:
if reply:
self.send_simple_reply(
msg,
self.process_template(template_name, reply),
private,
threaded,
)
else:
reply = method(msg, match) if match else method(msg, args)
if reply:
self.send_simple_reply(
msg,
self.process_template(template_name, reply),
private,
threaded,
)
# The command is a success, check if this has not made a flow progressed
self.flow_executor.trigger(cmd, msg.frm, msg.ctx)
except CommandError as command_error:
reason = command_error.reason
if command_error.template:
reason = self.process_template(command_error.template, reason)
self.send_simple_reply(msg, reason, private, threaded)
except Exception as e:
tb = traceback.format_exc()
log.exception(
f'An error happened while processing a message ("{msg.body}"): {tb}"'
)
self.send_simple_reply(
msg, self.MSG_ERROR_OCCURRED + f":\n{e}", private, threaded
)
def unknown_command(self, _, cmd: str, args: Optional[str]) -> str:
"""Override the default unknown command behavior"""
full_cmd = cmd + " " + args.split(" ")[0] if args else None
if full_cmd:
msg = f'Command "{cmd}" / "{full_cmd}" not found.'
else:
msg = f'Command "{cmd}" not found.'
ununderscore_keys = [m.replace("_", " ") for m in self.commands.keys()]
matches = difflib.get_close_matches(cmd, ununderscore_keys)
if full_cmd:
matches.extend(difflib.get_close_matches(full_cmd, ununderscore_keys))
matches = set(matches)
if matches:
alternatives = ('" or "' + self.bot_config.BOT_PREFIX).join(matches)
msg += f'\n\nDid you mean "{self.bot_config.BOT_PREFIX}{alternatives}" ?'
return msg
def inject_commands_from(self, instance_to_inject):
with self._gbl:
plugin_name = instance_to_inject.name
for name, value in inspect.getmembers(instance_to_inject, inspect.ismethod):
if getattr(value, "_err_command", False):
commands = (
self.re_commands
if getattr(value, "_err_re_command")
else self.commands
)
name = getattr(value, "_err_command_name")
if name in commands:
f = commands[name]
new_name = (plugin_name + "-" + name).lower()
self.warn_admins(
f"{plugin_name}.{name} clashes with {type(f.__self__).__name__}.{f.__name__} "
f"so it has been renamed {new_name}"
)
name = new_name
value.__func__._err_command_name = (
new_name # To keep track of the renaming.
)
commands[name] = value
if getattr(value, "_err_re_command"):
log.debug(
"Adding regex command: %s -> %s.", name, value.__name__
)
self.re_commands = commands
else:
log.debug("Adding command: %s -> %s.", name, value.__name__)
self.commands = commands
def inject_flows_from(self, instance_to_inject) -> None:
classname = instance_to_inject.__class__.__name__
for name, method in inspect.getmembers(instance_to_inject, inspect.ismethod):
if getattr(method, "_err_flow", False):
log.debug("Found new flow %s: %s", classname, name)
flow = FlowRoot(name, method.__doc__)
try:
method(flow)
except Exception:
log.exception("Exception initializing a flow")
self.flow_executor.add_flow(flow)
def inject_command_filters_from(self, instance_to_inject) -> None:
with self._gbl:
for name, method in inspect.getmembers(
instance_to_inject, inspect.ismethod
):
if getattr(method, "_err_command_filter", False):
log.debug("Adding command filter: %s", name)
self.command_filters.append(method)
def remove_flows_from(self, instance_to_inject) -> None:
for name, value in inspect.getmembers(instance_to_inject, inspect.ismethod):
if getattr(value, "_err_flow", False):
log.debug("Remove flow %s", name)
# TODO(gbin)
def remove_commands_from(self, instance_to_inject) -> None:
with self._gbl:
for name, value in inspect.getmembers(instance_to_inject, inspect.ismethod):
if getattr(value, "_err_command", False):
name = getattr(value, "_err_command_name")
if getattr(value, "_err_re_command") and name in self.re_commands:
del self.re_commands[name]
elif (
not getattr(value, "_err_re_command") and name in self.commands
):
del self.commands[name]
def remove_command_filters_from(self, instance_to_inject) -> None:
with self._gbl:
for name, method in inspect.getmembers(
instance_to_inject, inspect.ismethod
):
if getattr(method, "_err_command_filter", False):
log.debug("Removing command filter: %s", name)
self.command_filters.remove(method)
def _admins_to_notify(self) -> List:
"""
Creates a list of administrators to notify
"""
admins_to_notify = self.bot_config.BOT_ADMINS_NOTIFICATIONS
return admins_to_notify
def warn_admins(self, warning: str) -> None:
"""
Send a warning to the administrators of the bot.
:param warning: The markdown-formatted text of the message to send.
"""
for admin in self._admins_to_notify():
self.send(self.build_identifier(admin), warning)
log.warning(warning)
def callback_message(self, msg: Message) -> None:
"""Processes for commands and dispatches the message to all the plugins."""
if self.process_message(msg):
# Act only in the backend tells us that this message is OK to broadcast
self._dispatch_to_plugins("callback_message", msg)
def callback_mention(self, msg: Message, people: List[Identifier]) -> None:
log.debug("%s has/have been mentioned", ", ".join(str(p) for p in people))
self._dispatch_to_plugins("callback_mention", msg, people)
def callback_presence(self, pres: Presence) -> None:
self._dispatch_to_plugins("callback_presence", pres)
def callback_room_joined(
self,
room: Room,
identifier: Optional[Identifier] = None,
invited_by: Optional[Identifier] = None,
) -> None:
"""
Triggered when a user has joined a MUC.
:param room:
An instance of :class:`~errbot.backends.base.MUCRoom`
representing the room that was joined.
:param identifier: An instance of Identifier (Person). Defaults to bot
:param invited_by: An instance of Identifier (Person). Defaults to None
"""
if identifier is None:
identifier = self.bot_identifier
self._dispatch_to_plugins("callback_room_joined", room, identifier, invited_by)
def callback_room_left(
self,
room: Room,
identifier: Optional[Identifier] = None,
kicked_by: Optional[Identifier] = None,
) -> None:
"""
Triggered when a user has left a MUC.
:param room:
An instance of :class:`~errbot.backends.base.MUCRoom`
representing the room that was left.
:param identifier: An instance of Identifier (Person). Defaults to bot
:param kicked_by: An instance of Identifier (Person). Defaults to None
"""
if identifier is None:
identifier = self.bot_identifier
self._dispatch_to_plugins("callback_room_left", room, identifier, kicked_by)
def callback_room_topic(self, room: Room) -> None:
"""
Triggered when the topic in a MUC changes.
:param room:
An instance of :class:`~errbot.backends.base.MUCRoom`
representing the room for which the topic changed.
"""
self._dispatch_to_plugins("callback_room_topic", room)
def callback_stream(self, stream) -> None:
log.info("Initiated an incoming transfer %s.", stream)
Tee(stream, self.plugin_manager.get_all_active_plugins()).start()
def callback_reaction(self, reaction) -> None:
"""
Triggered when a reaction occurs.
:param reaction:
An instance of :class:`~errbot.backends.base.Reaction`
representing the reaction event data
"""
self._dispatch_to_plugins("callback_reaction", reaction)
def signal_connect_to_all_plugins(self) -> None:
for bot in self.plugin_manager.get_all_active_plugins():
if hasattr(bot, "callback_connect"):
# noinspection PyBroadException
try:
log.debug("Trigger callback_connect on %s.", bot.__class__.__name__)
bot.callback_connect()
except Exception:
log.exception(f"callback_connect failed for {bot}.")
def connect_callback(self) -> None:
log.info("Activate internal commands")
if self._plugin_errors_during_startup:
errors = f"Some plugins failed to start during bot startup:\n\n{self._plugin_errors_during_startup}"
else:
errors = ""
errors += self.plugin_manager.activate_non_started_plugins()
if errors:
self.warn_admins(errors)
log.info(errors)
log.info("Notifying connection to all the plugins...")
self.signal_connect_to_all_plugins()
log.info("Plugin activation done.")
def disconnect_callback(self) -> None:
log.info("Disconnect callback, deactivating all the plugins.")
self.plugin_manager.deactivate_all_plugins()
def get_doc(self, command: Callable) -> str:
"""Get command documentation"""
if not command.__doc__:
return "(undocumented)"
if self.prefix == "!":
return command.__doc__
ununderscore_keys = (m.replace("_", " ") for m in self.all_commands.keys())
pat = re.compile(rf'!({"|".join(ununderscore_keys)})')
return re.sub(pat, self.prefix + "\1", command.__doc__)
@staticmethod
def get_plugin_class_from_method(meth):
for cls in inspect.getmro(type(meth.__self__)):
if meth.__name__ in cls.__dict__:
return cls
return None
def get_command_classes(self) -> Tuple[Any]:
return (
self.get_plugin_class_from_method(command)
for command in self.all_commands.values()
)
def shutdown(self) -> None:
self.close_storage()
self.plugin_manager.shutdown()
self.repo_manager.shutdown()
def prefix_groupchat_reply(self, message: Message, identifier: Identifier) -> None:
if message.body.startswith("#"):
# Markdown heading, insert an extra newline to ensure the
# markdown rendering doesn't break.
message.body = "\n" + message.body
| 34,614
|
Python
|
.py
| 743
| 34.211306
| 112
| 0.577122
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,154
|
plugin_wizard.py
|
errbotio_errbot/errbot/plugin_wizard.py
|
import errno
import os
import re
import sys
from configparser import ConfigParser
from typing import List, Optional
import jinja2
from errbot.version import VERSION
def new_plugin_wizard(directory: Optional[str] = None) -> None:
"""
Start the wizard to create a new plugin in the current working directory.
"""
if directory is None:
print("This wizard will create a new plugin for you in the current directory.")
directory = os.getcwd()
else:
print(f"This wizard will create a new plugin for you in '{directory}'.")
if os.path.exists(directory) and not os.path.isdir(directory):
print(f"Error: The path '{directory}' exists but it isn't a directory")
sys.exit(1)
name = ask(
"What should the name of your new plugin be?",
validation_regex=r"^[a-zA-Z][a-zA-Z0-9 _-]*$",
).strip()
module_name = name.lower().replace(" ", "_")
directory_name = name.lower().replace(" ", "-")
class_name = "".join([s.capitalize() for s in name.lower().split(" ")])
description = ask(
"What may I use as a short (one-line) description of your plugin?"
)
python_version = "3"
errbot_min_version = ask(
f"Which minimum version of errbot will your plugin work with?\n"
f"Leave blank to support any version or input CURRENT to select "
f"the current version {VERSION}."
).strip()
if errbot_min_version.upper() == "CURRENT":
errbot_min_version = VERSION
errbot_max_version = ask(
f"Which maximum version of errbot will your plugin work with?\n"
f"Leave blank to support any version or input CURRENT to select "
f"the current version {VERSION}."
).strip()
if errbot_max_version.upper() == "CURRENT":
errbot_max_version = VERSION
plug = ConfigParser()
plug["Core"] = {
"Name": name,
"Module": module_name,
}
plug["Documentation"] = {
"Description": description,
}
plug["Python"] = {
"Version": python_version,
}
if errbot_max_version != "" or errbot_min_version != "":
plug["Errbot"] = {}
if errbot_min_version != "":
plug["Errbot"]["Min"] = errbot_min_version
if errbot_max_version != "":
plug["Errbot"]["Max"] = errbot_max_version
plugin_path = directory
plugfile_path = os.path.join(plugin_path, module_name + ".plug")
pyfile_path = os.path.join(plugin_path, module_name + ".py")
try:
os.makedirs(plugin_path, mode=0o700)
except IOError as e:
if e.errno != errno.EEXIST:
raise
if os.path.exists(plugfile_path) or os.path.exists(pyfile_path):
path = os.path.join(directory, f"{module_name}.{{py,plug}}")
ask(
f"Warning: A plugin with this name was already found at {path}\n"
f"If you continue, these will be overwritten.\n"
f"Press Ctrl+C to abort now or type in 'overwrite' to confirm overwriting of these files.",
valid_responses=["overwrite"],
)
with open(plugfile_path, "w") as f:
plug.write(f)
with open(pyfile_path, "w") as f:
f.write(render_plugin(locals()))
print(f"Success! You'll find your new plugin at '{plugfile_path}'")
print(
"(Don't forget to include a LICENSE file if you are going to publish your plugin)."
)
def ask(
question: str,
valid_responses: Optional[List[str]] = None,
validation_regex: Optional[str] = None,
) -> Optional[str]:
"""
Ask the user for some input. If valid_responses is supplied, the user
must respond with something present in this list.
"""
response = None
print(question)
while True:
response = input("> ")
if valid_responses is not None:
assert isinstance(valid_responses, list)
if response in valid_responses:
break
else:
print(f"Bad input: Please answer one of: {', '.join(valid_responses)}")
elif validation_regex is not None:
m = re.search(validation_regex, response)
if m is None:
print(
f"Bad input: Please respond with something matching this regex: {validation_regex}"
)
else:
break
else:
break
return response
def render_plugin(values) -> jinja2.Template:
"""
Render the Jinja template for the plugin with the given values.
"""
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(os.path.dirname(__file__), "templates")
),
auto_reload=False,
keep_trailing_newline=True,
autoescape=True,
)
template = env.get_template("new_plugin.py.tmpl")
return template.render(**values)
if __name__ == "__main__":
try:
new_plugin_wizard()
except KeyboardInterrupt:
sys.exit(1)
| 4,981
|
Python
|
.py
| 135
| 29.42963
| 103
| 0.614715
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,155
|
bootstrap.py
|
errbotio_errbot/errbot/bootstrap.py
|
import importlib
import logging
import sys
import warnings
from os import makedirs, path
from typing import Callable, Optional
from errbot.backend_plugin_manager import BackendPluginManager
from errbot.core import ErrBot
from errbot.logs import format_logs
from errbot.plugin_manager import BotPluginManager
from errbot.repo_manager import BotRepoManager
from errbot.storage.base import StoragePluginBase
from errbot.utils import PLUGINS_SUBDIR
log = logging.getLogger(__name__)
HERE = path.dirname(path.abspath(__file__))
CORE_BACKENDS = path.join(HERE, "backends")
CORE_STORAGE = path.join(HERE, "storage")
PLUGIN_DEFAULT_INDEX = "https://errbot.io/repos.json"
def bot_config_defaults(config: object) -> None:
if not hasattr(config, "ACCESS_CONTROLS_DEFAULT"):
config.ACCESS_CONTROLS_DEFAULT = {}
if not hasattr(config, "ACCESS_CONTROLS"):
config.ACCESS_CONTROLS = {}
if not hasattr(config, "HIDE_RESTRICTED_COMMANDS"):
config.HIDE_RESTRICTED_COMMANDS = False
if not hasattr(config, "HIDE_RESTRICTED_ACCESS"):
config.HIDE_RESTRICTED_ACCESS = False
if not hasattr(config, "BOT_PREFIX_OPTIONAL_ON_CHAT"):
config.BOT_PREFIX_OPTIONAL_ON_CHAT = False
if not hasattr(config, "BOT_PREFIX"):
config.BOT_PREFIX = "!"
if not hasattr(config, "BOT_ALT_PREFIXES"):
config.BOT_ALT_PREFIXES = ()
if not hasattr(config, "BOT_ALT_PREFIX_SEPARATORS"):
config.BOT_ALT_PREFIX_SEPARATORS = ()
if not hasattr(config, "BOT_ALT_PREFIX_CASEINSENSITIVE"):
config.BOT_ALT_PREFIX_CASEINSENSITIVE = False
if not hasattr(config, "DIVERT_TO_PRIVATE"):
config.DIVERT_TO_PRIVATE = ()
if not hasattr(config, "DIVERT_TO_THREAD"):
config.DIVERT_TO_THREAD = ()
if not hasattr(config, "MESSAGE_SIZE_LIMIT"):
config.MESSAGE_SIZE_LIMIT = None # No user limit declared.
if not hasattr(config, "GROUPCHAT_NICK_PREFIXED"):
config.GROUPCHAT_NICK_PREFIXED = False
if not hasattr(config, "AUTOINSTALL_DEPS"):
config.AUTOINSTALL_DEPS = True
if not hasattr(config, "SUPPRESS_CMD_NOT_FOUND"):
config.SUPPRESS_CMD_NOT_FOUND = False
if not hasattr(config, "BOT_ASYNC"):
config.BOT_ASYNC = True
if not hasattr(config, "BOT_ASYNC_POOLSIZE"):
config.BOT_ASYNC_POOLSIZE = 10
if not hasattr(config, "CHATROOM_PRESENCE"):
config.CHATROOM_PRESENCE = ()
if not hasattr(config, "CHATROOM_RELAY"):
config.CHATROOM_RELAY = ()
if not hasattr(config, "REVERSE_CHATROOM_RELAY"):
config.REVERSE_CHATROOM_RELAY = ()
if not hasattr(config, "CHATROOM_FN"):
config.CHATROOM_FN = "Errbot"
if not hasattr(config, "TEXT_DEMO_MODE"):
config.TEXT_DEMO_MODE = True
if not hasattr(config, "BOT_ADMINS"):
raise ValueError("BOT_ADMINS missing from config.py.")
if not hasattr(config, "TEXT_COLOR_THEME"):
config.TEXT_COLOR_THEME = "light"
if not hasattr(config, "BOT_ADMINS_NOTIFICATIONS"):
config.BOT_ADMINS_NOTIFICATIONS = config.BOT_ADMINS
def setup_bot(
backend_name: str,
logger: logging.Logger,
config: object,
restore: Optional[str] = None,
) -> ErrBot:
# from here the environment is supposed to be set (daemon / non daemon,
# config.py in the python path )
bot_config_defaults(config)
if hasattr(config, "BOT_LOG_FORMATTER"):
format_logs(formatter=config.BOT_LOG_FORMATTER)
else:
format_logs(theme_color=config.TEXT_COLOR_THEME)
if hasattr(config, "BOT_LOG_FILE") and config.BOT_LOG_FILE:
hdlr = logging.FileHandler(config.BOT_LOG_FILE)
hdlr.setFormatter(
logging.Formatter("%(asctime)s %(levelname)-8s %(name)-25s %(message)s")
)
logger.addHandler(hdlr)
if hasattr(config, "BOT_LOG_SENTRY") and config.BOT_LOG_SENTRY:
sentry_integrations = []
try:
import sentry_sdk
from sentry_sdk.integrations.logging import LoggingIntegration
except ImportError:
log.exception(
"You have BOT_LOG_SENTRY enabled, but I couldn't import modules "
"needed for Sentry integration. Did you install sentry-sdk? "
"(See https://docs.sentry.io/platforms/python for installation instructions)"
)
exit(-1)
sentry_logging = LoggingIntegration(
level=config.SENTRY_LOGLEVEL, event_level=config.SENTRY_EVENTLEVEL
)
sentry_integrations.append(sentry_logging)
if hasattr(config, "BOT_LOG_SENTRY_FLASK") and config.BOT_LOG_SENTRY_FLASK:
try:
from sentry_sdk.integrations.flask import FlaskIntegration
except ImportError:
log.exception(
"You have BOT_LOG_SENTRY enabled, but I couldn't import modules "
"needed for Sentry integration. Did you install sentry-sdk[flask]? "
"(See https://docs.sentry.io/platforms/python/flask for installation instructions)"
)
exit(-1)
sentry_integrations.append(FlaskIntegration())
sentry_options = getattr(config, "SENTRY_OPTIONS", {})
if hasattr(config, "SENTRY_TRANSPORT") and isinstance(
config.SENTRY_TRANSPORT, tuple
):
warnings.warn(
"SENTRY_TRANSPORT is deprecated. Please use SENTRY_OPTIONS instead.",
DeprecationWarning,
)
try:
mod = importlib.import_module(config.SENTRY_TRANSPORT[1])
transport = getattr(mod, config.SENTRY_TRANSPORT[0])
sentry_options["transport"] = transport
except ImportError:
log.exception(
f"Unable to import selected SENTRY_TRANSPORT - {config.SENTRY_TRANSPORT}"
)
exit(-1)
# merge options dict with dedicated SENTRY_DSN setting
sentry_kwargs = {
**sentry_options,
**{"dsn": config.SENTRY_DSN, "integrations": sentry_integrations},
}
sentry_sdk.init(**sentry_kwargs)
logger.setLevel(config.BOT_LOG_LEVEL)
storage_plugin = get_storage_plugin(config)
# init the botplugin manager
botplugins_dir = path.join(config.BOT_DATA_DIR, PLUGINS_SUBDIR)
if not path.exists(botplugins_dir):
makedirs(botplugins_dir, mode=0o755)
plugin_indexes = getattr(config, "BOT_PLUGIN_INDEXES", (PLUGIN_DEFAULT_INDEX,))
if isinstance(plugin_indexes, str):
plugin_indexes = (plugin_indexes,)
# 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]
backendpm = BackendPluginManager(
config, "errbot.backends", backend_name, ErrBot, CORE_BACKENDS, extra_backend
)
log.info(f"Found Backend plugin: {backendpm.plugin_info.name}")
repo_manager = BotRepoManager(storage_plugin, botplugins_dir, plugin_indexes)
try:
bot = backendpm.load_plugin()
botpm = BotPluginManager(
storage_plugin,
config.BOT_EXTRA_PLUGIN_DIR,
config.AUTOINSTALL_DEPS,
getattr(config, "CORE_PLUGINS", None),
lambda name, clazz: clazz(bot, name),
getattr(config, "PLUGINS_CALLBACK_ORDER", (None,)),
)
bot.attach_storage_plugin(storage_plugin)
bot.attach_repo_manager(repo_manager)
bot.attach_plugin_manager(botpm)
bot.initialize_backend_storage()
# restore the bot from the restore script
if restore:
# Prepare the context for the restore script
if "repos" in bot:
log.fatal("You cannot restore onto a non empty bot.")
sys.exit(-1)
log.info(f"**** RESTORING the bot from {restore}")
restore_bot_from_backup(restore, bot=bot, log=log)
print("Restore complete. You can restart the bot normally")
sys.exit(0)
errors = bot.plugin_manager.update_plugin_places(
repo_manager.get_all_repos_paths()
)
if errors:
startup_errors = "\n".join(errors.values())
log.error("Some plugins failed to load:\n%s", startup_errors)
bot._plugin_errors_during_startup = startup_errors
return bot
except Exception:
log.exception("Unable to load or configure the backend.")
exit(-1)
def restore_bot_from_backup(backup_filename: str, *, bot, log: logging.Logger):
"""Restores the given bot by executing the 'backup' script.
The backup file is a python script which manually execute a series of commands on the bot
to restore it to its previous state.
:param backup_filename: the full path to the backup script.
:param bot: the bot instance to restore
:param log: logger to use during the restoration process
"""
with open(backup_filename) as f:
exec(f.read(), {"log": log, "bot": bot})
bot.close_storage()
def get_storage_plugin(config: object) -> Callable:
"""
Find and load the storage plugin
:param config: the bot configuration.
:return: the storage plugin
"""
storage_name = getattr(config, "STORAGE", "Shelf")
extra_storage_plugins_dir = getattr(config, "BOT_EXTRA_STORAGE_PLUGINS_DIR", None)
spm = BackendPluginManager(
config,
"errbot.storage",
storage_name,
StoragePluginBase,
CORE_STORAGE,
extra_storage_plugins_dir,
)
log.info(f"Found Storage plugin: {spm.plugin_info.name}.")
return spm.load_plugin()
def bootstrap(
bot_class, logger: logging.Logger, config: object, restore: Optional[str] = None
) -> None:
"""
Main starting point of Errbot.
:param bot_class: The backend class inheriting from Errbot you want to start.
:param logger: The logger you want to use.
:param config: The config.py module.
:param restore: Start Errbot in restore mode (from a backup).
"""
bot = setup_bot(bot_class, logger, config, restore)
log.debug(f"Start serving commands from the {bot.mode} backend.")
bot.serve_forever()
| 10,328
|
Python
|
.py
| 233
| 36.085837
| 103
| 0.65722
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,156
|
repo_manager.py
|
errbotio_errbot/errbot/repo_manager.py
|
import json
import logging
import os
import re
import shutil
import tarfile
from collections import namedtuple
from datetime import datetime, timedelta
from os import path
from pathlib import Path
from typing import Dict, Generator, List, Optional, Sequence, Tuple
from urllib.error import HTTPError, URLError
from urllib.parse import urlparse
from urllib.request import Request, urlopen
from errbot.storage import StoreMixin
from errbot.storage.base import StoragePluginBase
from .utils import ON_WINDOWS, git_clone, git_pull
log = logging.getLogger(__name__)
def human_name_for_git_url(url: str) -> str:
# try to humanize the last part of the git url as much as we can
s = url.split(":")[-1].split("/")[-2:]
if s[-1].endswith(".git"):
s[-1] = s[-1][:-4]
return str("/".join(s))
INSTALLED_REPOS = "installed_repos"
REPO_INDEXES_CHECK_INTERVAL = timedelta(hours=1)
REPO_INDEX = "repo_index"
LAST_UPDATE = "last_update"
RepoEntry = namedtuple(
"RepoEntry", "entry_name, name, python, repo, path, avatar_url, documentation"
)
FIND_WORDS_RE = re.compile(r"(\w[\w']*\w|\w)")
class RepoException(Exception):
pass
def makeEntry(repo_name: str, plugin_name: str, json_value: dict) -> RepoEntry:
return RepoEntry(
entry_name=repo_name,
name=plugin_name,
python=json_value["python"],
repo=json_value["repo"],
path=json_value["path"],
avatar_url=json_value["avatar_url"],
documentation=json_value["documentation"],
)
def tokenizeJsonEntry(json_dict: dict) -> set:
"""
Returns all the words in a repo entry.
"""
search = " ".join((str(word) for word in json_dict.values()))
return set(FIND_WORDS_RE.findall(search.lower()))
def which(program: str) -> Optional[str]:
if ON_WINDOWS:
program += ".exe"
def is_exe(file_path):
return os.path.isfile(file_path) and os.access(file_path, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
def check_dependencies(req_path: Path) -> Tuple[Optional[str], Sequence[str]]:
"""This methods returns a pair of (message, packages missing).
Or None, [] if everything is OK.
"""
log.debug("check dependencies of %s", req_path)
# noinspection PyBroadException
try:
from pkg_resources import get_distribution
missing_pkg = []
if not req_path.is_file():
log.debug("%s has no requirements.txt file", req_path)
return None, missing_pkg
with req_path.open() as f:
for line in f:
stripped = line.strip()
# skip empty lines.
if not stripped:
continue
# noinspection PyBroadException
try:
get_distribution(stripped)
except Exception:
missing_pkg.append(stripped)
if missing_pkg:
return (
f"You need these dependencies for {req_path}: " + ",".join(missing_pkg),
missing_pkg,
)
return None, missing_pkg
except Exception:
log.exception("Problem checking for dependencies.")
return (
"You need to have setuptools installed for the dependency check of the plugins",
[],
)
class BotRepoManager(StoreMixin):
"""
Manages the repo list, git clones/updates or the repos.
"""
def __init__(
self,
storage_plugin: StoragePluginBase,
plugin_dir: str,
plugin_indexes: Tuple[str, ...],
) -> None:
"""
Make a repo manager.
:param storage_plugin: where the manager store its state.
:param plugin_dir: where on disk it will git clone the repos.
:param plugin_indexes: a list of URL / path to get the json repo index.
"""
super().__init__()
self.plugin_indexes = plugin_indexes
self.storage_plugin = storage_plugin
self.plugin_dir = plugin_dir
self.open_storage(storage_plugin, "repomgr")
def shutdown(self) -> None:
self.close_storage()
def check_for_index_update(self) -> None:
if REPO_INDEX not in self:
log.info("No repo index, creating it.")
self.index_update()
return
if (
datetime.fromtimestamp(self[REPO_INDEX][LAST_UPDATE])
< datetime.now() - REPO_INDEXES_CHECK_INTERVAL
):
log.info("Index is too old, update it.")
self.index_update()
def index_update(self) -> None:
index = {LAST_UPDATE: datetime.now().timestamp()}
for source in reversed(self.plugin_indexes):
try:
if urlparse(source).scheme in ("http", "https"):
req = Request(source, headers={"User-Agent": "Errbot"})
with urlopen(url=req, timeout=10) as request: # nosec
log.debug("Update from remote source %s...", source)
encoding = request.headers.get_content_charset()
content = request.read().decode(
encoding if encoding else "utf-8"
)
else:
with open(source, encoding="utf-8", mode="r") as src_file:
log.debug("Update from local source %s...", source)
content = src_file.read()
index.update(json.loads(content))
except (HTTPError, URLError, IOError):
log.exception(
"Could not update from source %s, keep the index as it is.", source
)
break
else:
# nothing failed so ok, we can store the index.
self[REPO_INDEX] = index
log.debug("Stored %d repo entries.", len(index) - 1)
def get_repo_from_index(self, repo_name: str) -> List[RepoEntry]:
"""
Retrieve the list of plugins for the repo_name from the index.
:param repo_name: the name of the repo
:return: a list of RepoEntry
"""
plugins = self[REPO_INDEX].get(repo_name, None)
if plugins is None:
return None
result = []
for name, plugin in plugins.items():
result.append(makeEntry(repo_name, name, plugin))
return result
def search_repos(self, query: str) -> Generator[RepoEntry, None, None]:
"""
A simple search feature, keywords are AND and case insensitive on all the fields.
:param query: a string query
:return: an iterator of RepoEntry
"""
# first see if we are up to date.
self.check_for_index_update()
if REPO_INDEX not in self:
log.error("No index.")
return
query_work_set = set(FIND_WORDS_RE.findall(query.lower()))
for repo_name, plugins in self[REPO_INDEX].items():
if repo_name == LAST_UPDATE:
continue
for plugin_name, plugin in plugins.items():
if query_work_set.intersection(tokenizeJsonEntry(plugin)):
yield makeEntry(repo_name, plugin_name, plugin)
def get_installed_plugin_repos(self) -> Dict[str, str]:
return self.get(INSTALLED_REPOS, {})
def add_plugin_repo(self, name: str, url: str) -> None:
with self.mutable(INSTALLED_REPOS, {}) as repos:
repos[name] = url
def set_plugin_repos(self, repos: Dict[str, str]) -> None:
"""Used externally."""
self[INSTALLED_REPOS] = repos
def get_all_repos_paths(self) -> List[str]:
return [
os.path.join(self.plugin_dir, d)
for d in self.get(INSTALLED_REPOS, {}).keys()
]
def install_repo(self, repo: str) -> str:
"""
Install the repository from repo
:param repo:
The url, git url or path on disk of a repository. It can point to either a git repo or
a .tar.gz of a plugin
:returns:
The path on disk where the repo has been installed on.
:raises: :class:`~RepoException` if an error occured.
"""
self.check_for_index_update()
human_name = None
# try to find if we have something with that name in our index
if repo in self[REPO_INDEX]:
human_name = repo
repo_url = next(iter(self[REPO_INDEX][repo].values()))["repo"]
elif not repo.endswith("tar.gz"):
# This is a repo url, make up a plugin definition for it
human_name = human_name_for_git_url(repo)
repo_url = repo
else:
repo_url = repo
# TODO: Update download path of plugin.
if repo_url.endswith("tar.gz"):
fo = urlopen(repo_url) # nosec
tar = tarfile.open(fileobj=fo, mode="r:gz")
tar.extractall(path=self.plugin_dir)
s = repo_url.split(":")[-1].split("/")[-1]
human_name = s[: -len(".tar.gz")]
else:
human_name = human_name or human_name_for_git_url(repo_url)
try:
git_clone(repo_url, os.path.join(self.plugin_dir, human_name))
except (
Exception
) as exception: # dulwich errors all base on exceptions.Exception
raise RepoException(
f"Could not load this plugin: \n\n{repo_url}\n\n---\n\n{exception}"
)
self.add_plugin_repo(human_name, repo_url)
return os.path.join(self.plugin_dir, human_name)
def update_repos(self, repos) -> Generator[Tuple[str, int, str], None, None]:
"""
This git pulls the specified repos on disk.
Yields tuples like (name, success, reason)
"""
# protects for update outside of what we know is installed
names = set(self.get_installed_plugin_repos().keys()).intersection(set(repos))
for d in (path.join(self.plugin_dir, name) for name in names):
success = False
try:
git_pull(d)
feedback = "Pulled remote"
success = True
except Exception as exception:
feedback = f"Error pulling remote {exception}"
pass
dep_err, missing_pkgs = check_dependencies(Path(d) / "requirements.txt")
if dep_err:
feedback += dep_err + "\n"
yield d, success, feedback
def update_all_repos(self) -> Generator[Tuple[str, int, str], None, None]:
return self.update_repos(self.get_installed_plugin_repos().keys())
def uninstall_repo(self, name: str) -> None:
repo_path = path.join(self.plugin_dir, name)
# ignore errors because the DB can be desync'ed from the file tree.
shutil.rmtree(repo_path, ignore_errors=True)
repos = self.get_installed_plugin_repos()
del repos[name]
self.set_plugin_repos(repos)
| 11,285
|
Python
|
.py
| 274
| 31.160584
| 98
| 0.587097
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,157
|
version.py
|
errbotio_errbot/errbot/version.py
|
# Just the current version of Errbot.
# It is used for deployment on pypi AND for version checking at plugin load time.
VERSION = "9.9.9" # leave it at 9.9.9 on master until it is branched to a version.
| 204
|
Python
|
.py
| 3
| 67
| 83
| 0.746269
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,158
|
shelf.py
|
errbotio_errbot/errbot/storage/shelf.py
|
import logging
import os
import shelve
import shutil
from typing import Any
from errbot.storage.base import StorageBase, StoragePluginBase
log = logging.getLogger("errbot.storage.shelf")
class ShelfStorage(StorageBase):
def __init__(self, path):
log.debug("Open shelf storage %s", path)
self.shelf = shelve.DbfilenameShelf(path, protocol=2)
def get(self, key: str) -> Any:
return self.shelf[key]
def remove(self, key: str):
if key not in self.shelf:
raise KeyError(f"{key} doesn't exist.")
del self.shelf[key]
def set(self, key: str, value: Any) -> None:
self.shelf[key] = value
def len(self):
return len(self.shelf)
def keys(self):
return self.shelf.keys()
def close(self) -> None:
self.shelf.close()
self.shelf = None
class ShelfStoragePlugin(StoragePluginBase):
def __init__(self, bot_config):
super().__init__(bot_config)
if "basedir" not in self._storage_config:
self._storage_config["basedir"] = bot_config.BOT_DATA_DIR
def open(self, namespace: str) -> StorageBase:
config = self._storage_config
# Hack to port move old DBs to the new location.
new_spot = os.path.join(config["basedir"], namespace + ".db")
old_spot = os.path.join(config["basedir"], "plugins", namespace + ".db")
if os.path.isfile(old_spot):
if os.path.isfile(new_spot):
log.warning(
"You have an old v3 DB at %s and a duplicate new one at %s.",
old_spot,
new_spot,
)
log.warning(
"You need to either remove the old one or move it in place of the new one manually."
)
else:
log.info("Moving your old v3 DB from %s to %s.", old_spot, new_spot)
shutil.move(old_spot, new_spot)
return ShelfStorage(new_spot)
| 1,997
|
Python
|
.py
| 50
| 30.58
| 104
| 0.594413
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,159
|
memory.py
|
errbotio_errbot/errbot/storage/memory.py
|
from typing import Any
from errbot.storage.base import StorageBase, StoragePluginBase
ROOTS = {} # make a little bit of an emulated persistence.
class MemoryStorage(StorageBase):
def __init__(self, namespace):
self.namespace = namespace
self.root = ROOTS.get(namespace, {})
def get(self, key: str) -> Any:
if key not in self.root:
raise KeyError(f"{key} doesn't exist.")
return self.root[key]
def set(self, key: str, value: Any) -> None:
self.root[key] = value
def remove(self, key: str):
if key not in self.root:
raise KeyError(f"{key} doesn't exist.")
del self.root[key]
def len(self):
return len(self.root)
def keys(self):
return self.root.keys()
def close(self) -> None:
ROOTS[self.namespace] = self.root
class MemoryStoragePlugin(StoragePluginBase):
def open(self, namespace: str) -> StorageBase:
return MemoryStorage(namespace)
| 991
|
Python
|
.py
| 26
| 31.115385
| 62
| 0.648478
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,160
|
__init__.py
|
errbotio_errbot/errbot/storage/__init__.py
|
import logging
from collections.abc import MutableMapping
from contextlib import contextmanager
log = logging.getLogger(__name__)
class StoreException(Exception):
pass
class StoreAlreadyOpenError(StoreException):
pass
class StoreNotOpenError(StoreException):
pass
class StoreMixin(MutableMapping):
"""
This class handle the basic needs of bot plugins and core like loading, unloading and creating a storage
"""
def __init__(self):
self._store = None
self.namespace = None
def open_storage(self, storage_plugin, namespace):
if self.is_open_storage():
raise StoreAlreadyOpenError("Storage appears to be opened already")
log.debug("Opening storage '%s'", namespace)
self._store = storage_plugin.open(namespace)
self.namespace = namespace
def close_storage(self):
if not self.is_open_storage():
raise StoreNotOpenError("Storage does not appear to have been opened yet")
self._store.close()
self._store = None
log.debug("Closed storage '%s'", self.namespace)
def is_open_storage(self):
has_store_key = hasattr(self, "_store")
if has_store_key and self._store:
return True
elif not has_store_key or self._store is None:
return False
else:
return False
# those are the minimal things to behave like a dictionary with the UserDict.DictMixin
def __getitem__(self, key):
return self._store.get(key)
@contextmanager
def mutable(self, key, default=None):
try:
obj = self._store.get(key)
except KeyError:
obj = default
yield obj
# implements autosave for a plugin persistent entry
# with self['foo'] as f:
# f[4] = 2
# saves the entry !
self._store.set(key, obj)
def __setitem__(self, key, item):
return self._store.set(key, item)
def __delitem__(self, key):
return self._store.remove(key)
def keys(self):
return self._store.keys()
def __len__(self):
return self._store.len()
def __iter__(self):
for i in self._store.keys():
yield i
def __contains__(self, x):
try:
self._store.get(x)
return True
except KeyError:
return False
# compatibility with with
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close_storage()
| 2,544
|
Python
|
.py
| 74
| 26.581081
| 108
| 0.622395
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,161
|
base.py
|
errbotio_errbot/errbot/storage/base.py
|
from abc import abstractmethod
from typing import Any, Iterable
class StorageBase:
"""
Contract to implemement a storage.
"""
@abstractmethod
def set(self, key: str, value: Any) -> None:
"""
Atomically set the key to the given value.
The caller of set will protect against set on non open.
:param key: string as key
:param value: pickalable python object
"""
pass
@abstractmethod
def get(self, key: str) -> Any:
"""
Get the value stored for key. Raises KeyError if the key doesn't exist.
The caller of get will protect against get on non open.
:param key: the key
:return: the value
"""
pass
@abstractmethod
def remove(self, key: str) -> None:
"""
Remove key. Raises KeyError if the key doesn't exist.
The caller of get will protect against get on non open.
:param key: the key
"""
pass
@abstractmethod
def len(self) -> int:
"""
:return: the number of keys set.
"""
pass
@abstractmethod
def keys(self) -> Iterable[str]:
"""
:return: an iterator on all the entries
"""
pass
@abstractmethod
def close(self) -> None:
"""
Sync and close the storage.
The caller of close will protect against close on non open and double close.
"""
pass
class StoragePluginBase:
"""
Base to implement a storage plugin.
This is a factory for the namespaces.
"""
def __init__(self, bot_config):
self._storage_config = getattr(bot_config, "STORAGE_CONFIG", {})
@abstractmethod
def open(self, namespace: str) -> StorageBase:
"""
Open the storage with the given namespace (core, or plugin name) and config.
The caller of open will protect against double opens.
:param namespace: a namespace to isolate the plugin storages.
:return:
"""
pass
| 2,048
|
Python
|
.py
| 67
| 23.089552
| 84
| 0.602649
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,162
|
new_plugin.py.tmpl
|
errbotio_errbot/errbot/templates/new_plugin.py.tmpl
|
from errbot import BotPlugin, arg_botcmd, botcmd, webhook
class {{ class_name }}(BotPlugin):
"""
{{ description }}
"""
def activate(self):
"""
Triggers on plugin activation
You should delete it if you're not using it to override any default behaviour
"""
super({{ class_name }}, self).activate()
def deactivate(self):
"""
Triggers on plugin deactivation
You should delete it if you're not using it to override any default behaviour
"""
super({{ class_name }}, self).deactivate()
def get_configuration_template(self):
"""
Defines the configuration structure this plugin supports
You should delete it if your plugin doesn't use any configuration like this
"""
return {
"EXAMPLE_KEY_1": "Example value",
"EXAMPLE_KEY_2": ["Example", "Value"],
}
def check_configuration(self, configuration):
"""
Triggers when the configuration is checked, shortly before activation
Raise a errbot.ValidationException in case of an error
You should delete it if you're not using it to override any default behaviour
"""
super({{ class_name }}, self).check_configuration(configuration)
def callback_connect(self):
"""
Triggers when bot is connected
You should delete it if you're not using it to override any default behaviour
"""
pass
def callback_message(self, message):
"""
Triggered for every received message that isn't coming from the bot itself
You should delete it if you're not using it to override any default behaviour
"""
pass
def callback_botmessage(self, message):
"""
Triggered for every message that comes from the bot itself
You should delete it if you're not using it to override any default behaviour
"""
pass
@webhook
def example_webhook(self, incoming_request):
"""A webhook which simply returns 'Example'"""
return "Example"
# Passing split_args_with=None will cause arguments to be split on any kind
# of whitespace, just like Python's split() does
@botcmd(split_args_with=None)
def example(self, message, args):
"""A command which simply returns 'Example'"""
return "Example"
@arg_botcmd("name", type=str)
@arg_botcmd("--favorite-number", type=int, unpack_args=False)
def hello(self, message, args):
"""
A command which says hello to someone.
If you include --favorite-number, it will also tell you their
favorite number.
"""
if args.favorite_number:
return f"Hello {args.name}, I hear your favorite number is {args.favorite_number}."
else:
return f"Hello {args.name}."
| 2,901
|
Python
|
.py
| 73
| 31.493151
| 95
| 0.636266
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,163
|
example.py
|
errbotio_errbot/errbot/templates/initdir/example.py
|
from errbot import BotPlugin, botcmd
class Example(BotPlugin):
"""
This is a very basic plugin to try out your new installation and get you started.
Feel free to tweak me to experiment with Errbot.
You can find me in your init directory in the subdirectory plugins.
"""
@botcmd # flags a command
def tryme(self, msg, args): # a command callable with !tryme
"""
Execute to check if Errbot responds to command.
Feel free to tweak me to experiment with Errbot.
You can find me in your init directory in the subdirectory plugins.
"""
return "It *works*!" # This string format is markdown.
| 667
|
Python
|
.py
| 15
| 38.2
| 85
| 0.687211
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,164
|
config.py.tmpl
|
errbotio_errbot/errbot/templates/initdir/config.py.tmpl
|
import logging
# This is a minimal configuration to get you started with the Text mode.
# If you want to connect Errbot to chat services, checkout
# the options in the more complete config-template.py from here:
# https://raw.githubusercontent.com/errbotio/errbot/master/errbot/config-template.py
BACKEND = "Text" # Errbot will start in text mode (console only mode) and will answer commands from there.
BOT_DATA_DIR = r"{{ data_dir }}"
BOT_EXTRA_PLUGIN_DIR = r"{{ extra_plugin_dir }}"
BOT_EXTRA_BACKEND_DIR = r"{{ extra_backend_plugin_dir }}"
BOT_LOG_FILE = r"{{ log_path }}"
BOT_LOG_LEVEL = logging.INFO
BOT_ADMINS = (
"@CHANGE_ME",
) # Don't leave this as "@CHANGE_ME" if you connect your errbot to a chat system!!
| 729
|
Python
|
.py
| 14
| 50.428571
| 107
| 0.73662
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,165
|
webserver.py
|
errbotio_errbot/errbot/core_plugins/webserver.py
|
import logging
import os
import sys
from json import loads
from random import randrange
from threading import Thread
from urllib.request import unquote
from OpenSSL import crypto
from webtest import TestApp
from werkzeug.serving import ThreadedWSGIServer
from errbot import BotPlugin, botcmd, webhook
from errbot.core_plugins import flask_app
def make_ssl_certificate(key_path, cert_path):
"""
Generate a self-signed certificate
The generated key will be written out to key_path, with the corresponding
certificate itself being written to cert_path.
:param cert_path: path where to write the certificate.
:param key_path: path where to write the key.
"""
cert = crypto.X509()
cert.set_serial_number(randrange(1, sys.maxsize))
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(60 * 60 * 24 * 365)
subject = cert.get_subject()
subject.CN = "*"
setattr(
subject, "O", "Self-Signed Certificate for Errbot"
) # Pep8 annoyance workaround
issuer = cert.get_issuer()
issuer.CN = "Self-proclaimed Authority"
setattr(issuer, "O", "Self-Signed") # Pep8 annoyance workaround
pkey = crypto.PKey()
pkey.generate_key(crypto.TYPE_RSA, 4096)
cert.set_pubkey(pkey)
cert.sign(pkey, "sha256")
f = open(cert_path, "w")
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode("utf-8"))
f.close()
f = open(key_path, "w")
f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey).decode("utf-8"))
f.close()
class Webserver(BotPlugin):
def __init__(self, *args, **kwargs):
self.server = None
self.server_thread = None
self.ssl_context = None
self.test_app = TestApp(flask_app)
super().__init__(*args, **kwargs)
def get_configuration_template(self):
return {
"HOST": "0.0.0.0",
"PORT": 3141,
"SSL": {
"enabled": False,
"host": "0.0.0.0",
"port": 3142,
"certificate": "",
"key": "",
},
}
def check_configuration(self, configuration):
# it is a pain, just assume a default config if SSL is absent or set to None
if configuration.get("SSL", None) is None:
configuration["SSL"] = {
"enabled": False,
"host": "0.0.0.0",
"port": 3142,
"certificate": "",
"key": "",
}
super().check_configuration(configuration)
def activate(self):
if not self.config:
self.log.info("Webserver is not configured. Forbid activation")
return
if self.server_thread and self.server_thread.is_alive():
raise Exception(
"Invalid state, you should not have a webserver already running."
)
self.server_thread = Thread(target=self.run_server, name="Webserver Thread")
self.server_thread.start()
self.log.debug("Webserver started.")
super().activate()
def deactivate(self):
if self.server is not None:
self.log.info("Shutting down the internal webserver.")
self.server.shutdown()
self.log.info("Waiting for the webserver thread to quit.")
self.server_thread.join()
self.log.info("Webserver shut down correctly.")
super().deactivate()
def run_server(self):
try:
host = self.config["HOST"]
port = self.config["PORT"]
ssl = self.config["SSL"]
self.log.info("Starting the webserver on %s:%i", host, port)
ssl_context = (ssl["certificate"], ssl["key"]) if ssl["enabled"] else None
self.server = ThreadedWSGIServer(
host,
ssl["port"] if ssl_context else port,
flask_app,
ssl_context=ssl_context,
)
wsgi_log = logging.getLogger("werkzeug")
wsgi_log.setLevel(self.bot_config.BOT_LOG_LEVEL)
self.server.serve_forever()
self.log.debug("Webserver stopped")
except KeyboardInterrupt:
self.log.info("Keyboard interrupt, request a global shutdown.")
self.server.shutdown()
except Exception:
self.log.exception("The webserver exploded.")
@botcmd(template="webstatus")
def webstatus(self, msg, args):
"""
Gives a quick status of what is mapped in the internal webserver
"""
return {
"rules": (((rule.rule, rule.endpoint) for rule in flask_app.url_map._rules))
}
@webhook
def echo(self, incoming_request):
"""
A simple test webhook
"""
self.log.debug("Your incoming request is: %s", incoming_request)
return str(incoming_request)
@botcmd(split_args_with=" ", template="webserver")
def webhook_test(self, _, args):
"""
Test your webhooks from within err.
The syntax is :
!webhook test [relative_url] [post content]
It triggers the notification and generate also a little test report.
"""
url = args[0]
content = " ".join(args[1:])
# try to guess the content-type of what has been passed
try:
# try if it is plain json
loads(content)
contenttype = "application/json"
except ValueError:
# try if it is a form
splitted = content.split("=")
# noinspection PyBroadException
try:
payload = "=".join(splitted[1:])
loads(unquote(payload))
contenttype = "application/x-www-form-urlencoded"
except Exception as _:
contenttype = "text/plain" # dunno what it is
self.log.debug("Detected your post as : %s.", contenttype)
response = self.test_app.post(url, params=content, content_type=contenttype)
return {
"url": url,
"content": content,
"contenttype": contenttype,
"response": response,
}
@botcmd(admin_only=True)
def generate_certificate(self, _, args):
"""
Generate a self-signed SSL certificate for the Webserver
"""
yield (
"Generating a new private key and certificate. This could take a "
"while if your system is slow or low on entropy"
)
key_path = os.sep.join((self.bot_config.BOT_DATA_DIR, "webserver_key.pem"))
cert_path = os.sep.join(
(self.bot_config.BOT_DATA_DIR, "webserver_certificate.pem")
)
make_ssl_certificate(key_path=key_path, cert_path=cert_path)
yield f"Certificate successfully generated and saved in {self.bot_config.BOT_DATA_DIR}."
suggested_config = self.config
suggested_config["SSL"]["enabled"] = True
suggested_config["SSL"]["host"] = suggested_config["HOST"]
suggested_config["SSL"]["port"] = suggested_config["PORT"] + 1
suggested_config["SSL"]["key"] = key_path
suggested_config["SSL"]["certificate"] = cert_path
yield "To enable SSL with this certificate, the following config is recommended:"
yield f"{suggested_config!r}"
| 7,352
|
Python
|
.py
| 185
| 30.281081
| 96
| 0.597786
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,166
|
help.py
|
errbotio_errbot/errbot/core_plugins/help.py
|
import textwrap
from dulwich import errors as dulwich_errors
from errbot import BotPlugin, botcmd
from errbot.utils import git_tag_list
from errbot.version import VERSION
class Help(BotPlugin):
MSG_HELP_TAIL = (
"Type help <command name> to get more info " "about that specific command."
)
MSG_HELP_UNDEFINED_COMMAND = "That command is not defined."
def is_git_directory(self, path="."):
try:
tags = git_tag_list(path)
except dulwich_errors.NotGitRepository:
tags = None
except Exception as _:
# we might want to handle other exceptions another way. For now leaving this general
tags = None
return tags.pop(-1) if tags is not None else None
# noinspection PyUnusedLocal
@botcmd(template="about")
def about(self, msg, args):
"""Return information about this Errbot instance and version"""
git_version = self.is_git_directory()
if git_version:
return dict(version=f"{git_version.decode('utf-8')} GIT CHECKOUT")
else:
return {"version": VERSION}
# noinspection PyUnusedLocal
@botcmd
def apropos(self, msg, args):
"""Returns a help string listing available options.
Automatically assigned to the "help" command."""
if not args:
return "Usage: " + self._bot.prefix + "apropos search_term"
description = "Available commands:\n"
cls_commands = {}
for name, command in self._bot.all_commands.items():
cls = self._bot.get_plugin_class_from_method(command)
cls = str.__module__ + "." + cls.__name__ # makes the fuul qualified name
commands = cls_commands.get(cls, [])
if (
not self.bot_config.HIDE_RESTRICTED_COMMANDS
or self._bot.check_command_access(msg, name)[0]
):
commands.append((name, command))
cls_commands[cls] = commands
usage = ""
for cls in sorted(cls_commands):
commands = []
for name, command in cls_commands[cls]:
if name == "help":
continue
if command._err_command_hidden:
continue
doc = command.__doc__
if doc is not None and args.lower() not in doc.lower():
continue
name_with_spaces = name.replace("_", " ", 1)
doc = (doc or "(undocumented)").strip().split("\n", 1)[0]
commands.append("\t" + self._bot.prefix + name_with_spaces + ": " + doc)
usage += "\n".join(commands)
usage += "\n\n"
return "".join(filter(None, [description, usage])).strip()
@botcmd
def help(self, msg, args):
"""Returns a help string listing available options.
Automatically assigned to the "help" command."""
def may_access_command(m, cmd):
m, _, _ = self._bot._process_command_filters(
msg=m, cmd=cmd, args=None, dry_run=True
)
return m is not None
def get_name(named):
return named.__name__.lower()
# Normalize args to lowercase for ease of use
args = args.lower() if args else ""
usage = ""
description = "### All commands\n"
cls_obj_commands = {}
for name, command in self._bot.all_commands.items():
cls = self._bot.get_plugin_class_from_method(command)
obj = command.__self__
_, commands = cls_obj_commands.get(cls, (None, []))
if not self.bot_config.HIDE_RESTRICTED_COMMANDS or may_access_command(
msg, name
):
commands.append((name, command))
cls_obj_commands[cls] = (obj, commands)
# show all
if not args:
for cls in sorted(
cls_obj_commands.keys(), key=lambda c: cls_obj_commands[c][0].name
):
obj, commands = cls_obj_commands[cls]
name = obj.name
# shows class and description
usage += f"\n**{name}**\n\n"
if getattr(cls.__errdoc__, "strip", None):
usage += f"{cls.__errdoc__.strip()}\n\n"
else:
usage += cls.__errdoc__ or "\n\n"
for name, command in sorted(commands):
if command._err_command_hidden:
continue
# show individual commands
usage += self._cmd_help_line(name, command)
usage += "\n\n" # end cls section
elif args:
for cls, (obj, cmds) in cls_obj_commands.items():
if obj.name.lower() == args:
break
else:
cls, obj, cmds = None, None, None
if cls is None:
# Plugin not found.
description = ""
all_commands = dict(self._bot.all_commands)
all_commands.update(
{k.replace("_", " "): v for k, v in all_commands.items()}
)
if args in all_commands:
usage += self._cmd_help_line(args, all_commands[args], True)
else:
usage += self.MSG_HELP_UNDEFINED_COMMAND
else:
# filter out the commands related to this class
description = ""
description += f"\n**{obj.name}**\n\n"
if getattr(cls.__errdoc__, "strip", None):
description += f"{cls.__errdoc__.strip()}\n\n"
else:
description += cls.__errdoc__ or "\n\n"
pairs = []
for name, command in cmds:
if self.bot_config.HIDE_RESTRICTED_COMMANDS:
if command._err_command_hidden:
continue
if not may_access_command(msg, name):
continue
pairs.append((name, command))
pairs = sorted(pairs)
for name, command in pairs:
usage += self._cmd_help_line(name, command)
return "".join(filter(None, [description, usage]))
def _cmd_help_line(self, name, command, show_doc=False):
"""
Returns:
str. a single line indicating the help representation of a command.
"""
cmd_name = name.replace("_", " ")
cmd_doc = textwrap.dedent(self._bot.get_doc(command)).strip()
prefix = (
self._bot.prefix
if getattr(command, "_err_command_prefix_required", True)
else ""
)
name = cmd_name
patt = getattr(command, "_err_command_re_pattern", None)
if patt:
re_help_name = getattr(command, "_err_command_re_name_help", None)
name = re_help_name if re_help_name else patt.pattern
if not show_doc:
cmd_doc = cmd_doc.split("\n")[0]
if len(cmd_doc) > 80:
cmd_doc = f"{cmd_doc[:77]}..."
help_str = f"- **{prefix}{name}** - {cmd_doc}\n"
return help_str
| 7,318
|
Python
|
.py
| 168
| 30.267857
| 96
| 0.519893
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,167
|
plugins.py
|
errbotio_errbot/errbot/core_plugins/plugins.py
|
import logging
import os
import shutil
from ast import literal_eval
from pprint import pformat
from errbot import BotPlugin, botcmd
from errbot.plugin_manager import (
PluginActivationException,
PluginConfigurationException,
)
from errbot.repo_manager import RepoException
class Plugins(BotPlugin):
@botcmd(admin_only=True)
def repos_install(self, _, args):
"""install a plugin repository from the given source or a known public repo (see !repos to find those).
for example from a known repo: !install err-codebot
for example a git url: git@github.com:gbin/plugin.git
or an url towards an archive: https://github.com/errbotio/err-helloworld/archive/refs/heads/master.zip
"""
args = args.strip()
if not args:
yield 'Please specify a repository listed in "!repos" or "give me the URL to a git repository that I should clone for you."'
return
try:
yield f"Installing {args}..."
local_path = self._bot.repo_manager.install_repo(args)
errors = self._bot.plugin_manager.update_plugin_places(
self._bot.repo_manager.get_all_repos_paths()
)
if errors:
v = "\n".join(errors.values())
yield f"Some plugins are generating errors:\n{v}."
# if the load of the plugin failed, uninstall cleanly teh repo
for path in errors.keys():
if str(path).startswith(local_path):
yield f"Removing {local_path} as it did not load correctly."
shutil.rmtree(local_path)
else:
yield f"A new plugin repository has been installed correctly from {args}. Refreshing the plugins commands..."
loading_errors = self._bot.plugin_manager.activate_non_started_plugins()
if loading_errors:
yield loading_errors
yield "Plugins reloaded."
except RepoException as re:
yield f"Error installing the repo: {re}"
@botcmd(admin_only=True)
def repos_uninstall(self, _, repo_name):
"""uninstall a plugin repository by name."""
if not repo_name.strip():
yield "You should have a repo name as argument"
return
repos = self._bot.repo_manager.get_installed_plugin_repos()
if repo_name not in repos:
yield f"This repo is not installed check with {self._bot.prefix}repos the list of installed ones"
return
plugin_path = os.path.join(self._bot.repo_manager.plugin_dir, repo_name)
self._bot.plugin_manager.remove_plugins_from_path(plugin_path)
self._bot.repo_manager.uninstall_repo(repo_name)
yield f"Repo {repo_name} removed."
@botcmd(template="repos")
def repos(self, _, args):
"""list the current active plugin repositories"""
installed_repos = self._bot.repo_manager.get_installed_plugin_repos()
all_names = [name for name in installed_repos]
repos = {"repos": []}
for repo_name in all_names:
installed = False
if repo_name in installed_repos:
installed = True
from_index = self._bot.repo_manager.get_repo_from_index(repo_name)
if from_index is not None:
description = "\n".join(
(f"{plug.name}: {plug.documentation}" for plug in from_index)
)
else:
description = "No description."
# installed, public, name, desc
repos["repos"].append(
(installed, from_index is not None, repo_name, description)
)
return repos
@botcmd(template="repos2")
def repos_search(self, _, args):
"""Searches the repo index.
for example: !repos search jenkins
"""
if not args:
# TODO(gbin): return all the repos.
return {"error": "Please specify a keyword."}
return {"repos": self._bot.repo_manager.search_repos(args)}
@botcmd(split_args_with=" ", admin_only=True)
def repos_update(self, _, args):
"""update the bot and/or plugins
use: !repos update all
to update everything
or: !repos update repo_name repo_name ...
to update selectively some repos
"""
if "all" in args:
results = self._bot.repo_manager.update_all_repos()
else:
results = self._bot.repo_manager.update_repos(args)
yield "Start updating ... "
for d, success, feedback in results:
if success:
yield f"Update of {d} succeeded...\n\n{feedback}\n\n"
for plugin in self._bot.plugin_manager.get_plugins_by_path(d):
if hasattr(plugin, "is_activated") and plugin.is_activated:
name = plugin.name
yield f"/me is reloading plugin {name}"
try:
self._bot.plugin_manager.reload_plugin_by_name(plugin.name)
yield f"Plugin {plugin.name} reloaded."
except PluginActivationException as pae:
yield f"Error reactivating plugin {plugin.name}: {pae}"
else:
yield f"Update of {d} failed...\n\n{feedback}"
yield "Done."
@botcmd(split_args_with=" ", admin_only=True)
def plugin_config(self, _, args):
"""configure or get the configuration / configuration template for a specific plugin
ie.
!plugin config ExampleBot
could return a template if it is not configured:
{'LOGIN': 'example@example.com', 'PASSWORD': 'password', 'DIRECTORY': '/toto'}
Copy paste, adapt so can configure the plugin:
!plugin config ExampleBot {'LOGIN': 'my@email.com', 'PASSWORD': 'myrealpassword', 'DIRECTORY': '/tmp'}
It will then reload the plugin with this config.
You can at any moment retrieve the current values:
!plugin config ExampleBot
should return:
{'LOGIN': 'my@email.com', 'PASSWORD': 'myrealpassword', 'DIRECTORY': '/tmp'}
"""
plugin_name = args[0]
if self._bot.plugin_manager.is_plugin_blacklisted(plugin_name):
return f"Load this plugin first with {self._bot.prefix} load {plugin_name}."
obj = self._bot.plugin_manager.get_plugin_obj_by_name(plugin_name)
if obj is None:
return f"Unknown plugin or the plugin could not load {plugin_name}."
template_obj = obj.get_configuration_template()
if template_obj is None:
return "This plugin is not configurable."
if len(args) == 1:
response = (
f"Default configuration for this plugin (you can copy and paste this directly as a command):"
f"\n\n```\n{self._bot.prefix}plugin config {plugin_name} {pformat(template_obj)}\n```"
)
current_config = self._bot.plugin_manager.get_plugin_configuration(
plugin_name
)
if current_config:
response += (
f"\n\nCurrent configuration:\n\n```\n{self._bot.prefix}plugin config {plugin_name} "
f"{pformat(current_config)}\n```"
)
return response
# noinspection PyBroadException
try:
real_config_obj = literal_eval(" ".join(args[1:]))
except Exception:
self.log.exception("Invalid expression for the configuration of the plugin")
return "Syntax error in the given configuration"
if type(real_config_obj) is not type(template_obj):
return "It looks fishy, your config type is not the same as the template!"
self._bot.plugin_manager.set_plugin_configuration(plugin_name, real_config_obj)
try:
self._bot.plugin_manager.deactivate_plugin(plugin_name)
except PluginActivationException as pae:
return f"Error deactivating {plugin_name}: {pae}."
try:
self._bot.plugin_manager.activate_plugin(plugin_name)
except PluginConfigurationException as ce:
self.log.debug(
"Invalid configuration for the plugin, reverting the plugin to unconfigured."
)
self._bot.plugin_manager.set_plugin_configuration(plugin_name, None)
return f"Incorrect plugin configuration: {ce}."
except PluginActivationException as pae:
return f"Error activating plugin: {pae}."
return "Plugin configuration done."
def formatted_plugin_list(self, active_only=True):
"""
Return a formatted, plain-text list of loaded plugins.
When active_only=True, this will only return plugins which
are actually active. Otherwise, it will also include inactive
(blacklisted) plugins.
"""
if active_only:
all_plugins = self._bot.plugin_manager.get_all_active_plugin_names()
else:
all_plugins = self._bot.plugin_manager.get_all_plugin_names()
return "\n".join(("- " + plugin for plugin in all_plugins))
@botcmd(admin_only=True)
def plugin_reload(self, _, args):
"""reload a plugin: reload the code of the plugin leaving the activation status intact."""
name = args.strip()
if not name:
yield (
f"Please tell me which of the following plugins to reload:\n"
f"{self.formatted_plugin_list(active_only=False)}"
)
return
if name not in self._bot.plugin_manager.get_all_plugin_names():
yield (
f"{name} isn't a valid plugin name. "
f"The current plugins are:\n{self.formatted_plugin_list(active_only=False)}"
)
return
if name not in self._bot.plugin_manager.get_all_active_plugin_names():
answer = f"Warning: plugin {name} is currently not activated. "
answer += f"Use `{self._bot.prefix}plugin activate {name}` to activate it."
yield answer
try:
self._bot.plugin_manager.reload_plugin_by_name(name)
yield f"Plugin {name} reloaded."
except PluginActivationException as pae:
yield f"Error activating plugin {name}: {pae}."
@botcmd(admin_only=True)
def plugin_activate(self, _, args):
"""activate a plugin. [calls .activate() on the plugin]"""
args = args.strip()
if not args:
return (
f"Please tell me which of the following plugins to activate:\n"
f"{self.formatted_plugin_list(active_only=False)}"
)
if args not in self._bot.plugin_manager.get_all_plugin_names():
return (
f"{args} isn't a valid plugin name. The current plugins are:\n"
f"{self.formatted_plugin_list(active_only=False)}"
)
if args in self._bot.plugin_manager.get_all_active_plugin_names():
return f"{args} is already activated."
try:
self._bot.plugin_manager.activate_plugin(args)
except PluginActivationException as pae:
return f"Error activating plugin: {pae}"
return f"Plugin {args} activated."
@botcmd(admin_only=True)
def plugin_deactivate(self, _, args):
"""deactivate a plugin. [calls .deactivate on the plugin]"""
args = args.strip()
if not args:
return (
f"Please tell me which of the following plugins to deactivate:\n"
f"{self.formatted_plugin_list(active_only=False)}"
)
if args not in self._bot.plugin_manager.get_all_plugin_names():
return (
f"{args} isn't a valid plugin name. The current plugins are:\n"
f"{self.formatted_plugin_list(active_only=False)}"
)
if args not in self._bot.plugin_manager.get_all_active_plugin_names():
return f"{args} is already deactivated."
try:
self._bot.plugin_manager.deactivate_plugin(args)
except PluginActivationException as pae:
return f"Error deactivating {args}: {pae}"
return f"Plugin {args} deactivated."
@botcmd(admin_only=True)
def plugin_blacklist(self, _, args):
"""Blacklist a plugin so that it will not be loaded automatically during bot startup.
If the plugin is currently activated, it will deactiveate it first."""
if args not in self._bot.plugin_manager.get_all_plugin_names():
return (
f"{args} isn't a valid plugin name. The current plugins are:\n"
f"{self.formatted_plugin_list(active_only=False)}"
)
if args in self._bot.plugin_manager.get_all_active_plugin_names():
try:
self._bot.plugin_manager.deactivate_plugin(args)
except PluginActivationException as pae:
return f"Error deactivating {args}: {pae}."
return self._bot.plugin_manager.blacklist_plugin(args)
@botcmd(admin_only=True)
def plugin_unblacklist(self, _, args):
"""Remove a plugin from the blacklist"""
if args not in self._bot.plugin_manager.get_all_plugin_names():
return (
f"{args} isn't a valid plugin name. The current plugins are:\n"
f"{self.formatted_plugin_list(active_only=False)}"
)
if args not in self._bot.plugin_manager.get_all_active_plugin_names():
try:
self._bot.plugin_manager.activate_plugin(args)
except PluginActivationException as pae:
return f"Error activating plugin: {pae}"
return self._bot.plugin_manager.unblacklist_plugin(args)
@botcmd(admin_only=True, template="plugin_info")
def plugin_info(self, _, args):
"""Gives you a more technical information about a specific plugin."""
pm = self._bot.plugin_manager
if args not in pm.get_all_plugin_names():
return (
f"{args} isn't a valid plugin name. The current plugins are:\n"
f"{self.formatted_plugin_list(active_only=False)}"
)
return {
"plugin_info": pm.plugin_infos[args],
"plugin": pm.plugins[args],
"logging": logging,
}
| 14,566
|
Python
|
.py
| 302
| 36.629139
| 136
| 0.601069
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,168
|
backup.py
|
errbotio_errbot/errbot/core_plugins/backup.py
|
import os
from errbot import BotPlugin, botcmd
class Backup(BotPlugin):
"""Backup related commands."""
@botcmd(admin_only=True)
def backup(self, msg, args):
"""Backup everything.
Makes a backup script called backup.py in the data bot directory.
You can restore the backup from the command line with errbot --restore
"""
filename = os.path.join(self.bot_config.BOT_DATA_DIR, "backup.py")
with open(filename, "w") as f:
f.write(
"## This file is not executable on its own. use errbot -r FILE to restore your bot.\n\n"
)
f.write('log.info("Restoring repo_manager.")\n')
for key, value in self._bot.repo_manager.items():
f.write('bot.repo_manager["' + key + '"] = ' + repr(value) + "\n")
f.write('log.info("Restoring plugin_manager.")\n')
for (
key,
value,
) in (
self._bot.plugin_manager.items()
): # don't mimic that in real plugins, this is core only.
f.write('bot.plugin_manager["' + key + '"] = ' + repr(value) + "\n")
f.write('log.info("Installing plugins.")\n')
f.write('if "installed_repos" in bot.repo_manager:\n')
f.write(' for repo in bot.repo_manager["installed_repos"]:\n')
f.write(" log.error(bot.repo_manager.install_repo(repo))\n")
f.write('log.info("Restoring plugins data.")\n')
f.write(
"bot.plugin_manager.update_plugin_places(bot.repo_manager.get_all_repos_paths())\n"
)
for plugin in self._bot.plugin_manager.plugins.values():
if plugin._store:
f.write(
'pobj = bot.plugin_manager.plugins["' + plugin.name + '"]\n'
)
f.write("pobj.init_storage()\n")
for key, value in plugin.items():
f.write('pobj["' + key + '"] = ' + repr(value) + "\n")
f.write("pobj.close_storage()\n")
return f'The backup file has been written in "{filename}".'
| 2,200
|
Python
|
.py
| 44
| 36.636364
| 104
| 0.528399
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,169
|
acls.py
|
errbotio_errbot/errbot/core_plugins/acls.py
|
import fnmatch
from errbot import BotPlugin, cmdfilter
from errbot.backends.base import RoomOccupant
BLOCK_COMMAND = (None, None, None)
def get_acl_usr(msg):
"""Return the ACL attribute of the sender of the given message"""
if hasattr(
msg.frm, "aclattr"
): # if the identity requires a special field to be used for acl
return msg.frm.aclattr
return msg.frm.person # default
def get_acl_room(room):
"""Return the ACL attribute of the room used for a given message"""
if hasattr(room, "aclattr"):
return room.aclattr
return str(room) # old behaviour
def glob(text, patterns):
"""
Match text against the list of patterns according to unix glob rules.
Return True if a match is found, False otherwise.
"""
if isinstance(patterns, str):
patterns = (patterns,)
if not isinstance(text, str):
text = str(text)
return any(fnmatch.fnmatchcase(text, str(pattern)) for pattern in patterns)
def ciglob(text, patterns):
"""
Case-insensitive version of glob.
Match text against the list of patterns according to unix glob rules.
Return True if a match is found, False otherwise.
"""
if isinstance(patterns, str):
patterns = (patterns,)
return glob(text.lower(), [p.lower() for p in patterns])
class ACLS(BotPlugin):
"""
This plugin implements access controls for commands, allowing them to be
restricted via various rules.
"""
def access_denied(self, msg, reason, dry_run):
if not dry_run and not self.bot_config.HIDE_RESTRICTED_ACCESS:
self._bot.send_simple_reply(msg, reason)
return BLOCK_COMMAND
@cmdfilter
def acls(self, msg, cmd, args, dry_run):
"""
Check command against ACL rules as defined in the bot configuration.
:param msg: The original chat message.
:param cmd: The command name itself.
:param args: Arguments passed to the command.
:param dry_run: True when this is a dry-run.
"""
self.log.debug("Check %s for ACLs.", cmd)
f = self._bot.all_commands[cmd]
cmd_str = f"{f.__self__.name}:{cmd}"
usr = get_acl_usr(msg)
acl = self.bot_config.ACCESS_CONTROLS_DEFAULT.copy()
for pattern, acls in self.bot_config.ACCESS_CONTROLS.items():
if ":" not in pattern:
pattern = f"*:{pattern}"
if ciglob(cmd_str, (pattern,)):
acl.update(acls)
break
self.log.info(
f"Matching ACL {acl} against username {usr} for command {cmd_str}."
)
if "allowargs" in acl and not glob(args, acl["allowargs"]):
return self.access_denied(
msg,
"You're not allowed to access this command using the provided arguments",
dry_run,
)
if "denyargs" in acl and glob(args, acl["denyargs"]):
return self.access_denied(
msg,
"You're not allowed to access this command using the provided arguments",
dry_run,
)
if "allowusers" in acl and not glob(usr, acl["allowusers"]):
return self.access_denied(
msg, "You're not allowed to access this command from this user", dry_run
)
if "denyusers" in acl and glob(usr, acl["denyusers"]):
return self.access_denied(
msg, "You're not allowed to access this command from this user", dry_run
)
if msg.is_group:
if not isinstance(msg.frm, RoomOccupant):
raise Exception(
f"msg.frm is not a RoomOccupant. Class of frm: {msg.frm.__class__}"
)
room = get_acl_room(msg.frm.room)
if "allowmuc" in acl and acl["allowmuc"] is False:
return self.access_denied(
msg,
"You're not allowed to access this command from a chatroom",
dry_run,
)
if "allowrooms" in acl and not glob(room, acl["allowrooms"]):
return self.access_denied(
msg,
"You're not allowed to access this command from this room",
dry_run,
)
if "denyrooms" in acl and glob(room, acl["denyrooms"]):
return self.access_denied(
msg,
"You're not allowed to access this command from this room",
dry_run,
)
elif "allowprivate" in acl and acl["allowprivate"] is False:
return self.access_denied(
msg,
"You're not allowed to access this command via private message to me",
dry_run,
)
self.log.debug(f"Check if {cmd} is admin only command.")
if f._err_command_admin_only:
if not glob(get_acl_usr(msg), self.bot_config.BOT_ADMINS):
return self.access_denied(
msg, "This command requires bot-admin privileges", dry_run
)
# For security reasons, admin-only commands are direct-message only UNLESS
# specifically overridden by setting allowmuc to True for such commands.
if msg.is_group and not acl.get("allowmuc", False):
return self.access_denied(
msg,
"This command may only be issued through a direct message",
dry_run,
)
return msg, cmd, args
| 5,645
|
Python
|
.py
| 132
| 31.439394
| 89
| 0.578871
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,170
|
wsview.py
|
errbotio_errbot/errbot/core_plugins/wsview.py
|
import logging
from inspect import getmembers, ismethod
from json import loads
from flask import request
from flask.app import Flask
from flask.views import View
import errbot.core_plugins
log = logging.getLogger(__name__)
def strip_path():
# strip the trailing slashes on incoming requests
request.environ["PATH_INFO"] = request.environ["PATH_INFO"].rstrip("/")
def try_decode_json(req):
data = req.data.decode()
try:
return loads(data)
except Exception:
return None
def reset_app():
"""Zap everything here, useful for unit tests"""
errbot.core_plugins.flask_app = Flask(__name__)
def route(obj):
"""Check for functions to route in obj and route them."""
flask_app = errbot.core_plugins.flask_app
classname = obj.__class__.__name__
log.info("Checking %s for webhooks", classname)
for name, func in getmembers(obj, ismethod):
if getattr(func, "_err_webhook_uri_rule", False):
log.info("Webhook routing %s", func.__name__)
form_param = func._err_webhook_form_param
uri_rule = func._err_webhook_uri_rule
verbs = func._err_webhook_methods
raw = func._err_webhook_raw
callable_view = WebView.as_view(
func.__name__ + "_" + "_".join(verbs), func, form_param, raw
)
# Change existing rule.
for rule in flask_app.url_map._rules:
if rule.rule == uri_rule:
flask_app.view_functions[rule.endpoint] = callable_view
return
# Add a new rule
flask_app.add_url_rule(
uri_rule, view_func=callable_view, methods=verbs, strict_slashes=False
)
class WebView(View):
def __init__(self, func, form_param, raw):
if form_param is not None and raw:
raise Exception(
"Incompatible parameters: form_param cannot be set if raw is True"
)
self.func = func
self.raw = raw
self.form_param = form_param
self.method_filter = (
lambda obj: ismethod(obj) and self.func.__name__ == obj.__name__
)
def dispatch_request(self, *args, **kwargs):
if self.raw: # override and gives the request directly
response = self.func(request, **kwargs)
elif self.form_param:
content = request.form.get(self.form_param)
if content is None:
raise Exception(
"Received a request on a webhook with a form_param defined, "
"but that key (%s) is missing from the request.",
self.form_param,
)
try:
content = loads(content)
except ValueError:
log.debug("The form parameter is not JSON, return it as a string.")
response = self.func(content, **kwargs)
else:
data = try_decode_json(request)
if not data:
if hasattr(request, "forms"):
data = dict(request.forms) # form encoded
else:
data = request.data.decode()
response = self.func(data, **kwargs)
return (
response if response else ""
) # assume None as an OK response (simplifies the client side)
| 3,376
|
Python
|
.py
| 83
| 30.216867
| 86
| 0.57906
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,171
|
utils.py
|
errbotio_errbot/errbot/core_plugins/utils.py
|
from os import path
from errbot import BotPlugin, botcmd
def tail(f, window=20):
return "".join(f.readlines()[-window:])
class Utils(BotPlugin):
# noinspection PyUnusedLocal
@botcmd
def echo(self, _, args):
"""A simple echo command. Useful for encoding tests etc ..."""
return args
@botcmd
def whoami(self, msg, args):
"""A simple command echoing the details of your identifier. Useful to debug identity problems."""
if args:
frm = self.build_identifier(str(args).strip('"'))
else:
frm = msg.frm
resp = ""
if self.bot_config.GROUPCHAT_NICK_PREFIXED:
resp += "\n\n"
resp += "| key | value\n"
resp += "| -------- | --------\n"
resp += f"| person | `{frm.person}`\n"
resp += f"| nick | `{frm.nick}`\n"
resp += f"| fullname | `{frm.fullname}`\n"
resp += f"| client | `{frm.client}`\n"
resp += f"| email | `{frm.email}`\n"
# extra info if it is a MUC
if hasattr(frm, "room"):
resp += f"\n`room` is {frm.room}\n"
resp += f"\n\n- string representation is '{frm}'\n"
resp += f"- class is '{frm.__class__.__name__}'\n"
return resp
# noinspection PyUnusedLocal
@botcmd(historize=False)
def history(self, msg, args):
"""display the command history"""
answer = []
user_cmd_history = self._bot.cmd_history[msg.frm.person]
length = len(user_cmd_history)
for i in range(0, length):
c = user_cmd_history[i]
answer.append(f"{length - i:2d}:{self._bot.prefix}{c[0]} {c[1]}")
return "\n".join(answer)
# noinspection PyUnusedLocal
@botcmd(admin_only=True)
def log_tail(self, msg, args):
"""Display a tail of the log of n lines or 40 by default
use : !log tail 10
"""
n = 40
if args.isdigit():
n = int(args)
if self.bot_config.BOT_LOG_FILE:
with open(self.bot_config.BOT_LOG_FILE) as f:
return "```\n" + tail(f, n) + "\n```"
return "No log is configured, please define BOT_LOG_FILE in config.py"
@botcmd
def render_test(self, _, args):
"""Tests / showcases the markdown rendering on your current backend"""
with open(path.join(path.dirname(path.realpath(__file__)), "test.md")) as f:
return f.read()
| 2,462
|
Python
|
.py
| 62
| 31.193548
| 105
| 0.552389
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,172
|
cnf_filter.py
|
errbotio_errbot/errbot/core_plugins/cnf_filter.py
|
from errbot import BotPlugin, cmdfilter
class CommandNotFoundFilter(BotPlugin):
@cmdfilter(catch_unprocessed=True)
def cnf_filter(self, msg, cmd, args, dry_run, emptycmd=False):
"""
Check if command exists. If not, signal plugins. This plugin
will be called twice: once as a command filter and then again
as a "command not found" filter. See the emptycmd parameter.
:param msg: Original chat message.
:param cmd: Parsed command.
:param args: Command arguments.
:param dry_run: True when this is a dry-run.
:param emptycmd: False when this command has been parsed and is valid.
True if the command was not found.
"""
if not emptycmd:
return msg, cmd, args
if self.bot_config.SUPPRESS_CMD_NOT_FOUND:
self.log.debug("Suppressing command not found feedback.")
return
command = msg.body.strip()
for prefix in self.bot_config.BOT_ALT_PREFIXES + (self.bot_config.BOT_PREFIX,):
if command.startswith(prefix):
command = command.replace(prefix, "", 1)
break
command_args = command.split(" ", 1)
command = command_args[0]
if len(command_args) > 1:
args = " ".join(command_args[1:])
return self._bot.unknown_command(msg, command, args)
| 1,404
|
Python
|
.py
| 30
| 36.533333
| 87
| 0.621245
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,173
|
textcmds.py
|
errbotio_errbot/errbot/core_plugins/textcmds.py
|
from errbot import BotPlugin, botcmd
INROOM, USER, MULTILINE = "inroom", "user", "multiline"
class TextModeCmds(BotPlugin):
"""
Internal to TextBackend.
"""
__errdoc__ = "Added commands for testing purposes"
def activate(self):
# This won't activate the plugin in anything else than text mode.
if self.mode != "text":
return
super().activate()
# Some defaults if it was never used before'.
if INROOM not in self:
self[INROOM] = False
if USER not in self:
self[USER] = self.build_identifier(self.bot_config.BOT_ADMINS[0])
if MULTILINE not in self:
self[MULTILINE] = False
# Restore the values to their live state.
self._bot._inroom = self[INROOM]
self._bot.user = self[USER]
self._bot._multiline = self[MULTILINE]
def deactivate(self):
# Save the live state.
self[INROOM] = self._bot._inroom
self[USER] = self._bot.user
self[MULTILINE] = self._bot._multiline
super().deactivate()
@botcmd
def inroom(self, msg, args):
"""
This puts you in a room with the bot.
"""
self._bot._inroom = True
if args:
room = args
else:
room = "#testroom"
self._bot.query_room(room).join()
return f"Joined Room {room}."
@botcmd
def inperson(self, msg, _):
"""
This puts you in a 1-1 chat with the bot.
"""
self._bot._inroom = False
return "Now in one-on-one with the bot."
@botcmd
def asuser(self, msg, args):
"""
This puts you in a room with the bot. You can specify a name otherwise it will default to 'luser'.
"""
if args:
usr = args
if usr[0] != "@":
usr = "@" + usr
self._bot.user = self.build_identifier(usr)
else:
self._bot.user = self.build_identifier("@luser")
return f"You are now: {self._bot.user}."
@botcmd
def asadmin(self, msg, _):
"""
This puts you in a 1-1 chat with the bot.
"""
self._bot.user = self.build_identifier(self.bot_config.BOT_ADMINS[0])
return f"You are now an admin: {self._bot.user}."
@botcmd
def ml(self, msg, _):
"""
Switch back and forth between normal mode and multiline mode. Use this if you want to test
commands spanning multiple lines. Note: in multiline, press enter twice to end and send the message.
"""
self._bot._multiline = not self._bot._multiline
return (
"Multiline mode, press enter twice to end messages"
if self._bot._multiline
else "Normal one line mode."
)
| 2,816
|
Python
|
.py
| 80
| 26.3375
| 108
| 0.569327
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,174
|
chatRoom.py
|
errbotio_errbot/errbot/core_plugins/chatRoom.py
|
import logging
from errbot import BotPlugin, ShlexArgParser, botcmd
from errbot.backends.base import RoomNotJoinedError
log = logging.getLogger(__name__)
class ChatRoom(BotPlugin):
connected = False
def callback_connect(self):
self.log.info("Connecting bot chatrooms")
if not self.connected:
self.connected = True
for room in self.bot_config.CHATROOM_PRESENCE:
self.log.debug("Try to join room %s", repr(room))
try:
self._join_room(room)
except Exception:
# Ensure failure to join a room doesn't crash the plugin
# as a whole.
self.log.exception(f"Joining room {repr(room)} failed")
def _join_room(self, room):
username = self.bot_config.CHATROOM_FN
password = None
if isinstance(room, (tuple, list)):
room, password = room # unpack
self.log.info(
"Joining room %s with username %s and pass ***.", room, username
)
else:
self.log.info("Joining room %s with username %s.", room, username)
self.query_room(room).join(
username=self.bot_config.CHATROOM_FN, password=password
)
def deactivate(self):
self.connected = False
super().deactivate()
@botcmd(split_args_with=ShlexArgParser())
def room_create(self, message, args):
"""
Create a chatroom.
Usage:
!room create <room>
Examples (XMPP):
!room create example-room@chat.server.tld
Examples (IRC):
!room create #example-room
"""
if len(args) < 1:
return "Please tell me which chatroom to create."
room = self.query_room(args[0])
room.create()
return f"Created the room {room}."
@botcmd(split_args_with=ShlexArgParser())
def room_join(self, message, args):
"""
Join (creating it first if needed) a chatroom.
Usage:
!room join <room> [<password>]
Examples (XMPP):
!room join example-room@chat.server.tld
!room join example-room@chat.server.tld super-secret-password
Examples (IRC):
!room join #example-room
!room join #example-room super-secret-password
!room join #example-room "password with spaces"
"""
arglen = len(args)
if arglen < 1:
return "Please tell me which chatroom to join."
args[0].strip()
room_name, password = (args[0], None) if arglen == 1 else (args[0], args[1])
room = self.query_room(room_name)
if room is None:
return f"Cannot find room {room_name}."
room.join(username=self.bot_config.CHATROOM_FN, password=password)
return f"Joined the room {room_name}."
@botcmd(split_args_with=ShlexArgParser())
def room_leave(self, message, args):
"""
Leave a chatroom.
Usage:
!room leave <room>
Examples (XMPP):
!room leave example-room@chat.server.tld
Examples (IRC):
!room leave #example-room
"""
if len(args) < 1:
return "Please tell me which chatroom to leave."
self.query_room(args[0]).leave()
return f"Left the room {args[0]}."
@botcmd(split_args_with=ShlexArgParser())
def room_destroy(self, message, args):
"""
Destroy a chatroom.
Usage:
!room destroy <room>
Examples (XMPP):
!room destroy example-room@chat.server.tld
Examples (IRC):
!room destroy #example-room
"""
if len(args) < 1:
return "Please tell me which chatroom to destroy."
self.query_room(args[0]).destroy()
return f"Destroyed the room {args[0]}."
@botcmd(split_args_with=ShlexArgParser())
def room_invite(self, message, args):
"""
Invite one or more people into a chatroom.
Usage:
!room invite <room> <identifier1> [<identifier2>, ..]
Examples (XMPP):
!room invite room@conference.server.tld bob@server.tld
Examples (IRC):
!room invite #example-room bob
"""
if len(args) < 2:
return "Please tell me which person(s) to invite into which room."
self.query_room(args[0]).invite(*args[1:])
return f'Invited {", ".join(args[1:])} into the room {args[0]}.'
@botcmd
def room_list(self, message, args):
"""
List chatrooms the bot has joined.
Usage:
!room list
Examples:
!room list
"""
rooms = [str(room) for room in self.rooms()]
if len(rooms):
rooms_str = "\n\t".join(rooms)
return f"I'm currently in these rooms:\n\t{rooms_str}"
else:
return "I'm not currently in any rooms."
@botcmd(split_args_with=ShlexArgParser())
def room_occupants(self, message, args):
"""
List the occupants in a given chatroom.
Usage:
!room occupants <room 1> [<room 2> ..]
Examples (XMPP):
!room occupants room@conference.server.tld
Examples (IRC):
!room occupants #example-room #another-example-room
"""
if len(args) < 1:
yield "Please supply a room to list the occupants of."
return
for room in args:
try:
occupants = [o.person for o in self.query_room(room).occupants]
occupants_str = "\n\t".join(map(str, occupants))
yield f"Occupants in {room}:\n\t{occupants_str}."
except RoomNotJoinedError as e:
yield f"Cannot list occupants in {room}: {e}."
@botcmd(split_args_with=ShlexArgParser())
def room_topic(self, message, args):
"""
Get or set the topic for a room.
Usage:
!room topic <room> [<new topic>]
Examples (XMPP):
!room topic example-room@chat.server.tld
!room topic example-room@chat.server.tld "Err rocks!"
Examples (IRC):
!room topic #example-room
!room topic #example-room "Err rocks!"
"""
arglen = len(args)
if arglen < 1:
return "Please tell me which chatroom you want to know the topic of."
if arglen == 1:
try:
topic = self.query_room(args[0]).topic
except RoomNotJoinedError as e:
return f"Cannot get the topic for {args[0]}: {e}."
if topic is None:
return f"No topic is set for {args[0]}."
else:
return f"Topic for {args[0]}: {topic}."
else:
try:
self.query_room(args[0]).topic = args[1]
except RoomNotJoinedError as e:
return f"Cannot set the topic for {args[0]}: {e}."
return f"Topic for {args[0]} set."
def callback_message(self, msg):
try:
if msg.is_direct:
username = msg.frm.person
if username in self.bot_config.CHATROOM_RELAY:
self.log.debug("Message to relay from %s.", username)
body = msg.body
rooms = self.bot_config.CHATROOM_RELAY[username]
for roomstr in rooms:
self.send(self.query_room(roomstr), body)
elif msg.is_group:
fr = msg.frm
chat_room = str(fr.room)
if chat_room in self.bot_config.REVERSE_CHATROOM_RELAY:
users_to_relay_to = self.bot_config.REVERSE_CHATROOM_RELAY[
chat_room
]
self.log.debug("Message to relay to %s.", users_to_relay_to)
body = f"[{fr.person}] {msg.body}"
for user in users_to_relay_to:
self.send(user, body)
except Exception as e:
self.log.exception(f"crashed in callback_message {e}")
| 8,117
|
Python
|
.py
| 209
| 27.933014
| 84
| 0.559878
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,175
|
health.py
|
errbotio_errbot/errbot/core_plugins/health.py
|
import gc
import os
import signal
from datetime import datetime
from errbot import BotPlugin, arg_botcmd, botcmd
from errbot.utils import format_timedelta, global_restart
class Health(BotPlugin):
@botcmd(template="status")
def status(self, msg, args):
"""If I am alive I should be able to respond to this one"""
plugins_statuses = self.status_plugins(msg, args)
loads = self.status_load(msg, args)
gc = self.status_gc(msg, args)
return {
"plugins_statuses": plugins_statuses["plugins_statuses"],
"loads": loads["loads"],
"gc": gc["gc"],
}
@botcmd(template="status_load")
def status_load(self, _, args):
"""shows the load status"""
try:
from posix import getloadavg
loads = getloadavg()
except Exception:
loads = None
return {"loads": loads}
@botcmd(template="status_gc")
def status_gc(self, _, args):
"""shows the garbage collection details"""
return {"gc": gc.get_count()}
@botcmd(template="status_plugins")
def status_plugins(self, _, args):
"""shows the plugin status"""
pm = self._bot.plugin_manager
all_blacklisted = pm.get_blacklisted_plugin()
all_loaded = pm.get_all_active_plugin_names()
all_attempted = sorted(pm.plugin_infos.keys())
plugins_statuses = []
for name in all_attempted:
if name in all_blacklisted:
if name in all_loaded:
plugins_statuses.append(("BA", name))
else:
plugins_statuses.append(("BD", name))
elif name in all_loaded:
plugins_statuses.append(("A", name))
elif (
pm.get_plugin_obj_by_name(name) is not None
and pm.get_plugin_obj_by_name(name).get_configuration_template()
is not None
and pm.get_plugin_configuration(name) is None
):
plugins_statuses.append(("C", name))
else:
plugins_statuses.append(("D", name))
return {"plugins_statuses": plugins_statuses}
@botcmd
def uptime(self, _, args):
"""Return the uptime of the bot"""
u = format_timedelta(datetime.now() - self._bot.startup_time)
since = self._bot.startup_time.strftime("%A, %b %d at %H:%M")
return f"I've been up for {u} (since {since})."
# noinspection PyUnusedLocal
@botcmd(admin_only=True)
def restart(self, msg, args):
"""Restart the bot."""
self.send(msg.frm, "Deactivating all the plugins...")
self._bot.plugin_manager.deactivate_all_plugins()
self.send(msg.frm, "Restarting")
self._bot.shutdown()
global_restart()
return "I'm restarting..."
# noinspection PyUnusedLocal
@arg_botcmd(
"--confirm",
dest="confirmed",
action="store_true",
help="confirm you want to shut down",
admin_only=True,
)
@arg_botcmd(
"--kill",
dest="kill",
action="store_true",
help="kill the bot instantly, don't shut down gracefully",
admin_only=True,
)
def shutdown(self, msg, confirmed, kill):
"""
Shutdown the bot.
Useful when the things are going crazy and you don't have access to the machine.
"""
if not confirmed:
yield "Please provide `--confirm` to confirm you really want me to shut down."
return
if kill:
yield "Killing myself right now!"
os.kill(os.getpid(), signal.SIGKILL)
else:
yield "Roger that. I am shutting down."
os.kill(os.getpid(), signal.SIGINT)
| 3,805
|
Python
|
.py
| 102
| 27.843137
| 90
| 0.579447
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,176
|
vcheck.py
|
errbotio_errbot/errbot/core_plugins/vcheck.py
|
import sys
import threading
from json import JSONDecodeError
from urllib.error import HTTPError, URLError
import requests
from requests.exceptions import ConnectionError
from errbot import BotPlugin
from errbot.utils import version2tuple
from errbot.version import VERSION
HOME = "https://errbot.io/versions.json"
installed_version = version2tuple(VERSION)
PY_VERSION = ".".join(str(e) for e in sys.version_info[:3])
class VersionChecker(BotPlugin):
connected = False
activated = False
def activate(self):
if self.mode not in (
"null",
"test",
"Dummy",
"text",
): # skip in all test confs.
self.activated = True
self.version_check() # once at startup anyway
self.start_poller(3600 * 24, self.version_check) # once every 24H
super().activate()
else:
self.log.info("Skip version checking under %s mode.", self.mode)
def deactivate(self):
self.activated = False
super().deactivate()
def _get_version(self):
"""Get errbot version based on python version."""
version = VERSION
major_py_version = PY_VERSION.partition(".")[0]
# noinspection PyBroadException
try:
possible_versions = requests.get(HOME).json()
version = possible_versions.get(f"python{major_py_version}", VERSION)
self.log.debug("Latest Errbot version is: %s", version)
except (HTTPError, URLError, ConnectionError, JSONDecodeError):
self.log.info("Could not establish connection to retrieve latest version.")
return version
def _async_vcheck(self):
current_version_txt = self._get_version()
self.log.debug("Installed Errbot version is: %s", current_version_txt)
current_version = version2tuple(current_version_txt)
if installed_version < current_version:
self.log.debug(
"A new version %s has been found, notify the admins!",
current_version_txt,
)
self.warn_admins(
f"Version {current_version_txt} of Errbot is available. "
f"http://pypi.python.org/pypi/errbot/{current_version_txt}. "
f"To disable this check do: {self._bot.prefix}plugin blacklist VersionChecker"
)
def version_check(self):
if not self.activated:
self.log.debug("Version check disabled")
return
self.log.debug("Checking version in background.")
threading.Thread(target=self._async_vcheck).start()
def callback_connect(self):
if not self.connected:
self.connected = True
| 2,728
|
Python
|
.py
| 66
| 32.363636
| 94
| 0.638218
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,177
|
flows.py
|
errbotio_errbot/errbot/core_plugins/flows.py
|
import io
import json
from errbot import BotPlugin, arg_botcmd, botcmd
from errbot.core_plugins.acls import get_acl_usr, glob
from errbot.flow import FLOW_END, Flow, FlowNode, FlowRoot
class Flows(BotPlugin):
"""Management commands related to flows / conversations."""
def recurse_node(
self, response: io.StringIO, stack, f: FlowNode, flow: Flow = None
):
if f in stack:
response.write(f'{"  " * (len(stack))}↺<br>')
return
if isinstance(f, FlowRoot):
doc = f.description if flow else ""
response.write("Flow [" + f.name + "] " + doc + " <br>")
if flow and flow.current_step == f:
response.write(f"↪ Start (_{flow.requestor}_)<br>")
else:
cmd = "END" if f is FLOW_END else self._bot.all_commands[f.command]
requestor = (
f"(_{str(flow.requestor)}_)" if flow and flow.current_step == f else ""
)
doc = cmd.__doc__ if flow and f is not FLOW_END else ""
response.write(
f'{"  " * len(stack)}'
f'↪ **{f if f is not FLOW_END else "END"}** {doc if doc else ""} {requestor}<br>'
)
for _, sf in f.children:
self.recurse_node(response, stack + [f], sf, flow)
@botcmd(syntax="<name>")
def flows_show(self, _, args):
"""Shows the structure of a flow."""
if not args:
return "You need to specify a flow name."
with io.StringIO() as response:
flow_node = self._bot.flow_executor.flow_roots.get(args, None)
if flow_node is None:
return f"Flow {args} doesn't exist."
self.recurse_node(response, [], flow_node)
return response.getvalue()
# noinspection PyUnusedLocal
@botcmd
def flows_list(self, msg, args):
"""Displays the list of setup flows."""
with io.StringIO() as response:
for name, flow_node in self._bot.flow_executor.flow_roots.items():
if flow_node.description:
response.write("- **" + name + "** " + flow_node.description + "\n")
else:
response.write("- **" + name + "** " + "No description" + "\n")
return response.getvalue()
@botcmd(split_args_with=" ", syntax="<name> [initial_payload]")
def flows_start(self, msg, args):
"""Manually start a flow within the context of the calling user.
You can prefeed the flow data with a json payload.
Example:
!flows start poll_setup {"title":"yeah!","options":["foo","bar","baz"]}
"""
if not args:
return "You need to specify a flow to manually start"
context = {}
flow_name = args[0]
if len(args) > 1:
json_payload = " ".join(args[1:])
try:
context = json.loads(json_payload)
except Exception as e:
return f"Cannot parse json {json_payload}: {e}."
self._bot.flow_executor.start_flow(flow_name, msg.frm, context)
return f"Flow **{flow_name}** started ..."
@botcmd()
def flows_status(self, msg, args):
"""Displays the list of started flows."""
with io.StringIO() as response:
if not self._bot.flow_executor.in_flight:
response.write("No Flow started.\n")
else:
if not [
flow
for flow in self._bot.flow_executor.in_flight
if self.check_user(msg, flow)
]:
response.write(
f"No Flow started for current user: {get_acl_usr(msg)}.\n"
)
else:
if args:
for flow in self._bot.flow_executor.in_flight:
if self.check_user(msg, flow):
if flow.name == args:
self.recurse_node(response, [], flow.root, flow)
else:
for flow in self._bot.flow_executor.in_flight:
if self.check_user(msg, flow):
next_steps = [
f"\\*{str(step[1].command)}\\*"
for step in flow._current_step.children
if step[1].command
]
next_steps_str = "\n".join(next_steps)
text = (
f"\\>>> {str(flow.requestor)} is using flow \\*{flow.name}\\* on step "
f"\\*{flow.current_step}\\*\nNext Step(s): \n{next_steps_str}"
)
response.write(text)
return response.getvalue()
@botcmd(syntax="[flow_name]")
def flows_stop(self, msg, args):
"""Stop flows you are in.
optionally, stop a specific flow you are in.
"""
if args:
flow = self._bot.flow_executor.stop_flow(args, msg.frm)
if flow:
yield flow.name + " stopped."
return
yield "Flow not found."
return
one_stopped = False
for flow in self._bot.flow_executor.in_flight:
if flow.requestor == msg.frm:
flow = self._bot.flow_executor.stop_flow(flow.name, msg.frm)
if flow:
one_stopped = True
yield flow.name + " stopped."
if not one_stopped:
yield "No Flow found."
@arg_botcmd("flow_name", type=str)
@arg_botcmd("user", type=str)
def flows_kill(self, _, user, flow_name):
"""Admin command to kill a specific flow."""
flow = self._bot.flow_executor.stop_flow(flow_name, self.build_identifier(user))
if flow:
return flow.name + " killed."
return "Flow not found."
def check_user(self, msg, flow):
"""Checks to make sure that either the user started the flow, or is a bot admin"""
if glob(get_acl_usr(msg), self.bot_config.BOT_ADMINS):
return True
elif glob(get_acl_usr(msg), flow.requestor.person):
return True
return False
| 6,478
|
Python
|
.py
| 143
| 31.132867
| 108
| 0.506654
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,178
|
test.py
|
errbotio_errbot/errbot/backends/test.py
|
import importlib
import logging
import sys
import textwrap
import unittest
from os.path import abspath, sep
from queue import Empty, Queue
from tempfile import mkdtemp
from threading import Thread
from typing import BinaryIO, List, Optional
import pytest
from errbot.backends.base import (
ONLINE,
Identifier,
Message,
Person,
Presence,
Room,
RoomOccupant,
)
from errbot.bootstrap import setup_bot
from errbot.core import ErrBot
from errbot.core_plugins.wsview import reset_app
from errbot.rendering import text
from errbot.utils import deprecated
log = logging.getLogger(__name__)
QUIT_MESSAGE = "$STOP$"
STZ_MSG = 1
STZ_PRE = 2
STZ_IQ = 3
class TestPerson(Person):
"""
This is an identifier just represented as a string.
DO NOT USE THIS DIRECTLY AS IT IS NOT COMPATIBLE WITH MOST BACKENDS,
use self.build_identifier(identifier_as_string) instead.
Note to back-end implementors: You should provide a custom
<yourbackend>Identifier object that adheres to this interface.
You should not directly inherit from SimpleIdentifier, inherit
from object instead and make sure it includes all properties and
methods exposed by this class.
"""
__test__ = False
def __init__(self, person, client=None, nick=None, fullname=None, email=None):
self._person = person
self._client = client
self._nick = nick
self._fullname = fullname
self._email = email
@property
def person(self):
"""This needs to return the part of the identifier pointing to a person."""
return self._person
@property
def client(self) -> Optional[str]:
"""This needs to return the part of the identifier pointing to a client
from which a person is sending a message from.
Returns None is unspecified"""
return self._client
@property
def nick(self) -> Optional[str]:
"""This needs to return a short display name for this identifier e.g. gbin.
Returns None is unspecified"""
return self._nick
@property
def fullname(self) -> Optional[str]:
"""This needs to return a long display name for this identifier e.g. Guillaume Binet.
Returns None is unspecified"""
return self._fullname
@property
def email(self) -> Optional[str]:
"""This needs to return an email for this identifier e.g. Guillaume.Binet@gmail.com.
Returns None is unspecified"""
return self._email
aclattr = person
def __unicode__(self) -> str:
if self.client:
return f"{self._person}/{self._client}"
return f"{self._person}"
__str__ = __unicode__
def __eq__(self, other):
if not isinstance(other, Person):
return False
return self.person == other.person
# noinspection PyAbstractClass
class TestOccupant(TestPerson, RoomOccupant):
"""This is a MUC occupant represented as a string.
DO NOT USE THIS DIRECTLY AS IT IS NOT COMPATIBLE WITH MOST BACKENDS,
"""
__test__ = False
def __init__(self, person, room):
super().__init__(person)
self._room = room
@property
def room(self) -> Room:
return self._room
def __unicode__(self):
return self._person + "@" + str(self._room)
__str__ = __unicode__
def __eq__(self, other):
return self.person == other.person and self.room == other.room
class TestRoom(Room):
__test__ = False
def invite(self, *args):
pass
def __init__(
self,
name: str,
occupants: Optional[List[TestOccupant]] = None,
topic: Optional[str] = None,
bot: ErrBot = None,
):
"""
:param name: Name of the room
:param occupants: Occupants of the room
:param topic: The MUC's topic
"""
if occupants is None:
occupants = []
self._occupants = occupants
self._topic = topic
self._bot = bot
self._name = name
self._bot_mucid = TestOccupant(
self._bot.bot_config.BOT_IDENTITY["username"], self._name
)
@property
def occupants(self) -> List[TestOccupant]:
return self._occupants
def find_croom(self) -> Optional["TestRoom"]:
"""find back the canonical room from a this room"""
for croom in self._bot._rooms:
if croom == self:
return croom
return None
@property
def joined(self) -> bool:
room = self.find_croom()
if room:
return self._bot_mucid in room.occupants
return False
def join(
self, username: Optional[str] = None, password: Optional[str] = None
) -> None:
if self.joined:
logging.warning(
"Attempted to join room %s, but already in this room.", self
)
return
if not self.exists:
log.debug("Room %s doesn't exist yet, creating it.", self)
self.create()
room = self.find_croom()
room._occupants.append(self._bot_mucid)
log.info("Joined room %s.", self)
self._bot.callback_room_joined(room, self._bot_mucid)
def leave(self, reason: Optional[str] = None) -> None:
if not self.joined:
logging.warning("Attempted to leave room %s, but not in this room.", self)
return
room = self.find_croom()
room._occupants.remove(self._bot_mucid)
log.info("Left room %s.", self)
self._bot.callback_room_left(room, self._bot_mucid)
@property
def exists(self) -> bool:
return self.find_croom() is not None
def create(self) -> None:
if self.exists:
logging.warning("Room %s already created.", self)
return
self._bot._rooms.append(self)
log.info("Created room %s.", self)
def destroy(self) -> None:
if not self.exists:
logging.warning("Cannot destroy room %s, it doesn't exist.", self)
return
self._bot._rooms.remove(self)
log.info("Destroyed room %s.", self)
@property
def topic(self) -> str:
return self._topic
@topic.setter
def topic(self, topic: str):
self._topic = topic
room = self.find_croom()
room._topic = self._topic
log.info("Topic for room %s set to %s.", self, topic)
self._bot.callback_room_topic(self)
def __unicode__(self):
return self._name
def __str__(self):
return self._name
def __eq__(self, other):
return self._name == other._name
class TestRoomAcl(TestRoom):
def __init__(self, name, occupants=None, topic=None, bot=None):
super().__init__(name, occupants, topic, bot)
@property
def aclattr(self):
return self._name
def __str__(self):
return "not room name"
class TestBackend(ErrBot):
def change_presence(self, status: str = ONLINE, message: str = "") -> None:
pass
def __init__(self, config):
config.BOT_LOG_LEVEL = logging.DEBUG
config.CHATROOM_PRESENCE = (
"testroom",
) # we are testing with simple identfiers
config.BOT_IDENTITY = {
"username": "err"
} # we are testing with simple identfiers
self.bot_identifier = self.build_identifier("Err") # whatever
super().__init__(config)
self.incoming_stanza_queue = Queue()
self.outgoing_message_queue = Queue()
self.sender = self.build_identifier(
config.BOT_ADMINS[0]
) # By default, assume this is the admin talking
self.reset_rooms()
self.md = text()
def send_message(self, msg: Message) -> None:
log.info("\n\n\nMESSAGE:\n%s\n\n\n", msg.body)
super().send_message(msg)
self.outgoing_message_queue.put(self.md.convert(msg.body))
def send_stream_request(
self,
user: Identifier,
fsource: Optional[BinaryIO],
name: Optional[str],
size: Optional[int],
stream_type: Optional[str],
) -> None:
# Just dump the stream contents to the message queue
self.outgoing_message_queue.put(fsource.read())
def serve_forever(self) -> None:
self.connect_callback() # notify that the connection occured
try:
while True:
log.debug("waiting on queue")
stanza_type, entry, extras = self.incoming_stanza_queue.get()
log.debug("message received")
if entry == QUIT_MESSAGE:
log.info("Stop magic message received, quitting...")
break
if stanza_type is STZ_MSG:
msg = Message(entry, extras=extras)
msg.frm = self.sender
msg.to = self.bot_identifier # To me only
self.callback_message(msg)
# implements the mentions.
mentioned = [
self.build_identifier(word[1:])
for word in entry.split()
if word.startswith("@")
]
if mentioned:
self.callback_mention(msg, mentioned)
elif stanza_type is STZ_PRE:
log.info("Presence stanza received.")
self.callback_presence(entry)
elif stanza_type is STZ_IQ:
log.info("IQ stanza received.")
else:
log.error("Unknown stanza type.")
except EOFError:
pass
except KeyboardInterrupt:
pass
finally:
log.debug("Trigger disconnect callback")
self.disconnect_callback()
log.debug("Trigger shutdown")
self.shutdown()
def shutdown(self) -> None:
if self.is_open_storage():
self.close_storage()
self.plugin_manager.shutdown()
self.repo_manager.shutdown()
# super().shutdown()
def connect(self) -> None:
return
def build_identifier(self, text_representation) -> TestPerson:
return TestPerson(text_representation)
def build_reply(
self, msg: Message, text=None, private: bool = False, threaded: bool = False
) -> Message:
msg = self.build_message(text)
msg.frm = self.bot_identifier
msg.to = msg.frm
return msg
@property
def mode(self) -> str:
return "test"
def rooms(self) -> List[TestRoom]:
return [r for r in self._rooms if r.joined]
def query_room(self, room: TestRoom) -> TestRoom:
try:
return [r for r in self._rooms if str(r) == str(room)][0]
except IndexError:
r = TestRoom(room, bot=self)
return r
def prefix_groupchat_reply(self, message: Message, identifier: Identifier):
super().prefix_groupchat_reply(message, identifier)
message.body = f"@{identifier.nick} {message.body}"
def pop_message(self, timeout: int = 5, block: bool = True):
return self.outgoing_message_queue.get(timeout=timeout, block=block)
def push_message(self, msg: Message, extras=""):
self.incoming_stanza_queue.put((STZ_MSG, msg, extras), timeout=5)
def push_presence(self, presence):
"""presence must at least duck type base.Presence"""
self.incoming_stanza_queue.put((STZ_PRE, presence), timeout=5)
def zap_queues(self) -> None:
while not self.incoming_stanza_queue.empty():
msg = self.incoming_stanza_queue.get(block=False)
log.error("Message left in the incoming queue during a test: %s.", msg)
while not self.outgoing_message_queue.empty():
msg = self.outgoing_message_queue.get(block=False)
log.error("Message left in the outgoing queue during a test: %s.", msg)
def reset_rooms(self) -> None:
"""Reset/clear all rooms"""
self._rooms = []
class ShallowConfig:
pass
class TestBot:
"""
A minimal bot utilizing the TestBackend, for use with unit testing.
Only one instance of this class should globally be active at any one
time.
End-users should not use this class directly. Use
:func:`~errbot.backends.test.testbot` or
:class:`~errbot.backends.test.FullStackTest` instead, which use this
class under the hood.
"""
def __init__(
self, extra_plugin_dir=None, loglevel=logging.DEBUG, extra_config=None
):
self.bot_thread = None
self.setup(
extra_plugin_dir=extra_plugin_dir,
loglevel=loglevel,
extra_config=extra_config,
)
def setup(
self,
extra_plugin_dir: Optional[str] = None,
loglevel=logging.DEBUG,
extra_config=None,
):
"""
:param extra_config: Piece of extra configuration you want to inject to the config.
:param extra_plugin_dir: Path to a directory from which additional
plugins should be loaded.
:param loglevel: Logging verbosity. Expects one of the constants
defined by the logging module.
"""
tempdir = mkdtemp()
# This is for test isolation.
config = ShallowConfig()
config.__dict__.update(
importlib.import_module("errbot.config-template").__dict__
)
config.BOT_DATA_DIR = tempdir
config.BOT_LOG_FILE = tempdir + sep + "log.txt"
config.STORAGE = "Memory"
if extra_config is not None:
log.debug("Merging %s to the bot config.", repr(extra_config))
for k, v in extra_config.items():
setattr(config, k, v)
# reset logging to console
logging.basicConfig(format="%(levelname)s:%(message)s")
file = logging.FileHandler(config.BOT_LOG_FILE, encoding="utf-8")
self.logger = logging.getLogger("")
self.logger.setLevel(loglevel)
self.logger.addHandler(file)
config.BOT_EXTRA_PLUGIN_DIR = extra_plugin_dir
config.BOT_LOG_LEVEL = loglevel
self.bot_config = config
def start(self, timeout: int = 2) -> None:
"""
Start the bot
Calling this method when the bot has already started will result
in an Exception being raised.
:param timeout: Timeout for the ready message pop. pop will be done 60 times so the total timeout is 60*timeout
"""
if self.bot_thread is not None:
raise Exception("Bot has already been started")
self._bot = setup_bot("Test", self.logger, self.bot_config)
self.bot_thread = Thread(
target=self.bot.serve_forever,
name="TestBot main thread",
daemon=True,
)
self.bot_thread.start()
self.bot.push_message("!echo ready")
# Ensure bot is fully started and plugins are loaded before returning
try:
for i in range(60):
# Gobble initial error messages...
msg = self.bot.pop_message(timeout=timeout)
if msg == "ready":
break
log.warning("Queue was not empty, the non-consumed message is:")
log.warning(msg)
log.warning("Check the previous test and remove spurrious messages.")
except Empty:
raise AssertionError('The "ready" message has not been received (timeout).')
@property
def bot(self) -> ErrBot:
return self._bot
def stop(self) -> None:
"""
Stop the bot
Calling this method before the bot has started will result in an
Exception being raised.
"""
if self.bot_thread is None:
raise Exception("Bot has not yet been started")
self.bot.push_message(QUIT_MESSAGE)
self.bot_thread.join()
reset_app() # empty the bottle ... hips!
log.info("Main bot thread quits")
self.bot.zap_queues()
self.bot.reset_rooms()
self.bot_thread = None
def pop_message(self, timeout: int = 5, block: bool = True):
return self.bot.pop_message(timeout, block)
def push_message(self, msg: Message, extras=""):
return self.bot.push_message(msg, extras=extras)
def push_presence(self, presence: Presence):
"""presence must at least duck type base.Presence"""
return self.bot.push_presence(presence)
def exec_command(self, command, timeout: int = 5):
"""Execute a command and return the first response.
This makes more py.test'ist like:
assert 'blah' in exec_command('!hello')
"""
self.bot.push_message(command)
return self.bot.pop_message(timeout)
def zap_queues(self):
return self.bot.zap_queues()
def assertInCommand(self, command, response, timeout=5, dedent=False):
"""Assert the given command returns the given response"""
if dedent:
command = "\n".join(textwrap.dedent(command).splitlines()[1:])
self.bot.push_message(command)
msg = self.bot.pop_message(timeout)
assert response in msg, f"{response} not in {msg}."
@deprecated(assertInCommand)
def assertCommand(self, command, response, timeout=5, dedent=False):
"""Assert the given command returns the given response"""
pass
def assertCommandFound(self, command, timeout=5):
"""Assert the given command exists"""
self.bot.push_message(command)
assert "not found" not in self.bot.pop_message(timeout)
def inject_mocks(self, plugin_name: str, mock_dict: dict):
"""Inject mock objects into the plugin
Example::
mock_dict = {
'field_1': obj_1,
'field_2': obj_2,
}
testbot.inject_mocks(HelloWorld, mock_dict)
assert 'blah' in testbot.exec_command('!hello')
"""
plugin = self.bot.plugin_manager.get_plugin_obj_by_name(plugin_name)
if plugin is None:
raise Exception(f'"{plugin_name}" is not loaded.')
for field, mock_obj in mock_dict.items():
if not hasattr(plugin, field):
raise ValueError(f'No property/attribute named "{field}" attached.')
setattr(plugin, field, mock_obj)
class FullStackTest(unittest.TestCase, TestBot):
"""
Test class for use with Python's unittest module to write tests
against a fully functioning bot.
For example, if you wanted to test the builtin `!about` command,
you could write a test file with the following::
from errbot.backends.test import FullStackTest
class TestCommands(FullStackTest):
def test_about(self):
self.push_message('!about')
self.assertIn('Err version', self.pop_message())
"""
def setUp(
self,
extra_plugin_dir=None,
extra_test_file=None,
loglevel=logging.DEBUG,
extra_config=None,
) -> None:
"""
:param extra_plugin_dir: Path to a directory from which additional
plugins should be loaded.
:param extra_test_file: [Deprecated but kept for backward-compatibility,
use extra_plugin_dir instead]
Path to an additional plugin which should be loaded.
:param loglevel: Logging verbosity. Expects one of the constants
defined by the logging module.
:param extra_config: Piece of extra bot config in a dict.
"""
if extra_plugin_dir is None and extra_test_file is not None:
extra_plugin_dir = sep.join(abspath(extra_test_file).split(sep)[:-2])
self.setup(
extra_plugin_dir=extra_plugin_dir,
loglevel=loglevel,
extra_config=extra_config,
)
self.start()
def tearDown(self) -> None:
self.stop()
@pytest.fixture
def testbot(request) -> TestBot:
"""
Pytest fixture to write tests against a fully functioning bot.
For example, if you wanted to test the builtin `!about` command,
you could write a test file with the following::
def test_about(testbot):
testbot.push_message('!about')
assert "Err version" in testbot.pop_message()
It's possible to provide additional configuration to this fixture,
by setting variables at module level or as class attributes (the
latter taking precedence over the former). For example::
extra_plugin_dir = '/foo/bar'
def test_about(testbot):
testbot.push_message('!about')
assert "Err version" in testbot.pop_message()
..or::
extra_plugin_dir = '/foo/bar'
class Tests:
# Wins over `extra_plugin_dir = '/foo/bar'` above
extra_plugin_dir = '/foo/baz'
def test_about(self, testbot):
testbot.push_message('!about')
assert "Err version" in testbot.pop_message()
..to load additional plugins from the directory `/foo/bar` or
`/foo/baz` respectively. This works for the following items, which are
passed to the constructor of :class:`~errbot.backends.test.TestBot`:
* `extra_plugin_dir`
* `loglevel`
"""
def on_finish() -> TestBot:
bot.stop()
# setup the logging to something digestable.
logger = logging.getLogger("")
logging.getLogger("MARKDOWN").setLevel(
logging.ERROR
) # this one is way too verbose in debug
logger.setLevel(logging.DEBUG)
console_hdlr = logging.StreamHandler(sys.stdout)
console_hdlr.setFormatter(
logging.Formatter("%(levelname)-8s %(name)-25s %(message)s")
)
logger.handlers = []
logger.addHandler(console_hdlr)
kwargs = {}
for attr, default in (
("extra_plugin_dir", None),
("extra_config", None),
("loglevel", logging.DEBUG),
):
if hasattr(request, "instance"):
kwargs[attr] = getattr(request.instance, attr, None)
if kwargs[attr] is None:
kwargs[attr] = getattr(request.module, attr, default)
bot = TestBot(**kwargs)
bot.start()
request.addfinalizer(on_finish)
return bot
| 22,382
|
Python
|
.py
| 571
| 30.259194
| 119
| 0.611931
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,179
|
null.py
|
errbotio_errbot/errbot/backends/null.py
|
import logging
from time import sleep
from errbot.backends.base import ONLINE
from errbot.backends.test import TestPerson
from errbot.core import ErrBot
log = logging.getLogger(__name__)
class ConnectionMock:
def send(self, msg):
pass
def send_message(self, msg):
pass
class NullBackend(ErrBot):
conn = ConnectionMock()
running = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.bot_identifier = self.build_identifier("Err") # whatever
def serve_forever(self):
self.connect() # be sure we are "connected" before the first command
self.connect_callback() # notify that the connection occured
try:
while self.running:
sleep(1)
except EOFError:
pass
except KeyboardInterrupt:
pass
finally:
log.debug("Trigger disconnect callback")
self.disconnect_callback()
log.debug("Trigger shutdown")
self.shutdown()
def connect(self):
if not self.conn:
self.conn = ConnectionMock()
return self.conn
def build_identifier(self, strrep):
return TestPerson(strrep)
def shutdown(self):
if self.running:
self.running = False
super().shutdown() # only once (hackish)
def change_presence(self, status: str = ONLINE, message: str = "") -> None:
pass
def build_reply(self, msg, text=None, private=False, threaded=False):
pass
def prefix_groupchat_reply(self, message, identifier):
pass
def query_room(self, room):
pass
def rooms(self):
pass
@property
def mode(self):
return "null"
| 1,771
|
Python
|
.py
| 55
| 24.309091
| 79
| 0.620507
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,180
|
text.py
|
errbotio_errbot/errbot/backends/text.py
|
import copyreg
import logging
import re
import sys
from time import sleep
from typing import BinaryIO, List, Optional, Union
from ansi.color import fg, fx
from markdown import Markdown
from markdown.extensions.extra import ExtraExtension
from pygments import highlight
from pygments.formatters import Terminal256Formatter
from pygments.lexers import get_lexer_by_name
from errbot.backends.base import (
OFFLINE,
ONLINE,
Identifier,
Message,
Person,
Presence,
Room,
RoomOccupant,
Stream,
)
from errbot.core import ErrBot
from errbot.logs import console_hdlr
from errbot.rendering import ansi, imtext, text, xhtml
from errbot.rendering.ansiext import ANSI_CHRS, AnsiExtension, enable_format
log = logging.getLogger(__name__)
ENCODING_INPUT = sys.stdin.encoding
ANSI = hasattr(sys.stderr, "isatty") and sys.stderr.isatty()
enable_format("borderless", ANSI_CHRS, borders=False)
def borderless_ansi() -> Markdown:
"""This makes a converter from markdown to ansi (console) format.
It can be called like this:
from errbot.rendering import ansi
md_converter = ansi() # you need to cache the converter
ansi_txt = md_converter.convert(md_txt)
"""
md = Markdown(
output_format="borderless", extensions=[ExtraExtension(), AnsiExtension()]
)
md.stripTopLevelTags = False
return md
class TextPerson(Person):
"""
Simple Person implementation which represents users as simple text strings.
"""
def __init__(self, person, client=None, nick=None, fullname=None):
self._person = person
self._client = client
self._nick = nick
self._fullname = fullname
self._email = ""
@property
def person(self) -> Person:
return self._person
@property
def client(self) -> str:
return self._client
@property
def nick(self) -> str:
return self._nick
@property
def fullname(self) -> str:
return self._fullname
@property
def email(self) -> str:
return self._email
@property
def aclattr(self) -> str:
return str(self)
def __str__(self):
return "@" + self._person
def __eq__(self, other):
if not isinstance(other, Person):
return False
return self.person == other.person
def __hash__(self):
return self.person.__hash__()
class TextRoom(Room):
def __init__(self, name: str, bot: ErrBot):
self._topic = ""
self._joined = False
self.name = name
self._bot = bot
# get the bot username
bot_config = self._bot.bot_config
default_bot_name = "@errbot"
if hasattr(bot_config, "BOT_IDENTITY"):
bot_name = bot_config.BOT_IDENTITY.get("username", default_bot_name)
else:
bot_name = default_bot_name
# fill up the room with a coherent set of identities.
self._occupants = [
TextOccupant("somebody", self),
TextOccupant(TextPerson(bot.bot_config.BOT_ADMINS[0]), self),
TextOccupant(bot_name, self),
]
def join(
self, username: Optional[str] = None, password: Optional[str] = None
) -> None:
self._joined = True
def leave(self, reason: Optional[str] = None) -> None:
self._joined = False
def create(self) -> None:
self._joined = True
def destroy(self) -> None:
self._joined = False
@property
def exists(self) -> bool:
return True
@property
def joined(self) -> bool:
return self._joined
@property
def topic(self) -> str:
return self._topic
@topic.setter
def topic(self, topic: str) -> None:
self._topic = topic
@property
def occupants(self) -> List["TextOccupant"]:
return self._occupants
def invite(self, *args):
pass
def __str__(self):
return "#" + self.name
def __eq__(self, other):
return self.name == other.name
def __hash__(self):
return self.name.__hash__()
class TextOccupant(TextPerson, RoomOccupant):
def __init__(self, person, room):
super().__init__(person)
self._room = room
@property
def room(self) -> TextRoom:
return self._room
def __str__(self):
return f"#{self._room.name}/{self._person.person}"
def __eq__(self, other):
return self.person == other.person and self.room == other.room
def __hash__(self):
return self.person.__hash__() + self.room.__hash__()
INTRO = """
---
You start as a **bot admin in a one-on-one conversation** with the bot.
### Context of the chat
- Use `!inroom`{:color='blue'} to switch to a room conversation.
- Use `!inperson`{:color='blue'} to switch back to a one-on-one conversation.
- Use `!asuser`{:color='green'} to talk as a normal user.
- Use `!asadmin`{:color='red'} to switch back as a bot admin.
### Preferences
- Use `!ml`{:color='yellow'} to flip on/off the multiline mode (Enter twice at the end to send).
---
"""
class TextBackend(ErrBot):
def __init__(self, config):
super().__init__(config)
log.debug("Text Backend Init.")
if (
hasattr(self.bot_config, "BOT_IDENTITY")
and "username" in self.bot_config.BOT_IDENTITY
):
self.bot_identifier = self.build_identifier(
self.bot_config.BOT_IDENTITY["username"]
)
else:
# Just a default identity for the bot if nothing has been specified.
self.bot_identifier = self.build_identifier("@errbot")
log.debug("Bot username set at %s.", self.bot_identifier)
self._inroom = False
self._rooms = []
self._multiline = False
self.demo_mode = (
self.bot_config.TEXT_DEMO_MODE
if hasattr(self.bot_config, "TEXT_DEMO_MODE")
else False
)
if not self.demo_mode:
self.md_html = xhtml() # for more debug feedback on md
self.md_text = text() # for more debug feedback on md
self.md_borderless_ansi = borderless_ansi()
self.md_im = imtext()
self.md_lexer = get_lexer_by_name("md", stripall=True)
self.md_ansi = ansi()
self.html_lexer = get_lexer_by_name("html", stripall=True)
self.terminal_formatter = Terminal256Formatter(style="paraiso-dark")
self.user = self.build_identifier(self.bot_config.BOT_ADMINS[0])
self._register_identifiers_pickling()
@staticmethod
def _unpickle_identifier(identifier_str):
return TextBackend.__build_identifier(identifier_str)
@staticmethod
def _pickle_identifier(identifier):
return TextBackend._unpickle_identifier, (str(identifier),)
def _register_identifiers_pickling(self):
"""
Register identifiers pickling.
"""
TextBackend.__build_identifier = self.build_identifier
for cls in (TextPerson, TextOccupant, TextRoom):
copyreg.pickle(
cls, TextBackend._pickle_identifier, TextBackend._unpickle_identifier
)
def serve_forever(self) -> None:
self.readline_support()
if not self._rooms:
# artificially join a room if None were specified.
self.query_room("#testroom").join()
if self.demo_mode:
# disable the console logging once it is serving in demo mode.
root = logging.getLogger()
root.removeHandler(console_hdlr)
root.addHandler(logging.NullHandler())
self.connect_callback() # notify that the connection occured
self.callback_presence(Presence(identifier=self.user, status=ONLINE))
self.send_message(Message(INTRO))
try:
while True:
if self._inroom:
frm = TextOccupant(self.user, self.rooms()[0])
to = self.rooms()[0]
else:
frm = self.user
to = self.bot_identifier
print()
full_msg = ""
while True:
prompt = "[␍] " if full_msg else ">>> "
if ANSI or self.demo_mode:
color = (
fg.red
if self.user.person in self.bot_config.BOT_ADMINS[0]
else fg.green
)
prompt = f"{color}[{frm} ➡ {to}] {fg.cyan}{prompt}{fx.reset}"
entry = input(prompt)
else:
entry = input(f"[{frm} ➡ {to}] {prompt}")
if not self._multiline:
full_msg = entry
break
if not entry:
break
full_msg += entry + "\n"
msg = Message(full_msg)
msg.frm = frm
msg.to = to
self.callback_message(msg)
mentioned = [
self.build_identifier(word)
for word in re.findall(r"(?<=\s)@[\w]+", entry)
]
if mentioned:
self.callback_mention(msg, mentioned)
sleep(0.5)
except EOFError:
pass
except KeyboardInterrupt:
pass
finally:
# simulate some real presence
self.callback_presence(Presence(identifier=self.user, status=OFFLINE))
log.debug("Trigger disconnect callback")
self.disconnect_callback()
log.debug("Trigger shutdown")
self.shutdown()
def readline_support(self) -> None:
try:
# Load readline for better editing/history behaviour
import readline
# Implement a simple completer for commands
def completer(txt, state):
options = (
[i for i in self.all_commands if i.startswith(txt)]
if txt
else list(self.all_commands.keys())
)
if state < len(options):
return options[state]
readline.parse_and_bind("tab: complete")
readline.set_completer(completer)
except ImportError:
# Readline is Unix-only
log.debug("Python readline module is not available")
def send_message(self, msg: Message) -> None:
if self.demo_mode:
print(self.md_ansi.convert(msg.body))
else:
bar = "\n╌╌[{mode}]" + ("╌" * 60)
super().send_message(msg)
print(bar.format(mode="MD "))
if ANSI:
print(highlight(msg.body, self.md_lexer, self.terminal_formatter))
else:
print(msg.body)
print(bar.format(mode="HTML"))
html = self.md_html.convert(msg.body)
if ANSI:
print(highlight(html, self.html_lexer, self.terminal_formatter))
else:
print(html)
print(bar.format(mode="TEXT"))
print(self.md_text.convert(msg.body))
print(bar.format(mode="IM "))
print(self.md_im.convert(msg.body))
if ANSI:
print(bar.format(mode="ANSI"))
print(self.md_ansi.convert(msg.body))
print(bar.format(mode="BORDERLESS"))
print(self.md_borderless_ansi.convert(msg.body))
print("\n\n")
def add_reaction(self, msg: Message, reaction: str) -> None:
# this is like the Slack backend's add_reaction
self._react("+", msg, reaction)
def remove_reaction(self, msg: Message, reaction: str) -> None:
self._react("-", msg, reaction)
def _react(self, sign: str, msg: Message, reaction: str) -> None:
self.send(msg.frm, f"reaction {sign}:{reaction}:", in_reply_to=msg)
def change_presence(self, status: str = ONLINE, message: str = "") -> None:
log.debug("*** Changed presence to [%s] %s", status, message)
def build_identifier(
self, text_representation: str
) -> Union[TextOccupant, TextRoom, TextPerson]:
if text_representation.startswith("#"):
rem = text_representation[1:]
if "/" in text_representation:
room, person = rem.split("/")
return TextOccupant(TextPerson(person), TextRoom(room, self))
return self.query_room("#" + rem)
if not text_representation.startswith("@"):
raise ValueError(
"An identifier for the Text backend needs to start with # for a room or @ for a person."
)
return TextPerson(text_representation[1:])
def build_reply(
self,
msg: Message,
text: str = None,
private: bool = False,
threaded: bool = False,
) -> Message:
response = self.build_message(text)
response.frm = self.bot_identifier
if private:
response.to = msg.frm
else:
response.to = msg.frm.room if isinstance(msg.frm, RoomOccupant) else msg.frm
return response
@property
def mode(self):
return "text"
def query_room(self, room: str) -> TextRoom:
if not room.startswith("#"):
raise ValueError("A Room name must start by #.")
text_room = TextRoom(room[1:], self)
if text_room not in self._rooms:
self._rooms.insert(0, text_room)
else:
self._rooms.insert(0, self._rooms.pop(self._rooms.index(text_room)))
return text_room
def rooms(self) -> List[TextRoom]:
return self._rooms
def prefix_groupchat_reply(self, message: Message, identifier: Identifier):
message.body = f"{identifier.person} {message.body}"
def send_stream_request(
self,
user: Identifier,
fsource: BinaryIO,
name: str = None,
size: int = None,
stream_type: str = None,
) -> Stream:
"""
Starts a file transfer. For Slack, the size and stream_type are unsupported
:param user: is the identifier of the person you want to send it to.
:param fsource: is a file object you want to send.
:param name: is an optional filename for it.
:param size: not supported in Slack backend
:param stream_type: not supported in Slack backend
:return Stream: object on which you can monitor the progress of it.
"""
stream = Stream(user, fsource, name, size, stream_type)
log.debug(
"Requesting upload of %s to %s (size hint: %d, stream type: %s).",
stream.name,
stream.identifier,
size,
stream_type,
)
return stream
| 14,985
|
Python
|
.py
| 392
| 28.293367
| 104
| 0.579325
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,181
|
base.py
|
errbotio_errbot/errbot/backends/base.py
|
import io
import logging
import random
import time
from abc import ABC, abstractmethod
from collections import defaultdict, deque
from typing import Any, BinaryIO, List, Mapping, Optional, Sequence, Tuple, Type
log = logging.getLogger(__name__)
class Identifier(ABC):
"""This is just use for type hinting representing the Identifier contract,
NEVER TRY TO SUBCLASS IT OUTSIDE OF A BACKEND, it is just here to show you what you can expect from an Identifier.
To get an instance of a real identifier, always use the properties from Message (to, from) or self.build_identifier
to make an identifier from a String.
The semantics is anything you can talk to: Person, Room, RoomOccupant etc.
"""
pass
class Person(Identifier):
"""This is just use for type hinting representing the Identifier contract,
NEVER TRY TO SUBCLASS IT OUTSIDE OF A BACKEND, it is just here to show you what you can expect from an Identifier.
To get an instance of a real identifier, always use the properties from Message (to, from) or self.build_identifier
to make an identifier from a String.
"""
@property
@abstractmethod
def person(self) -> str:
"""
:return: a backend specific unique identifier representing the person you are talking to.
"""
pass
@property
@abstractmethod
def client(self) -> str:
"""
:return: a backend specific unique identifier representing the device or client the person is using to talk.
"""
pass
@property
@abstractmethod
def nick(self) -> str:
"""
:return: a backend specific nick returning the nickname of this person if available.
"""
pass
@property
@abstractmethod
def aclattr(self) -> str:
"""
:return: returns the unique identifier that will be used for ACL matches.
"""
pass
@property
@abstractmethod
def fullname(self) -> str:
"""
Some backends have the full name of a user.
:return: the fullname of this user if available.
"""
pass
@property
def email(self) -> str:
"""
Some backends have the email of a user.
:return: the email of this user if available.
"""
return ""
class RoomOccupant(Identifier):
@property
@abstractmethod
def room(self) -> Any: # this is oom defined below
"""
Some backends have the full name of a user.
:return: the fullname of this user if available.
"""
pass
class Room(Identifier):
"""
This class represents a Multi-User Chatroom.
"""
def join(self, username: str = None, password: str = None) -> None:
"""
Join the room.
If the room does not exist yet, this will automatically call
:meth:`create` on it first.
"""
raise NotImplementedError(
"It should be implemented specifically for your backend"
)
def leave(self, reason: str = None) -> None:
"""
Leave the room.
:param reason:
An optional string explaining the reason for leaving the room.
"""
raise NotImplementedError(
"It should be implemented specifically for your backend"
)
def create(self) -> None:
"""
Create the room.
Calling this on an already existing room is a no-op.
"""
raise NotImplementedError(
"It should be implemented specifically for your backend"
)
def destroy(self) -> None:
"""
Destroy the room.
Calling this on a non-existing room is a no-op.
"""
raise NotImplementedError(
"It should be implemented specifically for your backend"
)
@property
def aclattr(self) -> str:
"""
:return: returns the unique identifier that will be used for ACL matches.
"""
return str(self)
@property
def exists(self) -> bool:
"""
Boolean indicating whether this room already exists or not.
:getter:
Returns `True` if the room exists, `False` otherwise.
"""
raise NotImplementedError(
"It should be implemented specifically for your backend"
)
@property
def joined(self) -> bool:
"""
Boolean indicating whether this room has already been joined.
:getter:
Returns `True` if the room has been joined, `False` otherwise.
"""
raise NotImplementedError(
"It should be implemented specifically for your backend"
)
@property
def topic(self) -> str:
"""
The room topic.
:getter:
Returns the topic (a string) if one is set, `None` if no
topic has been set at all.
.. note::
Back-ends may return an empty string rather than `None`
when no topic has been set as a network may not
differentiate between no topic and an empty topic.
:raises:
:class:`~MUCNotJoinedError` if the room has not yet been joined.
"""
raise NotImplementedError(
"It should be implemented specifically for your backend"
)
@topic.setter
def topic(self, topic: str) -> None:
"""
Set the room's topic.
:param topic:
The topic to set.
"""
raise NotImplementedError(
"It should be implemented specifically for your backend"
)
@property
def occupants(self) -> List[RoomOccupant]:
"""
The room's occupants.
:getter:
Returns a list of occupant identities.
:raises:
:class:`~MUCNotJoinedError` if the room has not yet been joined.
"""
raise NotImplementedError(
"It should be implemented specifically for your backend"
)
def invite(self, *args) -> None:
"""
Invite one or more people into the room.
:param *args:
One or more identifiers to invite into the room.
"""
raise NotImplementedError(
"It should be implemented specifically for your backend"
)
class RoomError(Exception):
"""General exception class for MUC-related errors"""
class RoomNotJoinedError(RoomError):
"""Exception raised when performing MUC operations
that require the bot to have joined the room"""
class RoomDoesNotExistError(RoomError):
"""Exception that is raised when performing an operation
on a room that doesn't exist"""
class UserDoesNotExistError(Exception):
"""Exception that is raised when performing an operation
on a user that doesn't exist"""
class UserNotUniqueError(Exception):
"""
Exception raised to report a user has not been uniquely identified on the chat service.
"""
class Message:
"""
A chat message.
This class represents chat messages that are sent or received by
the bot.
"""
def __init__(
self,
body: str = "",
frm: Identifier = None,
to: Identifier = None,
parent: "Message" = None,
delayed: bool = False,
partial: bool = False,
extras: Mapping = None,
flow=None,
):
"""
:param body:
The markdown body of the message.
:param extras:
Extra data attached by a backend
:param flow:
The flow in which this message has been triggered.
:param parent:
The parent message of this message in a thread. (Not supported by all backends)
:param partial:
Indicates whether the message was obtained by breaking down the message to fit
the ``MESSAGE_SIZE_LIMIT``.
"""
self._body = body
self._from = frm
self._to = to
self._parent = parent
self._delayed = delayed
self._extras = extras or dict()
self._flow = flow
self._partial = partial
# Convenience shortcut to the flow context
if flow:
self.ctx = flow.ctx
else:
self.ctx = {}
def clone(self) -> "Message":
return Message(
body=self._body,
frm=self._from,
to=self._to,
parent=self._parent,
delayed=self._delayed,
partial=self._partial,
extras=self._extras,
flow=self._flow,
)
@property
def to(self) -> Identifier:
"""
Get the recipient of the message.
:returns:
A backend specific identifier representing the recipient.
"""
return self._to
@to.setter
def to(self, to: Identifier):
"""
Set the recipient of the message.
:param to:
An identifier from for example build_identifier().
"""
self._to = to
@property
def frm(self) -> Identifier:
"""
Get the sender of the message.
:returns:
An :class:`~errbot.backends.base.Identifier` identifying
the sender.
"""
return self._from
@frm.setter
def frm(self, from_: Identifier):
"""
Set the sender of the message.
:param from_:
An identifier from build_identifier.
"""
self._from = from_
@property
def body(self) -> str:
"""
Get the plaintext body of the message.
:returns:
The body as a string.
"""
return self._body
@body.setter
def body(self, body: str):
self._body = body
@property
def delayed(self) -> bool:
return self._delayed
@delayed.setter
def delayed(self, delayed: bool):
self._delayed = delayed
@property
def parent(self) -> Optional["Message"]:
return self._parent
@parent.setter
def parent(self, parent: "Message"):
self._parent = parent
@property
def extras(self) -> Mapping:
return self._extras
@property
def flow(self) -> Type["errbot.Flow"]: # noqa: F821
"""
Get the conversation flow for this message.
:returns:
A :class:`~errbot.Flow`
"""
return self._from
def __str__(self):
return self._body
@property
def is_direct(self) -> bool:
return isinstance(self.to, Person)
@property
def is_group(self) -> bool:
return isinstance(self.to, Room)
@property
def is_threaded(self) -> bool:
return self._parent is not None
@property
def partial(self) -> bool:
return self._partial
@partial.setter
def partial(self, partial):
self._partial = partial
class Card(Message):
"""
Card is a special type of preformatted message. If it matches with a backend similar concept like on
Slack it will be rendered natively, otherwise it will be sent as a regular message formatted with
the card.md template.
"""
def __init__(
self,
body: str = "",
frm: Identifier = None,
to: Identifier = None,
parent: Message = None,
summary: str = None,
title: str = "",
link: str = None,
image: str = None,
thumbnail: str = None,
color: str = None,
fields: Tuple[Tuple[str, str]] = (),
):
"""
Creates a Card.
:param body: main text of the card in markdown.
:param frm: the card is sent from this identifier.
:param to: the card is sent to this identifier (Room, RoomOccupant, Person...).
:param parent: the parent message this card replies to. (threads the message if the backend supports it).
:param summary: (optional) One liner summary of the card, possibly collapsed to it.
:param title: (optional) Title possibly linking.
:param link: (optional) url the title link is pointing to.
:param image: (optional) link to the main image of the card.
:param thumbnail: (optional) link to an icon / thumbnail.
:param color: (optional) background color or color indicator.
:param fields: (optional) a tuple of (key, value) pairs.
"""
super().__init__(body=body, frm=frm, to=to, parent=parent)
self._summary = summary
self._title = title
self._link = link
self._image = image
self._thumbnail = thumbnail
self._color = color
self._fields = fields
@property
def summary(self) -> str:
return self._summary
@property
def title(self) -> str:
return self._title
@property
def link(self) -> str:
return self._link
@property
def image(self) -> str:
return self._image
@property
def thumbnail(self) -> str:
return self._thumbnail
@property
def color(self) -> str:
return self._color
@property
def text_color(self) -> str:
if self._color in ("black", "blue"):
return "white"
return "black"
@property
def fields(self) -> Tuple[Tuple[str, str]]:
return self._fields
ONLINE = "online"
OFFLINE = "offline"
AWAY = "away"
DND = "dnd"
class Presence:
"""
This class represents a presence change for a user or a user in a chatroom.
Instances of this class are passed to :meth:`~errbot.botplugin.BotPlugin.callback_presence`
when the presence of people changes.
"""
def __init__(self, identifier: Identifier, status: str = None, message: str = None):
if identifier is None:
raise ValueError("Presence: identifiers is None")
if status is None and message is None:
raise ValueError(
"Presence: at least a new status or a new status message mustbe present"
)
self._identifier = identifier
self._status = status
self._message = message
@property
def identifier(self) -> Identifier:
"""
Identifier for whom its status changed. It can be a RoomOccupant or a Person.
:return: the person or roomOccupant
"""
return self._identifier
@property
def status(self) -> str:
"""Returns the status of the presence change.
It can be one of the constants ONLINE, OFFLINE, AWAY, DND, but
can also be custom statuses depending on backends.
It can be None if it is just an update of the status message (see get_message)
"""
return self._status
@property
def message(self) -> str:
"""Returns a human readable message associated with the status if any.
like : "BRB, washing the dishes"
It can be None if it is only a general status update (see get_status)
"""
return self._message
def __str__(self):
response = ""
if self._identifier:
response += f'identifier: "{self._identifier}" '
if self._status:
response += f'status: "{self._status}" '
if self._message:
response += f'message: "{self._message}" '
return response
def __unicode__(self):
return str(self.__str__())
REACTION_ADDED = "added"
REACTION_REMOVED = "removed"
class Reaction:
"""
This class represents a reaction event, either an added or removed reaction,
to some message or object.
Instances of this class are passed to :meth:`~errbot.botplugin.BotPlugin.callback_reaction`
when the reaction event is received.
Note: Reactions, at the time of implementation, are only provided by the
Slack backend. This class is largely based on the Slack reaction event data.
"""
def __init__(
self,
reactor: Identifier = None,
reacted_to_owner: Identifier = None,
action: str = None,
timestamp: str = None,
reaction_name: str = None,
reacted_to: Mapping = None,
):
if reactor is None:
raise ValueError("Reaction: reactor is None")
if reaction_name is None:
raise ValueError("Reaction: reaction_name is None")
self._reactor = reactor
self._reacted_to_owner = reacted_to_owner
self._action = action
self._timestamp = timestamp
self._reaction_name = reaction_name
self._reacted_to = reacted_to
@property
def reactor(self) -> Identifier:
"""
Identifier of the reacting individual. It can be a RoomOccupant or a Person.
:return: the person or roomOccupant
"""
return self._reactor
@property
def reacted_to_owner(self) -> Identifier:
"""
Identifier of the owner, if any, of the item that was reacted to.
It can be a RoomOccupant or a Person.
:return: the person or roomOccupant
"""
return self._reacted_to_owner
@property
def action(self) -> str:
"""Returns the action performed
It can be one of the constants REACTION_ADDED or REACTION_REMOVED
It can also be backend specific
"""
return self._action
@property
def timestamp(self) -> str:
"""Returns the timestamp string in which the event occurred
Format of the timestamp string is backend specific
"""
return self._timestamp
@property
def reaction_name(self) -> str:
"""Returns the reaction that was added or removed
Format of the reaction is backend specific
"""
return self._reaction_name
@property
def reacted_to(self) -> Mapping:
"""Returns the item that was reacted to
Structure of the reacted to item is backend specific
"""
return self._reacted_to
def __str__(self):
response = ""
if self._reactor:
response += f'reactor: "{self._reactor}" '
if self._reaction_name:
response += f'reaction_name: "{self._reaction_name}" '
if self._action:
response += f'action: "{self._action}" '
if self._timestamp:
response += f'timestamp: "{self._timestamp}" '
if self._reacted_to_owner:
response += f'reacted_to_owner: "{self._reacted_to_owner}" '
if self._reacted_to:
response += f'reacted_to: "{self._reacted_to}" '
return response
STREAM_WAITING_TO_START = "pending"
STREAM_TRANSFER_IN_PROGRESS = "in progress"
STREAM_SUCCESSFULLY_TRANSFERED = "success"
STREAM_PAUSED = "paused"
STREAM_ERROR = "error"
STREAM_REJECTED = "rejected"
DEFAULT_REASON = "unknown"
class Stream(io.BufferedReader):
"""
This class represents a stream request.
Instances of this class are passed to :meth:`~errbot.botplugin.BotPlugin.callback_stream`
when an incoming stream is requested.
"""
def __init__(
self,
identifier: Identifier,
fsource: BinaryIO,
name: str = None,
size: int = None,
stream_type: str = None,
):
super().__init__(fsource)
self._identifier = identifier
self._name = name
self._size = size
self._stream_type = stream_type
self._status = STREAM_WAITING_TO_START
self._reason = DEFAULT_REASON
self._transfered = 0
@property
def identifier(self) -> Identifier:
"""
The identity the stream is coming from if it is an incoming request
or to if it is an outgoing request.
"""
return self._identifier
@property
def name(self) -> str:
"""
The name of the stream/file if it has one or None otherwise.
!! Be carefull of injections if you are using this name directly as a filename.
"""
return self._name
@property
def size(self) -> int:
"""
The expected size in bytes of the stream if it is known or None.
"""
return self._size
@property
def transfered(self) -> int:
"""
The currently transfered size.
"""
return self._transfered
@property
def stream_type(self) -> str:
"""
The mimetype of the stream if it is known or None.
"""
return self._stream_type
@property
def status(self) -> str:
"""
The status for this stream.
"""
return self._status
def accept(self) -> None:
"""
Signal that the stream has been accepted.
"""
if self._status != STREAM_WAITING_TO_START:
raise ValueError("Invalid state, the stream is not pending.")
self._status = STREAM_TRANSFER_IN_PROGRESS
def reject(self) -> None:
"""
Signal that the stream has been rejected.
"""
if self._status != STREAM_WAITING_TO_START:
raise ValueError("Invalid state, the stream is not pending.")
self._status = STREAM_REJECTED
def error(self, reason=DEFAULT_REASON) -> None:
"""
An internal plugin error prevented the transfer.
"""
self._status = STREAM_ERROR
self._reason = reason
def success(self) -> None:
"""
The streaming finished normally.
"""
if self._status != STREAM_TRANSFER_IN_PROGRESS:
raise ValueError("Invalid state, the stream is not in progress.")
self._status = STREAM_SUCCESSFULLY_TRANSFERED
def clone(self, new_fsource: BinaryIO) -> "Stream":
"""
Creates a clone and with an alternative stream
"""
return Stream(
self._identifier, new_fsource, self._name, self._size, self._stream_type
)
def ack_data(self, length: int) -> None:
"""Acknowledge data has been transfered."""
self._transfered = length
class Backend(ABC):
"""
Implements the basic Bot logic (logic independent from the backend) and leaves
you to implement the missing parts.
"""
cmd_history = defaultdict(
lambda: deque(maxlen=10)
) # this will be a per user history
MSG_ERROR_OCCURRED = (
"Sorry for your inconvenience. " "An unexpected error occurred."
)
def __init__(self, _):
"""Those arguments will be directly those put in BOT_IDENTITY"""
log.debug("Backend init.")
self._reconnection_count = 0 # Increments with each failed (re)connection
self._reconnection_delay = 1 # Amount of seconds the bot will sleep on the
# # next reconnection attempt
self._reconnection_max_delay = (
600 # Maximum delay between reconnection attempts
)
self._reconnection_multiplier = 1.75 # Delay multiplier
self._reconnection_jitter = (0, 3) # Random jitter added to delay (min, max)
@abstractmethod
def send_message(self, msg: Message) -> None:
"""Should be overridden by backends with a super().send_message() call."""
@abstractmethod
def change_presence(self, status: str = ONLINE, message: str = "") -> None:
"""Signal a presence change for the bot. Should be overridden by backends with a super().send_message() call."""
@abstractmethod
def build_reply(
self,
msg: Message,
text: str = None,
private: bool = False,
threaded: bool = False,
):
"""Should be implemented by the backend"""
@abstractmethod
def callback_presence(self, presence: Presence) -> None:
"""Implemented by errBot."""
pass
@abstractmethod
def callback_room_joined(self, room: Room) -> None:
"""See :class:`~errbot.errBot.ErrBot`"""
pass
@abstractmethod
def callback_room_left(self, room: Room) -> None:
"""See :class:`~errbot.errBot.ErrBot`"""
pass
@abstractmethod
def callback_room_topic(self, room: Room) -> None:
"""See :class:`~errbot.errBot.ErrBot`"""
pass
def serve_forever(self) -> None:
"""
Connect the back-end to the server and serve forever.
Back-ends MAY choose to re-implement this method, in which case
they are responsible for implementing reconnection logic themselves.
Back-ends SHOULD trigger :func:`~connect_callback()` and
:func:`~disconnect_callback()` themselves after connection/disconnection.
"""
while True:
try:
if self.serve_once():
break # Truth-y exit from serve_once means shutdown was requested
except KeyboardInterrupt:
log.info("Interrupt received, shutting down..")
break
except Exception:
log.exception("Exception occurred in serve_once:")
log.info(
"Reconnecting in %d seconds (%d attempted reconnections so far).",
self._reconnection_delay,
self._reconnection_count,
)
try:
self._delay_reconnect()
self._reconnection_count += 1
except KeyboardInterrupt:
log.info("Interrupt received, shutting down..")
break
log.info("Trigger shutdown")
self.shutdown()
def _delay_reconnect(self) -> None:
"""Delay next reconnection attempt until a suitable back-off time has passed"""
time.sleep(self._reconnection_delay)
self._reconnection_delay *= self._reconnection_multiplier
if self._reconnection_delay > self._reconnection_max_delay:
self._reconnection_delay = self._reconnection_max_delay
self._reconnection_delay += random.uniform(*self._reconnection_jitter) # nosec
def reset_reconnection_count(self) -> None:
"""
Reset the reconnection count. Back-ends should call this after
successfully connecting.
"""
self._reconnection_count = 0
self._reconnection_delay = 1
def build_message(self, text: str) -> Message:
"""You might want to override this one depending on your backend"""
return Message(body=text)
# ##### HERE ARE THE SPECIFICS TO IMPLEMENT PER BACKEND
@abstractmethod
def prefix_groupchat_reply(self, message: Message, identifier: Identifier):
"""Patches message with the conventional prefix to ping the specific contact
For example:
@gbin, you forgot the milk !
"""
@abstractmethod
def build_identifier(self, text_representation: str) -> Identifier:
pass
def is_from_self(self, msg: Message) -> bool:
"""
Needs to be overridden to check if the incoming message is from the bot itself.
:param msg: The incoming message.
:return: True if the message is coming from the bot.
"""
# Default implementation (XMPP-like check using an extra config).
# Most of the backends should have a better way to determine this.
return (msg.is_direct and msg.frm == self.bot_identifier) or (
msg.is_group and msg.frm.nick == self.bot_config.CHATROOM_FN
)
def serve_once(self) -> None:
"""
Connect the back-end to the server and serve a connection once
(meaning until disconnected for any reason).
Back-ends MAY choose not to implement this method, IF they implement a custom
:func:`~serve_forever`.
This function SHOULD raise an exception or return a value that evaluates
to False in order to signal something went wrong. A return value that
evaluates to True will signal the bot that serving is done and a shut-down
is requested.
"""
raise NotImplementedError(
"It should be implemented specifically for your backend"
)
def connect(self) -> Any:
"""Connects the bot to server or returns current connection"""
@abstractmethod
def query_room(self, room: str) -> Room:
"""
Query a room for information.
:param room:
The room to query for.
:returns:
An instance of :class:`~Room`.
"""
@abstractmethod
def connect_callback(self) -> None:
pass
@abstractmethod
def disconnect_callback(self) -> None:
pass
@property
@abstractmethod
def mode(self) -> str:
pass
@property
@abstractmethod
def rooms(self) -> Sequence[Room]:
"""
Return a list of rooms the bot is currently in.
:returns:
A list of :class:`~errbot.backends.base.Room` instances.
"""
| 28,814
|
Python
|
.py
| 813
| 27.206642
| 120
| 0.610322
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,182
|
xmpp.py
|
errbotio_errbot/errbot/backends/xmpp.py
|
from __future__ import annotations
import logging
import sys
from datetime import datetime
from functools import lru_cache
from time import sleep
from typing import Callable, List, Optional, Tuple, Union
from errbot.backends.base import (
AWAY,
DND,
OFFLINE,
ONLINE,
Identifier,
Message,
Person,
Presence,
Room,
RoomNotJoinedError,
RoomOccupant,
)
from errbot.core import ErrBot
from errbot.rendering import text, xhtml, xhtmlim
log = logging.getLogger(__name__)
try:
from slixmpp import JID, ClientXMPP
from slixmpp.exceptions import IqError
except ImportError:
log.exception("Could not start the XMPP backend")
log.fatal(
"""
If you intend to use the XMPP backend please install the support for XMPP with:
pip install errbot[XMPP]
"""
)
sys.exit(-1)
# LRU to cache the JID queries.
IDENTIFIERS_LRU = 1024
class XMPPIdentifier(Identifier):
"""
This class is the parent and the basic contract of all the ways the backends
are identifying a person on their system.
"""
def __init__(self, node, domain, resource):
if not node:
raise Exception("An XMPPIdentifier needs to have a node.")
if not domain:
raise Exception("An XMPPIdentifier needs to have a domain.")
self._node = node
self._domain = domain
self._resource = resource
self._email = ""
@property
def node(self) -> str:
return self._node
@property
def domain(self) -> str:
return self._domain
@property
def resource(self) -> str:
return self._resource
@property
def person(self) -> str:
return self._node + "@" + self._domain
@property
def nick(self) -> str:
return self._node
@property
def fullname(self) -> None:
return None # Not supported by default on XMPP.
@property
def email(self):
return self._email
@property
def client(self):
return self._resource
def __str__(self):
answer = self._node + "@" + self._domain # don't call .person: see below
if self._resource:
answer += "/" + self._resource
return answer
def __unicode__(self):
return str(self.__str__())
def __eq__(self, other):
if not isinstance(other, XMPPIdentifier):
log.debug("Weird, you are comparing an XMPPIdentifier to a %s", type(other))
return False
return (
self._domain == other._domain
and self._node == other._node
and self._resource == other._resource
)
class XMPPPerson(XMPPIdentifier, Person):
aclattr = XMPPIdentifier.person
def __eq__(self, other):
if not isinstance(other, XMPPPerson):
log.debug("Weird, you are comparing an XMPPPerson to a %s", type(other))
return False
return self._domain == other._domain and self._node == other._node
class XMPPRoom(XMPPIdentifier, Room):
def __init__(self, room_jid, bot: ErrBot):
self._bot = bot
self.xep0045 = self._bot.conn.client.plugin["xep_0045"]
node, domain, resource = split_identifier(room_jid)
super().__init__(node, domain, resource)
def join(
self, username: Optional[str] = None, password: Optional[str] = None
) -> None:
"""
Join the room.
If the room does not exist yet, this will automatically call
:meth:`create` on it first.
"""
room = str(self)
self.xep0045.join_muc(room, username, password=password)
self._bot.conn.add_event_handler(
f"muc::{room}::got_online", self._bot.user_joined_chat
)
self._bot.conn.add_event_handler(
f"muc::{room}::got_offline", self._bot.user_left_chat
)
self.configure()
self._bot.callback_room_joined(self, self._bot.bot_identifier)
log.info("Joined room %s.", room)
def leave(self, reason: Optional[str] = None) -> None:
"""
Leave the room.
:param reason:
An optional string explaining the reason for leaving the room
"""
if reason is None:
reason = ""
room = str(self)
try:
self.xep0045.leave_muc(
room=room, nick=self.xep0045.ourNicks[room], msg=reason
)
self._bot.conn.del_event_handler(
f"muc::{room}::got_online", self._bot.user_joined_chat
)
self._bot.conn.del_event_handler(
f"muc::{room}::got_offline", self._bot.user_left_chat
)
log.info("Left room %s.", room)
self._bot.callback_room_left(self, self._bot.bot_identifier)
except KeyError:
log.debug("Trying to leave %s while not in this room.", room)
def create(self) -> None:
"""
Not supported on this back-end (Slixmpp doesn't support it).
Will join the room to ensure it exists, instead.
"""
logging.warning(
"XMPP back-end does not support explicit creation, joining room "
"instead to ensure it exists."
)
self.join(username=str(self))
def destroy(self) -> None:
"""
Destroy the room.
Calling this on a non-existing room is a no-op.
"""
self.xep0045.destroy(str(self))
log.info("Destroyed room %s.", self)
@property
def exists(self) -> bool:
"""
Boolean indicating whether this room already exists or not.
:getter:
Returns `True` if the room exists, `False` otherwise.
"""
logging.warning(
"XMPP back-end does not support determining if a room exists. Returning the result of joined instead."
)
return self.joined
@property
def joined(self) -> bool:
"""
Boolean indicating whether this room has already been joined.
:getter:
Returns `True` if the room has been joined, `False` otherwise.
"""
return str(self) in self.xep0045.get_joined_rooms()
@property
def topic(self) -> Optional[str]:
"""
The room topic.
:getter:
Returns the topic (a string) if one is set, `None` if no
topic has been set at all.
:raises:
:class:`~RoomNotJoinedError` if the room has not yet been joined.
"""
if not self.joined:
raise RoomNotJoinedError("Must be in a room in order to see the topic.")
try:
return self._bot._room_topics[str(self)]
except KeyError:
return None
@topic.setter
def topic(self, topic: str) -> None:
"""
Set the room's topic.
:param topic:
The topic to set.
"""
# Not supported by Slixmpp at the moment :(
raise NotImplementedError(
"Setting the topic is not supported on this back-end."
)
@property
def occupants(self) -> List[XMPPRoomOccupant]:
"""
The room's occupants.
:getter:
Returns a list of :class:`~errbot.backends.base.MUCOccupant` instances.
:raises:
:class:`~MUCNotJoinedError` if the room has not yet been joined.
"""
occupants = []
try:
for occupant in self.xep0045.rooms[str(self)].values():
room_node, room_domain, _ = split_identifier(occupant["room"])
nick = occupant["nick"]
occupants.append(XMPPRoomOccupant(room_node, room_domain, nick, self))
except KeyError:
raise RoomNotJoinedError("Must be in a room in order to see occupants.")
return occupants
def invite(self, *args) -> None:
"""
Invite one or more people into the room.
:*args:
One or more JID's to invite into the room.
"""
room = str(self)
for jid in args:
self.xep0045.invite(room, jid)
log.info("Invited %s to %s.", jid, room)
def configure(self) -> None:
"""
Configure the room.
Currently this simply sets the default room configuration as
received by the server. May be extended in the future to set
a custom room configuration instead.
"""
room = str(self)
affiliation = None
while affiliation is None:
sleep(0.5)
affiliation = self.xep0045.get_jid_property(
room=room, nick=self.xep0045.our_nicks[room], jid_property="affiliation"
)
if affiliation == "owner":
log.debug("Configuring room %s: we have owner affiliation.", room)
form = yield from self.xep0045.get_room_config(room)
self.xep0045.configure_room(room, form)
else:
log.debug(
"Not configuring room %s: we don't have owner affiliation (affiliation=%s)",
room,
affiliation,
)
class XMPPRoomOccupant(XMPPPerson, RoomOccupant):
def __init__(self, node, domain, resource, room):
super().__init__(node, domain, resource)
self._room = room
@property
def person(self):
return str(self) # this is the full identifier.
@property
def real_jid(self) -> str:
"""
The JID of the room occupant, they used to login.
Will only work if the errbot is moderator in the MUC or it is not anonymous.
"""
room_jid = self._node + "@" + self._domain
jid = JID(self._room.xep0045.get_jid_property(room_jid, self.resource, "jid"))
return jid.bare
@property
def room(self) -> XMPPRoom:
return self._room
nick = XMPPPerson.resource
class XMPPConnection:
def __init__(
self,
jid,
password,
feature=None,
keepalive=None,
ca_cert=None,
server=None,
use_ipv6=None,
bot=None,
ssl_version=None,
):
if feature is None:
feature = {}
self._bot = bot
self.connected = False
self.server = server
self.client = ClientXMPP(
jid, password, plugin_config={"feature_mechanisms": feature}
)
self.client.register_plugin("xep_0030") # Service Discovery
self.client.register_plugin("xep_0045") # Multi-User Chat
self.client.register_plugin("xep_0199") # XMPP Ping
self.client.register_plugin("xep_0203") # XMPP Delayed messages
self.client.register_plugin("xep_0249") # XMPP direct MUC invites
if keepalive is not None:
self.client.whitespace_keepalive = (
True # Just in case Slixmpp's default changes to False in the future
)
self.client.whitespace_keepalive_interval = keepalive
if use_ipv6 is not None:
self.client.use_ipv6 = use_ipv6
if ssl_version:
self.client.ssl_version = ssl_version
self.client.ca_certs = ca_cert # Used for TLS certificate validation
self.client.add_event_handler("session_start", self.session_start)
def session_start(self, _):
self.client.send_presence()
self.client.get_roster()
def connect(self) -> XMPPConnection:
if not self.connected:
if self.server is not None:
self.client.connect(self.server)
else:
self.client.connect()
self.connected = True
return self
def disconnect(self) -> None:
self.client.disconnect(wait=True)
self.connected = False
def serve_forever(self) -> None:
self.client.process()
def add_event_handler(self, name: str, cb: Callable) -> None:
self.client.add_event_handler(name, cb)
def del_event_handler(self, name: str, cb: Callable) -> None:
self.client.del_event_handler(name, cb)
XMPP_TO_ERR_STATUS = {
"available": ONLINE,
"away": AWAY,
"dnd": DND,
"unavailable": OFFLINE,
}
def split_identifier(txtrep: str) -> Tuple[str, str, str]:
split_jid = txtrep.split("@", 1)
node, domain = "@".join(split_jid[:-1]), split_jid[-1]
if domain.find("/") != -1:
domain, resource = domain.split("/", 1)
else:
resource = None
return node, domain, resource
class XMPPBackend(ErrBot):
room_factory = XMPPRoom
roomoccupant_factory = XMPPRoomOccupant
def __init__(self, config):
super().__init__(config)
identity = config.BOT_IDENTITY
self.jid = identity["username"] # backward compatibility
self.password = identity["password"]
self.server = identity.get("server", None)
self.feature = config.__dict__.get("XMPP_FEATURE_MECHANISMS", {})
self.keepalive = config.__dict__.get("XMPP_KEEPALIVE_INTERVAL", None)
self.ca_cert = config.__dict__.get(
"XMPP_CA_CERT_FILE", "/etc/ssl/certs/ca-certificates.crt"
)
self.xhtmlim = config.__dict__.get("XMPP_XHTML_IM", False)
self.use_ipv6 = config.__dict__.get("XMPP_USE_IPV6", None)
self.ssl_version = config.__dict__.get("XMPP_SSL_VERSION", None)
# generic backend compatibility
self.bot_identifier = self._build_person(self.jid)
self.conn = self.create_connection()
self.conn.add_event_handler("message", self.incoming_message)
self.conn.add_event_handler("session_start", self.connected)
self.conn.add_event_handler("disconnected", self.disconnected)
# presence related handlers
self.conn.add_event_handler("got_online", self.contact_online)
self.conn.add_event_handler("got_offline", self.contact_offline)
self.conn.add_event_handler("changed_status", self.user_changed_status)
# MUC subject events
self.conn.add_event_handler("groupchat_subject", self.chat_topic)
self._room_topics = {}
self.md_xhtml = xhtml()
self.md_text = text()
def create_connection(self) -> XMPPConnection:
return XMPPConnection(
jid=self.jid, # textual and original representation
password=self.password,
feature=self.feature,
keepalive=self.keepalive,
ca_cert=self.ca_cert,
server=self.server,
use_ipv6=self.use_ipv6,
bot=self,
ssl_version=self.ssl_version,
)
def _build_room_occupant(self, txtrep: str) -> XMPPRoomOccupant:
node, domain, resource = split_identifier(txtrep)
return self.roomoccupant_factory(
node, domain, resource, self.query_room(node + "@" + domain)
)
def _build_person(self, txtrep: str) -> XMPPPerson:
return XMPPPerson(*split_identifier(txtrep))
def incoming_message(self, xmppmsg: dict) -> None:
"""Callback for message events"""
if xmppmsg["type"] == "error":
log.warning("Received error message: %s", xmppmsg)
return
msg = Message(xmppmsg["body"])
if "html" in xmppmsg.keys():
msg.html = xmppmsg["html"]
log.debug("incoming_message from: %s", msg.frm)
if xmppmsg["type"] == "groupchat":
msg.frm = self._build_room_occupant(xmppmsg["from"].full)
msg.to = msg.frm.room
else:
msg.frm = self._build_person(xmppmsg["from"].full)
msg.to = self._build_person(xmppmsg["to"].full)
msg.nick = xmppmsg["mucnick"]
now = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
delay = xmppmsg["delay"]._get_attr(
"stamp"
) # this is a bug in sleekxmpp it should be ['from']
msg.delayed = bool(delay and delay != now)
self.callback_message(msg)
def _idd_from_event(self, event) -> Union[XMPPRoomOccupant, XMPPPerson]:
txtrep = event["from"].full
return (
self._build_room_occupant(txtrep)
if "muc" in event
else self._build_person(txtrep)
)
def contact_online(self, event) -> None:
log.debug("contact_online %s.", event)
self.callback_presence(
Presence(identifier=self._idd_from_event(event), status=ONLINE)
)
def contact_offline(self, event) -> None:
log.debug("contact_offline %s.", event)
self.callback_presence(
Presence(identifier=self._idd_from_event(event), status=OFFLINE)
)
def user_joined_chat(self, event) -> None:
log.debug("user_join_chat %s", event)
self.callback_presence(
Presence(identifier=self._idd_from_event(event), status=ONLINE)
)
def user_left_chat(self, event) -> None:
log.debug("user_left_chat %s", event)
self.callback_presence(
Presence(identifier=self._idd_from_event(event), status=OFFLINE)
)
def chat_topic(self, event) -> None:
log.debug("chat_topic %s.", event)
room = event.values["mucroom"]
topic = event.values["subject"]
if topic == "":
topic = None
self._room_topics[room] = topic
room = XMPPRoom(event.values["mucroom"], self)
self.callback_room_topic(room)
def user_changed_status(self, event) -> None:
log.debug("user_changed_status %s.", event)
errstatus = XMPP_TO_ERR_STATUS.get(event["type"], None)
message = event["status"]
if not errstatus:
errstatus = event["type"]
self.callback_presence(
Presence(
identifier=self._idd_from_event(event),
status=errstatus,
message=message,
)
)
def connected(self, data) -> None:
"""Callback for connection events"""
self.connect_callback()
def disconnected(self, data) -> None:
"""Callback for disconnection events"""
self.disconnect_callback()
def send_message(self, msg: Message) -> None:
super().send_message(msg)
log.debug("send_message to %s", msg.to)
# We need to unescape the unicode characters (not the markup incompatible ones)
mhtml = (
xhtmlim.unescape(self.md_xhtml.convert(msg.body)) if self.xhtmlim else None
)
self.conn.client.send_message(
mto=str(msg.to),
mbody=self.md_text.convert(msg.body),
mhtml=mhtml,
mtype="chat" if msg.is_direct else "groupchat",
)
def change_presence(self, status: str = ONLINE, message: str = "") -> None:
log.debug("Change bot status to %s, message %s.", status, message)
self.conn.client.send_presence(pshow=status, pstatus=message)
def serve_forever(self) -> None:
self.conn.connect()
try:
self.conn.serve_forever()
finally:
log.debug("Trigger disconnect callback")
self.disconnect_callback()
log.debug("Trigger shutdown")
self.shutdown()
@lru_cache(IDENTIFIERS_LRU)
def build_identifier(
self, txtrep: str
) -> Union[XMPPRoomOccupant, XMPPRoom, XMPPPerson]:
log.debug("build identifier for %s", txtrep)
try:
xep0030 = self.conn.client.plugin["xep_0030"]
info = xep0030.get_info(jid=txtrep)
disco_info = info["disco_info"]
if disco_info:
for category, typ, _, name in disco_info["identities"]:
if category == "conference":
log.debug("This is a room ! %s", txtrep)
return self.query_room(txtrep)
if (
category == "client"
and "http://jabber.org/protocol/muc"
in info["disco_info"]["features"]
):
log.debug("This is room occupant ! %s", txtrep)
return self._build_room_occupant(txtrep)
except IqError as iq:
log.debug("xep_0030 is probably not implemented on this server. %s.", iq)
log.debug("This is a person ! %s", txtrep)
return self._build_person(txtrep)
def build_reply(
self,
msg: Message,
text: str = None,
private: bool = False,
threaded: bool = False,
) -> Message:
response = self.build_message(text)
response.frm = self.bot_identifier
if msg.is_group and not private:
# stripped returns the full bot@conference.domain.tld/chat_username
# but in case of a groupchat, we should only try to send to the MUC address
# itself (bot@conference.domain.tld)
response.to = XMPPRoom(msg.frm.node + "@" + msg.frm.domain, self)
elif msg.is_direct:
# preserve from in case of a simple chat message.
# it is either a user to user or user_in_chatroom to user case.
# so we need resource.
response.to = msg.frm
elif (
hasattr(msg.to, "person")
and msg.to.person == self.bot_config.BOT_IDENTITY["username"]
):
# This is a direct private message, not initiated through a MUC. Use
# stripped to remove the resource so that the response goes to the
# client with the highest priority
response.to = XMPPPerson(msg.frm.node, msg.frm.domain, None)
else:
# This is a private message that was initiated through a MUC. Don't use
# stripped here to retain the resource, else the XMPP server doesn't
# know which user we're actually responding to.
response.to = msg.frm
return response
@property
def mode(self):
return "xmpp"
def rooms(self) -> List[XMPPRoom]:
"""
Return a list of rooms the bot is currently in.
:returns:
A list of :class:`~errbot.backends.base.XMPPMUCRoom` instances.
"""
xep0045 = self.conn.client.plugin["xep_0045"]
return [XMPPRoom(room, self) for room in xep0045.get_joined_rooms()]
def query_room(self, room) -> XMPPRoom:
"""
Query a room for information.
:param room:
The JID/identifier of the room to query for.
:returns:
An instance of :class:`~XMPPMUCRoom`.
"""
return XMPPRoom(room, self)
def prefix_groupchat_reply(self, message: Message, identifier: Identifier):
super().prefix_groupchat_reply(message, identifier)
message.body = f"@{identifier.nick} {message.body}"
def __hash__(self):
return 0
| 22,837
|
Python
|
.py
| 588
| 29.454082
| 114
| 0.59402
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,183
|
irc.py
|
errbotio_errbot/errbot/backends/irc.py
|
from __future__ import absolute_import
import logging
import re
import struct
import subprocess
import sys
import threading
from typing import Any, BinaryIO, List, Optional, Union
from markdown import Markdown
from markdown.extensions.extra import ExtraExtension
from errbot.backends.base import (
ONLINE,
Identifier,
Message,
Person,
Room,
RoomError,
RoomNotJoinedError,
RoomOccupant,
Stream,
)
from errbot.core import ErrBot
from errbot.rendering.ansiext import NSC, AnsiExtension, CharacterTable, enable_format
from errbot.utils import rate_limited
log = logging.getLogger(__name__)
IRC_CHRS = CharacterTable(
fg_black=NSC("\x0301"),
fg_red=NSC("\x0304"),
fg_green=NSC("\x0303"),
fg_yellow=NSC("\x0308"),
fg_blue=NSC("\x0302"),
fg_magenta=NSC("\x0306"),
fg_cyan=NSC("\x0310"),
fg_white=NSC("\x0300"),
fg_default=NSC("\x03"),
bg_black=NSC("\x03,01"),
bg_red=NSC("\x03,04"),
bg_green=NSC("\x03,03"),
bg_yellow=NSC("\x03,08"),
bg_blue=NSC("\x03,02"),
bg_magenta=NSC("\x03,06"),
bg_cyan=NSC("\x03,10"),
bg_white=NSC("\x03,00"),
bg_default=NSC("\x03,"),
fx_reset=NSC("\x03"),
fx_bold=NSC("\x02"),
fx_italic=NSC("\x1d"),
fx_underline=NSC("\x1f"),
fx_not_italic=NSC("\x0f"),
fx_not_underline=NSC("\x0f"),
fx_normal=NSC("\x0f"),
fixed_width="",
end_fixed_width="",
inline_code="",
end_inline_code="",
)
IRC_NICK_REGEX = r"[a-zA-Z\[\]\\`_\^\{\|\}][a-zA-Z0-9\[\]\\`_\^\{\|\}-]+"
try:
import irc.connection
from irc.bot import SingleServerIRCBot
from irc.client import NickMask, ServerNotConnectedError
except ImportError:
log.fatal(
"""You need the IRC support to use IRC, you can install it with:
pip install errbot[IRC]
"""
)
sys.exit(-1)
def irc_md() -> Markdown:
"""This makes a converter from markdown to mirc color format."""
md = Markdown(output_format="irc", extensions=[ExtraExtension(), AnsiExtension()])
md.stripTopLevelTags = False
return md
class IRCPerson(Person):
def __init__(self, mask):
self._nickmask = NickMask(mask)
self._email = ""
@property
def nick(self) -> str:
return self._nickmask.nick
@property
def user(self) -> str:
return self._nickmask.user
@property
def host(self) -> str:
return self._nickmask.host
# generic compatibility
person = nick
@property
def client(self):
return self._nickmask.userhost
@property
def fullname(self) -> None:
# TODO: this should be possible to get
return None
@property
def email(self) -> str:
return self._email
@property
def aclattr(self):
return IRCBackend.aclpattern.format(
nick=self._nickmask.nick, user=self._nickmask.user, host=self._nickmask.host
)
def __unicode__(self):
return str(self._nickmask)
def __str__(self):
return self.__unicode__()
def __eq__(self, other):
if not isinstance(other, IRCPerson):
log.warning("Weird you are comparing an IRCPerson to a %s.", type(other))
return False
return self.person == other.person
class IRCRoomOccupant(IRCPerson, RoomOccupant):
def __init__(self, mask, room):
super().__init__(mask)
self._room = room
@property
def room(self) -> Room:
return self._room
def __unicode__(self):
return self._nickmask
def __str__(self):
return self.__unicode__()
def __repr__(self):
return f"<{self.__unicode__()} - {super().__repr__()}>"
class IRCRoom(Room):
"""
Represent the specifics of a IRC Room/Channel.
This lifecycle of this object is:
- Created in IRCConnection.on_join
- The joined status change in IRCConnection on_join/on_part
- Deleted/destroyed in IRCConnection.on_disconnect
"""
def __init__(self, room: Room, bot):
self._bot = bot
self.room = room
self.connection = self._bot.conn.connection
self._topic_lock = threading.Lock()
self._topic = None
def __unicode__(self):
return self.room
def __str__(self):
return self.__unicode__()
def __repr__(self):
return f"<{self.__unicode__()} - {super().__repr__()}>"
def cb_set_topic(self, current_topic: str) -> None:
"""
Store the current topic for this room.
This method is called by the IRC backend when a `currenttopic`,
`topic` or `notopic` IRC event is received to store the topic set for this channel.
This function is not meant to be executed by regular plugins.
To get or set
"""
with self._topic_lock:
self._topic = current_topic
def join(self, username: Any = None, password: Optional[str] = None) -> None:
"""
Join the room.
If the room does not exist yet, this will automatically call
:meth:`create` on it first.
"""
if username is not None:
log.debug(
"Ignored username parameter on join(), it is unsupported on this back-end."
)
if password is None:
password = "" # nosec
self.connection.join(self.room, key=password)
self._bot.callback_room_joined(self, self._bot.bot_identifier)
log.info("Joined room %s.", self.room)
def leave(self, reason: Optional[str] = None) -> None:
"""
Leave the room.
:param reason:
An optional string explaining the reason for leaving the room
"""
if reason is None:
reason = ""
self.connection.part(self.room, reason)
self._bot.callback_room_left(self, self._bot.bot_identifier)
log.info(
"Leaving room %s with reason %s.",
self.room,
reason if reason is not None else "",
)
def create(self) -> None:
"""
Not supported on this back-end. Will join the room to ensure it exists, instead.
"""
logging.warning(
"IRC back-end does not support explicit creation, joining room instead to ensure it exists."
)
self.join()
def destroy(self) -> None:
"""
Not supported on IRC, will raise :class:`~errbot.backends.base.RoomError`.
"""
raise RoomError("IRC back-end does not support destroying rooms.")
@property
def exists(self) -> bool:
"""
Boolean indicating whether this room already exists or not.
:getter:
Returns `True` if the room exists, `False` otherwise.
"""
logging.warning(
"IRC back-end does not support determining if a room exists. "
"Returning the result of joined instead."
)
return self.joined
@property
def joined(self) -> bool:
"""
Boolean indicating whether this room has already been joined.
:getter:
Returns `True` if the room has been joined, `False` otherwise.
"""
return self.room in self._bot.conn.channels.keys()
@property
def topic(self) -> Optional[str]:
"""
The room topic.
:getter:
Returns the topic (a string) if one is set, `None` if no
topic has been set at all.
"""
if not self.joined:
raise RoomNotJoinedError("Must join the room to get the topic.")
with self._topic_lock:
return self._topic
@topic.setter
def topic(self, topic: str):
"""
Set the room's topic.
:param topic:
The topic to set.
"""
if not self.joined:
raise RoomNotJoinedError("Must join the room to set the topic.")
self.connection.topic(self.room, topic)
@property
def occupants(self) -> List[IRCRoomOccupant]:
"""
The room's occupants.
:getter:
Returns a list of occupants.
:raises:
:class:`~MUCNotJoinedError` if the room has not yet been joined.
"""
occupants = []
try:
for nick in self._bot.conn.channels[self.room].users():
occupants.append(IRCRoomOccupant(nick, room=self.room))
except KeyError:
raise RoomNotJoinedError("Must be in a room in order to see occupants.")
return occupants
def invite(self, *args) -> None:
"""
Invite one or more people into the room.
:param \*args:
One or more nicks to invite into the room.
"""
for nick in args:
self.connection.invite(nick, self.room)
log.info("Invited %s to %s.", nick, self.room)
def __eq__(self, other):
if not isinstance(other, IRCRoom):
log.warning(
"This is weird you are comparing an IRCRoom to a %s.", type(other)
)
return False
return self.room == other.room
class IRCConnection(SingleServerIRCBot):
def __init__(
self,
bot,
nickname,
server,
port=6667,
ssl=False,
bind_address=None,
ipv6=False,
password=None,
username=None,
nickserv_password=None,
private_rate=1,
channel_rate=1,
reconnect_on_kick=5,
reconnect_on_disconnect=5,
):
self.use_ssl = ssl
self.use_ipv6 = ipv6
self.bind_address = bind_address
self.bot = bot
# manually decorate functions
if private_rate:
self.send_private_message = rate_limited(private_rate)(
self.send_private_message
)
if channel_rate:
self.send_public_message = rate_limited(channel_rate)(
self.send_public_message
)
self._reconnect_on_kick = reconnect_on_kick
self._pending_transfers = {}
self._rooms_lock = threading.Lock()
self._rooms = {}
self._recently_joined_to = set()
self.nickserv_password = nickserv_password
if username is None:
username = nickname
self.transfers = {}
super().__init__(
[(server, port, password)],
nickname,
username,
)
def connect(self, *args, **kwargs) -> None:
# Decode all input to UTF-8, but use a replacement character for
# unrecognized byte sequences
# (as described at https://pypi.python.org/pypi/irc)
self.connection.buffer_class.errors = "replace"
connection_factory_kwargs = {}
if self.use_ssl:
import ssl
connection_factory_kwargs["wrapper"] = ssl.wrap_socket
if self.bind_address is not None:
connection_factory_kwargs["bind_address"] = self.bind_address
if self.use_ipv6:
connection_factory_kwargs["ipv6"] = True
connection_factory = irc.connection.Factory(**connection_factory_kwargs)
self.connection.connect(*args, connect_factory=connection_factory, **kwargs)
def on_welcome(self, _, e) -> None:
log.info("IRC welcome %s", e)
# try to identify with NickServ if there is a NickServ password in the
# config
if self.nickserv_password:
msg = f"identify {self.nickserv_password}"
self.send_private_message("NickServ", msg)
# Must be done in a background thread, otherwise the join room
# from the ChatRoom plugin joining channels from CHATROOM_PRESENCE
# ends up blocking on connect.
t = threading.Thread(target=self.bot.connect_callback)
t.daemon = True
t.start()
def _pubmsg(self, e, notice: bool = False) -> None:
msg = Message(e.arguments[0], extras={"notice": notice})
room_name = e.target
if room_name[0] != "#" and room_name[0] != "$":
raise Exception(f"[{room_name}] is not a room")
room = IRCRoom(room_name, self.bot)
msg.frm = IRCRoomOccupant(e.source, room)
msg.to = room
msg.nick = msg.frm.nick # FIXME find the real nick in the channel
self.bot.callback_message(msg)
possible_mentions = re.findall(IRC_NICK_REGEX, e.arguments[0])
room_users = self.channels[room_name].users()
mentions = filter(lambda x: x in room_users, possible_mentions)
if mentions:
mentions = [self.bot.build_identifier(mention) for mention in mentions]
self.bot.callback_mention(msg, mentions)
def _privmsg(self, e, notice: bool = False) -> None:
msg = Message(e.arguments[0], extras={"notice": notice})
msg.frm = IRCPerson(e.source)
msg.to = IRCPerson(e.target)
self.bot.callback_message(msg)
def on_pubmsg(self, _, e) -> None:
self._pubmsg(e)
def on_privmsg(self, _, e) -> None:
self._privmsg(e)
def on_pubnotice(self, _, e) -> None:
self._pubmsg(e, True)
def on_privnotice(self, _, e) -> None:
self._privmsg(e, True)
def on_kick(self, _, e) -> None:
if not self._reconnect_on_kick:
log.info("RECONNECT_ON_KICK is 0 or None, won't try to reconnect")
return
log.info(
"Got kicked out of %s... reconnect in %d seconds... ",
e.target,
self._reconnect_on_kick,
)
def reconnect_channel(name):
log.info("Reconnecting to %s after having beeing kicked.", name)
self.bot.query_room(name).join()
t = threading.Timer(
self._reconnect_on_kick,
reconnect_channel,
[
e.target,
],
)
t.daemon = True
t.start()
def send_private_message(self, to, line: str) -> None:
try:
self.connection.privmsg(to, line)
except ServerNotConnectedError:
pass # the message will be lost
def send_public_message(self, to, line: str) -> None:
try:
self.connection.privmsg(to, line)
except ServerNotConnectedError:
pass # the message will be lost
def on_disconnect(self, connection, event) -> None:
self._rooms = {}
self.bot.disconnect_callback()
def send_stream_request(
self,
identifier: Identifier,
fsource: BinaryIO,
name: Optional[str] = None,
size: Optional[int] = None,
stream_type: Optional[str] = None,
) -> Stream:
# Creates a new connection
dcc = self.dcc_listen("raw")
msg_parts = map(
str,
(
"SEND",
name,
irc.client.ip_quad_to_numstr(dcc.localaddress),
dcc.localport,
size,
),
)
msg = subprocess.list2cmdline(msg_parts)
self.connection.ctcp("DCC", identifier.nick, msg)
stream = Stream(identifier, fsource, name, size, stream_type)
self.transfers[dcc] = stream
return stream
def on_dcc_connect(self, dcc, event) -> None:
stream = self.transfers.get(dcc, None)
if stream is None:
log.error("DCC connect on a none registered connection")
return
log.debug("Start transfer for %s.", stream.identifier)
stream.accept()
self.send_chunk(stream, dcc)
def on_dcc_disconnect(self, dcc, event):
self.transfers.pop(dcc)
def on_part(
self, connection: irc.client.ServerConnection, event: irc.client.Event
) -> None:
"""
Handler of the part IRC Message/event.
The part message is sent to the client as a confirmation of a
/PART command sent by someone in the room/channel.
If the event.source contains the bot nickname then we need to fire
the :meth:`~errbot.backends.base.Backend.callback_room_left` event on the bot.
:param connection: Is an 'irc.client.ServerConnection' object
:param event: Is an 'irc.client.Event' object
The event.source contains the nickmask of the user that
leave the room
The event.target contains the channel name
"""
leaving_nick = event.source.nick
leaving_room = event.target
if self.bot.bot_identifier.nick == leaving_nick:
with self._rooms_lock:
self.bot.callback_room_left(self._rooms[leaving_room])
log.info("Left room {}.", leaving_room)
def on_endofnames(
self, connection: irc.client.ServerConnection, event: irc.client.Event
) -> None:
"""
Handler of the enfofnames IRC message/event.
The endofnames message is sent to the client when the server finish
to send the list of names of the room ocuppants.
This usually happens when you join to the room.
So in this case, we use this event to determine that our bot is
finally joined to the room.
:param connection: Is an 'irc.client.ServerConnection' object
:param event: Is an 'irc.client.Event' object
the event.arguments[0] contains the channel name
"""
# The event.arguments[0] contains the channel name.
# We filter that to avoid a misfire of the event.
room_name = event.arguments[0]
with self._rooms_lock:
if room_name in self._recently_joined_to:
self._recently_joined_to.remove(room_name)
self.bot.callback_room_joined(self._rooms[room_name])
def on_join(
self, connection: irc.client.ServerConnection, event: irc.client.Event
) -> None:
"""
Handler of the join IRC message/event.
Is in response of a /JOIN client message.
:param connection: Is an 'irc.client.ServerConnection' object
:param event: Is an 'irc.client.Event' object
the event.target contains the channel name
"""
# We can't fire the room_joined event yet,
# because we don't have the occupants info.
# We need to wait to endofnames message.
room_name = event.target
with self._rooms_lock:
if room_name not in self._rooms:
self._rooms[room_name] = IRCRoom(room_name, self.bot)
self._recently_joined_to.add(room_name)
def on_currenttopic(
self, connection: irc.client.ServerConnection, event: irc.client.Event
) -> None:
"""
When you Join a room with a topic set this event fires up to
with the topic information.
If the room that you join don't have a topic set, nothing happens.
Here is NOT the place to fire the :meth:`~errbot.backends.base.Backend.callback_room_topic` event for
that case exist on_topic.
:param connection: Is an 'irc.client.ServerConnection' object
:param event: Is an 'irc.client.Event' object
The event.arguments[0] contains the room name
The event.arguments[1] contains the topic of the room.
"""
room_name, current_topic = event.arguments
with self._rooms_lock:
self._rooms[room_name].cb_set_topic(current_topic)
def on_topic(
self, connection: irc.client.ServerConnection, event: irc.client.Event
) -> None:
"""
On response to the /TOPIC command if the room have a topic.
If the room don't have a topic the event fired is on_notopic
:param connection: Is an 'irc.client.ServerConnection' object
:param event: Is an 'irc.client.Event' object
The event.target contains the room name.
The event.arguments[0] contains the topic name
"""
room_name = event.target
current_topic = event.arguments[0]
with self._rooms_lock:
self._rooms[room_name].cb_set_topic(current_topic)
self.bot.callback_room_topic(self._rooms[room_name])
def on_notopic(
self, connection: irc.client.ServerConnection, event: irc.client.Event
) -> None:
"""
This event fires ip when there is no topic set on a room
:param connection: Is an 'irc.client.ServerConnection' object
:param event: Is an 'irc.client.Event' object
The event.arguments[0] contains the room name
"""
room_name = event.arguments[0]
with self._rooms_lock:
self._rooms[room_name].cb_set_topic(None)
self.bot.callback_room_topic(self._rooms[room_name])
@staticmethod
def send_chunk(stream, dcc):
data = stream.read(4096)
dcc.send_bytes(data)
stream.ack_data(len(data))
def on_dccmsg(self, dcc, event):
stream = self.transfers.get(dcc, None)
if stream is None:
log.error("DCC connect on a none registered connection")
return
acked = struct.unpack("!I", event.arguments[0])[0]
if acked == stream.size:
log.info(
"File %s successfully transfered to %s", stream.name, stream.identifier
)
dcc.disconnect()
self.transfers.pop(dcc)
elif acked == stream.transfered:
log.debug(
"Chunk for file %s successfully transfered to %s (%d/%d).",
stream.name,
stream.identifier,
stream.transfered,
stream.size,
)
self.send_chunk(stream, dcc)
else:
log.debug(
"Partial chunk for file %s successfully transfered to %s (%d/%d), wait for more",
stream.name,
stream.identifier,
stream.transfered,
stream.size,
)
def away(self, message: Optional[str] = "") -> None:
"""
Extend the original implementation to support AWAY.
To set an away message, set message to something.
To cancel an away message, leave message at empty string.
"""
self.connection.send_raw(" ".join(["AWAY", message]).strip())
class IRCBackend(ErrBot):
aclpattern = "{nick}!{user}@{host}"
def __init__(self, config):
if hasattr(config, "IRC_ACL_PATTERN"):
IRCBackend.aclpattern = config.IRC_ACL_PATTERN
identity = config.BOT_IDENTITY
nickname = identity["nickname"]
server = identity["server"]
port = identity.get("port", 6667)
password = identity.get("password", None)
ssl = identity.get("ssl", False)
bind_address = identity.get("bind_address", None)
ipv6 = identity.get("ipv6", False)
username = identity.get("username", None)
nickserv_password = identity.get("nickserv_password", None)
compact = config.COMPACT_OUTPUT if hasattr(config, "COMPACT_OUTPUT") else True
enable_format("irc", IRC_CHRS, borders=not compact)
private_rate = getattr(config, "IRC_PRIVATE_RATE", 1)
channel_rate = getattr(config, "IRC_CHANNEL_RATE", 1)
reconnect_on_kick = getattr(config, "IRC_RECONNECT_ON_KICK", 5)
reconnect_on_disconnect = getattr(config, "IRC_RECONNECT_ON_DISCONNECT", 5)
self.bot_identifier = IRCPerson(nickname + "!" + nickname + "@" + server)
super().__init__(config)
self.conn = IRCConnection(
bot=self,
nickname=nickname,
server=server,
port=port,
ssl=ssl,
bind_address=bind_address,
ipv6=ipv6,
password=password,
username=username,
nickserv_password=nickserv_password,
private_rate=private_rate,
channel_rate=channel_rate,
reconnect_on_kick=reconnect_on_kick,
reconnect_on_disconnect=reconnect_on_disconnect,
)
self.md = irc_md()
def set_message_size_limit(self, limit: int = 510, hard_limit: int = 510) -> None:
"""
IRC message size limit
"""
super().set_message_size_limit(limit, hard_limit)
def send_message(self, msg: Message) -> None:
super().send_message(msg)
if msg.is_direct:
msg_func = self.conn.send_private_message
msg_to = msg.to.person
else:
msg_func = self.conn.send_public_message
msg_to = msg.to.room
body = self.md.convert(msg.body)
for line in body.split("\n"):
msg_func(msg_to, line)
def change_presence(self, status: str = ONLINE, message: str = "") -> None:
if status == ONLINE:
self.conn.away() # cancels the away message
else:
self.conn.away(f"[{status}] {message}")
def send_stream_request(
self,
identifier: Identifier,
fsource: BinaryIO,
name: Optional[str] = None,
size: Optional[int] = None,
stream_type: Optional[str] = None,
) -> Stream:
return self.conn.send_stream_request(
identifier, fsource, name, size, stream_type
)
def build_reply(
self,
msg: Message,
text: Optional[str] = None,
private: bool = False,
threaded: str = False,
) -> Message:
response = self.build_message(text)
if msg.is_group:
if private:
response.frm = self.bot_identifier
response.to = IRCPerson(str(msg.frm))
else:
response.frm = IRCRoomOccupant(str(self.bot_identifier), msg.frm.room)
response.to = msg.frm.room
else:
response.frm = self.bot_identifier
response.to = msg.frm
return response
def serve_forever(self) -> None:
try:
self.conn.start()
except KeyboardInterrupt:
log.info("Interrupt received, shutting down")
finally:
self.conn.disconnect("Shutting down")
log.debug("Trigger disconnect callback")
self.disconnect_callback()
log.debug("Trigger shutdown")
self.shutdown()
def connect(self) -> IRCConnection:
return self.conn
def build_message(self, text: str) -> Message:
text = text.replace(
"", "*"
) # there is a weird chr IRC is sending that we need to filter out
return super().build_message(text)
def build_identifier(
self, txtrep: str
) -> Union[IRCRoom, IRCRoomOccupant, IRCPerson]:
log.debug("Build identifier from %s.", txtrep)
# A textual representation starting with # means that we are talking
# about an IRC channel -- IRCRoom in internal err-speak.
if txtrep.startswith("#"):
return IRCRoom(txtrep, self)
# Occupants are represented as 2 lines, one is the IRC mask and the second is the Room.
if "\n" in txtrep:
m, r = txtrep.split("\n")
return IRCRoomOccupant(m, IRCRoom(r, self))
return IRCPerson(txtrep)
def shutdown(self) -> None:
super().shutdown()
def query_room(self, room: IRCRoom) -> IRCRoom:
"""
Query a room for information.
:param room:
The channel name to query for.
:returns:
An instance of :class:`~IRCMUCRoom`.
"""
with self.conn._rooms_lock:
if room not in self.conn._rooms:
self.conn._rooms[room] = IRCRoom(room, self)
return self.conn._rooms[room]
@property
def mode(self) -> str:
return "irc"
def rooms(self) -> List[IRCRoom]:
"""
Return a list of rooms the bot is currently in.
:returns:
A list of :class:`~IRCMUCRoom` instances.
"""
with self.conn._rooms_lock:
return self.conn._rooms.values()
def prefix_groupchat_reply(self, message: Message, identifier: Identifier):
super().prefix_groupchat_reply(message, identifier)
message.body = f"{identifier.nick}: {message.body}"
| 28,216
|
Python
|
.py
| 740
| 28.966216
| 109
| 0.596152
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,184
|
telegram_messenger.py
|
errbotio_errbot/errbot/backends/telegram_messenger.py
|
import logging
import sys
from typing import Any, BinaryIO, Optional, Union
from errbot.backends.base import (
ONLINE,
Identifier,
Message,
Person,
Room,
RoomError,
RoomOccupant,
Stream,
)
from errbot.core import ErrBot
from errbot.rendering import text
from errbot.rendering.ansiext import TEXT_CHRS, enable_format
log = logging.getLogger(__name__)
UPDATES_OFFSET_KEY = "_telegram_updates_offset"
try:
import telegram
except ImportError:
log.exception("Could not start the Telegram back-end")
log.fatal(
"You need to install the telegram support in order "
"to use the Telegram backend.\n"
"You should be able to install this package using:\n"
"pip install errbot[telegram]"
)
sys.exit(1)
class RoomsNotSupportedError(RoomError):
def __init__(self, message: Optional[str] = None):
if message is None:
message = (
"Room operations are not supported on Telegram. "
"While Telegram itself has groupchat functionality, it does not "
"expose any APIs to bots to get group membership or otherwise "
"interact with groupchats."
)
super().__init__(message)
class TelegramBotFilter:
"""
This is a filter for the logging library that filters the
"No new updates found." log message generated by telegram.bot.
This is an INFO-level log message that gets logged for every
getUpdates() call where there are no new messages, so is way
too verbose.
"""
@staticmethod
def filter(record):
if record.getMessage() == "No new updates found.":
return 0
class TelegramIdentifier(Identifier):
def __init__(self, id):
self._id = str(id)
@property
def id(self) -> str:
return self._id
def __unicode__(self):
return str(self._id)
def __eq__(self, other):
return self._id == other.id
__str__ = __unicode__
aclattr = id
class TelegramPerson(TelegramIdentifier, Person):
def __init__(self, id, first_name=None, last_name=None, username=None):
super().__init__(id)
self._first_name = first_name
self._last_name = last_name
self._username = username
@property
def id(self) -> str:
return self._id
@property
def first_name(self) -> str:
return self._first_name
@property
def last_name(self) -> str:
return self._last_name
@property
def fullname(self) -> str:
fullname = self.first_name
if self.last_name is not None:
fullname += " " + self.last_name
return fullname
@property
def username(self) -> str:
return self._username
@property
def client(self) -> None:
return None
person = id
nick = username
class TelegramRoom(TelegramIdentifier, Room):
def __init__(self, id, title=None):
super().__init__(id)
self._title = title
@property
def id(self) -> str:
return self._id
@property
def title(self):
"""Return the groupchat title (only applies to groupchats)"""
return self._title
def join(self, username: str = None, password: str = None) -> None:
raise RoomsNotSupportedError()
def create(self) -> None:
raise RoomsNotSupportedError()
def leave(self, reason: str = None) -> None:
raise RoomsNotSupportedError()
def destroy(self) -> None:
raise RoomsNotSupportedError()
@property
def joined(self) -> None:
raise RoomsNotSupportedError()
@property
def exists(self) -> None:
raise RoomsNotSupportedError()
@property
def topic(self) -> None:
raise RoomsNotSupportedError()
@property
def occupants(self) -> None:
raise RoomsNotSupportedError()
def invite(self, *args) -> None:
raise RoomsNotSupportedError()
class TelegramMUCOccupant(TelegramPerson, RoomOccupant):
"""
This class represents a person inside a MUC.
"""
def __init__(
self, id, room: TelegramRoom, first_name=None, last_name=None, username=None
):
super().__init__(
id=id, first_name=first_name, last_name=last_name, username=username
)
self._room = room
@property
def room(self) -> TelegramRoom:
return self._room
@property
def username(self) -> str:
return self._username
class TelegramBackend(ErrBot):
def __init__(self, config):
super().__init__(config)
logging.getLogger("telegram.bot").addFilter(TelegramBotFilter())
identity = config.BOT_IDENTITY
self.token = identity.get("token", None)
if not self.token:
log.fatal(
"You need to supply a token for me to use. You can obtain "
"a token by registering your bot with the Bot Father (@BotFather)"
)
sys.exit(1)
self.telegram = None # Will be initialized in serve_once
self.bot_instance = None # Will be set in serve_once
compact = config.COMPACT_OUTPUT if hasattr(config, "COMPACT_OUTPUT") else False
enable_format("text", TEXT_CHRS, borders=not compact)
self.md_converter = text()
def set_message_size_limit(self, limit: int = 1024, hard_limit: int = 1024) -> None:
"""
Telegram message size limit
"""
super().set_message_size_limit(limit, hard_limit)
def serve_once(self) -> None:
log.info("Initializing connection")
try:
self.telegram = telegram.Bot(token=self.token)
me = self.telegram.getMe()
except telegram.TelegramError as e:
log.error("Connection failure: %s", e.message)
return False
self.bot_identifier = TelegramPerson(
id=me.id,
first_name=me.first_name,
last_name=me.last_name,
username=me.username,
)
log.info("Connected")
self.reset_reconnection_count()
self.connect_callback()
try:
offset = self[UPDATES_OFFSET_KEY]
except KeyError:
offset = 0
try:
while True:
log.debug("Getting updates with offset %s", offset)
for update in self.telegram.getUpdates(offset=offset, timeout=60):
offset = update.update_id + 1
self[UPDATES_OFFSET_KEY] = offset
log.debug("Processing update: %s", update)
if not hasattr(update, "message"):
log.warning("Unknown update type (no message present)")
continue
try:
self._handle_message(update.message)
except Exception:
log.exception("An exception occurred while processing update")
log.debug("All updates processed, new offset is %s", offset)
except KeyboardInterrupt:
log.info("Interrupt received, shutting down..")
return True
except Exception:
log.exception("Error reading from Telegram updates stream:")
finally:
log.debug("Triggering disconnect callback")
self.disconnect_callback()
def _handle_message(self, message: Message) -> None:
"""
Handle a received message.
:param message:
A message with a structure as defined at
https://core.telegram.org/bots/api#message
"""
if message.text is None:
log.warning("Unhandled message type (not a text message) ignored")
return
message_instance = self.build_message(message.text)
if message.chat["type"] == "private":
message_instance.frm = TelegramPerson(
id=message.from_user.id,
first_name=message.from_user.first_name,
last_name=message.from_user.last_name,
username=message.from_user.username,
)
message_instance.to = self.bot_identifier
else:
room = TelegramRoom(id=message.chat.id, title=message.chat.title)
message_instance.frm = TelegramMUCOccupant(
id=message.from_user.id,
room=room,
first_name=message.from_user.first_name,
last_name=message.from_user.last_name,
username=message.from_user.username,
)
message_instance.to = room
message_instance.extras["message_id"] = message.message_id
self.callback_message(message_instance)
def send_message(self, msg: Message) -> None:
super().send_message(msg)
body = self.md_converter.convert(msg.body)
try:
self.telegram.sendMessage(msg.to.id, body)
except Exception:
log.exception(
f"An exception occurred while trying to send the following message to {msg.to.id}: {msg.body}"
)
raise
def change_presence(self, status: str = ONLINE, message: str = "") -> None:
# It looks like telegram doesn't supports online presence for privacy reason.
pass
def build_identifier(self, txtrep: str) -> Union[TelegramPerson, TelegramRoom]:
"""
Convert a textual representation into a :class:`~TelegramPerson` or :class:`~TelegramRoom`.
"""
log.debug("building an identifier from %s.", txtrep)
if not self._is_numeric(txtrep):
raise ValueError("Telegram identifiers must be numeric.")
id_ = int(txtrep)
if id_ > 0:
return TelegramPerson(id=id_)
else:
return TelegramRoom(id=id_)
def build_reply(
self,
msg: Message,
text: Optional[str] = None,
private: bool = False,
threaded: bool = False,
) -> Message:
response = self.build_message(text)
response.frm = self.bot_identifier
if private:
response.to = msg.frm
else:
response.to = msg.frm if msg.is_direct else msg.to
return response
@property
def mode(self) -> text:
return "telegram"
def query_room(self, room: TelegramRoom) -> None:
"""
Not supported on Telegram.
:raises: :class:`~RoomsNotSupportedError`
"""
raise RoomsNotSupportedError()
def rooms(self) -> None:
"""
Not supported on Telegram.
:raises: :class:`~RoomsNotSupportedError`
"""
raise RoomsNotSupportedError()
def prefix_groupchat_reply(self, message: Message, identifier: Identifier):
super().prefix_groupchat_reply(message, identifier)
message.body = f"@{identifier.nick}: {message.body}"
def _telegram_special_message(
self, chat_id: Any, content: Any, msg_type: str, **kwargs
) -> telegram.Message:
"""Send special message."""
if msg_type == "document":
msg = self.telegram.sendDocument(
chat_id=chat_id, document=content, **kwargs
)
elif msg_type == "photo":
msg = self.telegram.sendPhoto(chat_id=chat_id, photo=content, **kwargs)
elif msg_type == "audio":
msg = self.telegram.sendAudio(chat_id=chat_id, audio=content, **kwargs)
elif msg_type == "video":
msg = self.telegram.sendVideo(chat_id=chat_id, video=content, **kwargs)
elif msg_type == "sticker":
msg = self.telegram.sendSticker(chat_id=chat_id, sticker=content, **kwargs)
elif msg_type == "location":
msg = self.telegram.sendLocation(
chat_id=chat_id,
latitude=kwargs.pop("latitude", ""),
longitude=kwargs.pop("longitude", ""),
**kwargs,
)
else:
raise ValueError(
f"Expected a valid choice for `msg_type`, got: {msg_type}."
)
return msg
def _telegram_upload_stream(self, stream: Stream, **kwargs) -> None:
"""Perform upload defined in a stream."""
msg = None
try:
stream.accept()
msg = self._telegram_special_message(
chat_id=stream.identifier.id,
content=stream.raw,
msg_type=stream.stream_type,
**kwargs,
)
except Exception:
log.exception(f"Upload of {stream.name} to {stream.identifier} failed.")
else:
if msg is None:
stream.error()
else:
stream.success()
def send_stream_request(
self,
identifier: Union[TelegramPerson, TelegramMUCOccupant],
fsource: Union[str, dict, BinaryIO],
name: Optional[str] = "file",
size: Optional[int] = None,
stream_type: Optional[str] = None,
) -> Union[str, Stream]:
"""Starts a file transfer.
:param identifier: TelegramPerson or TelegramMUCOccupant
Identifier of the Person or Room to send the stream to.
:param fsource: str, dict or binary data
File URL or binary content from a local file.
Optionally a dict with binary content plus metadata can be given.
See `stream_type` for more details.
:param name: str, optional
Name of the file. Not sure if this works always.
:param size: str, optional
Size of the file obtained with os.path.getsize.
This is only used for debug logging purposes.
:param stream_type: str, optional
Type of the stream. Choices: 'document', 'photo', 'audio', 'video', 'sticker', 'location'.
If 'video', a dict is optional as {'content': fsource, 'duration': str}.
If 'voice', a dict is optional as {'content': fsource, 'duration': str}.
If 'audio', a dict is optional as {'content': fsource, 'duration': str, 'performer': str, 'title': str}.
For 'location' a dict is mandatory as {'latitude': str, 'longitude': str}.
For 'venue': TODO # see: https://core.telegram.org/bots/api#sendvenue
:return stream: str or Stream
If `fsource` is str will return str, else return Stream.
"""
def _telegram_metadata(fsource):
if isinstance(fsource, dict):
return fsource.pop("content"), fsource
else:
return fsource, None
def _is_valid_url(url) -> bool:
try:
from urlparse import urlparse
except Exception:
from urllib.parse import urlparse
return bool(urlparse(url).scheme)
content, meta = _telegram_metadata(fsource)
if isinstance(content, str):
if not _is_valid_url(content):
raise ValueError(f"Not valid URL: {content}")
self._telegram_special_message(
chat_id=identifier.id, content=content, msg_type=stream_type, **meta
)
log.debug(
"Requesting upload of %s to %s (size hint: %d, stream type: %s).",
name,
identifier.username,
size,
stream_type,
)
stream = content
else:
stream = Stream(identifier, content, name, size, stream_type)
log.debug(
"Requesting upload of %s to %s (size hint: %d, stream type: %s)",
name,
identifier,
size,
stream_type,
)
self.thread_pool.apply_async(self._telegram_upload_stream, (stream,))
return stream
@staticmethod
def _is_numeric(input_) -> bool:
"""Return true if input is a number"""
try:
int(input_)
return True
except ValueError:
return False
| 16,107
|
Python
|
.py
| 417
| 28.561151
| 116
| 0.588642
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,185
|
__init__.py
|
errbotio_errbot/errbot/rendering/__init__.py
|
# vim: noai:ts=4:sw=4
import re
from markdown import Markdown
from markdown.extensions.extra import ExtraExtension
# Attribute regexp looks for extendend syntax: {: ... }
ATTR_RE = re.compile(r"{:([^}]*)}")
MD_ESCAPE_RE = re.compile(
"|".join(
re.escape(c)
for c in (
"\\",
"`",
"*",
"_",
"{",
"}",
"[",
"]",
"(",
")",
">",
"#",
"+",
"-",
".",
"!",
)
)
)
# Here are few helpers to simplify the conversion from markdown to various
# backend formats.
def ansi():
"""This makes a converter from markdown to ansi (console) format.
It can be called like this:
from errbot.rendering import ansi
md_converter = ansi() # you need to cache the converter
ansi_txt = md_converter.convert(md_txt)
"""
from .ansiext import AnsiExtension
md = Markdown(output_format="ansi", extensions=[ExtraExtension(), AnsiExtension()])
md.stripTopLevelTags = False
return md
def text():
"""This makes a converter from markdown to text (unicode) format.
It can be called like this:
from errbot.rendering import text
md_converter = text() # you need to cache the converter
pure_text = md_converter.convert(md_txt)
"""
from .ansiext import AnsiExtension
md = Markdown(output_format="text", extensions=[ExtraExtension(), AnsiExtension()])
md.stripTopLevelTags = False
return md
def imtext():
"""This makes a converter from markdown to imtext (unicode) format.
imtest is the format like gtalk, slack or skype with simple _ or * markup.
It can be called like this:
from errbot.rendering import imtext
md_converter = imtext() # you need to cache the converter
im_text = md_converter.convert(md_txt)
"""
from .ansiext import AnsiExtension
md = Markdown(
output_format="imtext", extensions=[ExtraExtension(), AnsiExtension()]
)
md.stripTopLevelTags = False
return md
class Mde2mdConverter:
def convert(self, mde):
while True:
m = ATTR_RE.search(mde)
if m is None:
break
left, right = m.span()
mde = mde[:left] + mde[right:]
return mde
def md():
"""This makes a converter from markdown-extra to markdown, stripping the attributes from extra."""
return Mde2mdConverter()
def xhtml():
"""This makes a converter from markdown to xhtml format.
It can be called like this:
from errbot.rendering import xhtml
md_converter = xhtml() # you need to cache the converter
html = md_converter.convert(md_txt)
"""
return Markdown(output_format="xhtml", extensions=[ExtraExtension()])
def md_escape(txt):
"""Call this if you want to be sure your text won't be interpreted as markdown
:param txt: bare text to escape.
"""
return MD_ESCAPE_RE.sub(lambda match: "\\" + match.group(0), txt)
| 3,059
|
Python
|
.py
| 92
| 26.586957
| 102
| 0.620326
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,186
|
ansiext.py
|
errbotio_errbot/errbot/rendering/ansiext.py
|
import io
import logging
from collections import namedtuple
from functools import partial
from html import unescape
from itertools import chain
from ansi.colour import bg, fg, fx
from markdown import Markdown
from markdown.extensions import Extension
from markdown.extensions.fenced_code import FencedBlockPreprocessor
from markdown.inlinepatterns import SubstituteTagPattern
from markdown.postprocessors import Postprocessor
log = logging.getLogger(__name__)
# chr that should not count as a space
class NSC:
def __init__(self, s):
self.s = s
def __str__(self):
return self.s
# The translation table for the special characters.
CharacterTable = namedtuple(
"CharacterTable",
[
"fg_black",
"fg_red",
"fg_green",
"fg_yellow",
"fg_blue",
"fg_magenta",
"fg_cyan",
"fg_white",
"fg_default",
"bg_black",
"bg_red",
"bg_green",
"bg_yellow",
"bg_blue",
"bg_magenta",
"bg_cyan",
"bg_white",
"bg_default",
"fx_reset",
"fx_bold",
"fx_italic",
"fx_underline",
"fx_not_italic",
"fx_not_underline",
"fx_normal",
"fixed_width",
"end_fixed_width",
"inline_code",
"end_inline_code",
],
)
ANSI_CHRS = CharacterTable(
fg_black=fg.black,
fg_red=fg.red,
fg_green=fg.green,
fg_yellow=fg.yellow,
fg_blue=fg.blue,
fg_magenta=fg.magenta,
fg_cyan=fg.cyan,
fg_white=fg.white,
fg_default=fg.default,
bg_black=bg.black,
bg_red=bg.red,
bg_green=bg.green,
bg_yellow=bg.yellow,
bg_blue=bg.blue,
bg_magenta=bg.magenta,
bg_cyan=bg.cyan,
bg_white=bg.white,
bg_default=bg.default,
fx_reset=fx.reset,
fx_bold=fx.bold,
fx_italic=fx.italic,
fx_underline=fx.underline,
fx_not_italic=fx.not_italic,
fx_not_underline=fx.not_underline,
fx_normal=fx.normal,
fixed_width="",
end_fixed_width="",
inline_code="",
end_inline_code="",
)
# Pure Text doesn't have any graphical chrs.
TEXT_CHRS = CharacterTable(
fg_black="",
fg_red="",
fg_green="",
fg_yellow="",
fg_blue="",
fg_magenta="",
fg_cyan="",
fg_white="",
fg_default="",
bg_black="",
bg_red="",
bg_green="",
bg_yellow="",
bg_blue="",
bg_magenta="",
bg_cyan="",
bg_white="",
bg_default="",
fx_reset="",
fx_bold="",
fx_italic="",
fx_underline="",
fx_not_italic="",
fx_not_underline="",
fx_normal="",
fixed_width="",
end_fixed_width="",
inline_code="",
end_inline_code="",
)
# IMText have some formatting available
IMTEXT_CHRS = CharacterTable(
fg_black="",
fg_red="",
fg_green="",
fg_yellow="",
fg_blue="",
fg_magenta="",
fg_cyan="",
fg_white="",
fg_default="",
bg_black="",
bg_red="",
bg_green="",
bg_yellow="",
bg_blue="",
bg_magenta="",
bg_cyan="",
bg_white="",
bg_default="",
fx_reset="",
fx_bold=NSC("*"),
fx_italic="",
fx_underline=NSC("_"),
fx_not_italic="",
fx_not_underline=NSC("_"),
fx_normal=NSC("*"),
fixed_width="```\n",
end_fixed_width="```\n",
inline_code="`",
end_inline_code="`",
)
NEXT_ROW = "&NEXT_ROW;"
class Table(object):
def __init__(self, chr_table):
self.headers = []
self.rows = []
self.in_headers = False
self.ct = chr_table
def next_row(self):
if self.in_headers:
self.headers.append([]) # is that exists ?
else:
self.rows.append([])
def add_col(self):
if not self.rows:
self.rows = [[]]
else:
self.rows[-1].append(("", 0))
def add_header(self):
if not self.headers:
self.headers = [[]]
else:
self.headers[-1].append(("", 0))
def begin_headers(self):
self.in_headers = True
def end_headers(self):
self.in_headers = False
def write(self, text):
cells = self.headers if self.in_headers else self.rows
text_cell, count = cells[-1][-1]
if isinstance(text, str):
text_cell += text
count += len(text)
else:
text_cell += str(text) # This is a non space chr
cells[-1][-1] = text_cell, count
def __str__(self):
nbcols = max(len(row) for row in chain(self.headers, self.rows))
maxes = [
0,
] * nbcols
for row in chain(self.headers, self.rows):
for i, el in enumerate(row):
txt, length = el
# Account for multiline cells
cnt = str(txt).count(NEXT_ROW)
if cnt > 0:
length -= cnt * len(NEXT_ROW)
if maxes[i] < length:
maxes[i] = length
# add up margins
maxes = [m + 2 for m in maxes]
output = io.StringIO()
if self.headers:
output.write("┏" + "┳".join("━" * m for m in maxes) + "┓")
output.write("\n")
first = True
for row in self.headers:
if not first:
output.write("┣" + "╋".join("━" * m for m in maxes) + "┫")
output.write("\n")
first = False
for i, header in enumerate(row):
text, ln = header
output.write("┃ " + text + " " * (maxes[i] - 2 - ln) + " ")
output.write("┃")
output.write("\n")
output.write("┡" + "╇".join("━" * m for m in maxes) + "┩")
output.write("\n")
else:
output.write("┌" + "┬".join("─" * m for m in maxes) + "┐")
output.write("\n")
first = True
for row in self.rows:
max_row_height = 1
for i, item in enumerate(row):
text, _ = item
row_height = str(text).count(NEXT_ROW) + 1
if row_height > max_row_height:
max_row_height = row_height
if not first:
output.write("├" + "┼".join("─" * m for m in maxes) + "┤")
output.write("\n")
first = False
for j in range(max_row_height):
for i, item in enumerate(row):
text, ln = item
multi = text.split(NEXT_ROW)
if len(multi) > j:
text = multi[j]
ln = len(text)
else:
ln = 1
text = " "
output.write("│ " + text + " " * (maxes[i] - 2 - ln) + " ")
output.write("│")
output.write("\n")
output.write("└" + "┴".join("─" * m for m in maxes) + "┘")
output.write("\n")
return (
str(self.ct.fixed_width) + output.getvalue() + str(self.ct.end_fixed_width)
)
class BorderlessTable:
def __init__(self, chr_table):
self.headers = []
self.rows = []
self.in_headers = False
self.ct = chr_table
def next_row(self):
if self.in_headers:
self.headers.append([]) # is that exists ?
else:
self.rows.append([])
def add_col(self):
if not self.rows:
self.rows = [[]]
else:
self.rows[-1].append(("", 0))
def add_header(self):
if not self.headers:
self.headers = [[]]
else:
self.headers[-1].append(("", 0))
def begin_headers(self):
self.in_headers = True
def end_headers(self):
self.in_headers = False
def write(self, text):
cells = self.headers if self.in_headers else self.rows
text_cell, count = cells[-1][-1]
if isinstance(text, str):
text_cell += text
count += len(text)
else:
text_cell += str(text) # This is a non space chr
cells[-1][-1] = text_cell, count
def __str__(self):
nbcols = max(len(row) for row in chain(self.headers, self.rows))
maxes = [
0,
] * nbcols
for row in chain(self.headers, self.rows):
for i, el in enumerate(row):
txt, length = el
# Account for multiline cells
cnt = str(txt).count(NEXT_ROW)
if cnt > 0:
length -= cnt * len(NEXT_ROW)
if maxes[i] < length:
maxes[i] = length
# add up margins
maxes = [m + 2 for m in maxes]
output = io.StringIO()
if self.headers:
for row in self.headers:
for i, header in enumerate(row):
text, ln = header
output.write(text + " " * (maxes[i] - 2 - ln) + " ")
output.write("\n")
for row in self.rows:
max_row_height = 1
for i, item in enumerate(row):
text, _ = item
row_height = str(text).count(NEXT_ROW) + 1
if row_height > max_row_height:
max_row_height = row_height
for j in range(max_row_height):
for i, item in enumerate(row):
text, ln = item
multi = text.split(NEXT_ROW)
if len(multi) > j:
text = multi[j]
ln = len(text)
else:
ln = 1
text = " "
output.write(text + " " * (maxes[i] - 2 - ln) + " ")
output.write("\n")
return (
str(self.ct.fixed_width) + output.getvalue() + str(self.ct.end_fixed_width)
)
def recurse(write, chr_table, element, table=None, borders=True):
post_element = []
if element.text:
text = element.text
else:
text = ""
items = element.items()
for k, v in items:
if k == "color":
color_attr = getattr(chr_table, "fg_" + v, None)
if color_attr is None:
log.warning("there is no '%s' color in ansi.", v)
continue
write(color_attr)
post_element.append(chr_table.fg_default)
elif k == "bgcolor":
color_attr = getattr(chr_table, "bg_" + v, None)
if color_attr is None:
log.warning("there is no '%s' bgcolor in ansi", v)
continue
write(color_attr)
post_element.append(chr_table.bg_default)
if element.tag == "img":
text = dict(items)["src"]
elif element.tag == "strong":
write(chr_table.fx_bold)
post_element.append(chr_table.fx_normal)
elif element.tag == "code":
write(chr_table.inline_code)
post_element.append(chr_table.end_inline_code)
elif element.tag == "em":
write(chr_table.fx_underline)
post_element.append(chr_table.fx_not_underline)
elif element.tag == "p":
write(" ")
post_element.append("\n")
elif element.tag == "br" and table: # Treat <br/> differently in a table.
write(NEXT_ROW)
elif element.tag == "a":
post_element.append(" (" + element.get("href") + ")")
elif element.tag == "li":
write("• ")
post_element.append("\n")
elif element.tag == "hr":
write("─" * 80)
write("\n")
elif element.tag == "ul": # ignore the text part
text = None
elif element.tag == "h1":
write(chr_table.fx_bold)
text = text.upper()
post_element.append(chr_table.fx_normal)
post_element.append("\n\n")
elif element.tag == "h2":
write("\n")
write(" ")
write(chr_table.fx_bold)
post_element.append(chr_table.fx_normal)
post_element.append("\n\n")
elif element.tag == "h3":
write("\n")
write(" ")
write(chr_table.fx_underline)
post_element.append(chr_table.fx_not_underline)
post_element.append("\n\n")
elif element.tag in ("h4", "h5", "h6"):
write("\n")
write(" ")
post_element.append("\n")
elif element.tag == "table":
table = Table(chr_table) if borders else BorderlessTable(chr_table)
orig_write = write
write = table.write
text = None
elif element.tag == "tbody":
text = None
elif element.tag == "thead":
table.begin_headers()
text = None
elif element.tag == "tr":
table.next_row()
text = None
elif element.tag == "td":
table.add_col()
elif element.tag == "th":
table.add_header()
if text:
write(text)
for e in element:
recurse(write, chr_table, e, table, borders)
if element.tag == "table":
write = orig_write
write(str(table))
if element.tag == "thead":
table.end_headers()
for restore in post_element:
write(restore)
if element.tail:
tail = element.tail.rstrip("\n")
if tail:
write(tail)
def translate(element, chr_table=ANSI_CHRS, borders=True):
f = io.StringIO()
def write(ansi_obj):
return f.write(str(ansi_obj))
recurse(write, chr_table, element, borders=borders)
result = f.getvalue().rstrip("\n") # remove the useless final \n
return result + str(chr_table.fx_reset)
# patch us in
def enable_format(name, chr_table, borders=True):
Markdown.output_formats[name] = partial(
translate, chr_table=chr_table, borders=borders
)
for n, ct in (("ansi", ANSI_CHRS), ("text", TEXT_CHRS), ("imtext", IMTEXT_CHRS)):
enable_format(n, ct)
class AnsiPostprocessor(Postprocessor):
"""Markdown generates html entities, this reputs them back to their unicode equivalent"""
def run(self, text):
return unescape(text)
# This is an adapted FencedBlockPreprocessor that doesn't insert <code><pre>
class AnsiPreprocessor(FencedBlockPreprocessor):
def run(self, lines):
"""Match and store Fenced Code Blocks in the HtmlStash."""
text = "\n".join(lines)
while 1:
m = self.FENCED_BLOCK_RE.search(text)
if m:
code = self._escape(m.group("code"))
placeholder = self.md.htmlStash.store(code)
text = f"{text[:m.start()]}\n{placeholder}\n{text[m.end():]}"
else:
break
return text.split("\n")
def _escape(self, txt):
"""basic html escaping"""
txt = txt.replace("&", "&")
txt = txt.replace("<", "<")
txt = txt.replace(">", ">")
txt = txt.replace('"', """)
return txt
class AnsiExtension(Extension):
"""(kinda hackish) This is just a private extension to postprocess the html text to ansi text"""
def extendMarkdown(self, md):
md.registerExtension(self)
md.postprocessors.register(AnsiPostprocessor(), "unescape_html", 15)
md.preprocessors.register(AnsiPreprocessor(md, {}), "ansi_fenced_codeblock", 20)
md.inlinePatterns.register(SubstituteTagPattern(r"<br/>", "br"), "br", 95)
md.preprocessors.deregister("fenced_code_block") # remove the old fenced block
md.treeprocessors.deregister(
"prettify"
) # remove prettify treeprocessor since it adds extra new lines
| 15,663
|
Python
|
.py
| 480
| 23.383333
| 100
| 0.525697
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,187
|
xhtmlim.py
|
errbotio_errbot/errbot/rendering/xhtmlim.py
|
import re
from html.entities import entitydefs
# Helpers for xhtml-im
SAFE_ENTITIES = {
e: entitydefs[e] for e in entitydefs if e not in ("amp", "quot", "apos", "gt", "lt")
}
_invalid_codepoints = {
# 0x0001 to 0x0008
0x1,
0x2,
0x3,
0x4,
0x5,
0x6,
0x7,
0x8,
# 0x000E to 0x001F
0xE,
0xF,
0x10,
0x11,
0x12,
0x13,
0x14,
0x15,
0x16,
0x17,
0x18,
0x19,
0x1A,
0x1B,
0x1C,
0x1D,
0x1E,
0x1F,
# 0x007F to 0x009F
0x7F,
0x80,
0x81,
0x82,
0x83,
0x84,
0x85,
0x86,
0x87,
0x88,
0x89,
0x8A,
0x8B,
0x8C,
0x8D,
0x8E,
0x8F,
0x90,
0x91,
0x92,
0x93,
0x94,
0x95,
0x96,
0x97,
0x98,
0x99,
0x9A,
0x9B,
0x9C,
0x9D,
0x9E,
0x9F,
# 0xFDD0 to 0xFDEF
0xFDD0,
0xFDD1,
0xFDD2,
0xFDD3,
0xFDD4,
0xFDD5,
0xFDD6,
0xFDD7,
0xFDD8,
0xFDD9,
0xFDDA,
0xFDDB,
0xFDDC,
0xFDDD,
0xFDDE,
0xFDDF,
0xFDE0,
0xFDE1,
0xFDE2,
0xFDE3,
0xFDE4,
0xFDE5,
0xFDE6,
0xFDE7,
0xFDE8,
0xFDE9,
0xFDEA,
0xFDEB,
0xFDEC,
0xFDED,
0xFDEE,
0xFDEF,
# others
0xB,
0xFFFE,
0xFFFF,
0x1FFFE,
0x1FFFF,
0x2FFFE,
0x2FFFF,
0x3FFFE,
0x3FFFF,
0x4FFFE,
0x4FFFF,
0x5FFFE,
0x5FFFF,
0x6FFFE,
0x6FFFF,
0x7FFFE,
0x7FFFF,
0x8FFFE,
0x8FFFF,
0x9FFFE,
0x9FFFF,
0xAFFFE,
0xAFFFF,
0xBFFFE,
0xBFFFF,
0xCFFFE,
0xCFFFF,
0xDFFFE,
0xDFFFF,
0xEFFFE,
0xEFFFF,
0xFFFFE,
0xFFFFF,
0x10FFFE,
0x10FFFF,
}
_invalid_charrefs = {
0x00: "\ufffd", # REPLACEMENT CHARACTER
0x0D: "\r", # CARRIAGE RETURN
0x80: "\u20ac", # EURO SIGN
0x81: "\x81", # <control>
0x82: "\u201a", # SINGLE LOW-9 QUOTATION MARK
0x83: "\u0192", # LATIN SMALL LETTER F WITH HOOK
0x84: "\u201e", # DOUBLE LOW-9 QUOTATION MARK
0x85: "\u2026", # HORIZONTAL ELLIPSIS
0x86: "\u2020", # DAGGER
0x87: "\u2021", # DOUBLE DAGGER
0x88: "\u02c6", # MODIFIER LETTER CIRCUMFLEX ACCENT
0x89: "\u2030", # PER MILLE SIGN
0x8A: "\u0160", # LATIN CAPITAL LETTER S WITH CARON
0x8B: "\u2039", # SINGLE LEFT-POINTING ANGLE QUOTATION MARK
0x8C: "\u0152", # LATIN CAPITAL LIGATURE OE
0x8D: "\x8d", # <control>
0x8E: "\u017d", # LATIN CAPITAL LETTER Z WITH CARON
0x8F: "\x8f", # <control>
0x90: "\x90", # <control>
0x91: "\u2018", # LEFT SINGLE QUOTATION MARK
0x92: "\u2019", # RIGHT SINGLE QUOTATION MARK
0x93: "\u201c", # LEFT DOUBLE QUOTATION MARK
0x94: "\u201d", # RIGHT DOUBLE QUOTATION MARK
0x95: "\u2022", # BULLET
0x96: "\u2013", # EN DASH
0x97: "\u2014", # EM DASH
0x98: "\u02dc", # SMALL TILDE
0x99: "\u2122", # TRADE MARK SIGN
0x9A: "\u0161", # LATIN SMALL LETTER S WITH CARON
0x9B: "\u203a", # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
0x9C: "\u0153", # LATIN SMALL LIGATURE OE
0x9D: "\x9d", # <control>
0x9E: "\u017e", # LATIN SMALL LETTER Z WITH CARON
0x9F: "\u0178", # LATIN CAPITAL LETTER Y WITH DIAERESIS
}
def _replace_charref(s):
s = s.group(1)
if s[0] == "#":
# numeric charref
if s[1] in "xX":
num = int(s[2:].rstrip(";"), 16)
else:
num = int(s[1:].rstrip(";"))
if num in _invalid_charrefs:
return _invalid_charrefs[num]
if 0xD800 <= num <= 0xDFFF or num > 0x10FFFF:
return "\ufffd"
if num in _invalid_codepoints:
return ""
return chr(num)
else:
# named charref
if s in SAFE_ENTITIES:
return SAFE_ENTITIES[s]
# find the longest matching name (as defined by the standard)
for x in range(len(s) - 1, 1, -1):
if s[:x] in SAFE_ENTITIES:
return SAFE_ENTITIES[s[:x]] + s[x:]
else:
return "&" + s
_charref = re.compile(
r"&(#[0-9]+;?" r"|#[xX][0-9a-fA-F]+;?" r"|[^\t\n\f <&#;]{1,32};?)"
)
def unescape(s):
if "&" not in s:
return s
return _charref.sub(_replace_charref, s)
| 4,271
|
Python
|
.py
| 207
| 15.217391
| 88
| 0.556981
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,188
|
notest_dump_last.py
|
cve-search_cve-search/test/unit/notest_dump_last.py
|
import pytest
from test.runners.cli_test_runner import CLITestRunner
@pytest.fixture
def runner():
return CLITestRunner()
def test_dump_last_atom(runner):
result = runner.runcommand("bin/dump_last.py -f atom -l 2")
test_results = result.stdout.replace("\n", "")
assert result.returncode == 0
assert test_results[39:81] == '<feed xmlns="http://www.w3.org/2005/Atom">'
assert test_results[99:109] == "Last 2 CVE"
def test_dump_last_rss1(runner):
result = runner.runcommand("bin/dump_last.py -f rss1 -l 2")
assert result.returncode == 0
def test_dump_last_rss2(runner):
result = runner.runcommand("bin/dump_last.py -f rss2 -l 2")
assert result.returncode == 0
assert (
result.stdout.replace("\n", "")[0:58]
== '<?xml version="1.0" encoding="UTF-8" ?><rss version="2.0">'
)
def test_dump_last_html(runner):
result = runner.runcommand("bin/dump_last.py -f html -l 2")
assert result.returncode == 0
assert result.stdout[:6] == "<html>"
def test_dump_last_with_capec_and_cveranking(runner):
result = runner.runcommand("bin/dump_last.py -f atom -c -r -l 2")
assert result.returncode == 0
| 1,183
|
Python
|
.py
| 28
| 37.571429
| 78
| 0.676937
|
cve-search/cve-search
| 2,271
| 587
| 2
|
AGPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,189
|
test_db_dump.py
|
cve-search_cve-search/test/unit/test_db_dump.py
|
import pytest
from test.runners.cli_test_runner import CLITestRunner
@pytest.fixture
def runner():
return CLITestRunner()
def test_db_dump(runner):
result = runner.runcommand("bin/db_dump.py -l 1 -r -v -c")
assert result.returncode == 0
| 255
|
Python
|
.py
| 8
| 28.625
| 62
| 0.746888
|
cve-search/cve-search
| 2,271
| 587
| 2
|
AGPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,190
|
notest_cve_doc.py
|
cve-search_cve-search/test/unit/notest_cve_doc.py
|
import pytest
from test.runners.cli_test_runner import CLITestRunner
@pytest.fixture
def runner():
return CLITestRunner()
def test_cve_doc(runner):
result = runner.runcommand("bin/cve_doc.py")
test_results = result.stdout.replace("\n", "")
assert result.returncode == 0
assert test_results[105:118] == "CVE-2015-0001"
| 345
|
Python
|
.py
| 10
| 30.8
| 54
| 0.731707
|
cve-search/cve-search
| 2,271
| 587
| 2
|
AGPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,191
|
test_search.py
|
cve-search_cve-search/test/unit/test_search.py
|
import json
import pytest
from test.runners.cli_test_runner import CLITestRunner
@pytest.fixture
def runner():
return CLITestRunner()
def test_search(runner):
result = runner.runcommand("bin/search.py -p cisco:ios:12.4")
assert result.returncode == 0
assert result.stdout[:20] == "CVE\t: CVE-2017-12231"
def test_search_lax(runner):
result = runner.runcommand("bin/search.py -p cisco:ios:12.4 --lax")
assert result.returncode == 0
assert result.stdout[:20] == "CVE\t: CVE-2017-12231"
def test_search_lax_alphanumeric_version(runner):
result = runner.runcommand("bin/search.py -p juniper:junos:15.1x53 --lax")
assert result.returncode == 0
assert result.stdout.startswith(
"Notice: Target version 15.1x53 simplified as 15.1.0.53 "
)
assert result.stdout.splitlines()[2] == "CVE\t: CVE-2018-0004"
def test_search_lax_complex_version_simplification(runner):
result = runner.runcommand('bin/search.py -p "cisco:ios:15.6\(2\)sp2a" --lax')
assert result.returncode == 0
assert result.stdout.splitlines()[0].find(" simplified as 15.6.0.2.0.2.0 ") > 0
def test_search_lax_wildcard_version(runner):
result = runner.runcommand("bin/search.py -p juniper:junos:* --lax")
assert result.returncode == 0
# A '0' is a fine simplification for a wildcard as zero is below any version.
assert result.stdout.startswith("Notice: Target version * simplified as 0 ")
assert result.stdout.splitlines()[2] == "CVE\t: CVE-2018-0004"
def test_search_lax_missing_version(runner):
result = runner.runcommand("bin/search.py -p juniper:junos --lax")
assert result.returncode == 1
def test_search_if_vuln(runner):
result = runner.runcommand("bin/search.py -p cisco:ios:12.4 --only-if-vulnerable")
assert result.returncode == 0
assert result.stdout[:20] == "CVE\t: CVE-2017-12231"
def test_search_json(runner):
result = runner.runcommand(
"bin/search.py -p cpe:2.3:o:microsoft:windows_7:*:sp1:*:*:*:*:*:* -o json"
)
assert result.returncode == 0
res = json.loads(result.stdout)
assert res["id"] == "CVE-2017-0123"
def test_search_html(runner):
result = runner.runcommand(
"bin/search.py -p cpe:2.3:o:microsoft:windows_7:*:sp1:*:*:*:*:*:* -o html"
)
assert result.returncode == 0
assert result.stdout[:6] == "<html>"
def test_search_xml(runner):
result = runner.runcommand(
"bin/search.py -p cpe:2.3:o:microsoft:windows_7:*:sp1:*:*:*:*:*:* -o xml"
)
assert result.returncode == 0
assert result.stdout[0:39] == '<?xml version="1.0" encoding="UTF-8" ?>'
def test_search_cveid(runner):
result = runner.runcommand(
"bin/search.py -p cpe:2.3:o:microsoft:windows_7:*:sp1:*:*:*:*:*:* -o cveid"
)
assert result.returncode == 0
assert result.stdout == "CVE-2017-0123\n"
def test_search_cveid_desc(runner):
result = runner.runcommand(
"bin/search.py -p cpe:2.3:o:microsoft:windows_7:*:sp1:*:*:*:*:*:* -o csv -l"
)
assert result.returncode == 0
assert (
result.stdout[:60]
== "CVE-2017-0123|2017-03-17 00:59:00|4.3|Uniscribe in Microsoft"
)
def test_search_nra(runner):
result = runner.runcommand("bin/search.py -p openstack:keystone -n -r -a")
assert result.returncode == 0
assert result.stdout[:19] == "CVE\t: CVE-2013-0270"
def test_search_vendor(runner):
result = runner.runcommand(
"bin/search.py -p microsoft:windows_7 --strict_vendor_product"
)
assert result.returncode == 0
assert result.stdout[:19] == "CVE\t: CVE-2017-0123"
def test_search_summary(runner):
result = runner.runcommand("bin/search.py -s flaw -i 1")
assert result.returncode == 0
def test_search_ti(runner):
result = runner.runcommand("bin/search.py -p microsoft:windows_7 -t 30 -i 1")
assert result.returncode == 0
# def test_search_cve(runner):
# result = runner.runcommand("bin/search.py -c CVE-2010-3333")
#
# assert result.returncode == 0
# assert result.stdout[:19] == "CVE\t: CVE-2010-3333"
| 4,098
|
Python
|
.py
| 93
| 39.204301
| 86
| 0.676456
|
cve-search/cve-search
| 2,271
| 587
| 2
|
AGPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,192
|
test_search_cpe.py
|
cve-search_cve-search/test/unit/test_search_cpe.py
|
import pytest
from test.runners.cli_test_runner import CLITestRunner
@pytest.fixture
def runner():
return CLITestRunner()
def test_search_cpe(runner):
result = runner.runcommand("bin/search_cpe.py -s wordpress")
resultlist = result.stdout.split("\n")
assert result.returncode == 0
# check if wordpress is matched in returned results; first, somewhere middle and somewhere last
first_val = resultlist[0][41:].lower()
middle_val = resultlist[int(len(resultlist) / 2)][41:].lower()
last_val = resultlist[-1][41:].lower()
if last_val == "":
last_val = resultlist[-2][41:].lower()
assert "wordpress" in first_val
assert "wordpress" in middle_val
assert "wordpress" in last_val
def test_search_cpe_json(runner):
result = runner.runcommand("bin/search_cpe.py -s wordpress -o json")
assert result.returncode == 0
def test_search_cpe_compact(runner):
result = runner.runcommand("bin/search_cpe.py -s wordpress -o compact")
assert result.returncode == 0
def test_search_cpe_csv(runner):
result = runner.runcommand("bin/search_cpe.py -s wordpress -o csv")
assert result.returncode == 0
| 1,173
|
Python
|
.py
| 27
| 38.814815
| 99
| 0.712766
|
cve-search/cve-search
| 2,271
| 587
| 2
|
AGPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,193
|
setup_test_data.py
|
cve-search_cve-search/test/test_data/setup_test_data.py
|
import os
import sys
runPath = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(runPath, "../.."))
from dateutil.parser import parse as parse_datetime
from lib.Config import Configuration as conf
data = {
"cves": [
{
"id": "CVE-2015-0001",
"assigner": "cve@mitre.org",
"published": parse_datetime("2015-01-13T22:59:00.000Z", ignoretz=True),
"modified": parse_datetime("2018-10-12T22:07:00.000Z", ignoretz=True),
"lastModified": parse_datetime("2018-10-12T22:07:00.000Z", ignoretz=True),
"summary": 'The Windows Error Reporting (WER) component in Microsoft Windows 8, Windows 8.1, Windows Server 2012 Gold and R2, and Windows RT Gold and 8.1 allows local users to bypass the Protected Process Light protection mechanism and read the contents of arbitrary process-memory locations by leveraging administrative privileges, aka "Windows Error Reporting Security Feature Bypass Vulnerability."',
"access": {
"authentication": "NONE",
"complexity": "MEDIUM",
"vector": "LOCAL",
},
"impact": {
"availability": "NONE",
"confidentiality": "PARTIAL",
"integrity": "NONE",
},
"cvss": 1.9,
"cvssTime": parse_datetime("2018-10-12T22:07:00.000Z", ignoretz=True),
"cvssVector": "AV:L/AC:M/Au:N/C:P/I:N/A:N",
"references": [
"http://packetstormsecurity.com/files/134392/Microsoft-Windows-8.1-Ahcache.sys-NtApphelpCacheControl-Privilege-Escalation.html",
"http://secunia.com/advisories/62134",
"http://www.securityfocus.com/bid/71927",
"https://docs.microsoft.com/en-us/security-updates/securitybulletins/2015/ms15-006",
"https://exchange.xforce.ibmcloud.com/vulnerabilities/99513",
"https://exchange.xforce.ibmcloud.com/vulnerabilities/99514",
],
"vulnerable_configuration": [
"cpe:2.3:o:microsoft:windows_8:-:*:*:*:*:*:*:*",
"cpe:2.3:o:microsoft:windows_8.1:-:*:*:*:*:*:*:*",
"cpe:2.3:o:microsoft:windows_rt:-:gold:*:*:*:*:*:*",
"cpe:2.3:o:microsoft:windows_rt_8.1:-:*:*:*:*:*:*:*",
"cpe:2.3:o:microsoft:windows_server_2012:-:gold:*:*:*:*:*:*",
"cpe:2.3:o:microsoft:windows_server_2012:r2:*:*:*:*:x64:*:*",
],
"vulnerable_product": [
"cpe:2.3:o:microsoft:windows_8:-:*:*:*:*:*:*:*",
"cpe:2.3:o:microsoft:windows_8.1:-:*:*:*:*:*:*:*",
"cpe:2.3:o:microsoft:windows_rt:-:gold:*:*:*:*:*:*",
"cpe:2.3:o:microsoft:windows_rt_8.1:-:*:*:*:*:*:*:*",
"cpe:2.3:o:microsoft:windows_server_2012:-:gold:*:*:*:*:*:*",
"cpe:2.3:o:microsoft:windows_server_2012:r2:*:*:*:*:x64:*:*",
],
"vendors": ["microsoft"],
"products": [
"windows_8",
"windows_8.1",
"windows_rt",
"windows_rt_8.1",
"windows_server_2012",
],
"vulnerable_product_stems": [
"cpe:2.3:o:microsoft:windows_8",
"cpe:2.3:o:microsoft:windows_8.1",
"cpe:2.3:o:microsoft:windows_rt",
"cpe:2.3:o:microsoft:windows_rt_8.1",
"cpe:2.3:o:microsoft:windows_server_2012",
],
"vulnerable_configuration_stems": [
"cpe:2.3:o:microsoft:windows_8",
"cpe:2.3:o:microsoft:windows_8.1",
"cpe:2.3:o:microsoft:windows_rt",
"cpe:2.3:o:microsoft:windows_rt_8.1",
"cpe:2.3:o:microsoft:windows_server_2012",
],
"cwe": "CWE-264",
"vulnerable_configuration_cpe_2_2": [],
},
{
"id": "CVE-2018-0004",
"assigner": "cve@mitre.org",
"published": parse_datetime("2018-01-10T22:29:00.000Z", ignoretz=True),
"modified": parse_datetime("2019-10-09T23:30:00.000Z", ignoretz=True),
"lastModified": parse_datetime("2019-10-09T23:30:00.000Z", ignoretz=True),
"summary": "A sustained sequence of different types of normal transit traffic can trigger a high CPU consumption denial of service condition in the Junos OS register and schedule software interrupt handler subsystem when a specific command is issued to the device. This affects one or more threads and conversely one or more running processes running on the system. Once this occurs, the high CPU event(s) affects either or both the forwarding and control plane. As a result of this condition the device can become inaccessible in either or both the control and forwarding plane and stops forwarding traffic until the device is rebooted. The issue will reoccur after reboot upon receiving further transit traffic. Score: 5.7 MEDIUM (CVSS:3.0/AV:A/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H) For network designs utilizing layer 3 forwarding agents or other ARP through layer 3 technologies, the score is slightly higher. Score: 6.5 MEDIUM (CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H) If the following entry exists in the RE message logs then this may indicate the issue is present. This entry may or may not appear when this issue occurs. /kernel: Expensive timeout(9) function: Affected releases are Juniper Networks Junos OS: 12.1X46 versions prior to 12.1X46-D50; 12.3X48 versions prior to 12.3X48-D30; 12.3R versions prior to 12.3R12-S7; 14.1 versions prior to 14.1R8-S4, 14.1R9; 14.1X53 versions prior to 14.1X53-D30, 14.1X53-D34; 14.2 versions prior to 14.2R8; 15.1 versions prior to 15.1F6, 15.1R3; 15.1X49 versions prior to 15.1X49-D40; 15.1X53 versions prior to 15.1X53-D31, 15.1X53-D33, 15.1X53-D60. No other Juniper Networks products or platforms are affected by this issue.",
"access": {
"authentication": "NONE",
"complexity": "MEDIUM",
"vector": "NETWORK",
},
"impact": {
"availability": "COMPLETE",
"confidentiality": "NONE",
"integrity": "NONE",
},
"cvss": 7.1,
"cvssTime": parse_datetime("2019-10-09T23:30:00.000Z", ignoretz=True),
"cvssVector": "AV:N/AC:M/Au:N/C:N/I:N/A:C",
"references": [
"http://www.securitytracker.com/id/1040183",
"https://kb.juniper.net/JSA10832",
],
"vulnerable_configuration": [
"cpe:2.3:o:juniper:junos:12.1x46:*:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.1x46:d10:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.1x46:d15:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.1x46:d20:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.1x46:d25:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.1x46:d30:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.1x46:d35:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.1x46:d40:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.1x46:d45:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3x48:*:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3x48:d10:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3x48:d15:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3x48:d20:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3x48:d25:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r1:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r11:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r12:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r2:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r3:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r4:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r5:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r6:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r7:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r8:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r9:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:*:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:r1:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:r2:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:r3:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:r4:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:r5:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:r6:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:r7:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:r9:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1x53:*:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1x53:d10:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1x53:d15:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1x53:d16:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1x53:d25:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1x53:d26:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1x53:d27:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1x53:d34:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.2:*:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.2:r1:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.2:r2:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.2:r3:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.2:r4:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.2:r5:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.2:r6:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.2:r7:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:*:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:a1:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f1:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f2:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f2-s1:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f2-s2:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f2-s3:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f2-s4:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f3:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f4:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f5:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:r3:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x49:*:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x49:d10:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x49:d20:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x49:d30:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x49:d35:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:*:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:d10:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:d20:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:d21:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:d210:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:d25:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:d30:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:d33:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:d60:*:*:*:*:*:*",
],
"vulnerable_product": [
"cpe:2.3:o:juniper:junos:12.1x46:*:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.1x46:d10:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.1x46:d15:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.1x46:d20:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.1x46:d25:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.1x46:d30:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.1x46:d35:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.1x46:d40:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.1x46:d45:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3x48:*:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3x48:d10:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3x48:d15:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3x48:d20:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3x48:d25:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r1:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r11:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r12:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r2:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r3:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r4:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r5:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r6:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r7:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r8:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:12.3:r9:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:*:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:r1:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:r2:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:r3:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:r4:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:r5:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:r6:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:r7:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1:r9:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1x53:*:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1x53:d10:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1x53:d15:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1x53:d16:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1x53:d25:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1x53:d26:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1x53:d27:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.1x53:d34:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.2:*:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.2:r1:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.2:r2:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.2:r3:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.2:r4:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.2:r5:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.2:r6:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:14.2:r7:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:*:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:a1:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f1:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f2:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f2-s1:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f2-s2:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f2-s3:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f2-s4:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f3:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f4:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:f5:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1:r3:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x49:*:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x49:d10:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x49:d20:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x49:d30:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x49:d35:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:*:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:d10:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:d20:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:d21:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:d210:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:d25:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:d30:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:d33:*:*:*:*:*:*",
"cpe:2.3:o:juniper:junos:15.1x53:d60:*:*:*:*:*:*",
],
"vendors": ["juniper"],
"products": ["junos"],
"vulnerable_product_stems": ["cpe:2.3:o:juniper:junos"],
"vulnerable_configuration_stems": ["cpe:2.3:o:juniper:junos"],
"cwe": "CWE-400",
"vulnerable_configuration_cpe_2_2": [],
},
{
"id": "CVE-2020-0079",
"assigner": "cve@mitre.org",
"published": parse_datetime("2020-04-17T19:15:00.000Z", ignoretz=True),
"modified": parse_datetime("2020-04-23T18:56:00.000Z", ignoretz=True),
"lastModified": parse_datetime("2020-04-23T18:56:00.000Z", ignoretz=True),
"summary": "In decrypt_1_2 of CryptoPlugin.cpp, there is a possible out of bounds write due to stale pointer. This could lead to local escalation of privilege with no additional execution privileges needed. User interaction is not needed for exploitation.Product: AndroidVersions: Android-9 Android-10Android ID: A-144506242",
"access": {
"authentication": "NONE",
"complexity": "LOW",
"vector": "LOCAL",
},
"impact": {
"availability": "PARTIAL",
"confidentiality": "PARTIAL",
"integrity": "PARTIAL",
},
"cvss": 4.6,
"cvssTime": parse_datetime("2020-04-23T18:56:00.000Z", ignoretz=True),
"cvssVector": "AV:L/AC:L/Au:N/C:P/I:P/A:P",
"references": ["https://source.android.com/security/bulletin/2020-04-01"],
"vulnerable_configuration": [
"cpe:2.3:o:google:android:9.0:*:*:*:*:*:*:*",
"cpe:2.3:o:google:android:10.0:*:*:*:*:*:*:*",
],
"vulnerable_product": [
"cpe:2.3:o:google:android:9.0:*:*:*:*:*:*:*",
"cpe:2.3:o:google:android:10.0:*:*:*:*:*:*:*",
],
"vendors": ["google"],
"products": ["android"],
"vulnerable_product_stems": ["cpe:2.3:o:google:android"],
"vulnerable_configuration_stems": ["cpe:2.3:o:google:android"],
"cwe": "CWE-787",
"vulnerable_configuration_cpe_2_2": [],
},
{
"id": "CVE-2010-3333",
"assigner": "cve@mitre.org",
"published": parse_datetime("2010-11-10T03:00:00.000Z", ignoretz=True),
"modified": parse_datetime("2018-10-12T21:58:00.000Z", ignoretz=True),
"lastModified": parse_datetime("2018-10-12T21:58:00.000Z", ignoretz=True),
"summary": 'Stack-based buffer overflow in Microsoft Office XP SP3, Office 2003 SP3, Office 2007 SP2, Office 2010, Office 2004 and 2008 for Mac, Office for Mac 2011, and Open XML File Format Converter for Mac allows remote attackers to execute arbitrary code via crafted RTF data, aka "RTF Stack Buffer Overflow Vulnerability."',
"access": {
"authentication": "NONE",
"complexity": "MEDIUM",
"vector": "NETWORK",
},
"impact": {
"availability": "COMPLETE",
"confidentiality": "COMPLETE",
"integrity": "COMPLETE",
},
"cvss": 9.3,
"cvssTime": parse_datetime("2018-10-12T21:58:00.000Z", ignoretz=True),
"cvssVector": "AV:N/AC:M/Au:N/C:C/I:C/A:C",
"references": [
"http://labs.idefense.com/intelligence/vulnerabilities/display.php?id=880",
"http://secunia.com/advisories/38521",
"http://secunia.com/advisories/42144",
"http://securityreason.com/securityalert/8293",
"http://www.securityfocus.com/bid/44652",
"http://www.securitytracker.com/id?1024705",
"http://www.us-cert.gov/cas/techalerts/TA10-313A.html",
"http://www.vupen.com/english/advisories/2010/2923",
"https://docs.microsoft.com/en-us/security-updates/securitybulletins/2010/ms10-087",
"https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A11931",
],
"vulnerable_configuration": [
"cpe:2.3:a:microsoft:office:2003:sp3:*:*:*:*:*:*",
"cpe:2.3:a:microsoft:office:2004:*:mac:*:*:*:*:*",
"cpe:2.3:a:microsoft:office:2007:sp2:*:*:*:*:*:*",
"cpe:2.3:a:microsoft:office:2008:*:mac:*:*:*:*:*",
"cpe:2.3:a:microsoft:office:2010:*:*:*:*:*:*:*",
"cpe:2.3:a:microsoft:office:2011:*:mac:*:*:*:*:*",
"cpe:2.3:a:microsoft:office:xp:sp3:*:*:*:*:*:*",
"cpe:2.3:a:microsoft:open_xml_file_format_converter:*:*:mac:*:*:*:*:*",
],
"vulnerable_product": [
"cpe:2.3:a:microsoft:office:2003:sp3:*:*:*:*:*:*",
"cpe:2.3:a:microsoft:office:2004:*:mac:*:*:*:*:*",
"cpe:2.3:a:microsoft:office:2007:sp2:*:*:*:*:*:*",
"cpe:2.3:a:microsoft:office:2008:*:mac:*:*:*:*:*",
"cpe:2.3:a:microsoft:office:2010:*:*:*:*:*:*:*",
"cpe:2.3:a:microsoft:office:2011:*:mac:*:*:*:*:*",
"cpe:2.3:a:microsoft:office:xp:sp3:*:*:*:*:*:*",
"cpe:2.3:a:microsoft:open_xml_file_format_converter:*:*:mac:*:*:*:*:*",
],
"vendors": ["microsoft"],
"products": ["office", "open_xml_file_format_converter"],
"vulnerable_product_stems": [
"cpe:2.3:a:microsoft:office",
"cpe:2.3:a:microsoft:open_xml_file_format_converter",
],
"vulnerable_configuration_stems": [
"cpe:2.3:a:microsoft:office",
"cpe:2.3:a:microsoft:open_xml_file_format_converter",
],
"cwe": "CWE-119",
"vulnerable_configuration_cpe_2_2": [],
},
{
"id": "CVE-2017-12231",
"assigner": "cve@mitre.org",
"published": parse_datetime("2017-09-29T01:34:00.000Z", ignoretz=True),
"modified": parse_datetime("2019-10-09T23:22:00.000Z", ignoretz=True),
"lastModified": parse_datetime("2019-10-09T23:22:00.000Z", ignoretz=True),
"summary": "A vulnerability in the implementation of Network Address Translation (NAT) functionality in Cisco IOS 12.4 through 15.6 could allow an unauthenticated, remote attacker to cause a denial of service (DoS) condition on an affected device. The vulnerability is due to the improper translation of H.323 messages that use the Registration, Admission, and Status (RAS) protocol and are sent to an affected device via IPv4 packets. An attacker could exploit this vulnerability by sending a crafted H.323 RAS packet through an affected device. A successful exploit could allow the attacker to cause the affected device to crash and reload, resulting in a DoS condition. This vulnerability affects Cisco devices that are configured to use an application layer gateway with NAT (NAT ALG) for H.323 RAS messages. By default, a NAT ALG is enabled for H.323 RAS messages. Cisco Bug IDs: CSCvc57217.",
"access": {
"authentication": "NONE",
"complexity": "LOW",
"vector": "NETWORK",
},
"impact": {
"availability": "COMPLETE",
"confidentiality": "NONE",
"integrity": "NONE",
},
"cvss": 7.8,
"cvssTime": parse_datetime("2019-10-09T23:22:00.000Z", ignoretz=True),
"cvssVector": "AV:N/AC:L/Au:N/C:N/I:N/A:C",
"references": [
"http://www.securityfocus.com/bid/101039",
"http://www.securitytracker.com/id/1039449",
"https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20170927-nat",
],
"vulnerable_configuration": [
"cpe:2.3:o:cisco:ios:12.4\\(25e\\)jao3a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:12.4\\(25e\\)jao20s:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:12.4\\(25e\\)jap1n:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:12.4\\(25e\\)jap9:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.0\\(2\\)sqd7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.1\\(2\\)sg7a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(2\\)e3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(2\\)e5b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(3\\)ex:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)ec:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)m8:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)m9:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)m10:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)m11:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)s7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(5\\)e2a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(5\\)e2b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(5a\\)e1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jbb6a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jc7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jc50:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jc51:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jca7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jd7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jda3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)je1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jf1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jnc4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jnd2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jnp2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jnp4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jpb:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jpb2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jpc3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)m6:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)m7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)m8:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)m8a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)s6:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)s7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)s8:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)s8a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)s9:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(1\\)s4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(1\\)t4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(2\\)s4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(2\\)t4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)m3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)m4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)m5:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)m6:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)m6a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s5:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s5a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s6:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s6a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s6b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s7a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(1\\)s2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(1\\)s3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(1\\)s4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(1\\)t2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(1\\)t3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(1\\)t4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)s:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)s1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)s2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)s3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)s4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)t:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)t1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)t2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)t3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)t4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)m:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)m0a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)m1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)m2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)m3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)m4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)m4a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s0a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s1a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s2a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s2b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s3a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s4a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s4b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s4d:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s5:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)s:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)s1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)s1a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)s2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)s3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)t:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)t0a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)t1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)t2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s0a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp1b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp1c:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp2a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)t:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)t1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)t2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(3\\)m:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(3\\)m0a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(3\\)m1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(3\\)m1b:*:*:*:*:*:*:*",
],
"vulnerable_product": [
"cpe:2.3:o:cisco:ios:12.4\\(25e\\)jao3a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:12.4\\(25e\\)jao20s:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:12.4\\(25e\\)jap1n:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:12.4\\(25e\\)jap9:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.0\\(2\\)sqd7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.1\\(2\\)sg7a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(2\\)e3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(2\\)e5b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(3\\)ex:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)ec:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)m8:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)m9:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)m10:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)m11:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)s7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(5\\)e2a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(5\\)e2b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(5a\\)e1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jbb6a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jc7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jc50:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jc51:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jca7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jd7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jda3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)je1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jf1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jnc4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jnd2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jnp2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jnp4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jpb:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jpb2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jpc3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)m6:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)m7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)m8:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)m8a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)s6:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)s7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)s8:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)s8a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)s9:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(1\\)s4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(1\\)t4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(2\\)s4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(2\\)t4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)m3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)m4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)m5:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)m6:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)m6a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s5:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s5a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s6:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s6a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s6b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.4\\(3\\)s7a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(1\\)s2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(1\\)s3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(1\\)s4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(1\\)t2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(1\\)t3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(1\\)t4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)s:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)s1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)s2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)s3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)s4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)t:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)t1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)t2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)t3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(2\\)t4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)m:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)m0a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)m1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)m2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)m3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)m4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)m4a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s0a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s1a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s2a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s2b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s3a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s4a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s4b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s4d:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.5\\(3\\)s5:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)s:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)s1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)s1a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)s2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)s3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)t:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)t0a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)t1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)t2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s0a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp1b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp1c:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp2a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)t:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)t1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)t2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(3\\)m:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(3\\)m0a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(3\\)m1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(3\\)m1b:*:*:*:*:*:*:*",
],
"vendors": ["cisco"],
"products": ["ios"],
"vulnerable_product_stems": ["cpe:2.3:o:cisco:ios"],
"vulnerable_configuration_stems": ["cpe:2.3:o:cisco:ios"],
"cwe": "NVD-CWE-noinfo",
"vulnerable_configuration_cpe_2_2": [],
},
{
"id": "CVE-2017-12233",
"assigner": "cve@mitre.org",
"published": parse_datetime("2017-09-29T01:34:00.000Z", ignoretz=True),
"modified": parse_datetime("2019-10-09T23:22:00.000Z", ignoretz=True),
"lastModified": parse_datetime("2019-10-09T23:22:00.000Z", ignoretz=True),
"summary": "Multiple vulnerabilities in the implementation of the Common Industrial Protocol (CIP) feature in Cisco IOS 12.4 through 15.6 could allow an unauthenticated, remote attacker to cause an affected device to reload, resulting in a denial of service (DoS) condition. The vulnerabilities are due to the improper parsing of crafted CIP packets destined to an affected device. An attacker could exploit these vulnerabilities by sending crafted CIP packets to be processed by an affected device. A successful exploit could allow the attacker to cause the affected device to reload, resulting in a DoS condition. Cisco Bug IDs: CSCuz95334.",
"access": {
"authentication": "NONE",
"complexity": "LOW",
"vector": "NETWORK",
},
"impact": {
"availability": "COMPLETE",
"confidentiality": "NONE",
"integrity": "NONE",
},
"cvss": 7.8,
"cvssTime": parse_datetime("2019-10-09T23:22:00.000Z", ignoretz=True),
"cvssVector": "AV:N/AC:L/Au:N/C:N/I:N/A:C",
"references": [
"http://www.securityfocus.com/bid/101038",
"http://www.securitytracker.com/id/1039459",
"https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20170927-cip",
],
"vulnerable_configuration": [
"cpe:2.3:o:cisco:ios:12.4\\(25e\\)jao3a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:12.4\\(25e\\)jao20s:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:12.4\\(25e\\)jap1n:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:12.4\\(25e\\)jap9:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.0\\(2\\)sqd7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.1\\(2\\)sg7a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(2\\)e3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(2\\)e5b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(2\\)eb:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(2\\)eb1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(2\\)eb2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(3\\)ex:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)ec:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)ec1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)ec2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(5\\)e:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(5\\)e2a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(5\\)e2b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(5a\\)e1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jbb6a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jc7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jc50:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jc51:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jca7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jda3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)je1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jnc4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jnd2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jnp2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jpb:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jpb2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jpc3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)s1a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s0a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp1b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp1c:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp2a:*:*:*:*:*:*:*",
],
"vulnerable_product": [
"cpe:2.3:o:cisco:ios:12.4\\(25e\\)jao3a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:12.4\\(25e\\)jao20s:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:12.4\\(25e\\)jap1n:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:12.4\\(25e\\)jap9:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.0\\(2\\)sqd7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.1\\(2\\)sg7a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(2\\)e3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(2\\)e5b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(2\\)eb:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(2\\)eb1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(2\\)eb2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(3\\)ex:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)ec:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)ec1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(4\\)ec2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(5\\)e:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(5\\)e2a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(5\\)e2b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.2\\(5a\\)e1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jbb6a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jc7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jc50:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jc51:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jca7:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jda3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)je1:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jnc4:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jnd2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jnp2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jpb:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jpb2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.3\\(3\\)jpc3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(1\\)s1a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s0a:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s2:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)s3:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp1b:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp1c:*:*:*:*:*:*:*",
"cpe:2.3:o:cisco:ios:15.6\\(2\\)sp2a:*:*:*:*:*:*:*",
],
"vendors": ["cisco"],
"products": ["ios"],
"vulnerable_product_stems": ["cpe:2.3:o:cisco:ios"],
"vulnerable_configuration_stems": ["cpe:2.3:o:cisco:ios"],
"cwe": "CWE-20",
"vulnerable_configuration_cpe_2_2": [],
},
{
"id": "CVE-2017-0123",
"assigner": "cve@mitre.org",
"published": parse_datetime("2017-03-17T00:59:00.000Z"),
"modified": parse_datetime("2017-08-16T01:29:00.000Z"),
"lastModified": parse_datetime("2017-08-16T01:29:00.000Z"),
"summary": 'Uniscribe in Microsoft Windows Vista SP2, Windows Server 2008 SP2 and R2 SP1, and Windows 7 SP1 allows remote attackers to obtain sensitive information from process memory via a crafted web site, aka "Uniscribe Information Disclosure Vulnerability." CVE-2017-0085, CVE-2017-0091, CVE-2017-0092, CVE-2017-0111, CVE-2017-0112, CVE-2017-0113, CVE-2017-0114, CVE-2017-0115, CVE-2017-0116, CVE-2017-0117, CVE-2017-0118, CVE-2017-0119, CVE-2017-0120, CVE-2017-0121, CVE-2017-0122, CVE-2017-0124, CVE-2017-0125, CVE-2017-0126, CVE-2017-0127, and CVE-2017-0128.',
"access": {
"authentication": "NONE",
"complexity": "MEDIUM",
"vector": "NETWORK",
},
"impact": {
"availability": "NONE",
"confidentiality": "PARTIAL",
"integrity": "NONE",
},
"cvss": 4.3,
"cvssTime": parse_datetime("2017-08-16T01:29:00.000Z"),
"cvssVector": "AV:N/AC:M/Au:N/C:P/I:N/A:N",
"references": [
"http://www.securityfocus.com/bid/96669",
"http://www.securitytracker.com/id/1037992",
"https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2017-0123",
"https://www.exploit-db.com/exploits/41655/",
],
"vulnerable_configuration": [
"cpe:2.3:o:microsoft:windows_7:*:sp1:*:*:*:*:*:*",
"cpe:2.3:o:microsoft:windows_server_2008:*:sp2:*:*:*:*:*:*",
"cpe:2.3:o:microsoft:windows_server_2008:r2:sp1:*:*:*:*:*:*",
"cpe:2.3:o:microsoft:windows_vista:*:sp2:*:*:*:*:*:*",
],
"vulnerable_product": [
"cpe:2.3:o:microsoft:windows_7:*:sp1:*:*:*:*:*:*",
"cpe:2.3:o:microsoft:windows_server_2008:*:sp2:*:*:*:*:*:*",
"cpe:2.3:o:microsoft:windows_server_2008:r2:sp1:*:*:*:*:*:*",
"cpe:2.3:o:microsoft:windows_vista:*:sp2:*:*:*:*:*:*",
],
"vendors": ["microsoft"],
"products": ["windows_7", "windows_server_2008", "windows_vista"],
"vulnerable_product_stems": [
"cpe:2.3:o:microsoft:windows_7",
"cpe:2.3:o:microsoft:windows_server_2008",
"cpe:2.3:o:microsoft:windows_vista",
],
"vulnerable_configuration_stems": [
"cpe:2.3:o:microsoft:windows_7",
"cpe:2.3:o:microsoft:windows_server_2008",
"cpe:2.3:o:microsoft:windows_vista",
],
"cwe": "CWE-200",
"vulnerable_configuration_cpe_2_2": [],
},
{
"id": "CVE-2013-0270",
"assigner": "cve@mitre.org",
"published": parse_datetime("2013-04-12T22:55:00.000Z"),
"modified": parse_datetime("2018-11-16T14:38:00.000Z"),
"lastModified": parse_datetime("2018-11-16T14:38:00.000Z"),
"summary": "OpenStack Keystone Grizzly before 2013.1, Folsom, and possibly earlier allows remote attackers to cause a denial of service (CPU and memory consumption) via a large HTTP request, as demonstrated by a long tenant_name when requesting a token.",
"access": {
"authentication": "NONE",
"complexity": "LOW",
"vector": "NETWORK",
},
"impact": {
"availability": "PARTIAL",
"confidentiality": "NONE",
"integrity": "NONE",
},
"cvss": 5.0,
"cvssTime": parse_datetime("2018-11-16T14:38:00.000Z"),
"cvssVector": "AV:N/AC:L/Au:N/C:N/I:N/A:P",
"references": [
"http://rhn.redhat.com/errata/RHSA-2013-0708.html",
"https://bugs.launchpad.net/keystone/+bug/1099025",
"https://bugzilla.redhat.com/show_bug.cgi?id=909012",
"https://github.com/openstack/keystone/commit/7691276b869a86c2b75631d5bede9f61e030d9d8",
"https://github.com/openstack/keystone/commit/82c87e5638ebaf9f166a9b07a0155291276d6fdc",
"https://launchpad.net/keystone/grizzly/2013.1",
],
"vulnerable_configuration": [
"cpe:2.3:a:openstack:keystone:2012.1:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.1.1:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.1.2:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.1.3:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.2:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.2:milestone1:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.2:milestone2:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.2.1:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.2.2:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.2.3:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.2.4:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2013.1:milestone1:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2013.1:milestone2:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2013.1:milestone3:*:*:*:*:*:*",
],
"vulnerable_product": [
"cpe:2.3:a:openstack:keystone:2012.1:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.1.1:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.1.2:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.1.3:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.2:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.2:milestone1:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.2:milestone2:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.2.1:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.2.2:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.2.3:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2012.2.4:*:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2013.1:milestone1:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2013.1:milestone2:*:*:*:*:*:*",
"cpe:2.3:a:openstack:keystone:2013.1:milestone3:*:*:*:*:*:*",
],
"vendors": ["openstack"],
"products": ["keystone"],
"vulnerable_product_stems": ["cpe:2.3:a:openstack:keystone"],
"vulnerable_configuration_stems": ["cpe:2.3:a:openstack:keystone"],
"cwe": "CWE-119",
"vulnerable_configuration_cpe_2_2": [],
},
],
"cpe": [
{
"title": "Wordpress Dean Logan Wp-People Plugin 1.6.1",
"cpeName": "cpe:2.3:a:wordpress:dean_logan_wp-people_plugin:1.6.1:*:*:*:*:*:*:*",
"vendor": "wordpress",
"product": "dean_logan_wp-people_plugin",
"id": "8d9041e6a59af093b211f8447540596feccc1dc8",
},
{
"title": "Wordpress Page Flip Image Gallery Plugin 0.1.3",
"cpeName": "cpe:2.3:a:wordpress:page_flip_image_gallery_plugin:0.1.3:*:*:*:*:*:*:*",
"vendor": "wordpress",
"product": "page_flip_image_gallery_plugin",
"id": "725efec7e0f927cf691e2dbbbd305bab4b187031",
},
{
"title": "Wordpress Wordpress 2.0.6",
"cpeName": "cpe:2.3:a:wordpress:wordpress:2.0.6:*:*:*:*:*:*:*",
"vendor": "wordpress",
"product": "wordpress",
"id": "61795296ab416170d85b347f2423878091bb0447",
},
{
"title": "Wordpress Wordpress 3.9.9",
"cpeName": "cpe:2.3:a:wordpress:wordpress:3.9.9:*:*:*:*:*:*:*",
"vendor": "wordpress",
"product": "wordpress",
"id": "6a77c773807325a0fa1ac1a52419f7ddc517db72",
},
{
"title": "Wordpress Wordspew 3.3",
"cpeName": "cpe:2.3:a:wordpress:wordspew:3.3:*:*:*:*:*:*:*",
"vendor": "wordpress",
"product": "wordspew",
"id": "090fadcd41d66eee335fae5fbd0177b4000b7e27",
},
],
}
database = conf.getMongoConnection()
for collection in data:
database[collection].insert_many(data[collection])
| 58,258
|
Python
|
.py
| 929
| 47.159311
| 1,688
| 0.428973
|
cve-search/cve-search
| 2,271
| 587
| 2
|
AGPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,194
|
notest_web.py
|
cve-search_cve-search/test/web/notest_web.py
|
import pytest
from bs4 import BeautifulSoup
from test.runners.web_test_runner import WebTestRunner
@pytest.fixture
def webrunner():
return WebTestRunner(address=("localhost", 443))
def test_web_up(webrunner):
result = webrunner.call(method="GET", resource="/")
soup = BeautifulSoup(result.text, features="html.parser")
assert result.status_code == 200
assert soup.find("title").text == "Most recent entries - CVE-Search"
| 448
|
Python
|
.py
| 11
| 37.272727
| 72
| 0.753488
|
cve-search/cve-search
| 2,271
| 587
| 2
|
AGPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,195
|
cli_test_runner.py
|
cve-search_cve-search/test/runners/cli_test_runner.py
|
from subprocess import run, PIPE, STDOUT
class CLITestRunner(object):
def __init__(self):
self.runner = None
self.cmd = None
def runcommand(self, cmd):
self.cmd = cmd
self.runner = run(
self.cmd.split(" "),
stdout=PIPE,
stderr=STDOUT,
universal_newlines=True,
shell=False,
)
return self.runner
| 414
|
Python
|
.py
| 15
| 18.6
| 40
| 0.549367
|
cve-search/cve-search
| 2,271
| 587
| 2
|
AGPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,196
|
web_test_runner.py
|
cve-search_cve-search/test/runners/web_test_runner.py
|
import json
from json import JSONDecodeError
import requests
class WebTestRunner(object):
"""
The WebTestRunner class serves as a base class for all API's used within the tests
"""
def __init__(self, address, api_path=None, proxies={}, protocol="https"):
"""
The WebTestRunner caller handles all communication towards a api resource.
:param address: Tuple with host ip/name and port
:type address: tuple
:param api_path: Generic to connect to api resources, defaults to 'None'
:type api_path: str
:param proxies: If you need to use a proxy, you can configure individual requests with the proxies argument
to any request method
:type proxies: dict
:param protocol: Protocol to use when connecting to api; defaults to 'https'
:type protocol: str
"""
if not isinstance(address, tuple):
raise TypeError(
"The parameter 'address' has to be a tuple with the address and port of the api host"
"e.g. ('127.0.0.1', 8834) "
)
self.verify = False
self.server = address[0]
self.port = address[1]
self.protocol = protocol
self.baseurl = "{}://{}:{}".format(self.protocol, self.server, self.port)
self.api_path = api_path
self.proxies = proxies
self.myheaders = {
"Accept": "application/json",
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0",
}
def __repr__(self):
"""return a string representation of the obj GenericApi"""
return "<<WebTestRunner:({}, {})>>".format(self.server, self.port)
def __del__(self):
"""Called when the class is garbage collected."""
pass
def __build_url(self, resource):
"""
Internal method to build a url to use when executing commands
:param resource: API end point to connect to
:type resource: str
:return: url string
:rtype: str
"""
if self.api_path is None:
return "{0}/{1}".format(self.baseurl, resource)
else:
return "{0}/{1}/{2}".format(self.baseurl, self.api_path, resource)
def __connect(self, method, resource, session, data=None, timeout=60):
"""
Send a request
Send a request to api host based on the specified data. Specify the content type as JSON and
convert the data to JSON format.
:param method: http method to use (e.g. POST, GET, DELETE, PUT)
:type method: str
:param resource: API end point to connect to
:type resource: str
:param session: Session object from requests library
:type session: object
:param data: Request body data
:type data: dict
:param timeout: Set the timeout on a request, defaults to 60 seconds
:type timeout: int
:return: response from the server
:rtype: dict
"""
requests.packages.urllib3.disable_warnings()
if data is None:
request_api_resource = {
"headers": self.myheaders,
"verify": self.verify,
"timeout": timeout,
"proxies": self.proxies,
}
else:
data = json.dumps(data)
request_api_resource = {
"data": data,
"headers": self.myheaders,
"verify": self.verify,
"timeout": timeout,
"proxies": self.proxies,
}
if method == "POST":
r = session.post(self.__build_url(resource), **request_api_resource)
elif method == "PUT":
r = session.put(self.__build_url(resource), **request_api_resource)
elif method == "DELETE":
r = session.delete(self.__build_url(resource), **request_api_resource)
else:
r = session.get(self.__build_url(resource), **request_api_resource)
try:
json_response = json.loads(r.text)
except JSONDecodeError:
json_response = r
return json_response
def call(self, method=None, resource=None, data=None):
"""
Method for requesting free format api resources
:param method: http method to use (e.g. POST, GET, DELETE, PUT)
:type method: str
:param resource: API end point to connect to
:type resource: str
:param data: Request body data
:type data: dict
:return: query result
:rtype: dict
"""
try:
with requests.Session() as session:
result = self.__connect(
method=method, resource=resource, session=session, data=data
)
return result
except requests.ConnectionError:
print("Connection error, is the host up?")
raise
@property
def headers(self):
"""
Property to return the current headers
:return: self.myheaders
:rtype: dict
"""
return self.myheaders
def set_header_field(self, field, value):
"""
Method to add a header and set it's value
:param field: Name of the header field to add
:type field: str
:param value: Value of the header field
:type value: str
:return: self.myheaders
:rtype: dict
"""
self.myheaders[field] = value
return self.myheaders
def del_header_field(self, field):
"""
Method to delete a header field
:param field: Name of the header field to delete
:type field: str
:return: self.myheaders
:rtype: dict
"""
self.myheaders.pop(field)
return self.myheaders
def reset_headers(self):
"""
Method to reset the headers to the default values
"""
self.myheaders = {
"Accept": "application/json",
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0",
}
| 6,286
|
Python
|
.py
| 163
| 28.441718
| 115
| 0.578679
|
cve-search/cve-search
| 2,271
| 587
| 2
|
AGPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,197
|
cve_doc.py
|
cve-search_cve-search/bin/cve_doc.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# cve_doc converts CVE to asciidoc
#
# Software is free software released under the "GNU Affero General Public License v3.0"
#
# Copyright (c) 2015-2018 Alexandre Dulaunoy - a@foo.be
import json
import os
import re
import sys
from optparse import OptionParser
runPath = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(runPath, ".."))
from lib.Query import apigetcve
optp = OptionParser()
optp.add_option(
"-c", "--cve", dest="cve", default="CVE-2015-0001", help="CVE id to convert"
)
optp.add_option(
"-f", "--format", dest="format", default="asciidoc", help="output format : asciidoc"
)
optp.add_option(
"-a",
"--api",
dest="api",
default="http://cve.circl.lu/",
help="HTTP API url (default: http://cve.circl.lu)",
)
(opts, args) = optp.parse_args()
cve = json.loads(apigetcve(opts.api, cveid=opts.cve))
if not cve:
sys.exit(10)
print("= Common Vulnerabilities and Exposures - {}".format(cve["id"]))
print("cve-search <{}/cve/{}>".format(opts.api, cve["id"]))
print("{},{}".format(cve["id"], cve["modified"]))
print(":toc:")
print("== {} Summary".format(cve["id"]))
print("\n" + cve["summary"])
print("\n== Vulnerable configurations\n")
for vul in cve["vulnerable_configuration"]:
print("* {}".format(re.sub(r"\n", "-", vul["title"])))
if cve.get("cvss"):
print("\n== Common Vulnerability Scoring System")
print("CVSS value:: {}".format(cve["cvss"]))
if cve.get("impact"):
print("\n== Impact Metrics")
print('\n[cols="1,2"]')
print("|===")
types = ["availability", "confidentiality", "integrity"]
for t in types:
print("|{}".format(t.title()))
print("|{}".format(cve["impact"][t]))
print("|===")
if cve.get("access"):
print("\n== Access to the vulnerability")
print('\n[cols="1,2"]')
print("|===")
types = ["authentication", "complexity", "vector"]
for t in types:
print("|{}".format(t.title()))
print("|{}".format(cve["access"][t]))
print("|===")
if cve.get("references"):
print("\n== References")
if len(cve["references"]) > 1:
for ref in cve["references"]:
print("* {}".format(ref))
elif len(cve["references"]) == 1:
ref = cve["references"][0]
print("* {}".format(ref))
| 2,329
|
Python
|
.py
| 72
| 28.847222
| 88
| 0.617163
|
cve-search/cve-search
| 2,271
| 587
| 2
|
AGPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,198
|
db_dump.py
|
cve-search_cve-search/bin/db_dump.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Tool to dump in JSON the database along with the associated ranking
#
# Software is free software released under the "GNU Affero General Public License v3.0"
#
# Copyright (c) 2012-2018 Alexandre Dulaunoy - a@foo.be
# Copyright (c) 2015-2018 Pieter-Jan Moreels - pieterjan.moreels@gmail.com
import argparse
import json
import os
import sys
from bson import json_util
runPath = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(runPath, ".."))
from lib.CVEs import CveHandler
from lib.DatabaseLayer import getCVEIDs
argParser = argparse.ArgumentParser(description="Dump database in JSON format")
argParser.add_argument(
"-r", default=False, action="store_true", help="Include ranking value"
)
argParser.add_argument(
"-v", default=False, action="store_true", help="Include via4 map"
)
argParser.add_argument(
"-c", default=False, action="store_true", help="Include CAPEC information"
)
argParser.add_argument(
"-l",
default=False,
type=int,
help="Limit output to n elements (default: unlimited)",
)
args = argParser.parse_args()
rankinglookup = args.r
via4lookup = args.v
capeclookup = args.c
cves = CveHandler(
rankinglookup=rankinglookup, via4lookup=via4lookup, capeclookup=capeclookup
)
for cveid in getCVEIDs(limit=args.l):
item = cves.getcve(cveid=cveid)
if "cvss" in item:
if type(item["cvss"]) == str:
item["cvss"] = float(item["cvss"])
date_fields = ["cvssTime", "modified", "published"]
for field in date_fields:
if field in item:
item[field] = str(item[field])
print(json.dumps(item, sort_keys=True, default=json_util.default))
| 1,713
|
Python
|
.py
| 51
| 30.627451
| 87
| 0.726119
|
cve-search/cve-search
| 2,271
| 587
| 2
|
AGPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,199
|
cve_refs.py
|
cve-search_cve-search/bin/cve_refs.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Lookup NIST CVE Reference Key/Maps from a CVE
#
# Software is free software released under the "GNU Affero General Public License v3.0"
#
# Copyright (c) 2015-2018 Alexandre Dulaunoy - a@foo.be
import argparse
import os
import sys
runPath = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(runPath, ".."))
from lib.Config import Configuration
try:
r = Configuration.getRedisRefConnection()
except:
sys.exit(1)
argparser = argparse.ArgumentParser(description="Lookup the NIST ref database")
argparser.add_argument("-c", help="CVE id to lookup", default=False)
argparser.add_argument(
"-u", action="store_true", help="Enable URL expansion", default=False
)
argparser.add_argument("-v", action="store_true", help="verbose output", default=False)
args = argparser.parse_args()
if not args.c:
sys.exit("CVE id missing")
ref_urls = {
"MS": "https://technet.microsoft.com/library/security/",
"SECUNIA": "http://secunia.com/advisories/",
"SREASON": "http://securityreason.com/security_alert",
"CERT": "http://www.cert.org/advisories",
"BID": "http://www.securityfocus.com/bid/",
"AIXAPART": "",
"ALLAIRE": "",
"APPLE": "",
"ASCEND": "",
"ATSTAKE": "",
"AUSCERT": "",
"BEA": "",
"BINDVIEW": "",
"SECTRACK": "http://www.securitytracker.com/id/",
"MANDRIVA": "http://www.mandriva.com/security/advisories?name=",
}
refs = r.smembers(args.c)
if not refs:
sys.exit("{} has no NIST references".format(args.c))
for ref in refs:
if args.u:
(provider, refid) = ref.split(":", 1)
if provider in ref_urls.keys():
print("{}{}".format(ref_urls[provider], refid))
elif provider == "CONFIRM":
print("{}".format(refid))
else:
print(ref)
else:
print(ref)
| 1,881
|
Python
|
.py
| 58
| 28.396552
| 87
| 0.655991
|
cve-search/cve-search
| 2,271
| 587
| 2
|
AGPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|