Skip to content

add new predefined filter 'Filters.Date' to filter on message age. #1978

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions telegram/ext/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"""This module contains the Filters for use with the MessageHandler class."""

import re
import time

from abc import ABC, abstractmethod
from future.utils import string_types
Expand Down Expand Up @@ -1397,3 +1398,33 @@ def filter(self, update):
channel_posts: Updates with either :attr:`telegram.Update.channel_post` or
:attr:`telegram.Update.edited_channel_post`
"""

class date(BaseFilter):
"""Filters messages to allow only those which are not older than a specified number
of sec ago.

Examples:
``MessageHandler(Filters.date(seconds_ago=15), callback_method)``

Args:
seconds_ago(:obj:`int`, optional): Max time diff between when the message was sent
(message.date) and 'now' for message to be allowed through, in seconds.

Raises:
ValueError: If seconds_ago not set or smaller than 2.
"""

def __init__(self, seconds_ago=None):
if not bool(seconds_ago):
raise ValueError('seconds_ago must be used')
elif seconds_ago is not None and isinstance(seconds_ago, int) and seconds_ago < 2:
raise ValueError('seconds_ago must be 2 at minimum')
elif seconds_ago is not None and isinstance(seconds_ago, int) and seconds_ago >= 2:
self.seconds_ago = seconds_ago
else:
# should never end up here
raise ValueError('Unknown error!')

def filter(self, message):
# msg.date > (now - seconds_ago)
return bool(int(message.date.timestamp()) > (int(time.time()) - int(self.seconds_ago)))
12 changes: 12 additions & 0 deletions tests/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@ def test_filters_text(self, update):
update.message.text = '/test'
assert (Filters.text)(update)

def test_filters_date_init(self):
with pytest.raises(ValueError, match='must be used'):
Filters.date(seconds_ago=0)
with pytest.raises(ValueError, match='at minimum'):
Filters.date(seconds_ago=1)

def test_filters_date(self, update):
update.message.date = datetime.datetime.utcnow()
assert Filters.date(seconds_ago=10)(update)
update.message.date = datetime.datetime.utcnow() - datetime.timedelta(seconds=100)
assert not Filters.date(seconds_ago=10)(update)

def test_filters_text_strings(self, update):
update.message.text = '/test'
assert Filters.text({'/test', 'test1'})(update)
Expand Down