def quote(bot: DeltaBot, payload: str, message: Message,
          replies: Replies) -> None:
    """Get Wikiquote quotes.

    Search in Wikiquote or get the quote of the day if no text is given.
    Example: `/quote Richard Stallman`
    """
    locale = _get_locale(bot, message.get_sender_contact().addr)
    if locale in wq.supported_languages():
        lang = locale
    else:
        lang = None
    if payload:
        authors = wq.search(payload, lang=lang)
        if authors:
            if payload.lower() == authors[0].lower():
                author = authors[0]
            else:
                author = choice(authors)
            text = f'"{choice(wq.quotes(author, max_quotes=200, lang=lang))}"\n\n― {author}'
        else:
            text = f"No quote found for: {payload}"
    else:
        _quote, author = wq.quote_of_the_day(lang=lang)
        text = f'"{_quote}"\n\n― {author}'

    replies.add(text=text)
Exemplo n.º 2
0
    def test_quotd_all_langs(self):
        logger.info('\n========= QOTD =========\n')
        for lang in wikiquote.supported_languages():
            logger.info(lang.upper() + ':')
            quote, author = wikiquote.quote_of_the_day(lang=lang)
            logger.info('- quote: ' + quote)
            logger.info('- author: ' + author)

            self.assertTrue(len(quote) > 0 and len(author) > 0)
Exemplo n.º 3
0
    def test_normal_quotes(self):

        query_by_lang = defaultdict(lambda: "Barack Obama")
        # Special case: The hebrew wikiquote doesn't support searches in English
        query_by_lang["he"] = "ברק אובמה"

        for lang in wikiquote.supported_languages():
            quotes = wikiquote.quotes(query_by_lang[lang], lang=lang)
            self.assertTrue(len(quotes) > 0)
Exemplo n.º 4
0
def __init_quote_lang__(lang: str = 'en'):
    try:
        l = db[const.QUOTE_LANG_DB_KEY]
        if (l in wikiquote.supported_languages()):
            return l
        else:
            raise KeyError
    except KeyError:
        db[const.QUOTE_LANG_DB_KEY] = lang
        return lang
Exemplo n.º 5
0
    def test_search(self):

        query_by_lang = defaultdict(lambda: "Matrix")
        special_cases = {
            # The hebrew wikiquote doesn't support searches in English
            "he": "מטריקס",
        }

        query_by_lang.update(special_cases)

        for lang in wikiquote.supported_languages():
            results = wikiquote.search(query_by_lang[lang], lang=lang)
            self.assertTrue(len(results) > 0)
Exemplo n.º 6
0
async def lang(ctx, new_lang: str = None):
    global quote_lang
    if (new_lang == None):
        await ctx.send(f"No param was given! Language is {quote_lang}")
        return
    try:
        l = new_lang.lower()
        if (l in wikiquote.supported_languages()):
            db[const.QUOTE_LANG_DB_KEY] = l
            quote_lang = l
            await ctx.send(f"Quote Language updated => {quote_lang}")
        else:
            await ctx.send(
                f"Quote Language '{l}' is not supported. Language is {quote_lang}"
            )
    except:
        await ctx.send("Ops! Something went wrong, how embarassing!🙈")
Exemplo n.º 7
0
 def activate(cls, bot):
     super().activate(bot)
     if bot.locale in wq.supported_languages():
         cls.LANG = bot.locale
     else:
         cls.LANG = None
     localedir = os.path.join(os.path.dirname(__file__), 'locale')
     lang = gettext.translation('simplebot_wikiquote',
                                localedir=localedir,
                                languages=[bot.locale],
                                fallback=True)
     lang.install()
     cls.description = _('Access Wikiquote content on Delta Chat.')
     cls.commands = [
         PluginCommand(
             '/quote', ['[text]'],
             _('Search in Wikiquote or get the quote of the day if no text is given.'
               ), cls.quote_cmd)
     ]
     cls.bot.add_commands(cls.commands)
Exemplo n.º 8
0
 def test_supported_languages(self):
     # Check that all language modules are being loaded
     self.assertListEqual(wikiquote.supported_languages(),
                          ['de', 'en', 'es', 'fr', 'it'])
