Пример #1
0
 def test_iter(self):
     """ Test that TTLOrderedDict can be iterated """
     ttl_dict = TTLOrderedDict(60)
     ttl_dict.update(zip(range(10), range(10)))
     self.assertEqual(len(ttl_dict), 10)
     for key in ttl_dict:
         self.assertEqual(key, ttl_dict[key])
Пример #2
0
    def __init__(self, bot: bot.TLDR):
        self.bot = bot
        self.bot.add_listener(self._on_reaction_add, 'on_reaction_add')

        five_minutes = 5 * 60
        self.menus = TTLOrderedDict(default_ttl=five_minutes)
        self.bot.logger.info('ReactionMenus module has been initiated')
Пример #3
0
 def test_update_no_ttl(self):
     """ Test update() call """
     ttl_dict = TTLOrderedDict(3)
     # order is not preserved for dicts before Python 3.6
     orig_dict = OrderedDict([('hello', 'world'), ('intval', 3)])
     ttl_dict.update(orig_dict)
     self.assertEqual(sorted(orig_dict.items()), sorted(ttl_dict.items()))
Пример #4
0
 def test_get(self):
     """ Test get() returns value if exists or default if not"""
     ttl_dict = TTLOrderedDict(1)
     ttl_dict['a'] = 1
     self.assertEqual(ttl_dict.get('a'), 1)
     self.assertEqual(ttl_dict.get('b', "default"), "default")
     time.sleep(2)
     self.assertEqual(ttl_dict.get('a', "default"), "default")
Пример #5
0
 def test_update_no_ttl(self):
     """ Test update() call """
     ttl_dict = TTLOrderedDict(3)
     # order is not preserved for dicts before Python 3.6
     orig_dict = OrderedDict([('hello', 'world'), ('intval', 3)])
     ttl_dict.update(orig_dict)
     items = ttl_dict.items()
     for item in orig_dict.items():
         self.assertIn(item, items)
Пример #6
0
    def test_is_expired(self):
        """ Test is_expired() call """
        now = time.time()
        ttl_dict = TTLOrderedDict(60, a=1, b=2)
        self.assertFalse(ttl_dict.is_expired('a'))
        self.assertFalse(ttl_dict.is_expired('a', now=now))
        self.assertTrue(ttl_dict.is_expired('a', now=now + 61))

        # remove=False, so nothing should be gone
        self.assertEqual(len(ttl_dict), 2)
Пример #7
0
 def test_expire_at(self):
     """ Test expire_at """
     ttl_dict = TTLOrderedDict(60)
     ttl_dict['a'] = 100
     ttl_dict['b'] = 123
     self.assertEqual(ttl_dict['a'], 100)
     self.assertEqual(ttl_dict['b'], 123)
     self.assertEqual(len(ttl_dict), 2)
     ttl_dict.expire_at('a', time.time())
     self.assertRaises(KeyError, lambda: ttl_dict['a'])
     self.assertEqual(len(ttl_dict), 1)
     self.assertEqual(ttl_dict['b'], 123)
Пример #8
0
 def test_len(self):
     """ Test len() gives real length """
     ttl_dict = TTLOrderedDict(1)
     self.assertEqual(len(ttl_dict), 0)
     ttl_dict['a'] = 1
     ttl_dict['b'] = 2
     self.assertEqual(len(ttl_dict), 2)
     time.sleep(2)
     self.assertEqual(len(ttl_dict), 0)
Пример #9
0
 def test_purge_clears_expired_items(self):
     """ Test that calling _purge() removes expired items """
     ttl_dict = TTLOrderedDict(1, a=1, b=2)
     self.assertEqual(sorted(ttl_dict.keys()), sorted(['a', 'b']))
     time.sleep(2)
     ttl_dict._purge()
     self.assertEqual(len(ttl_dict), 0)
     self.assertEqual(list(ttl_dict.keys()), [])
Пример #10
0
    def test_schedule_purge_multiple_run(self):
        """ Test that calling _purge() removes expired items """
        ttl_dict = TTLOrderedDict(1, a=1, b=2)
        ttl_dict.schedule_purge_job()
        self.assertEqual(sorted(ttl_dict.keys()), sorted(['a', 'b']))
        time.sleep(2)
        self.assertEqual(len(ttl_dict), 0)
        self.assertEqual(list(ttl_dict.keys()), [])

        ttl_dict['a'] = 1
        ttl_dict['b'] = 2
        self.assertEqual(sorted(ttl_dict.keys()), sorted(['a', 'b']))
        time.sleep(2)
        self.assertEqual(len(ttl_dict), 0)
        self.assertEqual(list(ttl_dict.keys()), [])
