Code Monkey home page Code Monkey logo

django-slack's Introduction

django-slack's People

Contributors

akestner avatar aleksanb avatar ataylor32 avatar avelis avatar chesstrian avatar cleitondelima avatar clokep avatar djailla avatar garnertb avatar inglesp avatar jheld avatar joshblum avatar l-nd-n avatar lamby avatar lociii avatar lutoma avatar lvpython avatar michael-k avatar nejczupec avatar peterjclaw avatar serdarjan1995 avatar simonbarendse avatar stianjensen avatar taskle avatar thomwiggers avatar trojkat avatar yxy avatar zpdldhkdl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-slack's Issues

Indentation error in 4.2.4

There seems to have been an indentation error introduced in the latest release an hour ago. See below:

  File "/usr/local/lib/python2.7/site-packages/django_slack/api.py", line 86
    "URL is not specified"
    ^
IndentationError: unexpected indent

Error on initialisation (Python 3)

Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/ttn-dev/.venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/home/ttn-dev/.venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 312, in execute
    django.setup()
  File "/home/ttn-dev/.venv/lib/python3.4/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/ttn-dev/.venv/lib/python3.4/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/home/ttn-dev/.venv/lib/python3.4/site-packages/django/apps/config.py", line 86, in create
    module = import_module(entry)
  File "/home/ttn-dev/.venv/lib/python3.4/importlib/__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1129, in _exec
  File "<frozen importlib._bootstrap>", line 1471, in exec_module
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "/home/ttn-dev/.venv/lib/python3.4/site-packages/django_slack/__init__.py", line 244, in <module>
    from .api import slack_message
  File "/home/ttn-dev/.venv/lib/python3.4/site-packages/django_slack/api.py", line 10, in <module>
    backend = from_dotted_path(app_settings.BACKEND)()
  File "/home/ttn-dev/.venv/lib/python3.4/site-packages/django_slack/utils.py", line 16, in from_dotted_path
    return getattr(__import__(module, {}, {}, (attr,)), attr)
  File "/home/ttn-dev/.venv/lib/python3.4/site-packages/django_slack/backends.py", line 27
    print "I: Slack message:"
                            ^
SyntaxError: Missing parentheses in call to 'print'

Looks like there's some problems with Python 3 support?

Django is unable to initialize when slack.com is not available

Django is unable to initialize when slack.com is not available or when the target channel is missing.
Suggest that a failure in the API key, or other environmental problems will post errors into the django log whilst still allowing the system to load and function without.

Error when trying to log DisallowedHost error

I'm trying to log DisallowedHost errors to slack with the following logging config:

[...]
    'handlers': {
        'slack': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django_slack.log.SlackExceptionHandler',
        },
     },
     'loggers': {
        'django.security.DisallowedHost': {
            'handlers': ['slack'],
            'propagate': False,
           'level': 'ERROR',
        },
}
[...]

The problem is that when trying to get the error traceback, the same exception is raised (django.core.exceptions.DisallowedHost)