Exemplo n.º 9
0
from telegram.ext import Updater, CommandHandler
import wikiquote
import random
import logging

LANGS = wikiquote.supported_languages()
MAX_QUOTES = 100
DEFAULT_LANG = 'en'

with open('token.txt') as f:
    apiToken = f.read()

def lang_and_terms(args):
    if not args:
        return DEFAULT_LANG, []
    
    if args[0] in LANGS:
        return args[0], args[1:]
    
    return DEFAULT_LANG, args

def start(bot, update):
    update.message.reply_text('Hello, I\'m the Wikiquote bot.')

def qotd(bot, update, args):
    lang, terms = lang_and_terms(args)
    try:
        quote, author = wikiquote.quote_of_the_day(lang=lang)
        reply = '"' + quote + '" - ' + author
        update.message.reply_text(reply)
    except:
Exemplo n.º 10
0
 def test_supported_languages(self):
     # Check that all language modules are being loaded
     self.assertListEqual(
         wikiquote.supported_languages(),
         ["de", "en", "es", "fr", "he", "it", "pl", "pt"],
     )
Exemplo n.º 11
0
 def test_normal_quotes(self):
     for lang in wikiquote.supported_languages():
         quotes = wikiquote.quotes("Barack Obama", lang=lang)
         self.assertTrue(len(quotes) > 0)
Exemplo n.º 12
0
 def test_random(self):
     for lang in wikiquote.supported_languages():
         results = wikiquote.random_titles(lang=lang, max_titles=20)
         self.assertTrue(len(results) == 20)
Exemplo n.º 13
0
import wikiquote

# manual_checks.py
# A short script to manually test wikiquote's functionality

MAX_QUOTE_LEN = 70

articles = ['Barack Obama', 'Albert Einstein', 'Ada Lovelace', 'Leonard Cohen']

for lang in wikiquote.supported_languages():
    print('\n----------------------------------------------------')
    print('\nLanguage: {}'.format(lang))
    print('\n----------------------------------------------------\n')

    print('QOTD:')
    try:
        qotd, author = wikiquote.quote_of_the_day(lang=lang)
        print(qotd)
        print('   by: {}'.format(author))
    except Exception as e:
        print(e)

    for article in articles:
        print('\nArticle: {}'.format(article))
        try:
            results = wikiquote.search(article, lang=lang)

            if results:
                print('Results:')
                for result in results:
                    print(' - {}'.format(result))
Exemplo n.º 14
0
 def test_search(self):
     for lang in wikiquote.supported_languages():
         results = wikiquote.search("Matrix", lang=lang)
         self.assertTrue(len(results) > 0)
Exemplo n.º 15
0
"""
Test wikiquote.quote_of_the_day()
"""
import pytest

import wikiquote


@pytest.mark.parametrize("lang", wikiquote.supported_languages())
def test_qotd_quote(lang):
    if lang == "pt":
        pytest.skip()

    quote, _ = wikiquote.quote_of_the_day(lang=lang)
    assert isinstance(quote, str)
    assert len(quote) > 0


def test_unsupported_lang():
    with pytest.raises(wikiquote.UnsupportedLanguageException):
        wikiquote.quote_of_the_day(lang="foobar")


@pytest.mark.parametrize("lang", wikiquote.supported_languages())
def test_qotd_author(lang):
    if lang == "pt":
        pytest.skip()

    _, author = wikiquote.quote_of_the_day(lang=lang)
    assert isinstance(author, str)
    assert len(author) > 0
Exemplo n.º 16
0
 def test_qotd_quote(self):
     for lang in wikiquote.supported_languages():
         quote, author = wikiquote.quote_of_the_day(lang=lang)
         self.assertIsInstance(quote, str)
         self.assertTrue(len(quote) > 0)
Exemplo n.º 17
0
 def test_qotd_author(self):
     for lang in wikiquote.supported_languages():
         quote, author = wikiquote.quote_of_the_day()
         self.assertIsInstance(author, str)
         self.assertTrue(len(author) > 0)