<commit_before>from celery import Task
from telegram.ext.messagehandler import Filters
from marvinbot.models import User
from marvinbot.utils import get_message
from marvinbot.core import get_adapter
from datetime import datetime
import logging


log = logging.getLogger(__name__)


class Handler(object):
    def __init__(self, callback, adapter=None, allow_edits=True, call_async=False, discard_threshold=300):
        """Initialize this handler.

        Parameters:
        - `allow_edits`: if enabled, handler will also accept edits.
        - `call_async`: if callback is a celery task, call asynchronously.
          Else call in the current worker.
        - `discard_threshold`: Messages older than X seconds will get discarded.
        '"""
        self.callback = callback
        if not self.callback:
            raise ValueError('Callback is required')
        self.allow_edits = allow_edits
        self.call_async = call_async
        self.discard_threshold = discard_threshold
        self.adapter = adapter or get_adapter()

    def get_registered_user(self, message):
        """Return a registered User instance for message.

        Returns None if the user isn't registered."""
        user = message.from_user
        user_id = user.id

        return User.by_id(user_id)

    def can_handle(self, update):
        """Return True/False if this handler can process the given update."""
        message = get_message(update, self.allow_edits)
        age = datetime.now() - message.date
        if self.discard_threshold and age.total_seconds() > self.discard_threshold:
            return False

        return self.validate(message)

    def validate(self, message):
        """Return True/False if this handler can process the given update.

        You need to override this method."""
        raise NotImplementedError

    def process_update(self, update):
        """Process the given update.

        Callbacks are expected to get a hold of the adapter (it's a singleton).
        Override if you need to do anything other than calling the callback and then
        call the parent class method."""
        self.do_call(update)

    def do_call(self, update, *args, **kwargs):
        if self.call_async and isinstance(self.callback, Task) and self.adapter.async_available:
            self.callback.s(update, *args, **kwargs).apply_async()
        else:
            self.callback(update, *args, **kwargs)


class CommandHandler(Handler):
    def __init__(self, command, callback, required_roles=None, *args, **kwargs):
        self.command = command
        self.required_roles = None
        if required_roles:
            if not isinstance(required_roles, list):
                self.required_roles = [required_roles]
            else:<commit_msg>Fix derp: send args/kwargs to do_call<commit_after>from celery import Task
from telegram.ext.messagehandler import Filters
from marvinbot.models import User
from marvinbot.utils import get_message
from marvinbot.core import get_adapter
from datetime import datetime
import logging


log = logging.getLogger(__name__)


class Handler(object):
    def __init__(self, callback, adapter=None, allow_edits=True, call_async=False, discard_threshold=300):
        """Initialize this handler.

        Parameters:
        - `allow_edits`: if enabled, handler will also accept edits.
        - `call_async`: if callback is a celery task, call asynchronously.
          Else call in the current worker.
        - `discard_threshold`: Messages older than X seconds will get discarded.
        '"""
        self.callback = callback
        if not self.callback:
            raise ValueError('Callback is required')
        self.allow_edits = allow_edits
        self.call_async = call_async
        self.discard_threshold = discard_threshold
        self.adapter = adapter or get_adapter()

    def get_registered_user(self, message):
        """Return a registered User instance for message.

        Returns None if the user isn't registered."""
        user = message.from_user
        user_id = user.id

        return User.by_id(user_id)

    def can_handle(self, update):
        """Return True/False if this handler can process the given update."""
        message = get_message(update, self.allow_edits)
        age = datetime.now() - message.date
        if self.discard_threshold and age.total_seconds() > self.discard_threshold:
            return False

        return self.validate(message)

    def validate(self, message):
        """Return True/False if this handler can process the given update.

        You need to override this method."""
        raise NotImplementedError

    def process_update(self, update, *args, **kwargs):
        """Process the given update.

        Callbacks are expected to get a hold of the adapter (it's a singleton).
        Override if you need to do anything other than calling the callback and then
        call the parent class method."""
        self.do_call(update, *args, **kwargs)

    def do_call(self, update, *args, **kwargs):
        if self.call_async and isinstance(self.callback, Task) and self.adapter.async_available:
            self.callback.s(update, *args, **kwargs).apply_async()
        else:
            self.callback(update, *args, **kwargs)


class CommandHandler(Handler):
    def __init__(self, command, callback, required_roles=None, *args, **kwargs):
        self.command = command
        self.required_roles = None
        if required_roles:
            if not isinstance(required_roles, list):
                self.required_roles = [required_roles]
            else:
{'fraction_non_alphanumeric': 0.08190883190883191, 'fraction_numerical': 0.0010683760683760685, 'mean_word_length': 2.7723304231027535, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3909992', 'n_tokens_mistral': 1510, 'n_tokens_neox': 1447, 'n_words': 498}