[...]
django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'localhost'. You may need to add 'localhost' to ALLOWED_HOSTS.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.4/wsgiref/handlers.py", line 137, in run
    self.result = application(self.environ, self.start_response)
  File "/virtualenv/lib/python3.4/site-packages/whitenoise/base.py", line 119, in __call__
    return self.application(environ, start_response)
  File "/virtualenv/lib/python3.4/site-packages/django/core/handlers/wsgi.py", line 189, in __call__
    response = self.get_response(request)
  File "/virtualenv/lib/python3.4/site-packages/django/core/handlers/base.py", line 204, in get_response
    'request': request
  File "/usr/lib/python3.4/logging/__init__.py", line 1303, in error
    self._log(ERROR, msg, args, **kwargs)
  File "/usr/lib/python3.4/logging/__init__.py", line 1409, in _log
    self.handle(record)
  File "/usr/lib/python3.4/logging/__init__.py", line 1419, in handle
    self.callHandlers(record)
  File "/usr/lib/python3.4/logging/__init__.py", line 1481, in callHandlers
    hdlr.handle(record)
  File "/usr/lib/python3.4/logging/__init__.py", line 853, in handle
    self.emit(record)
  File "/virtualenv/lib/python3.4/site-packages/django_slack/log.py", line 53, in emit
    reporter.get_traceback_text(),
  File "/virtualenv/lib/python3.4/site-packages/django/views/debug.py", line 390, in get_traceback_text
    return t.render(c)
  File "/virtualenv/lib/python3.4/site-packages/django/template/base.py", line 209, in render
    return self._render(context)
  File "/virtualenv/lib/python3.4/site-packages/django/template/base.py", line 201, in _render
    return self.nodelist.render(context)
  File "/virtualenv/lib/python3.4/site-packages/django/template/base.py", line 903, in render
    bit = self.render_node(node, context)
  File "/virtualenv/lib/python3.4/site-packages/django/template/debug.py", line 79, in render_node
    return node.render(context)
  File "/virtualenv/lib/python3.4/site-packages/django/template/defaulttags.py", line 329, in render
    return nodelist.render(context)
  File "/virtualenv/lib/python3.4/site-packages/django/template/base.py", line 903, in render
    bit = self.render_node(node, context)
  File "/virtualenv/lib/python3.4/site-packages/django/template/debug.py", line 79, in render_node
    return node.render(context)
  File "/virtualenv/lib/python3.4/site-packages/django/template/debug.py", line 89, in render
    output = self.filter_expression.resolve(context)
  File "/virtualenv/lib/python3.4/site-packages/django/template/base.py", line 647, in resolve
    obj = self.var.resolve(context)
  File "/virtualenv/lib/python3.4/site-packages/django/template/base.py", line 787, in resolve
    value = self._resolve_lookup(context)
  File "/virtualenv/lib/python3.4/site-packages/django/template/base.py", line 847, in _resolve_lookup
    current = current()
  File "/virtualenv/lib/python3.4/site-packages/django/http/request.py", line 151, in build_absolute_uri
    host=self.get_host(),
  File "/virtualenv/lib/python3.4/site-packages/django/http/request.py", line 101, in get_host
    raise DisallowedHost(msg)
django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header

Any ideas how to avoid raising this when trying to log the error?

postEphemeral support

It would be nice to be able to specify method of delivering the message so we can send ephemeral or public messages.

Token should not be required if incoming webhook url is provided

Hi,

a token is not required if an endpoint url for an incoming webhook url is provided.
If you create an incoming webhook in slack, you will see that there is a curl example for this endpoint
which doesnt send a token. The webhook url is enough in this case.

python3 compatibility

Hi,

have you already thought about how to make django-slack compatible with django 1.9?
looks like django don't like the slack_message function imported at load time.
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

I know there is still some time until django 1.9 release, but maybe you have thought about it already?

bastian

support for django versions lower then 1.8

in the setup.py it says:

install_requires=(
     'Django>=1.8.0',

Do you know of any specific problems with lower versions?

We got a large project using Django 1.6 unfortunately.. so I'll try to see if it works, but if you know of any specific problems it would be helpful

Problem with celery

Hi, I'm using this slack integration in my project. I have all dockerized, and the main application container works fine, but, I'm also using celery in the project, and with celery version 5.0.0 I see this error in logs in the worker containers:

Traceback (most recent call last):
  File "/usr/local/bin/celery", line 8, in <module>
    sys.exit(main())
  File "/usr/local/lib/python3.9/site-packages/celery/__main__.py", line 15, in main
    sys.exit(_main())
  File "/usr/local/lib/python3.9/site-packages/celery/bin/celery.py", line 150, in main
    return celery(auto_envvar_prefix="CELERY")
  File "/usr/local/lib/python3.9/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1259, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/usr/local/lib/python3.9/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/click/decorators.py", line 21, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/celery/bin/worker.py", line 323, in worker
    worker = app.Worker(
  File "/usr/local/lib/python3.9/site-packages/celery/worker/worker.py", line 94, in __init__
    self.app.loader.init_worker()
  File "/usr/local/lib/python3.9/site-packages/celery/loaders/base.py", line 111, in init_worker
    self.import_default_modules()
  File "/usr/local/lib/python3.9/site-packages/celery/loaders/base.py", line 105, in import_default_modules
    raise response
  File "/usr/local/lib/python3.9/site-packages/celery/utils/dispatch/signal.py", line 276, in send
    response = receiver(signal=self, sender=sender, **named)
  File "/usr/local/lib/python3.9/site-packages/vine/promises.py", line 160, in __call__
    return self.throw()
  File "/usr/local/lib/python3.9/site-packages/vine/promises.py", line 157, in __call__
    retval = fun(*final_args, **final_kwargs)
  File "/usr/local/lib/python3.9/site-packages/celery/app/base.py", line 640, in _autodiscover_tasks
    return self._autodiscover_tasks_from_fixups(related_name)
  File "/usr/local/lib/python3.9/site-packages/celery/app/base.py", line 649, in _autodiscover_tasks_from_fixups
    return self._autodiscover_tasks_from_names([
  File "/usr/local/lib/python3.9/site-packages/celery/app/base.py", line 644, in _autodiscover_tasks_from_names
    return self.loader.autodiscover_tasks(
  File "/usr/local/lib/python3.9/site-packages/celery/loaders/base.py", line 219, in autodiscover_tasks
    mod.__name__ for mod in autodiscover_tasks(packages or (),
  File "/usr/local/lib/python3.9/site-packages/celery/loaders/base.py", line 245, in autodiscover_tasks
    return [find_related_module(pkg, related_name) for pkg in packages]
  File "/usr/local/lib/python3.9/site-packages/celery/loaders/base.py", line 245, in <listcomp>
    return [find_related_module(pkg, related_name) for pkg in packages]
  File "/usr/local/lib/python3.9/site-packages/celery/loaders/base.py", line 270, in find_related_module
    raise e
  File "/usr/local/lib/python3.9/site-packages/celery/loaders/base.py", line 266, in find_related_module
    return importlib.import_module(module_name)
  File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 790, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/usr/local/lib/python3.9/site-packages/django_slack/tasks.py", line 1, in <module>
    from celery import task
  File "/usr/local/lib/python3.9/site-packages/celery/local.py", line 497, in __getattr__
    module = __import__(self._direct[name], None, None, [name])
ModuleNotFoundError: No module named 'celery.task'

Changelog?

First, thanks for making this package! ๐Ÿ‘

I appreciate that you push new releases quickly after merging PRs, but is there a changelog available? It's hard to tell how big of a change was made between versions without seeing a list of changes somewhere.

Sorry if it's available somewhere already and I missed it! Thanks.

Uploading a file with a message

I recently needed to implement a new feature where I uploaded a CSV file to Slack along with a the message I was sending. I was not able to implement this using django-slack natively, so had to access the files.upload Slack API directly instead. I haven't yet thought of a clean way to do it, but what are your thoughts on providing some sort of support for file uploads in this project?

Wrong Subject for Error Messages

Hi,

I am getting the Subject as

\u001b[31;1m"POST /users/ HTTP/1.1" 400 184\u001b[0m

or the traceback for Slack handler whereas all other have correct Error messages.

How can I fix this?

'Loader' object is not iterable

Installed and configured django-slack and I get the follow exception when I add the django.template.loaders.app_directories.Loader, to my TEMPLATES

TypeError
'Loader' object is not iterable
/Users/tanner/.local/share/virtualenvs/cribbing-check-N6-Q5UUH/lib/python3.8/site-packages/django/template/context.py, line 244, in bind_template
/Users/tanner/.local/share/virtualenvs/cribbing-check-N6-Q5UUH/bin/python
3.8.5
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',

    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.github',

    'django_q',
    'django_slack',
    'storages',
]
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.request',

                'django.template.loaders.app_directories.Loader',
            ],
        },
    },
]

$ pip3 freeze | grep slack
django-slack==5.15.2

$ pip3 freeze | grep Django
Django==3.1.2

$ python -V
Python 3.8.5

$ sw_vers
ProductName: Mac OS X
ProductVersion: 10.14.6

AttributeError: 'dict' object has no attribute 'file_charset'

I followed simple example on from the docs, however, getting the error

  File "...../handlers.py", line 61, in request_arrived
    }, channel='userrequest', username='vdpo')
  File "...../e/lib/python3.6/site-packages/django_slack/api.py", line 76, in slack_message
    django_slack='django_slack/{}'.format(k),
  File ".....//lib/python3.6/site-packages/django/template/loader.py", line 61, in render_to_string
    template = get_template(template_name, using=using)
  File ".....//lib/python3.6/site-packages/django/template/loader.py", line 15, in get_template
    return engine.get_template(template_name)
  File "...../e/lib/python3.6/site-packages/django/template/loaders/base.py", line 24, in get_template
    contents = self.get_contents(origin)
  File ".....//lib/python3.6/site-packages/django/template/loaders/filesystem.py", line 23, in get_contents
    with open(origin.name, encoding=self.engine.file_charset) as fp:
AttributeError: 'dict' object has no attribute 'file_charset'

template:

{% extends django_slack %}

{% block text %}
Message text here: {{ foo }}
{% endblock %}

call

 slack_message('message.slack', {
            'foo': 'hello',
}, channel='bottest', username='mybot')

Slack message attachments is JSON encoded twice when using custom endpoint url.

The two If checks for attachments are located here:
https://github.com/lamby/django-slack/blob/master/django_slack/api.py#L59
and
https://github.com/lamby/django-slack/blob/master/django_slack/api.py#L67

In the event that you want to send a message attachment with custom endpoint url. The payload data will in turn encode the attachments value twice.

Slack in turn ignores the attachment value and does not display the richly formatted messages.

Over-aggressive HTML entity escaping

By default, django-slack escapes all HTML entites (well really Django templates do, but that's essentially the same thing here). This is documented, but the documentation should probably be expanded to say that only <, > and & should be escaped. In fact the slack documentation says NOT to escape other characters:

That's it. Don't HTML entity-encode the entire message. Of course, when you send your message using URL-encoding, you'll still need to URL encode the ampersand.

Specifically, I was running into an issue where I had a message with a single quote (') that was showing up as an entity in slack (&#39;). The examples in the documentation show usage of the safe templatetag, but it was not clear to me why this was happening. Calling this out explicitly would be nice.

I'm unsure if this is a documentation or a code issue, but the work around is to pass variables through the safe templatetag or disable autoescape.

No (obvious) way to test messages

As far as I can see, the only way to test that a message has been sent is through mocking.

Would you accept a patch that added a backend that looked like this?

class TestBackend(Backend):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.reset_messages()

    def send(self, url, data, **kwargs):
        self.messages.append(data)

    def reset_messages(self):
        self.messages = []

    def retrieve_messages(self):
        messages = self.messages
        self.reset_messages()
        return messages

This could be used in more-or-less the same way as Django's core.mail.backends.locmem.EmailBackend, with the proviso that you need to manually call .reset_messages() on the backend before testing that something has sent a message.

Overriding endpoint_url per message is not working.

Feature:
You can override on a per-message level by specifying a {% block endpoint_url %}{% endblock %} in your message template.

is not working.

in my template i have a block with incoming webhook url:
{% block endpoint_url %}
https://hooks.slack.com/services/xxxxx/xxxx/xxxxx
{% endblock %}

settings:
SLACK_CHANNEL = ''
SLACK_USERNAME = 'test'

error:
File "/Users/xx/.virtualenvs/xx-web/lib/python2.7/site-packages/django_slack/api.py", line 97, in slack_message
raise ValueError("channel parameter is required if custom "
ValueError: channel parameter is required if custom endpoint URL is not specified

Installation exception (Python 3)

Context

Name Version
Os OS X 10.11.1
Allauth 0.23.0.final.0
Crispy_Forms 1.5.2
Debug Toolbar 1.4
Django 1.8.5
Django_Extensions 1.5.7
Message queue 1.0.0
Python 3.4.1

What I did

$ pip install django-slack
Added INSTALLED_APPS += ('django_slack', ) to my settings.
$ ./manage.py runserver

Traceback

...
  File "/Users/eraldo/.virtualenvs/colegend/lib/python3.4/site-packages/django/apps/registry.py", line 137, in get_app_configs
    self.check_apps_ready()
  File "/Users/eraldo/.virtualenvs/colegend/lib/python3.4/site-packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

Process finished with exit code 1

Debugging

To find out what went wrong, I did:

import django_slack

That got me this trace:

  File "/Users/eraldo/.virtualenvs/colegend/lib/python3.4/site-packages/django_slack/backends.py", line 3, in <module>
    import urllib2
ImportError: No module named 'urllib2'

Some research later I found the suggested fix:
http://stackoverflow.com/questions/2792650/python3-error-import-error-no-module-name-urllib

Action

I would love your app to work with python 3.
I am not used to doing things like pull requests.

So Chris, how shall we proceed? :D

Friendly greetings from Berlin..
Eraldo

Can't override token per message

According to the docs, you can override on a per-message level by specifying a {% block token %}{% endblock %} in your message templates. But when I try this, I get the following error: ValueError: token parameter is required if custom endpoint URL is not specified.

It seems slack_message does not look for a token override in the message template, as render is not specified for the token param in the slack_message method: https://github.com/lamby/django-slack/blob/ea71627729e9c325914181f25ce7507a37c42a35/django_slack/api.py
render should be true for the token for it to be able to be overriden per message, right?

This looks to be the case for other params as well, e.g. icon_url, icon_emoji etc.

Unable to get the response of Slack API

Currently, django-slack does not provide the response of the Slack API, making it impossible to update a sent message afterwards (which requires the ts value from the response).

Is this specially designed so, or just a missing feature?

Unable to use override_settings

It seems that django-slack caches all of the settings from django.conf.settings as import time, this means that using the override_settings decorator/context manager will not work.

I took a whack at fixing this, but ran into issues.

What needs to be fixed is to actually query each setting from django.conf.settings when requested inside of django.app_settings. Also backend needs to not be cached so it can be overridden:

diff --git a/django_slack/api.py b/django_slack/api.py
--- a/django_slack/api.py
+++ b/django_slack/api.py
@@ -6,7 +6,9 @@ from django.template.loader import render_to_string
 from . import app_settings
 from .utils import from_dotted_path

-backend = from_dotted_path(app_settings.BACKEND)()
+def _get_backend():
+    return from_dotted_path(app_settings.BACKEND)()

 def slack_message(template, context=None, attachments=None, fail_silently=app_settings.FAIL_SILENTLY):
     data = {}
@@ -102,7 +104,7 @@ def slack_message(template, context=None, attachments=None, fail_silently=app_se
         data = {'payload': json.dumps(data)}

     try:
-        backend.send(endpoint_url, data)
+        _get_backend().send(endpoint_url, data)
     except Exception:
         if not fail_silently:
             raise

Of course this means the backend will get re-created each time, this looks like it would be an issue for the RequestsBackend, which re-uses a single session... This could be cached, which would at least give the user one chance to use override_settings, which would work for my use-case. ๐Ÿ˜„

Clarification on how to obtain a production token

During the development of my Django project, I've been using a test token from Slack, since that's what Slack says to do here (emphasis mine):

While developing or testing your app, you may use test tokens using our test token generator.

It has been working fine. But now that I'm ready to go live with my Django project, I'm not sure what to do. I created a Slack app at https://api.slack.com/apps and saw that the app has a client ID and a client secret, but that doesn't seem like what I need for django-slack. Would you mind updating the documentation to clarify where to get a Slack token that's meant for production? Thank you!

Logging messages not showing up in Slack

I am not seeing any logging messages in my target Slack channel and am trying to debug what's going on. I don't see any trace messages on the Python/Django side, so not sure where to look now, please let me know if you have any thoughts. My setup is below.

Slack settings in settings.py

SLACK_TOKEN='[my toket is here]'
SLACK_CHANNEL='#logs-info'
SLACK_USERNAME='django-logger'
SLACK_FAIL_SILENTLY=False

Logger settings (not require_debug_false is off for testing):

    'loggers': {
        'django.request': {
            'handlers': ['console'],
            'level': 'ERROR',
            'propagate': False,
        },
        'docnavapp': {
            'handlers': ['console', 'slack_admins'],
            'level': 'DEBUG',
            'propagate': False
        }
    },
    'handlers': {
        'console':{
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'filters': ['request_id'],
            'formatter': 'standard'
        },
        'slack_admins': {
            'level': 'DEBUG',
            # 'filters': ['require_debug_false'],
            'filters': [],
            'class': 'django_slack.log.SlackExceptionHandler',
        },
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }

    }

Then I run:

./manage.py shell

import logging
logger = logging.getLogger("docnavapp")
logger.debug('Testing message')

But get no message in my slack channel #logs-info

RemovedInDjango20Warning: django.utils.functional.allow_lazy() is deprecated in favor of django.utils.functional.keep_lazy()

I'm seeing the following on one of my projects running Django 1.10.5 with django-slack 5.7.1.

/usr/local/venv/local/lib/python2.7/site-packages/django_slack/templatetags/django_slack.py:27:
RemovedInDjango20Warning: django.utils.functional.allow_lazy() is deprecated in favor of django.utils.functional.keep_lazy()

Looking at the docs it looks like allow_lazy is only in 1.10, so probably just needs a:

try:
    from django.utils.functional import keep_lazy as allow_lazy
except ImportError
    from django.utils.functional import allow_lazy

Error in UrllibBackend with Django 2.1

Hi there,

I just found that when running with the UrllibBackend under Django 2.1, I get an error when using slack_message

AttributeError: 'bool' object has no attribute 'encode'

This is because the value of the SLACK_AS_USER setting is passed into the django.http.request.urlencode function in its "raw" form and unlike in previous versions of Django, where it got converted into string, Django 2.1 tries to run .encode directly on it.

The fix should be fairly easy - just convert the values into strings before url-encoding, but as there may be unforeseen consequences, I would rather leave it to someone who knows the codebase better.

Best regards
Beda

p.s.- If SLACK_AS_USER is set to True than there is a simple workaround by changing this value to string in settings SLACK_AS_USER='True'. Another workaround is to switch to RequestsBackend which does not have this problem.

Pip installs 0.1 by default.

I would expect to get version 4.

$ pip freeze | grep slack
$ pip install django-slack
Downloading/unpacking django-slack
Downloading django-slack-0.0.1.tar.gz
...
Installing collected packages: django-slack
  Running setup.py install for django-slack
Successfully installed django-slack
Cleaning up...
$ pip freeze | grep slack
django-slack==0.0.1

EncodeError with CeleryBackend using Python 3.5

Hi,

I get the following error using the CeleryBackend on Python 3.5:

File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.5/site-packages/django/contrib/admin/options.py" in wrapper
  618.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/contrib/admin/sites.py" in inner
  233.             return view(request, *args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/contrib/admin/options.py" in change_view
  1521.         return self.changeform_view(request, object_id, form_url, extra_context)
File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper
  34.             return bound_func(*args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py" in bound_func
  30.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/local/lib/python3.5/contextlib.py" in inner
  30.                 return func(*args, **kwds)
File "/usr/local/lib/python3.5/site-packages/django/contrib/admin/options.py" in changeform_view
  1469.                 self.save_model(request, new_object, form, not add)
File "/app/hq/admin/event.py" in save_model
  58.             'change': change,
File "/usr/local/lib/python3.5/site-packages/django_slack/api.py" in slack_message
  114.         backend.send(endpoint_url, data, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django_slack/backends.py" in send
  65.         self._send.delay(*args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/celery/app/task.py" in delay
  453.         return self.apply_async(args, kwargs)
File "/usr/local/lib/python3.5/site-packages/celery/app/task.py" in apply_async
  565.             **dict(self._get_exec_options(), **options)
File "/usr/local/lib/python3.5/site-packages/celery/app/base.py" in send_task
  354.                 reply_to=reply_to or self.oid, **options
File "/usr/local/lib/python3.5/site-packages/celery/app/amqp.py" in publish_task
  310.             **kwargs
File "/usr/local/lib/python3.5/site-packages/kombu/messaging.py" in publish
  165.             compression, headers)
File "/usr/local/lib/python3.5/site-packages/kombu/messaging.py" in _prepare
  241.              body) = dumps(body, serializer=serializer)
File "/usr/local/lib/python3.5/site-packages/kombu/serialization.py" in dumps
  164.             payload = encoder(data)
File "/usr/local/lib/python3.5/contextlib.py" in __exit__
  77.                 self.gen.throw(type, value, traceback)
File "/usr/local/lib/python3.5/site-packages/kombu/serialization.py" in _reraise_errors
  59.         reraise(wrapper, wrapper(exc), sys.exc_info()[2])
File "/usr/local/lib/python3.5/site-packages/kombu/five.py" in reraise
  131.             raise value.with_traceback(tb)
File "/usr/local/lib/python3.5/site-packages/kombu/serialization.py" in _reraise_errors
  55.         yield
File "/usr/local/lib/python3.5/site-packages/kombu/serialization.py" in dumps
  164.             payload = encoder(data)
File "/usr/local/lib/python3.5/site-packages/anyjson/__init__.py" in dumps
  141.         return implementation.dumps(value)
File "/usr/local/lib/python3.5/site-packages/anyjson/__init__.py" in dumps
  89.             raise TypeError(TypeError(*exc.args)).with_traceback(sys.exc_info()[2])
File "/usr/local/lib/python3.5/site-packages/anyjson/__init__.py" in dumps
  87.             return self._encode(data)
File "/usr/local/lib/python3.5/json/__init__.py" in dumps
  230.         return _default_encoder.encode(obj)
File "/usr/local/lib/python3.5/json/encoder.py" in encode
  198.         chunks = self.iterencode(o, _one_shot=True)
File "/usr/local/lib/python3.5/json/encoder.py" in iterencode
  256.         return _iterencode(o, 0)
File "/usr/local/lib/python3.5/json/encoder.py" in default
  179.         raise TypeError(repr(o) + " is not JSON serializable")

Exception Type: EncodeError at /core/event/1/
Exception Value: b'Hello world' is not JSON serializable

Apparently, the template contents are returned as a Bytes literal instead of a string:

self._send.delay(*args, **kwargs):

('https://slack.com/api/chat.postMessage',
 {'channel': '#general',
  'text': b'Hello world',
  'token': 'xoxp-xxx',
  'username': 'xxx'})

Any idea?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.