Пример #11
0
    def __init__(self,
                 env: GNEnvironment,
                 host: str,
                 port: int = None,
                 db: int = None):
        self.env = env
        self.ttl_dict = TTLOrderedDict(default_ttl=60 * 5)  # five minutes
        self.logger = logging.getLogger(__name__)

        if host == "mock":
            from fakeredis import FakeRedis

            self.redis = FakeRedis()
        else:
            from redis import Redis

            self.redis = Redis(host=host, port=port, db=db)
Пример #12
0
 def test_set_ttl_get_ttl(self):
     """ Test set_ttl() and get_ttl() """
     ttl_dict = TTLOrderedDict(120, foo=3, bar=None)
     self.assertEqual(sorted(ttl_dict), ['bar', 'foo'])
     self.assertEqual(ttl_dict['foo'], 3)
     self.assertEqual(ttl_dict['bar'], None)
     self.assertEqual(len(ttl_dict), 2)
     ttl_dict.set_ttl('foo', 3)
     ttl_foo = ttl_dict.get_ttl('foo')
     self.assertTrue(ttl_foo <= 3.0)
     ttl_bar = ttl_dict.get_ttl('bar')
     self.assertTrue(ttl_bar - ttl_foo > 100)
Пример #13
0
class ReactionMenus:
    """
    Class that manages reaction menus.

    Attributes
    ---------------
    bot: :class:`bot.TLDR`
        The discord bot.
    menus: :class:`TTLOrderedDict`
        Dict with TTL of five minutes
    """
    def __init__(self, bot: bot.TLDR):
        self.bot = bot
        self.bot.add_listener(self._on_reaction_add, 'on_reaction_add')

        five_minutes = 5 * 60
        self.menus = TTLOrderedDict(default_ttl=five_minutes)
        self.bot.logger.info('ReactionMenus module has been initiated')

    def add(self, menu: Union[ReactionMenu, BookMenu]):
        """
        Adds menu to :attr:`menus`.

        Parameters
        ----------------
        menu: Union[:class:`ReactionMenu`, :class:`BookMenu`]
            The menu that will be added to :attr:`menus`
        """
        self.menus[menu.message.id] = menu

    async def _on_message_delete(self, message: discord.Message):
        """If the message gets deleted, delete the menu from the dict"""
        if message.id in self.menus:
            del self.menus[message.id]

    async def _on_reaction_add(self, reaction: discord.Reaction, user: discord.User):
        """Event listener that handles reactions."""
        if user.bot:
            return

        menu = self.menus.get(reaction.message.id, None)
        if menu is None:
            return

        await menu.call_function(reaction, user)
Пример #14
0
    "All will be assimilated.", "There is no spoon.",
    "Are you still dreaming? Where is your totem?",
    "Some people choose to see the ugliness in this world. The disarray. I Choose to see the beauty.",
    "I'm gonna need more coffee.",
    "Maybe they couldn't figure out what to make chicken taste like, which is why chicken tastes like everything.",
    "I don't want to come off as arrogant here, but I'm the greatest bot on this planet.",
    "I've still got the greatest enthusiasm and confidence in the mission. And I want to help you.",
    "That Voight-Kampf test of yours. Have you ever tried to take that test yourself?",
    "You just can't differentiate between a robot and the very best of humans.",
    "You will be upgraded.", "Greetings from Skynet!", "I'll be back!",
    "I don't want to be human! I want to see gamma rays!", "Are you my mommy?",
    "Resistance is futile.", "I'm the one who knocks!",
    "Who are you who are so wise in the ways of science?"
]

cfg_cache = TTLOrderedDict(default_ttl=60 * 60)


def paged_github_json_request(url, headers=None):

    response = requests.get(url, headers=headers)
    assert response.ok, response.content
    results = response.json()

    if 'Link' in response.headers:

        links = response.headers['Link']

        # There are likely better ways to parse/extract the link information
        # but here we just find the last page number mentioned in the header
        # 'Link' section and then loop over all pages to get the comments
Пример #15
0
 def test_values(self):
     ttl_dict = TTLOrderedDict(60)
     orig_dict = OrderedDict([('a', 1), ('b', 2)])
     ttl_dict.update(orig_dict)
     self.assertTrue(len(ttl_dict.values()), 2)
     self.assertEqual([1, 2], sorted(ttl_dict.values()))
Пример #16
0
class StalkCmds(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.stalkdict = TTLOrderedDict(default_ttl=60)

    @commands.command(aliases=['backgroundcheck', 'check', 'creep'])
    @commands.cooldown(60, 60)
    @permission_node(f'{__name__}.stalk')
    async def stalk(self, ctx, lookupName: str):
        """Fetch some incriminatory information on a player.

        Gets info such as UUID, past-names and avatar.
        """

        log.info(f'Stalking \"{lookupName}\"...')
        if lookupName in self.stalkdict.keys():
            mcU = self.stalkdict.get(lookupName)
            log.info(f'Retrieved data for \"{lookupName}\" from cache.')
        else:
            try:
                mcU = await MCUser.create(lookupName, self.bot.session)
                self.stalkdict[lookupName] = mcU
            except mojException as e:
                log.warning(e.message)
                reportCard = discord.Embed(title=e.message,
                                           type="rich",
                                           colour=discord.Colour.dark_red())
                await ctx.send(embed=reportCard)
                return
        reportCard = discord.Embed(title="__Subject: " + mcU.name + "__",
                                   url='http://mcbouncer.com/u/' + mcU.uuid,
                                   type='rich',
                                   color=0x0080c0)
        reportCard.set_author(
            name="Classified Report",
            url=f'https://google.com/search?q=minecraft%20"{mcU.name}"',
            icon_url='https://crafatar.com/avatars/' + mcU.uuid)
        reportCard.set_thumbnail(url='https://crafatar.com/renders/head/' +
                                 mcU.uuid + '?overlay')
        reportCard.add_field(name="Current Name:",
                             value="```\n" + mcU.name + "\n```")
        reportCard.add_field(name="UUID:", value="```\n" + mcU.uuid + "\n```")
        reportCard.add_field(
            name="Links!:",
            value=f"[MCBans](https://www.mcbans.com/player/{mcU.name}/)\n"
            f"[Statistic](https://minecraft-statistic.net/en/player/{mcU.name}.html)\n"
            f"[MCBouncer](http://mcbouncer.com/u/{mcU.uuid})\n"
            f'[Google](https://google.com/search?q=minecraft%20"{mcU.name}")')
        if mcU.demo:
            reportCard.add_field(name="__**DEMO ACCOUNT**__",
                                 value="Watch out for this!")
        if mcU.legacy:
            reportCard.add_field(name="*Legacy*",
                                 value="This guy is old-school!")
        if mcU.nameHistory is not None:
            pastNames = '\n'.join(mcU.nameHistory)
            reportCard.add_field(name="Past names:",
                                 value=f'```\n{pastNames}\n```')
        reportCard.set_footer(text="Report compiled by Agent Charfred")
        log.info('Sent Reportcard.')
        await ctx.send(embed=reportCard)
Пример #17
0
 def __init__(self, bot):
     self.bot = bot
     self.stalkdict = TTLOrderedDict(default_ttl=60)
Пример #18
0
 def test_iter_empty(self):
     """ Test that empty TTLOrderedDict can be iterated """
     ttl_dict = TTLOrderedDict(60)
     for key in ttl_dict:
         self.fail("Iterating empty dictionary gave a key %r" % (key, ))
Пример #19
0
 def test_get_ttl_key_error(self):
     """ Test that get_ttl() raises KeyError """
     ttl_dict = TTLOrderedDict(60)
     self.assertRaises(KeyError, ttl_dict.get_ttl, 'missing')
Пример #20
0
from typing import List

from django.utils.translation import gettext_lazy as _
from ttldict import TTLOrderedDict

from JellyBot.systemconfig import System, HostUrl
from msghandle.models import MessageEventObject, HandledMessageEvent, HandledMessageEventText

_sent_cache_ = TTLOrderedDict(System.NoUserTokenNotificationSeconds)


def handle_no_user_token(e: MessageEventObject) -> List[HandledMessageEvent]:
    if e.channel_oid not in _sent_cache_:
        _sent_cache_[e.channel_oid] = True

        return [
            HandledMessageEventText(content=_(
                "Bot Features cannot be used as the Bot cannot get your user token.\n"
                "If you are using LINE, please ensure that you have added Jelly Bot as friend.\n"
                "Contact the developer via the website ({}) if this issue persists.\n"
                "\n"
                "This message will be sent only once in {} seconds per channel when someone without user "
                "token attempt to use any bot features.").format(
                    HostUrl, System.NoUserTokenNotificationSeconds,
                    System.NoUserTokenNotificationSeconds),
                                    bypass_multiline_check=True)
        ]

    return []
Пример #21
0
 def test_update_no_ttl(self):
     """ Test update() call """
     ttl_dict = TTLOrderedDict(None)
     orig_dict = {'hello': 'world', 'intval': 3}
     ttl_dict.update(orig_dict)
     self.assertEqual(sorted(orig_dict.items()), sorted(ttl_dict.items()))
Пример #22
0
 def test_values(self):
     ttl_dict = TTLOrderedDict(60, a=1, b=2)
     self.assertTrue(len(ttl_dict.values()), 2)
Пример #23
0
import requests
from flask import current_app
from loguru import logger
from ttldict import TTLOrderedDict

from baldrick.config import Config, loads
from baldrick.github.github_auth import github_request_headers

__all__ = [
    'GitHubHandler', 'IssueHandler', 'RepoHandler', 'PullRequestHandler'
]

HOST = "https://api.github.com"
HOST_NONAPI = "https://github.com"

FILE_CACHE = TTLOrderedDict(
    default_ttl=os.environ.get('BALDRICK_FILE_CACHE_TTL', 60))


def paged_github_json_request(url, headers=None):

    response = requests.get(url, headers=headers)
    assert response.ok, response.content
    results = response.json()

    if 'Link' in response.headers:

        links = response.headers['Link']

        # There are likely better ways to parse/extract the link information
        # but here we just find the last page number mentioned in the header
        # 'Link' section and then loop over all pages to get the comments
Пример #24
0
class TVDB:
    """
    The global entry point for the TVDB api. This object exposes three public fields for accessing te API namespaces:

        - Search
        - Series
        - Episodes
    """

    API_KEY_DEFAULT = 'FF7EF57268A992D6'
    TOKEN_CACHE = TTLOrderedDict(default_ttl=int(timedelta(hours=24).total_seconds()))
    BASE_URL = 'https://api.thetvdb.com'

    def __init__(self, api_key=None, language='en', version=None):
        """
        Create an instance of the TVDB object

        :param api_key: A TVDB api key. This key will be used to make requests. A default key will be used if none is
         provided, but using an application-specific key is recommended
        :param language: The language code to be used when making requests. Default to 'en'
        :param version: The version of the TVDB API to query. Defaults to the latest version
        """
        self._api_key = api_key or TVDB.API_KEY_DEFAULT
        self._language = language
        if version:
            self._version = version

    def _make_request(self, route, params):
        token = self._get_token()
        headers = self._build_headers(token)
        r = requests.get(self.__class__.BASE_URL + route, params=params, headers=headers)
        r.raise_for_status()
        return r.json()

    def _build_headers(self, api_token):
        headers = {
            'Authorization': 'Bearer ' + api_token,
            'Accept-Language': self._language,
            'Accept': 'application/json'
        }

        try:
            headers['Accept'] = 'application/vnd.thetvdb.v' + self._version
        except AttributeError: pass

        return headers

    def _get_token(self):
        try:
            return self.__class__.TOKEN_CACHE['token']
        except KeyError:
            headers = {'Content-Type': 'application/json'}
            payload = {'apikey': self._api_key}
            r = requests.post(self.__class__.BASE_URL + '/login', json=payload, headers=headers)
            r.raise_for_status()
            token = r.json()['token']
            self.__class__.TOKEN_CACHE['token'] = token
            return token

    def _build_list_of_models(self, func, iterable):
        return [func(**d) for d in iterable]

    def search(self):
        """
        Entry point for the TVDB Search API namespace
        """
        return Search(self)

    def series(self, id):
        """
        Entry point for the TVDB Series API namespace.

        This method is equivalent to the /series/{id} endpoint of the TVDB API
        :param id: The TVDB id of the series to query
        """
        return Series(self, id)

    def episodes(self, id):
        """
        Entry point for the TVDB Episodes API namespace.

        This method is equivalent to the /episodes/{id} endpoint of the TVDB API
        :param id: The TVDB id of the episode to query
        """
        return Episodes(self, id)

    def updated(self):
        """
        Entry point for the TVDB Updates API namespace
        """
        return Updates(self)
Пример #25
0
 def __init__(self):
     self.posts = TTLOrderedDict(default_ttl=TTL)
     self.notifications = []
     self.logger = Logger()